Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,9 @@ Each validation function accepts an (optional) object with the following attribu
- `example` - An example value for the env var.
- `docs` - A URL that leads to more detailed documentation about the env var.
- `requiredWhen` - A function (env -> boolean) specifying when this env var is required. Use With default: undefined (optional value).
- `mask` - Redacts this env var's value wherever the library prints it (validation error
messages, including `example`), so secrets don't leak into logs. Accepts `'all'`,
`'last4'`, or a custom `(value) => string` renderer. Without it, behavior is unchanged.

## Custom validators

Expand All @@ -137,6 +140,10 @@ const env = cleanEnv(process.env, {
})
```

If a custom validator is used for a secret, pass `mask` to its spec. Any quoted occurrence
of the value in the thrown error is redacted automatically, e.g. a validator that throws
`` `Bad token: "${x}"` `` will log `Bad token: "****wxyz"`.

### TypeScript users

You can use either one of `makeValidator`, `makeExactValidator` and `makeStructuredValidator`
Expand Down
10 changes: 7 additions & 3 deletions src/core.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { EnvError, EnvMissingError } from './errors.ts'
import { applyMask } from './mask.ts'
import { defaultReporter } from './reporter.ts'
import type { CleanOptions, Spec, SpecsOutput, ValidatorSpec } from './types.ts'

Expand Down Expand Up @@ -26,7 +27,8 @@ function validateVar<T>({
if (!Array.isArray(spec.choices)) {
throw new TypeError(`"choices" must be an array (in spec for "${name}")`)
} else if (!spec.choices.includes(value)) {
throw new EnvError(`Value "${value}" not in choices [${spec.choices}]`)
const shown = spec.mask ? applyMask(value, spec.mask) : value
throw new EnvError(`Value "${shown}" not in choices [${spec.choices}]`)
}
}
if (value == null) throw new EnvError(`Invalid value for env var "${name}"`)
Expand All @@ -35,9 +37,11 @@ function validateVar<T>({

// Format a string error message for when a required env var is missing
export function formatSpecDescription<T>(spec: Spec<T>) {
const egText = spec.example ? ` (eg. "${spec.example}")` : ''
const example = spec.example
? ` (eg. "${spec.mask ? applyMask(spec.example, spec.mask) : spec.example}")`
: ''
const docsText = spec.docs ? `. See ${spec.docs}` : ''
return `${spec.desc}${egText}${docsText}`
return `${spec.desc}${example}${docsText}`
}

const readRawEnvValue = <T>(
Expand Down
24 changes: 21 additions & 3 deletions src/makers.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,25 @@
import type { Spec, BaseValidator, StructuredValidator, ExactValidator } from './types.ts'
import type { Mask, Spec, BaseValidator, StructuredValidator, ExactValidator } from './types.ts'
import { redactError } from './mask.ts'

const internalMakeValidator = <T>(parseFn: (input: string) => T) => {
return (spec?: Spec<unknown>) => ({ ...spec, _parse: parseFn })
// Validators receive the spec's `mask` so they can render values safely. Custom
// parse functions written against the old 1-arg signature still work (they just
// ignore the extra arg), and the maker redacts any quoted raw value as a fallback.
type ParseFn<T> = (input: string, mask?: Mask) => T

const internalMakeValidator = <T>(parseFn: ParseFn<T>) => {
return (spec?: Spec<unknown>) => {
const { mask } = spec ?? {}
return {
...spec,
_parse: (input: string) => {
try {
return parseFn(input, mask)
} catch (err) {
throw mask ? redactError(err, input, mask) : err
}
},
}
}
}

/**
Expand Down
50 changes: 50 additions & 0 deletions src/mask.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import type { Mask } from './types.ts'

// ponytail: presets cover the common cases; a custom fn signature is the escape hatch.
// Unknown/misspelled presets fail safe (full redaction) rather than leaking.
const presets: Record<string, (value: unknown) => string> = {
all: () => '****',
last4: (value: unknown) => {
const s = String(value)
return s.length <= 4 ? '****' : `****${s.slice(-4)}`
},
}

/** Render a value the way it's allowed to appear in logs. */
export const applyMask = (value: unknown, mask: Mask): string => {
if (typeof mask === 'function') return mask(value)
return (presets[mask] ?? presets.all)(value)
}

/**
* Render `: "<value>"` for a validator error message. Without a mask the raw value is
* shown (backward compatible); with a mask, the masked form is shown instead.
*/
export const displayValue = (value: unknown, mask?: Mask): string =>
`: "${mask ? applyMask(value, mask) : String(value)}"`

/**
* Render `: "<masked>"` only when a mask is set, otherwise nothing. Used by validators
* whose messages must never contain the raw value (url, json).
*/
export const displayMasked = (value: unknown, mask?: Mask): string =>
mask ? `: "${applyMask(value, mask)}"` : ''

/**
* Best-effort redaction for validators that render their own message and don't use
* `displayValue`. Only replaces a *quoted* occurrence of the raw value, so short values
* can't corrupt surrounding text (e.g. an input of "a" must not eat the "a" in "Invalid").
*/
export const redactError = (err: unknown, input: unknown, mask: Mask): unknown => {
const raw = String(input)
if (!raw) return err
const from = `"${raw}"`
const to = `"${applyMask(input, mask)}"`
if (err instanceof Error) {
err.message = err.message.split(from).join(to)
return err
}
if (typeof err === 'string') return err.split(from).join(to)
return err
}

22 changes: 22 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
/**
* How a value is allowed to appear when its env var's value is included in validation
* error output. Either a preset or a function that renders the replacement string.
*/
export type Mask = 'all' | 'last4' | ((value: unknown) => string)

export interface Spec<T> {
/**
* An Array that lists the admissable parsed values for the env var.
Expand Down Expand Up @@ -34,6 +40,22 @@ export interface Spec<T> {
* conditions are met with the rest of the env object. Use With default: undefined.
*/
requiredWhen?: (cleanedEnv: Record<string, unknown>) => boolean | undefined

/**
* If set, any occurrence of this env var's value in a validation error message is
* replaced with a masked form, so secrets don't leak into logs. Pass a preset
* ('all' | 'last4') or a custom `(value) => string` renderer. Also masks `example`.
*
* ```ts
* cleanEnv(process.env, { API_KEY: str({ mask: 'last4' }) })
* // error shows: Not a string: "****wxyz"
* ```
*
* Note: this only redacts values the library itself prints (error messages). It
* cannot prevent a consumer from logging the resolved value, since primitives
* can't be intercepted.
*/
mask?: Mask
}

// All the default-providing attributes, each independently optional and allowed
Expand Down
39 changes: 21 additions & 18 deletions src/validators.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { EnvError } from './errors.ts'
import { displayMasked, displayValue } from './mask.ts'
import { makeExactValidator, makeStructuredValidator, makeValidator } from './makers.ts'
import type { Mask } from './types.ts'

// Simplified adaptation of https://github.com/validatorjs/validator.js/blob/master/src/lib/isFQDN.js
const isFQDN = (input: string) => {
Expand Down Expand Up @@ -30,7 +32,7 @@ const EMAIL_REGEX = /^[^@\s]+@[^@\s]+\.[^@\s]+$/ // intentionally non-exhaustive

// We use exact validator here because narrowing down to either 'true' or 'false'
// makes no sense.
export const bool = makeExactValidator<boolean>((input: string | boolean) => {
export const bool = makeExactValidator<boolean>((input: string | boolean, mask?: Mask) => {
switch (input) {
case true:
case 'true':
Expand All @@ -47,34 +49,34 @@ export const bool = makeExactValidator<boolean>((input: string | boolean) => {
case '0':
return false
default:
throw new EnvError(`Invalid bool input: "${input}"`)
throw new EnvError(`Invalid bool input${displayValue(input, mask)}`)
}
})

export const num = makeValidator<number>((input: string) => {
export const num = makeValidator<number>((input: string, mask?: Mask) => {
const coerced = parseFloat(input)
if (Number.isNaN(coerced)) throw new EnvError(`Invalid number input: "${input}"`)
if (Number.isNaN(coerced)) throw new EnvError(`Invalid number input${displayValue(input, mask)}`)
return coerced
})

export const str = makeValidator<string>((input: string) => {
export const str = makeValidator<string>((input: string, mask?: Mask) => {
if (typeof input === 'string') return input
throw new EnvError(`Not a string: "${input}"`)
throw new EnvError(`Not a string${displayValue(input, mask)}`)
})

export const email = makeValidator<string>((x: string) => {
export const email = makeValidator<string>((x: string, mask?: Mask) => {
if (EMAIL_REGEX.test(x)) return x
throw new EnvError(`Invalid email address: "${x}"`)
throw new EnvError(`Invalid email address${displayValue(x, mask)}`)
})

export const host = makeValidator<string>((input: string) => {
export const host = makeValidator<string>((input: string, mask?: Mask) => {
if (!isFQDN(input) && !isIP(input)) {
throw new EnvError(`Invalid host (domain or ip): "${input}"`)
throw new EnvError(`Invalid host (domain or ip)${displayValue(input, mask)}`)
}
return input
})

export const port = makeValidator<number>((input: string) => {
export const port = makeValidator<number>((input: string, mask?: Mask) => {
const coerced = +input
if (
Number.isNaN(coerced) ||
Expand All @@ -83,18 +85,18 @@ export const port = makeValidator<number>((input: string) => {
coerced < 1 ||
coerced > 65535
) {
throw new EnvError(`Invalid port input: "${input}"`)
throw new EnvError(`Invalid port input${displayValue(input, mask)}`)
}
return coerced
})

export const url = makeValidator<string>((x: string) => {
export const url = makeValidator<string>((x: string, mask?: Mask) => {
try {
new URL(x)
return x
} catch {
// Not logging the url value as it could contain sensitive data
throw new EnvError(`Invalid url`)
// Not logging the url value unless a mask was provided
throw new EnvError(`Invalid url${displayMasked(x, mask)}`)
}
})

Expand All @@ -109,10 +111,11 @@ export const url = makeValidator<string>((x: string) => {
* })
* ```
*/
export const json = makeStructuredValidator((x: string) => {
export const json = makeStructuredValidator((x: string, mask?: Mask) => {
try {
return JSON.parse(x)
} catch (e) {
throw new EnvError(`Invalid json: "${x}"`)
} catch {
// Not logging the json value unless a mask was provided
throw new EnvError(`Invalid json${displayMasked(x, mask)}`)
}
})
Loading