node-env-resolver 1.1.0 → 2.0.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 +879 -166
- package/dist/builder.d.ts +1 -1
- package/dist/builder.d.ts.map +1 -1
- package/dist/builder.js +1 -1
- package/dist/index.d.ts +2 -56
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -8
- package/dist/performance.test.d.ts +7 -0
- package/dist/performance.test.d.ts.map +1 -0
- package/dist/priority.test.d.ts +6 -0
- package/dist/priority.test.d.ts.map +1 -0
- package/dist/resolver.d.ts +3 -3
- package/dist/resolver.d.ts.map +1 -1
- package/dist/resolver.js +9 -9
- package/dist/types.d.ts +23 -1
- package/dist/types.d.ts.map +1 -1
- package/dist/utils.d.ts +1 -1
- package/dist/utils.d.ts.map +1 -1
- package/dist/utils.js +1 -1
- package/dist/web.d.ts.map +1 -1
- package/dist/web.js +5 -5
- package/dist/zod.d.ts +129 -1
- package/dist/zod.d.ts.map +1 -1
- package/dist/zod.js +1 -1
- package/package.json +3 -5
package/README.md
CHANGED
|
@@ -1,62 +1,77 @@
|
|
|
1
1
|
# node-env-resolver
|
|
2
2
|
|
|
3
|
-
Type-safe environment variable
|
|
3
|
+
Type-safe environment variable resolution with zero dependencies and ultra-small bundle size.
|
|
4
4
|
|
|
5
5
|
[](https://www.npmjs.com/package/node-env-resolver)
|
|
6
6
|
|
|
7
|
+
**Bundle Size:** ~6KB gzipped (includes all validators)
|
|
8
|
+
|
|
7
9
|
## Install
|
|
8
10
|
|
|
9
11
|
```bash
|
|
10
12
|
npm install node-env-resolver
|
|
11
13
|
```
|
|
12
14
|
|
|
13
|
-
## Quick start
|
|
15
|
+
## Quick start (uses process.env)
|
|
14
16
|
|
|
15
17
|
```ts
|
|
16
18
|
import { resolve } from 'node-env-resolver';
|
|
17
19
|
|
|
18
|
-
const config =
|
|
20
|
+
const config = resolve({
|
|
19
21
|
PORT: 3000,
|
|
20
|
-
DATABASE_URL: '
|
|
22
|
+
DATABASE_URL: 'postgres',
|
|
21
23
|
DEBUG: false,
|
|
22
24
|
API_KEY: 'string?'
|
|
23
25
|
});
|
|
24
26
|
|
|
25
|
-
//
|
|
27
|
+
// config is fully typed
|
|
26
28
|
config.PORT; // number
|
|
27
|
-
config.DATABASE_URL; //
|
|
29
|
+
config.DATABASE_URL; // verified postgres connection string
|
|
28
30
|
config.DEBUG; // boolean
|
|
29
31
|
config.API_KEY; // string | undefined
|
|
30
32
|
```
|
|
31
33
|
|
|
32
|
-
##
|
|
34
|
+
## Quick start (async)
|
|
33
35
|
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
- Custom validation functions
|
|
37
|
-
- Standard Schema compliant
|
|
38
|
-
- Works with any Node.js application
|
|
36
|
+
```ts
|
|
37
|
+
import { resolve } from 'node-env-resolver';
|
|
39
38
|
|
|
40
|
-
|
|
39
|
+
const config = await resolve.with([asyncEnvProvider(),{
|
|
40
|
+
PORT: 3000,
|
|
41
|
+
DATABASE_URL: 'postgres',
|
|
42
|
+
DEBUG: false,
|
|
43
|
+
API_KEY: 'string?'
|
|
44
|
+
}]);
|
|
41
45
|
|
|
42
|
-
|
|
46
|
+
// config is fully typed
|
|
47
|
+
config.PORT; // number
|
|
48
|
+
config.DATABASE_URL; // verified postgres connection string
|
|
49
|
+
config.DEBUG; // boolean
|
|
50
|
+
config.API_KEY; // string | undefined
|
|
51
|
+
```
|
|
43
52
|
|
|
44
|
-
|
|
45
|
-
- **Network**: `url`, `http`, `https`, `email`
|
|
46
|
-
- **Database**: `postgres`, `mysql`, `mongodb`, `redis`
|
|
53
|
+
## Basic usage
|
|
47
54
|
|
|
48
|
-
|
|
55
|
+
### Required values
|
|
49
56
|
|
|
50
|
-
|
|
57
|
+
If an environment variable is missing and has no default, validation fails:
|
|
51
58
|
|
|
52
59
|
```ts
|
|
53
|
-
|
|
60
|
+
const config = resolve({
|
|
61
|
+
DATABASE_URL: 'url', // Required
|
|
62
|
+
API_KEY: 'string' // Required
|
|
63
|
+
});
|
|
64
|
+
```
|
|
54
65
|
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
66
|
+
### Default values
|
|
67
|
+
|
|
68
|
+
Provide a default value to use when the environment variable is not set:
|
|
69
|
+
|
|
70
|
+
```ts
|
|
71
|
+
const config = resolve({
|
|
72
|
+
PORT: 3000, // Defaults to 3000
|
|
73
|
+
DEBUG: false, // Defaults to false
|
|
74
|
+
LOG_LEVEL: 'info' // Defaults to 'info'
|
|
60
75
|
});
|
|
61
76
|
```
|
|
62
77
|
|
|
@@ -65,18 +80,141 @@ const config = await resolve({
|
|
|
65
80
|
Add `?` to make a value optional:
|
|
66
81
|
|
|
67
82
|
```ts
|
|
68
|
-
const config =
|
|
69
|
-
API_KEY: 'string?',
|
|
70
|
-
REDIS_URL: 'url?'
|
|
83
|
+
const config = resolve({
|
|
84
|
+
API_KEY: 'string?', // string | undefined
|
|
85
|
+
REDIS_URL: 'url?', // string | undefined
|
|
86
|
+
MAX_RETRIES: 'number?' // number | undefined
|
|
71
87
|
});
|
|
72
88
|
```
|
|
73
89
|
|
|
74
|
-
###
|
|
90
|
+
### Enums
|
|
91
|
+
|
|
92
|
+
Use arrays for enum validation:
|
|
93
|
+
|
|
94
|
+
```ts
|
|
95
|
+
const config = resolve({
|
|
96
|
+
NODE_ENV: ['development', 'production', 'test'] as const,
|
|
97
|
+
LOG_LEVEL: ['debug', 'info', 'warn', 'error'] as const
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
// TypeScript knows the exact types
|
|
101
|
+
config.NODE_ENV; // 'development' | 'production' | 'test'
|
|
102
|
+
config.LOG_LEVEL; // 'debug' | 'info' | 'warn' | 'error'
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
## Performance & Bundle Size
|
|
106
|
+
|
|
107
|
+
**Ultra-lightweight and optimized.** The library uses intelligent validation strategies to minimize bundle size:
|
|
108
|
+
|
|
109
|
+
### Inline validation for basic types
|
|
110
|
+
|
|
111
|
+
Common types use **inline validation** with zero external dependencies:
|
|
112
|
+
- `string`, `number`, `boolean` (with min/max validation)
|
|
113
|
+
- `enum` (array validation)
|
|
114
|
+
- `pattern` (regex validation)
|
|
115
|
+
- `custom` (validator functions)
|
|
116
|
+
|
|
117
|
+
```ts
|
|
118
|
+
// Minimal overhead for basic validation
|
|
119
|
+
const config = resolve({
|
|
120
|
+
PORT: 3000,
|
|
121
|
+
DEBUG: false,
|
|
122
|
+
NODE_ENV: ['development', 'production'] as const,
|
|
123
|
+
API_KEY: 'string'
|
|
124
|
+
});
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
### All types work synchronously
|
|
128
|
+
|
|
129
|
+
All validator types (including advanced ones) work in both synchronous and asynchronous contexts:
|
|
130
|
+
|
|
131
|
+
```ts
|
|
132
|
+
// Synchronous - works with all types
|
|
133
|
+
const config = resolve({
|
|
134
|
+
DATABASE_URL: 'postgres',
|
|
135
|
+
API_URL: 'url',
|
|
136
|
+
PORT: 'port:3000'
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
// Also works with async resolvers
|
|
140
|
+
const config = await resolve.with([
|
|
141
|
+
awsSecrets(),
|
|
142
|
+
{ DATABASE_URL: 'postgres', API_URL: 'url' }
|
|
143
|
+
]);
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
### Audit Logging (Lazy Loaded)
|
|
147
|
+
|
|
148
|
+
Audit logging is **only loaded when enabled**:
|
|
149
|
+
|
|
150
|
+
```ts
|
|
151
|
+
// Audit module not loaded
|
|
152
|
+
const config = resolve({ PORT: 3000 });
|
|
153
|
+
|
|
154
|
+
// Audit loaded when enabled
|
|
155
|
+
const config = resolve({ PORT: 3000 }, { enableAudit: true });
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
### Tree-Shaking Friendly
|
|
159
|
+
|
|
160
|
+
The library uses ES modules for optimal tree-shaking:
|
|
161
|
+
|
|
162
|
+
```ts
|
|
163
|
+
// Your bundle only includes what you import
|
|
164
|
+
import { resolve } from 'node-env-resolver'; // ✅ Core functionality
|
|
165
|
+
|
|
166
|
+
import { resolveZod } from 'node-env-resolver/zod'; // ✅ Separate chunk
|
|
167
|
+
import { awsSecrets } from 'node-env-resolver-aws'; // ✅ Separate package
|
|
168
|
+
```
|
|
169
|
+
|
|
170
|
+
## Built-in validators
|
|
171
|
+
|
|
172
|
+
All validator types work synchronously and asynchronously.
|
|
173
|
+
|
|
174
|
+
### Basic types
|
|
175
|
+
|
|
176
|
+
These types use inline validation with **zero external dependencies**:
|
|
177
|
+
|
|
178
|
+
- `'string'` - Any string value (with optional `min`/`max` length)
|
|
179
|
+
- `'number'` - Numeric value (coerced from string, with optional `min`/`max`)
|
|
180
|
+
- `'boolean'` - Boolean value (`'true'`/`'false'` coerced to boolean)
|
|
181
|
+
- `'enum'` - Array of allowed values
|
|
182
|
+
- `'pattern'` - Regex pattern validation
|
|
183
|
+
- `'custom'` - Custom validator function
|
|
184
|
+
|
|
185
|
+
### Advanced types
|
|
186
|
+
|
|
187
|
+
Advanced validators provide specialized validation and parsing:
|
|
188
|
+
|
|
189
|
+
**Network types:**
|
|
190
|
+
|
|
191
|
+
- `'url'` - Valid URL (returns URL object)
|
|
192
|
+
- `'http'` - HTTP or HTTPS URL
|
|
193
|
+
- `'https'` - HTTPS-only URL (strict)
|
|
194
|
+
- `'email'` - Email address
|
|
195
|
+
|
|
196
|
+
**Database connection strings:**
|
|
197
|
+
|
|
198
|
+
- `'postgres'` or `'postgresql'` - PostgreSQL connection string
|
|
199
|
+
- `'mysql'` - MySQL connection string
|
|
200
|
+
- `'mongodb'` - MongoDB connection string
|
|
201
|
+
- `'redis'` - Redis connection string
|
|
202
|
+
|
|
203
|
+
**Format types:**
|
|
204
|
+
|
|
205
|
+
- `'json'` - JSON value (parsed automatically)
|
|
206
|
+
- `'port'` - Port number (1-65535)
|
|
207
|
+
- `'date'` - ISO 8601 date string
|
|
208
|
+
- `'timestamp'` - Unix timestamp
|
|
209
|
+
|
|
210
|
+
All validators automatically handle type coercion from environment variable strings.
|
|
211
|
+
|
|
212
|
+
## Custom validators
|
|
75
213
|
|
|
76
214
|
Write your own validation functions:
|
|
77
215
|
|
|
78
216
|
```ts
|
|
79
|
-
const
|
|
217
|
+
const isValidPort = (value: string): number => {
|
|
80
218
|
const port = parseInt(value, 10);
|
|
81
219
|
if (isNaN(port) || port < 1 || port > 65535) {
|
|
82
220
|
throw new Error('Port must be between 1 and 65535');
|
|
@@ -84,15 +222,22 @@ const portValidator = (value: string): number => {
|
|
|
84
222
|
return port;
|
|
85
223
|
};
|
|
86
224
|
|
|
87
|
-
const
|
|
88
|
-
|
|
89
|
-
|
|
225
|
+
const isValidEmail = (value: string): string => {
|
|
226
|
+
if (!value.includes('@')) {
|
|
227
|
+
throw new Error('Invalid email address');
|
|
228
|
+
}
|
|
229
|
+
return value.toLowerCase();
|
|
230
|
+
};
|
|
231
|
+
|
|
232
|
+
const config = resolve({
|
|
233
|
+
CUSTOM_PORT: isValidPort,
|
|
234
|
+
ADMIN_EMAIL: isValidEmail
|
|
90
235
|
});
|
|
91
236
|
```
|
|
92
237
|
|
|
93
|
-
|
|
238
|
+
## Multiple sources
|
|
94
239
|
|
|
95
|
-
Load from
|
|
240
|
+
Load configuration from multiple sources. By default, later sources override earlier ones:
|
|
96
241
|
|
|
97
242
|
```ts
|
|
98
243
|
import { resolve, processEnv, dotenv } from 'node-env-resolver';
|
|
@@ -103,237 +248,805 @@ const config = await resolve.with(
|
|
|
103
248
|
NODE_ENV: ['development', 'production'] as const,
|
|
104
249
|
}],
|
|
105
250
|
[dotenv(), {
|
|
106
|
-
DATABASE_URL: '
|
|
251
|
+
DATABASE_URL: 'url',
|
|
107
252
|
API_KEY: 'string',
|
|
108
253
|
}]
|
|
109
254
|
);
|
|
110
255
|
```
|
|
111
256
|
|
|
112
|
-
|
|
257
|
+
### Controlling merge behaviour
|
|
258
|
+
|
|
259
|
+
Use `priority` to control how resolvers merge values:
|
|
260
|
+
|
|
261
|
+
```ts
|
|
262
|
+
// priority: 'last' (default) - later resolvers override earlier ones
|
|
263
|
+
const config = await resolve.with(
|
|
264
|
+
[processEnv(), { DATABASE_URL: 'url' }],
|
|
265
|
+
[awsSecrets(), { DATABASE_URL: 'url' }]
|
|
266
|
+
// AWS wins
|
|
267
|
+
);
|
|
268
|
+
|
|
269
|
+
// priority: 'first' - earlier resolvers take precedence
|
|
270
|
+
const config = await resolve.with(
|
|
271
|
+
[dotenv(), { DATABASE_URL: 'url' }],
|
|
272
|
+
[awsSecrets(), { DATABASE_URL: 'url' }],
|
|
273
|
+
{ priority: 'first' }
|
|
274
|
+
// dotenv wins
|
|
275
|
+
);
|
|
276
|
+
```
|
|
277
|
+
|
|
278
|
+
This is useful for development workflows where local overrides should take precedence over cloud secrets.
|
|
279
|
+
|
|
280
|
+
### Performance optimizations
|
|
281
|
+
|
|
282
|
+
The library includes two automatic performance optimizations:
|
|
283
|
+
|
|
284
|
+
#### 1. Early termination with `priority: 'first'`
|
|
285
|
+
|
|
286
|
+
When using `priority: 'first'`, resolvers are called sequentially, but execution **stops early** once all required environment variables are satisfied:
|
|
287
|
+
|
|
288
|
+
```ts
|
|
289
|
+
const config = await resolve.with(
|
|
290
|
+
[dotenv(), { DATABASE_URL: 'url', API_KEY: 'string', PORT: 3000 }],
|
|
291
|
+
[awsSecrets(), { DATABASE_URL: 'url', API_KEY: 'string', PORT: 3000 }],
|
|
292
|
+
[gcpSecrets(), { DATABASE_URL: 'url', API_KEY: 'string', PORT: 3000 }],
|
|
293
|
+
{ priority: 'first' }
|
|
294
|
+
);
|
|
295
|
+
// If dotenv() provides all required keys, awsSecrets() and gcpSecrets() are never called!
|
|
296
|
+
```
|
|
297
|
+
|
|
298
|
+
This is particularly valuable in development where:
|
|
299
|
+
|
|
300
|
+
- Local `.env` file contains all needed variables
|
|
301
|
+
- Expensive remote resolver calls (AWS Secrets Manager, Parameter Store, GCP Secret Manager) are skipped
|
|
302
|
+
- Startup time is significantly reduced
|
|
303
|
+
|
|
304
|
+
**What counts as "satisfied"?**
|
|
113
305
|
|
|
114
|
-
|
|
306
|
+
- Only **required** keys (no `optional: true`, no `default` value) trigger early termination
|
|
307
|
+
- Optional variables and variables with defaults do **not** prevent calling remaining resolvers
|
|
115
308
|
|
|
116
|
-
|
|
309
|
+
#### 2. Parallel execution with `priority: 'last'`
|
|
310
|
+
|
|
311
|
+
When using `priority: 'last'` (the default), all resolvers are called **in parallel** for maximum performance:
|
|
117
312
|
|
|
118
313
|
```ts
|
|
119
|
-
|
|
314
|
+
const config = await resolve.with(
|
|
315
|
+
[awsSecrets(), { DATABASE_URL: 'url' }], // 100ms
|
|
316
|
+
[awsParameterStore(), { API_KEY: 'string' }], // 100ms
|
|
317
|
+
[gcpSecrets(), { JWT_SECRET: 'string' }] // 100ms
|
|
318
|
+
// Default: priority: 'last'
|
|
319
|
+
);
|
|
320
|
+
// Total time: ~100ms (parallel) instead of ~300ms (sequential)
|
|
321
|
+
```
|
|
120
322
|
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
323
|
+
Since `priority: 'last'` means "last write wins", the order doesn't matter for conflict resolution, so all resolvers can run concurrently.
|
|
324
|
+
|
|
325
|
+
**Use cases:**
|
|
326
|
+
|
|
327
|
+
- Production environments loading from multiple remote secret stores
|
|
328
|
+
- Fetching different variables from different sources
|
|
329
|
+
- Significant speedup when resolvers have network latency
|
|
330
|
+
|
|
331
|
+
## Safe error handling
|
|
332
|
+
|
|
333
|
+
Like Zod's `safeParse()`, use `safeResolve()` to get a result object instead of throwing:
|
|
131
334
|
|
|
132
|
-
|
|
133
|
-
|
|
335
|
+
```ts
|
|
336
|
+
import { safeResolve } from 'node-env-resolver';
|
|
337
|
+
|
|
338
|
+
const result = safeResolve({
|
|
134
339
|
PORT: 'number',
|
|
135
|
-
DATABASE_URL: '
|
|
340
|
+
DATABASE_URL: 'url'
|
|
136
341
|
});
|
|
137
342
|
|
|
138
343
|
if (result.success) {
|
|
139
|
-
|
|
140
|
-
|
|
344
|
+
// Use result.data with full type safety
|
|
345
|
+
console.log(result.data.PORT);
|
|
141
346
|
} else {
|
|
142
|
-
|
|
347
|
+
// Handle error gracefully
|
|
348
|
+
console.error(result.error);
|
|
349
|
+
process.exit(1);
|
|
143
350
|
}
|
|
144
351
|
```
|
|
145
352
|
|
|
146
|
-
|
|
353
|
+
All functions have safe variants:
|
|
354
|
+
|
|
355
|
+
- `resolve()` → `safeResolve()` (both synchronous)
|
|
356
|
+
- `resolve.with()` → `safeResolve.with()` (both async)
|
|
147
357
|
|
|
148
|
-
|
|
149
|
-
|----------|----------|----------|
|
|
150
|
-
| `resolve()` | Throws on error | Simple apps, fail-fast |
|
|
151
|
-
| `safeResolve()` | Returns `{ success, data?, error? }` | Graceful error handling |
|
|
152
|
-
| `resolveSync()` | Sync, throws on error | Sync config loading |
|
|
153
|
-
| `safeResolveSync()` | Sync, returns result object | Sync with error handling |
|
|
358
|
+
## Synchronous resolution
|
|
154
359
|
|
|
155
|
-
|
|
360
|
+
`resolve()` is **synchronous by default** when reading from `process.env`:
|
|
156
361
|
|
|
157
362
|
```ts
|
|
158
|
-
|
|
363
|
+
import { resolve } from 'node-env-resolver';
|
|
364
|
+
|
|
365
|
+
// Synchronous - no await needed, works with ALL types
|
|
366
|
+
const config = resolve({
|
|
367
|
+
PORT: 3000,
|
|
368
|
+
NODE_ENV: ['development', 'production'] as const,
|
|
369
|
+
API_KEY: 'string',
|
|
370
|
+
API_URL: 'url', // Advanced types work synchronously!
|
|
371
|
+
DATABASE_URL: 'postgres',
|
|
372
|
+
DEBUG: false
|
|
373
|
+
});
|
|
374
|
+
```
|
|
375
|
+
|
|
376
|
+
`resolve.with()` is **async** when using custom resolvers:
|
|
377
|
+
|
|
378
|
+
```ts
|
|
379
|
+
// Async - await required when using custom resolvers
|
|
380
|
+
const config = await resolve.with(
|
|
159
381
|
[processEnv(), { PORT: 3000 }],
|
|
160
|
-
[
|
|
382
|
+
[dotenv(), { DATABASE_URL: 'postgres', API_URL: 'url' }]
|
|
161
383
|
);
|
|
384
|
+
```
|
|
162
385
|
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
386
|
+
## Advanced features
|
|
387
|
+
|
|
388
|
+
### Zod integration
|
|
389
|
+
|
|
390
|
+
Use Zod schemas directly:
|
|
391
|
+
|
|
392
|
+
```ts
|
|
393
|
+
import { resolveZod } from 'node-env-resolver/zod';
|
|
394
|
+
import { z } from 'zod';
|
|
395
|
+
|
|
396
|
+
const schema = z.object({
|
|
397
|
+
PORT: z.coerce.number().default(3000),
|
|
398
|
+
DATABASE_URL: z.string().url(),
|
|
399
|
+
NODE_ENV: z.enum(['development', 'production', 'test']),
|
|
400
|
+
DEBUG: z.coerce.boolean().optional(),
|
|
401
|
+
});
|
|
402
|
+
|
|
403
|
+
const config = await resolveZod(schema);
|
|
167
404
|
```
|
|
168
405
|
|
|
169
|
-
|
|
406
|
+
Available functions:
|
|
407
|
+
|
|
408
|
+
- `resolveZod()` - Async, throws on error
|
|
409
|
+
- `safeResolveZod()` - Async, returns result object
|
|
410
|
+
|
|
411
|
+
### Custom resolvers
|
|
170
412
|
|
|
171
|
-
|
|
413
|
+
Create resolvers to load configuration from any source:
|
|
172
414
|
|
|
173
415
|
```ts
|
|
174
|
-
import { resolve,
|
|
416
|
+
import { resolve, type Resolver } from 'node-env-resolver';
|
|
417
|
+
|
|
418
|
+
const databaseResolver: Resolver = {
|
|
419
|
+
name: 'database',
|
|
420
|
+
async load() {
|
|
421
|
+
const rows = await db.query('SELECT key, value FROM config');
|
|
422
|
+
return Object.fromEntries(rows.map(r => [r.key, r.value]));
|
|
423
|
+
}
|
|
424
|
+
};
|
|
175
425
|
|
|
176
426
|
const config = await resolve.with(
|
|
177
427
|
[processEnv(), { PORT: 3000 }],
|
|
178
|
-
[
|
|
179
|
-
API_KEY: 'string',
|
|
180
|
-
}]
|
|
428
|
+
[databaseResolver, { FEATURE_FLAGS: 'json' }]
|
|
181
429
|
);
|
|
182
430
|
```
|
|
183
431
|
|
|
184
|
-
|
|
432
|
+
### AWS Secrets Manager
|
|
185
433
|
|
|
186
|
-
|
|
434
|
+
Install the AWS package:
|
|
435
|
+
|
|
436
|
+
```bash
|
|
437
|
+
npm install node-env-resolver-aws
|
|
438
|
+
```
|
|
439
|
+
|
|
440
|
+
Single source:
|
|
441
|
+
|
|
442
|
+
```ts
|
|
443
|
+
import { resolveSecrets } from 'node-env-resolver-aws';
|
|
444
|
+
|
|
445
|
+
const config = await resolveSecrets({
|
|
446
|
+
secretId: 'myapp/secrets'
|
|
447
|
+
}, {
|
|
448
|
+
DATABASE_URL: 'url',
|
|
449
|
+
API_KEY: 'string'
|
|
450
|
+
});
|
|
451
|
+
```
|
|
452
|
+
|
|
453
|
+
Multiple sources:
|
|
187
454
|
|
|
188
455
|
```ts
|
|
189
|
-
'
|
|
190
|
-
'
|
|
191
|
-
'url' // URL (returns URL object)
|
|
192
|
-
'email' // Email address
|
|
193
|
-
'port' // Port number (1-65535)
|
|
194
|
-
'json' // JSON value
|
|
195
|
-
'postgres' // PostgreSQL connection string
|
|
196
|
-
'mysql' // MySQL connection string
|
|
197
|
-
'mongodb' // MongoDB connection string
|
|
198
|
-
'redis' // Redis connection string
|
|
456
|
+
import { resolve } from 'node-env-resolver';
|
|
457
|
+
import { awsSecrets, awsSsm } from 'node-env-resolver-aws';
|
|
199
458
|
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
[
|
|
459
|
+
const config = await resolve.with(
|
|
460
|
+
[processEnv(), { PORT: 3000 }],
|
|
461
|
+
[awsSecrets({ secretId: 'app/secrets' }), { DATABASE_URL: 'url' }],
|
|
462
|
+
[awsSsm({ path: '/app/config' }), { FEATURE_FLAGS: 'json' }]
|
|
463
|
+
);
|
|
204
464
|
```
|
|
205
465
|
|
|
206
|
-
|
|
466
|
+
See the [AWS package documentation](../node-env-resolver-aws/README.md) for details on credentials, caching, and best practices.
|
|
467
|
+
|
|
468
|
+
### TTL caching
|
|
207
469
|
|
|
208
|
-
|
|
470
|
+
Cache expensive operations like AWS API calls:
|
|
209
471
|
|
|
210
472
|
```ts
|
|
211
|
-
{
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
}
|
|
473
|
+
import { resolve, cached, TTL } from 'node-env-resolver';
|
|
474
|
+
import { awsSecrets } from 'node-env-resolver-aws';
|
|
475
|
+
|
|
476
|
+
export const getConfig = async () => {
|
|
477
|
+
return await resolve.with(
|
|
478
|
+
[cached(
|
|
479
|
+
awsSecrets({ secretId: 'app/secrets' }),
|
|
480
|
+
{ ttl: TTL.minutes5 }
|
|
481
|
+
), {
|
|
482
|
+
DATABASE_URL: 'url',
|
|
483
|
+
API_KEY: 'string',
|
|
484
|
+
}]
|
|
485
|
+
);
|
|
486
|
+
};
|
|
487
|
+
|
|
488
|
+
// Call getConfig() in your handlers
|
|
489
|
+
app.get('/api/data', async (req, res) => {
|
|
490
|
+
const config = await getConfig(); // Fast after first call
|
|
491
|
+
});
|
|
219
492
|
```
|
|
220
493
|
|
|
221
|
-
|
|
494
|
+
Performance:
|
|
495
|
+
|
|
496
|
+
- First call: ~200ms (loads from AWS)
|
|
497
|
+
- Subsequent calls (< 5min): <1ms (cached)
|
|
498
|
+
- After 5min: ~200ms (refresh from AWS)
|
|
499
|
+
|
|
500
|
+
**Important:** Call `resolve()` every time. The `cached()` wrapper handles the caching.
|
|
501
|
+
|
|
502
|
+
## API Reference
|
|
503
|
+
|
|
504
|
+
### Function variants
|
|
505
|
+
|
|
506
|
+
| Function | Behaviour | Use case |
|
|
507
|
+
|----------|-----------|----------|
|
|
508
|
+
| `resolve()` | Sync, throws on error | Most applications (reading from process.env) |
|
|
509
|
+
| `safeResolve()` | Sync, returns result object | Graceful error handling |
|
|
510
|
+
| `resolve.with()` | Async, throws on error | Multiple sources (dotenv, AWS, etc.) |
|
|
511
|
+
| `safeResolve.with()` | Async, returns result object | Multiple sources with error handling |
|
|
512
|
+
|
|
513
|
+
### Shorthand syntax
|
|
514
|
+
|
|
515
|
+
| Syntax | Type | Description |
|
|
516
|
+
|--------|------|-------------|
|
|
517
|
+
| `'string'` | `string` | Required string |
|
|
518
|
+
| `'string?'` | `string \| undefined` | Optional string |
|
|
519
|
+
| `'number'` | `number` | Required number |
|
|
520
|
+
| `'number?'` | `number \| undefined` | Optional number |
|
|
521
|
+
| `'boolean'` | `boolean` | Required boolean |
|
|
522
|
+
| `'boolean?'` | `boolean \| undefined` | Optional boolean |
|
|
523
|
+
| `'url'` | `string` | Valid URL |
|
|
524
|
+
| `'email'` | `string` | Email address |
|
|
525
|
+
| `'port'` | `number` | Port (1-65535) |
|
|
526
|
+
| `'json'` | `unknown` | Parsed JSON |
|
|
527
|
+
| `'postgres'` | `string` | PostgreSQL connection string |
|
|
528
|
+
| `3000` | `number` | Number with default |
|
|
529
|
+
| `false` | `boolean` | Boolean with default |
|
|
530
|
+
| `['a', 'b']` | `'a' \| 'b'` | Enum (requires `as const`) |
|
|
531
|
+
|
|
532
|
+
## Configuration Options
|
|
533
|
+
|
|
534
|
+
All `resolve()` functions accept an optional `options` parameter to control behaviour:
|
|
222
535
|
|
|
223
536
|
```ts
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
strict: true,
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
537
|
+
// Single source (process.env) - options as second parameter
|
|
538
|
+
const config = resolve(schema, {
|
|
539
|
+
interpolate: false,
|
|
540
|
+
strict: true,
|
|
541
|
+
policies: {...},
|
|
542
|
+
enableAudit: true
|
|
543
|
+
});
|
|
544
|
+
|
|
545
|
+
// Multiple sources - options as last parameter to resolve.with()
|
|
546
|
+
const config = await resolve.with(
|
|
547
|
+
[resolver1, schema],
|
|
548
|
+
[resolver2, schema],
|
|
549
|
+
{
|
|
550
|
+
interpolate: false,
|
|
551
|
+
strict: true,
|
|
552
|
+
policies: {...},
|
|
553
|
+
enableAudit: true,
|
|
554
|
+
priority: 'last'
|
|
233
555
|
}
|
|
556
|
+
);
|
|
557
|
+
```
|
|
558
|
+
|
|
559
|
+
**Note:** The `resolvers` option has been removed. For single source resolution, use `resolve()` directly (defaults to `process.env`). For multiple sources, use `resolve.with()` syntax.
|
|
560
|
+
|
|
561
|
+
### `interpolate`
|
|
562
|
+
|
|
563
|
+
**What:** Enables variable interpolation using `${VAR_NAME}` syntax.
|
|
564
|
+
|
|
565
|
+
**When:** Use when environment variables reference other variables.
|
|
566
|
+
|
|
567
|
+
**Why:** Keeps configuration DRY and maintainable.
|
|
568
|
+
|
|
569
|
+
**Default:** `true` in `resolve.with()`, `false` in `resolve()`
|
|
570
|
+
|
|
571
|
+
```ts
|
|
572
|
+
// With interpolation
|
|
573
|
+
process.env.BASE_URL = 'https://api.example.com';
|
|
574
|
+
process.env.API_ENDPOINT = '${BASE_URL}/v1';
|
|
575
|
+
|
|
576
|
+
const config = resolve({
|
|
577
|
+
BASE_URL: 'url',
|
|
578
|
+
API_ENDPOINT: 'url'
|
|
579
|
+
}, {
|
|
580
|
+
interpolate: true
|
|
234
581
|
});
|
|
582
|
+
|
|
583
|
+
// config.API_ENDPOINT === 'https://api.example.com/v1'
|
|
235
584
|
```
|
|
236
585
|
|
|
237
|
-
###
|
|
586
|
+
### `strict`
|
|
587
|
+
|
|
588
|
+
**What:** Controls whether resolver failures stop the entire resolution process.
|
|
589
|
+
|
|
590
|
+
**When:**
|
|
591
|
+
|
|
592
|
+
- `strict: true` (default) - Production environments where you want fail-fast behaviour
|
|
593
|
+
- `strict: false` - Graceful degradation when some sources might be unavailable
|
|
594
|
+
|
|
595
|
+
**Why:**
|
|
596
|
+
|
|
597
|
+
- `true`: Ensures all resolvers work correctly (reliability)
|
|
598
|
+
- `false`: Allows partial success when some resolvers fail (availability)
|
|
599
|
+
|
|
600
|
+
**Default:** `true`
|
|
238
601
|
|
|
239
602
|
```ts
|
|
240
|
-
|
|
603
|
+
const flakyResolver = {
|
|
604
|
+
name: 'external-api',
|
|
605
|
+
async load() {
|
|
606
|
+
throw new Error('Service unavailable');
|
|
607
|
+
}
|
|
608
|
+
};
|
|
241
609
|
|
|
242
|
-
//
|
|
243
|
-
|
|
610
|
+
// ❌ Throws immediately
|
|
611
|
+
await resolve.with(
|
|
612
|
+
[flakyResolver, schema],
|
|
613
|
+
[processEnv(), schema],
|
|
614
|
+
{ strict: true } // default
|
|
615
|
+
);
|
|
244
616
|
|
|
245
|
-
//
|
|
246
|
-
|
|
617
|
+
// ✅ Continues with processEnv()
|
|
618
|
+
await resolve.with(
|
|
619
|
+
[flakyResolver, schema],
|
|
620
|
+
[processEnv(), schema],
|
|
621
|
+
{ strict: false } // graceful degradation
|
|
622
|
+
);
|
|
247
623
|
```
|
|
248
624
|
|
|
249
|
-
|
|
625
|
+
**Note:** In sync mode with `strict: true`, resolvers without `loadSync()` method will throw errors.
|
|
626
|
+
|
|
627
|
+
### `priority`
|
|
628
|
+
|
|
629
|
+
**What:** Controls merge strategy when multiple resolvers provide the same variable.
|
|
630
|
+
|
|
631
|
+
**When:**
|
|
632
|
+
|
|
633
|
+
- `priority: 'last'` (default) - Production: cloud secrets override local env
|
|
634
|
+
- `priority: 'first'` - Development: local overrides override cloud secrets
|
|
635
|
+
|
|
636
|
+
**Why:** Different environments need different precedence rules.
|
|
637
|
+
|
|
638
|
+
**Default:** `'last'`
|
|
250
639
|
|
|
251
640
|
```ts
|
|
252
|
-
|
|
641
|
+
// Production: AWS secrets override process.env
|
|
642
|
+
await resolve.with(
|
|
643
|
+
[processEnv(), { DATABASE_URL: 'url' }],
|
|
644
|
+
[awsSecrets(), { DATABASE_URL: 'url' }]
|
|
645
|
+
// priority: 'last' (default) - AWS wins
|
|
646
|
+
);
|
|
647
|
+
|
|
648
|
+
// Development: Local .env overrides cloud
|
|
649
|
+
await resolve.with(
|
|
650
|
+
[dotenv(), { DATABASE_URL: 'url' }],
|
|
651
|
+
[awsSecrets(), { DATABASE_URL: 'url' }],
|
|
652
|
+
{ priority: 'first' } // dotenv wins
|
|
653
|
+
);
|
|
654
|
+
```
|
|
655
|
+
|
|
656
|
+
**See:** "Controlling merge behaviour" section above for details.
|
|
253
657
|
|
|
254
|
-
|
|
255
|
-
cached(resolver, { ttl: 300 })
|
|
658
|
+
### `policies`
|
|
256
659
|
|
|
257
|
-
|
|
258
|
-
retry(resolver, { attempts: 3 })
|
|
660
|
+
**What:** Security policies to enforce where variables can be loaded from.
|
|
259
661
|
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
662
|
+
**When:** Use in production to enforce security requirements.
|
|
663
|
+
|
|
664
|
+
**Why:** Prevent accidental use of `.env` files or ensure secrets come from secure sources.
|
|
665
|
+
|
|
666
|
+
**Default:** `undefined` (no policies enforced)
|
|
667
|
+
|
|
668
|
+
```ts
|
|
669
|
+
await resolve.with(
|
|
670
|
+
[processEnv(), schema],
|
|
671
|
+
[awsSecrets(), schema],
|
|
672
|
+
{
|
|
673
|
+
policies: {
|
|
674
|
+
// Block .env in production (default behaviour)
|
|
675
|
+
allowDotenvInProduction: false,
|
|
676
|
+
|
|
677
|
+
// Force secrets to come from AWS
|
|
678
|
+
enforceAllowedSources: {
|
|
679
|
+
DATABASE_PASSWORD: ['aws-secrets'],
|
|
680
|
+
API_KEY: ['aws-secrets']
|
|
681
|
+
}
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
);
|
|
265
685
|
```
|
|
266
686
|
|
|
267
|
-
|
|
687
|
+
**See:** "Security Policies" section below for complete documentation.
|
|
688
|
+
|
|
689
|
+
### `enableAudit`
|
|
690
|
+
|
|
691
|
+
**What:** Enables audit logging to track where each variable was loaded from.
|
|
692
|
+
|
|
693
|
+
**When:**
|
|
694
|
+
|
|
695
|
+
- Production monitoring and compliance
|
|
696
|
+
- Debugging configuration issues
|
|
697
|
+
- Security audits
|
|
698
|
+
|
|
699
|
+
**Why:** Track configuration sources for compliance and troubleshooting.
|
|
268
700
|
|
|
269
|
-
|
|
701
|
+
**Default:** `false` (disabled in development), automatically `true` in production (`NODE_ENV === 'production'`)
|
|
270
702
|
|
|
271
703
|
```ts
|
|
704
|
+
await resolve.with(
|
|
705
|
+
[processEnv(), schema],
|
|
706
|
+
[awsSecrets(), schema],
|
|
707
|
+
{ enableAudit: true } // Explicitly enable in development
|
|
708
|
+
);
|
|
709
|
+
|
|
710
|
+
const logs = getAuditLog();
|
|
711
|
+
// [
|
|
712
|
+
// { type: 'env_loaded', key: 'DATABASE_URL', source: 'aws-secrets', ... },
|
|
713
|
+
// { type: 'validation_success', ... }
|
|
714
|
+
// ]
|
|
715
|
+
```
|
|
716
|
+
|
|
717
|
+
**See:** "Audit Logging" section below for complete documentation.
|
|
718
|
+
|
|
719
|
+
### Complete Interface
|
|
720
|
+
|
|
721
|
+
```ts
|
|
722
|
+
interface ResolveOptions {
|
|
723
|
+
interpolate?: boolean; // Variable interpolation (default: true in .with())
|
|
724
|
+
strict?: boolean; // Fail-fast behaviour (default: true)
|
|
725
|
+
priority?: 'first' | 'last'; // Merge strategy (default: 'last')
|
|
726
|
+
policies?: PolicyOptions; // Security policies (default: undefined)
|
|
727
|
+
enableAudit?: boolean; // Audit logging (default: auto in production)
|
|
728
|
+
}
|
|
729
|
+
|
|
730
|
+
interface PolicyOptions {
|
|
731
|
+
allowDotenvInProduction?: boolean | string[]; // .env in production control
|
|
732
|
+
enforceAllowedSources?: Record<string, string[]>; // Source restrictions
|
|
733
|
+
}
|
|
734
|
+
```
|
|
735
|
+
|
|
736
|
+
## Framework examples
|
|
737
|
+
|
|
738
|
+
### Express
|
|
739
|
+
|
|
740
|
+
```ts
|
|
741
|
+
import express from 'express';
|
|
272
742
|
import { resolve } from 'node-env-resolver';
|
|
273
743
|
|
|
274
|
-
const config =
|
|
744
|
+
const config = resolve({
|
|
275
745
|
PORT: 3000,
|
|
276
|
-
NODE_ENV: ['development', 'production', 'test'] as const,
|
|
277
746
|
DATABASE_URL: 'postgres',
|
|
278
|
-
|
|
279
|
-
JWT_SECRET: 'string',
|
|
280
|
-
JWT_EXPIRES_IN: '7d',
|
|
281
|
-
ENABLE_ANALYTICS: false
|
|
747
|
+
SESSION_SECRET: 'string'
|
|
282
748
|
});
|
|
283
749
|
|
|
284
|
-
app
|
|
285
|
-
|
|
750
|
+
const app = express();
|
|
751
|
+
app.listen(config.PORT);
|
|
752
|
+
```
|
|
753
|
+
|
|
754
|
+
### Next.js
|
|
755
|
+
|
|
756
|
+
```ts
|
|
757
|
+
// env.mjs
|
|
758
|
+
import { resolve } from 'node-env-resolver/nextjs';
|
|
759
|
+
|
|
760
|
+
export const env = resolve({
|
|
761
|
+
server: {
|
|
762
|
+
DATABASE_URL: 'url',
|
|
763
|
+
API_SECRET: 'string',
|
|
764
|
+
},
|
|
765
|
+
client: {
|
|
766
|
+
NEXT_PUBLIC_APP_URL: 'url',
|
|
767
|
+
}
|
|
286
768
|
});
|
|
287
769
|
```
|
|
288
770
|
|
|
289
771
|
### AWS Lambda
|
|
290
772
|
|
|
291
773
|
```ts
|
|
292
|
-
import { resolve } from 'node-env-resolver';
|
|
774
|
+
import { resolve, cached, TTL } from 'node-env-resolver';
|
|
293
775
|
import { awsSecrets } from 'node-env-resolver-aws';
|
|
294
776
|
|
|
295
|
-
const
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
}
|
|
300
|
-
|
|
301
|
-
|
|
777
|
+
const getConfig = async () => {
|
|
778
|
+
return await resolve.with(
|
|
779
|
+
[cached(
|
|
780
|
+
awsSecrets({ secretId: 'lambda/config' }),
|
|
781
|
+
{ ttl: TTL.minutes5 }
|
|
782
|
+
), {
|
|
783
|
+
DATABASE_URL: 'url',
|
|
784
|
+
}]
|
|
785
|
+
);
|
|
786
|
+
};
|
|
302
787
|
|
|
303
788
|
export const handler = async (event) => {
|
|
304
|
-
|
|
789
|
+
const config = await getConfig();
|
|
790
|
+
// Use config
|
|
305
791
|
};
|
|
306
792
|
```
|
|
307
793
|
|
|
308
|
-
##
|
|
794
|
+
## Security Policies
|
|
309
795
|
|
|
310
|
-
|
|
796
|
+
Control where environment variables can be loaded from to enforce security requirements.
|
|
797
|
+
|
|
798
|
+
### Policy: `allowDotenvInProduction`
|
|
311
799
|
|
|
800
|
+
By default, `.env` files are **completely blocked in production** for security. Production platforms (Vercel, AWS, Docker) inject environment variables via `process.env`, NOT `.env` files.
|
|
801
|
+
|
|
802
|
+
**Default behavior (secure):**
|
|
803
|
+
|
|
804
|
+
```ts
|
|
805
|
+
// In production (NODE_ENV=production)
|
|
806
|
+
const config = await resolve.with(
|
|
807
|
+
[dotenv(), {
|
|
808
|
+
DATABASE_URL: 'url',
|
|
809
|
+
}]
|
|
810
|
+
);
|
|
811
|
+
// ❌ Throws: "DATABASE_URL cannot be sourced from .env files in production"
|
|
312
812
|
```
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
813
|
+
|
|
814
|
+
**Allow all .env variables (NOT recommended):**
|
|
815
|
+
|
|
816
|
+
```ts
|
|
817
|
+
const config = await resolve.with(
|
|
818
|
+
[dotenv(), {
|
|
819
|
+
DATABASE_URL: 'url',
|
|
820
|
+
}],
|
|
821
|
+
{
|
|
822
|
+
policies: {
|
|
823
|
+
allowDotenvInProduction: true // Allow all (risky!)
|
|
824
|
+
}
|
|
825
|
+
}
|
|
826
|
+
);
|
|
827
|
+
```
|
|
828
|
+
|
|
829
|
+
**Allow specific variables only (recommended if needed):**
|
|
830
|
+
|
|
831
|
+
```ts
|
|
832
|
+
const config = await resolve.with(
|
|
833
|
+
[dotenv(), {
|
|
834
|
+
PORT: 3000,
|
|
835
|
+
DATABASE_URL: 'url',
|
|
836
|
+
}],
|
|
837
|
+
{
|
|
838
|
+
policies: {
|
|
839
|
+
allowDotenvInProduction: ['PORT'] // Only PORT allowed from .env
|
|
840
|
+
// DATABASE_URL must come from process.env or cloud resolvers
|
|
841
|
+
}
|
|
842
|
+
}
|
|
843
|
+
);
|
|
317
844
|
```
|
|
318
845
|
|
|
319
|
-
|
|
846
|
+
### Policy: `enforceAllowedSources`
|
|
320
847
|
|
|
321
|
-
|
|
848
|
+
Restrict sensitive variables to specific resolvers (e.g., force secrets to come from AWS):
|
|
322
849
|
|
|
323
850
|
```ts
|
|
324
|
-
|
|
325
|
-
|
|
851
|
+
import { resolve, processEnv } from 'node-env-resolver';
|
|
852
|
+
import { awsSecrets } from 'node-env-resolver-aws';
|
|
853
|
+
|
|
854
|
+
const config = await resolve.with(
|
|
855
|
+
[processEnv(), {
|
|
856
|
+
PORT: 3000,
|
|
857
|
+
}],
|
|
858
|
+
[awsSecrets({ secretId: 'prod/secrets' }), {
|
|
859
|
+
DATABASE_PASSWORD: 'string',
|
|
860
|
+
API_KEY: 'string',
|
|
861
|
+
}],
|
|
862
|
+
{
|
|
863
|
+
policies: {
|
|
864
|
+
enforceAllowedSources: {
|
|
865
|
+
DATABASE_PASSWORD: ['aws-secrets'], // Must come from AWS
|
|
866
|
+
API_KEY: ['aws-secrets'] // Must come from AWS
|
|
867
|
+
// PORT not restricted - can come from any resolver
|
|
868
|
+
}
|
|
869
|
+
}
|
|
870
|
+
}
|
|
871
|
+
);
|
|
872
|
+
```
|
|
873
|
+
|
|
874
|
+
**Use case:** Ensure production secrets only come from AWS Secrets Manager, never from `.env` or `process.env`:
|
|
875
|
+
|
|
876
|
+
```ts
|
|
877
|
+
import { resolve, processEnv, cached, TTL } from 'node-env-resolver';
|
|
878
|
+
import { awsSecrets } from 'node-env-resolver-aws';
|
|
879
|
+
|
|
880
|
+
const config = await resolve.with(
|
|
881
|
+
[processEnv(), {}],
|
|
882
|
+
[cached(awsSecrets({ secretId: 'prod/db' }), { ttl: TTL.minutes5 }), {
|
|
883
|
+
DATABASE_PASSWORD: 'string',
|
|
884
|
+
STRIPE_SECRET: 'string',
|
|
885
|
+
}],
|
|
886
|
+
{
|
|
887
|
+
policies: {
|
|
888
|
+
enforceAllowedSources: {
|
|
889
|
+
DATABASE_PASSWORD: ['cached(aws-secrets)'],
|
|
890
|
+
STRIPE_SECRET: ['cached(aws-secrets)']
|
|
891
|
+
}
|
|
892
|
+
}
|
|
893
|
+
}
|
|
894
|
+
);
|
|
895
|
+
|
|
896
|
+
// ✅ If secrets come from AWS → Success
|
|
897
|
+
// ❌ If secrets come from process.env → Throws policy violation error
|
|
898
|
+
```
|
|
899
|
+
|
|
900
|
+
### PolicyOptions Interface
|
|
901
|
+
|
|
902
|
+
```ts
|
|
903
|
+
interface PolicyOptions {
|
|
904
|
+
/**
|
|
905
|
+
* Control loading from .env files in production.
|
|
906
|
+
*
|
|
907
|
+
* - undefined (default): .env files completely ignored in production
|
|
908
|
+
* - true: Allow all vars from .env in production (NOT recommended)
|
|
909
|
+
* - string[]: Allow only specific vars from .env in production
|
|
910
|
+
*/
|
|
911
|
+
allowDotenvInProduction?: boolean | string[];
|
|
912
|
+
|
|
913
|
+
/**
|
|
914
|
+
* Restrict variables to specific resolvers.
|
|
915
|
+
*
|
|
916
|
+
* Example: { DATABASE_PASSWORD: ['aws-secrets'] }
|
|
917
|
+
*/
|
|
918
|
+
enforceAllowedSources?: Record<string, string[]>;
|
|
919
|
+
}
|
|
920
|
+
```
|
|
921
|
+
|
|
922
|
+
## Audit Logging
|
|
923
|
+
|
|
924
|
+
Track environment variable resolution for security and compliance monitoring.
|
|
925
|
+
|
|
926
|
+
### Important: Audit is Disabled by Default in Development
|
|
927
|
+
|
|
928
|
+
**Audit logging is only enabled automatically in production** (`NODE_ENV === 'production'`) for performance reasons. In development, you must explicitly enable it.
|
|
929
|
+
|
|
930
|
+
### Enable Audit Logging
|
|
931
|
+
|
|
932
|
+
```ts
|
|
933
|
+
import { resolve, getAuditLog, clearAuditLog } from 'node-env-resolver';
|
|
934
|
+
|
|
935
|
+
// Option 1: Explicitly enable (works in any environment)
|
|
936
|
+
const config = resolve({
|
|
326
937
|
DATABASE_URL: 'url',
|
|
327
|
-
|
|
328
|
-
|
|
938
|
+
API_KEY: 'string',
|
|
939
|
+
}, {
|
|
940
|
+
enableAudit: true // ← Enable audit logging
|
|
329
941
|
});
|
|
330
942
|
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
943
|
+
console.log(getAuditLog());
|
|
944
|
+
// [
|
|
945
|
+
// { type: 'env_loaded', key: 'DATABASE_URL', source: 'process.env', timestamp: ... },
|
|
946
|
+
// { type: 'env_loaded', key: 'API_KEY', source: 'aws-secrets', timestamp: ... },
|
|
947
|
+
// { type: 'validation_success', metadata: { variableCount: 2 }, timestamp: ... }
|
|
948
|
+
// ]
|
|
949
|
+
|
|
950
|
+
// Clear the log
|
|
951
|
+
clearAuditLog();
|
|
952
|
+
```
|
|
953
|
+
|
|
954
|
+
```ts
|
|
955
|
+
// Option 2: Automatic in production
|
|
956
|
+
process.env.NODE_ENV = 'production';
|
|
957
|
+
|
|
958
|
+
const config = resolve({
|
|
959
|
+
DATABASE_URL: 'url',
|
|
960
|
+
});
|
|
961
|
+
|
|
962
|
+
// Audit automatically enabled in production
|
|
963
|
+
console.log(getAuditLog());
|
|
964
|
+
```
|
|
965
|
+
|
|
966
|
+
### Audit Event Types
|
|
967
|
+
|
|
968
|
+
| Event Type | When It Occurs |
|
|
969
|
+
|------------|----------------|
|
|
970
|
+
| `env_loaded` | Environment variable successfully loaded from a resolver |
|
|
971
|
+
| `validation_success` | All variables validated successfully |
|
|
972
|
+
| `validation_failure` | Variable validation failed |
|
|
973
|
+
| `policy_violation` | Security policy check failed |
|
|
974
|
+
| `resolver_error` | Resolver failed to load data |
|
|
975
|
+
|
|
976
|
+
### Monitoring Cache Performance
|
|
977
|
+
|
|
978
|
+
Audit logs include cache metadata to help monitor performance:
|
|
979
|
+
|
|
980
|
+
```ts
|
|
981
|
+
import { resolve, cached, getAuditLog } from 'node-env-resolver';
|
|
982
|
+
import { awsSecrets } from 'node-env-resolver-aws';
|
|
983
|
+
|
|
984
|
+
const config = await resolve.with(
|
|
985
|
+
[cached(awsSecrets({ secretId: 'prod/db' }), { ttl: 300000 }), {
|
|
986
|
+
DATABASE_URL: 'url',
|
|
987
|
+
}],
|
|
988
|
+
{ enableAudit: true }
|
|
989
|
+
);
|
|
990
|
+
|
|
991
|
+
const logs = getAuditLog();
|
|
992
|
+
logs.forEach(log => {
|
|
993
|
+
if (log.type === 'env_loaded') {
|
|
994
|
+
console.log(`${log.key} from ${log.source}`,
|
|
995
|
+
log.metadata?.cached ? '[CACHED]' : '[FRESH]');
|
|
996
|
+
}
|
|
997
|
+
});
|
|
998
|
+
// Output:
|
|
999
|
+
// DATABASE_URL from cached(aws-secrets) [FRESH]
|
|
1000
|
+
// (subsequent calls show [CACHED])
|
|
1001
|
+
```
|
|
1002
|
+
|
|
1003
|
+
### Production Security Monitoring
|
|
1004
|
+
|
|
1005
|
+
Use audit logs for compliance and security monitoring:
|
|
1006
|
+
|
|
1007
|
+
```ts
|
|
1008
|
+
import { resolve, processEnv, getAuditLog } from 'node-env-resolver';
|
|
1009
|
+
import { awsSecrets } from 'node-env-resolver-aws';
|
|
1010
|
+
|
|
1011
|
+
// In production
|
|
1012
|
+
const config = await resolve.with(
|
|
1013
|
+
[processEnv(), {}],
|
|
1014
|
+
[awsSecrets(), {
|
|
1015
|
+
DATABASE_PASSWORD: 'string',
|
|
1016
|
+
API_KEY: 'string',
|
|
1017
|
+
}],
|
|
1018
|
+
{
|
|
1019
|
+
policies: {
|
|
1020
|
+
enforceAllowedSources: {
|
|
1021
|
+
DATABASE_PASSWORD: ['aws-secrets'],
|
|
1022
|
+
API_KEY: ['aws-secrets']
|
|
1023
|
+
}
|
|
1024
|
+
}
|
|
1025
|
+
// enableAudit: true automatically in production
|
|
1026
|
+
}
|
|
1027
|
+
);
|
|
1028
|
+
|
|
1029
|
+
// Send audit logs to your monitoring system
|
|
1030
|
+
const logs = getAuditLog();
|
|
1031
|
+
const policyViolations = logs.filter(l => l.type === 'policy_violation');
|
|
1032
|
+
|
|
1033
|
+
if (policyViolations.length > 0) {
|
|
1034
|
+
// Alert: Secrets loaded from unauthorized source!
|
|
1035
|
+
console.error('Security violation:', policyViolations);
|
|
1036
|
+
}
|
|
1037
|
+
```
|
|
1038
|
+
|
|
1039
|
+
## Error messages
|
|
1040
|
+
|
|
1041
|
+
The library provides clear, actionable error messages:
|
|
1042
|
+
|
|
1043
|
+
```text
|
|
1044
|
+
Environment validation failed:
|
|
1045
|
+
- Missing required environment variable: DATABASE_URL
|
|
1046
|
+
- PORT: Invalid port number (1-65535)
|
|
1047
|
+
- NODE_ENV: must be one of: development, production (got: "staging")
|
|
335
1048
|
```
|
|
336
1049
|
|
|
337
|
-
##
|
|
1050
|
+
## Licence
|
|
338
1051
|
|
|
339
|
-
MIT
|
|
1052
|
+
MIT
|