@stacksjs/env 0.75.515 → 0.75.519
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +24 -24
- package/dist/crypto.js +1 -1
- package/dist/deployment.js +1 -1
- package/dist/integrations.js +1 -1
- package/dist/numeric-keys.js +1 -1
- package/dist/parser.js +3 -3
- package/dist/plaintext-env.js +1 -1
- package/dist/plaintext.js +1 -1
- package/dist/plugin.js +1 -1
- package/dist/runtime.js +3 -3
- package/dist/tenants.js +1 -1
- package/dist/utils.js +1 -1
- package/dist/withheld.js +1 -1
- package/package.json +3 -3
package/dist/cli.js
CHANGED
|
@@ -1,31 +1,31 @@
|
|
|
1
|
-
import{randomUUID}from"node:crypto";import{chmodSync,existsSync,readFileSync,renameSync,rmSync,writeFileSync}from"node:fs";import{basename,dirname,resolve}from"node:path";import{decryptValue,encryptValue,generateKeypair,publicKeyMatchesPrivateKey}from"./crypto";import{parse}from"./parser";function writePrivateKeys(path,content){const temporary=resolve(dirname(path),`.${basename(path)}.${randomUUID()}.tmp`);try{writeFileSync(temporary,content,{encoding:"utf8",mode:384,flag:"wx"});chmodSync(temporary,384);renameSync(temporary,path)}finally{rmSync(temporary,{force
|
|
2
|
-
`)){const trimmed=line.trim();if(!trimmed||trimmed.startsWith("#"))continue;if(trimmed.startsWith("DOTENV_PUBLIC_KEY"))continue;const match=trimmed.match(/^([^=]+)=(.*)$/);if(!match||match[1]===
|
|
3
|
-
`)){const trimmed=line.trim();if(trimmed.startsWith("#/"))continue;if(trimmed.startsWith("DOTENV_PUBLIC_KEY"))continue;if(!trimmed&&!seenBody)continue;if(!trimmed||trimmed.startsWith("#")){seenBody
|
|
4
|
-
`)}export function envKeyNames(file){const
|
|
5
|
-
`)){const trimmed=line.trim();if(!trimmed||trimmed.startsWith("#"))continue;const match=trimmed.match(/^([^=]+)=(.*)$/);if(!match?.[1]||match[2]===
|
|
6
|
-
`)){const trimmed=line.trim();if(!trimmed||trimmed.startsWith("#"))continue;const match=trimmed.match(/^([^=]+)=["']?([^"'\n]+)["']?/);if(!match?.[1]||!match[2])continue;const key=match[1].trim();if(names.includes(key))return{name:key,key:match[2]}}return}export function reusableEnvPublicKey(envContent,publicKeyName){let publicKey
|
|
7
|
-
`)){const trimmed=line.trim();if(!trimmed||trimmed.startsWith("#"))continue;const match=trimmed.match(/^([^=]+)=(.*)$/);if(!match?.[1]||match[2]===
|
|
1
|
+
import{randomUUID}from"node:crypto";import{chmodSync,existsSync,readFileSync,renameSync,rmSync,writeFileSync}from"node:fs";import{basename,dirname,resolve}from"node:path";import{decryptValue,encryptValue,generateKeypair,publicKeyMatchesPrivateKey}from"./crypto";import{parse}from"./parser";function writePrivateKeys(path,content){const temporary=resolve(dirname(path),`.${basename(path)}.${randomUUID()}.tmp`);try{writeFileSync(temporary,content,{encoding:"utf8",mode:384,flag:"wx"});chmodSync(temporary,384);renameSync(temporary,path)}finally{rmSync(temporary,{force:true})}}export function resolveEnvFile(file,environment){if(file)return file;const name=String(environment??"").trim();if(!name||name==="development"||name==="dev"||name==="local")return"";if(!/^[\w.-]+$/.test(name))return"";return`.env.${name}`}function inEncryptScope(key,options){return(!options.key||key.includes(options.key))&&(!options.excludeKey||!key.includes(options.excludeKey))}function encryptableKeys(envContent,options){const keys=[];for(const line of envContent.split(`
|
|
2
|
+
`)){const trimmed=line.trim();if(!trimmed||trimmed.startsWith("#"))continue;if(trimmed.startsWith("DOTENV_PUBLIC_KEY"))continue;const match=trimmed.match(/^([^=]+)=(.*)$/);if(!match||match[1]===undefined)continue;const key=match[1].trim();if(inEncryptScope(key,options))keys.push(key)}return keys}function encryptedEnvContent(envContent,publicKey,publicKeyName,options){const encryptedLines=["#/-------------------[DOTENV_PUBLIC_KEY]--------------------/","#/ versioned X25519 encryption for .env files /","#/ [how it works](https://stacksjs.com/encryption) /","#/----------------------------------------------------------/",`${publicKeyName}="${publicKey}"`,""];let seenBody=false;for(const line of envContent.split(`
|
|
3
|
+
`)){const trimmed=line.trim();if(trimmed.startsWith("#/"))continue;if(trimmed.startsWith("DOTENV_PUBLIC_KEY"))continue;if(!trimmed&&!seenBody)continue;if(!trimmed||trimmed.startsWith("#")){seenBody=true;encryptedLines.push(line);continue}seenBody=true;const match=trimmed.match(/^([^=]+)=(.*)$/);if(!match||match[1]===undefined||match[2]===undefined){encryptedLines.push(line);continue}const key=match[1].trim();let value=match[2].trim();if(value.startsWith('"')&&value.endsWith('"')||value.startsWith(`'`)&&value.endsWith(`'`))value=value.slice(1,-1);const selected=inEncryptScope(key,options);if(selected&&!value.startsWith("encrypted:"))value=encryptValue(value,publicKey);encryptedLines.push(`${key}="${value}"`)}return encryptedLines.join(`
|
|
4
|
+
`)}export function envKeyNames(file){const baseName=(file||".env").split("/").pop()||"";const suffix=baseName.replace(/^\.env\./,"").replace(/^\.env$/,"").toUpperCase();return{publicKeyName:suffix?`DOTENV_PUBLIC_KEY_${suffix}`:"DOTENV_PUBLIC_KEY",privateKeyName:suffix?`DOTENV_PRIVATE_KEY_${suffix}`:"DOTENV_PRIVATE_KEY"}}export function envPublicKeyNames(file){const{publicKeyName}=envKeyNames(file);return publicKeyName==="DOTENV_PUBLIC_KEY"?[publicKeyName]:[publicKeyName,"DOTENV_PUBLIC_KEY"]}export function envPrivateKeyNames(file){const{privateKeyName}=envKeyNames(file);return privateKeyName==="DOTENV_PRIVATE_KEY"?[privateKeyName]:[privateKeyName,"DOTENV_PRIVATE_KEY"]}export function resolveEnvPrivateKey(options={}){const keysPath=resolve(options.cwd||process.cwd(),options.keysFile||".env.keys");const keys=existsSync(keysPath)?parse(readFileSync(keysPath,"utf8")).parsed:{};for(const name of envPrivateKeyNames(options.file)){const value=keys[name]||process.env[name];if(value)return value}return}function assertMatchingPrivateKey(publicKey,keysPath,file){const privateKey=resolveEnvPrivateKey({file,keysFile:keysPath});if(privateKey&&!publicKeyMatchesPrivateKey(publicKey,privateKey))throw new Error("Encryption public key does not match the configured private key. Restore the matching keypair or run buddy env:rotate before writing encrypted values.")}export function envHasCiphertext(envContent){for(const line of envContent.split(`
|
|
5
|
+
`)){const trimmed=line.trim();if(!trimmed||trimmed.startsWith("#"))continue;const match=trimmed.match(/^([^=]+)=(.*)$/);if(!match?.[1]||match[2]===undefined)continue;const value=match[2].trim().replace(/^["']|["']$/g,"");if(value.startsWith("encrypted:")||value.startsWith("enc:"))return true}return false}export function declaredEnvPublicKey(envContent,file){const names=envPublicKeyNames(file);for(const line of envContent.split(`
|
|
6
|
+
`)){const trimmed=line.trim();if(!trimmed||trimmed.startsWith("#"))continue;const match=trimmed.match(/^([^=]+)=["']?([^"'\n]+)["']?/);if(!match?.[1]||!match[2])continue;const key=match[1].trim();if(names.includes(key))return{name:key,key:match[2]}}return}export function reusableEnvPublicKey(envContent,publicKeyName){let publicKey;let hasCiphertext=false;for(const line of envContent.split(`
|
|
7
|
+
`)){const trimmed=line.trim();if(!trimmed||trimmed.startsWith("#"))continue;const match=trimmed.match(/^([^=]+)=(.*)$/);if(!match?.[1]||match[2]===undefined)continue;const key=match[1].trim();const value=match[2].trim().replace(/^["']|["']$/g,"");if(key===publicKeyName)publicKey=value;else if(value.startsWith("encrypted:")||value.startsWith("enc:"))hasCiphertext=true}return publicKey&&hasCiphertext?publicKey:undefined}export function encryptEnv(options={}){const cwd=options.cwd||process.cwd();const envPath=resolve(cwd,options.file||".env");const keysPath=resolve(cwd,options.keysFile||".env.keys");if(!existsSync(envPath)){return{success:false,error:`File not found: ${envPath}`}}try{if(existsSync(keysPath))chmodSync(keysPath,384);let publicKey;let privateKey;const existingPublicKey=reusableEnvPublicKey(readFileSync(envPath,"utf-8"),envKeyNames(options.file).publicKeyName);if(existingPublicKey){publicKey=existingPublicKey}else if(existsSync(keysPath)){const keysContent=readFileSync(keysPath,"utf-8");const{parsed}=parse(keysContent);const{publicKeyName,privateKeyName}=envKeyNames(options.file);publicKey=parsed[publicKeyName]||"";privateKey=parsed[privateKeyName]||"";if(!publicKey||!privateKey){const keypair=generateKeypair();publicKey=keypair.publicKey;privateKey=keypair.privateKey;const newKeys=`
|
|
8
8
|
${publicKeyName}="${publicKey}"
|
|
9
9
|
${privateKeyName}="${privateKey}"
|
|
10
|
-
`;writePrivateKeys(keysPath,keysContent+newKeys)}}else{const keypair=generateKeypair();publicKey=keypair.publicKey;privateKey=keypair.privateKey;const{publicKeyName,privateKeyName}=envKeyNames(options.file)
|
|
10
|
+
`;writePrivateKeys(keysPath,keysContent+newKeys)}}else{const keypair=generateKeypair();publicKey=keypair.publicKey;privateKey=keypair.privateKey;const{publicKeyName,privateKeyName}=envKeyNames(options.file);const keysContent=`# .env.keys - Keep this file secure and never commit to source control
|
|
11
11
|
${publicKeyName}="${publicKey}"
|
|
12
12
|
${privateKeyName}="${privateKey}"
|
|
13
|
-
`;writePrivateKeys(keysPath,keysContent)}assertMatchingPrivateKey(publicKey,keysPath,options.file);const envContent=readFileSync(envPath,"utf-8")
|
|
14
|
-
|
|
15
|
-
`)
|
|
16
|
-
`);if(options.stdout)return{success
|
|
17
|
-
`);let found
|
|
18
|
-
Generating one would leave every existing encrypted value unreadable.
|
|
19
|
-
Provide the private key as ${envPrivateKeyNames(options.file)[0]} in the environment, restore ${keysPath}, or use --plain to write this value unencrypted.`}
|
|
13
|
+
`;writePrivateKeys(keysPath,keysContent)}assertMatchingPrivateKey(publicKey,keysPath,options.file);const envContent=readFileSync(envPath,"utf-8");const output=encryptedEnvContent(envContent,publicKey,envKeyNames(options.file).publicKeyName,options);if(options.stdout){return{success:true,output}}writeFileSync(envPath,output,"utf-8");return{success:true,output:`✔ encrypted (${options.file||".env"})
|
|
14
|
+
✔ key added to ${options.keysFile||".env.keys"}`}}catch(error){return{success:false,error:`Failed to encrypt: ${error instanceof Error?error.message:"Unknown error"}`}}}export function decryptEnv(options={}){const cwd=options.cwd||process.cwd();const envPath=resolve(cwd,options.file||".env");const keysPath=resolve(cwd,options.keysFile||".env.keys");if(!existsSync(envPath)){return{success:false,error:`File not found: ${envPath}`}}if(!existsSync(keysPath)){return{success:false,error:`Keys file not found: ${keysPath}`}}try{const keysContent=readFileSync(keysPath,"utf-8");const{parsed:keys}=parse(keysContent);const envFileName=options.file||".env";const baseName=envFileName.split("/").pop()||"";const env=baseName.replace(/^\.env\./,"").replace(/^\.env$/,"").toUpperCase();const privateKeyName=env?`DOTENV_PRIVATE_KEY_${env}`:"DOTENV_PRIVATE_KEY";const privateKey=keys[privateKeyName];if(!privateKey){return{success:false,error:`Private key not found: ${privateKeyName}`}}const privateKeys=[privateKey];if(privateKeyName!=="DOTENV_PRIVATE_KEY"&&keys.DOTENV_PRIVATE_KEY&&keys.DOTENV_PRIVATE_KEY!==privateKey)privateKeys.push(keys.DOTENV_PRIVATE_KEY);const envContent=readFileSync(envPath,"utf-8");const lines=envContent.split(`
|
|
15
|
+
`);const decryptedLines=[];for(const line of lines){const trimmed=line.trim();if(!trimmed||trimmed.startsWith("#")){decryptedLines.push(line);continue}if(trimmed.startsWith("DOTENV_PUBLIC_KEY")){continue}const match=trimmed.match(/^([^=]+)=(.*)$/);if(!match||match[1]===undefined||match[2]===undefined){decryptedLines.push(line);continue}const key=match[1].trim();let value=match[2].trim();if(value.startsWith('"')&&value.endsWith('"')||value.startsWith(`'`)&&value.endsWith(`'`)){value=value.slice(1,-1)}let shouldDecrypt=value.startsWith("encrypted:");if(options.key&&!key.includes(options.key)){shouldDecrypt=false}if(shouldDecrypt){let decrypted;let lastError;for(const candidate of privateKeys){try{decrypted=decryptValue(value,candidate);break}catch(error){lastError=error}}if(decrypted===undefined)throw lastError instanceof Error?lastError:new Error(`Unable to decrypt ${key}`);value=decrypted}decryptedLines.push(`${key}="${value}"`)}const output=decryptedLines.join(`
|
|
16
|
+
`);if(options.stdout){return{success:true,output}}writeFileSync(envPath,output,"utf-8");return{success:true,output:`✔ decrypted (${options.file||".env"})`}}catch(error){return{success:false,error:`Failed to decrypt: ${error instanceof Error?error.message:"Unknown error"}`}}}export function setEnv(key,value,options={}){const cwd=options.cwd||process.cwd();const envPath=resolve(cwd,options.file||".env");const keysPath=options.keysFile?resolve(cwd,options.keysFile):resolve(dirname(envPath),".env.keys");try{if(!options.plain&&existsSync(keysPath))chmodSync(keysPath,384);let content="";if(existsSync(envPath)){content=readFileSync(envPath,"utf-8")}const lines=content.split(`
|
|
17
|
+
`);let found=false;let publicKey;const envFileName=options.file||".env";const baseName=envFileName.split("/").pop()||"";const env=baseName.replace(/^\.env\./,"").replace(/^\.env$/,"").toUpperCase();const publicKeyName=env?`DOTENV_PUBLIC_KEY_${env}`:"DOTENV_PUBLIC_KEY";const privateKeyName=env?`DOTENV_PRIVATE_KEY_${env}`:"DOTENV_PRIVATE_KEY";const declared=declaredEnvPublicKey(content,options.file);const declaredName=declared?.name??publicKeyName;publicKey=declared?.key;if(publicKey){let hasMatchingPrivateKey=false;if(existsSync(keysPath)){const keysContent=readFileSync(keysPath,"utf-8");const{parsed:keys}=parse(keysContent);hasMatchingPrivateKey=envPrivateKeyNames(options.file).some((name)=>Boolean(keys[name]))}const privateKeyInEnv=envPrivateKeyNames(options.file).some((name)=>Boolean(process.env[name]));if(!hasMatchingPrivateKey&&!privateKeyInEnv&&!envHasCiphertext(content)){publicKey=undefined}}if(!options.plain&&!publicKey&&envHasCiphertext(content)){return{success:false,error:`${options.file||".env"} already contains encrypted values, but no key that can be used to add another was found.
|
|
18
|
+
`+`Generating one would leave every existing encrypted value unreadable.
|
|
19
|
+
`+`Provide the private key as ${envPrivateKeyNames(options.file)[0]} in the environment, restore ${keysPath}, `+`or use --plain to write this value unencrypted.`}}if(!options.plain&&!publicKey){const keypair=generateKeypair();publicKey=keypair.publicKey;let keysContent="";if(existsSync(keysPath)){keysContent=readFileSync(keysPath,"utf-8")}keysContent+=`
|
|
20
20
|
${publicKeyName}="${keypair.publicKey}"
|
|
21
21
|
${privateKeyName}="${keypair.privateKey}"
|
|
22
|
-
`;writePrivateKeys(keysPath,keysContent);const staleNames=envPublicKeyNames(options.file);for(let i=lines.length-1;i>=0;i--){const lineEntry=lines[i];if(lineEntry!==
|
|
23
|
-
`);writeFileSync(envPath,output,"utf-8");return{success
|
|
24
|
-
`)
|
|
25
|
-
`)}export function getEnv(key,options={}){const cwd=options.cwd||process.cwd()
|
|
26
|
-
`);break;case"json":default:output=options.prettyPrint?JSON.stringify(result,null,2):JSON.stringify(result);break}return{success
|
|
27
|
-
`);let replacedPublic
|
|
22
|
+
`;writePrivateKeys(keysPath,keysContent);const staleNames=envPublicKeyNames(options.file);for(let i=lines.length-1;i>=0;i--){const lineEntry=lines[i];if(lineEntry!==undefined&&staleNames.some((name)=>lineEntry.trim().startsWith(`${name}=`)))lines.splice(i,1)}lines.unshift(`${declaredName}="${publicKey}"`)}let finalValue=value;if(!options.plain&&publicKey){assertMatchingPrivateKey(publicKey,keysPath,options.file);finalValue=encryptValue(value,publicKey)}for(let i=0;i<lines.length;i++){const lineEntry=lines[i];if(lineEntry===undefined)continue;const line=lineEntry.trim();if(line.startsWith(`${key}=`)){lines[i]=`${key}="${finalValue}"`;found=true;break}}if(!found){lines.push(`${key}="${finalValue}"`)}const output=lines.join(`
|
|
23
|
+
`);writeFileSync(envPath,output,"utf-8");return{success:true,output:`set ${key}${options.plain?"":" with encryption"} (${options.file||".env"})`}}catch(error){return{success:false,error:`Failed to set: ${error instanceof Error?error.message:"Unknown error"}`}}}function undecryptableMessage(unreadable,parsed,privateKey,options){const file=options.file||".env";const keysFile=options.keysFile||".env.keys";const[privateKeyName]=envPrivateKeyNames(options.file);const values=`${unreadable.length===1?"Value":"Values"} that cannot be decrypted: ${unreadable.join(", ")}.`;if(!privateKey){return[`Cannot read ${file}: no private key for it.`,` Expected ${privateKeyName} in ${keysFile} or the environment, and found neither.`,` ${values}`].join(`
|
|
24
|
+
`)}const publicKeyName=envPublicKeyNames(options.file).find((name)=>parsed[name]);const declared=publicKeyName?parsed[publicKeyName]:undefined;const reason=declared&&!publicKeyMatchesPrivateKey(declared,privateKey)?` The private key found for it does not match ${publicKeyName} in the file, so it belongs to a different key pair.`:` The private key found for it did not decrypt them. It may belong to a different key pair, or the values may be damaged.`;return[`Cannot read ${file}: its private key does not decrypt it.`,reason,` ${values}`].join(`
|
|
25
|
+
`)}export function getEnv(key,options={}){const cwd=options.cwd||process.cwd();const envPath=resolve(cwd,options.file||".env");if(!existsSync(envPath)){return{success:false,error:`File not found: ${envPath}`}}try{const privateKey=resolveEnvPrivateKey(options);const envContent=readFileSync(envPath,"utf-8");const{parsed,skippedEncrypted}=parse(envContent,{privateKey});const unreadable=key&&!options.all?skippedEncrypted.filter((name)=>name===key):skippedEncrypted;if(unreadable.length>0)return{success:false,error:undecryptableMessage(unreadable,parsed,privateKey,options)};if(key&&!options.all){const value=parsed[key];if(value===undefined){return{success:false,error:`Key not found: ${key}`}}return{success:true,output:value}}const result=parsed;let output;switch(options.format){case"shell":output=Object.entries(result).map(([k,v])=>`${k}=${v}`).join(" ");break;case"eval":output=Object.entries(result).map(([k,v])=>`${k}="${v}"`).join(`
|
|
26
|
+
`);break;case"json":default:output=options.prettyPrint?JSON.stringify(result,null,2):JSON.stringify(result);break}return{success:true,output}}catch(error){return{success:false,error:`Failed to get: ${error instanceof Error?error.message:"Unknown error"}`}}}export function getKeypair(keyName,options={}){const cwd=options.cwd||process.cwd();const keysPath=resolve(cwd,options.keysFile||".env.keys");if(!existsSync(keysPath)){return{success:false,error:`Keys file not found: ${keysPath}`}}try{const keysContent=readFileSync(keysPath,"utf-8");const{parsed}=parse(keysContent);const envFileName=options.file||".env";const baseName=envFileName.split("/").pop()||"";const env=baseName.replace(/^\.env\./,"").replace(/^\.env$/,"").toUpperCase();const publicKeyName=env?`DOTENV_PUBLIC_KEY_${env}`:"DOTENV_PUBLIC_KEY";const privateKeyName=env?`DOTENV_PRIVATE_KEY_${env}`:"DOTENV_PRIVATE_KEY";if(keyName){const value=parsed[keyName];if(!value){return{success:false,error:`Key not found: ${keyName}`}}return{success:true,output:value}}const keypair={[publicKeyName]:parsed[publicKeyName],[privateKeyName]:parsed[privateKeyName]};const output=options.format==="shell"?`${publicKeyName}=${keypair[publicKeyName]} ${privateKeyName}=${keypair[privateKeyName]}`:JSON.stringify(keypair);return{success:true,output}}catch(error){return{success:false,error:`Failed to get keypair: ${error instanceof Error?error.message:"Unknown error"}`}}}function rotatedKeysContent(keysContent,keypair,publicKeyName,privateKeyName){const lines=keysContent.split(`
|
|
27
|
+
`);let replacedPublic=false;let replacedPrivate=false;for(let i=0;i<lines.length;i++){const entry=lines[i];if(entry===undefined)continue;if(entry.startsWith(`${publicKeyName}=`)){lines[i]=`${publicKeyName}="${keypair.publicKey}"`;replacedPublic=true}else if(entry.startsWith(`${privateKeyName}=`)){lines[i]=`${privateKeyName}="${keypair.privateKey}"`;replacedPrivate=true}}if(!replacedPublic)lines.push(`${publicKeyName}="${keypair.publicKey}"`);if(!replacedPrivate)lines.push(`${privateKeyName}="${keypair.privateKey}"`);return`${lines.join(`
|
|
28
28
|
`).replace(/\n+$/,"")}
|
|
29
|
-
`}export function rotateKeypair(options={}){const decryptResult=decryptEnv({file:options.file,keysFile:options.keysFile,stdout
|
|
30
|
-
`)}}const keypair=generateKeypair()
|
|
31
|
-
`)}
|
|
29
|
+
`}export function rotateKeypair(options={}){const decryptResult=decryptEnv({file:options.file,keysFile:options.keysFile,stdout:true,cwd:options.cwd});if(!decryptResult.success){return decryptResult}if(decryptResult.output===undefined)return{success:false,error:"Rotation produced no decrypted content"};const cwd=options.cwd||process.cwd();const envFileName=options.file||".env";const keysFileName=options.keysFile||".env.keys";const envPath=resolve(cwd,envFileName);const keysPath=resolve(cwd,keysFileName);const{publicKeyName,privateKeyName}=envKeyNames(options.file);if(options.dryRun){const values=encryptableKeys(decryptResult.output,options);return{success:true,output:["Dry run: nothing was written.",`${envFileName}: ${values.length} value${values.length===1?"":"s"} would be re-encrypted under a new ${publicKeyName}.`,`${keysFileName}: ${publicKeyName} and ${privateKeyName} would be replaced.`,`The current ${privateKeyName} decrypts nothing once that happens, so keep a copy until the rotation is verified.`].join(`
|
|
30
|
+
`)}}const keypair=generateKeypair();const nextEnv=encryptedEnvContent(decryptResult.output,keypair.publicKey,publicKeyName,options);if(options.stdout){return{success:true,output:nextEnv,notice:[`Nothing was written. To adopt the output above, put this keypair in ${keysFileName}:`,"",`${publicKeyName}="${keypair.publicKey}"`,`${privateKeyName}="${keypair.privateKey}"`,"",`Without it that output cannot be decrypted. Run without --stdout to have both applied together.`].join(`
|
|
31
|
+
`)}}const originalEnv=readFileSync(envPath);const originalKeys=readFileSync(keysPath);const nextKeys=rotatedKeysContent(originalKeys.toString("utf8"),keypair,publicKeyName,privateKeyName);const token=`${process.pid}-${Date.now()}`;const envTemp=resolve(dirname(envPath),`.${basename(envPath)}.${token}.rotate`);const keysTemp=resolve(dirname(keysPath),`.${basename(keysPath)}.${token}.rotate`);try{writeFileSync(envTemp,nextEnv,{encoding:"utf8",mode:384});writeFileSync(keysTemp,nextKeys,{encoding:"utf8",mode:384});renameSync(envTemp,envPath);try{renameSync(keysTemp,keysPath)}catch(error){writeFileSync(envPath,originalEnv);throw error}return{success:true,output:`✔ rotated (${envFileName}) to encrypted:v2`}}catch(error){if(!existsSync(keysPath))writePrivateKeys(keysPath,originalKeys);return{success:false,error:`Failed to rotate without exposing plaintext: ${error instanceof Error?error.message:"Unknown error"}`}}finally{rmSync(envTemp,{force:true});rmSync(keysTemp,{force:true})}}
|
package/dist/crypto.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createCipheriv,createDecipheriv,createHash,createPrivateKey,createPublicKey,diffieHellman,generateKeyPairSync,hkdfSync,randomBytes}from"node:crypto";const PUBLIC_KEY_PREFIX="x25519-public:"
|
|
1
|
+
import{createCipheriv,createDecipheriv,createHash,createPrivateKey,createPublicKey,diffieHellman,generateKeyPairSync,hkdfSync,randomBytes}from"node:crypto";const PUBLIC_KEY_PREFIX="x25519-public:";const PRIVATE_KEY_PREFIX="x25519-private:";const ENVELOPE_PREFIX="encrypted:v2:";const LEGACY_PREFIX="encrypted:";const HKDF_INFO=Buffer.from("stacks-env:v2","utf8");const DECRYPTION_ERROR="Environment decryption failed: authentication or format error";function encryptionKey(key){if(key.length===32)return key;return createHash("sha256").update(key).digest()}export function aesEncrypt(plaintext,key){const iv=randomBytes(16);const cipher=createCipheriv("aes-256-gcm",encryptionKey(key),iv);const encrypted=Buffer.concat([cipher.update(plaintext,"utf8"),cipher.final()]);return{ciphertext:encrypted.toString("hex"),iv:iv.toString("hex"),authTag:cipher.getAuthTag().toString("hex")}}export function aesDecrypt(ciphertext,key,iv,authTag){try{const decipher=createDecipheriv("aes-256-gcm",encryptionKey(key),Buffer.from(iv,"hex"));decipher.setAuthTag(Buffer.from(authTag,"hex"));return Buffer.concat([decipher.update(Buffer.from(ciphertext,"hex")),decipher.final()]).toString("utf8")}catch{throw new Error("Decryption failed: authentication or format error")}}function encode(data){return data.toString("base64url")}function decode(value,label,expectedLength){if(typeof value!=="string"||value.length>0&&!/^[A-Za-z0-9_-]+$/.test(value))throw new Error(`${label} is not canonical base64url`);const decoded=Buffer.from(value,"base64url");if(encode(decoded)!==value)throw new Error(`${label} is not canonical base64url`);if(expectedLength!==undefined&&decoded.length!==expectedLength)throw new Error(`${label} has an invalid length`);return decoded}function parsePublicKey(value){if(!value.startsWith(PUBLIC_KEY_PREFIX))throw new Error("Legacy or invalid public key. Run buddy env:rotate before creating new ciphertext.");const key=createPublicKey({key:decode(value.slice(PUBLIC_KEY_PREFIX.length),"public key"),format:"der",type:"spki"});if(key.asymmetricKeyType!=="x25519")throw new Error("Public key is not X25519");return key}export function isValidPublicKey(value){if(typeof value!=="string")return false;try{const key=parsePublicKey(value);return value===`${PUBLIC_KEY_PREFIX}${encode(key.export({format:"der",type:"spki"}))}`}catch{return false}}function parsePrivateKey(value){if(!value.startsWith(PRIVATE_KEY_PREFIX))throw new Error("Private key is not a version 2 X25519 key");const key=createPrivateKey({key:decode(value.slice(PRIVATE_KEY_PREFIX.length),"private key"),format:"der",type:"pkcs8"});if(key.asymmetricKeyType!=="x25519")throw new Error("Private key is not X25519");return key}export function publicKeyMatchesPrivateKey(publicKey,privateKey){if(!isValidPublicKey(publicKey)||typeof privateKey!=="string")return false;try{const derived=createPublicKey(parsePrivateKey(privateKey));return publicKey===`${PUBLIC_KEY_PREFIX}${encode(derived.export({format:"der",type:"spki"}))}`}catch{return false}}function aad(envelope){return Buffer.from(`stacks-env:v2;${envelope.epk};${envelope.salt};${envelope.nonce}`,"utf8")}export function generateKeypair(){const{publicKey,privateKey}=generateKeyPairSync("x25519");const publicDer=publicKey.export({format:"der",type:"spki"});const privateDer=privateKey.export({format:"der",type:"pkcs8"});return{publicKey:`${PUBLIC_KEY_PREFIX}${encode(publicDer)}`,privateKey:`${PRIVATE_KEY_PREFIX}${encode(privateDer)}`}}export function encryptValue(value,recipientPublicKey){const recipient=parsePublicKey(recipientPublicKey);const ephemeral=generateKeyPairSync("x25519");const epk=encode(ephemeral.publicKey.export({format:"der",type:"spki"}));const salt=randomBytes(16);const nonce=randomBytes(12);const shared=diffieHellman({privateKey:ephemeral.privateKey,publicKey:recipient});const key=Buffer.from(hkdfSync("sha256",shared,salt,HKDF_INFO,32));const metadata={epk,salt:encode(salt),nonce:encode(nonce)};try{const cipher=createCipheriv("aes-256-gcm",key,nonce);cipher.setAAD(aad(metadata));const ciphertext=Buffer.concat([cipher.update(value,"utf8"),cipher.final()]);const envelope={v:2,...metadata,ciphertext:encode(ciphertext),tag:encode(cipher.getAuthTag())};return`${ENVELOPE_PREFIX}${encode(Buffer.from(JSON.stringify(envelope),"utf8"))}`}finally{shared.fill(0);key.fill(0)}}function parseEnvelope(value){const serialized=decode(value.slice(ENVELOPE_PREFIX.length),"envelope").toString("utf8");const parsed=JSON.parse(serialized);if(!parsed||typeof parsed!=="object"||Array.isArray(parsed))throw new Error("envelope is not an object");const keys=Object.keys(parsed).sort();const expected=["ciphertext","epk","nonce","salt","tag","v"];if(keys.length!==expected.length||keys.some((key,index)=>key!==expected[index]))throw new Error("envelope fields are invalid");if(parsed.v!==2)throw new Error("envelope version is unsupported");for(const field of["epk","salt","nonce","ciphertext","tag"]){if(typeof parsed[field]!=="string")throw new Error(`${field} is invalid`)}return parsed}function decryptV2(encryptedValue,recipientPrivateKey){try{const envelope=parseEnvelope(encryptedValue);const recipient=parsePrivateKey(recipientPrivateKey);const ephemeral=createPublicKey({key:decode(envelope.epk,"ephemeral public key"),format:"der",type:"spki"});if(ephemeral.asymmetricKeyType!=="x25519")throw new Error("ephemeral key is not X25519");const salt=decode(envelope.salt,"salt",16);const nonce=decode(envelope.nonce,"nonce",12);const ciphertext=decode(envelope.ciphertext,"ciphertext");const tag=decode(envelope.tag,"tag",16);const shared=diffieHellman({privateKey:recipient,publicKey:ephemeral});const key=Buffer.from(hkdfSync("sha256",shared,salt,HKDF_INFO,32));try{const decipher=createDecipheriv("aes-256-gcm",key,nonce);decipher.setAAD(aad(envelope));decipher.setAuthTag(tag);return Buffer.concat([decipher.update(ciphertext),decipher.final()]).toString("utf8")}finally{shared.fill(0);key.fill(0)}}catch{throw new Error(DECRYPTION_ERROR)}}function decryptLegacy(encryptedValue,privateKey){try{if(!/^[0-9a-f]{64}$/.test(privateKey))throw new Error("invalid legacy private key");const data=Buffer.from(encryptedValue.slice(LEGACY_PREFIX.length),"base64");if(data.length<32)throw new Error("invalid legacy payload");const publicKeyHash=createHash("sha256").update(Buffer.from(privateKey,"hex")).digest();const key=createHash("sha256").update(publicKeyHash).digest();return aesDecrypt(data.subarray(32).toString("hex"),key,data.subarray(0,16).toString("hex"),data.subarray(16,32).toString("hex"))}catch{throw new Error(DECRYPTION_ERROR)}}export function isLegacyEncryptedValue(value){return value.startsWith(LEGACY_PREFIX)&&!value.startsWith(ENVELOPE_PREFIX)}export function decryptValue(encryptedValue,privateKey){if(!encryptedValue.startsWith(LEGACY_PREFIX))return encryptedValue;return encryptedValue.startsWith(ENVELOPE_PREFIX)?decryptV2(encryptedValue,privateKey):decryptLegacy(encryptedValue,privateKey)}export function migrateEncryptedValue(encryptedValue,oldPrivateKey,newPublicKey){return encryptValue(decryptValue(encryptedValue,oldPrivateKey),newPublicKey)}export function parseEnvFromKey(keyName){const match=keyName.match(/^DOTENV_PRIVATE_KEY_(.+)$/);return match&&match[1]?match[1].toLowerCase():""}export function getPrivateKey(env=""){return env?process.env[`DOTENV_PRIVATE_KEY_${env.toUpperCase()}`]:process.env.DOTENV_PRIVATE_KEY}
|
package/dist/deployment.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import process from"node:process";export function isLoopbackHost(hostname){const host=hostname.toLowerCase();return host==="localhost"||host.endsWith(".localhost")||host==="127.0.0.1"||host==="0.0.0.0"||host==="::1"||host==="[::1]"}export function isLocalDeployment(){const name=(process.env.APP_ENV??process.env.NODE_ENV??"").toLowerCase();if(name==="production"||name==="prod"||name==="staging")return
|
|
1
|
+
import process from"node:process";export function isLoopbackHost(hostname){const host=hostname.toLowerCase();return host==="localhost"||host.endsWith(".localhost")||host==="127.0.0.1"||host==="0.0.0.0"||host==="::1"||host==="[::1]"}export function isLocalDeployment(){const name=(process.env.APP_ENV??process.env.NODE_ENV??"").toLowerCase();if(name==="production"||name==="prod"||name==="staging")return false;const url=(process.env.APP_URL??"").trim();if(url){try{return isLoopbackHost(new URL(url.includes("://")?url:`https://${url}`).hostname)}catch{}}return name===""||name==="local"||name==="dev"||name==="test"||name==="testing"}
|
package/dist/integrations.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export const REMOTE_TELEMETRY_ENVIRONMENTS=["production","staging"];export function normalizeEnvironmentName(value){if(typeof value!=="string")return;const normalized=value.trim().toLowerCase();if(!/^[a-z0-9_-]+$/.test(normalized))return;if(normalized==="prod")return"production";if(normalized==="stage")return"staging";if(normalized==="dev")return"development";return normalized}export function integrationEnvironment(){return normalizeEnvironmentName(process.env.APP_ENV)}export function integrationGate(options,defaultEnvironments=REMOTE_TELEMETRY_ENVIRONMENTS){const environment=integrationEnvironment();if(options?.enabled
|
|
1
|
+
export const REMOTE_TELEMETRY_ENVIRONMENTS=["production","staging"];export function normalizeEnvironmentName(value){if(typeof value!=="string")return;const normalized=value.trim().toLowerCase();if(!/^[a-z0-9_-]+$/.test(normalized))return;if(normalized==="prod")return"production";if(normalized==="stage")return"staging";if(normalized==="dev")return"development";return normalized}export function integrationEnvironment(){return normalizeEnvironmentName(process.env.APP_ENV)}export function integrationGate(options,defaultEnvironments=REMOTE_TELEMETRY_ENVIRONMENTS){const environment=integrationEnvironment();if(options?.enabled===false)return{enabled:false,environment,reason:"disabled-explicitly"};const allowlist=options?.environments??defaultEnvironments;if(allowlist.length===0)return{enabled:false,environment,reason:"empty-allowlist"};if(environment===undefined)return{enabled:false,environment,reason:"environment-unknown"};const permitted=new Set;for(const entry of allowlist){const name=normalizeEnvironmentName(entry);if(name!==undefined)permitted.add(name)}return permitted.has(environment)?{enabled:true,environment,reason:"environment-allowed"}:{enabled:false,environment,reason:"environment-excluded"}}export function initializeIntegration(options,initialize,defaultEnvironments=REMOTE_TELEMETRY_ENVIRONMENTS){const gate=integrationGate(options,defaultEnvironments);if(!gate.enabled||gate.environment===undefined)return{initialized:false,gate};return{initialized:true,gate,value:initialize({environment:gate.environment})}}
|
package/dist/numeric-keys.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export const FRAMEWORK_NUMERIC_ENV_KEYS=new Set(["PORT","PORT_BACKEND","PORT_ADMIN","PORT_LIBRARY","PORT_DESKTOP","PORT_EMAIL","PORT_DOCS","PORT_INSPECT","PORT_API","PORT_SYSTEM_TRAY","DB_PORT","DB_POOL_MAX","DB_POOL_IDLE_TIMEOUT_MS","DB_POOL_ACQUIRE_TIMEOUT_MS","DB_QUERY_LOGGING_SLOW_THRESHOLD","DB_QUERY_LOGGING_RETENTION_DAYS","DB_QUERY_LOGGING_PRUNE_FREQUENCY","MAIL_PORT","STRIPE_CONNECT_FEE_PERCENT","BROADCAST_PORT","REDIS_PORT","AUTH_TOKEN_EXPIRY","AUTH_REFRESH_TOKEN_EXPIRY","AUTH_TOKEN_ROTATION","AUTH_PASSWORD_RESET_EXPIRE","AUTH_PASSWORD_RESET_THROTTLE"])
|
|
1
|
+
export const FRAMEWORK_NUMERIC_ENV_KEYS=new Set(["PORT","PORT_BACKEND","PORT_ADMIN","PORT_LIBRARY","PORT_DESKTOP","PORT_EMAIL","PORT_DOCS","PORT_INSPECT","PORT_API","PORT_SYSTEM_TRAY","DB_PORT","DB_POOL_MAX","DB_POOL_IDLE_TIMEOUT_MS","DB_POOL_ACQUIRE_TIMEOUT_MS","DB_QUERY_LOGGING_SLOW_THRESHOLD","DB_QUERY_LOGGING_RETENTION_DAYS","DB_QUERY_LOGGING_PRUNE_FREQUENCY","MAIL_PORT","STRIPE_CONNECT_FEE_PERCENT","BROADCAST_PORT","REDIS_PORT","AUTH_TOKEN_EXPIRY","AUTH_REFRESH_TOKEN_EXPIRY","AUTH_TOKEN_ROTATION","AUTH_PASSWORD_RESET_EXPIRE","AUTH_PASSWORD_RESET_THROTTLE"]);export const NUMERIC_ENV_SUFFIXES=["_PORT","_TIMEOUT","_TTL","_SIZE","_LIMIT","_MAX","_MIN","_INTERVAL","_RETRIES","_CONCURRENCY","_WORKERS","_CONNECTIONS"];const declaredNumericKeys=new Set;export function registerNumericEnvKeys(schema){for(const[key,entry]of Object.entries(schema)){const validation=entry?.validation;if(validation?.name==="number")declaredNumericKeys.add(key)}}export function isDeclaredNumericEnvKey(key){return FRAMEWORK_NUMERIC_ENV_KEYS.has(key)||declaredNumericKeys.has(key)}
|
package/dist/parser.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{spawnSync}from"node:child_process";import{readFileSync}from"node:fs";import{arch,hostname,platform,release,userInfo}from"node:os";import{basename,dirname,resolve}from"node:path";import{decryptValue}from"./crypto";import{plaintextEnv}from"./plaintext-env";export function parse(src,options={}){const parsed={}
|
|
2
|
-
`)
|
|
3
|
-
`)}if(value.startsWith("encrypted:")||value.startsWith("enc:")){if(!options.privateKey){skippedEncrypted.push(key);continue}try{const normalized=value.startsWith("enc:")?`encrypted:${value.slice(4)}`:value;value=decryptValue(normalized,options.privateKey)}catch(error){errors.push(`Failed to decrypt ${key}: ${error instanceof Error?error.message:"Unknown error"}`);skippedEncrypted.push(key);continue}}value=expandVariables(value,{...processEnv,...parsed});value=expandCommands(value);parsed[key]=value}return{parsed,errors,skippedEncrypted}}function expandVariables(value,env){return value.replace(/\$\{([^}]+)\}/g,(match,expression)=>{const defaultMatch=expression.match(/^([^:\-+]+)(:-|-)(.+)$/);if(defaultMatch){const[,varName,operator,defaultValue]=defaultMatch
|
|
1
|
+
import{spawnSync}from"node:child_process";import{readFileSync}from"node:fs";import{arch,hostname,platform,release,userInfo}from"node:os";import{basename,dirname,resolve}from"node:path";import{decryptValue}from"./crypto";import{plaintextEnv}from"./plaintext-env";export function parse(src,options={}){const parsed={};const errors=[];const skippedEncrypted=[];const lines=src.split(`
|
|
2
|
+
`);const processEnv=plaintextEnv(options.processEnv||process.env);for(const rawLine of lines){const line=rawLine.trim();if(!line||line.startsWith("#")){continue}if(line.startsWith("DOTENV_PUBLIC_KEY=")){const match=line.match(/^DOTENV_PUBLIC_KEY=["']?([^"'\n]+)["']?/);if(match&&match[1]!==undefined){parsed.DOTENV_PUBLIC_KEY=match[1]}continue}const match=line.match(/^([^=]+)=(.*)$/);if(!match||match[1]===undefined||match[2]===undefined){continue}const key=match[1].trim();let value=match[2].trim();if(value.startsWith('"')&&value.endsWith('"')||value.startsWith(`'`)&&value.endsWith(`'`)){value=value.slice(1,-1);if(value.includes("\\n")){value=value.replace(/\\n/g,`
|
|
3
|
+
`)}}if(value.startsWith("encrypted:")||value.startsWith("enc:")){if(!options.privateKey){skippedEncrypted.push(key);continue}try{const normalized=value.startsWith("enc:")?`encrypted:${value.slice(4)}`:value;value=decryptValue(normalized,options.privateKey)}catch(error){errors.push(`Failed to decrypt ${key}: ${error instanceof Error?error.message:"Unknown error"}`);skippedEncrypted.push(key);continue}}value=expandVariables(value,{...processEnv,...parsed});value=expandCommands(value);parsed[key]=value}return{parsed,errors,skippedEncrypted}}function expandVariables(value,env){return value.replace(/\$\{([^}]+)\}/g,(match,expression)=>{const defaultMatch=expression.match(/^([^:\-+]+)(:-|-)(.+)$/);if(defaultMatch){const[,varName,operator,defaultValue]=defaultMatch;const varValue=env[varName];if(operator===":-"){return varValue||defaultValue}else{return varValue!==undefined?varValue:defaultValue}}const alternateMatch=expression.match(/^([^:\-+]+)(:?\+)(.+)$/);if(alternateMatch){const[,varName,operator,alternateValue]=alternateMatch;const varValue=env[varName];if(operator===":+"){return varValue?alternateValue:""}else{return varValue!==undefined?alternateValue:""}}return env[expression]||""})}const ALLOWED_ENV_COMMANDS=new Set(["date","hostname","whoami","uname","pwd","echo","printf","cat","basename","dirname"]);function splitCommand(command){const parts=[];let current="";let quote=null;let escaped=false;for(const character of command.trim()){if(escaped){current+=character;escaped=false;continue}if(character==="\\"&"e!=="'"){escaped=true;continue}if(quote){if(character===quote)quote=null;else current+=character;continue}if(character==='"'||character==="'"){quote=character;continue}if(/\s/.test(character)){if(current){parts.push(current);current=""}continue}current+=character}if(escaped||quote)throw new Error("Command substitution contains an unterminated escape or quote");if(current)parts.push(current);return parts}function portableCommand(parts){const[executable,...args]=parts;const hasFlags=args.some((argument)=>argument.startsWith("-"));if(executable==="echo"&&!hasFlags)return args.join(" ");if(executable==="printf"&&args.length===1&&!args[0]?.includes("%"))return args[0];if(executable==="hostname"&&args.length===0)return hostname();if(executable==="whoami"&&args.length===0)return userInfo().username;if(executable==="pwd"&&args.length===0)return process.cwd();if(executable==="basename"&&args.length===1)return basename(args[0]??"");if(executable==="dirname"&&args.length===1)return dirname(args[0]??"");if(executable==="cat"&&args.length>0&&!hasFlags){return args.map((path)=>readFileSync(resolve(process.cwd(),path),"utf8")).join("")}if(executable==="uname"){const flag=args[0]??"-s";if(args.length<=1&&flag==="-m")return arch();if(args.length<=1&&flag==="-r")return release();if(args.length<=1&&flag==="-s"){const platformNames={aix:"AIX",android:"Android",cygwin:"CYGWIN",darwin:"Darwin",freebsd:"FreeBSD",haiku:"Haiku",linux:"Linux",netbsd:"NetBSD",openbsd:"OpenBSD",sunos:"SunOS",win32:"Windows_NT"};return platformNames[platform()]??platform()}}return}function expandCommands(value){return value.replace(/\$\(([^)]+)\)/g,(_match,command)=>{try{const parts=splitCommand(command);const executable=parts[0];if(!executable||!ALLOWED_ENV_COMMANDS.has(executable)){console.warn(`[env] Blocked command substitution for disallowed command: ${executable}`);return""}const portableResult=portableCommand(parts);if(portableResult!==undefined)return portableResult.trim();const result=spawnSync(executable,parts.slice(1),{encoding:"utf8",env:process.env});if(result.status===0){return result.stdout.trim()}const detail=result.stderr.trim();console.warn(`[env] Command substitution failed (exit code ${result.status??"unknown"}): ${executable}${detail?`: ${detail}`:""}`)}catch(error){console.warn(`[env] Command substitution error: ${error instanceof Error?error.message:String(error)}`)}return""})}export async function loadEnvFiles(files,options={}){const allParsed={};const allErrors=[];const allSkipped=[];for(const file of files){try{const content=Bun.file(file);if(!content.size){continue}const src=await content.text();const{parsed,errors,skippedEncrypted}=parse(src,options);allErrors.push(...errors);allSkipped.push(...skippedEncrypted);for(const[key,value]of Object.entries(parsed)){if(!options.overload&&allParsed[key]!==undefined){continue}allParsed[key]=value}}catch(error){if(error?.code==="ENOENT"){continue}allErrors.push(`Failed to read ${file}: ${error instanceof Error?error.message:String(error)}`)}}return{parsed:allParsed,errors:allErrors,skippedEncrypted:allSkipped}}
|
package/dist/plaintext-env.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isEncryptedValue}from"./encrypted-value";export function plaintextEnv(values,encryptedKeys=Object.keys(values)){const ciphertext=encryptedKeys.map((key)=>values[key]).filter((value)=>isEncryptedValue(value));return Object.fromEntries(Object.entries(values).filter(([,value])=>value===
|
|
1
|
+
import{isEncryptedValue}from"./encrypted-value";export function plaintextEnv(values,encryptedKeys=Object.keys(values)){const ciphertext=encryptedKeys.map((key)=>values[key]).filter((value)=>isEncryptedValue(value));return Object.fromEntries(Object.entries(values).filter(([,value])=>value===undefined||!ciphertext.some((encrypted)=>value.includes(encrypted))))}
|
package/dist/plaintext.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{isEncryptedValue}from"./encrypted-value";import{isValidPublicKey}from"./crypto";export{isEncryptedValue};export const SECRET_NAME_PATTERN=/(?:^|_)(?:PASSWORD|PASSWD|SECRET|TOKEN|APIKEY|API_KEY|CREDENTIAL|CREDENTIALS|PRIVATE|SALT|DSN|CERT|CIPHER|SIGNATURE|WEBHOOK)(?:_|$)|(?:^|_)(?:ACCESS|SECRET)_KEY(?:_|$)|_KEY$/;const CRYPTO_METADATA_PATTERN=/^DOTENV_(?:PUBLIC|PRIVATE)_KEY
|
|
1
|
+
import{isEncryptedValue}from"./encrypted-value";import{isValidPublicKey}from"./crypto";export{isEncryptedValue};export const SECRET_NAME_PATTERN=/(?:^|_)(?:PASSWORD|PASSWD|SECRET|TOKEN|APIKEY|API_KEY|CREDENTIAL|CREDENTIALS|PRIVATE|SALT|DSN|CERT|CIPHER|SIGNATURE|WEBHOOK)(?:_|$)|(?:^|_)(?:ACCESS|SECRET)_KEY(?:_|$)|_KEY$/;const CRYPTO_METADATA_PATTERN=/^DOTENV_(?:PUBLIC|PRIVATE)_KEY/;const EXPANSION_PATTERN=/^\$\{[^}]+\}$/;export function plaintextSecrets(values,options={}){const{placeholders={},strict=false}=options;const findings=[];for(const[key,value]of Object.entries(values)){if(strict&&key.startsWith("DOTENV_PUBLIC_KEY")){if(!isValidPublicKey(value))findings.push({key,reason:"invalid-public-key"});continue}if(strict&&key.startsWith("DOTENV_PRIVATE_KEY")){if(value.trim())findings.push({key,reason:"private-key-material"});continue}if(!value||value.trim()==="")continue;if(isEncryptedValue(value))continue;if(CRYPTO_METADATA_PATTERN.test(key))continue;if(EXPANSION_PATTERN.test(value.trim()))continue;const looksSecret=SECRET_NAME_PATTERN.test(key);const isPlaceholder=Object.prototype.hasOwnProperty.call(placeholders,key)&&placeholders[key]===value;if(looksSecret&&!isPlaceholder){findings.push({key,reason:"plaintext-secret"});continue}if(strict)findings.push({key,reason:"plaintext-value"})}return findings}export function trackedEnvFiles(gitLsFilesOutput){return gitLsFilesOutput.split(`
|
|
2
2
|
`).map((line)=>line.trim()).filter(Boolean).filter((file)=>file!==".env.example").filter((file)=>/(?:^|\/)\.env(?:\.|$)/.test(file)).filter((file)=>!file.endsWith(".env.keys"))}
|
package/dist/plugin.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
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";function normalizeEnvName(value){if(!value||isEncryptedValue(value))return;const normalized=value.trim().toLowerCase();if(!/^[a-z0-9_-]+$/.test(normalized))return;if(normalized==="prod")return"production";if(normalized==="stage")return"staging";if(normalized==="dev")return"development";return normalized}let cachedKeyEnv=null
|
|
1
|
+
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";function normalizeEnvName(value){if(!value||isEncryptedValue(value))return;const normalized=value.trim().toLowerCase();if(!/^[a-z0-9_-]+$/.test(normalized))return;if(normalized==="prod")return"production";if(normalized==="stage")return"staging";if(normalized==="dev")return"development";return normalized}let cachedKeyEnv=null;let cachedKeyCwd=null;let cachedPrivateKey;let loadedEnvName;function keyFromKeysFile(envName,cwd,keysFile=".env.keys"){const keysPath=resolve(cwd,keysFile);if(!existsSync(keysPath))return;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}}export function activeEnvName(options={}){return normalizeEnvName(options.env)||loadedEnvName||normalizeEnvName(process.env.NODE_ENV)||normalizeEnvName(process.env.DOTENV_ENV)||normalizeEnvName(process.env.APP_ENV)||"development"}export function resolvePrivateKey(options={}){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}export function resetPrivateKeyCache(){cachedKeyEnv=null;cachedKeyCwd=null;cachedPrivateKey=undefined;loadedEnvName=undefined}export function decryptEnvValue(value,options={}){if(!isEncryptedValue(value))return value;const key=resolvePrivateKey(options);if(!key)return;try{const normalized=value.startsWith("enc:")?`encrypted:${value.slice(4)}`:value;return decryptValue(normalized,key)}catch{return}}export function loadEnv(options={}){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=[];let loaded=0;const withheld=withheldEnvKeys();const externalOverrides=new Set(Object.entries(plaintextEnv(process.env)).filter(([,value])=>value!==undefined).map(([key])=>key));let privateKey=customPrivateKey;if(!privateKey&&keysFile){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(!privateKey){privateKey=getPrivateKey(envName||"")||getPrivateKey()}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});errors.push(...parseErrors);if(skippedEncrypted.length>0){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}`)}let applied=0;for(const[key,value]of Object.entries(parsed)){if(key==="DOTENV_PUBLIC_KEY"||withheld.has(key)){continue}const existing=process.env[key];const isStaleCiphertext=isEncryptedValue(existing)&&value!==existing;if(overload||!externalOverrides.has(key)||isStaleCiphertext){process.env[key]=value;loaded++;applied++}}if(!quiet&&!process.env.__ENV_LOADED__){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);applyWithheldEnv();return{loaded,errors}}const reportedForeignCiphertext=new Set;function scrubForeignCiphertext(privateKey){const undecryptable=[];for(const[key,value]of Object.entries(process.env)){if(!isEncryptedValue(value))continue;let plaintext;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;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.<NODE_ENV> on its own): ${preview}${rest}`)}export function envPlugin(options={}){return{name:"env-plugin",setup(build){loadEnv(options)}}}export function autoLoadEnv(options={}){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();if(loadedEnvName!==env){loadedEnvName=env;cachedKeyEnv=null;cachedKeyCwd=null;cachedPrivateKey=undefined}const paths=[];const addIfPresent=(file)=>{if(!paths.includes(file)&&existsSync(resolve(cwd,file)))paths.push(file)};addIfPresent(".env");addIfPresent(".env.local");const envFile=`.env.${env}`;const envLocalFile=`.env.${env}.local`;addIfPresent(envFile);addIfPresent(envLocalFile);return loadEnv({...options,path:paths,env})}export default envPlugin;
|
package/dist/runtime.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
|
|
2
|
-
`)
|
|
3
|
-
`))}export function validateEnv(envProxy=env){const errors=[]
|
|
1
|
+
import p from"node:process";import{projectPath}from"@stacksjs/path";import fs from"node:fs";import{isDeclaredNumericEnvKey,NUMERIC_ENV_SUFFIXES}from"./numeric-keys";import{envEnum}from"./types";let decryptionRuntime;function getDecryptionRuntime(){decryptionRuntime||=require("./plugin");return decryptionRuntime}const warnedUndecryptable=new Set;function warnUndecryptable(key){if(warnedUndecryptable.has(key))return;warnedUndecryptable.add(key);const envName=getDecryptionRuntime().activeEnvName();console.warn(`[env] warning: "${key}" is encrypted but no usable private key was found for the "${envName}" environment; falling back to its default. Set DOTENV_PRIVATE_KEY_${envName.toUpperCase()} or ship .env.keys.`)}const handler={get:(target,key)=>{const bag=target;let value=bag[key];if(typeof value==="string"&&(value.startsWith("encrypted:")||value.startsWith("enc:"))){const decrypted=getDecryptionRuntime().decryptEnvValue(value);if(decrypted===undefined){warnUndecryptable(key);delete bag[key];return}bag[key]=decrypted;value=decrypted}if(typeof value==="string"&&isDeclaredNumericEnvKey(key)&&/^-?\d+(?:\.\d+)?$/.test(value.trim()))return Number(value);if(typeof value==="string"&&/^\d+$/.test(value)&&(value==="0"||!value.startsWith("0"))&&NUMERIC_ENV_SUFFIXES.some((s)=>key.endsWith(s)))return Number(value);if(typeof value==="string"){const lower=value.toLowerCase();if(lower==="true")return true;if(lower==="false")return false}return value},set:(target,key,value)=>{return Reflect.set(target,key,value,target)},deleteProperty:(target,key)=>Reflect.deleteProperty(target,key)};export function process(){return typeof Bun!=="undefined"?Bun.env:p.env}export const env=new Proxy(process(),handler);export function writeEnv(key,value,options){const envPath=options?.path||projectPath(".env");const env=fs.readFileSync(envPath,"utf-8");const lines=env.split(`
|
|
2
|
+
`);const index=lines.findIndex((line)=>line.startsWith(`${key}=`));const needsQuoting=/[\s"'#$\\]/.test(value);const quotedValue=needsQuoting?`"${value.replace(/"/g,"\\\"")}"`:value;if(index!==-1)lines[index]=`${key}=${quotedValue}`;else lines.push(`${key}=${quotedValue}`);fs.writeFileSync(envPath,lines.join(`
|
|
3
|
+
`))}export function validateEnv(envProxy=env){const errors=[];const bag=envProxy;for(const[key,allowedValues]of Object.entries(envEnum)){const value=bag[key];if(value!==undefined&&value!==""&&!allowedValues.includes(String(value))){errors.push(`${key}="${value}" is not valid. Allowed values: ${allowedValues.join(", ")}`)}}return errors}export function requireEnv(keys,envProxy=env){const missing=[];const bag=envProxy;for(const key of keys){const value=bag[key];if(value===undefined||value===""||value===null)missing.push(key)}if(missing.length>0){throw new Error(`[env] Missing required environment variable(s): ${missing.join(", ")}. Set them in .env or your process environment before booting.`)}return envProxy}
|
package/dist/tenants.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export function tenantEnvPrefix(slug){return`${slug.replace(/[^a-z0-9]/gi,"").toUpperCase()}_`}export function partitionTenantEnv(values,options={}){const selfPrefix=options.self?tenantEnvPrefix(options.self):
|
|
1
|
+
export function tenantEnvPrefix(slug){return`${slug.replace(/[^a-z0-9]/gi,"").toUpperCase()}_`}export function partitionTenantEnv(values,options={}){const selfPrefix=options.self?tenantEnvPrefix(options.self):undefined;const tenants=(options.tenants??[]).filter((slug)=>typeof slug==="string"&&slug.trim().length>0).map((slug)=>({slug,prefix:tenantEnvPrefix(slug)})).filter(({prefix})=>prefix!==selfPrefix).sort((a,b)=>b.prefix.length-a.prefix.length);const own={};const foreign={};for(const[key,value]of Object.entries(values)){const match=tenants.find(({prefix})=>key.startsWith(prefix));if(match){(foreign[match.slug]??={})[key]=value;continue}own[key]=value}return{own,foreign}}export function stripForeignTenantEnv(values,options={}){return partitionTenantEnv(values,options).own}export function foreignTenantKeys(partition){return Object.entries(partition.foreign).map(([tenant,values])=>({tenant,keys:Object.keys(values).sort()})).sort((a,b)=>a.tenant.localeCompare(b.tenant))}
|
package/dist/utils.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import process from"node:process";import{platform as osPlatform}from"node:os";export const isBun=typeof Bun
|
|
1
|
+
import process from"node:process";import{platform as osPlatform}from"node:os";export const isBun=typeof Bun!=="undefined";export const isNode=typeof process!=="undefined"&&process.versions?.node!==undefined;export const runtime=isBun?"bun":isNode?"node":"unknown";export const runtimeInfo={name:runtime,version:isBun?Bun.version:isNode?process.version:undefined};export const platform=osPlatform();export const isWindows=platform==="win32";export const isMacOS=platform==="darwin";export const isLinux=platform==="linux";export const hasTTY=Boolean(process.stdout?.isTTY);export const hasWindow=typeof globalThis.window!=="undefined";export function appEnv(){return process.env.APP_ENV||process.env.NODE_ENV||"local"}export function isLocal(){return appEnv()==="local"}export function isDevelopment(){const name=appEnv();return name==="development"||name==="dev"||name==="local"}export function isStaging(){return appEnv()==="staging"}export function isProduction(){const name=appEnv();return name==="production"||name==="prod"}export function isTesting(){const name=appEnv();return name==="test"||name==="testing"}export const isCI=Boolean(process.env.CI||process.env.CONTINUOUS_INTEGRATION||process.env.BUILD_NUMBER||process.env.RUN_ID);export const isDebug=Boolean(process.env.DEBUG||process.env.VERBOSE||process.argv.includes("--debug")||process.argv.includes("--verbose"));export const isMinimal=isCI||!hasTTY;export const isColorSupported=Boolean(!isMinimal&&(hasTTY||process.env.COLORTERM||process.env.FORCE_COLOR||process.env.TERM&&process.env.TERM!=="dumb"));const providers={github:{name:"GitHub Actions",detected:Boolean(process.env.GITHUB_ACTIONS)},gitlab:{name:"GitLab CI",detected:Boolean(process.env.GITLAB_CI)},circle:{name:"CircleCI",detected:Boolean(process.env.CIRCLECI)},travis:{name:"Travis CI",detected:Boolean(process.env.TRAVIS)},jenkins:{name:"Jenkins",detected:Boolean(process.env.JENKINS_URL)},vercel:{name:"Vercel",detected:Boolean(process.env.VERCEL)},netlify:{name:"Netlify",detected:Boolean(process.env.NETLIFY)},heroku:{name:"Heroku",detected:Boolean(process.env.DYNO)},aws:{name:"AWS",detected:Boolean(process.env.AWS_REGION||process.env.AWS_LAMBDA_FUNCTION_NAME)},azure:{name:"Azure",detected:Boolean(process.env.AZURE_HTTP_USER_AGENT)},cloudflare:{name:"Cloudflare",detected:Boolean(process.env.CF_PAGES)},railway:{name:"Railway",detected:Boolean(process.env.RAILWAY_ENVIRONMENT)},render:{name:"Render",detected:Boolean(process.env.RENDER)}};export const provider=Object.keys(providers).find((key)=>{const entry=providers[key];return entry!==undefined&&entry.detected})||"unknown";export const providerInfo=providers[provider]||{name:"Unknown",detected:false};
|
package/dist/withheld.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import process from"node:process";export const WITHHELD_ENV="STACKS_ENV_WITHHOLD";export function withheldEnvKeys(env=process.env){return new Set((env[WITHHELD_ENV]??"").split(",").map((key)=>key.trim()).filter(Boolean))}export function withholdEnv(keys){const merged=new Set([...withheldEnvKeys(),...keys]);return{[WITHHELD_ENV]:[...merged].join(",")}}export function applyWithheldEnv(env=process.env){const removed=[];for(const key of withheldEnvKeys(env))if(key in env){delete env[key];removed.push(key)}return removed}
|
|
1
|
+
import process from"node:process";export const WITHHELD_ENV="STACKS_ENV_WITHHOLD";export function withheldEnvKeys(env=process.env){return new Set((env[WITHHELD_ENV]??"").split(",").map((key)=>key.trim()).filter(Boolean))}export function withholdEnv(keys){const merged=new Set([...withheldEnvKeys(),...keys]);return{[WITHHELD_ENV]:[...merged].join(",")}}export function applyWithheldEnv(env=process.env){const removed=[];for(const key of withheldEnvKeys(env)){if(key in env){delete env[key];removed.push(key)}}return removed}
|
package/package.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"name": "@stacksjs/env",
|
|
3
3
|
"type": "module",
|
|
4
4
|
"sideEffects": false,
|
|
5
|
-
"version": "0.75.
|
|
5
|
+
"version": "0.75.519",
|
|
6
6
|
"description": "Stacks env helper methods.",
|
|
7
7
|
"author": "Chris Breuer",
|
|
8
8
|
"contributors": [
|
|
@@ -56,11 +56,11 @@
|
|
|
56
56
|
"prepublishOnly": "bun run build"
|
|
57
57
|
},
|
|
58
58
|
"dependencies": {
|
|
59
|
-
"@stacksjs/path": "0.75.
|
|
59
|
+
"@stacksjs/path": "0.75.519",
|
|
60
60
|
"@stacksjs/ts-validation": "^0.5.7"
|
|
61
61
|
},
|
|
62
62
|
"devDependencies": {
|
|
63
63
|
"better-dx": "^0.2.24",
|
|
64
|
-
"@stacksjs/validation": "0.75.
|
|
64
|
+
"@stacksjs/validation": "0.75.519"
|
|
65
65
|
}
|
|
66
66
|
}
|