/** * Bun plugin for .env file loading with encryption support * Automatically loads and decrypts .env files at runtime */ import type { BunPlugin } from 'bun' import { existsSync } from 'node:fs' import { readFileSync } from 'node:fs' import { resolve } from 'node:path' import { decryptValue, getPrivateKey } from './crypto' import { parse } from './parser' import { isEncryptedValue } from './encrypted-value' import { plaintextEnv } from './plaintext-env' import { applyWithheldEnv, withheldEnvKeys } from './withheld' export interface EnvPluginOptions { /** * Path(s) to .env file(s) to load * @default ['.env'] */ path?: string | string[] /** * Whether to override existing environment variables * @default false */ overload?: boolean /** * Environment to load (e.g., 'production', 'ci') * Will look for .env.{env} file and DOTENV_PRIVATE_KEY_{ENV} variable */ env?: string /** * Custom private key for decryption */ privateKey?: string /** * Path to .env.keys file */ keysFile?: string /** * Whether to suppress output * @default false */ quiet?: boolean /** * Root directory to resolve paths from * @default process.cwd() */ cwd?: string } function normalizeEnvName(value: string | undefined): string | undefined { if (!value || isEncryptedValue(value)) return undefined const normalized = value.trim().toLowerCase() if (!/^[a-z0-9_-]+$/.test(normalized)) return undefined if (normalized === 'prod') return 'production' if (normalized === 'stage') return 'staging' if (normalized === 'dev') return 'development' return normalized } // --- Lazy decryption for the env proxy ------------------------------------- // The eager path (`autoLoadEnv`) bulk-decrypts every value into process.env at // boot, but it only runs from the preloader. Fast CLI commands skip the // preloader, and config/app code can read env before it runs — so the env // proxy needs to decrypt on read too. These helpers resolve the private key // once (process.env first, then `.env.keys`) and cache the result (including // "no key") per environment and project root, so repeated reads use the cache // rather than touching disk. let cachedKeyEnv: string | null = null let cachedKeyCwd: string | null = null let cachedPrivateKey: string | undefined /** * The environment whose file was actually loaded. * * Key resolution and file loading used to read the same three variables in * different orders: `autoLoadEnv` asked NODE_ENV first, `resolvePrivateKey` * asked APP_ENV first. An app whose `.env` says `APP_ENV=development` and * whose server runs with `NODE_ENV=production` therefore loaded * `.env.production` and then looked for the *development* private key - so * every encrypted value in the file it had just read came back undecryptable * and silently fell back to its default. Recording what was loaded keeps the * two answers the same. */ let loadedEnvName: string | undefined function keyFromKeysFile(envName: string | undefined, cwd: string, keysFile = '.env.keys'): string | undefined { const keysPath = resolve(cwd, keysFile) if (!existsSync(keysPath)) return undefined try { const { parsed } = parse(readFileSync(keysPath, 'utf-8')) if (envName) { const specific = parsed[`DOTENV_PRIVATE_KEY_${envName.toUpperCase()}`] if (specific) return specific } return parsed.DOTENV_PRIVATE_KEY } catch { return undefined } } /** * The environment the env layer is operating as. * * Exposed so a failure can say which key it went looking for. */ export function activeEnvName(options: { env?: string } = {}): string { return normalizeEnvName(options.env) || loadedEnvName || normalizeEnvName(process.env.NODE_ENV) || normalizeEnvName(process.env.DOTENV_ENV) || normalizeEnvName(process.env.APP_ENV) || 'development' } /** * Resolve the dotenvx private key for the active environment, checking * process.env (`DOTENV_PRIVATE_KEY_` then `DOTENV_PRIVATE_KEY`) and * finally a local `.env.keys` file. The result — key or `undefined` — is * cached per environment and resolved project root so the env proxy can read * encrypted values without repeatedly touching disk. */ export function resolvePrivateKey(options: { env?: string, cwd?: string } = {}): string | undefined { const envName = activeEnvName(options) const cwd = resolve(options.cwd || process.cwd()) if (cachedKeyEnv === envName && cachedKeyCwd === cwd) return cachedPrivateKey let key = getPrivateKey(envName) if (!key) key = process.env.DOTENV_PRIVATE_KEY if (!key) key = keyFromKeysFile(envName, cwd) cachedKeyEnv = envName cachedKeyCwd = cwd cachedPrivateKey = key return key } /** * Clear the cached private key AND the recorded environment. Needed after key * rotation and between tests that swap `DOTENV_PRIVATE_KEY*` or `APP_ENV`. * * `loadedEnvName` has to go with it. It deliberately outranks `APP_ENV` in * {@link activeEnvName} — an env file that has been read owns the keys for * anything decrypted afterwards — so leaving it set means a later * `APP_ENV` swap is silently ignored, which is the one thing this function * exists to make possible. Whether it happened to be set at all depended on * which test file ran first in the process, so the env proxy's decryption * tests passed or failed on file ordering and CI went red on roughly half of * all runs (stacksjs/stacks#2259). * * Test-only: nothing outside `core/env/tests` calls this, so clearing the * recorded environment cannot affect a running app. */ export function resetPrivateKeyCache(): void { cachedKeyEnv = null cachedKeyCwd = null cachedPrivateKey = undefined loadedEnvName = undefined } /** * Decrypt a single `encrypted:` / `enc:` value on demand. Returns the * plaintext, or `undefined` when the value is unusable (no key available or * decryption failed) so callers can treat it exactly like an unset variable. * Non-encrypted input is returned unchanged. */ export function decryptEnvValue(value: string, options: { env?: string, cwd?: string } = {}): string | undefined { if (!isEncryptedValue(value)) return value const key = resolvePrivateKey(options) if (!key) return undefined try { const normalized = value.startsWith('enc:') ? `encrypted:${value.slice(4)}` : value return decryptValue(normalized, key) } catch { return undefined } } /** * Load .env files and inject into process.env */ export function loadEnv(options: EnvPluginOptions = {}): { loaded: number, errors: string[] } { const { path: envPaths = ['.env'], overload = false, env: envName, privateKey: customPrivateKey, keysFile = '.env.keys', quiet = false, cwd = process.cwd(), } = options const paths = Array.isArray(envPaths) ? envPaths : [envPaths] const errors: string[] = [] let loaded = 0 // Keys the parent process withheld are not this file's to supply (#3028). const withheld = withheldEnvKeys() // Snapshot genuine shell/CI overrides before loading any files. Values that // Bun preloaded as ciphertext are not usable overrides and may be replaced. // Values loaded from an earlier file in this call are also not external, so // a later, more-specific file can override them without `overload: true`. // // Bun also preloads `.env` in plaintext, and that is indistinguishable here // from a shell export, except by value: a variable already holding exactly // what a file in this call says came from that file (see the loop below). const externalOverrides = new Map( Object.entries(plaintextEnv(process.env)) .filter((entry): entry is [string, string] => entry[1] !== undefined), ) // Determine which private key to use let privateKey = customPrivateKey if (!privateKey && keysFile) { // Load private key from .env.keys file const keysPath = resolve(cwd, keysFile) if (existsSync(keysPath)) { try { const keysContent = readFileSync(keysPath, 'utf-8') const { parsed } = parse(keysContent) if (envName) { const keyName = `DOTENV_PRIVATE_KEY_${envName.toUpperCase()}` privateKey = parsed[keyName] || parsed.DOTENV_PRIVATE_KEY } else { privateKey = parsed.DOTENV_PRIVATE_KEY } } catch (error) { errors.push(`Failed to load keys file: ${error instanceof Error ? error.message : 'Unknown error'}`) } } } // If still no private key, check environment variables if (!privateKey) { privateKey = getPrivateKey(envName || '') || getPrivateKey() } // Resolve and load each .env file for (const envPath of paths) { const fullPath = resolve(cwd, envPath) if (!existsSync(fullPath)) { if (!quiet) { errors.push(`File not found: ${fullPath}`) } continue } try { const content = readFileSync(fullPath, 'utf-8') const { parsed, errors: parseErrors, skippedEncrypted } = parse(content, { privateKey, processEnv: process.env as Record, }) errors.push(...parseErrors) // Encrypted entries with no usable key were skipped by the parser. // Scrub any ciphertext Bun preloaded natively for the same keys (Bun // auto-loads .env/.env. without knowing about encryption), // so config falls back to defaults instead of validating against // unusable ciphertext. Then warn — once per file per process, even in // quiet mode, because running on defaults in what the user believes // is a configured environment is a correctness issue, not noise. if (skippedEncrypted.length > 0) { // Remove dependent copies before forgetting their encrypted source, // or a later file can expand them after the source has been scrubbed. const usable = plaintextEnv(process.env, skippedEncrypted) for (const key of Object.keys(process.env)) { if (!Object.hasOwn(usable, key)) delete process.env[key] } const keyName = envName ? `DOTENV_PRIVATE_KEY_${envName.toUpperCase()}` : 'DOTENV_PRIVATE_KEY' const reason = privateKey ? 'decryption failed' : `${keyName} not set` const preview = skippedEncrypted.slice(0, 5).join(', ') const rest = skippedEncrypted.length > 5 ? `, … +${skippedEncrypted.length - 5} more` : '' console.warn(`[env] warning: skipped ${skippedEncrypted.length} encrypted value(s) in ${envPath} (${reason}; existing plaintext or defaults apply): ${preview}${rest}`) } // Inject parsed values into process.env let applied = 0 for (const [key, value] of Object.entries(parsed)) { // Skip DOTENV_PUBLIC_KEY if (key === 'DOTENV_PUBLIC_KEY' || withheld.has(key)) { continue } const existing = process.env[key] // Bun natively loads `.env` / `.env.` into process.env before // any preload script runs, and it knows nothing about dotenvx-style // encryption — so on an encrypted file it leaves raw `encrypted:...` // ciphertext in process.env before this plugin ever executes. The // `undefined` check below then treated that ciphertext as a // pre-existing value and skipped the decrypted one, so every secret // stayed encrypted process-wide with no error: config validation // reported `database.default: got "encrypted:..."`, DB_CONNECTION // never resolved to a real driver, and auth-table creation silently // wrote nowhere. Ciphertext is unusable to every consumer, so it // never wins; genuine external overrides (shell/CI) still do. const isStaleCiphertext = isEncryptedValue(existing) && value !== existing // Bun reads `.env` into process.env before this runs, so every key of // the base file looked like a shell override and `.env.production` // could not replace it: a blank `AWS_ENDPOINT=` in `.env` silently // beat the production endpoint. A variable holding exactly this // file's value was loaded from this file, so it stops being external // and a later, more-specific file wins. A shell export that differs // from the file still does. if (externalOverrides.get(key) === value) externalOverrides.delete(key) if (overload || !externalOverrides.has(key) || isStaleCiphertext) { process.env[key] = value loaded++ applied++ } } // Only log once per process to avoid duplicate messages. Report what // was actually applied, not the parsed count — the old message said // "loaded 64 variables" even when it had injected none of them, which // is precisely what hid the decryption failure above. if (!quiet && !process.env.__ENV_LOADED__) { // Environment diagnostics belong on stderr so commands with a // machine-readable stdout contract can be piped and parsed safely. console.error(`[env] loaded ${applied}/${Object.keys(parsed).length} variables from ${envPath}`) process.env.__ENV_LOADED__ = '1' } } catch (error) { errors.push(`Failed to load ${fullPath}: ${error instanceof Error ? error.message : 'Unknown error'}`) } } scrubForeignCiphertext(privateKey) // Bun's native load ran before this code and knows nothing of the list. applyWithheldEnv() return { loaded, errors } } const reportedForeignCiphertext = new Set() /** * Resolve or remove ciphertext that none of the loaded files accounted for. * * Bun loads `.env.` natively, and with NODE_ENV unset that is * `.env.development` - whatever APP_ENV says. So a production deploy started * its life holding the development file's ciphertext, and the loop above only * replaces keys the production file also defines. Everything else stayed * `encrypted:...` in process.env, where a direct reader took it as a real * value. The mail reconcile did exactly that: it set the development file's * MAIL_PASSWORD_ ciphertext as the live password on three * production mailboxes, and every mail client using the real one was locked out. * * The env proxy already treats such a value as unset when it cannot decrypt * it; this gives direct process.env readers the same answer. */ function scrubForeignCiphertext(privateKey: string | undefined): void { const undecryptable: string[] = [] for (const [key, value] of Object.entries(process.env)) { if (!isEncryptedValue(value)) continue let plaintext: string | undefined if (privateKey) { try { plaintext = decryptValue(value!.startsWith('enc:') ? `encrypted:${value!.slice(4)}` : value!, privateKey) } catch {} } if (plaintext === undefined) undecryptable.push(key) else process.env[key] = plaintext } if (!undecryptable.length) return // Also drop anything Bun interpolated from those values. const usable = plaintextEnv(process.env, undecryptable) for (const key of Object.keys(process.env)) { if (!Object.hasOwn(usable, key)) delete process.env[key] } const fresh = undecryptable.filter(key => !reportedForeignCiphertext.has(key)) if (!fresh.length) return for (const key of fresh) reportedForeignCiphertext.add(key) const preview = fresh.slice(0, 5).join(', ') const rest = fresh.length > 5 ? `, … +${fresh.length - 5} more` : '' console.warn(`[env] warning: unset ${fresh.length} encrypted value(s) no loaded env file could decrypt (Bun preloads .env. on its own): ${preview}${rest}`) } /** * Bun plugin for automatic .env loading */ export function envPlugin(options: EnvPluginOptions = {}): BunPlugin { return { name: 'env-plugin', setup(build) { // Load .env files when plugin is initialized loadEnv(options) }, } } /** * Auto-detect and load .env files based on environment */ export function autoLoadEnv(options: Omit = {}): { loaded: number, errors: string[] } { const env = normalizeEnvName(options.env) || normalizeEnvName(process.env.NODE_ENV) || normalizeEnvName(process.env.DOTENV_ENV) || normalizeEnvName(process.env.APP_ENV) || 'development' const cwd = options.cwd || process.cwd() // Anything decrypted later belongs to this environment's key, whatever the // process environment says afterwards. if (loadedEnvName !== env) { loadedEnvName = env cachedKeyEnv = null cachedKeyCwd = null cachedPrivateKey = undefined } return loadEnv({ ...options, path: environmentFiles(env, cwd), env, }) } /** * The env files {@link autoLoadEnv} reads for an environment, least specific * first: `.env`, `.env.local`, `.env.`, `.env..local`, each only if * it exists in `cwd`. * * A later file's value replaces an earlier one's (loadEnv preserves what was * set before the call, and lets later files in the list override earlier * ones), so the last file here that sets a key, and that this process can * read, is where the app's value for it comes from. * * Exported so a tool that edits env files edits the ones the app loads. The * dashboard's Mail settings page edited `.env` alone, and a key set again in * `.env.` kept that file's value however often it was saved * (stacksjs/stacks#3340). */ export function environmentFiles(env: string, cwd: string = process.cwd()): string[] { const files: string[] = [] for (const file of ['.env', '.env.local', `.env.${env}`, `.env.${env}.local`]) { if (!files.includes(file) && existsSync(resolve(cwd, file))) files.push(file) } return files } // Default export for easy usage export default envPlugin