@env-ctrl/node 0.0.0-stage → 0.2.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 +48 -2
- package/package.json +39 -4
- package/src/cache.cjs +81 -0
- package/src/core.cjs +94 -0
- package/src/fetch-worker.mjs +23 -0
- package/src/index.js +4 -0
- package/src/load.cjs +12 -0
- package/src/load.js +3 -0
package/README.md
CHANGED
|
@@ -1,3 +1,49 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @env-ctrl/node
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Load the environment variables of one [env-ctrl](https://envctrl.com) environment into `process.env`
|
|
4
|
+
when your Node.js app starts. One token instead of a `.env` file; no wrapper command needed.
|
|
5
|
+
|
|
6
|
+
```bash
|
|
7
|
+
npm i @env-ctrl/node
|
|
8
|
+
export ENVCTRL_TOKEN=ec_svc_... # the only secret the app needs
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
Pick one:
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
node --import @env-ctrl/node/load server.js # ESM (Node >= 18.19), no code changes
|
|
15
|
+
node -r @env-ctrl/node/load server.js # CommonJS
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
```js
|
|
19
|
+
import '@env-ctrl/node/load'; // first line of your entry file (ESM)
|
|
20
|
+
require('@env-ctrl/node/load'); // first line of your entry file (CommonJS)
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
Values are fetched **synchronously**, before any of your modules run, so `process.env.DATABASE_URL`
|
|
24
|
+
is there when your config is read. Nothing is written to disk.
|
|
25
|
+
|
|
26
|
+
| Variable | Effect |
|
|
27
|
+
|---|---|
|
|
28
|
+
| `ENVCTRL_TOKEN` | Service token (create it in the project's *Access tokens* tab). Without it, loading is skipped so local `.env` setups keep working. |
|
|
29
|
+
| `ENVCTRL_URL` | API URL, default `https://api.envctrl.com`. |
|
|
30
|
+
| `ENVCTRL_STRICT=1` | Exit with code 1 if required keys are missing or a value fails its type / regex check. |
|
|
31
|
+
| `ENVCTRL_REQUIRED=1` | Exit with code 1 if there is no token. |
|
|
32
|
+
|
|
33
|
+
Token and URL can also come from `.envctrl.json` (`{"token": "...", "url": "..."}`) in the working directory or a parent.
|
|
34
|
+
|
|
35
|
+
## API
|
|
36
|
+
|
|
37
|
+
```js
|
|
38
|
+
import { load, fetchEnvSync } from '@env-ctrl/node';
|
|
39
|
+
|
|
40
|
+
load({ strict: true, keepExisting: false }); // into process.env
|
|
41
|
+
const { values, missing, invalid } = fetchEnvSync(); // just read them
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
Values from env-ctrl win over variables already set, unless `keepExisting: true`.
|
|
45
|
+
Prefer a wrapper instead? See [`@env-ctrl/cli`](https://www.npmjs.com/package/@env-ctrl/cli): `npx @env-ctrl/cli run -- npm start`.
|
|
46
|
+
|
|
47
|
+
## Offline cache
|
|
48
|
+
|
|
49
|
+
If the API can't be reached (network error, timeout, 5xx), the last successfully fetched values are used, with a warning; never after 401/403. They are kept encrypted (key derived from the token) in `~/.cache/envctrl`, max age 7 days. `ENVCTRL_CACHE=0` disables it, `ENVCTRL_CACHE_MAX_AGE=1d` shortens it.
|
package/package.json
CHANGED
|
@@ -1,6 +1,41 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@env-ctrl/node",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Load environment variables from env-ctrl (envctrl.com) into process.env at startup: one token instead of a .env file.",
|
|
5
|
+
"homepage": "https://envctrl.com",
|
|
6
|
+
"keywords": [
|
|
7
|
+
"env",
|
|
8
|
+
"environment-variables",
|
|
9
|
+
"secrets",
|
|
10
|
+
"dotenv",
|
|
11
|
+
"config",
|
|
12
|
+
"envctrl",
|
|
13
|
+
"secrets-manager"
|
|
14
|
+
],
|
|
15
|
+
"author": "Andrei Shelenhouski",
|
|
16
|
+
"license": "MIT",
|
|
17
|
+
"type": "module",
|
|
18
|
+
"exports": {
|
|
19
|
+
".": {
|
|
20
|
+
"import": "./src/index.js",
|
|
21
|
+
"require": "./src/core.cjs"
|
|
22
|
+
},
|
|
23
|
+
"./load": {
|
|
24
|
+
"import": "./src/load.js",
|
|
25
|
+
"require": "./src/load.cjs"
|
|
26
|
+
}
|
|
27
|
+
},
|
|
28
|
+
"files": [
|
|
29
|
+
"src",
|
|
30
|
+
"README.md"
|
|
31
|
+
],
|
|
32
|
+
"engines": {
|
|
33
|
+
"node": ">=18"
|
|
34
|
+
},
|
|
35
|
+
"publishConfig": {
|
|
36
|
+
"access": "public"
|
|
37
|
+
},
|
|
38
|
+
"scripts": {
|
|
39
|
+
"test": "node --test test.mjs"
|
|
40
|
+
}
|
|
41
|
+
}
|
package/src/cache.cjs
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// Offline cache shared by @env-ctrl/cli and @env-ctrl/node (same file in both packages) and
|
|
3
|
+
// envctrl-spring-boot (Java port, same format). Spec: docs/CACHE.md.
|
|
4
|
+
//
|
|
5
|
+
// After every successful fetch the environment is written to
|
|
6
|
+
// $ENVCTRL_CACHE_DIR | $XDG_CACHE_HOME/envctrl | ~/.cache/envctrl
|
|
7
|
+
// as <name>.json, mode 600, encrypted with AES-256-GCM under a key derived from the token and API URL:
|
|
8
|
+
// without the token the file is useless, and a different token never reads another token's cache.
|
|
9
|
+
// It is used only when the API cannot be reached (network error, timeout, 5xx), never after 401/403,
|
|
10
|
+
// and only while younger than ENVCTRL_CACHE_MAX_AGE (default 7d). ENVCTRL_CACHE=0 disables it.
|
|
11
|
+
const { createCipheriv, createDecipheriv, createHash, randomBytes } = require('node:crypto');
|
|
12
|
+
const { mkdirSync, readFileSync, renameSync, writeFileSync, chmodSync } = require('node:fs');
|
|
13
|
+
const { homedir } = require('node:os');
|
|
14
|
+
const { join } = require('node:path');
|
|
15
|
+
|
|
16
|
+
const VERSION = 1;
|
|
17
|
+
|
|
18
|
+
function enabled() {
|
|
19
|
+
return process.env.ENVCTRL_CACHE !== '0';
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function dir() {
|
|
23
|
+
if (process.env.ENVCTRL_CACHE_DIR) return process.env.ENVCTRL_CACHE_DIR;
|
|
24
|
+
return join(process.env.XDG_CACHE_HOME || join(homedir(), '.cache'), 'envctrl');
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const sha256 = (s) => createHash('sha256').update(s, 'utf8').digest();
|
|
28
|
+
const keyOf = (url, token) => sha256(`envctrl-cache-key-v1\n${url}\n${token}`);
|
|
29
|
+
const nameOf = (url, token) => sha256(`envctrl-cache-name-v1\n${url}\n${token}`).toString('hex').slice(0, 32);
|
|
30
|
+
|
|
31
|
+
/** "7d", "12h", "30m", "3600" (seconds) → milliseconds. */
|
|
32
|
+
function parseAge(s) {
|
|
33
|
+
const m = /^(\d+)\s*([smhd]?)$/.exec(String(s ?? '7d').trim());
|
|
34
|
+
if (!m) return 7 * 86_400_000;
|
|
35
|
+
return Number(m[1]) * { '': 1000, s: 1000, m: 60_000, h: 3_600_000, d: 86_400_000 }[m[2]];
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** @param data {{values: object, missing: string[], invalid: string[]}} */
|
|
39
|
+
function write(url, token, data) {
|
|
40
|
+
if (!enabled()) return;
|
|
41
|
+
try {
|
|
42
|
+
const d = dir();
|
|
43
|
+
mkdirSync(d, { recursive: true, mode: 0o700 });
|
|
44
|
+
const iv = randomBytes(12);
|
|
45
|
+
const cipher = createCipheriv('aes-256-gcm', keyOf(url, token), iv);
|
|
46
|
+
const plain = JSON.stringify({ ...data, fetchedAt: new Date().toISOString() });
|
|
47
|
+
const ct = Buffer.concat([cipher.update(plain, 'utf8'), cipher.final(), cipher.getAuthTag()]);
|
|
48
|
+
const file = join(d, `${nameOf(url, token)}.json`);
|
|
49
|
+
const tmp = `${file}.${process.pid}.tmp`;
|
|
50
|
+
writeFileSync(tmp, JSON.stringify({ v: VERSION, iv: iv.toString('base64'), data: ct.toString('base64') }), { mode: 0o600 });
|
|
51
|
+
chmodSync(tmp, 0o600);
|
|
52
|
+
renameSync(tmp, file);
|
|
53
|
+
} catch {
|
|
54
|
+
// A cache that can't be written must never break a successful start.
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** @returns {{values: object, missing: string[], invalid: string[], fetchedAt: string} | null} */
|
|
59
|
+
function read(url, token) {
|
|
60
|
+
if (!enabled()) return null;
|
|
61
|
+
try {
|
|
62
|
+
const f = JSON.parse(readFileSync(join(dir(), `${nameOf(url, token)}.json`), 'utf8'));
|
|
63
|
+
if (f.v !== VERSION) return null;
|
|
64
|
+
const raw = Buffer.from(f.data, 'base64');
|
|
65
|
+
const decipher = createDecipheriv('aes-256-gcm', keyOf(url, token), Buffer.from(f.iv, 'base64'));
|
|
66
|
+
decipher.setAuthTag(raw.subarray(raw.length - 16));
|
|
67
|
+
const plain = Buffer.concat([decipher.update(raw.subarray(0, raw.length - 16)), decipher.final()]).toString('utf8');
|
|
68
|
+
const data = JSON.parse(plain);
|
|
69
|
+
if (Date.now() - Date.parse(data.fetchedAt) > parseAge(process.env.ENVCTRL_CACHE_MAX_AGE)) return null;
|
|
70
|
+
return data;
|
|
71
|
+
} catch {
|
|
72
|
+
return null;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Errors where falling back to the cache is allowed: the API is unreachable, not "you are not allowed". */
|
|
77
|
+
function isOutage(status) {
|
|
78
|
+
return status === undefined || status === 0 || status >= 500;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
module.exports = { read, write, isOutage, dir, parseAge };
|
package/src/core.cjs
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// Implementation (CommonJS so that both `require` and `import` get the same module).
|
|
3
|
+
const { execFileSync } = require('node:child_process');
|
|
4
|
+
const { existsSync, readFileSync } = require('node:fs');
|
|
5
|
+
const { dirname, join, resolve } = require('node:path');
|
|
6
|
+
|
|
7
|
+
const cache = require('./cache.cjs');
|
|
8
|
+
const WORKER = join(__dirname, 'fetch-worker.mjs');
|
|
9
|
+
const DEFAULT_URL = 'https://api.envctrl.com';
|
|
10
|
+
|
|
11
|
+
class EnvCtrlError extends Error {}
|
|
12
|
+
|
|
13
|
+
function findConfig(start) {
|
|
14
|
+
let dir = resolve(start);
|
|
15
|
+
for (;;) {
|
|
16
|
+
const f = join(dir, '.envctrl.json');
|
|
17
|
+
if (existsSync(f)) return JSON.parse(readFileSync(f, 'utf8'));
|
|
18
|
+
const parent = dirname(dir);
|
|
19
|
+
if (parent === dir) return {};
|
|
20
|
+
dir = parent;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Token / URL: options, then ENVCTRL_TOKEN / ENVCTRL_URL, then .envctrl.json in cwd or a parent. */
|
|
25
|
+
function settings(opts = {}) {
|
|
26
|
+
const file = findConfig(opts.cwd ?? process.cwd());
|
|
27
|
+
return {
|
|
28
|
+
token: opts.token ?? process.env.ENVCTRL_TOKEN ?? file.token,
|
|
29
|
+
url: (opts.url ?? process.env.ENVCTRL_URL ?? file.url ?? DEFAULT_URL).replace(/\/+$/, ''),
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Fetches the token's environment synchronously.
|
|
35
|
+
* @returns {{ values: Record<string,string>, missing: string[], invalid: string[] }}
|
|
36
|
+
*/
|
|
37
|
+
function fetchEnvSync(opts = {}) {
|
|
38
|
+
const s = settings(opts);
|
|
39
|
+
if (!s.token) throw new EnvCtrlError('no token: set ENVCTRL_TOKEN or add .envctrl.json');
|
|
40
|
+
// The token goes to the short-lived child over stdin: not in argv (visible in `ps`) or its env.
|
|
41
|
+
const raw = execFileSync(process.execPath, [WORKER], {
|
|
42
|
+
input: JSON.stringify({ ...s, timeoutMs: opts.timeoutMs ?? 10_000 }),
|
|
43
|
+
encoding: 'utf8',
|
|
44
|
+
env: { PATH: process.env.PATH ?? '', NODE_EXTRA_CA_CERTS: process.env.NODE_EXTRA_CA_CERTS ?? '' },
|
|
45
|
+
stdio: ['pipe', 'pipe', 'inherit'],
|
|
46
|
+
windowsHide: true,
|
|
47
|
+
});
|
|
48
|
+
const r = JSON.parse(raw);
|
|
49
|
+
const useCache = opts.cache !== false;
|
|
50
|
+
if (r.error) {
|
|
51
|
+
// Offline cache only when the API is unreachable, never after 401/403 (revoked token).
|
|
52
|
+
if (useCache && cache.isOutage(r.status)) {
|
|
53
|
+
const cached = cache.read(s.url, s.token);
|
|
54
|
+
if (cached) {
|
|
55
|
+
if (!opts.quiet) process.stderr.write(`envctrl: warning: ${r.error}; using cached values from ${cached.fetchedAt}\n`);
|
|
56
|
+
return { ...cached, fromCache: true };
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
throw new EnvCtrlError(r.error);
|
|
60
|
+
}
|
|
61
|
+
if (useCache) cache.write(s.url, s.token, r);
|
|
62
|
+
return r;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Loads the environment into process.env (or `opts.target`).
|
|
67
|
+
* - values from env-ctrl win over existing variables unless `keepExisting: true`;
|
|
68
|
+
* - `strict: true` throws when required keys are missing or invalid (default: warn on stderr);
|
|
69
|
+
* - without a token it does nothing (local .env workflows keep working) unless `required: true`.
|
|
70
|
+
* @returns {{ loaded: number, missing: string[], invalid: string[] }}
|
|
71
|
+
*/
|
|
72
|
+
function load(opts = {}) {
|
|
73
|
+
const target = opts.target ?? process.env;
|
|
74
|
+
if (!settings(opts).token) {
|
|
75
|
+
if (opts.required) throw new EnvCtrlError('no token: set ENVCTRL_TOKEN or add .envctrl.json');
|
|
76
|
+
return { loaded: 0, missing: [], invalid: [] };
|
|
77
|
+
}
|
|
78
|
+
const { values, missing, invalid } = fetchEnvSync(opts);
|
|
79
|
+
for (const [k, v] of Object.entries(values)) {
|
|
80
|
+
if (opts.keepExisting && target[k] !== undefined) continue;
|
|
81
|
+
target[k] = v;
|
|
82
|
+
}
|
|
83
|
+
const problems = [
|
|
84
|
+
...(missing.length ? [`missing required keys: ${missing.join(', ')}`] : []),
|
|
85
|
+
...(invalid.length ? [`invalid values: ${invalid.join(', ')}`] : []),
|
|
86
|
+
];
|
|
87
|
+
if (problems.length) {
|
|
88
|
+
if (opts.strict) throw new EnvCtrlError(problems.join('; '));
|
|
89
|
+
if (!opts.quiet) process.stderr.write(`envctrl: warning: ${problems.join('; ')}\n`);
|
|
90
|
+
}
|
|
91
|
+
return { loaded: Object.keys(values).length, missing, invalid };
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
module.exports = { load, fetchEnvSync, settings, EnvCtrlError, DEFAULT_URL };
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
// Runs in a child process so that loading can be synchronous (works from `require`, `-r` and
|
|
2
|
+
// `--import` before any application code). Reads settings (JSON) from stdin, prints the result as JSON.
|
|
3
|
+
let input = '';
|
|
4
|
+
for await (const chunk of process.stdin) input += chunk;
|
|
5
|
+
const { token, url, timeoutMs } = JSON.parse(input);
|
|
6
|
+
const out = (o) => process.stdout.write(JSON.stringify(o));
|
|
7
|
+
try {
|
|
8
|
+
const res = await fetch(`${url}/v1/env`, {
|
|
9
|
+
headers: { Authorization: `Bearer ${token}`, 'User-Agent': 'envctrl-node/0.1' },
|
|
10
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
11
|
+
});
|
|
12
|
+
if (!res.ok) {
|
|
13
|
+
const hint = res.status === 401 ? 'token rejected (revoked, expired or not a service token)'
|
|
14
|
+
: res.status === 429 ? `rate limited, retry in ${res.headers.get('retry-after') ?? '?'}s`
|
|
15
|
+
: `API error ${res.status}`;
|
|
16
|
+
out({ error: hint, status: res.status });
|
|
17
|
+
} else {
|
|
18
|
+
const list = (h) => (res.headers.get(h) ?? '').split(',').filter(Boolean);
|
|
19
|
+
out({ values: await res.json(), missing: list('x-envctrl-missing'), invalid: list('x-envctrl-invalid') });
|
|
20
|
+
}
|
|
21
|
+
} catch (e) {
|
|
22
|
+
out({ error: `cannot reach ${url} (${e.cause?.code ?? e.name ?? e.message})` });
|
|
23
|
+
}
|
package/src/index.js
ADDED
package/src/load.cjs
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// Side-effect entry: `node -r @env-ctrl/node/load app.js` or `require('@env-ctrl/node/load')` first thing.
|
|
3
|
+
// ENVCTRL_STRICT=1 → exit when required keys are missing or invalid; ENVCTRL_REQUIRED=1 → exit without a token.
|
|
4
|
+
const { load, EnvCtrlError } = require('./core.cjs');
|
|
5
|
+
|
|
6
|
+
try {
|
|
7
|
+
load({ strict: process.env.ENVCTRL_STRICT === '1', required: process.env.ENVCTRL_REQUIRED === '1' });
|
|
8
|
+
} catch (e) {
|
|
9
|
+
if (!(e instanceof EnvCtrlError)) throw e;
|
|
10
|
+
process.stderr.write(`envctrl: ${e.message}\n`);
|
|
11
|
+
process.exit(1);
|
|
12
|
+
}
|
package/src/load.js
ADDED