# @dotenvx/primitives

Official Node.js implementation of [dotenvx primitives](https://github.com/dotenvx/primitives).

It provides dotenv parsing, expansion, command evaluation, secp256k1 ECIES
encryption and decryption, keyrings, scanning, matching, sealed detection, and
dotenv source updates.

## Installation

```sh
npm install @dotenvx/primitives
```

Create a `.env` file:

```dotenv
HELLO=World
```

Encrypt it:

```sh
$ dotenvx encrypt
```

Read and parse it in `index.cjs`, then print each key and value:

```js
// 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.

```sh
$ node index.cjs
HELLO=World
```

## API

| Node.js | Purpose |
| --- | --- |
| `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 |
| `publickeys` | Extract dotenv public-key metadata |
| `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 |

### `decrypt`

Decrypts an `encrypted:` value using a hex-encoded private key. Plain values
are returned unchanged.

```js
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:

```js
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.

```js
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.

```js
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`.

```js
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.

```js
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.

```js
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 |

### `keypair`

Generates a new keypair or restores one from an existing private key.

```js
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.

```js
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.

```js
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.

```js
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.

```js
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.

```js
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.

```js
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.

```js
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)`.

### `publickeys`

Extracts the final value of every `DOTENV_PUBLIC_KEY*` assignment while
preserving key order.

```js
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']
```

### `scan`

Scans dotenv assignments without applying expansion or decryption. Duplicate
values and their comments are preserved in source order.

```js
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:

```js
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.

```js
const { sealed } = require('@dotenvx/primitives')

console.log(sealed('HELLO=encrypted:abc123'))
// true
console.log(sealed('HELLO=World'))
// false
```

### `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.

```js
const { remove } = require('@dotenvx/primitives')

const updated = remove('HELLO=one\nFOO=bar\nHELLO=two\n', 'HELLO')
console.log(updated === 'FOO=bar\n')
// true
```

### `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.

```js
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](rust/README.md) provides the corresponding primitives
with Rust-native types and naming.

## Publishing

Publishing is performed manually from this directory. Keep the npm and Rust
versions matched, following [DEVELOPMENT.md](DEVELOPMENT.md), then run:

```sh
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.
