@dotenvx/primitives
v4.4.0
Published
a secure dotenv–from the creator of `dotenv`
Readme
@dotenvx/primitives
Official Node.js implementation of dotenvx primitives.
It provides dotenv parsing, expansion, command evaluation, secp256k1 ECIES encryption and decryption, keyrings, scanning, matching, sealed detection, and dotenv source updates.
Installation
npm install @dotenvx/primitivesCreate a .env file:
HELLO=WorldEncrypt it:
$ dotenvx encryptRead and parse it in index.cjs, then print each key and value:
// index.cjs
const fs = require('node:fs')
const { parseSync } = require('@dotenvx/primitives')
const path = '.env'
const src = fs.readFileSync(path, 'utf8')
const parsed = parseSync(src)
for (const [key, value] of Object.entries(parsed.parsed)) {
console.log(`${key}=${value}`)
}Then run it.
$ node index.cjs
HELLO=WorldAPI
One Dotenvxfile source produces two policies for different stages:
| Generate | Validate | Rules per key | Values supplied to the checker |
| --- | --- | --- | --- |
| policy | check | env and stdout | Final resolved environment strings |
| storagepolicy | storagecheck | storage only | Original stored strings, before decryption |
Both policy generators work in memory. The caller supplies the source text and values; these primitives do not read files or load the shell environment.
| Node.js | Purpose |
| --- | --- |
| check | Check a compiled Dotenvxfile policy against final environment values |
| decrypt | Decrypt an encrypted dotenvx value |
| derive | Derive a compressed public key from a private key |
| encrypt | Encrypt a value for a public key |
| encrypted | Detect the encrypted: prefix |
| evaluate | Evaluate $(command) substitutions |
| expand | Expand environment-variable expressions |
| keypair | Generate or restore a secp256k1 keypair |
| keyring | Build a public-to-private-key map |
| keyringSync | Build a keyring synchronously |
| match | Create a key-pattern matcher |
| parse | Parse, expand, decrypt, and classify dotenv strings |
| parseSync | Parse dotenv strings synchronously |
| parsearrays | Parse dotenv values while preserving duplicate assignments |
| parsearraysSync | Parse dotenv arrays synchronously |
| parsedotenvxfile | Return declared keys with empty string values from Dotenvxfile source |
| parsedotenvxfileSync | Synchronously return declared keys with empty string values |
| policy | Compile Dotenvxfile text or a Buffer into a resolved policy object |
| profile | Select a comma-separated file list from Dotenvxfile profiles and caller inputs |
| publickeys | Extract dotenv public-key metadata |
| redact | Replace secret strings with redacted markers |
| remove | Remove dotenv assignments by key |
| scan | Scan dotenv assignments, duplicates, and comments |
| sealed | Check whether values are encrypted, blank, or secret references |
| storagecheck | Validate original stored strings against a storage policy |
| storagepolicy | Compile storage rules from Dotenvxfile source for one file |
| upsert | Insert or replace dotenv assignments |
check(policy, env)
Validates the final environment object env and returns { checked, errors }. Returned values
follow their named redaction rules, falling back to keys["*"].stdout.redacted
for undeclared keys; inputs are unchanged. Supplied undeclared keys also use
the wildcard environment validation rules and diagnostic strictness. Missing
undeclared keys produce no diagnostics. Errors include the
key, code, rule, message, and strict flag.
check(policy('redacted true\nenv "TOKEN"'), { TOKEN: 'abc123' })
// { checked: { TOKEN: '[REDACTED]' }, errors: [] }decrypt
Decrypts an encrypted: value using a hex-encoded private key. Plain values
are returned unchanged.
const { decrypt, encrypt, keypair } = require('@dotenvx/primitives')
const { privateKey, publicKey } = keypair()
const encryptedValue = encrypt(publicKey, 'World')
const plaintext = decrypt(privateKey, encryptedValue)
console.log(plaintext)
// WorldErrors expose stable dotenvx codes:
const { decrypt } = require('@dotenvx/primitives')
try {
decrypt('', 'encrypted:abc123')
} catch (error) {
console.log(error.code)
// MISSING_PRIVATE_KEY
}Pass { prefix: false } as the third argument to decrypt base64 ciphertext
that does not include the encrypted: prefix.
derive
Derives the compressed secp256k1 public key for a private key.
const { derive, keypair } = require('@dotenvx/primitives')
const { privateKey, publicKey } = keypair()
console.log(derive(privateKey) === publicKey)
// trueencrypt
Encrypts a UTF-8 value using dotenvx-compatible ECIES and returns an
encrypted:-prefixed value.
const { encrypt, keypair } = require('@dotenvx/primitives')
const { publicKey } = keypair()
const encryptedValue = encrypt(publicKey, 'World')
console.log(encryptedValue.startsWith('encrypted:'))
// trueEncryption is randomized, so encrypting the same value twice produces different ciphertexts.
encrypted
Checks whether a value begins with the case-sensitive encrypted: prefix.
The prefix is also available as encrypted.PREFIX.
const { encrypted } = require('@dotenvx/primitives')
console.log(encrypted.PREFIX)
// encrypted:
console.log(encrypted('encrypted:abc123'))
// true
console.log(encrypted('World'))
// falseevaluate
Evaluates shell command substitutions and removes trailing newlines from command output. The example below uses a POSIX shell command.
const { evaluate } = require('@dotenvx/primitives')
const value = evaluate('HELLO=$(printf World)', {})
console.log(value)
// HELLO=WorldPass an options object, using {} for defaults:
| Option | Default | Purpose |
| --- | --- | --- |
| processEnv | process.env | Environment values supplied to the command |
| runningParsed | {} | Previously parsed values; override processEnv for the command |
Failed commands throw an error with code COMMAND_SUBSTITUTION_FAILED.
expand
Expands $NAME, ${NAME}, default-value expressions, and alternate-value
expressions.
const { expand } = require('@dotenvx/primitives')
const value = expand('postgres://${USER}:$PASS@localhost', {
processEnv: { USER: 'scott', PASS: 'secret' }
})
console.log(value)
// postgres://scott:secret@localhostSupported operators:
${NAME:-fallback}uses the fallback when missing or empty.${NAME-fallback}uses the fallback when missing.${NAME:+alternate}uses the alternate when present and non-empty.${NAME+alternate}uses the alternate when present.
Pass an options object, using {} for defaults:
| Option | Default | Purpose |
| --- | --- | --- |
| processEnv | process.env | Existing environment values |
| runningParsed | {} | Progressively parsed values |
| overload | false | Give runningParsed precedence over processEnv |
| literals | {} | Literal values whose expansion expressions should not be expanded again |
injectsummary
injectsummary(count, files = []) formats the shared injection
summary without logging, inspecting environment values, or adding ANSI colors.
Callers decide when and where to print it, and apply their own quiet settings.
const { injectsummary } = require('@dotenvx/primitives')
injectsummary(2, ['.env']) // ⟐ injected env (2) from .envFiles may also be public metadata objects with filepath, publicKeys, and
keySources (public key → provider identifier). This includes short codes and
unique custody labels, for example:
injectsummary(3, [{
filepath: '.env',
publicKeys: ['031f20abc'],
keySources: { '031f20abc': 'armor' }
}]) // ⟐ injected env (3) from .env (031 F20) via Armor ⛨injectsummary.sources(files) returns { files, suffix } for other command
summaries, so encryption and decryption use the same labels and short codes.
Only pass public metadata, never private keys or environment values.
keypair
Generates a new keypair or restores one from an existing private key.
const { keypair } = require('@dotenvx/primitives')
const generated = keypair()
const restored = keypair(generated.privateKey)
console.log(generated.publicKey === restored.publicKey)
// trueThe returned object contains privateKey and publicKey hex strings.
keyring
Builds an object whose keys are public keys and whose values are their matching private keys.
const { keyring, keypair } = require('@dotenvx/primitives')
const { privateKey, publicKey } = keypair()
const ring = await keyring({
processEnv: { DOTENV_PRIVATE_KEY: privateKey }
})
console.log(ring[publicKey] === privateKey)
// trueBy default, keyring() reads .env.keys from the current working directory
and keys from process.env. Missing or unreadable key files are silently
ignored. Set fk to override the paths, or to [] to disable file reads.
| Option | Default | Purpose |
| --- | --- | --- |
| processEnv | process.env | Environment containing DOTENV_PRIVATE_KEY* and DOTENV_PUBLIC_KEY* entries |
| ring | {} | Existing public-to-private-key object, populated in place |
| fk | '.env.keys' | Key-file path or array of paths |
| provider | None | Function called with a public key when its private key is missing; returns a keyring object or a promise for one |
Private-key assignments in key files may be repeated or comma-separated. Invalid private keys are ignored. Public keys without a matching private key remain in the ring with an empty value.
keyringSync
Builds a keyring synchronously with the same options. A supplied provider
must return an object synchronously.
const { keyringSync, keypair } = require('@dotenvx/primitives')
const { privateKey, publicKey } = keypair()
const ring = keyringSync({ processEnv: { DOTENV_PRIVATE_KEY: privateKey } })
console.log(ring[publicKey] === privateKey)
// trueAlso available as keyring.sync(options).
match
Creates a matcher supporting glob patterns, including * and ?, plus
ignored patterns. Uses picomatch patterns and options.
const { match } = require('@dotenvx/primitives')
const isAllowed = match(['DOTENV_*'], { ignore: ['DOTENV_PRIVATE_*'] })
console.log(isAllowed('DOTENV_PUBLIC_KEY'))
// true
console.log(isAllowed('DOTENV_PRIVATE_KEY'))
// falseparse
Parses dotenv source while applying expansion, overload precedence, selective decryption, and injected-versus-existing classification.
const { parse } = require('@dotenvx/primitives')
const result = await parse('A=file\nB=$A\nHELLO=World', { processEnv: {} })
console.log(result.parsed.B)
// file
for (const [key, value] of Object.entries(result.parsed)) {
console.log(`${key}=${value}`)
}parse() automatically calls keyring(), reading .env.keys from the current
working directory by default. Missing or unreadable key files are silently
ignored. Override fk to use other paths, or supply [] to disable file reads.
The caller still supplies the dotenv source string; parse() does not read
.env or write the returned values into process.env.
| Option | Default | Purpose |
| --- | --- | --- |
| processEnv | process.env | Existing environment values for precedence, expansion, and key discovery |
| overload | false | Let source values override existing environment values |
| ik | All keys | Key pattern or array of patterns to decrypt |
| ek | No exclusions | Key pattern or array of patterns to exclude from decryption |
| fk | '.env.keys' | Key-file path or array of paths |
| provider | None | Resolve missing private keys; same callback as keyring() |
Exclusion patterns win over inclusion patterns. These patterns control decryption; excluded keys remain in the parsed output.
The result contains:
| Field | Contents |
| --- | --- |
| parsed | All parsed key/value pairs |
| injected | Values classified for injection, including decrypted pre-existing ciphertext |
| existed | Values preserved from the supplied environment |
| errors | Parsing/decryption error objects with code and message |
Values in all three objects are strings. Repeated keys keep their last
processed value. Check errors for unresolved encrypted values. Exceptions
from a key provider can reject the promise.
parseSync
Parses dotenv source synchronously with the same options and result shape.
A supplied provider must be synchronous.
const { parseSync } = require('@dotenvx/primitives')
const result = parseSync('HELLO=World', { processEnv: {} })
console.log(result.parsed.HELLO)
// WorldAlso available as parse.sync(source, options).
parsearrays
Use parsearrays(source, options) to preserve duplicate assignments as arrays.
It accepts the same options as parse(). All three objects (parsed,
injected, and existed) contain arrays, even for keys with a single assignment.
parse() keeps the last value instead.
const { parsearrays } = require('@dotenvx/primitives')
const result = await parsearrays('HELLO=World\nHELLO=Node', { processEnv: {} })
console.log(result.parsed.HELLO)
// ['World', 'Node']Both functions automatically build a keyring and share expansion, decryption, and precedence behavior. Exclusion patterns win over inclusion patterns.
Migration: replace parse(source, { array: true }) with parsearrays(source).
Remove array from the options; it no longer changes the output type.
parsearraysSync
Parses arrays synchronously with the same options and result shape as
parsearrays(). A supplied provider must be synchronous.
const { parsearraysSync } = require('@dotenvx/primitives')
const result = parsearraysSync('HELLO=World\nHELLO=Node', { processEnv: {} })
console.log(result.parsed.HELLO)
// ['World', 'Node']Also available as parsearrays.sync(source, options).
parsedotenvxfile(source, file = '.env')
Also available synchronously as parsedotenvxfile.sync(source, file) or
parsedotenvxfileSync(source, file).
Returns declared keys with empty string values for the selected files.
await parsedotenvxfile('env "PORT"\nenv "TOKEN"')
// { PORT: '', TOKEN: '' }policy(source, file = '.env')
Compiles Dotenvxfile text or a Buffer into { keys: { ... } }. Each key has
env validation rules and stdout redaction rules. Storage settings are omitted.
For comma-separated filenames, the first file wins explicit rules. Compilation
works in memory; the caller reads files and loads environment values.
const rules = policy('env "TOKEN", required: true, redacted: true')
// rules.keys.TOKEN:
// { env: { type: 'string', required: true, strict: false },
// stdout: { redacted: true } }The reserved keys["*"] entry contains defaults for undeclared keys.
The same source can generate both policies:
const source = 'storage "encrypted"\nenv "TOKEN", required: true, redacted: true'
const envRules = policy(source, '.env.production')
const storageRules = storagepolicy(source, '.env.production')
check(envRules, { TOKEN: 'resolved-secret' })
// { checked: { TOKEN: '[REDACTED]' }, errors: [] }
storagecheck(storageRules, { TOKEN: ['encrypted:example'] })
// { checked: { TOKEN: ['encrypted:example'] }, errors: [] }storagepolicy(source, file = '.env')
Compiles the same source for exactly one filename. Each key contains only
storage rules: type (any, encrypted, or plaintext), required, and
strict. Type defaults to any. Required and strict follow the same
resolution as policy: per-key override, selected file setting, root setting,
then false.
There are no stdout/redaction settings in this policy.
const rules = storagepolicy('storage "encrypted"\nenv "PORT", storage: "plaintext"', '.env.production')
storagecheck(rules, { PORT: ['3000'], TOKEN: ['encrypted:example'] })Pass original stored strings to storagecheck, before decryption. Encryption checks
recognize the encrypted: prefix; they do not authenticate ciphertext.
storagecheck(policy, scanned)
Checks original stored strings against storagepolicy rules and returns
checked and errors. No stdout redaction is applied. Use check with
policy for resolved environment validation and redaction.
profile(source, options = {})
Resolves Dotenvxfile profiles to comma-separated filenames. Accepts f, profile,
processEnv, and environmentKeys options. processEnv defaults to process.env;
pass {} to ignore the process environment. Explicit files win over profile names;
without a selection, uses the development profile or .env.
profile('profile "production", files: [".env.production"]', { profile: 'production' })
// '.env.production'publickeys
Extracts the final value of every DOTENV_PUBLIC_KEY* assignment while
preserving key order.
const { publickeys } = require('@dotenvx/primitives')
const keys = publickeys('DOTENV_PUBLIC_KEY=public-a\nDOTENV_PUBLIC_KEY_PRODUCTION=public-b')
console.log(keys)
// ['public-a', 'public-b']redact(text, secrets)
Replaces literal secret strings with [REDACTED], including overlapping matches.
redact('token=abc123', ['abc123']) // 'token=[REDACTED]'remove
Removes every assignment for the given key. It preserves surrounding lines, comments, multiline values for other keys, and CRLF line endings. If the key is missing, the source is returned unchanged.
const { remove } = require('@dotenvx/primitives')
const updated = remove('HELLO=one\nFOO=bar\nHELLO=two\n', 'HELLO')
console.log(updated === 'FOO=bar\n')
// truescan
Scans dotenv assignments without applying expansion or decryption. Duplicate values and their comments are preserved in source order.
const { scan } = require('@dotenvx/primitives')
const result = scan('HELLO=first\nHELLO=second # optional')
console.log(result.scanned.HELLO)
// ['first', 'second']
console.log(result.comments.HELLO)
// [undefined, 'optional']| Option | Default | Purpose |
| --- | --- | --- |
| ik | All keys | Key pattern or array of patterns to include |
| ek | No exclusions | Key pattern or array of patterns to exclude |
| expandDoubleQuotedNewlines | true | Decode escaped newlines, carriage returns, and tabs in double-quoted values |
| convertWindowsNewlines | true | Normalize CRLF and CR line endings to LF |
An optional transform receives { name, value, quote, comment } for each
assignment. Its returned value is stored in the corresponding array:
const { scan } = require('@dotenvx/primitives')
const result = scan('HELLO=World', ({ value }) => value.toUpperCase())
console.log(result.scanned.HELLO)
// ['WORLD']With options, pass the transform as the third argument:
scan(source, options, transform).
sealed(src, storagePolicy?)
Returns true when every non-metadata value is encrypted, empty or whitespace-only,
or begins with op:// (1Password) or bw:// (Bitwarden Password Manager).
DOTENV_PUBLIC_KEY* and *_PLAIN values are allowed to remain plaintext.
Empty source is considered sealed. Every duplicate assignment is checked.
An optional resolved storagepolicy() allows plaintext keys. Explicit encrypted
rules override the _PLAIN suffix; any uses the suffix convention. Existing
ciphertext remains accepted even when the policy permits plaintext.
Secret references are recognized by their case-sensitive prefix; they are not
resolved or validated against the provider. Other URLs, variable references, and
command substitutions are not exempt.
const { sealed } = require('@dotenvx/primitives')
console.log(sealed('HELLO=encrypted:abc123'))
// true
console.log(sealed('HELLO=World'))
// falseupsert
Inserts a missing assignment or replaces all occurrences of an existing key. It preserves existing quote style, export prefixes, multiline values, and CRLF line endings.
const { upsert } = require('@dotenvx/primitives')
const updated = upsert('HELLO=one\nHELLO=two', 'HELLO', ['uno', 'dos'])
console.log(updated)
// HELLO=uno
// HELLO=dosA string replacement applies to every occurrence. For per-occurrence changes, supply an array with one replacement for each existing assignment. For a new key, supply a string; the inserted assignment is double-quoted.
Compatibility
The implementation is tested against private Node.js conformance tests.
The Rust implementation provides the corresponding primitives
with Rust-native types and naming, including policy, storagepolicy, profile, check, and
redact with the same Dotenvxfile defaults and precedence rules.
Publishing
Publishing is performed manually from this directory. Keep the npm and Rust versions matched, following DEVELOPMENT.md, then run:
npm run standard
npm run build
npm pack --dry-run
npm publishThird Party Notices
This package bundles portions of the following MIT-licensed packages:
eciesjs@ecies/ciphers@noble/curves@noble/hashes@noble/ciphers
eciesjs
MIT License
Copyright (c) 2019-2026 Weiliang Li
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@ecies/ciphers
MIT License
Copyright (c) 2019-2026 Weiliang Li
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@noble/curves and @noble/hashes
The MIT License (MIT)
Copyright (c) 2022 Paul Miller (https://paulmillr.com)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@noble/ciphers
The MIT License (MIT)
Copyright (c) 2022 Paul Miller (https://paulmillr.com) Copyright (c) 2016 Thomas Pornin [email protected]
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
