@super-repo/envx 0.2.3-b.5 → 0.3.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,1003 +1,111 @@
1
1
  # @super-repo/envx
2
2
 
3
- Workspace-aware env-file loader, runner, and encryption tool — built for monorepos.
3
+ > Workspace-aware env-file loader, runner, and encryption tool — built for monorepos.
4
4
 
5
- ```sh
6
- pnpm add @super-repo/envx
7
- ```
8
-
9
- ## Tribute
10
-
11
- This package stands on the shoulders of [`@dotenvx/dotenvx`](https://www.npmjs.com/package/@dotenvx/dotenvx). The encryption format, the `.env.keys` convention, the public-key header layout, and the broad CLI shape are all directly inspired by — and **wire-format compatible with** — dotenvx. We re-use [`eciesjs`](https://www.npmjs.com/package/eciesjs) (the same library dotenvx uses) for asymmetric encryption, so a `.env*` file encrypted by either tool can be decrypted by the other given the matching private key.
12
-
13
- If you're building a single application, **just use [`@dotenvx/dotenvx`](https://dotenvx.com)**. It's excellent, well-maintained, and battle-tested. This package exists for one specific case: when "load the environment for one app" doesn't capture what you actually need.
14
-
15
- ## The problem
16
-
17
- Monorepos break a lot of dotenv-style assumptions:
18
-
19
- - **Env files live at multiple levels.** Workspace-wide secrets sit at the repo root; per-package overrides sit inside each package; CI injects yet another layer. dotenv's "look in cwd" model produces different results depending on which package directory you happen to be in when you ran the command.
20
- - **`.env.keys` lives in *one* place, but encrypted `.env*` files live in many.** Without a workspace-aware lookup, every package needs its own copy of the keys file, or a fragile `--env-keys-file ../../../.env.keys` per command.
21
- - **Cascade resolution wants the workspace root, not cwd.** `--cascade prod` should layer `.env`, `.env.prod`, `.env.local`, and `.env.prod.local` from the *workspace root*, regardless of which subpackage triggered the load. Without this, a Vite build run from `packages/web/` and a Node script run from `apps/api/` see different environments for the same prod target.
22
- - **Encryption keys want to rotate atomically across the whole stack.** Rotating one package's key while leaving the others stale is a leak waiting to happen. You want one `rotate` command that walks the workspace.
23
- - **Per-package configuration is a real thing.** Some packages legitimately want a different env-file set than the rest of the monorepo (e.g. a Docker image-builder package that pulls from `vault/` while the rest pull from `.env`).
24
-
25
- dotenvx handles single-app cases beautifully. envx handles the workspace shape on top of dotenvx's foundation.
26
-
27
- ## The solution
28
-
29
- envx adds three things on top of the dotenvx model:
30
-
31
- 1. **Cwd-first paths with workspace-root fallback.** Both `--dir`/`--env-path` and `--env-keys-file`/`-fk` resolve **relative to where the command is invoked**. If the requested directory or keys file isn't there, envx walks *up* to the nearest workspace root (any ancestor with `pnpm-workspace.yaml`, `package.json#workspaces`, `nx.json`, etc.) and looks again. So `envx encrypt --dir vault` works whether `vault/` lives in your current package or at the workspace root — same command, same intent, no per-package `../../../.env.keys` ceremony.
32
-
33
- 2. **One `.env.keys` for the workspace by default.** With no `-fk` flag, envx looks for `.env.keys` at cwd; if it's not there, it walks up. So a single keys file at the workspace root serves every encrypted `.env*` across the monorepo. Override per-call with `-fk <path>` whenever you need a different file.
34
-
35
- 3. **`rotate` walks every encrypted file you point it at.** One command refreshes the asymmetric keypair for every file the resolver picks up — every file in `--dir vault`, every file in a `-e` list, every cascade target. The new keypair lands in both the env file's `ENVX_PUBLIC_KEY*` header and the matching `.env.keys` entry atomically.
36
-
37
- The CLI shape, the `encrypted:<base64>` ciphertext format, the `ENVX_PUBLIC_KEY*` headers, and the `.env.keys` file layout are all directly compatible with `dotenvx`. envx also reads keys stored under the upstream `DOTENV_PUBLIC_KEY*` / `DOTENV_PRIVATE_KEY*` names so a `.env.keys` produced by either tool decrypts under the other.
38
-
39
- ## envx vs. dotenvx
40
-
41
- | capability | `dotenvx` | `envx` |
42
- | ----------------------------------------- | ---------------------------------------------------------- | ------------------------------------------------------------------------------------- |
43
- | **Target shape** | Single application | pnpm / yarn / npm workspaces, Nx, Turborepo, Bazel, etc. |
44
- | **Env-file path resolution** | Relative to `cwd` | Cwd-first; walks up to workspace root (`pnpm-workspace.yaml`, `package.json#workspaces`, `nx.json`, …) on miss |
45
- | **`.env.keys` default location** | Alongside the env file | Cwd first, then walk-up to workspace root — one keys file serves the whole monorepo |
46
- | **`--env-keys-file` relative resolution** | Relative to `cwd` | Relative to `cwd`, with walk-up to the workspace root if the file isn't at cwd |
47
- | **`--dir` flag** | Not present (use `-f <path>` per file) | First-class `--dir` / `-d` / `--env-path`, cwd-first with workspace fallback |
48
- | **Per-package config** | Single project root | `package.json#envx.config: "<path>"` per package + workspace-level inheritance |
49
- | **Cascade discovery** | From cwd | From workspace root, then layered with package-local overrides |
50
- | **Encryption** | ECIES via `eciesjs` (secp256k1 + AES-256-GCM) | **Identical** ECIES via `eciesjs` — wire-format compatible |
51
- | **Public-key header** | `DOTENV_PUBLIC_KEY*` | `ENVX_PUBLIC_KEY*` (canonical), `DOTENV_PUBLIC_KEY*` accepted as a read fallback |
52
- | **Private-key var name** | `DOTENV_PRIVATE_KEY*` | `ENVX_PRIVATE_KEY*` (canonical), `DOTENV_PRIVATE_KEY*` accepted as a read fallback |
53
- | **`rotate` command** | Per-file rotation | Walks every encrypted file the resolver picks up |
54
- | **Programmatic API** | `dotenvx.config()` / library functions | `envx()` (single call), `import "@super-repo/envx/auto"` side-effect entry |
55
- | **Auto-environment detection** | Limited | Reads `VERCEL_ENV`, Netlify `CONTEXT`, `NODE_ENV` to pick `.env.<env>` when `--env` is omitted |
56
- | **Distribution** | npm package | npm package + workspace-private helpers (`envx-libs`, `envx-common`) bundled via Vite |
57
- | **Health check** | Not built in | `envx doctor` — workspace, config, keys file, decryptability, required, expand cycles |
58
- | **`.env.example` sync** | Not built in | `envx template` (and `--check` for CI drift detection) |
59
- | **Diff between env files** | Not built in | `envx diff` — keys-only-in-a/b + value mismatches (decrypts via `.env.keys`) |
60
- | **Shell injection** | Not built in | `envx hook bash|zsh|fish|powershell` — eval-able exports for the parent shell |
61
- | **Typed `process.env`** | Not built in | `envx types` — emits `env.d.ts` from loaded keys (Zod-shape-aware) |
62
- | **Watch mode** | Not built in | `envx watch -- node app.js` — restart on `.env*` change |
63
- | **Repo-wide secret audit** | Not built in | `envx audit` — AKIA, ghp_, sk_live_, JWT, OpenAI/Anthropic keys, PEM blocks, … |
64
- | **Selective encryption** | Per-key flag (`-k`) | Per-key, glob patterns (`--pattern`), and `--secrets` preset |
65
- | **Schema validation (Zod)** | Not built in | `schema:` field in config — duck-typed `safeParse()` with fail-fast exit |
66
- | **Named profiles** | Not built in | `profiles: { staging: { ... } }` + `--profile staging` (per-field override) |
67
- | **External secret refs** | Not built in | `${aws-secrets:my-id}` resolved by user-registered `resolvers:` callbacks |
68
- | **Secret-provider plugins** | Not built in | `@super-repo/envx-plugins` ships AWS, GCP, Azure, Vault, 1Password, Doppler, Infisical |
69
- | **Public-variable mirroring** | Not built in | `PUBLIC_*` vars auto-mirror under `VITE_`, `NEXT_PUBLIC_`, `REACT_APP_`, etc. |
70
- | **Build-time secret bake** | Not built in | `envx bake` resolves all refs into `.env.resolved` for bundlers (Vite/Next/esbuild) |
71
- | **Runtime / edge secrets** | Not built in | `createSecretRuntime()` — async, TTL-cached, V8-isolate-safe (CF Workers, Vercel Edge) |
72
- | **License** | BSD-3-Clause | MIT |
73
-
74
- In short: same crypto, same file formats, same CLI vocabulary — different path-resolution layer underneath.
5
+ [![NPM](https://nodei.co/npm/@super-repo/envx.png?downloads=true&downloadRank=true&stars=true)](https://www.npmjs.com/package/@super-repo/envx)
75
6
 
76
- ## Programmatic API
7
+ [![npm version](https://img.shields.io/npm/v/@super-repo/envx.svg)](https://www.npmjs.com/package/@super-repo/envx)
8
+ [![npm downloads](https://img.shields.io/npm/dm/@super-repo/envx.svg)](https://www.npmjs.com/package/@super-repo/envx)
9
+ [![license](https://img.shields.io/npm/l/@super-repo/envx.svg)](./LICENSE)
77
10
 
78
- ### `import envx from "@super-repo/envx"`
11
+ Monorepos break a lot of dotenv-style assumptions: env files live at multiple levels, encrypted `.env*` files spread across packages, `.env.keys` lives in *one* place, cascade resolution wants the workspace root rather than cwd. envx layers workspace-aware path resolution, a single shared keys file, and atomic key rotation on top of [dotenvx's](https://dotenvx.com) battle-tested encryption format.
79
12
 
80
- ```ts
81
- import envx from "@super-repo/envx";
82
-
83
- // Three call shapes — all mutate process.env and return it for ergonomics.
84
- const env = envx(); // load .env (auto-detect from NODE_ENV / VERCEL_ENV / NETLIFY)
85
- const env = envx("prod"); // cascade-load .env, .env.prod, .env.local, .env.prod.local
86
- const env = envx({ // full options
87
- envFiles: ["vault/.env.prod"],
88
- envPath: "vault",
89
- variables: ["PORT=3000"],
90
- override: false,
91
- quiet: false,
92
- });
93
- ```
13
+ Wire-format compatible with `@dotenvx/dotenvx` — same crypto (`eciesjs`), same `.env.keys` convention, same `ENCRYPTED:` ciphertext layout. A `.env*` encrypted by either tool decrypts under the other given the matching private key.
94
14
 
95
- The string form (`envx("prod")`) is shorthand for "scope this load to the named environment" — it sets `cascade` so `.env.prod` and any local overrides layer cleanly over `.env`.
96
-
97
- `envx()` discovers `envx.config.{ts,js,json}` and `package.json#envx.config` automatically; explicit args override matching fields from the config.
98
-
99
- #### Programmatic options — full surface
100
-
101
- `envx()` accepts everything from `LoadEnvOptions` plus an optional `profile` string. The full shape (`EnvxProgrammaticOptions`):
102
-
103
- ```ts
104
- import envx, { type EnvxProgrammaticOptions } from "@super-repo/envx";
105
-
106
- const opts: EnvxProgrammaticOptions = {
107
- // env-file selection
108
- envFiles: ["vault/.env.prod"],
109
- envPath: "vault",
110
- cascade: "prod", // string for explicit, true for auto-detected, false to disable
111
- vault: false, // shortcut for envPath: "vault"
112
-
113
- // load behavior
114
- override: false,
115
- quiet: true,
116
- variables: ["DEBUG=1"], // post-load mutation; always wins
117
-
118
- // auto-detection
119
- autoDetect: true,
120
- nodeEnvMap: { qa: "qa-prod" },
121
-
122
- // post-load behavior
123
- required: ["DATABASE_URL"], // exit 1 if any is unset after load
124
- expand: true, // resolve ${VAR} references
125
- defaults: { LOG_LEVEL: "info" }, // fill holes; never overwrite
126
-
127
- // validation + plug-ins
128
- schema: zodSchema, // any { safeParse(input) → { success, error?, data? } }
129
- resolvers: { // ${provider:id} → resolver(id)
130
- "aws-secrets": (id) => fetchSecret(id),
131
- },
132
-
133
- // profile selection (programmatic equivalent of --profile)
134
- profile: "staging", // throws if config.profiles[name] is missing
135
-
136
- // advanced
137
- workspaceRoot: "/abs/path", // skip findWorkspaceRoot() walk-up
138
- };
139
-
140
- envx(opts);
141
- ```
15
+ ## Inspiration
142
16
 
143
- Caller-supplied fields override matching fields from the discovered config **per-field** — anything you omit falls through to config, then to defaults.
17
+ This package stands on the shoulders of [`@dotenvx/dotenvx`](https://www.npmjs.com/package/@dotenvx/dotenvx) — the encryption format, `.env.keys` convention, public-key header layout, and broad CLI shape are all directly inspired by (and compatible with) dotenvx. **If you're building a single application, just use [`@dotenvx/dotenvx`](https://dotenvx.com)** it's excellent. envx exists for the workspace shape on top of dotenvx's foundation.
144
18
 
145
- ### Side-effect import
146
-
147
- ```ts
148
- // In your app's entry file:
149
- import "@super-repo/envx/auto";
150
-
151
- // envx() has already run by the time this line executes.
152
- const env = process.env;
153
- ```
154
-
155
- `@super-repo/envx/config` is an alias of `/auto` (matches the `dotenv/config` convention).
156
-
157
- ## CLI
19
+ ## Getting started
158
20
 
159
21
  ```sh
160
- envx -- node app.js # load .env (auto-detected) and run
161
- envx --env dev -- pnpm start # load .env.dev
162
- envx --dir vault -- pnpm test # load every .env* in vault/
163
- envx print DATABASE_URL # print one variable
164
- envx debug --cascade prod # show resolved paths
165
- envx encrypt -e .env.prod # encrypt values in .env.prod (writes ./.env.keys)
166
- envx encrypt --secrets # encrypt only conventional secret keys (*_SECRET, *_TOKEN, …)
167
- envx decrypt -e .env.prod -k FOO # decrypt only FOO
168
- envx rotate --dir vault # rotate keypair for every vault/.env* file
169
- envx expand -e vault/.env.prod # decrypt + expand to stdout
170
- envx doctor # health check (workspace, keys, decryptability, required, cycles)
171
- envx template # write .env.example with values stripped
172
- envx template --check # CI gate — exit 1 on .env.example drift
173
- envx diff .env.dev .env.prod # show keys-only-in-a/b + value mismatches
174
- eval "$(envx hook bash)" # inject loaded env into the parent shell
175
- envx types # emit env.d.ts for typed process.env access
176
- envx watch -- node app.js # restart on .env* change
177
- envx audit # scan repo for plaintext secrets
178
- envx --profile staging -- node app.js # apply named profile from envx.config.*
179
- envx -c ./envx.config.json run -- node app.js
180
- ```
181
-
182
- ### Bin commands
183
-
184
- | bin | source | what it does |
185
- | ---------------- | ---------------------------- | ----------------------------------------------- |
186
- | `envx` | `dist/cli.js` | This package's CLI (subcommands below) |
187
- | `dotenvx-proxy` | `dist/bin/dotenvx.js` | Direct passthrough to upstream `@dotenvx/dotenvx` |
188
-
189
- ### Subcommands
190
-
191
- #### Core
192
-
193
- | command | what it does |
194
- | --------- | -------------------------------------------------------------------------------------- |
195
- | `run` | (default) load env files into `process.env` and execute a command |
196
- | `print` | load env files and print a single variable's value |
197
- | `debug` | show which files would be loaded without loading them |
198
- | `encrypt` | encrypt values in one or more `.env*` files (writes `.env.keys` on first run). Selective: `--key`, `--pattern '*_SECRET,*_TOKEN'`, `--secrets` preset |
199
- | `decrypt` | decrypt values back in place |
200
- | `rotate` | generate a fresh keypair and re-encrypt every encrypted value in place |
201
- | `info` | print resolved configuration, auto-detection details, NODE_ENV mappings, and the env files that would load |
202
- | `expand` | decrypt (if needed) and expand `${VAR}` / `$VAR` / `${VAR:-default}` / `${VAR:?msg}` |
203
-
204
- #### Workflow + DX
205
-
206
- | command | what it does |
207
- | ------------- | ---------------------------------------------------------------------------------------------------------------- |
208
- | `doctor` | run health checks: workspace + config visible, env files exist, keys file present, every encrypted value decrypts, `required` keys filled after a dry load, expansion has no cycles. Exits non-zero on hard failures. CI-friendly. |
209
- | `template` | emit a value-stripped `.env.example` from your real env files. `--check` mode exits 1 on drift; `--stdout` prints to stdout; `--annotate` (default on) tags each key with the source file. |
210
- | `diff <a> <b>` | compare two env files key-by-key. Reports keys-only-in-a, keys-only-in-b, and value mismatches. Decrypts via `.env.keys` so the comparison reflects logical values; values are masked unless `--show-values`. |
211
- | `hook <shell>` | print eval-able shell exports for the loaded env. Supports `bash`, `zsh`, `fish`, `powershell`/`pwsh` with proper escaping. Use `eval "$(envx hook bash)"` to inject env into the parent shell. |
212
- | `types` | emit an `env.d.ts` declaring every loaded key on `NodeJS.ProcessEnv`. Keys listed in `required` (or non-optional in a Zod schema) narrow to `string`; everything else is `string \| undefined`. |
213
- | `watch` | spawn a command and restart it whenever any of the resolved env files change. Debounce + SIGTERM-then-SIGKILL grace for clean restarts. |
214
- | `audit` | walk the repo looking for plaintext secrets — AWS keys, GitHub PATs, Stripe live/test keys, JWTs, OpenAI / Anthropic keys, Google API keys, Slack tokens, PEM private-key blocks. Findings are redacted; exit 1 on any hit. `--json` for downstream tools. |
215
- | `bake` | resolve every `${{provider:id}}` ref + decrypt every encrypted value + run defaults / expand / schema / public-mirror, then write a sealed `.env.resolved` for build tools to consume. Output is plaintext — refuses to write under `.git/`; use `--public-only` for client bundles. `--json` for structured tools, `--out=-` for stdout. |
216
-
217
- ### Global options
218
-
219
- | option | alias | default | description |
220
- | ----------------- | ---------------- | -------------------- | ---------------------------------------------------------------------------------------- |
221
- | `--config` | `-c` | _(auto)_ | Path to an `envx.config.{ts,js,json}`. Discovery: flag → `package.json#envx.config` → walk-up auto-discovery. |
222
- | `--env` | `-e` | `[".env"]` | Files to load (repeatable). Auto-discovered from `--env-path` when omitted. |
223
- | `--env-path` | `-d`, `--dir` | _(none)_ | Subdirectory holding env files. Cwd-first; falls back to `<workspace-root>/<dir>` if the cwd path doesn't exist. When set + `--env` omitted, every `.env*` in the resolved dir is included. |
224
- | `--vault` | `--va` | `false` | Shortcut for `--env-path vault`. |
225
- | `--env-keys-file` | `-fk` | `<cwd>/.env.keys` | Path to the `.env.keys` file. Cwd-first; walks up to the workspace root if no keys file exists at cwd. |
226
- | `--variables` | `-v` | `[]` | Inline `name=value` overrides (repeatable). |
227
- | `--cascade` | | _(off)_ | Cascade name; expands `.env`, `.env.<c>`, `.env.local`, `.env.<c>.local`. |
228
- | `--override` | `-o` | `false` | Override existing `process.env` values. Conflicts with `--cascade`. |
229
- | `--quiet` | `-q` | `true` | Suppress dotenv's own output. |
230
- | `--profile` | `-P` | _(none)_ | Named profile from `profiles` in `envx.config.*` — fields override the base config per-field. |
231
-
232
- ### Defaults
233
-
234
- Six resolution rules drive every envx invocation. Each is overridable — see [Configuration](#configuration) below for the layered customization map.
235
-
236
- #### 1. Environment auto-detection
237
-
238
- When `--env` is left at its default (`[".env"]`), envx auto-detects the deployment environment from well-known platform signals and rewrites the env-file suffix accordingly. Source-of-truth: `detectEnvironment()`.
239
-
240
- Order of precedence: **Vercel → Netlify → `NODE_ENV` → unsuffixed**.
241
-
242
- | signal | detected | env file picked |
243
- | ------------------------------------------------------- | ---------- | --------------- |
244
- | `VERCEL` set + `VERCEL_ENV=production` | `prod` | `.env.prod` |
245
- | `VERCEL` set + any other `VERCEL_ENV` (or unset) | `dev` | `.env.dev` |
246
- | `NETLIFY` set + `CONTEXT=production` | `prod` | `.env.prod` |
247
- | `NETLIFY` set + `CONTEXT=deploy-preview` / `branch-deploy` | `dev` | `.env.dev` |
248
- | `NETLIFY` set + any other `CONTEXT` | `dev` | `.env.dev` |
249
- | `NODE_ENV=production` | `prod` | `.env.prod` |
250
- | `NODE_ENV=development` | `dev` | `.env.dev` |
251
- | `NODE_ENV=local` | `local` | `.env.local` |
252
- | `NODE_ENV=<other>` (e.g. `staging`, `qa`, `preview`) | `<other>` | `.env.<other>` |
253
- | _no signals_ | `root` | `.env` |
254
-
255
- `NODE_ENV` values not in the built-in map (`production`, `development`, `local`) **pass through lowercased** as the suffix. So `NODE_ENV=staging` → `.env.staging`, `NODE_ENV=QA` → `.env.qa`, etc. — no config required.
256
-
257
- **Customize:**
258
- - Pass `--env <name>` (or `-e <name>`) to bypass detection entirely; bare names get the `.env.` prefix automatically (`--env staging` → `.env.staging`).
259
- - Disable detection: set `autoDetect: false` in `envx.config.{ts,js,json}`.
260
- - Override the `NODE_ENV → suffix` mapping in config:
261
- ```ts
262
- // envx.config.ts
263
- export default {
264
- nodeEnvMap: {
265
- // built-ins keep working unless you override them:
266
- production: "prod",
267
- development: "dev",
268
- local: "local",
269
- // your additions / remappings:
270
- qa: "qa-prod", // NODE_ENV=qa → .env.qa-prod
271
- preview: "", // NODE_ENV=preview → .env (no suffix)
272
- },
273
- }
274
- ```
275
- - Programmatic: `envx({ envFiles: [...] })`, `envx("staging")` (sets `cascade`), or `envx({ autoDetect: false, nodeEnvMap: { ... } })`.
276
-
277
- Run **`envx info`** to print the resolved settings, the detected environment, the active mapping, and which files would be loaded.
278
-
279
- #### 2. Cascade expansion order
280
-
281
- `--cascade <name>` expands the base files into a layered set, **least- to most-specific**, so that the most specific one wins. Source-of-truth: `expandCascadePaths()`.
282
-
283
- For a base of `.env` and `--cascade prod`:
284
-
285
- | order | path | role |
286
- | :---: | ----------------- | --------------------------------- |
287
- | 1 | `.env.prod.local` | per-developer prod override (gitignored) |
288
- | 2 | `.env.local` | per-developer override (gitignored) |
289
- | 3 | `.env.prod` | shared prod values (committable, encryptable) |
290
- | 4 | `.env` | shared baseline |
291
-
292
- Without `--cascade`: `.env.local` → `.env` (still least-specific-last).
293
-
294
- **Customize:**
295
- - **CLI**: pass `--cascade <name>` to cascade with an explicit env name (e.g. `--cascade prod`).
296
- - **Config**: set `cascade: true` to cascade using the auto-detected env name. `cascade: false` (or omit) disables.
297
- - **Programmatic**: `envx({ cascade: true })` for auto-detected, `envx({ cascade: "prod" })` for explicit, `envx("prod")` (string shorthand) is equivalent to the explicit form.
298
- - `--override` conflicts with cascade — envx exits with an error if both are set.
299
-
300
- #### 3. Path resolution (cwd-first → workspace-root fallback)
301
-
302
- Every relative path passed to `--dir`, `--env-path`, `--env-keys-file`, or set in config goes through the same resolver. Source-of-truth: `resolveCwdOrWorkspace()`.
303
-
304
- ```
305
- absolute path? → use verbatim
306
- <cwd>/<rel> exists? → use that
307
- <workspaceRoot>/<rel>? → use that
308
- neither? → return <cwd>/<rel> so callers (encrypt, etc.) can create it
309
- ```
310
-
311
- The "default `.env.keys`" lookup runs the same resolver against the literal `".env.keys"` — so a single `.env.keys` at the workspace root serves every package by default.
312
-
313
- **Customize:**
314
- - Pass an absolute path to `-fk` / `--dir` to skip the walk-up entirely.
315
- - Set `envKeysFile` / `envPath` in `envx.config.{ts,js,json}`.
316
- - Programmatic: `envx({ envPath: "vault", envKeysFile: "/abs/path/.env.keys" })`.
317
-
318
- #### 4. Workspace root detection
319
-
320
- `findWorkspaceRoot(startDir)` walks up from `startDir` and returns the first directory that matches one of these signals, in order:
321
-
322
- | pass | signal |
323
- | :--: | ------------------------------------------------------------ |
324
- | 1 | `package.json` with a `workspaces` field (npm/yarn) |
325
- | 1 | `package.json` with a `pnpm.workspaces` field |
326
- | 2 | `pnpm-workspace.yaml` |
327
- | 2 | `lerna.json` |
328
- | 2 | `nx.json` |
329
- | 2 | `rush.json` |
330
- | 2 | `yarn.lock` |
331
- | 2 | `pnpm-lock.yaml` |
332
-
333
- If nothing matches, `startDir` is returned (so envx degrades to single-package behavior — the cwd-first / fallback resolver still works, the fallback is just a no-op).
334
-
335
- **Customize:**
336
- - The detection is currently hardcoded. If you have a non-standard layout, pass absolute paths to `--dir` / `-fk` / `--env` and skip the walk entirely. Reach out if you have a layout that needs a new indicator added.
337
-
338
- #### 5. Default `--env` / `--env-path` behavior
339
-
340
- | condition | resolved env files |
341
- | ------------------------------------------------------ | --------------------------------------------------------------- |
342
- | `--env` explicitly passed | exactly the files passed (with `.env.` prefix added to bare names) |
343
- | `envFiles` set in config | the config's list |
344
- | `--env-path <dir>` set, no `--env` | every `.env*` file inside `<dir>` (sorted, excluding `.env.keys`) |
345
- | neither set | `[".env"]` (with auto-detection from rule #1) |
346
-
347
- `--vault` is exact shorthand for `--env-path vault`. The `.env.keys` file is **never** discovered by `listEnvFiles`, so `--dir vault` won't accidentally try to "encrypt" your private keys.
348
-
349
- **Customize:**
350
- - `--env <file>` (repeatable) — explicit list.
351
- - `--env-path <dir>` (or `--dir`, `-d`) — pull every `.env*` from a directory.
352
- - `envFiles` / `envPath` in config.
353
- - Programmatic: `envx({ envFiles: [...], envPath: "..." })`.
354
-
355
- #### 6. CLI variable overrides
356
-
357
- `-v KEY=VALUE` (repeatable) sets values on `process.env` *after* env files load. Format is `^(\w+)=([\s\S]+)$` — multi-line values are supported, but the key must be a valid bash identifier. Source-of-truth: `validateCmdVariable()`.
358
-
359
- **Customize:**
360
- - `-v KEY=VALUE` per-call.
361
- - Programmatic: `envx({ variables: ["KEY=VALUE", ...] })`.
362
-
363
- ## Encryption
364
-
365
- envx uses **asymmetric (ECIES) encryption by default** — exactly the same scheme as `dotenvx`. On first encrypt of a fresh `.env*` file:
366
-
367
- 1. A fresh secp256k1 keypair is generated.
368
- 2. The public key gets prepended to the env file as a banner + `ENVX_PUBLIC_KEY*` header (safe to commit).
369
- 3. The matching private key gets written to `.env.keys` (gitignore this) under `ENVX_PRIVATE_KEY*` with a section banner per env file.
370
- 4. Every selected value is encrypted with the public key. Since the public key is committed alongside the env file, anyone with read access can encrypt new values; only the private-key holder can decrypt.
371
-
372
- A typical encrypted `.env.dev`:
373
-
374
- ```
375
- #/-------------------[ENVX_PUBLIC_KEY]----------------------/
376
- #/ public-key encryption for .env files /
377
- #/ [how it works](https://dotenvx.com/encryption) /
378
- #/----------------------------------------------------------/
379
- ENVX_PUBLIC_KEY_DEV="0266287313a6f4d107115d5963640830fcca378ae34a5e3dbf775122fd121f7084"
380
-
381
- DATABASE_URL=encrypted:Bf3p…
382
- API_KEY=encrypted:7nQ2…
383
- ```
384
-
385
- …and the matching `.env.keys` (gitignored):
386
-
387
- ```
388
- #/------------------!ENVX_PRIVATE_KEYS!---------------------/
389
- #/ private decryption keys. DO NOT commit to source control /
390
- #/ [how it works](https://dotenvx.com/encryption) /
391
- #/----------------------------------------------------------/
392
-
393
- # .env.dev
394
- ENVX_PRIVATE_KEY_DEV="…64 hex chars…"
395
-
396
- # .env.prod
397
- ENVX_PRIVATE_KEY_PROD="…64 hex chars…"
398
- ```
399
-
400
- ### Rotating keys
401
-
402
- ```sh
403
- envx rotate # rotate keypair for ./.env
404
- envx rotate --dir vault # rotate every vault/.env* file
405
- envx rotate -k API_KEY # rotate one variable in place
406
- ```
407
-
408
- Rotation generates a fresh keypair, decrypts every value with the old private key, re-encrypts with the new public key, and updates both the env file and `.env.keys` atomically. Files without a public-key header surface an error — run `envx encrypt` against them first to set up the keypair.
409
-
410
- ### dotenvx-compatible naming
411
-
412
- envx reads keys under either prefix and writes new ones under the canonical names:
413
-
414
- | concept | canonical (envx writes this) | dotenvx-compat (envx reads this) |
415
- | ----------- | ------------------------------- | -------------------------------- |
416
- | public key | `ENVX_PUBLIC_KEY*` | `DOTENV_PUBLIC_KEY*` |
417
- | private key | `ENVX_PRIVATE_KEY*` | `DOTENV_PRIVATE_KEY*` |
418
-
419
- A `.env.keys` produced by upstream dotenvx will Just Work — envx decrypts and re-encrypts in place without renaming the entry, so the diff doesn't ripple.
420
-
421
- ## Configuration
422
-
423
- Every default in the previous section can be overridden. There are three precedence layers — highest to lowest:
424
-
425
- | layer | scope | when to use |
426
- | ------------------------------------------------------ | --------------------------- | ---------------------------------------------------------- |
427
- | 1. **Per-invocation overrides** — CLI flag (`--env`, `--dir`, …) **or** programmatic arg (`envx({...})`) | one invocation | ad-hoc overrides, scripts, embedded usage |
428
- | 2. **The one resolved config file** | the package containing the resolved config | per-package or workspace-shared defaults |
429
- | 3. **Built-in defaults** | every invocation | the fallbacks documented in [Defaults](#defaults) |
430
-
431
- `-v KEY=VALUE` is **not** a config layer — it's a post-load mutation of `process.env` that runs after env files are read. See "Variable-value precedence" further down.
432
-
433
- The "one resolved config file" in layer 2 comes from this discovery walk (first match wins, no merging across files):
434
-
435
- | step | source | walks up? |
436
- | :--: | --------------------------------------------------------------- | :-------: |
437
- | 1 | `--config <path>` flag (CLI only) | n/a |
438
- | 2 | nearest `package.json#envx.config: "<path>"` from cwd up to `/` | yes |
439
- | 3 | `envx.config.{ts,mts,js,mjs,cjs,json}` in **cwd only** | no |
440
- | 4 | (none — fall through to defaults) | n/a |
441
-
442
- A workspace-root `envx.config.ts` is not auto-discovered from sub-packages — point sub-packages at it via `package.json#envx.config: "../../envx.config.ts"` (or whatever the relative path is).
443
-
444
- The programmatic API runs the same discovery (minus step 1):
445
-
446
- ```ts
447
- import envx from "@super-repo/envx";
448
-
449
- envx(); // discovery + defaults
450
- envx("staging"); // shorthand for envx({ cascade: "staging" })
451
- envx({ ... }); // explicit args play the role of CLI flags (layer 1)
452
- ```
453
-
454
- ### How the layers actually merge
455
-
456
- The precedence table glosses over a real distinction: **settings** (`envFiles`, `cascade`, `envKeysFile`, …) and **variable values** (the contents of `process.env` after envx runs) flow through different rules. Worth knowing the difference if you're debugging a "why is this value what it is?" moment.
457
-
458
- #### Per-setting merge (independent, top-to-bottom)
459
-
460
- Each setting in the config-file shape (next section) is resolved **independently**. envx walks the layers for each field on its own — there's no all-or-nothing inheritance.
461
-
462
- ```
463
- For each setting field (envFiles, cascade, envPath, envKeysFile, override, quiet, …):
464
-
465
- 1. Did the CLI flag — or programmatic arg — set this field? → use that, stop
466
- 2. Is it set in the resolved config file? → use that, stop
467
- 3. Otherwise → use the built-in default
468
- ```
469
-
470
- So you can do this without thinking about layer order:
471
-
472
- ```sh
473
- # Config provides envFiles; CLI overrides only `cascade`.
474
- # Effective settings: envFiles=[".env","vault/.env.prod"], cascade="prod", everything else default.
475
- envx --cascade prod -- node app.js
476
- ```
477
-
478
- with
479
-
480
- ```ts
481
- // envx.config.ts
482
- export default {
483
- envFiles: [".env", "vault/.env.prod"],
484
- }
485
- ```
486
-
487
- The CLI flag for `cascade` wins for that field; `envFiles` falls through to the config; everything else falls through to defaults.
488
-
489
- #### Variable-value precedence (after files load)
490
-
491
- Once envx has resolved settings and loaded the env files, the actual values that end up in `process.env` follow a different order — this is dotenv's contract, with two envx-specific tweaks:
492
-
493
- ```
494
- Final value of process.env.SOME_KEY is the FIRST hit, top-down:
495
-
496
- 1. `-v SOME_KEY=…` passed on the CLI (always wins)
497
- 2. Existing process.env.SOME_KEY when --override=false (the default)
498
- OR, when --override=true:
499
- The most-specific env file's value for SOME_KEY (cascade-wise)
500
- 3. The next-most-specific env file's value (cascade order)
501
- 4. … all the way down the cascade
502
- 5. unset
22
+ pnpm add -D @super-repo/envx
503
23
  ```
504
24
 
505
- `-v` is **not** a config layer — it's a post-load mutation of `process.env`. It runs after every env file has been loaded, and it unconditionally overwrites whatever was there. Rule of thumb:
506
-
507
- - Need to inject one ad-hoc value? `-v KEY=VALUE`.
508
- - Need to swap a whole environment? `--env`, `--cascade`, or `envFiles` in config.
509
-
510
- #### `--override` flips one thing only
511
-
512
- `--override=false` (the default) means **existing `process.env` wins** over what's in the env files. This matches dotenv: if your shell already exports `DATABASE_URL`, env files won't clobber it.
513
-
514
- `--override=true` means **env files win** over existing `process.env`. Useful when you want a config-driven environment to be authoritative regardless of what's in the parent shell. It's incompatible with `--cascade` (envx exits with an error) — within a cascade chain, the *most-specific* file wins anyway, which is the only ordering that makes sense.
515
-
516
- ### Config-file shape
517
-
518
25
  ```ts
519
26
  // envx.config.ts
520
27
  import { defineConfig } from "@super-repo/envx";
521
28
 
522
29
  export default defineConfig({
523
- // ── env-file selection ─────────────────────────────────
524
- envFiles: [".env", ".env.local"], // bypass auto-detect; explicit list
525
- envPath: "vault", // workspace-relative subdir (cwd-first, ws-root fallback)
526
- cascade: true, // boolean: enable layered cascade using the auto-detected env name
527
- // (CLI `--cascade <name>` still accepts an explicit string and overrides)
528
- variables: ["DEBUG=1"], // KEY=VALUE overrides applied after load
529
-
530
- // ── encryption keys ────────────────────────────────────
531
- envKeysFile: ".env.keys", // overrides the cwd-first / workspace fallback default
532
-
533
- // ── load behavior ──────────────────────────────────────
534
- override: false, // false: existing process.env wins
535
- // true: env files win (incompatible with cascade)
536
- quiet: true, // suppress dotenv's load-line output
537
-
538
- // ── auto-detection ─────────────────────────────────────
539
- autoDetect: true, // false disables Vercel/Netlify/NODE_ENV detection
540
- nodeEnvMap: { // override the NODE_ENV → suffix mapping
541
- production: "prod", // (built-ins shown — yours layer on top)
542
- development: "dev",
543
- local: "local",
544
- qa: "qa-prod", // NODE_ENV=qa → .env.qa-prod
545
- preview: "", // NODE_ENV=preview → .env (empty = no suffix)
546
- },
547
-
548
- // ── post-load behavior ─────────────────────────────────
549
- required: ["DATABASE_URL", "API_KEY"], // fail-fast: exit 1 if any are unset after load
550
- expand: true, // auto-resolve ${VAR} references against process.env
551
- defaults: { // applied AFTER files + variables, only for unset keys
552
- LOG_LEVEL: "info",
553
- PORT: "3000",
554
- },
555
-
556
- // ── validation ─────────────────────────────────────────
557
- schema: z.object({ // any object exposing `safeParse(input) → { success, error?, data? }`
558
- DATABASE_URL: z.string().url(), // Zod is the obvious choice but envx duck-types — bring your own
559
- PORT: z.coerce.number(), // coerced values are written back to process.env
560
- }),
561
-
562
- // ── named profiles ─────────────────────────────────────
563
- profiles: { // `--profile staging` (or programmatic `envx({ profile: "staging" })`)
564
- staging: { // merges this object onto the base config per-field, profile wins
565
- envFiles: [".env.staging"],
566
- required: ["DB_URL"],
567
- },
568
- prod: {
569
- envFiles: [".env.prod"],
570
- cascade: true,
571
- required: ["DB_URL", "API_KEY"],
572
- },
573
- },
574
-
575
- // ── external secret refs ───────────────────────────────
576
- resolvers: { // values like `${aws-secrets:my-id}` get passed to the resolver
577
- "aws-secrets": (id: string) => { // and replaced by its return. Sync — wrap async SDK calls externally.
578
- return cachedAwsSecret(id); // (e.g. pre-warm a cache before envx() runs in your bootstrap)
579
- },
580
- },
581
-
582
- // ── public-variable mirroring (SSR / client-side bundlers) ─
583
- publicPrefixes: ["VITE_", "NEXT_PUBLIC_"], // duplicate every PUBLIC_* under each prefix
584
- publicSource: "PUBLIC_", // (default) the prefix that marks a var as public
585
-
586
- // ── advanced ───────────────────────────────────────────
587
- workspaceRoot: "/abs/path/to/repo", // escape hatch — skip findWorkspaceRoot() walk-up
588
- })
589
- ```
590
-
591
- All fields are optional. Anything you omit falls through to the built-in default for that field. `defineConfig` is an identity helper — at runtime it just returns the object, but it gives editors full autocomplete and type-checking for `DotenvxConfig`. A plain `export default { … }` works too.
592
-
593
- > **Note:** `schema`, `profiles`, and `resolvers` are TS/JS-only — JSON configs can't carry callable functions. A `package.json#envx.config` reference must point at a `.ts` / `.mts` / `.js` / `.mjs` / `.cjs` file to use them.
594
-
595
- ### Discovery order
596
-
597
- When `--config <path>` is not passed, envx walks up looking for a config in this order:
598
-
599
- 1. `<cwd>/envx.config.{ts,js,json,mjs,cjs}` — first hit wins
600
- 2. `<cwd>/package.json#envx.config: "<path>"` — the string is resolved relative to that `package.json`'s directory
601
- 3. Each parent directory, up to the workspace root, repeating steps 1 & 2
602
-
603
- `package.json#envx.config` only accepts a **string path** (not an inline object), so the config is always a single file you can lint, review, and version-control independently from the manifest.
604
-
605
- ### Programmatic customization
606
-
607
- Every config field maps 1:1 onto the options accepted by the `envx()` programmatic entry point:
608
-
609
- ```ts
610
- import envx from "@super-repo/envx";
611
-
612
- // Same as `envx --env .env.prod --env-path vault --override`:
613
- envx({
614
- envFiles: [".env.prod"],
615
- envPath: "vault",
616
- override: true,
30
+ envFiles: [".env"],
31
+ cascade: true,
32
+ required: ["DATABASE_URL"],
617
33
  });
618
-
619
- // String shorthand sets `cascade`:
620
- envx("staging"); // == envx({ cascade: "staging" })
621
34
  ```
622
35
 
623
- Programmatic args **override** anything from the discovered config; the config supplies fields you didn't pass.
624
-
625
- ## Further reading
626
-
627
- Expanded explanations, worked examples, and recipes ship with the package in [`./docs/`](./docs/):
628
-
629
- - **[Auto-detection](./docs/auto-detection.md)** — every `VERCEL_ENV` / `CONTEXT` / `NODE_ENV` shape walked through with the file that ends up loading.
630
- - **[Configuration](./docs/configuration.md)** — full schema, the per-field merge rules, where each field gets read from, and the discovery walk.
631
- - **[Monorepo recipes](./docs/recipes.md)** — common layouts (single workspace `.env.keys`, vault subdir, per-app overrides, CI patterns) with the exact files and commands.
632
-
633
- ## Library API
634
-
635
- Beyond `envx()`, the package re-exports the building blocks the CLI uses internally — useful when you need to script the same behavior from your own tool, plugin, or test harness. Everything below is importable from the default entry:
636
-
637
- ```ts
638
- import {
639
- // Programmatic loader
640
- envx,
641
- type EnvxProgrammaticOptions,
642
- type LoadEnvOptions,
643
-
644
- // Audit (plaintext-secret scanner)
645
- auditFiles,
646
- BUILT_IN_PATTERNS,
647
- type AuditFinding,
648
- type AuditOptions,
649
- type SecretPattern,
650
-
651
- // Crypto primitives
652
- ENCRYPTED_PREFIX,
653
- generateKeyPair,
654
- encryptValueAsymmetric,
655
- decryptValueAsymmetric,
656
- isEncrypted,
657
-
658
- // Higher-level operations
659
- encryptFiles,
660
- decryptFiles,
661
- rotateFiles,
662
-
663
- // Env-file parser (line-preserving)
664
- parseEnv,
665
- serializeEnv,
666
- toRecord,
667
-
668
- // Variable expansion (cycle-safe)
669
- expandRecord,
670
- expandEnvSrc,
671
-
672
- // Config + path resolution
673
- defineConfig,
674
- loadDotenvxConfig,
675
- findWorkspaceRoot,
676
- resolveCwdOrWorkspace,
677
- resolveEnvPaths,
678
- detectEnvironment,
679
-
680
- // Keys-file management
681
- readKeysFile,
682
- writeKeysFile,
683
- defaultKeysPath,
684
- } from "@super-repo/envx";
685
- ```
686
-
687
- ### Audit programmatically
688
-
689
- `envx audit` is a thin wrapper around `auditFiles()`. Use it directly to plug envx's secret detection into a pre-commit hook, a CI script, or your own dashboard:
690
-
691
- ```ts
692
- import { auditFiles, type SecretPattern } from "@super-repo/envx";
693
-
694
- // Add custom patterns alongside the built-ins.
695
- const orgPatterns: SecretPattern[] = [
696
- { id: "internal-token", label: "ACME internal token", regex: /\bacme_[A-Za-z0-9]{32}\b/ },
697
- ];
698
-
699
- const { findings, filesScanned } = auditFiles({
700
- roots: ["packages/", "apps/"],
701
- ignore: ["fixtures", "snapshots"],
702
- extra: orgPatterns,
703
- max: 100, // 0 = unlimited
704
- });
705
-
706
- if (findings.length > 0) {
707
- console.error(`audit: ${findings.length} finding(s) across ${filesScanned} files`);
708
- process.exit(1);
709
- }
710
- ```
711
-
712
- Findings are redacted (`AKIA…MPLE [redacted 20 chars]`) so the report itself never leaks the secret payload.
713
-
714
- ### Custom profiles + resolvers in code
715
-
716
- When you need conditional behavior in a programmatic call (without a config file):
717
-
718
36
  ```ts
37
+ // app entry — pick one
38
+ import "@super-repo/envx/auto"; // side-effect load, dotenv-style
39
+ // or
719
40
  import envx from "@super-repo/envx";
720
- import { z } from "zod";
721
-
722
- const Schema = z.object({
723
- DATABASE_URL: z.string().url(),
724
- PORT: z.coerce.number().int().min(1).max(65535),
725
- });
726
-
727
- await preloadAwsSecretsCache(); // resolvers are sync — warm caches up front
728
-
729
- envx({
730
- schema: Schema,
731
- resolvers: {
732
- "aws-secrets": (id) => awsSecretsCache.get(id),
733
- "1password": (ref) => onePasswordCache.get(ref),
734
- },
735
- required: ["DATABASE_URL", "PORT"],
736
- expand: true, // ${HOST}/api works after resolvers run
737
- });
738
- ```
739
-
740
- Order of operations inside `envx()` once a profile / resolvers / schema are in play:
741
-
41
+ const { DATABASE_URL } = envx();
742
42
  ```
743
- 1. resolve workspaceRoot
744
- 2. resolve env file paths
745
- 3. load each env file → mutates process.env (subject to `override`)
746
- 4. apply `variables` → unconditional overwrite
747
- 5. run `resolvers` on ${provider:id} refs
748
- 6. apply `defaults` → only for keys still unset
749
- 7. expand `${VAR}` references (when `expand: true`)
750
- 8. validate against `schema` (when configured) — exits 1 on failure
751
- 9. enforce `required` (any unset → log + exit 1)
752
- ```
753
-
754
- ## Public variables (SSR + client bundlers)
755
-
756
- Modern frameworks each demand their own prefix for variables that should reach client-side code:
757
43
 
758
- | framework | prefix |
759
- | ----------------- | --------------- |
760
- | Vite | `VITE_` |
761
- | Next.js | `NEXT_PUBLIC_` |
762
- | Create React App | `REACT_APP_` |
763
- | Nuxt 3 (public) | `NUXT_PUBLIC_` |
764
- | SvelteKit (public)| `PUBLIC_` |
765
- | Remix (loader) | _(none)_ |
44
+ For everything else — full schema, recipes, hook recipes, CI examples — see [Docs](#docs).
766
45
 
767
- Maintaining the same value under three different keys (`VITE_API_URL`, `NEXT_PUBLIC_API_URL`, `REACT_APP_API_URL`) is the kind of busywork envx exists to delete. Mark a variable "public" once with `PUBLIC_` (or any prefix you configure as `publicSource`), and envx mirrors it under every framework prefix at load time.
768
-
769
- ```ts
770
- // envx.config.ts
771
- export default {
772
- publicPrefixes: ["VITE_", "NEXT_PUBLIC_"],
773
- // publicSource: "PUBLIC_" // (default)
774
- }
775
- ```
776
-
777
- ```env
778
- # .env
779
- PUBLIC_API_URL=https://api.example.com
780
- PUBLIC_FEATURE_FLAG=true
781
- DATABASE_URL=secret-stuff # not mirrored — no PUBLIC_ prefix
782
- ```
46
+ ## Features
783
47
 
784
- After `envx -- node app.js`, `process.env` looks like:
48
+ - **Workspace-aware path resolution** — `--dir`, `--env-path`, `--env-keys-file` resolve cwd-first then walk up to the nearest workspace root. One `.env.keys` at the repo root serves every encrypted `.env*` across the monorepo.
49
+ - **Cascade discovery** — `--cascade prod` layers `.env`, `.env.prod`, `.env.local`, `.env.prod.local` from the workspace root, regardless of which subpackage triggered the load.
50
+ - **Atomic key rotation** — one `envx rotate --dir vault` refreshes the keypair for every encrypted file at once. No stale keys lurking in sibling packages.
51
+ - **Auto-environment detection** — reads `VERCEL_ENV`, Netlify `CONTEXT`, `NODE_ENV` to pick `.env.<env>` automatically. Override per-call or disable globally.
52
+ - **`.env*` health gate** — `envx doctor`, `envx audit` (plaintext-secret scanner), `envx template --check` (drift detection) compose into a single CI / pre-commit gate.
53
+ - **Public-variable mirroring** — mark a variable `PUBLIC_*` once; envx auto-mirrors it under `VITE_`, `NEXT_PUBLIC_`, `REACT_APP_`, etc. so you don't maintain three near-identical entries.
54
+ - **Schema validation** — pass any object with `safeParse()` (Zod-friendly, but duck-typed) and envx fail-closes on validation errors at load time.
55
+ - **Edge / serverless runtime** — `createSecretRuntime()` for V8-isolate-safe lazy fetching with TTL caching and single-flight coalescing.
785
56
 
786
- | key | value | source |
787
- | ---------------------------- | --------------------------- | --------------- |
788
- | `PUBLIC_API_URL` | `https://api.example.com` | original |
789
- | `VITE_API_URL` | `https://api.example.com` | mirror |
790
- | `NEXT_PUBLIC_API_URL` | `https://api.example.com` | mirror |
791
- | `PUBLIC_FEATURE_FLAG` | `true` | original |
792
- | `VITE_FEATURE_FLAG` | `true` | mirror |
793
- | `NEXT_PUBLIC_FEATURE_FLAG` | `true` | mirror |
794
- | `DATABASE_URL` | `secret-stuff` | original (kept private — no mirror) |
795
-
796
- CLI flag for one-off use:
797
-
798
- ```sh
799
- envx --public-prefix VITE_ --public-prefix NEXT_PUBLIC_ -- pnpm build
800
- ```
801
-
802
- Mirroring runs **after** `expand`, so `${VAR}` references inside `PUBLIC_*` values resolve before being mirrored. Existing target keys are never overwritten — a `VITE_API_URL` already set in the parent shell wins over the auto-mirror.
803
-
804
- ## Security models — when secrets are fetched
805
-
806
- Pick one based on where you want plaintext to live:
807
-
808
- | model | when secrets are fetched | plaintext on disk? | best for |
809
- | ------------------------------ | --------------------------------------- | ------------------------------- | ---------------------------------------- |
810
- | **Encrypted-at-rest** (default)| process startup — `envx run --` decrypts via `.env.keys` | ciphertext only, in committed `.env*` | most apps — single binary, fast cold start |
811
- | **Load-time fetch** (resolvers)| process startup — plugins fetch via `resolvers:` | none — plaintext stays in process memory | server processes, long-running workers |
812
- | **Build-time bake** | once, in CI — `envx bake` writes `.env.resolved` | yes (in the build artifact) ⚠️ | static SPA bundles, public-only vars |
813
- | **Runtime fetch** (edge) | per cold start, lazily — `secrets.get()` on first read | none — secrets stay in the source-of-truth | edge functions, serverless, zero-trust |
814
-
815
- The four models stack — most apps end up using two or more (e.g. encrypted-at-rest for non-secret config, runtime fetch for actual secrets).
816
-
817
- ### Build-time bake (`envx bake`)
818
-
819
- ```sh
820
- # CI step — resolves every encrypted value + ${provider:id} ref + ${VAR}
821
- # expansion + schema validation, then writes a sealed file the bundler picks up.
822
- envx bake --out dist/.env.resolved
823
-
824
- # Public-only mode for client bundles — only PUBLIC_* keys + their framework mirrors.
825
- envx bake --public-only --out dist/.env.public
826
- ```
827
-
828
- ⚠️ The output file is **plaintext**. envx writes a `# DO NOT COMMIT` banner and refuses to write under `.git/`, but you must add the path to `.gitignore` yourself. Use `--public-only` whenever the artifact will ship to clients.
829
-
830
- Build-tool integration:
831
-
832
- ```ts
833
- // vite.config.ts
834
- import { defineConfig, loadEnv } from "vite";
835
-
836
- export default defineConfig(({ mode }) => {
837
- // Vite's loadEnv reads .env.resolved like any other .env file.
838
- const env = loadEnv(mode, process.cwd(), ".env.resolved");
839
- return {
840
- define: {
841
- "import.meta.env.VITE_API_URL": JSON.stringify(env.VITE_API_URL),
842
- },
843
- };
844
- });
845
- ```
846
-
847
- ```sh
848
- # CI script
849
- envx bake --public-only --out .env.resolved && pnpm vite build
850
- ```
851
-
852
- ### Runtime fetch — edge / serverless
853
-
854
- For the "secrets never leave the source-of-truth" model, use `createSecretRuntime` from `@super-repo/envx-plugins/runtime`. Async-first, TTL caching, no `fs` / `child_process` dependencies — works in Cloudflare Workers, Vercel Edge, Deno Deploy, AWS Lambda, Bun, Node.
855
-
856
- ```ts
857
- // src/secrets.ts — module-level singleton, one per worker
858
- import { createSecretRuntime } from "@super-repo/envx-plugins/runtime";
859
- import { hcVault } from "@super-repo/envx-plugins/vault";
860
-
861
- export const secrets = createSecretRuntime({
862
- providers: [
863
- hcVault({
864
- endpoint: env.VAULT_ADDR,
865
- token: env.VAULT_TOKEN,
866
- }),
867
- ],
868
- ttl: 300, // refresh every 5 min
869
- onFailure: "cache-stale", // serve stale on transient backend failures
870
- });
871
- ```
872
-
873
- ```ts
874
- // src/handler.ts (Cloudflare Worker / Vercel Edge / Lambda — same shape)
875
- import { secrets } from "./secrets";
876
-
877
- export default async function handler(req: Request): Promise<Response> {
878
- const dbUrl = await secrets.get("vault:prod/db");
879
- const apiKey = await secrets.get("vault:prod/api");
880
- // … handler logic …
881
- }
882
- ```
883
-
884
- What you get:
885
- - **Lazy fetch** — first read triggers the network call. Subsequent reads within the TTL window hit memory.
886
- - **Single-flight** — N concurrent reads of the same ref coalesce into one fetch. Edge functions handling a burst of requests don't fan out N parallel calls to your secret store.
887
- - **TTL refresh** — values older than `ttl` seconds are refetched on next read. Set `ttl: Infinity` to cache forever; `ttl: 0` to fetch every read.
888
- - **Failure modes** — `"throw"` (default), `"cache-stale"` (serve previous value, log warning), or `"cache-error"` (cache the failure for `errorTtl` seconds so you don't hammer a failing backend).
889
- - **No fs / child_process imports** — the runtime entry point is V8-isolate-safe.
890
-
891
- ### Compatibility note
892
-
893
- Plugin compatibility for the runtime entry depends on what each provider's transport needs:
894
-
895
- | provider | edge runtime? | reason |
896
- | ------------------ | --------------------------- | ----------------------------------- |
897
- | HashiCorp Vault | ✓ | native `fetch` |
898
- | Doppler | ✓ | native `fetch` |
899
- | Infisical | ✓ | native `fetch` |
900
- | AWS Secrets Manager| ⚠ Node-compat only | `@aws-sdk/client-secrets-manager` uses Node streams |
901
- | GCP Secret Manager | ⚠ Node-compat only | `@google-cloud/secret-manager` uses gRPC |
902
- | Azure Key Vault | ⚠ Node-compat only | `@azure/identity` token chain |
903
- | 1Password (CLI) | ✗ | spawns the `op` binary |
904
- | 1Password (SDK) | depends on `@1password/sdk` | check the SDK's runtime support |
905
-
906
- For Cloudflare Workers / Vercel Edge / Deno: prefer Vault, Doppler, Infisical, or a custom HTTP `buildProvider`. AWS / GCP / Azure SDKs run fine in Lambda / Cloud Run / Cloud Functions but won't work in V8-only edges.
907
-
908
- ## Secret-provider plugins
909
-
910
- Ship as a sibling package: [`@super-repo/envx-plugins`](https://www.npmjs.com/package/@super-repo/envx-plugins). Plugins return a `SecretProvider` you wire into envx's `resolvers:` config so values like `${aws-secrets:my-db}` and `${vault:prod/api}` fetch from the matching backend at load time.
911
-
912
- ```ts
913
- import envx from "@super-repo/envx";
914
- import { awsSecrets, autoPreload, asResolvers } from "@super-repo/envx-plugins";
915
-
916
- const aws = awsSecrets({ region: "us-east-1" });
917
-
918
- await autoPreload([aws], { envFiles: [".env", "vault/.env.prod"] });
919
-
920
- envx({ resolvers: asResolvers([aws]) });
921
- ```
922
-
923
- ```env
924
- DATABASE_URL=${aws-secrets:prod/db}
925
- ```
926
-
927
- Built-in providers: AWS Secrets Manager, GCP Secret Manager, Azure Key Vault, HashiCorp Vault, 1Password (CLI + SDK), Doppler, Infisical. Each plugin lazy-loads its SDK — install only what you use. See the [`@super-repo/envx-plugins` README](../plugins/README.md) for per-provider setup.
928
-
929
- ## Pre-commit hooks
930
-
931
- Three of the new commands (`audit`, `doctor`, `template --check`) are designed to compose into a single git pre-commit gate so secrets, broken configs, and stale `.env.example` files never reach the remote.
932
-
933
- The repo ships a reference `.hooks/pre-commit` you can adopt verbatim or copy into your own setup:
57
+ ## CLI
934
58
 
935
59
  ```sh
936
- # Activate the in-repo .hooks/ directory (one-time per clone)
937
- git config core.hooksPath .hooks
60
+ envx -- node app.js # load env + run command
61
+ envx --env dev -- pnpm start # load .env.dev
62
+ envx --dir vault -- pnpm test # load every .env* in vault/
63
+ envx encrypt -e .env.prod # encrypt values in .env.prod
64
+ envx rotate --dir vault # rotate keypair across vault/.env*
65
+ envx audit --staged # scan staged files for plaintext secrets
66
+ envx doctor # health check (CI-friendly)
67
+ envx template # write .env.example (mirrors comments/blank lines, strips values + ENVX_PUBLIC_KEY*)
68
+ envx template --ai # populate example values via Claude (reads ANTHROPIC_API_KEY from your loaded .env)
69
+ envx template --check # exit 1 on .env.example drift
70
+ envx --profile staging -- node app.js # apply a named profile
938
71
  ```
939
72
 
940
- That single config line tells git to look for hooks under `<repo>/.hooks/` instead of `.git/hooks/`. The directory is committed (everyone gets the same hooks), no third-party tool is required.
941
-
942
- The hook itself:
943
-
944
- ```bash
945
- #!/usr/bin/env bash
946
- # .hooks/pre-commit
947
- set -euo pipefail
948
- [[ "${ENVX_SKIP_HOOK:-}" == "1" ]] && exit 0
949
-
950
- # Use the workspace binary if available, else a global envx
951
- if command -v pnpm >/dev/null && [[ -f package.json ]]; then
952
- ENVX="pnpm exec envx"
953
- else
954
- ENVX="envx"
955
- fi
956
-
957
- failed=0
958
-
959
- # 1. Audit staged files for plaintext secrets (AKIA, ghp_, sk_live_, JWTs, …)
960
- staged=$(git diff --cached --name-only --diff-filter=ACMR | tr '\n' ' ')
961
- [[ -n "$staged" ]] && ! $ENVX audit $staged && failed=1
962
-
963
- # 2. Workspace health (skip required-key gate so dev machines don't fail)
964
- $ENVX doctor --ignore-required || failed=1
965
-
966
- # 3. .env.example drift gate
967
- [[ -f .env ]] && ! $ENVX template --check && failed=1
73
+ | bin | what it does |
74
+ | ---------------- | --------------------------------------------------- |
75
+ | `envx` | This package's CLI (run, encrypt, rotate, audit, …) |
76
+ | `dotenvx-proxy` | Direct passthrough to upstream `@dotenvx/dotenvx` |
968
77
 
969
- exit $failed
970
- ```
78
+ Full subcommand and flag reference: [docs/cli.md](./docs/cli.md). Full schema for `envx.config.{ts,js,json}`: [docs/configuration.md](./docs/configuration.md).
971
79
 
972
- Bypass options:
973
- - `ENVX_SKIP_HOOK=1 git commit ...` — skip just the envx hook
974
- - `git commit --no-verify` — skip every git hook (use sparingly)
80
+ ## envx vs. dotenvx
975
81
 
976
- The full annotated script lives at `.hooks/pre-commit` in this repo. CI should run the same three commands without the `--ignore-required` flag so missing required keys fail builds (not just commits).
82
+ | capability | `dotenvx` | `envx` |
83
+ | -------------------------------------- | ------------------------------- | -------------------------------------------------------- |
84
+ | **Target shape** | single application | workspaces (pnpm/yarn/npm, Nx, Turborepo, Bazel) |
85
+ | **Path resolution** | relative to `cwd` | cwd-first, walk up to workspace root |
86
+ | **`.env.keys` location** | alongside the env file | one shared file at the workspace root |
87
+ | **Cascade discovery** | from cwd | from workspace root, layered with package overrides |
88
+ | **`rotate`** | per-file | walks every encrypted file the resolver picks up |
89
+ | **Secret-provider plugins** | not built in | `@super-repo/envx-plugins` (AWS, GCP, Azure, Vault, …) |
90
+ | **Schema validation / profiles / audit / doctor / template / diff / hook / types / watch / bake** | not built in | first-class |
91
+ | **Encryption (wire format)** | ECIES via `eciesjs` | **identical** — interoperable |
92
+ | **License** | BSD-3-Clause | MIT |
977
93
 
978
- ### Pre-push variant
94
+ Same crypto, same file formats, same CLI vocabulary — different path-resolution layer underneath.
979
95
 
980
- For a stricter gate that runs only on push (so commits stay fast but pushes are guarded):
96
+ ## Pre-commit hooks & CI
981
97
 
982
- ```bash
983
- #!/usr/bin/env bash
984
- # .hooks/pre-push — same checks, run against the whole repo, no skip.
985
- set -euo pipefail
986
- envx audit && envx doctor && envx template --check
987
- ```
98
+ Three checks compose into the envx git gate, but they belong at different layers:
988
99
 
989
- ### CI-friendly invocations
100
+ - **pre-commit** → `envx audit --staged` only. Scans the staged file set for plaintext secrets — fast, scoped to the diff git is about to record.
101
+ - **pre-push** → `envx audit && envx doctor && envx template --check`. Whole-repo health check; runs once per push, not per commit.
102
+ - **CI** → same as pre-push without `--ignore-required` so missing required keys fail builds.
990
103
 
991
- ```yaml
992
- # .github/workflows/secrets.yml
993
- - run: pnpm exec envx audit --json > audit.json
994
- - run: pnpm exec envx doctor # fails the build on missing required keys
995
- - run: pnpm exec envx template --check # fails on .env.example drift
996
- ```
104
+ See [docs/hooks.md](./docs/hooks.md) for Husky, lefthook, simple-git-hooks, native-git, and GitHub Actions recipes (per-layer + per-runner).
997
105
 
998
106
  ## Embedding the CLI
999
107
 
1000
- The yargs factory is exported under the `./commands` subpath if you want to register envx's commands inside your own tool:
108
+ The yargs factory is exported under `./commands` if you want to register envx's subcommands inside your own tool:
1001
109
 
1002
110
  ```ts
1003
111
  import { createCli } from "@super-repo/envx/commands";
@@ -1005,59 +113,27 @@ import { createCli } from "@super-repo/envx/commands";
1005
113
  createCli(process.argv.slice(2)).parseSync();
1006
114
  ```
1007
115
 
1008
- ## Development
116
+ ## Docs
1009
117
 
1010
- ```sh
1011
- pnpm install
1012
- pnpm build # vite library build → dist/
1013
- pnpm test # vitest unit tests
1014
- pnpm test:integration # spawn-based subprocess tests
1015
- ```
1016
-
1017
- Tests live in `tests/`. Integration fixtures live in `tests/integration/__static__/` — each subdirectory is a self-contained worked example.
118
+ Deep references and worked examples live alongside this package in [./docs/](./docs/):
1018
119
 
1019
- ## Layout
120
+ - **[configuration.md](./docs/configuration.md)** — full `DotenvxConfig` schema, defaults, per-field merge rules, discovery walk.
121
+ - **[defaults.md](./docs/defaults.md)** — the six resolution rules driving every invocation (auto-detection, cascade, path resolution, workspace detection).
122
+ - **[encryption.md](./docs/encryption.md)** — ECIES key flow, file layout, rotation, dotenvx-compatible naming.
123
+ - **[template.md](./docs/template.md)** — `envx template` behavior: formatting preservation, banner/public-key stripping, `--ai` placeholder generation.
124
+ - **[auto-detection.md](./docs/auto-detection.md)** — every `VERCEL_ENV` / `CONTEXT` / `NODE_ENV` shape walked through with the file that ends up loading.
125
+ - **[recipes.md](./docs/recipes.md)** — common monorepo layouts (single workspace `.env.keys`, vault subdir, per-app overrides) with the exact files and commands.
126
+ - **[hooks.md](./docs/hooks.md)** — Husky / lefthook / simple-git-hooks / native-git / pre-push / GitHub Actions recipes.
127
+ - **[library-api.md](./docs/library-api.md)** — every exported function and type (`auditFiles`, `encryptFiles`, `loadDotenvxConfig`, …).
128
+ - **[public-variables.md](./docs/public-variables.md)** — the `PUBLIC_*` mirroring story for SSR / client bundlers.
129
+ - **[security-models.md](./docs/security-models.md)** — encrypted-at-rest vs. load-time fetch vs. build-time bake vs. runtime/edge fetch.
1020
130
 
1021
- ```
1022
- packages/envx/core/
1023
- ├── src/
1024
- │ ├── index.ts # default export: envx() programmatic API
1025
- │ ├── auto.ts # `import "@super-repo/envx/auto"` side-effect entry
1026
- │ ├── cli.ts # `envx` bin entry — wires yargs + parses argv
1027
- │ ├── bin/
1028
- │ │ └── dotenvx.ts # `dotenvx-proxy` direct passthrough to upstream
1029
- │ └── commands/
1030
- │ ├── index.ts # createCli — registers subcommands + global options
1031
- │ ├── run.ts # `run [command..]` — load env + spawn
1032
- │ ├── print.ts # `print <variable>` — print one value
1033
- │ ├── debug.ts # `debug` — show resolved paths
1034
- │ ├── encrypt.ts # `encrypt` — incl. --pattern / --secrets
1035
- │ ├── decrypt.ts # `decrypt`
1036
- │ ├── rotate.ts # `rotate` — refresh keypair across files
1037
- │ ├── expand.ts # `expand` — resolve ${VAR} on stdout
1038
- │ ├── info.ts # `info` — print resolved config
1039
- │ ├── doctor.ts # `doctor` — health checks (CI gate)
1040
- │ ├── template.ts # `template` — emit/check .env.example
1041
- │ ├── diff.ts # `diff <a> <b>` — keys + value mismatches
1042
- │ ├── hook.ts # `hook <shell>` — eval-able shell exports
1043
- │ ├── types.ts # `types` — emit env.d.ts
1044
- │ ├── watch.ts # `watch -- <cmd>` — restart on env change
1045
- │ └── audit.ts # `audit` — plaintext-secret scanner
1046
- ├── tests/
1047
- │ ├── *.test.ts # unit suites
1048
- │ └── integration/
1049
- │ ├── cli.test.ts # subprocess end-to-end suite
1050
- │ └── __static__/ # read-only fixtures (cp'd to tmp per test)
1051
- ├── configs/
1052
- │ ├── tsconfig.build.json
1053
- │ ├── vite.config.ts # bundles workspace-private envx-libs/common helpers
1054
- │ └── vitest.config.ts
1055
- ├── tsconfig.json
1056
- └── package.json
1057
- ```
131
+ ## References
1058
132
 
1059
- The `envx-libs` and `envx-common` workspace packages are bundled into the published `dist/` via Vite, so this is the only npm package consumers need to install.
133
+ - [`@dotenvx/dotenvx`](https://dotenvx.com) the upstream package envx builds on. Use it directly for single-app projects.
134
+ - [`@super-repo/envx-plugins`](../plugins) — secret-provider plugins (AWS, GCP, Azure, Vault, 1Password, Doppler, Infisical) consumed via `resolvers:`.
135
+ - [`eciesjs`](https://www.npmjs.com/package/eciesjs) — the secp256k1 + AES-256-GCM library used for encryption.
1060
136
 
1061
137
  ## License
1062
138
 
1063
- MIT — same as `@dotenvx/dotenvx`. We're grateful for their work; please go support [`dotenvx.com`](https://dotenvx.com) if you build single-app stuff.
139
+ MIT — same as `@dotenvx/dotenvx`. We're grateful for their work; please go support [`dotenvx.com`](https://dotenvx.com) if you build single-app stuff. See [LICENSE](./LICENSE).