@stacksjs/env 0.70.98 → 0.70.100

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/index.js CHANGED
@@ -1,25 +1,25 @@
1
1
  // @bun
2
- import{createCipheriv as a,createDecipheriv as i,createHash as f,randomBytes as K}from"crypto";function n(J,Q){let $=K(16),z=Q.length===32?Q:Buffer.from(Q.toString("hex").slice(0,64),"hex"),Z=a("aes-256-gcm",z,$),X=Buffer.concat([Z.update(J,"utf8"),Z.final()]),Y=Z.getAuthTag();return{ciphertext:X.toString("hex"),iv:$.toString("hex"),authTag:Y.toString("hex")}}function r(J,Q,$,z){let Z=Q.length===32?Q:Buffer.from(Q.toString("hex").slice(0,64),"hex");try{let X=i("aes-256-gcm",Z,Buffer.from($,"hex"));return X.setAuthTag(Buffer.from(z,"hex")),Buffer.concat([X.update(Buffer.from(J,"hex")),X.final()]).toString("utf8")}catch(X){throw Error(`Decryption failed (data may be corrupted or key is incorrect): ${X instanceof Error?X.message:String(X)}`)}}function b(){let J=K(32);return{publicKey:f("sha256").update(J).digest().toString("hex"),privateKey:J.toString("hex")}}function N(J,Q){let $=f("sha256").update(Buffer.from(Q,"hex")).digest(),{ciphertext:z,iv:Z,authTag:X}=n(J,$);return`encrypted:${Buffer.concat([Buffer.from(Z,"hex"),Buffer.from(X,"hex"),Buffer.from(z,"hex")]).toString("base64")}`}function S(J,Q){if(!J.startsWith("encrypted:"))return J;let $=J.slice(10),z=Buffer.from($,"base64");if(z.length<32)throw Error("Invalid encrypted data: payload too short (need at least iv + authTag = 32 bytes)");let Z=z.subarray(0,16).toString("hex"),X=z.subarray(16,32).toString("hex"),Y=z.subarray(32).toString("hex"),W=f("sha256").update(Buffer.from(Q,"hex")).digest(),G=f("sha256").update(W).digest();return r(Y,G,Z,X)}function HJ(J){let Q=J.match(/^DOTENV_PRIVATE_KEY_(.+)$/);return Q&&Q[1]?Q[1].toLowerCase():""}function m(J=""){if(!J)return process.env.DOTENV_PRIVATE_KEY;let Q=`DOTENV_PRIVATE_KEY_${J.toUpperCase()}`;return process.env[Q]}function L(J,Q={}){let $={},z=[],Z=J.split(`
3
- `);for(let X of Z){let Y=X.trim();if(!Y||Y.startsWith("#"))continue;if(Y.startsWith("DOTENV_PUBLIC_KEY=")){let q=Y.match(/^DOTENV_PUBLIC_KEY=["']?([^"'\n]+)["']?/);if(q&&q[1]!==void 0)$.DOTENV_PUBLIC_KEY=q[1];continue}let W=Y.match(/^([^=]+)=(.*)$/);if(!W||W[1]===void 0||W[2]===void 0)continue;let G=W[1].trim(),j=W[2].trim();if(j.startsWith('"')&&j.endsWith('"')||j.startsWith("'")&&j.endsWith("'")){if(j=j.slice(1,-1),j.includes("\\n"))j=j.replace(/\\n/g,`
4
- `)}if(Q.privateKey&&(j.startsWith("encrypted:")||j.startsWith("enc:")))try{let q=j.startsWith("enc:")?`encrypted:${j.slice(4)}`:j;j=S(q,Q.privateKey)}catch(q){z.push(`Failed to decrypt ${G}: ${q instanceof Error?q.message:"Unknown error"}`)}j=o(j,{...Q.processEnv||process.env,...$}),j=t(j),$[G]=j}return{parsed:$,errors:z}}function o(J,Q){return J.replace(/\$\{([^}]+)\}/g,($,z)=>{let Z=z.match(/^([^:\-+]+)(:-|-)(.+)$/);if(Z){let[,Y,W,G]=Z,j=Q[Y];if(W===":-")return j||G;else return j!==void 0?j:G}let X=z.match(/^([^:\-+]+)(:?\+)(.+)$/);if(X){let[,Y,W,G]=X,j=Q[Y];if(W===":+")return j?G:"";else return j!==void 0?G:""}return Q[z]||""})}var s=new Set(["date","hostname","whoami","uname","pwd","echo","printf","cat","basename","dirname"]);function t(J){return J.replace(/\$\(([^)]+)\)/g,(Q,$)=>{try{let z=$.trim().split(/\s+/),Z=z[0];if(!Z||!s.has(Z))return console.warn(`[env] Blocked command substitution for disallowed command: ${Z}`),"";let X=Bun.spawnSync(z,{stdout:"pipe",stderr:"pipe"});if(X.exitCode===0)return new TextDecoder().decode(X.stdout).trim();console.warn(`[env] Command substitution failed (exit code ${X.exitCode}): ${Z}`)}catch(z){console.warn(`[env] Command substitution error: ${z instanceof Error?z.message:String(z)}`)}return""})}async function qJ(J,Q={}){let $={},z=[];for(let Z of J)try{let X=Bun.file(Z);if(!X.size)continue;let Y=await X.text(),{parsed:W,errors:G}=L(Y,Q);z.push(...G);for(let[j,q]of Object.entries(W)){if(!Q.overload&&$[j]!==void 0)continue;$[j]=q}}catch(X){if(X?.code==="ENOENT")continue;z.push(`Failed to read ${Z}: ${X instanceof Error?X.message:String(X)}`)}return{parsed:$,errors:z}}import{existsSync as F}from"fs";import{readFileSync as h}from"fs";import{resolve as w}from"path";function k(J={}){let{path:Q=[".env"],overload:$=!1,env:z,privateKey:Z,keysFile:X,quiet:Y=!1,cwd:W=process.cwd()}=J,G=Array.isArray(Q)?Q:[Q],j=[],q=0,R=Z;if(!R&&X){let A=w(W,X);if(F(A))try{let O=h(A,"utf-8"),{parsed:U}=L(O);if(z){let B=`DOTENV_PRIVATE_KEY_${z.toUpperCase()}`;R=U[B]}else R=U.DOTENV_PRIVATE_KEY}catch(O){j.push(`Failed to load keys file: ${O instanceof Error?O.message:"Unknown error"}`)}}if(!R)R=m(z||"");for(let A of G){let O=w(W,A);if(!F(O)){if(!Y)j.push(`File not found: ${O}`);continue}try{let U=h(O,"utf-8"),{parsed:B,errors:D}=L(U,{privateKey:R,processEnv:process.env});j.push(...D);let H=0;for(let[M,I]of Object.entries(B)){if(M==="DOTENV_PUBLIC_KEY")continue;let T=process.env[M],p=typeof T==="string"&&(T.startsWith("encrypted:")||T.startsWith("enc:"))&&I!==T;if($||T===void 0||p)process.env[M]=I,q++,H++}if(!Y&&!process.env.__ENV_LOADED__)console.log(`[env] loaded ${H}/${Object.keys(B).length} variables from ${A}`),process.env.__ENV_LOADED__="1"}catch(U){j.push(`Failed to load ${O}: ${U instanceof Error?U.message:"Unknown error"}`)}}return{loaded:q,errors:j}}function e(J={}){return{name:"env-plugin",setup(Q){k(J)}}}function CJ(J={}){let Q=J.env||"development",$=J.cwd||process.cwd(),z=[],Z=`.env.${Q}`,X=`.env.${Q}.local`;if(F(w($,X)))z.push(X);if(F(w($,Z)))z.push(Z);if(F(w($,".env.local")))z.push(".env.local");if(F(w($,".env")))z.push(".env");return k({...J,path:z,env:Q})}var gJ=e;import{existsSync as g,readFileSync as C,writeFileSync as E}from"fs";import{resolve as V}from"path";function JJ(J={}){let Q=J.cwd||process.cwd(),$=V(Q,J.file||".env"),z=V(Q,J.keysFile||".env.keys");if(!g($))return{success:!1,error:`File not found: ${$}`};try{let Z,X;if(g(z)){let A=C(z,"utf-8"),{parsed:O}=L(A),D=((J.file||".env").split("/").pop()||"").replace(/^\.env\./,"").replace(/^\.env$/,"").toUpperCase(),H=D?`DOTENV_PUBLIC_KEY_${D}`:"DOTENV_PUBLIC_KEY",M=D?`DOTENV_PRIVATE_KEY_${D}`:"DOTENV_PRIVATE_KEY";if(Z=O[H]||"",X=O[M]||"",!Z||!X){let I=b();Z=I.publicKey,X=I.privateKey;let T=`
5
- ${H}="${Z}"
6
- ${M}="${X}"
7
- `;E(z,A+T,"utf-8")}}else{let A=b();Z=A.publicKey,X=A.privateKey;let B=((J.file||".env").split("/").pop()||"").replace(/^\.env\./,"").replace(/^\.env$/,"").toUpperCase(),D=B?`DOTENV_PUBLIC_KEY_${B}`:"DOTENV_PUBLIC_KEY",H=B?`DOTENV_PRIVATE_KEY_${B}`:"DOTENV_PRIVATE_KEY",M=`# .env.keys - Keep this file secure and never commit to source control
8
- ${D}="${Z}"
9
- ${H}="${X}"
10
- `;E(z,M,"utf-8")}let W=C($,"utf-8").split(`
11
- `),G=[],j=J.file?J.file.replace(/^\.env\./,"").toUpperCase():"",q=j?`DOTENV_PUBLIC_KEY_${j}`:"DOTENV_PUBLIC_KEY";G.push("#/-------------------[DOTENV_PUBLIC_KEY]--------------------/"),G.push("#/ public-key encryption for .env files /"),G.push("#/ [how it works](https://stacksjs.com/encryption) /"),G.push("#/----------------------------------------------------------/"),G.push(`${q}="${Z}"`),G.push("");for(let A of W){let O=A.trim();if(!O||O.startsWith("#")){G.push(A);continue}if(O.startsWith("DOTENV_PUBLIC_KEY"))continue;let U=O.match(/^([^=]+)=(.*)$/);if(!U||U[1]===void 0||U[2]===void 0){G.push(A);continue}let B=U[1].trim(),D=U[2].trim();if(D.startsWith('"')&&D.endsWith('"')||D.startsWith("'")&&D.endsWith("'"))D=D.slice(1,-1);let H=!0;if(J.key&&!B.includes(J.key))H=!1;if(J.excludeKey&&B.includes(J.excludeKey))H=!1;if(D.startsWith("encrypted:"))H=!1;if(H)D=N(D,Z);G.push(`${B}="${D}"`)}let R=G.join(`
12
- `);if(J.stdout)return{success:!0,output:R};return E($,R,"utf-8"),{success:!0,output:`\u2714 encrypted (${J.file||".env"})
13
- \u2714 key added to ${J.keysFile||".env.keys"}`}}catch(Z){return{success:!1,error:`Failed to encrypt: ${Z instanceof Error?Z.message:"Unknown error"}`}}}function QJ(J={}){let Q=J.cwd||process.cwd(),$=V(Q,J.file||".env"),z=V(Q,J.keysFile||".env.keys");if(!g($))return{success:!1,error:`File not found: ${$}`};if(!g(z))return{success:!1,error:`Keys file not found: ${z}`};try{let Z=C(z,"utf-8"),{parsed:X}=L(Z),G=((J.file||".env").split("/").pop()||"").replace(/^\.env\./,"").replace(/^\.env$/,"").toUpperCase(),j=G?`DOTENV_PRIVATE_KEY_${G}`:"DOTENV_PRIVATE_KEY",q=X[j];if(!q)return{success:!1,error:`Private key not found: ${j}`};let A=C($,"utf-8").split(`
14
- `),O=[];for(let B of A){let D=B.trim();if(!D||D.startsWith("#")){O.push(B);continue}if(D.startsWith("DOTENV_PUBLIC_KEY"))continue;let H=D.match(/^([^=]+)=(.*)$/);if(!H||H[1]===void 0||H[2]===void 0){O.push(B);continue}let M=H[1].trim(),I=H[2].trim();if(I.startsWith('"')&&I.endsWith('"')||I.startsWith("'")&&I.endsWith("'"))I=I.slice(1,-1);let T=I.startsWith("encrypted:");if(J.key&&!M.includes(J.key))T=!1;if(T)I=S(I,q);O.push(`${M}="${I}"`)}let U=O.join(`
15
- `);if(J.stdout)return{success:!0,output:U};return E($,U,"utf-8"),{success:!0,output:`\u2714 decrypted (${J.file||".env"})`}}catch(Z){return{success:!1,error:`Failed to decrypt: ${Z instanceof Error?Z.message:"Unknown error"}`}}}function fJ(J,Q,$={}){let z=$.cwd||process.cwd(),Z=V(z,$.file||".env"),X=V(z,$.keysFile||".env.keys");try{let Y="";if(g(Z))Y=C(Z,"utf-8");let W=Y.split(`
16
- `),G=!1,j,A=(($.file||".env").split("/").pop()||"").replace(/^\.env\./,"").replace(/^\.env$/,"").toUpperCase(),O=A?`DOTENV_PUBLIC_KEY_${A}`:"DOTENV_PUBLIC_KEY",U=A?`DOTENV_PRIVATE_KEY_${A}`:"DOTENV_PRIVATE_KEY";for(let H of W){let M=H.trim();if(M.startsWith(`${O}=`)){let I=M.match(/^[^=]+=["']?([^"'\n]+)["']?/);if(I)j=I[1];break}}if(j){let H=!1;if(g(X)){let M=C(X,"utf-8"),{parsed:I}=L(M);H=Boolean(I[U])}if(!H)j=void 0}if(!$.plain&&!j){let H=b();j=H.publicKey;let M="";if(g(X))M=C(X,"utf-8");M+=`
17
- ${O}="${H.publicKey}"
18
- ${U}="${H.privateKey}"
19
- `,E(X,M,"utf-8");for(let I=W.length-1;I>=0;I--){let T=W[I];if(T!==void 0&&T.trim().startsWith(`${O}=`))W.splice(I,1)}W.unshift(`${O}="${j}"`)}let B=Q;if(!$.plain&&j)B=N(Q,j);for(let H=0;H<W.length;H++){let M=W[H];if(M===void 0)continue;if(M.trim().startsWith(`${J}=`)){W[H]=`${J}="${B}"`,G=!0;break}}if(!G)W.push(`${J}="${B}"`);let D=W.join(`
20
- `);return E(Z,D,"utf-8"),{success:!0,output:`set ${J}${$.plain?"":" with encryption"} (${$.file||".env"})`}}catch(Y){return{success:!1,error:`Failed to set: ${Y instanceof Error?Y.message:"Unknown error"}`}}}function SJ(J,Q={}){let $=Q.cwd||process.cwd(),z=V($,Q.file||".env");if(!g(z))return{success:!1,error:`File not found: ${z}`};try{let Z,X=V($,Q.keysFile||".env.keys"),G=((Q.file||".env").split("/").pop()||"").replace(/^\.env\./,"").replace(/^\.env$/,"").toUpperCase(),j=G?`DOTENV_PRIVATE_KEY_${G}`:"DOTENV_PRIVATE_KEY";if(g(X)){let U=C(X,"utf-8"),{parsed:B}=L(U);Z=B[j]}if(!Z)Z=process.env[j];let q=C(z,"utf-8"),{parsed:R}=L(q,{privateKey:Z});if(J&&!Q.all){let U=R[J];if(U===void 0)return{success:!1,error:`Key not found: ${J}`};return{success:!0,output:U}}let A=Q.all?{...process.env,...R}:R,O;switch(Q.format){case"shell":O=Object.entries(A).map(([U,B])=>`${U}=${B}`).join(" ");break;case"eval":O=Object.entries(A).map(([U,B])=>`${U}="${B}"`).join(`
21
- `);break;case"json":default:O=Q.prettyPrint?JSON.stringify(A,null,2):JSON.stringify(A);break}return{success:!0,output:O}}catch(Z){return{success:!1,error:`Failed to get: ${Z instanceof Error?Z.message:"Unknown error"}`}}}function NJ(J,Q={}){let $=Q.cwd||process.cwd(),z=V($,Q.keysFile||".env.keys");if(!g(z))return{success:!1,error:`Keys file not found: ${z}`};try{let Z=C(z,"utf-8"),{parsed:X}=L(Z),G=((Q.file||".env").split("/").pop()||"").replace(/^\.env\./,"").replace(/^\.env$/,"").toUpperCase(),j=G?`DOTENV_PUBLIC_KEY_${G}`:"DOTENV_PUBLIC_KEY",q=G?`DOTENV_PRIVATE_KEY_${G}`:"DOTENV_PRIVATE_KEY";if(J){let O=X[J];if(!O)return{success:!1,error:`Key not found: ${J}`};return{success:!0,output:O}}let R={[j]:X[j],[q]:X[q]};return{success:!0,output:Q.format==="shell"?`${j}=${R[j]} ${q}=${R[q]}`:JSON.stringify(R)}}catch(Z){return{success:!1,error:`Failed to get keypair: ${Z instanceof Error?Z.message:"Unknown error"}`}}}function xJ(J={}){let Q=QJ({file:J.file,keysFile:J.keysFile,stdout:!0,cwd:J.cwd});if(!Q.success)return Q;let $=J.cwd||process.cwd(),z=V($,J.file||".env"),Z=V($,J.keysFile||".env.keys");if(Q.output)E(z,Q.output,"utf-8");let X=b(),W=C(Z,"utf-8").split(`
22
- `),G=J.file?J.file.replace(/^\.env\./,"").toUpperCase():"",j=G?`DOTENV_PUBLIC_KEY_${G}`:"DOTENV_PUBLIC_KEY",q=G?`DOTENV_PRIVATE_KEY_${G}`:"DOTENV_PRIVATE_KEY";for(let R=0;R<W.length;R++){let A=W[R];if(A===void 0)continue;if(A.startsWith(`${j}=`))W[R]=`${j}="${X.publicKey}"`;else if(A.startsWith(`${q}=`))W[R]=`${q}="${X.privateKey}"`}return E(Z,W.join(`
23
- `),"utf-8"),JJ({file:J.file,keysFile:J.keysFile,key:J.key,excludeKey:J.excludeKey,stdout:J.stdout,cwd:J.cwd})}import _ from"process";import{platform as ZJ}from"os";var d=typeof Bun<"u",u=typeof _<"u"&&_.versions?.node!==void 0,$J=d?"bun":u?"node":"unknown",hJ={name:$J,version:d?Bun.version:u?_.version:void 0},P=ZJ(),kJ=P==="win32",dJ=P==="darwin",uJ=P==="linux",c=Boolean(_.stdout?.isTTY),cJ=typeof globalThis.window<"u",zJ=Boolean(_.env.CI||_.env.CONTINUOUS_INTEGRATION||_.env.BUILD_NUMBER||_.env.RUN_ID),vJ=Boolean(_.env.DEBUG||_.env.VERBOSE||_.argv.includes("--debug")||_.argv.includes("--verbose")),XJ=zJ||!c,lJ=Boolean(!XJ&&(c||_.env.COLORTERM||_.env.FORCE_COLOR||_.env.TERM&&_.env.TERM!=="dumb")),x={github:{name:"GitHub Actions",detected:Boolean(_.env.GITHUB_ACTIONS)},gitlab:{name:"GitLab CI",detected:Boolean(_.env.GITLAB_CI)},circle:{name:"CircleCI",detected:Boolean(_.env.CIRCLECI)},travis:{name:"Travis CI",detected:Boolean(_.env.TRAVIS)},jenkins:{name:"Jenkins",detected:Boolean(_.env.JENKINS_URL)},vercel:{name:"Vercel",detected:Boolean(_.env.VERCEL)},netlify:{name:"Netlify",detected:Boolean(_.env.NETLIFY)},heroku:{name:"Heroku",detected:Boolean(_.env.DYNO)},aws:{name:"AWS",detected:Boolean(_.env.AWS_REGION||_.env.AWS_LAMBDA_FUNCTION_NAME)},azure:{name:"Azure",detected:Boolean(_.env.AZURE_HTTP_USER_AGENT)},cloudflare:{name:"Cloudflare",detected:Boolean(_.env.CF_PAGES)},railway:{name:"Railway",detected:Boolean(_.env.RAILWAY_ENVIRONMENT)},render:{name:"Render",detected:Boolean(_.env.RENDER)}},jJ=Object.keys(x).find((J)=>{let Q=x[J];return Q!==void 0&&Q.detected})||"unknown",yJ=x[jJ]||{name:"Unknown",detected:!1};import GJ from"process";import{projectPath as WJ}from"@stacksjs/path";import l from"fs";var v={APP_ENV:["local","dev","development","staging","prod","production"],DB_CONNECTION:["mysql","sqlite","postgres","dynamodb"],DB_MIGRATE_FRESH:["allow","confirm","disabled"],MAIL_MAILER:["smtp","mailgun","ses","log","sendgrid","mailtrap"],SEARCH_ENGINE_DRIVER:["opensearch","meilisearch","algolia","typesense"],FRONTEND_APP_ENV:["development","staging","production"]};var OJ={get:(J,Q)=>{let $=J[Q],z=["_PORT","_TIMEOUT","_TTL","_SIZE","_LIMIT","_MAX","_MIN","_INTERVAL","_RETRIES","_CONCURRENCY","_WORKERS","_CONNECTIONS"];if(typeof $==="string"&&/^\d+$/.test($)&&!$.startsWith("0")&&z.some((Z)=>Q.endsWith(Z)))return Number($);if(typeof $==="string"){let Z=$.toLowerCase();if(Z==="true")return!0;if(Z==="false")return!1}return $}};function YJ(){return typeof Bun<"u"?Bun.env:GJ.env}var y=new Proxy(YJ(),OJ);function sJ(J,Q,$){let z=$?.path||WJ(".env"),X=l.readFileSync(z,"utf-8").split(`
24
- `),Y=X.findIndex((j)=>j.startsWith(`${J}=`)),G=/[\s"'#$\\]/.test(Q)?`"${Q.replace(/"/g,"\\\"")}"`:Q;if(Y!==-1)X[Y]=`${J}=${G}`;else X.push(`${J}=${G}`);l.writeFileSync(z,X.join(`
25
- `))}function tJ(J=y){let Q=[];for(let[$,z]of Object.entries(v)){let Z=J[$];if(Z!==void 0&&Z!==""&&!z.includes(String(Z)))Q.push(`${$}="${Z}" is not valid. Allowed values: ${z.join(", ")}`)}return Q}function eJ(J,Q=y){let $=[];for(let z of J){let Z=Q[z];if(Z===void 0||Z===""||Z===null)$.push(z)}if($.length>0)throw Error(`[env] Missing required environment variable(s): ${$.join(", ")}. Set them in .env or your process environment before booting.`);return Q}export{sJ as writeEnv,tJ as validateEnv,fJ as setEnv,hJ as runtimeInfo,$J as runtime,xJ as rotateKeypair,eJ as requireEnv,yJ as providerInfo,jJ as provider,YJ as process,P as platform,HJ as parseEnvFromKey,L as parse,qJ as loadEnvFiles,k as loadEnv,kJ as isWindows,u as isNode,XJ as isMinimal,dJ as isMacOS,uJ as isLinux,vJ as isDebug,lJ as isColorSupported,zJ as isCI,d as isBun,cJ as hasWindow,c as hasTTY,m as getPrivateKey,NJ as getKeypair,SJ as getEnv,b as generateKeypair,e as envPlugin,v as envEnum,y as env,N as encryptValue,JJ as encryptEnv,S as decryptValue,QJ as decryptEnv,CJ as autoLoadEnv,n as aesEncrypt,r as aesDecrypt};
2
+ import{createCipheriv as r,createDecipheriv as s,createHash as E,randomBytes as k}from"crypto";function a(J,Q){let X=k(16),$=Q.length===32?Q:Buffer.from(Q.toString("hex").slice(0,64),"hex"),Z=r("aes-256-gcm",$,X),j=Buffer.concat([Z.update(J,"utf8"),Z.final()]),A=Z.getAuthTag();return{ciphertext:j.toString("hex"),iv:X.toString("hex"),authTag:A.toString("hex")}}function t(J,Q,X,$){let Z=Q.length===32?Q:Buffer.from(Q.toString("hex").slice(0,64),"hex");try{let j=s("aes-256-gcm",Z,Buffer.from(X,"hex"));return j.setAuthTag(Buffer.from($,"hex")),Buffer.concat([j.update(Buffer.from(J,"hex")),j.final()]).toString("utf8")}catch(j){throw Error(`Decryption failed (data may be corrupted or key is incorrect): ${j instanceof Error?j.message:String(j)}`)}}function w(){let J=k(32);return{publicKey:E("sha256").update(J).digest().toString("hex"),privateKey:J.toString("hex")}}function x(J,Q){let X=E("sha256").update(Buffer.from(Q,"hex")).digest(),{ciphertext:$,iv:Z,authTag:j}=a(J,X);return`encrypted:${Buffer.concat([Buffer.from(Z,"hex"),Buffer.from(j,"hex"),Buffer.from($,"hex")]).toString("base64")}`}function b(J,Q){if(!J.startsWith("encrypted:"))return J;let X=J.slice(10),$=Buffer.from(X,"base64");if($.length<32)throw Error("Invalid encrypted data: payload too short (need at least iv + authTag = 32 bytes)");let Z=$.subarray(0,16).toString("hex"),j=$.subarray(16,32).toString("hex"),A=$.subarray(32).toString("hex"),Y=E("sha256").update(Buffer.from(Q,"hex")).digest(),W=E("sha256").update(Y).digest();return t(A,W,Z,j)}function BJ(J){let Q=J.match(/^DOTENV_PRIVATE_KEY_(.+)$/);return Q&&Q[1]?Q[1].toLowerCase():""}function d(J=""){if(!J)return process.env.DOTENV_PRIVATE_KEY;let Q=`DOTENV_PRIVATE_KEY_${J.toUpperCase()}`;return process.env[Q]}function T(J,Q={}){let X={},$=[],Z=J.split(`
3
+ `);for(let j of Z){let A=j.trim();if(!A||A.startsWith("#"))continue;if(A.startsWith("DOTENV_PUBLIC_KEY=")){let D=A.match(/^DOTENV_PUBLIC_KEY=["']?([^"'\n]+)["']?/);if(D&&D[1]!==void 0)X.DOTENV_PUBLIC_KEY=D[1];continue}let Y=A.match(/^([^=]+)=(.*)$/);if(!Y||Y[1]===void 0||Y[2]===void 0)continue;let W=Y[1].trim(),G=Y[2].trim();if(G.startsWith('"')&&G.endsWith('"')||G.startsWith("'")&&G.endsWith("'")){if(G=G.slice(1,-1),G.includes("\\n"))G=G.replace(/\\n/g,`
4
+ `)}if(Q.privateKey&&(G.startsWith("encrypted:")||G.startsWith("enc:")))try{let D=G.startsWith("enc:")?`encrypted:${G.slice(4)}`:G;G=b(D,Q.privateKey)}catch(D){$.push(`Failed to decrypt ${W}: ${D instanceof Error?D.message:"Unknown error"}`)}G=e(G,{...Q.processEnv||process.env,...X}),G=QJ(G),X[W]=G}return{parsed:X,errors:$}}function e(J,Q){return J.replace(/\$\{([^}]+)\}/g,(X,$)=>{let Z=$.match(/^([^:\-+]+)(:-|-)(.+)$/);if(Z){let[,A,Y,W]=Z,G=Q[A];if(Y===":-")return G||W;else return G!==void 0?G:W}let j=$.match(/^([^:\-+]+)(:?\+)(.+)$/);if(j){let[,A,Y,W]=j,G=Q[A];if(Y===":+")return G?W:"";else return G!==void 0?W:""}return Q[$]||""})}var JJ=new Set(["date","hostname","whoami","uname","pwd","echo","printf","cat","basename","dirname"]);function QJ(J){return J.replace(/\$\(([^)]+)\)/g,(Q,X)=>{try{let $=X.trim().split(/\s+/),Z=$[0];if(!Z||!JJ.has(Z))return console.warn(`[env] Blocked command substitution for disallowed command: ${Z}`),"";let j=Bun.spawnSync($,{stdout:"pipe",stderr:"pipe"});if(j.exitCode===0)return new TextDecoder().decode(j.stdout).trim();console.warn(`[env] Command substitution failed (exit code ${j.exitCode}): ${Z}`)}catch($){console.warn(`[env] Command substitution error: ${$ instanceof Error?$.message:String($)}`)}return""})}async function zJ(J,Q={}){let X={},$=[];for(let Z of J)try{let j=Bun.file(Z);if(!j.size)continue;let A=await j.text(),{parsed:Y,errors:W}=T(A,Q);$.push(...W);for(let[G,D]of Object.entries(Y)){if(!Q.overload&&X[G]!==void 0)continue;X[G]=D}}catch(j){if(j?.code==="ENOENT")continue;$.push(`Failed to read ${Z}: ${j instanceof Error?j.message:String(j)}`)}return{parsed:X,errors:$}}import{existsSync as f}from"fs";import{readFileSync as u}from"fs";import{resolve as N}from"path";function P(J){return typeof J==="string"&&(J.startsWith("encrypted:")||J.startsWith("enc:"))}function S(J){if(!J||P(J))return;let Q=J.trim().toLowerCase();if(!/^[a-z0-9_-]+$/.test(Q))return;if(Q==="prod")return"production";if(Q==="stage")return"staging";if(Q==="dev")return"development";return Q}function c(J={}){let{path:Q=[".env"],overload:X=!1,env:$,privateKey:Z,keysFile:j=".env.keys",quiet:A=!1,cwd:Y=process.cwd()}=J,W=Array.isArray(Q)?Q:[Q],G=[],D=0,M=new Set(Object.entries(process.env).filter(([,O])=>O!==void 0&&!P(O)).map(([O])=>O)),H=Z;if(!H&&j){let O=N(Y,j);if(f(O))try{let U=u(O,"utf-8"),{parsed:_}=T(U);if($){let R=`DOTENV_PRIVATE_KEY_${$.toUpperCase()}`;H=_[R]}else H=_.DOTENV_PRIVATE_KEY}catch(U){G.push(`Failed to load keys file: ${U instanceof Error?U.message:"Unknown error"}`)}}if(!H)H=d($||"");for(let O of W){let U=N(Y,O);if(!f(U)){if(!A)G.push(`File not found: ${U}`);continue}try{let _=u(U,"utf-8"),{parsed:R,errors:q}=T(_,{privateKey:H,processEnv:process.env});G.push(...q);let I=0;for(let[z,g]of Object.entries(R)){if(z==="DOTENV_PUBLIC_KEY")continue;let m=process.env[z],o=P(m)&&g!==m;if(X||!M.has(z)||o)process.env[z]=g,D++,I++}if(!A&&!process.env.__ENV_LOADED__)console.log(`[env] loaded ${I}/${Object.keys(R).length} variables from ${O}`),process.env.__ENV_LOADED__="1"}catch(_){G.push(`Failed to load ${U}: ${_ instanceof Error?_.message:"Unknown error"}`)}}return{loaded:D,errors:G}}function ZJ(J={}){return{name:"env-plugin",setup(Q){c(J)}}}function VJ(J={}){let Q=S(J.env)||S("development")||S(process.env.DOTENV_ENV)||S(process.env.APP_ENV)||"development",X=J.cwd||process.cwd(),$=[],Z=(Y)=>{if(!$.includes(Y)&&f(N(X,Y)))$.push(Y)};Z(".env"),Z(".env.local");let j=`.env.${Q}`,A=`.env.${Q}.local`;return Z(j),Z(A),c({...J,path:$,env:Q})}var EJ=ZJ;import{existsSync as F,readFileSync as L,writeFileSync as V}from"fs";import{resolve as C}from"path";function $J(J={}){let Q=J.cwd||process.cwd(),X=C(Q,J.file||".env"),$=C(Q,J.keysFile||".env.keys");if(!F(X))return{success:!1,error:`File not found: ${X}`};try{let Z,j;if(F($)){let H=L($,"utf-8"),{parsed:O}=T(H),R=((J.file||".env").split("/").pop()||"").replace(/^\.env\./,"").replace(/^\.env$/,"").toUpperCase(),q=R?`DOTENV_PUBLIC_KEY_${R}`:"DOTENV_PUBLIC_KEY",I=R?`DOTENV_PRIVATE_KEY_${R}`:"DOTENV_PRIVATE_KEY";if(Z=O[q]||"",j=O[I]||"",!Z||!j){let z=w();Z=z.publicKey,j=z.privateKey;let g=`
5
+ ${q}="${Z}"
6
+ ${I}="${j}"
7
+ `;V($,H+g,"utf-8")}}else{let H=w();Z=H.publicKey,j=H.privateKey;let _=((J.file||".env").split("/").pop()||"").replace(/^\.env\./,"").replace(/^\.env$/,"").toUpperCase(),R=_?`DOTENV_PUBLIC_KEY_${_}`:"DOTENV_PUBLIC_KEY",q=_?`DOTENV_PRIVATE_KEY_${_}`:"DOTENV_PRIVATE_KEY",I=`# .env.keys - Keep this file secure and never commit to source control
8
+ ${R}="${Z}"
9
+ ${q}="${j}"
10
+ `;V($,I,"utf-8")}let Y=L(X,"utf-8").split(`
11
+ `),W=[],G=J.file?J.file.replace(/^\.env\./,"").toUpperCase():"",D=G?`DOTENV_PUBLIC_KEY_${G}`:"DOTENV_PUBLIC_KEY";W.push("#/-------------------[DOTENV_PUBLIC_KEY]--------------------/"),W.push("#/ public-key encryption for .env files /"),W.push("#/ [how it works](https://stacksjs.com/encryption) /"),W.push("#/----------------------------------------------------------/"),W.push(`${D}="${Z}"`),W.push("");for(let H of Y){let O=H.trim();if(!O||O.startsWith("#")){W.push(H);continue}if(O.startsWith("DOTENV_PUBLIC_KEY"))continue;let U=O.match(/^([^=]+)=(.*)$/);if(!U||U[1]===void 0||U[2]===void 0){W.push(H);continue}let _=U[1].trim(),R=U[2].trim();if(R.startsWith('"')&&R.endsWith('"')||R.startsWith("'")&&R.endsWith("'"))R=R.slice(1,-1);let q=!0;if(J.key&&!_.includes(J.key))q=!1;if(J.excludeKey&&_.includes(J.excludeKey))q=!1;if(R.startsWith("encrypted:"))q=!1;if(q)R=x(R,Z);W.push(`${_}="${R}"`)}let M=W.join(`
12
+ `);if(J.stdout)return{success:!0,output:M};return V(X,M,"utf-8"),{success:!0,output:`\u2714 encrypted (${J.file||".env"})
13
+ \u2714 key added to ${J.keysFile||".env.keys"}`}}catch(Z){return{success:!1,error:`Failed to encrypt: ${Z instanceof Error?Z.message:"Unknown error"}`}}}function XJ(J={}){let Q=J.cwd||process.cwd(),X=C(Q,J.file||".env"),$=C(Q,J.keysFile||".env.keys");if(!F(X))return{success:!1,error:`File not found: ${X}`};if(!F($))return{success:!1,error:`Keys file not found: ${$}`};try{let Z=L($,"utf-8"),{parsed:j}=T(Z),W=((J.file||".env").split("/").pop()||"").replace(/^\.env\./,"").replace(/^\.env$/,"").toUpperCase(),G=W?`DOTENV_PRIVATE_KEY_${W}`:"DOTENV_PRIVATE_KEY",D=j[G];if(!D)return{success:!1,error:`Private key not found: ${G}`};let H=L(X,"utf-8").split(`
14
+ `),O=[];for(let _ of H){let R=_.trim();if(!R||R.startsWith("#")){O.push(_);continue}if(R.startsWith("DOTENV_PUBLIC_KEY"))continue;let q=R.match(/^([^=]+)=(.*)$/);if(!q||q[1]===void 0||q[2]===void 0){O.push(_);continue}let I=q[1].trim(),z=q[2].trim();if(z.startsWith('"')&&z.endsWith('"')||z.startsWith("'")&&z.endsWith("'"))z=z.slice(1,-1);let g=z.startsWith("encrypted:");if(J.key&&!I.includes(J.key))g=!1;if(g)z=b(z,D);O.push(`${I}="${z}"`)}let U=O.join(`
15
+ `);if(J.stdout)return{success:!0,output:U};return V(X,U,"utf-8"),{success:!0,output:`\u2714 decrypted (${J.file||".env"})`}}catch(Z){return{success:!1,error:`Failed to decrypt: ${Z instanceof Error?Z.message:"Unknown error"}`}}}function NJ(J,Q,X={}){let $=X.cwd||process.cwd(),Z=C($,X.file||".env"),j=C($,X.keysFile||".env.keys");try{let A="";if(F(Z))A=L(Z,"utf-8");let Y=A.split(`
16
+ `),W=!1,G,H=((X.file||".env").split("/").pop()||"").replace(/^\.env\./,"").replace(/^\.env$/,"").toUpperCase(),O=H?`DOTENV_PUBLIC_KEY_${H}`:"DOTENV_PUBLIC_KEY",U=H?`DOTENV_PRIVATE_KEY_${H}`:"DOTENV_PRIVATE_KEY";for(let q of Y){let I=q.trim();if(I.startsWith(`${O}=`)){let z=I.match(/^[^=]+=["']?([^"'\n]+)["']?/);if(z)G=z[1];break}}if(G){let q=!1;if(F(j)){let I=L(j,"utf-8"),{parsed:z}=T(I);q=Boolean(z[U])}if(!q)G=void 0}if(!X.plain&&!G){let q=w();G=q.publicKey;let I="";if(F(j))I=L(j,"utf-8");I+=`
17
+ ${O}="${q.publicKey}"
18
+ ${U}="${q.privateKey}"
19
+ `,V(j,I,"utf-8");for(let z=Y.length-1;z>=0;z--){let g=Y[z];if(g!==void 0&&g.trim().startsWith(`${O}=`))Y.splice(z,1)}Y.unshift(`${O}="${G}"`)}let _=Q;if(!X.plain&&G)_=x(Q,G);for(let q=0;q<Y.length;q++){let I=Y[q];if(I===void 0)continue;if(I.trim().startsWith(`${J}=`)){Y[q]=`${J}="${_}"`,W=!0;break}}if(!W)Y.push(`${J}="${_}"`);let R=Y.join(`
20
+ `);return V(Z,R,"utf-8"),{success:!0,output:`set ${J}${X.plain?"":" with encryption"} (${X.file||".env"})`}}catch(A){return{success:!1,error:`Failed to set: ${A instanceof Error?A.message:"Unknown error"}`}}}function PJ(J,Q={}){let X=Q.cwd||process.cwd(),$=C(X,Q.file||".env");if(!F($))return{success:!1,error:`File not found: ${$}`};try{let Z,j=C(X,Q.keysFile||".env.keys"),W=((Q.file||".env").split("/").pop()||"").replace(/^\.env\./,"").replace(/^\.env$/,"").toUpperCase(),G=W?`DOTENV_PRIVATE_KEY_${W}`:"DOTENV_PRIVATE_KEY";if(F(j)){let U=L(j,"utf-8"),{parsed:_}=T(U);Z=_[G]}if(!Z)Z=process.env[G];let D=L($,"utf-8"),{parsed:M}=T(D,{privateKey:Z});if(J&&!Q.all){let U=M[J];if(U===void 0)return{success:!1,error:`Key not found: ${J}`};return{success:!0,output:U}}let H=Q.all?{...process.env,...M}:M,O;switch(Q.format){case"shell":O=Object.entries(H).map(([U,_])=>`${U}=${_}`).join(" ");break;case"eval":O=Object.entries(H).map(([U,_])=>`${U}="${_}"`).join(`
21
+ `);break;case"json":default:O=Q.prettyPrint?JSON.stringify(H,null,2):JSON.stringify(H);break}return{success:!0,output:O}}catch(Z){return{success:!1,error:`Failed to get: ${Z instanceof Error?Z.message:"Unknown error"}`}}}function KJ(J,Q={}){let X=Q.cwd||process.cwd(),$=C(X,Q.keysFile||".env.keys");if(!F($))return{success:!1,error:`Keys file not found: ${$}`};try{let Z=L($,"utf-8"),{parsed:j}=T(Z),W=((Q.file||".env").split("/").pop()||"").replace(/^\.env\./,"").replace(/^\.env$/,"").toUpperCase(),G=W?`DOTENV_PUBLIC_KEY_${W}`:"DOTENV_PUBLIC_KEY",D=W?`DOTENV_PRIVATE_KEY_${W}`:"DOTENV_PRIVATE_KEY";if(J){let O=j[J];if(!O)return{success:!1,error:`Key not found: ${J}`};return{success:!0,output:O}}let M={[G]:j[G],[D]:j[D]};return{success:!0,output:Q.format==="shell"?`${G}=${M[G]} ${D}=${M[D]}`:JSON.stringify(M)}}catch(Z){return{success:!1,error:`Failed to get keypair: ${Z instanceof Error?Z.message:"Unknown error"}`}}}function hJ(J={}){let Q=XJ({file:J.file,keysFile:J.keysFile,stdout:!0,cwd:J.cwd});if(!Q.success)return Q;let X=J.cwd||process.cwd(),$=C(X,J.file||".env"),Z=C(X,J.keysFile||".env.keys");if(Q.output)V($,Q.output,"utf-8");let j=w(),Y=L(Z,"utf-8").split(`
22
+ `),W=J.file?J.file.replace(/^\.env\./,"").toUpperCase():"",G=W?`DOTENV_PUBLIC_KEY_${W}`:"DOTENV_PUBLIC_KEY",D=W?`DOTENV_PRIVATE_KEY_${W}`:"DOTENV_PRIVATE_KEY";for(let M=0;M<Y.length;M++){let H=Y[M];if(H===void 0)continue;if(H.startsWith(`${G}=`))Y[M]=`${G}="${j.publicKey}"`;else if(H.startsWith(`${D}=`))Y[M]=`${D}="${j.privateKey}"`}return V(Z,Y.join(`
23
+ `),"utf-8"),$J({file:J.file,keysFile:J.keysFile,key:J.key,excludeKey:J.excludeKey,stdout:J.stdout,cwd:J.cwd})}import B from"process";import{platform as jJ}from"os";var v=typeof Bun<"u",y=typeof B<"u"&&B.versions?.node!==void 0,GJ=v?"bun":y?"node":"unknown",uJ={name:GJ,version:v?Bun.version:y?B.version:void 0},h=jJ(),cJ=h==="win32",vJ=h==="darwin",yJ=h==="linux",l=Boolean(B.stdout?.isTTY),lJ=typeof globalThis.window<"u",WJ=Boolean(B.env.CI||B.env.CONTINUOUS_INTEGRATION||B.env.BUILD_NUMBER||B.env.RUN_ID),pJ=Boolean(B.env.DEBUG||B.env.VERBOSE||B.argv.includes("--debug")||B.argv.includes("--verbose")),YJ=WJ||!l,iJ=Boolean(!YJ&&(l||B.env.COLORTERM||B.env.FORCE_COLOR||B.env.TERM&&B.env.TERM!=="dumb")),K={github:{name:"GitHub Actions",detected:Boolean(B.env.GITHUB_ACTIONS)},gitlab:{name:"GitLab CI",detected:Boolean(B.env.GITLAB_CI)},circle:{name:"CircleCI",detected:Boolean(B.env.CIRCLECI)},travis:{name:"Travis CI",detected:Boolean(B.env.TRAVIS)},jenkins:{name:"Jenkins",detected:Boolean(B.env.JENKINS_URL)},vercel:{name:"Vercel",detected:Boolean(B.env.VERCEL)},netlify:{name:"Netlify",detected:Boolean(B.env.NETLIFY)},heroku:{name:"Heroku",detected:Boolean(B.env.DYNO)},aws:{name:"AWS",detected:Boolean(B.env.AWS_REGION||B.env.AWS_LAMBDA_FUNCTION_NAME)},azure:{name:"Azure",detected:Boolean(B.env.AZURE_HTTP_USER_AGENT)},cloudflare:{name:"Cloudflare",detected:Boolean(B.env.CF_PAGES)},railway:{name:"Railway",detected:Boolean(B.env.RAILWAY_ENVIRONMENT)},render:{name:"Render",detected:Boolean(B.env.RENDER)}},OJ=Object.keys(K).find((J)=>{let Q=K[J];return Q!==void 0&&Q.detected})||"unknown",nJ=K[OJ]||{name:"Unknown",detected:!1};import AJ from"process";import{projectPath as HJ}from"@stacksjs/path";import i from"fs";var p={APP_ENV:["local","dev","development","staging","prod","production"],DB_CONNECTION:["mysql","sqlite","postgres","dynamodb"],DB_MIGRATE_FRESH:["allow","confirm","disabled"],MAIL_MAILER:["smtp","mailgun","ses","log","sendgrid","mailtrap"],SEARCH_ENGINE_DRIVER:["opensearch","meilisearch","algolia","typesense"],FRONTEND_APP_ENV:["development","staging","production"]};var UJ={get:(J,Q)=>{let X=J[Q],$=["_PORT","_TIMEOUT","_TTL","_SIZE","_LIMIT","_MAX","_MIN","_INTERVAL","_RETRIES","_CONCURRENCY","_WORKERS","_CONNECTIONS"];if(typeof X==="string"&&/^\d+$/.test(X)&&!X.startsWith("0")&&$.some((Z)=>Q.endsWith(Z)))return Number(X);if(typeof X==="string"){let Z=X.toLowerCase();if(Z==="true")return!0;if(Z==="false")return!1}return X}};function _J(){return typeof Bun<"u"?Bun.env:AJ.env}var n=new Proxy(_J(),UJ);function JQ(J,Q,X){let $=X?.path||HJ(".env"),j=i.readFileSync($,"utf-8").split(`
24
+ `),A=j.findIndex((G)=>G.startsWith(`${J}=`)),W=/[\s"'#$\\]/.test(Q)?`"${Q.replace(/"/g,"\\\"")}"`:Q;if(A!==-1)j[A]=`${J}=${W}`;else j.push(`${J}=${W}`);i.writeFileSync($,j.join(`
25
+ `))}function QQ(J=n){let Q=[];for(let[X,$]of Object.entries(p)){let Z=J[X];if(Z!==void 0&&Z!==""&&!$.includes(String(Z)))Q.push(`${X}="${Z}" is not valid. Allowed values: ${$.join(", ")}`)}return Q}function ZQ(J,Q=n){let X=[];for(let $ of J){let Z=Q[$];if(Z===void 0||Z===""||Z===null)X.push($)}if(X.length>0)throw Error(`[env] Missing required environment variable(s): ${X.join(", ")}. Set them in .env or your process environment before booting.`);return Q}export{JQ as writeEnv,QQ as validateEnv,NJ as setEnv,uJ as runtimeInfo,GJ as runtime,hJ as rotateKeypair,ZQ as requireEnv,nJ as providerInfo,OJ as provider,_J as process,h as platform,BJ as parseEnvFromKey,T as parse,zJ as loadEnvFiles,c as loadEnv,cJ as isWindows,y as isNode,YJ as isMinimal,vJ as isMacOS,yJ as isLinux,pJ as isDebug,iJ as isColorSupported,WJ as isCI,v as isBun,lJ as hasWindow,l as hasTTY,d as getPrivateKey,KJ as getKeypair,PJ as getEnv,w as generateKeypair,ZJ as envPlugin,p as envEnum,n as env,x as encryptValue,$J as encryptEnv,b as decryptValue,XJ as decryptEnv,VJ as autoLoadEnv,a as aesEncrypt,t as aesDecrypt};
package/dist/plugin.js CHANGED
@@ -1,4 +1,4 @@
1
1
  // @bun
2
- import{createCipheriv as K,createDecipheriv as P,createHash as H,randomBytes as w}from"crypto";function V(R,j){let U=w(16),I=j.length===32?j:Buffer.from(j.toString("hex").slice(0,64),"hex"),X=K("aes-256-gcm",I,U),J=Buffer.concat([X.update(R,"utf8"),X.final()]),Y=X.getAuthTag();return{ciphertext:J.toString("hex"),iv:U.toString("hex"),authTag:Y.toString("hex")}}function f(R,j,U,I){let X=j.length===32?j:Buffer.from(j.toString("hex").slice(0,64),"hex");try{let J=P("aes-256-gcm",X,Buffer.from(U,"hex"));return J.setAuthTag(Buffer.from(I,"hex")),Buffer.concat([J.update(Buffer.from(R,"hex")),J.final()]).toString("utf8")}catch(J){throw Error(`Decryption failed (data may be corrupted or key is incorrect): ${J instanceof Error?J.message:String(J)}`)}}function y(){let R=w(32);return{publicKey:H("sha256").update(R).digest().toString("hex"),privateKey:R.toString("hex")}}function u(R,j){let U=H("sha256").update(Buffer.from(j,"hex")).digest(),{ciphertext:I,iv:X,authTag:J}=V(R,U);return`encrypted:${Buffer.concat([Buffer.from(X,"hex"),Buffer.from(J,"hex"),Buffer.from(I,"hex")]).toString("base64")}`}function b(R,j){if(!R.startsWith("encrypted:"))return R;let U=R.slice(10),I=Buffer.from(U,"base64");if(I.length<32)throw Error("Invalid encrypted data: payload too short (need at least iv + authTag = 32 bytes)");let X=I.subarray(0,16).toString("hex"),J=I.subarray(16,32).toString("hex"),Y=I.subarray(32).toString("hex"),Z=H("sha256").update(Buffer.from(j,"hex")).digest(),$=H("sha256").update(Z).digest();return f(Y,$,X,J)}function c(R){let j=R.match(/^DOTENV_PRIVATE_KEY_(.+)$/);return j&&j[1]?j[1].toLowerCase():""}function F(R=""){if(!R)return process.env.DOTENV_PRIVATE_KEY;let j=`DOTENV_PRIVATE_KEY_${R.toUpperCase()}`;return process.env[j]}function L(R,j={}){let U={},I=[],X=R.split(`
3
- `);for(let J of X){let Y=J.trim();if(!Y||Y.startsWith("#"))continue;if(Y.startsWith("DOTENV_PUBLIC_KEY=")){let z=Y.match(/^DOTENV_PUBLIC_KEY=["']?([^"'\n]+)["']?/);if(z&&z[1]!==void 0)U.DOTENV_PUBLIC_KEY=z[1];continue}let Z=Y.match(/^([^=]+)=(.*)$/);if(!Z||Z[1]===void 0||Z[2]===void 0)continue;let $=Z[1].trim(),Q=Z[2].trim();if(Q.startsWith('"')&&Q.endsWith('"')||Q.startsWith("'")&&Q.endsWith("'")){if(Q=Q.slice(1,-1),Q.includes("\\n"))Q=Q.replace(/\\n/g,`
4
- `)}if(j.privateKey&&(Q.startsWith("encrypted:")||Q.startsWith("enc:")))try{let z=Q.startsWith("enc:")?`encrypted:${Q.slice(4)}`:Q;Q=b(z,j.privateKey)}catch(z){I.push(`Failed to decrypt ${$}: ${z instanceof Error?z.message:"Unknown error"}`)}Q=m(Q,{...j.processEnv||process.env,...U}),Q=k(Q),U[$]=Q}return{parsed:U,errors:I}}function m(R,j){return R.replace(/\$\{([^}]+)\}/g,(U,I)=>{let X=I.match(/^([^:\-+]+)(:-|-)(.+)$/);if(X){let[,Y,Z,$]=X,Q=j[Y];if(Z===":-")return Q||$;else return Q!==void 0?Q:$}let J=I.match(/^([^:\-+]+)(:?\+)(.+)$/);if(J){let[,Y,Z,$]=J,Q=j[Y];if(Z===":+")return Q?$:"";else return Q!==void 0?$:""}return j[I]||""})}var x=new Set(["date","hostname","whoami","uname","pwd","echo","printf","cat","basename","dirname"]);function k(R){return R.replace(/\$\(([^)]+)\)/g,(j,U)=>{try{let I=U.trim().split(/\s+/),X=I[0];if(!X||!x.has(X))return console.warn(`[env] Blocked command substitution for disallowed command: ${X}`),"";let J=Bun.spawnSync(I,{stdout:"pipe",stderr:"pipe"});if(J.exitCode===0)return new TextDecoder().decode(J.stdout).trim();console.warn(`[env] Command substitution failed (exit code ${J.exitCode}): ${X}`)}catch(I){console.warn(`[env] Command substitution error: ${I instanceof Error?I.message:String(I)}`)}return""})}async function i(R,j={}){let U={},I=[];for(let X of R)try{let J=Bun.file(X);if(!J.size)continue;let Y=await J.text(),{parsed:Z,errors:$}=L(Y,j);I.push(...$);for(let[Q,z]of Object.entries(Z)){if(!j.overload&&U[Q]!==void 0)continue;U[Q]=z}}catch(J){if(J?.code==="ENOENT")continue;I.push(`Failed to read ${X}: ${J instanceof Error?J.message:String(J)}`)}return{parsed:U,errors:I}}import{existsSync as A}from"fs";import{readFileSync as E}from"fs";import{resolve as O}from"path";function N(R={}){let{path:j=[".env"],overload:U=!1,env:I,privateKey:X,keysFile:J,quiet:Y=!1,cwd:Z=process.cwd()}=R,$=Array.isArray(j)?j:[j],Q=[],z=0,q=X;if(!q&&J){let _=O(Z,J);if(A(_))try{let G=E(_,"utf-8"),{parsed:W}=L(G);if(I){let C=`DOTENV_PRIVATE_KEY_${I.toUpperCase()}`;q=W[C]}else q=W.DOTENV_PRIVATE_KEY}catch(G){Q.push(`Failed to load keys file: ${G instanceof Error?G.message:"Unknown error"}`)}}if(!q)q=F(I||"");for(let _ of $){let G=O(Z,_);if(!A(G)){if(!Y)Q.push(`File not found: ${G}`);continue}try{let W=E(G,"utf-8"),{parsed:C,errors:S}=L(W,{privateKey:q,processEnv:process.env});Q.push(...S);let D=0;for(let[T,M]of Object.entries(C)){if(T==="DOTENV_PUBLIC_KEY")continue;let B=process.env[T],g=typeof B==="string"&&(B.startsWith("encrypted:")||B.startsWith("enc:"))&&M!==B;if(U||B===void 0||g)process.env[T]=M,z++,D++}if(!Y&&!process.env.__ENV_LOADED__)console.log(`[env] loaded ${D}/${Object.keys(C).length} variables from ${_}`),process.env.__ENV_LOADED__="1"}catch(W){Q.push(`Failed to load ${G}: ${W instanceof Error?W.message:"Unknown error"}`)}}return{loaded:z,errors:Q}}function h(R={}){return{name:"env-plugin",setup(j){N(R)}}}function e(R={}){let j=R.env||"development",U=R.cwd||process.cwd(),I=[],X=`.env.${j}`,J=`.env.${j}.local`;if(A(O(U,J)))I.push(J);if(A(O(U,X)))I.push(X);if(A(O(U,".env.local")))I.push(".env.local");if(A(O(U,".env")))I.push(".env");return N({...R,path:I,env:j})}var Ij=h;export{N as loadEnv,h as envPlugin,Ij as default,e as autoLoadEnv};
2
+ import{createCipheriv as x,createDecipheriv as f,createHash as I,randomBytes as S}from"crypto";function k(J,j){let Y=S(16),Q=j.length===32?j:Buffer.from(j.toString("hex").slice(0,64),"hex"),X=x("aes-256-gcm",Q,Y),U=Buffer.concat([X.update(J,"utf8"),X.final()]),Z=X.getAuthTag();return{ciphertext:U.toString("hex"),iv:Y.toString("hex"),authTag:Z.toString("hex")}}function m(J,j,Y,Q){let X=j.length===32?j:Buffer.from(j.toString("hex").slice(0,64),"hex");try{let U=f("aes-256-gcm",X,Buffer.from(Y,"hex"));return U.setAuthTag(Buffer.from(Q,"hex")),Buffer.concat([U.update(Buffer.from(J,"hex")),U.final()]).toString("utf8")}catch(U){throw Error(`Decryption failed (data may be corrupted or key is incorrect): ${U instanceof Error?U.message:String(U)}`)}}function p(){let J=S(32);return{publicKey:I("sha256").update(J).digest().toString("hex"),privateKey:J.toString("hex")}}function v(J,j){let Y=I("sha256").update(Buffer.from(j,"hex")).digest(),{ciphertext:Q,iv:X,authTag:U}=k(J,Y);return`encrypted:${Buffer.concat([Buffer.from(X,"hex"),Buffer.from(U,"hex"),Buffer.from(Q,"hex")]).toString("base64")}`}function g(J,j){if(!J.startsWith("encrypted:"))return J;let Y=J.slice(10),Q=Buffer.from(Y,"base64");if(Q.length<32)throw Error("Invalid encrypted data: payload too short (need at least iv + authTag = 32 bytes)");let X=Q.subarray(0,16).toString("hex"),U=Q.subarray(16,32).toString("hex"),Z=Q.subarray(32).toString("hex"),$=I("sha256").update(Buffer.from(j,"hex")).digest(),G=I("sha256").update($).digest();return m(Z,G,X,U)}function i(J){let j=J.match(/^DOTENV_PRIVATE_KEY_(.+)$/);return j&&j[1]?j[1].toLowerCase():""}function z(J=""){if(!J)return process.env.DOTENV_PRIVATE_KEY;let j=`DOTENV_PRIVATE_KEY_${J.toUpperCase()}`;return process.env[j]}function L(J,j={}){let Y={},Q=[],X=J.split(`
3
+ `);for(let U of X){let Z=U.trim();if(!Z||Z.startsWith("#"))continue;if(Z.startsWith("DOTENV_PUBLIC_KEY=")){let W=Z.match(/^DOTENV_PUBLIC_KEY=["']?([^"'\n]+)["']?/);if(W&&W[1]!==void 0)Y.DOTENV_PUBLIC_KEY=W[1];continue}let $=Z.match(/^([^=]+)=(.*)$/);if(!$||$[1]===void 0||$[2]===void 0)continue;let G=$[1].trim(),R=$[2].trim();if(R.startsWith('"')&&R.endsWith('"')||R.startsWith("'")&&R.endsWith("'")){if(R=R.slice(1,-1),R.includes("\\n"))R=R.replace(/\\n/g,`
4
+ `)}if(j.privateKey&&(R.startsWith("encrypted:")||R.startsWith("enc:")))try{let W=R.startsWith("enc:")?`encrypted:${R.slice(4)}`:R;R=g(W,j.privateKey)}catch(W){Q.push(`Failed to decrypt ${G}: ${W instanceof Error?W.message:"Unknown error"}`)}R=h(R,{...j.processEnv||process.env,...Y}),R=d(R),Y[G]=R}return{parsed:Y,errors:Q}}function h(J,j){return J.replace(/\$\{([^}]+)\}/g,(Y,Q)=>{let X=Q.match(/^([^:\-+]+)(:-|-)(.+)$/);if(X){let[,Z,$,G]=X,R=j[Z];if($===":-")return R||G;else return R!==void 0?R:G}let U=Q.match(/^([^:\-+]+)(:?\+)(.+)$/);if(U){let[,Z,$,G]=U,R=j[Z];if($===":+")return R?G:"";else return R!==void 0?G:""}return j[Q]||""})}var c=new Set(["date","hostname","whoami","uname","pwd","echo","printf","cat","basename","dirname"]);function d(J){return J.replace(/\$\(([^)]+)\)/g,(j,Y)=>{try{let Q=Y.trim().split(/\s+/),X=Q[0];if(!X||!c.has(X))return console.warn(`[env] Blocked command substitution for disallowed command: ${X}`),"";let U=Bun.spawnSync(Q,{stdout:"pipe",stderr:"pipe"});if(U.exitCode===0)return new TextDecoder().decode(U.stdout).trim();console.warn(`[env] Command substitution failed (exit code ${U.exitCode}): ${X}`)}catch(Q){console.warn(`[env] Command substitution error: ${Q instanceof Error?Q.message:String(Q)}`)}return""})}async function n(J,j={}){let Y={},Q=[];for(let X of J)try{let U=Bun.file(X);if(!U.size)continue;let Z=await U.text(),{parsed:$,errors:G}=L(Z,j);Q.push(...G);for(let[R,W]of Object.entries($)){if(!j.overload&&Y[R]!==void 0)continue;Y[R]=W}}catch(U){if(U?.code==="ENOENT")continue;Q.push(`Failed to read ${X}: ${U instanceof Error?U.message:String(U)}`)}return{parsed:Y,errors:Q}}import{existsSync as H}from"fs";import{readFileSync as N}from"fs";import{resolve as T}from"path";function D(J){return typeof J==="string"&&(J.startsWith("encrypted:")||J.startsWith("enc:"))}function C(J){if(!J||D(J))return;let j=J.trim().toLowerCase();if(!/^[a-z0-9_-]+$/.test(j))return;if(j==="prod")return"production";if(j==="stage")return"staging";if(j==="dev")return"development";return j}function E(J={}){let{path:j=[".env"],overload:Y=!1,env:Q,privateKey:X,keysFile:U=".env.keys",quiet:Z=!1,cwd:$=process.cwd()}=J,G=Array.isArray(j)?j:[j],R=[],W=0,K=new Set(Object.entries(process.env).filter(([,q])=>q!==void 0&&!D(q)).map(([q])=>q)),O=X;if(!O&&U){let q=T($,U);if(H(q))try{let A=N(q,"utf-8"),{parsed:_}=L(A);if(Q){let w=`DOTENV_PRIVATE_KEY_${Q.toUpperCase()}`;O=_[w]}else O=_.DOTENV_PRIVATE_KEY}catch(A){R.push(`Failed to load keys file: ${A instanceof Error?A.message:"Unknown error"}`)}}if(!O)O=z(Q||"");for(let q of G){let A=T($,q);if(!H(A)){if(!Z)R.push(`File not found: ${A}`);continue}try{let _=N(A,"utf-8"),{parsed:w,errors:P}=L(_,{privateKey:O,processEnv:process.env});R.push(...P);let F=0;for(let[B,M]of Object.entries(w)){if(B==="DOTENV_PUBLIC_KEY")continue;let b=process.env[B],V=D(b)&&M!==b;if(Y||!K.has(B)||V)process.env[B]=M,W++,F++}if(!Z&&!process.env.__ENV_LOADED__)console.log(`[env] loaded ${F}/${Object.keys(w).length} variables from ${q}`),process.env.__ENV_LOADED__="1"}catch(_){R.push(`Failed to load ${A}: ${_ instanceof Error?_.message:"Unknown error"}`)}}return{loaded:W,errors:R}}function y(J={}){return{name:"env-plugin",setup(j){E(J)}}}function Qj(J={}){let j=C(J.env)||C("development")||C(process.env.DOTENV_ENV)||C(process.env.APP_ENV)||"development",Y=J.cwd||process.cwd(),Q=[],X=($)=>{if(!Q.includes($)&&H(T(Y,$)))Q.push($)};X(".env"),X(".env.local");let U=`.env.${j}`,Z=`.env.${j}.local`;return X(U),X(Z),E({...J,path:Q,env:j})}var Uj=y;export{E as loadEnv,y as envPlugin,Uj as default,Qj as autoLoadEnv};
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@stacksjs/env",
3
3
  "type": "module",
4
4
  "sideEffects": false,
5
- "version": "0.70.98",
5
+ "version": "0.70.100",
6
6
  "description": "Stacks env helper methods.",
7
7
  "author": "Chris Breuer",
8
8
  "contributors": [
@@ -51,7 +51,7 @@
51
51
  },
52
52
  "devDependencies": {
53
53
  "better-dx": "^0.2.16",
54
- "@stacksjs/path": "0.70.98",
55
- "@stacksjs/validation": "0.70.98"
54
+ "@stacksjs/path": "0.70.100",
55
+ "@stacksjs/validation": "0.70.100"
56
56
  }
57
57
  }