npm.io
3.3.1 • Published 1 week ago

@dotenvx/primitives

Licence
BSD-3-Clause
Version
3.3.1
Deps
0
Size
190 kB
Vulns
0
Weekly
0
Stars
5.8K

@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/primitives

Create a .env file:

HELLO=World

Encrypt it:

$ dotenvx encrypt

Read 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=World

API

Node.js Purpose
check Check a compiled Envfile 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
policy Compile Envfile text or a Buffer into a resolved policy object
profile Select a comma-separated file list from Envfile 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
upsert Insert or replace dotenv assignments
check(policy, values)

Validates final string values and returns { checked, errors }. Returned values are redacted unless explicitly public; inputs are unchanged. Errors include the key, code, rule, message, and strict flag.

check(policy('env "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)
// World

Errors 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)
// true
encrypt

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:'))
// true

Encryption 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'))
// false
evaluate

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=World

Pass 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@localhost

Supported 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 .env

Files 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)
// true

The 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)
// true

By 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)
// true

Also 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'))
// false
parse

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)
// World

Also 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).

policy(source, file = '.env')

The caller reads files and loads environment values; policy compilation works in memory.

Compiles Envfile text or a Buffer into { keys: { ... } }, with env, fs, and stdio rules per key. For comma-separated files, the first file wins explicit rules.

const rules = policy('env "TOKEN"', '.env')
// { keys: { TOKEN: { env: { type: 'string', required: true, strict: false },
//                   fs: { encrypted: true }, stdio: { redacted: true } } } }
profile(source, options = {})

Resolves Envfile profiles to comma-separated filenames. Accepts f, profile, processEnv, and environmentKeys options. 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')
// true
scan

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.parsed.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.parsed.HELLO)
// ['WORLD']

With options, pass the transform as the third argument: scan(source, options, transform).

sealed

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. 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'))
// false
upsert

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=dos

A 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, profile, check, and redact with the same Envfile 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 publish

Third 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 pornin@bolet.org

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.

Keywords