@stacksjs/env 0.70.87 → 0.70.90
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 +21 -21
- package/dist/plugin.js +2 -2
- package/package.json +3 -3
package/dist/index.js
CHANGED
|
@@ -1,25 +1,25 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{createCipheriv as
|
|
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
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=
|
|
5
|
-
${
|
|
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
6
|
${M}="${X}"
|
|
7
|
-
`;
|
|
8
|
-
${
|
|
9
|
-
${
|
|
10
|
-
`;
|
|
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
|
|
12
|
-
`);if(J.stdout)return{success:!0,output:
|
|
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
|
|
14
|
-
`),O=[];for(let B of
|
|
15
|
-
`);if(J.stdout)return{success:!0,output:U};return
|
|
16
|
-
`),G=!1,j,
|
|
17
|
-
${O}="${
|
|
18
|
-
${U}="${
|
|
19
|
-
`,
|
|
20
|
-
`);return
|
|
21
|
-
`);break;case"json":default:O=Q.prettyPrint?JSON.stringify(
|
|
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
|
|
23
|
-
`),"utf-8"),
|
|
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
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
|
|
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};
|
package/dist/plugin.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{createCipheriv as
|
|
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
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=
|
|
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};
|
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.
|
|
5
|
+
"version": "0.70.90",
|
|
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.
|
|
55
|
-
"@stacksjs/validation": "0.70.
|
|
54
|
+
"@stacksjs/path": "0.70.90",
|
|
55
|
+
"@stacksjs/validation": "0.70.90"
|
|
56
56
|
}
|
|
57
57
|
}
|