@env-ctrl/node 0.1.0 → 0.2.1
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 +4 -0
- package/package.json +31 -8
- package/src/cache.cjs +81 -0
- package/src/core.cjs +14 -1
- package/src/fetch-worker.mjs +1 -1
package/README.md
CHANGED
|
@@ -43,3 +43,7 @@ const { values, missing, invalid } = fetchEnvSync(); // just read them
|
|
|
43
43
|
|
|
44
44
|
Values from env-ctrl win over variables already set, unless `keepExisting: true`.
|
|
45
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,18 +1,41 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@env-ctrl/node",
|
|
3
|
-
"version": "0.1
|
|
3
|
+
"version": "0.2.1",
|
|
4
4
|
"description": "Load environment variables from env-ctrl (envctrl.com) into process.env at startup: one token instead of a .env file.",
|
|
5
5
|
"homepage": "https://envctrl.com",
|
|
6
|
-
"keywords": [
|
|
6
|
+
"keywords": [
|
|
7
|
+
"env",
|
|
8
|
+
"environment-variables",
|
|
9
|
+
"secrets",
|
|
10
|
+
"dotenv",
|
|
11
|
+
"config",
|
|
12
|
+
"envctrl",
|
|
13
|
+
"secrets-manager"
|
|
14
|
+
],
|
|
7
15
|
"author": "Andrei Shelenhouski",
|
|
8
16
|
"license": "MIT",
|
|
9
17
|
"type": "module",
|
|
10
18
|
"exports": {
|
|
11
|
-
".": {
|
|
12
|
-
|
|
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
|
+
}
|
|
13
27
|
},
|
|
14
|
-
"files": [
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
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
|
+
}
|
|
18
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
CHANGED
|
@@ -4,6 +4,7 @@ const { execFileSync } = require('node:child_process');
|
|
|
4
4
|
const { existsSync, readFileSync } = require('node:fs');
|
|
5
5
|
const { dirname, join, resolve } = require('node:path');
|
|
6
6
|
|
|
7
|
+
const cache = require('./cache.cjs');
|
|
7
8
|
const WORKER = join(__dirname, 'fetch-worker.mjs');
|
|
8
9
|
const DEFAULT_URL = 'https://api.envctrl.com';
|
|
9
10
|
|
|
@@ -45,7 +46,19 @@ function fetchEnvSync(opts = {}) {
|
|
|
45
46
|
windowsHide: true,
|
|
46
47
|
});
|
|
47
48
|
const r = JSON.parse(raw);
|
|
48
|
-
|
|
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);
|
|
49
62
|
return r;
|
|
50
63
|
}
|
|
51
64
|
|
package/src/fetch-worker.mjs
CHANGED
|
@@ -19,5 +19,5 @@ try {
|
|
|
19
19
|
out({ values: await res.json(), missing: list('x-envctrl-missing'), invalid: list('x-envctrl-invalid') });
|
|
20
20
|
}
|
|
21
21
|
} catch (e) {
|
|
22
|
-
out({ error: `cannot reach ${url} (${e.cause?.code ?? e.
|
|
22
|
+
out({ error: `cannot reach ${url} (${e.cause?.code ?? e.cause?.errors?.[0]?.code ?? (e.name === 'TimeoutError' ? 'timeout' : e.message)})` });
|
|
23
23
|
}
|