node-env-resolver 6.5.1 → 6.6.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.
Files changed (92) hide show
  1. package/README.md +708 -400
  2. package/dist/builder.cjs +1 -1
  3. package/dist/builder.d.cts +1 -1
  4. package/dist/builder.d.ts +1 -1
  5. package/dist/builder.js +1 -1
  6. package/dist/chunk-3EWCMDFP.js +9 -0
  7. package/dist/chunk-BFLXBLZ3.cjs +1 -0
  8. package/dist/chunk-CDXO2XX3.cjs +2 -0
  9. package/dist/chunk-CTJYBBOB.js +2 -0
  10. package/dist/chunk-DIJNUFGZ.cjs +15 -0
  11. package/dist/chunk-DYFRO3NM.cjs +9 -0
  12. package/dist/chunk-K4NIC5T3.js +9 -0
  13. package/dist/chunk-WVMDTD6J.cjs +9 -0
  14. package/dist/chunk-ZMRT37K3.js +1 -0
  15. package/dist/chunk-ZSM2NDX5.js +15 -0
  16. package/dist/cli/bin.cjs +74 -0
  17. package/dist/cli/bin.js +74 -0
  18. package/dist/cli.d.cts +1 -1
  19. package/dist/cli.d.ts +1 -1
  20. package/dist/index.cjs +1 -1
  21. package/dist/index.d.cts +59 -3
  22. package/dist/index.d.ts +59 -3
  23. package/dist/index.js +1 -1
  24. package/dist/provider-kit.cjs +2 -0
  25. package/dist/provider-kit.d.cts +50 -0
  26. package/dist/provider-kit.d.ts +50 -0
  27. package/dist/provider-kit.js +2 -0
  28. package/dist/resolver.cjs +1 -1
  29. package/dist/resolver.d.cts +1 -1
  30. package/dist/resolver.d.ts +1 -1
  31. package/dist/resolver.js +1 -1
  32. package/dist/resolvers.cjs +1 -1
  33. package/dist/resolvers.d.cts +2 -27
  34. package/dist/resolvers.d.ts +2 -27
  35. package/dist/resolvers.js +1 -1
  36. package/dist/runtime/index.cjs +1 -0
  37. package/dist/runtime/index.d.cts +161 -0
  38. package/dist/runtime/index.d.ts +161 -0
  39. package/dist/runtime/index.js +1 -0
  40. package/dist/types--RcOnfdl.d.cts +284 -0
  41. package/dist/types--RcOnfdl.d.ts +284 -0
  42. package/dist/types.cjs +1 -1
  43. package/dist/types.d.cts +1 -129
  44. package/dist/types.d.ts +1 -129
  45. package/dist/types.js +1 -1
  46. package/dist/utils.cjs +1 -1
  47. package/dist/utils.d.cts +56 -12
  48. package/dist/utils.d.ts +56 -12
  49. package/dist/utils.js +1 -1
  50. package/dist/valibot.cjs +1 -1
  51. package/dist/valibot.d.cts +12 -25
  52. package/dist/valibot.d.ts +12 -25
  53. package/dist/valibot.js +1 -1
  54. package/dist/validators.cjs +2 -2
  55. package/dist/validators.d.cts +25 -48
  56. package/dist/validators.d.ts +25 -48
  57. package/dist/validators.js +2 -2
  58. package/dist/web.cjs +5 -5
  59. package/dist/web.d.cts +3 -1
  60. package/dist/web.d.ts +3 -1
  61. package/dist/web.js +5 -5
  62. package/dist/zod.cjs +1 -1
  63. package/dist/zod.d.cts +12 -25
  64. package/dist/zod.d.ts +12 -25
  65. package/dist/zod.js +1 -1
  66. package/package.json +26 -31
  67. package/binding.gyp +0 -9
  68. package/dist/chunk-2IQQVAXA.cjs +0 -9
  69. package/dist/chunk-46CBATKM.js +0 -1
  70. package/dist/chunk-C34FGZOG.js +0 -9
  71. package/dist/chunk-FNF55TN4.cjs +0 -1
  72. package/dist/chunk-G36OESVW.cjs +0 -1
  73. package/dist/chunk-I5UKYTX6.js +0 -1
  74. package/dist/chunk-MFFH2ZXS.js +0 -17
  75. package/dist/chunk-QCKMQEJP.cjs +0 -17
  76. package/dist/chunk-S7AB6UX7.cjs +0 -9
  77. package/dist/chunk-TGIYWWDY.js +0 -9
  78. package/dist/chunk-VUUPIWFJ.js +0 -9
  79. package/dist/chunk-ZDRU3RSU.cjs +0 -9
  80. package/dist/cli-main.cjs +0 -4
  81. package/dist/cli-main.js +0 -4
  82. package/dist/redaction.cjs +0 -1
  83. package/dist/redaction.d.cts +0 -54
  84. package/dist/redaction.d.ts +0 -54
  85. package/dist/redaction.js +0 -1
  86. package/dist/typegen.cjs +0 -1
  87. package/dist/typegen.d.cts +0 -52
  88. package/dist/typegen.d.ts +0 -52
  89. package/dist/typegen.js +0 -1
  90. package/index.js +0 -1
  91. /package/dist/{cli-main.d.cts → cli/bin.d.cts} +0 -0
  92. /package/dist/{cli-main.d.ts → cli/bin.d.ts} +0 -0
package/dist/index.d.ts CHANGED
@@ -1,8 +1,58 @@
1
- import { SimpleEnvSchema, ResolveAsyncConfig, InferSimpleValue, ResolveAsyncConfigWithSchema, Resolver, ResolveOptions, InferMergedSchemaResult, ResolveConfigWithSchema, SyncResolver, ResolveConfig } from './types.js';
2
- export { AsyncResolver, EnvDefinition, EnvSchema, InferResolveResult, InferSchema, InferSimpleSchema, InferType, PolicyOptions, Provenance, SimpleEnvValue, Validator, isAsyncOnlyResolver, isSyncResolver } from './types.js';
1
+ import { e as ReferenceHandler, P as PolicyOptions, R as ResolveOptions, S as SimpleEnvSchema, f as ResolveAsyncConfig, g as InferSimpleValue, h as ResolveAsyncConfigWithSchema, a as Resolver, b as ReferenceOptions, i as InferMergedSchemaResult, j as ResolveConfigWithSchema, d as SyncResolver, k as ResolveConfig } from './types--RcOnfdl.js';
2
+ export { A as AsyncResolver, F as DEFAULT_DEBUG_OPTIONS, G as DEFAULT_SENSITIVE_PATTERNS, v as DebugEntry, u as DebugOptions, D as DebugValueMode, c as EnvDefinition, E as EnvSchema, r as InferResolveResult, q as InferSchema, I as InferSimpleSchema, p as InferType, n as Provenance, l as ReferenceContext, m as ReferenceResolution, y as SecuritySnapshotEntry, x as SecuritySnapshotOptions, o as SimpleEnvValue, V as Validator, w as VisibilityLevel, z as createDebugView, C as createRedactedObject, B as createSecuritySnapshot, t as isAsyncOnlyResolver, s as isSyncResolver } from './types--RcOnfdl.js';
3
3
  export { SafeResolveResult as SafeResolveResultWithIssues, ValidationIssue } from './validation-types.js';
4
4
  export { AuditEvent, AuditEventType, clearAuditLog, getAuditLog } from './audit.js';
5
5
 
6
+ declare const processEnvReferenceHandler: ReferenceHandler;
7
+
8
+ interface StrictReferencePoliciesOptions {
9
+ /**
10
+ * Variables that must come from secret managers (not dotenv/process.env fallbacks).
11
+ * Example: ['STRIPE_KEY', 'DATABASE_URL']
12
+ */
13
+ sensitiveKeys: readonly string[];
14
+ /**
15
+ * Allowed resolver source(s) for sensitive keys.
16
+ * Matching accepts:
17
+ * - exact resolver/source name
18
+ * - source prefix before `(` (e.g. `aws-secrets(prod/app)` -> `aws-secrets`)
19
+ * - reference handler `resolvedVia` value
20
+ * Default: ['aws-secrets']
21
+ */
22
+ secretSources?: readonly string[] | string;
23
+ /**
24
+ * Keep secure default in production: false blocks dotenv values.
25
+ * You can pass a whitelist array to allow specific non-secret vars from dotenv.
26
+ * Default: false
27
+ */
28
+ allowDotenvInProduction?: PolicyOptions['allowDotenvInProduction'];
29
+ /**
30
+ * Optional base policy object to merge into.
31
+ */
32
+ basePolicies?: PolicyOptions;
33
+ }
34
+ /**
35
+ * Build a strict production policy preset for reference-first deployments:
36
+ * - Blocks dotenv in production by default
37
+ * - Forces sensitive keys to come from reference-backed resolvers (e.g. aws-secrets)
38
+ */
39
+ declare function strictReferencePolicies(options: StrictReferencePoliciesOptions): PolicyOptions;
40
+ interface StrictReferenceResolveOptions extends Omit<StrictReferencePoliciesOptions, 'basePolicies'> {
41
+ /**
42
+ * Optional extra resolve options to merge with this preset.
43
+ */
44
+ baseOptions?: Partial<ResolveOptions>;
45
+ /**
46
+ * Audit should be enabled for incident response reconstruction.
47
+ * Default: true
48
+ */
49
+ enableAudit?: boolean;
50
+ }
51
+ /**
52
+ * Resolve options preset for strict reference-first hardening.
53
+ */
54
+ declare function strictReferenceResolveOptions(options: StrictReferenceResolveOptions): Partial<ResolveOptions>;
55
+
6
56
  /**
7
57
  * Type-safe environment variable resolver
8
58
  *
@@ -40,18 +90,21 @@ declare function resolve<T extends SimpleEnvSchema>(config: ResolveConfigWithSch
40
90
  declare function resolve<T extends SimpleEnvSchema>(config: {
41
91
  resolvers: readonly [[SyncResolver, T]];
42
92
  options?: Partial<ResolveOptions>;
93
+ references?: ReferenceOptions;
43
94
  }): {
44
95
  [K in keyof T]: InferSimpleValue<T[K]>;
45
96
  };
46
97
  declare function resolve<T extends SimpleEnvSchema>(config: {
47
98
  resolvers: readonly [SyncResolver, T][];
48
99
  options?: Partial<ResolveOptions>;
100
+ references?: ReferenceOptions;
49
101
  }): {
50
102
  [K in keyof T]: InferSimpleValue<T[K]>;
51
103
  };
52
104
  declare function resolve<T extends readonly [SyncResolver, SimpleEnvSchema][]>(config: {
53
105
  resolvers: T;
54
106
  options?: Partial<ResolveOptions>;
107
+ references?: ReferenceOptions;
55
108
  }): InferMergedSchemaResult<T>;
56
109
  /**
57
110
  * Resolve environment variables asynchronously (supports all resolver types - both sync and async)
@@ -93,18 +146,21 @@ declare function resolveAsync<T extends SimpleEnvSchema>(config: ResolveAsyncCon
93
146
  declare function resolveAsync<T extends SimpleEnvSchema>(config: {
94
147
  resolvers: readonly [[Resolver, T]];
95
148
  options?: Partial<ResolveOptions>;
149
+ references?: ReferenceOptions;
96
150
  }): Promise<{
97
151
  [K in keyof T]: InferSimpleValue<T[K]>;
98
152
  }>;
99
153
  declare function resolveAsync<T extends SimpleEnvSchema>(config: {
100
154
  resolvers: readonly [Resolver, T][];
101
155
  options?: Partial<ResolveOptions>;
156
+ references?: ReferenceOptions;
102
157
  }): Promise<{
103
158
  [K in keyof T]: InferSimpleValue<T[K]>;
104
159
  }>;
105
160
  declare function resolveAsync<T extends readonly [Resolver, SimpleEnvSchema][]>(config: {
106
161
  resolvers: T;
107
162
  options?: Partial<ResolveOptions>;
163
+ references?: ReferenceOptions;
108
164
  }): Promise<InferMergedSchemaResult<T>>;
109
165
  /**
110
166
  * Safe resolve implementation (doesn't throw, returns result object)
@@ -161,4 +217,4 @@ declare function safeResolveAsync<T extends SimpleEnvSchema>(config: ResolveAsyn
161
217
  [K in keyof T]: InferSimpleValue<T[K]>;
162
218
  }>>;
163
219
 
164
- export { ResolveAsyncConfig, ResolveConfig, ResolveOptions, Resolver, type SafeResolveError, type SafeResolveResult, type SafeResolveResultType, SimpleEnvSchema, SyncResolver, resolve, resolveAsync, safeResolve, safeResolveAsync };
220
+ export { PolicyOptions, ReferenceHandler, ReferenceOptions, ResolveAsyncConfig, ResolveConfig, ResolveOptions, Resolver, type SafeResolveError, type SafeResolveResult, type SafeResolveResultType, SimpleEnvSchema, type StrictReferencePoliciesOptions, type StrictReferenceResolveOptions, SyncResolver, processEnvReferenceHandler, resolve, resolveAsync, safeResolve, safeResolveAsync, strictReferencePolicies, strictReferenceResolveOptions };
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- export{a as resolve,b as resolveAsync,c as safeResolve,d as safeResolveAsync}from'./chunk-C34FGZOG.js';import'./chunk-VUUPIWFJ.js';export{d as clearAuditLog,c as getAuditLog}from'./chunk-6EWR3WHU.js';export{b as isAsyncOnlyResolver,a as isSyncResolver}from'./chunk-46CBATKM.js';import'./chunk-WKIPEKF6.js';import'./chunk-I7AUKTXE.js';
1
+ export{c as resolve,d as resolveAsync,e as safeResolve,f as safeResolveAsync,a as strictReferencePolicies,b as strictReferenceResolveOptions}from'./chunk-3EWCMDFP.js';export{c as DEFAULT_DEBUG_OPTIONS,a as DEFAULT_SENSITIVE_PATTERNS,b as createDebugView,e as createRedactedObject,d as createSecuritySnapshot}from'./chunk-K4NIC5T3.js';export{a as processEnvReferenceHandler}from'./chunk-CTJYBBOB.js';export{d as clearAuditLog,c as getAuditLog}from'./chunk-6EWR3WHU.js';import'./chunk-WKIPEKF6.js';export{b as isAsyncOnlyResolver,a as isSyncResolver}from'./chunk-ZMRT37K3.js';import'./chunk-I7AUKTXE.js';
@@ -0,0 +1,2 @@
1
+ 'use strict';require('./chunk-D6WM53FN.cjs');function u(t,r){if(typeof t=="function"||typeof t=="string"&&t.trim()!=="")return t;throw new Error(`${r} is required`)}async function a(t,r){let n=typeof t=="function"?await t():t;if(typeof n!="string"||n.trim()==="")throw new Error(`${r} is required`);return n}async function c(t,r){return t===void 0?void 0:a(t,r)}function l(t,r,n=false){let e;try{e=new URL(t);}catch{throw new Error(`${r} is not a valid URL: ${JSON.stringify(t)}`)}if(e.protocol==="https:")return;let o=e.hostname==="localhost"||e.hostname==="127.0.0.1"||e.hostname==="[::1]"||e.hostname==="::1";if(!(e.protocol==="http:"&&(n||o)))throw new Error(`${r} must use https:// \u2014 got "${e.protocol}//". Credentials sent over http can be intercepted on the network. Set allowInsecureHttp: true to override for a trusted endpoint.`)}async function f(t,r,n,e=3e4){let o=new AbortController,s=setTimeout(()=>o.abort(),e);try{return await fetch(t,{...r,signal:o.signal})}catch(i){throw i instanceof Error&&i.name==="AbortError"?new Error(`Request to ${n} timed out after ${e}ms`,{cause:i}):i}finally{clearTimeout(s);}}
2
+ exports.assertSecureUrl=l;exports.fetchWithTimeout=f;exports.requireCredential=u;exports.resolveCredential=a;exports.resolveOptionalCredential=c;
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Toolkit for building remote-secret resolvers (Bitwarden, Infisical, Doppler,
3
+ * 1Password, and any third-party vault).
4
+ *
5
+ * It centralises the cross-cutting concerns every vault provider shares so each
6
+ * one is written — and audited — exactly once:
7
+ *
8
+ * - **Bootstrap-credential resolution** that accepts a lazy provider instead of
9
+ * forcing a plaintext environment string. The function form keeps the secret
10
+ * out of `process.env`/dotfiles (read it from the OS keychain, an STS/OIDC
11
+ * exchange, `op read`, …) so an environment harvest finds nothing.
12
+ * - **HTTPS transport enforcement** so a bootstrap credential is never sent in
13
+ * cleartext to an overridable (self-hosted) endpoint.
14
+ * - **A fetch wrapper** with an abort-based timeout.
15
+ */
16
+ /**
17
+ * A bootstrap credential — a vault access token, client secret, service token, …
18
+ *
19
+ * Either a literal string, or a function that produces one on demand. Prefer the
20
+ * function form in hardened setups: it lets the credential come from the OS
21
+ * keychain, a short-lived token exchange, or workload identity rather than living
22
+ * in an environment variable a supply-chain harvester can read.
23
+ */
24
+ type CredentialInput = string | (() => string | Promise<string>);
25
+ /**
26
+ * Validate a *required* credential at construction time.
27
+ *
28
+ * A literal string is checked eagerly so the familiar synchronous
29
+ * `"<label> is required"` error still fires the moment the resolver is built. A
30
+ * function provider is accepted as-is and validated when it is later resolved
31
+ * (its value isn't available yet).
32
+ */
33
+ declare function requireCredential(input: CredentialInput | undefined, label: string): CredentialInput;
34
+ /** Resolve a credential to its string value at use time, asserting it is non-empty. */
35
+ declare function resolveCredential(input: CredentialInput, label: string): Promise<string>;
36
+ /** Resolve an *optional* credential: `undefined` passes through, anything else is validated. */
37
+ declare function resolveOptionalCredential(input: CredentialInput | undefined, label: string): Promise<string | undefined>;
38
+ /**
39
+ * Reject a non-`https:` endpoint so a bootstrap credential is never transmitted
40
+ * in cleartext.
41
+ *
42
+ * Loopback hosts (`localhost`, `127.0.0.1`, `::1`) are always allowed — they are
43
+ * not exposed to network interception. Any other `http://` URL requires an
44
+ * explicit `allowInsecureHttp` opt-in.
45
+ */
46
+ declare function assertSecureUrl(rawUrl: string, label: string, allowInsecureHttp?: boolean): void;
47
+ /** `fetch()` with an abort-based timeout (default 30s), surfacing a clear timeout error. */
48
+ declare function fetchWithTimeout(url: string, init: RequestInit, service: string, timeoutMs?: number): Promise<Response>;
49
+
50
+ export { type CredentialInput, assertSecureUrl, fetchWithTimeout, requireCredential, resolveCredential, resolveOptionalCredential };
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Toolkit for building remote-secret resolvers (Bitwarden, Infisical, Doppler,
3
+ * 1Password, and any third-party vault).
4
+ *
5
+ * It centralises the cross-cutting concerns every vault provider shares so each
6
+ * one is written — and audited — exactly once:
7
+ *
8
+ * - **Bootstrap-credential resolution** that accepts a lazy provider instead of
9
+ * forcing a plaintext environment string. The function form keeps the secret
10
+ * out of `process.env`/dotfiles (read it from the OS keychain, an STS/OIDC
11
+ * exchange, `op read`, …) so an environment harvest finds nothing.
12
+ * - **HTTPS transport enforcement** so a bootstrap credential is never sent in
13
+ * cleartext to an overridable (self-hosted) endpoint.
14
+ * - **A fetch wrapper** with an abort-based timeout.
15
+ */
16
+ /**
17
+ * A bootstrap credential — a vault access token, client secret, service token, …
18
+ *
19
+ * Either a literal string, or a function that produces one on demand. Prefer the
20
+ * function form in hardened setups: it lets the credential come from the OS
21
+ * keychain, a short-lived token exchange, or workload identity rather than living
22
+ * in an environment variable a supply-chain harvester can read.
23
+ */
24
+ type CredentialInput = string | (() => string | Promise<string>);
25
+ /**
26
+ * Validate a *required* credential at construction time.
27
+ *
28
+ * A literal string is checked eagerly so the familiar synchronous
29
+ * `"<label> is required"` error still fires the moment the resolver is built. A
30
+ * function provider is accepted as-is and validated when it is later resolved
31
+ * (its value isn't available yet).
32
+ */
33
+ declare function requireCredential(input: CredentialInput | undefined, label: string): CredentialInput;
34
+ /** Resolve a credential to its string value at use time, asserting it is non-empty. */
35
+ declare function resolveCredential(input: CredentialInput, label: string): Promise<string>;
36
+ /** Resolve an *optional* credential: `undefined` passes through, anything else is validated. */
37
+ declare function resolveOptionalCredential(input: CredentialInput | undefined, label: string): Promise<string | undefined>;
38
+ /**
39
+ * Reject a non-`https:` endpoint so a bootstrap credential is never transmitted
40
+ * in cleartext.
41
+ *
42
+ * Loopback hosts (`localhost`, `127.0.0.1`, `::1`) are always allowed — they are
43
+ * not exposed to network interception. Any other `http://` URL requires an
44
+ * explicit `allowInsecureHttp` opt-in.
45
+ */
46
+ declare function assertSecureUrl(rawUrl: string, label: string, allowInsecureHttp?: boolean): void;
47
+ /** `fetch()` with an abort-based timeout (default 30s), surfacing a clear timeout error. */
48
+ declare function fetchWithTimeout(url: string, init: RequestInit, service: string, timeoutMs?: number): Promise<Response>;
49
+
50
+ export { type CredentialInput, assertSecureUrl, fetchWithTimeout, requireCredential, resolveCredential, resolveOptionalCredential };
@@ -0,0 +1,2 @@
1
+ import'./chunk-I7AUKTXE.js';function u(t,r){if(typeof t=="function"||typeof t=="string"&&t.trim()!=="")return t;throw new Error(`${r} is required`)}async function a(t,r){let n=typeof t=="function"?await t():t;if(typeof n!="string"||n.trim()==="")throw new Error(`${r} is required`);return n}async function c(t,r){return t===void 0?void 0:a(t,r)}function l(t,r,n=false){let e;try{e=new URL(t);}catch{throw new Error(`${r} is not a valid URL: ${JSON.stringify(t)}`)}if(e.protocol==="https:")return;let o=e.hostname==="localhost"||e.hostname==="127.0.0.1"||e.hostname==="[::1]"||e.hostname==="::1";if(!(e.protocol==="http:"&&(n||o)))throw new Error(`${r} must use https:// \u2014 got "${e.protocol}//". Credentials sent over http can be intercepted on the network. Set allowInsecureHttp: true to override for a trusted endpoint.`)}async function f(t,r,n,e=3e4){let o=new AbortController,s=setTimeout(()=>o.abort(),e);try{return await fetch(t,{...r,signal:o.signal})}catch(i){throw i instanceof Error&&i.name==="AbortError"?new Error(`Request to ${n} timed out after ${e}ms`,{cause:i}):i}finally{clearTimeout(s);}}
2
+ export{l as assertSecureUrl,f as fetchWithTimeout,u as requireCredential,a as resolveCredential,c as resolveOptionalCredential};
package/dist/resolver.cjs CHANGED
@@ -1 +1 @@
1
- 'use strict';var chunk2IQQVAXA_cjs=require('./chunk-2IQQVAXA.cjs');require('./chunk-O7NR4K6A.cjs'),require('./chunk-G36OESVW.cjs'),require('./chunk-D6WM53FN.cjs');Object.defineProperty(exports,"normalizeSchema",{enumerable:true,get:function(){return chunk2IQQVAXA_cjs.a}});Object.defineProperty(exports,"resolveEnvInternal",{enumerable:true,get:function(){return chunk2IQQVAXA_cjs.b}});Object.defineProperty(exports,"resolveEnvInternalSync",{enumerable:true,get:function(){return chunk2IQQVAXA_cjs.c}});
1
+ 'use strict';var chunkWVMDTD6J_cjs=require('./chunk-WVMDTD6J.cjs');require('./chunk-CDXO2XX3.cjs'),require('./chunk-O7NR4K6A.cjs'),require('./chunk-D6WM53FN.cjs');Object.defineProperty(exports,"normalizeSchema",{enumerable:true,get:function(){return chunkWVMDTD6J_cjs.f}});Object.defineProperty(exports,"resolveEnvInternal",{enumerable:true,get:function(){return chunkWVMDTD6J_cjs.g}});Object.defineProperty(exports,"resolveEnvInternalSync",{enumerable:true,get:function(){return chunkWVMDTD6J_cjs.h}});
@@ -1,4 +1,4 @@
1
- import { SimpleEnvSchema, EnvSchema, Resolver, ResolveOptions } from './types.cjs';
1
+ import { S as SimpleEnvSchema, E as EnvSchema, a as Resolver, R as ResolveOptions } from './types--RcOnfdl.cjs';
2
2
 
3
3
  /**
4
4
  * Internal resolver functions - extracted for use by both old and new APIs
@@ -1,4 +1,4 @@
1
- import { SimpleEnvSchema, EnvSchema, Resolver, ResolveOptions } from './types.js';
1
+ import { S as SimpleEnvSchema, E as EnvSchema, a as Resolver, R as ResolveOptions } from './types--RcOnfdl.js';
2
2
 
3
3
  /**
4
4
  * Internal resolver functions - extracted for use by both old and new APIs
package/dist/resolver.js CHANGED
@@ -1 +1 @@
1
- export{a as normalizeSchema,b as resolveEnvInternal,c as resolveEnvInternalSync}from'./chunk-VUUPIWFJ.js';import'./chunk-6EWR3WHU.js';import'./chunk-46CBATKM.js';import'./chunk-I7AUKTXE.js';
1
+ export{f as normalizeSchema,g as resolveEnvInternal,h as resolveEnvInternalSync}from'./chunk-K4NIC5T3.js';import'./chunk-CTJYBBOB.js';import'./chunk-6EWR3WHU.js';import'./chunk-I7AUKTXE.js';
@@ -1 +1 @@
1
- 'use strict';var chunkQCKMQEJP_cjs=require('./chunk-QCKMQEJP.cjs'),chunk4QOKRJ3F_cjs=require('./chunk-4QOKRJ3F.cjs');require('./chunk-D6WM53FN.cjs');Object.defineProperty(exports,"dotenv",{enumerable:true,get:function(){return chunkQCKMQEJP_cjs.a}});Object.defineProperty(exports,"exec",{enumerable:true,get:function(){return chunkQCKMQEJP_cjs.h}});Object.defineProperty(exports,"http",{enumerable:true,get:function(){return chunkQCKMQEJP_cjs.c}});Object.defineProperty(exports,"json",{enumerable:true,get:function(){return chunkQCKMQEJP_cjs.d}});Object.defineProperty(exports,"packageJson",{enumerable:true,get:function(){return chunkQCKMQEJP_cjs.b}});Object.defineProperty(exports,"secrets",{enumerable:true,get:function(){return chunkQCKMQEJP_cjs.e}});Object.defineProperty(exports,"toml",{enumerable:true,get:function(){return chunkQCKMQEJP_cjs.g}});Object.defineProperty(exports,"yaml",{enumerable:true,get:function(){return chunkQCKMQEJP_cjs.f}});Object.defineProperty(exports,"processEnv",{enumerable:true,get:function(){return chunk4QOKRJ3F_cjs.a}});
1
+ 'use strict';var chunkDIJNUFGZ_cjs=require('./chunk-DIJNUFGZ.cjs'),chunk4QOKRJ3F_cjs=require('./chunk-4QOKRJ3F.cjs');require('./chunk-D6WM53FN.cjs');Object.defineProperty(exports,"dotenv",{enumerable:true,get:function(){return chunkDIJNUFGZ_cjs.a}});Object.defineProperty(exports,"http",{enumerable:true,get:function(){return chunkDIJNUFGZ_cjs.c}});Object.defineProperty(exports,"json",{enumerable:true,get:function(){return chunkDIJNUFGZ_cjs.d}});Object.defineProperty(exports,"packageJson",{enumerable:true,get:function(){return chunkDIJNUFGZ_cjs.b}});Object.defineProperty(exports,"secrets",{enumerable:true,get:function(){return chunkDIJNUFGZ_cjs.e}});Object.defineProperty(exports,"toml",{enumerable:true,get:function(){return chunkDIJNUFGZ_cjs.g}});Object.defineProperty(exports,"yaml",{enumerable:true,get:function(){return chunkDIJNUFGZ_cjs.f}});Object.defineProperty(exports,"processEnv",{enumerable:true,get:function(){return chunk4QOKRJ3F_cjs.a}});
@@ -1,4 +1,4 @@
1
- import { SyncResolver, Resolver } from './types.cjs';
1
+ import { d as SyncResolver, a as Resolver } from './types--RcOnfdl.cjs';
2
2
 
3
3
  /**
4
4
  * Resolver that reads from process.env
@@ -186,30 +186,5 @@ interface TomlOptions {
186
186
  * ```
187
187
  */
188
188
  declare function toml(options?: string | TomlOptions): Resolver;
189
- interface ExecResolverOptions {
190
- /**
191
- * Output format to parse from stdout.
192
- * - 'env': KEY=VALUE lines
193
- * - 'json': JSON object (optionally nested)
194
- *
195
- * Default: 'env'
196
- */
197
- format?: 'env' | 'json';
198
- /**
199
- * Maximum time in milliseconds before killing the process.
200
- * Default: 5000ms
201
- */
202
- timeout?: number;
203
- }
204
- /**
205
- * Execute a shell command and load configuration from its stdout.
206
- *
207
- * Supports two formats:
208
- * - 'env': KEY=VALUE lines (one per line)
209
- * - 'json': JSON object (optionally nested, flattened to UPPER_SNAKE_CASE)
210
- *
211
- * Both async and sync modes are supported via exec/execSync.
212
- */
213
- declare function exec(command: string, options?: ExecResolverOptions): SyncResolver;
214
189
 
215
- export { type DotenvOptions, type ExecResolverOptions, type TomlOptions, type YamlOptions, dotenv, exec, http, json, packageJson, processEnv, secrets, toml, yaml };
190
+ export { type DotenvOptions, type TomlOptions, type YamlOptions, dotenv, http, json, packageJson, processEnv, secrets, toml, yaml };
@@ -1,4 +1,4 @@
1
- import { SyncResolver, Resolver } from './types.js';
1
+ import { d as SyncResolver, a as Resolver } from './types--RcOnfdl.js';
2
2
 
3
3
  /**
4
4
  * Resolver that reads from process.env
@@ -186,30 +186,5 @@ interface TomlOptions {
186
186
  * ```
187
187
  */
188
188
  declare function toml(options?: string | TomlOptions): Resolver;
189
- interface ExecResolverOptions {
190
- /**
191
- * Output format to parse from stdout.
192
- * - 'env': KEY=VALUE lines
193
- * - 'json': JSON object (optionally nested)
194
- *
195
- * Default: 'env'
196
- */
197
- format?: 'env' | 'json';
198
- /**
199
- * Maximum time in milliseconds before killing the process.
200
- * Default: 5000ms
201
- */
202
- timeout?: number;
203
- }
204
- /**
205
- * Execute a shell command and load configuration from its stdout.
206
- *
207
- * Supports two formats:
208
- * - 'env': KEY=VALUE lines (one per line)
209
- * - 'json': JSON object (optionally nested, flattened to UPPER_SNAKE_CASE)
210
- *
211
- * Both async and sync modes are supported via exec/execSync.
212
- */
213
- declare function exec(command: string, options?: ExecResolverOptions): SyncResolver;
214
189
 
215
- export { type DotenvOptions, type ExecResolverOptions, type TomlOptions, type YamlOptions, dotenv, exec, http, json, packageJson, processEnv, secrets, toml, yaml };
190
+ export { type DotenvOptions, type TomlOptions, type YamlOptions, dotenv, http, json, packageJson, processEnv, secrets, toml, yaml };
package/dist/resolvers.js CHANGED
@@ -1 +1 @@
1
- export{a as dotenv,h as exec,c as http,d as json,b as packageJson,e as secrets,g as toml,f as yaml}from'./chunk-MFFH2ZXS.js';export{a as processEnv}from'./chunk-WKIPEKF6.js';import'./chunk-I7AUKTXE.js';
1
+ export{a as dotenv,c as http,d as json,b as packageJson,e as secrets,g as toml,f as yaml}from'./chunk-ZSM2NDX5.js';export{a as processEnv}from'./chunk-WKIPEKF6.js';import'./chunk-I7AUKTXE.js';
@@ -0,0 +1 @@
1
+ 'use strict';require('../chunk-D6WM53FN.cjs');var P=[/password/i,/secret/i,/token/i,/key/i,/credential/i,/auth/i,/api[_-]?key/i,/access[_-]?token/i,/refresh[_-]?token/i,/private[_-]?key/i,/database[_-]?url/i,/db[_-]?url/i,/connection[_-]?string/i,/conn[_-]?string/i,/dsn/i,/bearer/i],x=[/sk_live_[a-zA-Z0-9]{24,}/g,/sk_test_[a-zA-Z0-9]{24,}/g,/pk_live_[a-zA-Z0-9]{24,}/g,/pk_test_[a-zA-Z0-9]{24,}/g,/xox[baprs]-[a-zA-Z0-9-]+/g,/ghp_[a-zA-Z0-9]{36}/g,/gho_[a-zA-Z0-9]{36}/g,/ghu_[a-zA-Z0-9]{36}/g,/ghs_[a-zA-Z0-9]{36}/g,/ghr_[a-zA-Z0-9]{36}/g,/eyJ[a-zA-Z0-9_-]*\.eyJ[a-zA-Z0-9_-]*\.[a-zA-Z0-9_-]*/g,/postgres:\/\/[^@]+:[^@]+@/g,/mysql:\/\/[^@]+:[^@]+@/g,/mongodb(\+srv)?:\/\/[^@]+:[^@]+@/g,/redis:\/\/[^:]+:[^@]+@/g,/rediss:\/\/[^:]+:[^@]+@/g];function S(e){let o=e.length;return o<=4?"****":o<=8?`${e[0]}****${e[o-1]}`:o<=16?`${e.slice(0,2)}****${e.slice(-2)}`:`${e.slice(0,4)}...${e.slice(-4)}`}function h(e,o={}){let{sensitivePatterns:i=P,customPatterns:a=[],fallbackValue:u="[REDACTED]"}=o,c=[...x,...a];function p(t){return i.some(n=>n.test(t))}function f(t){let n=t;for(let[,r]of e)if(typeof r=="string"&&r.length>0){let l=r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");n=n.replace(new RegExp(l,"g"),u);}for(let r of c)n=n.replace(r,u);return n}function g(t,n=0,r=new WeakSet){if(n>10||t==null)return t;if(typeof t=="string")return f(t);if(typeof t!="object")return t;if(r.has(t))return "[Circular]";if(r.add(t),Array.isArray(t))return t.map(s=>g(s,n+1,r));if(t instanceof Error){let s=new Error(f(t.message));return s.name=t.name,s.stack=t.stack?f(t.stack):void 0,s}if(t instanceof Date||t instanceof RegExp)return t;if(t instanceof Map)return new Map(Array.from(t.entries()).map(([s,d])=>[g(s,n+1,r),g(d,n+1,r)]));if(t instanceof Set)return new Set(Array.from(t.values()).map(s=>g(s,n+1,r)));let l={};for(let[s,d]of Object.entries(t))p(s)?l[s]=typeof d=="string"?u:"[REDACTED]":typeof d=="string"?l[s]=f(d):l[s]=g(d,n+1,r);return l}return {redactString:f,redactObject:g,maskValue:S,createFingerprint:t=>{let n=0;for(let r=0;r<t.length;r++){let l=t.charCodeAt(r);n=(n<<5)-n+l,n=n&n;}return `sha256:${Math.abs(n).toString(16).slice(0,8)}`},shouldRedactKey:p}}function y(e,o={}){let i=new Map,a=o.sensitiveKeys?.map(u=>new RegExp(u,"i"))??P;for(let[u,c]of Object.entries(e))typeof c=="string"&&a.some(p=>p.test(u))&&i.set(u,c);return i}var m="__nodeEnvResolverPatched";function _(e,o={}){let{enabled:i=true,methods:a=["log","debug","info","warn","error","trace"],redactStrings:u=true,redactObjects:c=true,...p}=o;if(!i)return ()=>{};let f=console;if(f[m])return ()=>{};let g=y(e),t=h(g,p),n={};for(let r of a)if(typeof console[r]=="function"){n[r]=console[r].bind(console);let l=n[r];console[r]=(...s)=>{let d=s.map(w=>typeof w=="string"&&u?t.redactString(w):typeof w=="object"&&c&&w!==null?t.redactObject(w):w);l(...d);};}return Object.defineProperty(f,m,{value:true,writable:true,enumerable:false,configurable:true}),()=>{for(let r of a)if(n[r]){let s=n[r].bind(console);console[r]=s;}try{delete f[m];}catch{}f[m]=false;}}function E(e,o={}){let i=y(e),a=h(i,o);return {redact:(...u)=>u.map(c=>typeof c=="string"?a.redactString(c):typeof c=="object"&&c!==null?a.redactObject(c):c),...a}}var O=["image/","video/","audio/","application/octet-stream","application/pdf"];function v(e,o){let i=e.toLowerCase();return !o.some(a=>i.includes(a.toLowerCase()))}function T(e,o,i){if(o===e)return e;if(i==="throw")throw new Error('Secret leak detected in HTTP response body. A sensitive value was found before it could be sent. Use mode: "redact" to automatically scrub, or mode: "warn" to log and continue.');return i==="warn"?(console.warn('[node-env-resolver] Potential secret leak detected in HTTP response. Set mode: "redact" to scrub automatically.'),e):o}function A(e,o={}){let{mode:i=process.env.NODE_ENV==="production"?"warn":"throw",ignoreContentTypes:a=O,maxBodySize:u=1024*1024,...c}=o,p=y(e),f=h(p,c);return function(t,n,r){let l=n.end.bind(n);n.end=function(...s){let d=s[0];if(d!=null&&(typeof d=="string"||Buffer.isBuffer(d))){let w=String(n.getHeader?.("content-type")??"");if(v(w,a)){let k=typeof d=="string"?d:d.toString("utf8");if(Buffer.byteLength(k)<=u)try{let R=f.redactString(k);s[0]=T(k,R,i);}catch(R){if(i==="throw")throw R;console.error("[node-env-resolver] Response scan error:",R);}}}return l(...s)},r();}}async function C(e,o,i={}){let{mode:a="warn",ignoreContentTypes:u=O,maxBodySize:c=1024*1024,...p}=i,f=e.headers.get("content-type")??"";if(!v(f,u))return e;let t=await e.clone().arrayBuffer();if(t.byteLength>c)return e;let n=new TextDecoder().decode(t),r=y(o),s=h(r,p).redactString(n);if(s===n)return e;if(a==="throw")throw new Error('Secret leak detected in HTTP response. Use mode: "redact" to scrub automatically.');return a==="warn"?(console.warn("[node-env-resolver] Potential secret leak detected in HTTP response."),e):new Response(s,{status:e.status,statusText:e.statusText,headers:e.headers})}function b(e,o,i={}){if(typeof e!="string"&&!Buffer.isBuffer(e))return {safe:true};let a=y(o),u=h(a,i),c=typeof e=="string"?e:e.toString("utf8"),p=u.redactString(c);return p!==c?{safe:false,redacted:p}:{safe:true}}function F(e,o={}){return o.console===false?()=>{}:_(e,o.console)}exports.createConsoleRedactor=E;exports.createRedactor=h;exports.createResponseMiddleware=A;exports.extractSensitiveValues=y;exports.patchGlobalConsole=_;exports.protect=F;exports.scanBodyForSecrets=b;exports.wrapFetchResponse=C;
@@ -0,0 +1,161 @@
1
+ /**
2
+ * Redaction utilities for protecting secrets in logs and responses
3
+ */
4
+ interface RedactorOptions {
5
+ sensitiveKeys?: string[];
6
+ sensitivePatterns?: RegExp[];
7
+ customPatterns?: RegExp[];
8
+ fallbackValue?: string;
9
+ }
10
+ declare function maskValue(value: string): string;
11
+ declare function createRedactor(sensitiveValues: Map<string, string>, options?: RedactorOptions): {
12
+ redactString: (str: string) => string;
13
+ redactObject: (obj: unknown, depth?: number, seen?: WeakSet<WeakKey>) => unknown;
14
+ maskValue: typeof maskValue;
15
+ createFingerprint: (value: string) => string;
16
+ shouldRedactKey: (key: string) => boolean;
17
+ };
18
+ declare function extractSensitiveValues(config: Record<string, unknown>, options?: {
19
+ sensitiveKeys?: string[];
20
+ }): Map<string, string>;
21
+
22
+ /**
23
+ * Patch global console methods to redact sensitive values
24
+ *
25
+ * Prevents accidental logging of secrets by intercepting console methods
26
+ * and redacting values matching sensitive patterns.
27
+ */
28
+
29
+ interface ConsolePatchOptions extends RedactorOptions {
30
+ enabled?: boolean;
31
+ methods?: ('log' | 'debug' | 'info' | 'warn' | 'error' | 'trace')[];
32
+ redactStrings?: boolean;
33
+ redactObjects?: boolean;
34
+ }
35
+ declare function patchGlobalConsole(config: Record<string, unknown>, options?: ConsolePatchOptions): () => void;
36
+ declare function createConsoleRedactor(config: Record<string, unknown>, options?: ConsolePatchOptions): {
37
+ redactString: (str: string) => string;
38
+ redactObject: (obj: unknown, depth?: number, seen?: WeakSet<WeakKey>) => unknown;
39
+ maskValue: (value: string) => string;
40
+ createFingerprint: (value: string) => string;
41
+ shouldRedactKey: (key: string) => boolean;
42
+ redact: (...args: unknown[]) => unknown[];
43
+ };
44
+
45
+ /**
46
+ * Response protection utilities for preventing secret leakage in HTTP responses
47
+ *
48
+ * Provides middleware for Node.js (Express/Connect/Hono) and a utility for
49
+ * Edge runtimes (Cloudflare Workers, Vercel Edge, etc.).
50
+ *
51
+ * @example Node.js / Express
52
+ * ```ts
53
+ * import express from 'express';
54
+ * import { createResponseMiddleware } from 'node-env-resolver/runtime';
55
+ *
56
+ * const app = express();
57
+ * app.use(createResponseMiddleware(config, { mode: 'throw' }));
58
+ * ```
59
+ *
60
+ * @example Edge runtime
61
+ * ```ts
62
+ * import { wrapFetchResponse } from 'node-env-resolver/runtime';
63
+ *
64
+ * export default {
65
+ * async fetch(req, env) {
66
+ * const response = await handler(req);
67
+ * return wrapFetchResponse(response, config, { mode: 'redact' });
68
+ * }
69
+ * }
70
+ * ```
71
+ */
72
+
73
+ interface ResponsePatchOptions extends RedactorOptions {
74
+ mode?: 'throw' | 'redact' | 'warn';
75
+ ignoreContentTypes?: string[];
76
+ maxBodySize?: number;
77
+ }
78
+ /**
79
+ * Express / Connect / Hono middleware that scans outgoing response bodies
80
+ * for sensitive values and redacts, warns, or throws depending on `mode`.
81
+ *
82
+ * Default mode: 'warn' in production, 'throw' in development.
83
+ */
84
+ declare function createResponseMiddleware(config: Record<string, unknown>, options?: ResponsePatchOptions): (_req: unknown, res: {
85
+ end: (...args: unknown[]) => unknown;
86
+ write?: (...args: unknown[]) => unknown;
87
+ getHeader?: (name: string) => string | number | string[] | undefined;
88
+ }, next: () => void) => void;
89
+ /**
90
+ * Scan and optionally redact an Edge runtime `Response` object.
91
+ * Returns a new Response (original is consumed). Safe to use in
92
+ * Cloudflare Workers, Vercel Edge Functions, and Deno Deploy.
93
+ */
94
+ declare function wrapFetchResponse(response: Response, config: Record<string, unknown>, options?: ResponsePatchOptions): Promise<Response>;
95
+ /**
96
+ * Utility to imperatively scan a response body for secrets.
97
+ * Useful when you need to check manually rather than via middleware.
98
+ */
99
+ declare function scanBodyForSecrets(body: string | Buffer | unknown, config: Record<string, unknown>, options?: ResponsePatchOptions): {
100
+ safe: boolean;
101
+ redacted?: string;
102
+ };
103
+
104
+ /**
105
+ * Runtime protection utilities for preventing secret leaks
106
+ *
107
+ * Quick start — protect everything with one call:
108
+ * ```typescript
109
+ * import { protect } from 'node-env-resolver/runtime';
110
+ *
111
+ * const unprotect = protect(config);
112
+ * // console methods now redact secrets automatically
113
+ *
114
+ * // Optional: add response scanning in your server/edge handler
115
+ * app.use(createResponseMiddleware(config)); // Express / Hono
116
+ * return wrapFetchResponse(response, config); // Edge runtime
117
+ * ```
118
+ *
119
+ * Or compose individual primitives for fine-grained control:
120
+ * ```typescript
121
+ * import {
122
+ * patchGlobalConsole,
123
+ * createResponseMiddleware,
124
+ * wrapFetchResponse,
125
+ * } from 'node-env-resolver/runtime';
126
+ *
127
+ * const unpatch = patchGlobalConsole(config, { methods: ['error', 'warn'] });
128
+ * app.use(createResponseMiddleware(config, { mode: 'redact' }));
129
+ * ```
130
+ */
131
+
132
+ interface ProtectOptions {
133
+ /** Options forwarded to patchGlobalConsole. Pass false to disable console patching. */
134
+ console?: ConsolePatchOptions | false;
135
+ /** Options forwarded to createResponseMiddleware. Response protection must still be
136
+ * wired up separately — this just pre-configures the options. */
137
+ responses?: ResponsePatchOptions;
138
+ }
139
+ /**
140
+ * Enable runtime secret protection in one call.
141
+ *
142
+ * Patches global console methods to redact sensitive values.
143
+ * Returns an `unpatch` function that restores the originals.
144
+ *
145
+ * Response protection is intentionally explicit — use `createResponseMiddleware`
146
+ * or `wrapFetchResponse` to add it to your server/edge handler.
147
+ *
148
+ * @example
149
+ * ```ts
150
+ * import { protect } from 'node-env-resolver/runtime';
151
+ *
152
+ * const unprotect = protect(config);
153
+ * // console.log('key:', config.API_KEY) → console.log('key:', '[REDACTED]')
154
+ *
155
+ * // Restore originals when done (e.g. in tests)
156
+ * unprotect();
157
+ * ```
158
+ */
159
+ declare function protect(config: Record<string, unknown>, options?: ProtectOptions): () => void;
160
+
161
+ export { type ConsolePatchOptions, type ProtectOptions, type RedactorOptions, type ResponsePatchOptions, createConsoleRedactor, createRedactor, createResponseMiddleware, extractSensitiveValues, patchGlobalConsole, protect, scanBodyForSecrets, wrapFetchResponse };