@env-ctrl/node 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 CHANGED
@@ -1,3 +1,45 @@
1
- # Temporary Holding Version
1
+ # @env-ctrl/node
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
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`.
package/package.json CHANGED
@@ -1,6 +1,18 @@
1
1
  {
2
2
  "name": "@env-ctrl/node",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.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": ["env", "environment-variables", "secrets", "dotenv", "config", "envctrl", "secrets-manager"],
7
+ "author": "Andrei Shelenhouski",
8
+ "license": "MIT",
9
+ "type": "module",
10
+ "exports": {
11
+ ".": { "import": "./src/index.js", "require": "./src/core.cjs" },
12
+ "./load": { "import": "./src/load.js", "require": "./src/load.cjs" }
13
+ },
14
+ "files": ["src", "README.md"],
15
+ "engines": { "node": ">=18" },
16
+ "publishConfig": { "access": "public" },
17
+ "scripts": { "test": "node --test test.mjs" }
18
+ }
package/src/core.cjs ADDED
@@ -0,0 +1,81 @@
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 WORKER = join(__dirname, 'fetch-worker.mjs');
8
+ const DEFAULT_URL = 'https://api.envctrl.com';
9
+
10
+ class EnvCtrlError extends Error {}
11
+
12
+ function findConfig(start) {
13
+ let dir = resolve(start);
14
+ for (;;) {
15
+ const f = join(dir, '.envctrl.json');
16
+ if (existsSync(f)) return JSON.parse(readFileSync(f, 'utf8'));
17
+ const parent = dirname(dir);
18
+ if (parent === dir) return {};
19
+ dir = parent;
20
+ }
21
+ }
22
+
23
+ /** Token / URL: options, then ENVCTRL_TOKEN / ENVCTRL_URL, then .envctrl.json in cwd or a parent. */
24
+ function settings(opts = {}) {
25
+ const file = findConfig(opts.cwd ?? process.cwd());
26
+ return {
27
+ token: opts.token ?? process.env.ENVCTRL_TOKEN ?? file.token,
28
+ url: (opts.url ?? process.env.ENVCTRL_URL ?? file.url ?? DEFAULT_URL).replace(/\/+$/, ''),
29
+ };
30
+ }
31
+
32
+ /**
33
+ * Fetches the token's environment synchronously.
34
+ * @returns {{ values: Record<string,string>, missing: string[], invalid: string[] }}
35
+ */
36
+ function fetchEnvSync(opts = {}) {
37
+ const s = settings(opts);
38
+ if (!s.token) throw new EnvCtrlError('no token: set ENVCTRL_TOKEN or add .envctrl.json');
39
+ // The token goes to the short-lived child over stdin: not in argv (visible in `ps`) or its env.
40
+ const raw = execFileSync(process.execPath, [WORKER], {
41
+ input: JSON.stringify({ ...s, timeoutMs: opts.timeoutMs ?? 10_000 }),
42
+ encoding: 'utf8',
43
+ env: { PATH: process.env.PATH ?? '', NODE_EXTRA_CA_CERTS: process.env.NODE_EXTRA_CA_CERTS ?? '' },
44
+ stdio: ['pipe', 'pipe', 'inherit'],
45
+ windowsHide: true,
46
+ });
47
+ const r = JSON.parse(raw);
48
+ if (r.error) throw new EnvCtrlError(r.error);
49
+ return r;
50
+ }
51
+
52
+ /**
53
+ * Loads the environment into process.env (or `opts.target`).
54
+ * - values from env-ctrl win over existing variables unless `keepExisting: true`;
55
+ * - `strict: true` throws when required keys are missing or invalid (default: warn on stderr);
56
+ * - without a token it does nothing (local .env workflows keep working) unless `required: true`.
57
+ * @returns {{ loaded: number, missing: string[], invalid: string[] }}
58
+ */
59
+ function load(opts = {}) {
60
+ const target = opts.target ?? process.env;
61
+ if (!settings(opts).token) {
62
+ if (opts.required) throw new EnvCtrlError('no token: set ENVCTRL_TOKEN or add .envctrl.json');
63
+ return { loaded: 0, missing: [], invalid: [] };
64
+ }
65
+ const { values, missing, invalid } = fetchEnvSync(opts);
66
+ for (const [k, v] of Object.entries(values)) {
67
+ if (opts.keepExisting && target[k] !== undefined) continue;
68
+ target[k] = v;
69
+ }
70
+ const problems = [
71
+ ...(missing.length ? [`missing required keys: ${missing.join(', ')}`] : []),
72
+ ...(invalid.length ? [`invalid values: ${invalid.join(', ')}`] : []),
73
+ ];
74
+ if (problems.length) {
75
+ if (opts.strict) throw new EnvCtrlError(problems.join('; '));
76
+ if (!opts.quiet) process.stderr.write(`envctrl: warning: ${problems.join('; ')}\n`);
77
+ }
78
+ return { loaded: Object.keys(values).length, missing, invalid };
79
+ }
80
+
81
+ 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
@@ -0,0 +1,4 @@
1
+ import core from './core.cjs';
2
+
3
+ export const { load, fetchEnvSync, settings, EnvCtrlError, DEFAULT_URL } = core;
4
+ export default core;
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
@@ -0,0 +1,3 @@
1
+ // Side-effect entry for ESM: `node --import @env-ctrl/node/load app.js` or `import '@env-ctrl/node/load'`
2
+ // as the first import of your entry file.
3
+ import './load.cjs';