@stacksjs/env 0.74.20 → 0.74.22
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 +2 -2
- package/dist/index.js +16 -16
- package/dist/parser.js +1 -1
- package/dist/plugin.js +2 -2
- package/package.json +3 -3
package/dist/cli.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{createCipheriv as U,createDecipheriv as L,createHash as W,createPrivateKey as ae,createPublicKey as j,diffieHellman as X,generateKeyPairSync as H,hkdfSync as J,randomBytes as B}from"crypto";var I="x25519-public:",S="x25519-private:",D="encrypted:v2:",Y="encrypted:",M=Buffer.from("stacks-env:v2","utf8"),z="Environment decryption failed: authentication or format error";function G(t){if(t.length===32)return t;return W("sha256").update(t).digest()}function Fe(t,n){let e=B(16),s=U("aes-256-gcm",G(n),e);return{ciphertext:Buffer.concat([s.update(t,"utf8"),s.final()]).toString("hex"),iv:e.toString("hex"),authTag:s.getAuthTag().toString("hex")}}function ue(t,n,e,s){try{let r=L("aes-256-gcm",G(n),Buffer.from(e,"hex"));return r.setAuthTag(Buffer.from(s,"hex")),Buffer.concat([r.update(Buffer.from(t,"hex")),r.final()]).toString("utf8")}catch{throw Error("Decryption failed: authentication or format error")}}function _(t){return t.toString("base64url")}function x(t,n,e){if(typeof t!=="string"||t.length>0&&!/^[A-Za-z0-9_-]+$/.test(t))throw Error(`${n} is not canonical base64url`);let s=Buffer.from(t,"base64url");if(_(s)!==t)throw Error(`${n} is not canonical base64url`);if(e!==void 0&&s.length!==e)throw Error(`${n} has an invalid length`);return s}function fe(t){if(!t.startsWith(I))throw Error("Legacy or invalid public key. Run buddy env:rotate before creating new ciphertext.");let n=j({key:x(t.slice(I.length),"public key"),format:"der",type:"spki"});if(n.asymmetricKeyType!=="x25519")throw Error("Public key is not X25519");return n}function le(t){if(!t.startsWith(S))throw Error("Private key is not a version 2 X25519 key");let n=ae({key:x(t.slice(S.length),"private key"),format:"der",type:"pkcs8"});if(n.asymmetricKeyType!=="x25519")throw Error("Private key is not X25519");return n}function q(t){return Buffer.from(`stacks-env:v2;${t.epk};${t.salt};${t.nonce}`,"utf8")}function V(){let{publicKey:t,privateKey:n}=H("x25519"),e=t.export({format:"der",type:"spki"}),s=n.export({format:"der",type:"pkcs8"});return{publicKey:`${I}${_(e)}`,privateKey:`${S}${_(s)}`}}function F(t,n){let e=fe(n),s=H("x25519"),r=_(s.publicKey.export({format:"der",type:"spki"})),i=B(16),c=B(12),a=X({privateKey:s.privateKey,publicKey:e}),u=Buffer.from(J("sha256",a,i,M,32)),f={epk:r,salt:_(i),nonce:_(c)};try{let o=U("aes-256-gcm",u,c);o.setAAD(q(f));let l=Buffer.concat([o.update(t,"utf8"),o.final()]),d={v:2,...f,ciphertext:_(l),tag:_(o.getAuthTag())};return`${D}${_(Buffer.from(JSON.stringify(d),"utf8"))}`}finally{a.fill(0),u.fill(0)}}function pe(t){let n=x(t.slice(D.length),"envelope").toString("utf8"),e=JSON.parse(n);if(!e||typeof e!=="object"||Array.isArray(e))throw Error("envelope is not an object");let s=Object.keys(e).sort(),r=["ciphertext","epk","nonce","salt","tag","v"];if(s.length!==r.length||s.some((i,c)=>i!==r[c]))throw Error("envelope fields are invalid");if(e.v!==2)throw Error("envelope version is unsupported");for(let i of["epk","salt","nonce","ciphertext","tag"])if(typeof e[i]!=="string")throw Error(`${i} is invalid`);return e}function de(t,n){try{let e=pe(t),s=le(n),r=j({key:x(e.epk,"ephemeral public key"),format:"der",type:"spki"});if(r.asymmetricKeyType!=="x25519")throw Error("ephemeral key is not X25519");let i=x(e.salt,"salt",16),c=x(e.nonce,"nonce",12),a=x(e.ciphertext,"ciphertext"),u=x(e.tag,"tag",16),f=X({privateKey:s,publicKey:r}),o=Buffer.from(J("sha256",f,i,M,32));try{let l=L("aes-256-gcm",o,c);return l.setAAD(q(e)),l.setAuthTag(u),Buffer.concat([l.update(a),l.final()]).toString("utf8")}finally{f.fill(0),o.fill(0)}}catch{throw Error(z)}}function ye(t,n){try{if(!/^[0-9a-f]{64}$/.test(n))throw Error("invalid legacy private key");let e=Buffer.from(t.slice(Y.length),"base64");if(e.length<32)throw Error("invalid legacy payload");let s=W("sha256").update(Buffer.from(n,"hex")).digest(),r=W("sha256").update(s).digest();return ue(e.subarray(32).toString("hex"),r,e.subarray(0,16).toString("hex"),e.subarray(16,32).toString("hex"))}catch{throw Error(z)}}function Re(t){return t.startsWith(Y)&&!t.startsWith(D)}function O(t,n){if(!t.startsWith(Y))return t;return t.startsWith(D)?de(t,n):ye(t,n)}function Ce(t,n,e){return F(O(t,n),e)}function We(t){let n=t.match(/^DOTENV_PRIVATE_KEY_(.+)$/);return n&&n[1]?n[1].toLowerCase():""}function Be(t=""){return t?process.env[`DOTENV_PRIVATE_KEY_${t.toUpperCase()}`]:process.env.DOTENV_PRIVATE_KEY}import{spawnSync as ge}from"child_process";import{readFileSync as he}from"fs";import{arch as me,hostname as ve,platform as Z,release as Ee,userInfo as $e}from"os";import{basename as ke,dirname as Ke,resolve as we}from"path";function P(t,n={}){let e={},s=[],r=[],i=t.split(`
|
|
2
|
+
import{existsSync as w,readFileSync as K,renameSync as Q,rmSync as ee,writeFileSync as b}from"fs";import{basename as te,dirname as ne,resolve as k}from"path";import{createCipheriv as U,createDecipheriv as L,createHash as W,createPrivateKey as ae,createPublicKey as j,diffieHellman as X,generateKeyPairSync as H,hkdfSync as J,randomBytes as B}from"crypto";var I="x25519-public:",S="x25519-private:",D="encrypted:v2:",Y="encrypted:",M=Buffer.from("stacks-env:v2","utf8"),z="Environment decryption failed: authentication or format error";function G(t){if(t.length===32)return t;return W("sha256").update(t).digest()}function Fe(t,n){let e=B(16),s=U("aes-256-gcm",G(n),e);return{ciphertext:Buffer.concat([s.update(t,"utf8"),s.final()]).toString("hex"),iv:e.toString("hex"),authTag:s.getAuthTag().toString("hex")}}function ue(t,n,e,s){try{let r=L("aes-256-gcm",G(n),Buffer.from(e,"hex"));return r.setAuthTag(Buffer.from(s,"hex")),Buffer.concat([r.update(Buffer.from(t,"hex")),r.final()]).toString("utf8")}catch{throw Error("Decryption failed: authentication or format error")}}function _(t){return t.toString("base64url")}function x(t,n,e){if(typeof t!=="string"||t.length>0&&!/^[A-Za-z0-9_-]+$/.test(t))throw Error(`${n} is not canonical base64url`);let s=Buffer.from(t,"base64url");if(_(s)!==t)throw Error(`${n} is not canonical base64url`);if(e!==void 0&&s.length!==e)throw Error(`${n} has an invalid length`);return s}function fe(t){if(!t.startsWith(I))throw Error("Legacy or invalid public key. Run buddy env:rotate before creating new ciphertext.");let n=j({key:x(t.slice(I.length),"public key"),format:"der",type:"spki"});if(n.asymmetricKeyType!=="x25519")throw Error("Public key is not X25519");return n}function le(t){if(!t.startsWith(S))throw Error("Private key is not a version 2 X25519 key");let n=ae({key:x(t.slice(S.length),"private key"),format:"der",type:"pkcs8"});if(n.asymmetricKeyType!=="x25519")throw Error("Private key is not X25519");return n}function q(t){return Buffer.from(`stacks-env:v2;${t.epk};${t.salt};${t.nonce}`,"utf8")}function V(){let{publicKey:t,privateKey:n}=H("x25519"),e=t.export({format:"der",type:"spki"}),s=n.export({format:"der",type:"pkcs8"});return{publicKey:`${I}${_(e)}`,privateKey:`${S}${_(s)}`}}function F(t,n){let e=fe(n),s=H("x25519"),r=_(s.publicKey.export({format:"der",type:"spki"})),i=B(16),c=B(12),a=X({privateKey:s.privateKey,publicKey:e}),u=Buffer.from(J("sha256",a,i,M,32)),f={epk:r,salt:_(i),nonce:_(c)};try{let o=U("aes-256-gcm",u,c);o.setAAD(q(f));let l=Buffer.concat([o.update(t,"utf8"),o.final()]),d={v:2,...f,ciphertext:_(l),tag:_(o.getAuthTag())};return`${D}${_(Buffer.from(JSON.stringify(d),"utf8"))}`}finally{a.fill(0),u.fill(0)}}function pe(t){let n=x(t.slice(D.length),"envelope").toString("utf8"),e=JSON.parse(n);if(!e||typeof e!=="object"||Array.isArray(e))throw Error("envelope is not an object");let s=Object.keys(e).sort(),r=["ciphertext","epk","nonce","salt","tag","v"];if(s.length!==r.length||s.some((i,c)=>i!==r[c]))throw Error("envelope fields are invalid");if(e.v!==2)throw Error("envelope version is unsupported");for(let i of["epk","salt","nonce","ciphertext","tag"])if(typeof e[i]!=="string")throw Error(`${i} is invalid`);return e}function de(t,n){try{let e=pe(t),s=le(n),r=j({key:x(e.epk,"ephemeral public key"),format:"der",type:"spki"});if(r.asymmetricKeyType!=="x25519")throw Error("ephemeral key is not X25519");let i=x(e.salt,"salt",16),c=x(e.nonce,"nonce",12),a=x(e.ciphertext,"ciphertext"),u=x(e.tag,"tag",16),f=X({privateKey:s,publicKey:r}),o=Buffer.from(J("sha256",f,i,M,32));try{let l=L("aes-256-gcm",o,c);return l.setAAD(q(e)),l.setAuthTag(u),Buffer.concat([l.update(a),l.final()]).toString("utf8")}finally{f.fill(0),o.fill(0)}}catch{throw Error(z)}}function ye(t,n){try{if(!/^[0-9a-f]{64}$/.test(n))throw Error("invalid legacy private key");let e=Buffer.from(t.slice(Y.length),"base64");if(e.length<32)throw Error("invalid legacy payload");let s=W("sha256").update(Buffer.from(n,"hex")).digest(),r=W("sha256").update(s).digest();return ue(e.subarray(32).toString("hex"),r,e.subarray(0,16).toString("hex"),e.subarray(16,32).toString("hex"))}catch{throw Error(z)}}function Re(t){return t.startsWith(Y)&&!t.startsWith(D)}function O(t,n){if(!t.startsWith(Y))return t;return t.startsWith(D)?de(t,n):ye(t,n)}function Ce(t,n,e){return F(O(t,n),e)}function We(t){let n=t.match(/^DOTENV_PRIVATE_KEY_(.+)$/);return n&&n[1]?n[1].toLowerCase():""}function Be(t=""){return t?process.env[`DOTENV_PRIVATE_KEY_${t.toUpperCase()}`]:process.env.DOTENV_PRIVATE_KEY}import{spawnSync as ge}from"child_process";import{readFileSync as he}from"fs";import{arch as me,hostname as ve,platform as Z,release as Ee,userInfo as $e}from"os";import{basename as ke,dirname as Ke,resolve as we}from"path";function P(t,n={}){let e={},s=[],r=[],i=t.split(`
|
|
3
3
|
`);for(let c of i){let a=c.trim();if(!a||a.startsWith("#"))continue;if(a.startsWith("DOTENV_PUBLIC_KEY=")){let l=a.match(/^DOTENV_PUBLIC_KEY=["']?([^"'\n]+)["']?/);if(l&&l[1]!==void 0)e.DOTENV_PUBLIC_KEY=l[1];continue}let u=a.match(/^([^=]+)=(.*)$/);if(!u||u[1]===void 0||u[2]===void 0)continue;let f=u[1].trim(),o=u[2].trim();if(o.startsWith('"')&&o.endsWith('"')||o.startsWith("'")&&o.endsWith("'")){if(o=o.slice(1,-1),o.includes("\\n"))o=o.replace(/\\n/g,`
|
|
4
|
-
`)}if(o.startsWith("encrypted:")||o.startsWith("enc:")){if(!n.privateKey){r.push(f);continue}try{let l=o.startsWith("enc:")?`encrypted:${o.slice(4)}`:o;o=O(l,n.privateKey)}catch(l){s.push(`Failed to decrypt ${f}: ${l instanceof Error?l.message:"Unknown error"}`)}}o=be(o,{...n.processEnv||process.env,...e}),o=Pe(o),e[f]=o}return{parsed:e,errors:s,skippedEncrypted:r}}function be(t,n){return t.replace(/\$\{([^}]+)\}/g,(e,s)=>{let r=s.match(/^([^:\-+]+)(:-|-)(.+)$/);if(r){let[,c,a,u]=r,f=n[c];if(a===":-")return f||u;else return f!==void 0?f:u}let i=s.match(/^([^:\-+]+)(:?\+)(.+)$/);if(i){let[,c,a,u]=i,f=n[c];if(a===":+")return f?u:"";else return f!==void 0?u:""}return n[s]||""})}var Ne=new Set(["date","hostname","whoami","uname","pwd","echo","printf","cat","basename","dirname"]);function _e(t){let n=[],e="",s=null,r=!1;for(let i of t.trim()){if(r){e+=i,r=!1;continue}if(i==="\\"&&s!=="'"){r=!0;continue}if(s){if(i===s)s=null;else e+=i;continue}if(i==='"'||i==="'"){s=i;continue}if(/\s/.test(i)){if(e)n.push(e),e="";continue}e+=i}if(r||s)throw Error("Command substitution contains an unterminated escape or quote");if(e)n.push(e);return n}function xe(t){let[n,...e]=t,s=e.some((r)=>r.startsWith("-"));if(n==="echo"&&!s)return e.join(" ");if(n==="printf"&&e.length===1&&!e[0]?.includes("%"))return e[0];if(n==="hostname"&&e.length===0)return ve();if(n==="whoami"&&e.length===0)return $e().username;if(n==="pwd"&&e.length===0)return process.cwd();if(n==="basename"&&e.length===1)return ke(e[0]??"");if(n==="dirname"&&e.length===1)return Ke(e[0]??"");if(n==="cat"&&e.length>0&&!s)return e.map((r)=>he(we(process.cwd(),r),"utf8")).join("");if(n==="uname"){let r=e[0]??"-s";if(e.length<=1&&r==="-m")return me();if(e.length<=1&&r==="-r")return Ee();if(e.length<=1&&r==="-s")return{aix:"AIX",android:"Android",cygwin:"CYGWIN",darwin:"Darwin",freebsd:"FreeBSD",haiku:"Haiku",linux:"Linux",netbsd:"NetBSD",openbsd:"OpenBSD",sunos:"SunOS",win32:"Windows_NT"}[Z()]??Z()}return}function Pe(t){return t.replace(/\$\(([^)]+)\)/g,(n,e)=>{try{let s=_e(e),r=s[0];if(!r||!Ne.has(r))return console.warn(`[env] Blocked command substitution for disallowed command: ${r}`),"";let i=xe(s);if(i!==void 0)return i.trim();let c=ge(r,s.slice(1),{encoding:"utf8",env:process.env});if(c.status===0)return c.stdout.trim();let a=c.stderr.trim();console.warn(`[env] Command substitution failed (exit code ${c.status??"unknown"}): ${r}${a?`: ${a}`:""}`)}catch(s){console.warn(`[env] Command substitution error: ${s instanceof Error?s.message:String(s)}`)}return""})}async function je(t,n={}){let e={},s=[],r=[];for(let i of t)try{let c=Bun.file(i);if(!c.size)continue;let a=await c.text(),{parsed:u,errors:f,skippedEncrypted:o}=P(a,n);s.push(...f),r.push(...o);for(let[l,d]of Object.entries(u)){if(!n.overload&&e[l]!==void 0)continue;e[l]=d}}catch(c){if(c?.code==="ENOENT")continue;s.push(`Failed to read ${i}: ${c instanceof Error?c.message:String(c)}`)}return{parsed:e,errors:s,skippedEncrypted:r}}
|
|
4
|
+
`)}if(o.startsWith("encrypted:")||o.startsWith("enc:")){if(!n.privateKey){r.push(f);continue}try{let l=o.startsWith("enc:")?`encrypted:${o.slice(4)}`:o;o=O(l,n.privateKey)}catch(l){s.push(`Failed to decrypt ${f}: ${l instanceof Error?l.message:"Unknown error"}`)}}o=be(o,{...n.processEnv||process.env,...e}),o=Pe(o),e[f]=o}return{parsed:e,errors:s,skippedEncrypted:r}}function be(t,n){return t.replace(/\$\{([^}]+)\}/g,(e,s)=>{let r=s.match(/^([^:\-+]+)(:-|-)(.+)$/);if(r){let[,c,a,u]=r,f=n[c];if(a===":-")return f||u;else return f!==void 0?f:u}let i=s.match(/^([^:\-+]+)(:?\+)(.+)$/);if(i){let[,c,a,u]=i,f=n[c];if(a===":+")return f?u:"";else return f!==void 0?u:""}return n[s]||""})}var Ne=new Set(["date","hostname","whoami","uname","pwd","echo","printf","cat","basename","dirname"]);function _e(t){let n=[],e="",s=null,r=!1;for(let i of t.trim()){if(r){e+=i,r=!1;continue}if(i==="\\"&&s!=="'"){r=!0;continue}if(s){if(i===s)s=null;else e+=i;continue}if(i==='"'||i==="'"){s=i;continue}if(/\s/.test(i)){if(e)n.push(e),e="";continue}e+=i}if(r||s)throw Error("Command substitution contains an unterminated escape or quote");if(e)n.push(e);return n}function xe(t){let[n,...e]=t,s=e.some((r)=>r.startsWith("-"));if(n==="echo"&&!s)return e.join(" ");if(n==="printf"&&e.length===1&&!e[0]?.includes("%"))return e[0];if(n==="hostname"&&e.length===0)return ve();if(n==="whoami"&&e.length===0)return $e().username;if(n==="pwd"&&e.length===0)return process.cwd();if(n==="basename"&&e.length===1)return ke(e[0]??"");if(n==="dirname"&&e.length===1)return Ke(e[0]??"");if(n==="cat"&&e.length>0&&!s)return e.map((r)=>he(we(process.cwd(),r),"utf8")).join("");if(n==="uname"){let r=e[0]??"-s";if(e.length<=1&&r==="-m")return me();if(e.length<=1&&r==="-r")return Ee();if(e.length<=1&&r==="-s")return{aix:"AIX",android:"Android",cygwin:"CYGWIN",darwin:"Darwin",freebsd:"FreeBSD",haiku:"Haiku",linux:"Linux",netbsd:"NetBSD",openbsd:"OpenBSD",sunos:"SunOS",win32:"Windows_NT"}[Z()]??Z()}return}function Pe(t){return t.replace(/\$\(([^)]+)\)/g,(n,e)=>{try{let s=_e(e),r=s[0];if(!r||!Ne.has(r))return console.warn(`[env] Blocked command substitution for disallowed command: ${r}`),"";let i=xe(s);if(i!==void 0)return i.trim();let c=ge(r,s.slice(1),{encoding:"utf8",env:process.env});if(c.status===0)return c.stdout.trim();let a=c.stderr.trim();console.warn(`[env] Command substitution failed (exit code ${c.status??"unknown"}): ${r}${a?`: ${a}`:""}`)}catch(s){console.warn(`[env] Command substitution error: ${s instanceof Error?s.message:String(s)}`)}return""})}async function je(t,n={}){let e={},s=[],r=[];for(let i of t)try{let c=Bun.file(i);if(!c.size)continue;let a=await c.text(),{parsed:u,errors:f,skippedEncrypted:o}=P(a,n);s.push(...f),r.push(...o);for(let[l,d]of Object.entries(u)){if(!n.overload&&e[l]!==void 0)continue;e[l]=d}}catch(c){if(c?.code==="ENOENT")continue;s.push(`Failed to read ${i}: ${c instanceof Error?c.message:String(c)}`)}return{parsed:e,errors:s,skippedEncrypted:r}}function Ge(t,n){if(t)return t;let e=String(n??"").trim();if(!e||e==="development"||e==="dev"||e==="local")return"";if(!/^[\w.-]+$/.test(e))return"";return`.env.${e}`}function re(t,n){return(!n.key||t.includes(n.key))&&(!n.excludeKey||!t.includes(n.excludeKey))}function Ve(t,n){let e=[];for(let s of t.split(`
|
|
5
5
|
`)){let r=s.trim();if(!r||r.startsWith("#"))continue;if(r.startsWith("DOTENV_PUBLIC_KEY"))continue;let i=r.match(/^([^=]+)=(.*)$/);if(!i||i[1]===void 0)continue;let c=i[1].trim();if(re(c,n))e.push(c)}return e}function se(t,n,e,s){let r=["#/-------------------[DOTENV_PUBLIC_KEY]--------------------/","#/ versioned X25519 encryption for .env files /","#/ [how it works](https://stacksjs.com/encryption) /","#/----------------------------------------------------------/",`${e}="${n}"`,""],i=!1;for(let c of t.split(`
|
|
6
6
|
`)){let a=c.trim();if(a.startsWith("#/"))continue;if(a.startsWith("DOTENV_PUBLIC_KEY"))continue;if(!a&&!i)continue;if(!a||a.startsWith("#")){i=!0,r.push(c);continue}i=!0;let u=a.match(/^([^=]+)=(.*)$/);if(!u||u[1]===void 0||u[2]===void 0){r.push(c);continue}let f=u[1].trim(),o=u[2].trim();if(o.startsWith('"')&&o.endsWith('"')||o.startsWith("'")&&o.endsWith("'"))o=o.slice(1,-1);if(re(f,s)&&!o.startsWith("encrypted:"))o=F(o,n);r.push(`${f}="${o}"`)}return r.join(`
|
|
7
7
|
`)}function T(t){let e=((t||".env").split("/").pop()||"").replace(/^\.env\./,"").replace(/^\.env$/,"").toUpperCase();return{publicKeyName:e?`DOTENV_PUBLIC_KEY_${e}`:"DOTENV_PUBLIC_KEY",privateKeyName:e?`DOTENV_PRIVATE_KEY_${e}`:"DOTENV_PRIVATE_KEY"}}function ie(t,n){let e,s=!1;for(let r of t.split(`
|
package/dist/index.js
CHANGED
|
@@ -1,31 +1,31 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{createCipheriv as ne,createDecipheriv as te,createHash as G,createPrivateKey as be,createPublicKey as re,diffieHellman as ie,generateKeyPairSync as se,hkdfSync as oe,randomBytes as H}from"crypto";var j="x25519-public:",X="x25519-private:",x="encrypted:v2:",Q="encrypted:",de=Buffer.from("stacks-env:v2","utf8"),ce="Environment decryption failed: authentication or format error";function ae(e){if(e.length===32)return e;return G("sha256").update(e).digest()}function vn(e,n){let t=H(16),r=ne("aes-256-gcm",ae(n),t);return{ciphertext:Buffer.concat([r.update(e,"utf8"),r.final()]).toString("hex"),iv:t.toString("hex"),authTag:r.getAuthTag().toString("hex")}}function Le(e,n,t,r){try{let i=te("aes-256-gcm",ae(n),Buffer.from(t,"hex"));return i.setAuthTag(Buffer.from(r,"hex")),Buffer.concat([i.update(Buffer.from(e,"hex")),i.final()]).toString("utf8")}catch{throw Error("Decryption failed: authentication or format error")}}function h(e){return e.toString("base64url")}function C(e,n,t){if(typeof e!=="string"||e.length>0&&!/^[A-Za-z0-9_-]+$/.test(e))throw Error(`${n} is not canonical base64url`);let r=Buffer.from(e,"base64url");if(h(r)!==e)throw Error(`${n} is not canonical base64url`);if(t!==void 0&&r.length!==t)throw Error(`${n} has an invalid length`);return r}function Ke(e){if(!e.startsWith(j))throw Error("Legacy or invalid public key. Run buddy env:rotate before creating new ciphertext.");let n=re({key:C(e.slice(j.length),"public key"),format:"der",type:"spki"});if(n.asymmetricKeyType!=="x25519")throw Error("Public key is not X25519");return n}function ke(e){if(!e.startsWith(X))throw Error("Private key is not a version 2 X25519 key");let n=be({key:C(e.slice(X.length),"private key"),format:"der",type:"pkcs8"});if(n.asymmetricKeyType!=="x25519")throw Error("Private key is not X25519");return n}function ue(e){return Buffer.from(`stacks-env:v2;${e.epk};${e.salt};${e.nonce}`,"utf8")}function k(){let{publicKey:e,privateKey:n}=se("x25519"),t=e.export({format:"der",type:"spki"}),r=n.export({format:"der",type:"pkcs8"});return{publicKey:`${j}${h(t)}`,privateKey:`${X}${h(r)}`}}function B(e,n){let t=Ke(n),r=se("x25519"),i=h(r.publicKey.export({format:"der",type:"spki"})),s=H(16),o=H(12),d=ie({privateKey:r.privateKey,publicKey:t}),c=Buffer.from(oe("sha256",d,s,de,32)),u={epk:i,salt:h(s),nonce:h(o)};try{let a=ne("aes-256-gcm",c,o);a.setAAD(ue(u));let f=Buffer.concat([a.update(e,"utf8"),a.final()]),p={v:2,...u,ciphertext:h(f),tag:h(a.getAuthTag())};return`${x}${h(Buffer.from(JSON.stringify(p),"utf8"))}`}finally{d.fill(0),c.fill(0)}}function Ue(e){let n=C(e.slice(x.length),"envelope").toString("utf8"),t=JSON.parse(n);if(!t||typeof t!=="object"||Array.isArray(t))throw Error("envelope is not an object");let r=Object.keys(t).sort(),i=["ciphertext","epk","nonce","salt","tag","v"];if(r.length!==i.length||r.some((s,o)=>s!==i[o]))throw Error("envelope fields are invalid");if(t.v!==2)throw Error("envelope version is unsupported");for(let s of["epk","salt","nonce","ciphertext","tag"])if(typeof t[s]!=="string")throw Error(`${s} is invalid`);return t}function $e(e,n){try{let t=Ue(e),r=ke(n),i=re({key:C(t.epk,"ephemeral public key"),format:"der",type:"spki"});if(i.asymmetricKeyType!=="x25519")throw Error("ephemeral key is not X25519");let s=C(t.salt,"salt",16),o=C(t.nonce,"nonce",12),d=C(t.ciphertext,"ciphertext"),c=C(t.tag,"tag",16),u=ie({privateKey:r,publicKey:i}),a=Buffer.from(oe("sha256",u,s,de,32));try{let f=te("aes-256-gcm",a,o);return f.setAAD(ue(t)),f.setAuthTag(c),Buffer.concat([f.update(d),f.final()]).toString("utf8")}finally{u.fill(0),a.fill(0)}}catch{throw Error(ce)}}function we(e,n){try{if(!/^[0-9a-f]{64}$/.test(n))throw Error("invalid legacy private key");let t=Buffer.from(e.slice(Q.length),"base64");if(t.length<32)throw Error("invalid legacy payload");let r=G("sha256").update(Buffer.from(n,"hex")).digest(),i=G("sha256").update(r).digest();return Le(t.subarray(32).toString("hex"),i,t.subarray(0,16).toString("hex"),t.subarray(16,32).toString("hex"))}catch{throw Error(ce)}}function On(e){return e.startsWith(Q)&&!e.startsWith(x)}function K(e,n){if(!e.startsWith(Q))return e;return e.startsWith(x)?$e(e,n):we(e,n)}function An(e,n,t){return B(K(e,n),t)}function Sn(e){let n=e.match(/^DOTENV_PRIVATE_KEY_(.+)$/);return n&&n[1]?n[1].toLowerCase():""}function q(e=""){return e?process.env[`DOTENV_PRIVATE_KEY_${e.toUpperCase()}`]:process.env.DOTENV_PRIVATE_KEY}import{spawnSync as xe}from"child_process";import{readFileSync as Be}from"fs";import{arch as Ve,hostname as Me,platform as fe,release as Fe,userInfo as Ye}from"os";import{basename as We,dirname as Ge,resolve as He}from"path";function S(e,n={}){let t={},r=[],i=[],s=e.split(`
|
|
2
|
+
import gn from"process";import{projectPath as _n}from"@stacksjs/path";import Ne from"fs";import{existsSync as V}from"fs";import{readFileSync as z}from"fs";import{resolve as M}from"path";import{createCipheriv as ne,createDecipheriv as te,createHash as G,createPrivateKey as be,createPublicKey as re,diffieHellman as ie,generateKeyPairSync as se,hkdfSync as oe,randomBytes as H}from"crypto";var j="x25519-public:",X="x25519-private:",x="encrypted:v2:",Q="encrypted:",de=Buffer.from("stacks-env:v2","utf8"),ce="Environment decryption failed: authentication or format error";function ae(e){if(e.length===32)return e;return G("sha256").update(e).digest()}function vn(e,n){let t=H(16),r=ne("aes-256-gcm",ae(n),t);return{ciphertext:Buffer.concat([r.update(e,"utf8"),r.final()]).toString("hex"),iv:t.toString("hex"),authTag:r.getAuthTag().toString("hex")}}function Le(e,n,t,r){try{let i=te("aes-256-gcm",ae(n),Buffer.from(t,"hex"));return i.setAuthTag(Buffer.from(r,"hex")),Buffer.concat([i.update(Buffer.from(e,"hex")),i.final()]).toString("utf8")}catch{throw Error("Decryption failed: authentication or format error")}}function h(e){return e.toString("base64url")}function C(e,n,t){if(typeof e!=="string"||e.length>0&&!/^[A-Za-z0-9_-]+$/.test(e))throw Error(`${n} is not canonical base64url`);let r=Buffer.from(e,"base64url");if(h(r)!==e)throw Error(`${n} is not canonical base64url`);if(t!==void 0&&r.length!==t)throw Error(`${n} has an invalid length`);return r}function Ke(e){if(!e.startsWith(j))throw Error("Legacy or invalid public key. Run buddy env:rotate before creating new ciphertext.");let n=re({key:C(e.slice(j.length),"public key"),format:"der",type:"spki"});if(n.asymmetricKeyType!=="x25519")throw Error("Public key is not X25519");return n}function ke(e){if(!e.startsWith(X))throw Error("Private key is not a version 2 X25519 key");let n=be({key:C(e.slice(X.length),"private key"),format:"der",type:"pkcs8"});if(n.asymmetricKeyType!=="x25519")throw Error("Private key is not X25519");return n}function ue(e){return Buffer.from(`stacks-env:v2;${e.epk};${e.salt};${e.nonce}`,"utf8")}function k(){let{publicKey:e,privateKey:n}=se("x25519"),t=e.export({format:"der",type:"spki"}),r=n.export({format:"der",type:"pkcs8"});return{publicKey:`${j}${h(t)}`,privateKey:`${X}${h(r)}`}}function B(e,n){let t=Ke(n),r=se("x25519"),i=h(r.publicKey.export({format:"der",type:"spki"})),s=H(16),o=H(12),d=ie({privateKey:r.privateKey,publicKey:t}),c=Buffer.from(oe("sha256",d,s,de,32)),u={epk:i,salt:h(s),nonce:h(o)};try{let a=ne("aes-256-gcm",c,o);a.setAAD(ue(u));let f=Buffer.concat([a.update(e,"utf8"),a.final()]),p={v:2,...u,ciphertext:h(f),tag:h(a.getAuthTag())};return`${x}${h(Buffer.from(JSON.stringify(p),"utf8"))}`}finally{d.fill(0),c.fill(0)}}function Ue(e){let n=C(e.slice(x.length),"envelope").toString("utf8"),t=JSON.parse(n);if(!t||typeof t!=="object"||Array.isArray(t))throw Error("envelope is not an object");let r=Object.keys(t).sort(),i=["ciphertext","epk","nonce","salt","tag","v"];if(r.length!==i.length||r.some((s,o)=>s!==i[o]))throw Error("envelope fields are invalid");if(t.v!==2)throw Error("envelope version is unsupported");for(let s of["epk","salt","nonce","ciphertext","tag"])if(typeof t[s]!=="string")throw Error(`${s} is invalid`);return t}function $e(e,n){try{let t=Ue(e),r=ke(n),i=re({key:C(t.epk,"ephemeral public key"),format:"der",type:"spki"});if(i.asymmetricKeyType!=="x25519")throw Error("ephemeral key is not X25519");let s=C(t.salt,"salt",16),o=C(t.nonce,"nonce",12),d=C(t.ciphertext,"ciphertext"),c=C(t.tag,"tag",16),u=ie({privateKey:r,publicKey:i}),a=Buffer.from(oe("sha256",u,s,de,32));try{let f=te("aes-256-gcm",a,o);return f.setAAD(ue(t)),f.setAuthTag(c),Buffer.concat([f.update(d),f.final()]).toString("utf8")}finally{u.fill(0),a.fill(0)}}catch{throw Error(ce)}}function we(e,n){try{if(!/^[0-9a-f]{64}$/.test(n))throw Error("invalid legacy private key");let t=Buffer.from(e.slice(Q.length),"base64");if(t.length<32)throw Error("invalid legacy payload");let r=G("sha256").update(Buffer.from(n,"hex")).digest(),i=G("sha256").update(r).digest();return Le(t.subarray(32).toString("hex"),i,t.subarray(0,16).toString("hex"),t.subarray(16,32).toString("hex"))}catch{throw Error(ce)}}function On(e){return e.startsWith(Q)&&!e.startsWith(x)}function K(e,n){if(!e.startsWith(Q))return e;return e.startsWith(x)?$e(e,n):we(e,n)}function An(e,n,t){return B(K(e,n),t)}function Sn(e){let n=e.match(/^DOTENV_PRIVATE_KEY_(.+)$/);return n&&n[1]?n[1].toLowerCase():""}function q(e=""){return e?process.env[`DOTENV_PRIVATE_KEY_${e.toUpperCase()}`]:process.env.DOTENV_PRIVATE_KEY}import{spawnSync as xe}from"child_process";import{readFileSync as Be}from"fs";import{arch as Ve,hostname as Me,platform as fe,release as Fe,userInfo as Ye}from"os";import{basename as We,dirname as Ge,resolve as He}from"path";function S(e,n={}){let t={},r=[],i=[],s=e.split(`
|
|
3
3
|
`);for(let o of s){let d=o.trim();if(!d||d.startsWith("#"))continue;if(d.startsWith("DOTENV_PUBLIC_KEY=")){let f=d.match(/^DOTENV_PUBLIC_KEY=["']?([^"'\n]+)["']?/);if(f&&f[1]!==void 0)t.DOTENV_PUBLIC_KEY=f[1];continue}let c=d.match(/^([^=]+)=(.*)$/);if(!c||c[1]===void 0||c[2]===void 0)continue;let u=c[1].trim(),a=c[2].trim();if(a.startsWith('"')&&a.endsWith('"')||a.startsWith("'")&&a.endsWith("'")){if(a=a.slice(1,-1),a.includes("\\n"))a=a.replace(/\\n/g,`
|
|
4
|
-
`)}if(a.startsWith("encrypted:")||a.startsWith("enc:")){if(!n.privateKey){i.push(u);continue}try{let f=a.startsWith("enc:")?`encrypted:${a.slice(4)}`:a;a=K(f,n.privateKey)}catch(f){r.push(`Failed to decrypt ${u}: ${f instanceof Error?f.message:"Unknown error"}`)}}a=je(a,{...n.processEnv||process.env,...t}),a=ze(a),t[u]=a}return{parsed:t,errors:r,skippedEncrypted:i}}function je(e,n){return e.replace(/\$\{([^}]+)\}/g,(t,r)=>{let i=r.match(/^([^:\-+]+)(:-|-)(.+)$/);if(i){let[,o,d,c]=i,u=n[o];if(d===":-")return u||c;else return u!==void 0?u:c}let s=r.match(/^([^:\-+]+)(:?\+)(.+)$/);if(s){let[,o,d,c]=s,u=n[o];if(d===":+")return u?c:"";else return u!==void 0?c:""}return n[r]||""})}var Xe=new Set(["date","hostname","whoami","uname","pwd","echo","printf","cat","basename","dirname"]);function Qe(e){let n=[],t="",r=null,i=!1;for(let s of e.trim()){if(i){t+=s,i=!1;continue}if(s==="\\"&&r!=="'"){i=!0;continue}if(r){if(s===r)r=null;else t+=s;continue}if(s==='"'||s==="'"){r=s;continue}if(/\s/.test(s)){if(t)n.push(t),t="";continue}t+=s}if(i||r)throw Error("Command substitution contains an unterminated escape or quote");if(t)n.push(t);return n}function qe(e){let[n,...t]=e,r=t.some((i)=>i.startsWith("-"));if(n==="echo"&&!r)return t.join(" ");if(n==="printf"&&t.length===1&&!t[0]?.includes("%"))return t[0];if(n==="hostname"&&t.length===0)return Me();if(n==="whoami"&&t.length===0)return Ye().username;if(n==="pwd"&&t.length===0)return process.cwd();if(n==="basename"&&t.length===1)return We(t[0]??"");if(n==="dirname"&&t.length===1)return Ge(t[0]??"");if(n==="cat"&&t.length>0&&!r)return t.map((i)=>Be(He(process.cwd(),i),"utf8")).join("");if(n==="uname"){let i=t[0]??"-s";if(t.length<=1&&i==="-m")return Ve();if(t.length<=1&&i==="-r")return Fe();if(t.length<=1&&i==="-s")return{aix:"AIX",android:"Android",cygwin:"CYGWIN",darwin:"Darwin",freebsd:"FreeBSD",haiku:"Haiku",linux:"Linux",netbsd:"NetBSD",openbsd:"OpenBSD",sunos:"SunOS",win32:"Windows_NT"}[fe()]??fe()}return}function ze(e){return e.replace(/\$\(([^)]+)\)/g,(n,t)=>{try{let r=Qe(t),i=r[0];if(!i||!Xe.has(i))return console.warn(`[env] Blocked command substitution for disallowed command: ${i}`),"";let s=qe(r);if(s!==void 0)return s.trim();let o=xe(i,r.slice(1),{encoding:"utf8",env:process.env});if(o.status===0)return o.stdout.trim();let d=o.stderr.trim();console.warn(`[env] Command substitution failed (exit code ${o.status??"unknown"}): ${i}${d?`: ${d}`:""}`)}catch(r){console.warn(`[env] Command substitution error: ${r instanceof Error?r.message:String(r)}`)}return""})}async function bn(e,n={}){let t={},r=[],i=[];for(let s of e)try{let o=Bun.file(s);if(!o.size)continue;let d=await o.text(),{parsed:c,errors:u,skippedEncrypted:a}=S(d,n);r.push(...u),i.push(...a);for(let[f,p]of Object.entries(c)){if(!n.overload&&t[f]!==void 0)continue;t[f]=p}}catch(o){if(o?.code==="ENOENT")continue;r.push(`Failed to read ${s}: ${o instanceof Error?o.message:String(o)}`)}return{parsed:t,errors:r,skippedEncrypted:i}}
|
|
5
|
-
`)){let i=r.trim();if(!i||i.startsWith("#"))continue;if(i.startsWith("DOTENV_PUBLIC_KEY"))continue;let s=i.match(/^([^=]+)=(.*)$/);if(!s||s[1]===void 0)continue;let o=s[1].trim();if(
|
|
6
|
-
`)){let d=o.trim();if(d.startsWith("#/"))continue;if(d.startsWith("DOTENV_PUBLIC_KEY"))continue;if(!d&&!s)continue;if(!d||d.startsWith("#")){s=!0,i.push(o);continue}s=!0;let c=d.match(/^([^=]+)=(.*)$/);if(!c||c[1]===void 0||c[2]===void 0){i.push(o);continue}let u=c[1].trim(),a=c[2].trim();if(a.startsWith('"')&&a.endsWith('"')||a.startsWith("'")&&a.endsWith("'"))a=a.slice(1,-1);if(
|
|
7
|
-
`)}function w(e){let t=((e||".env").split("/").pop()||"").replace(/^\.env\./,"").replace(/^\.env$/,"").toUpperCase();return{publicKeyName:t?`DOTENV_PUBLIC_KEY_${t}`:"DOTENV_PUBLIC_KEY",privateKeyName:t?`DOTENV_PRIVATE_KEY_${t}`:"DOTENV_PRIVATE_KEY"}}function
|
|
8
|
-
`)){let s=i.trim();if(!s||s.startsWith("#"))continue;let o=s.match(/^([^=]+)=(.*)$/);if(!o?.[1]||o[2]===void 0)continue;let d=o[1].trim(),c=o[2].trim().replace(/^["']|["']$/g,"");if(d===n)t=c;else if(c.startsWith("encrypted:")||c.startsWith("enc:"))r=!0}return t&&r?t:void 0}function
|
|
4
|
+
`)}if(a.startsWith("encrypted:")||a.startsWith("enc:")){if(!n.privateKey){i.push(u);continue}try{let f=a.startsWith("enc:")?`encrypted:${a.slice(4)}`:a;a=K(f,n.privateKey)}catch(f){r.push(`Failed to decrypt ${u}: ${f instanceof Error?f.message:"Unknown error"}`)}}a=je(a,{...n.processEnv||process.env,...t}),a=ze(a),t[u]=a}return{parsed:t,errors:r,skippedEncrypted:i}}function je(e,n){return e.replace(/\$\{([^}]+)\}/g,(t,r)=>{let i=r.match(/^([^:\-+]+)(:-|-)(.+)$/);if(i){let[,o,d,c]=i,u=n[o];if(d===":-")return u||c;else return u!==void 0?u:c}let s=r.match(/^([^:\-+]+)(:?\+)(.+)$/);if(s){let[,o,d,c]=s,u=n[o];if(d===":+")return u?c:"";else return u!==void 0?c:""}return n[r]||""})}var Xe=new Set(["date","hostname","whoami","uname","pwd","echo","printf","cat","basename","dirname"]);function Qe(e){let n=[],t="",r=null,i=!1;for(let s of e.trim()){if(i){t+=s,i=!1;continue}if(s==="\\"&&r!=="'"){i=!0;continue}if(r){if(s===r)r=null;else t+=s;continue}if(s==='"'||s==="'"){r=s;continue}if(/\s/.test(s)){if(t)n.push(t),t="";continue}t+=s}if(i||r)throw Error("Command substitution contains an unterminated escape or quote");if(t)n.push(t);return n}function qe(e){let[n,...t]=e,r=t.some((i)=>i.startsWith("-"));if(n==="echo"&&!r)return t.join(" ");if(n==="printf"&&t.length===1&&!t[0]?.includes("%"))return t[0];if(n==="hostname"&&t.length===0)return Me();if(n==="whoami"&&t.length===0)return Ye().username;if(n==="pwd"&&t.length===0)return process.cwd();if(n==="basename"&&t.length===1)return We(t[0]??"");if(n==="dirname"&&t.length===1)return Ge(t[0]??"");if(n==="cat"&&t.length>0&&!r)return t.map((i)=>Be(He(process.cwd(),i),"utf8")).join("");if(n==="uname"){let i=t[0]??"-s";if(t.length<=1&&i==="-m")return Ve();if(t.length<=1&&i==="-r")return Fe();if(t.length<=1&&i==="-s")return{aix:"AIX",android:"Android",cygwin:"CYGWIN",darwin:"Darwin",freebsd:"FreeBSD",haiku:"Haiku",linux:"Linux",netbsd:"NetBSD",openbsd:"OpenBSD",sunos:"SunOS",win32:"Windows_NT"}[fe()]??fe()}return}function ze(e){return e.replace(/\$\(([^)]+)\)/g,(n,t)=>{try{let r=Qe(t),i=r[0];if(!i||!Xe.has(i))return console.warn(`[env] Blocked command substitution for disallowed command: ${i}`),"";let s=qe(r);if(s!==void 0)return s.trim();let o=xe(i,r.slice(1),{encoding:"utf8",env:process.env});if(o.status===0)return o.stdout.trim();let d=o.stderr.trim();console.warn(`[env] Command substitution failed (exit code ${o.status??"unknown"}): ${i}${d?`: ${d}`:""}`)}catch(r){console.warn(`[env] Command substitution error: ${r instanceof Error?r.message:String(r)}`)}return""})}async function bn(e,n={}){let t={},r=[],i=[];for(let s of e)try{let o=Bun.file(s);if(!o.size)continue;let d=await o.text(),{parsed:c,errors:u,skippedEncrypted:a}=S(d,n);r.push(...u),i.push(...a);for(let[f,p]of Object.entries(c)){if(!n.overload&&t[f]!==void 0)continue;t[f]=p}}catch(o){if(o?.code==="ENOENT")continue;r.push(`Failed to read ${s}: ${o instanceof Error?o.message:String(o)}`)}return{parsed:t,errors:r,skippedEncrypted:i}}function U(e){return typeof e==="string"&&(e.startsWith("encrypted:")||e.startsWith("enc:"))}function b(e){if(!e||U(e))return;let n=e.trim().toLowerCase();if(!/^[a-z0-9_-]+$/.test(n))return;if(n==="prod")return"production";if(n==="stage")return"staging";if(n==="dev")return"development";return n}var F=null,Y,W;function Je(e,n,t=".env.keys"){let r=M(n,t);if(!V(r))return;try{let{parsed:i}=S(z(r,"utf-8"));if(e){let s=i[`DOTENV_PRIVATE_KEY_${e.toUpperCase()}`];if(s)return s}return i.DOTENV_PRIVATE_KEY}catch{return}}function J(e={}){return b(e.env)||W||b("development")||b(process.env.DOTENV_ENV)||b(process.env.APP_ENV)||"development"}function Ze(e={}){let n=J(e),t=e.cwd||process.cwd();if(F===n)return Y;let r=q(n);if(!r)r=process.env.DOTENV_PRIVATE_KEY;if(!r)r=Je(n,t);return F=n,Y=r,r}function xn(){F=null,Y=void 0,W=void 0}function Ee(e,n={}){if(!U(e))return e;let t=Ze(n);if(!t)return;try{let r=e.startsWith("enc:")?`encrypted:${e.slice(4)}`:e;return K(r,t)}catch{return}}function le(e={}){let{path:n=[".env"],overload:t=!1,env:r,privateKey:i,keysFile:s=".env.keys",quiet:o=!1,cwd:d=process.cwd()}=e,c=Array.isArray(n)?n:[n],u=[],a=0,f=new Set(Object.entries(process.env).filter(([,E])=>E!==void 0&&!U(E)).map(([E])=>E)),p=i;if(!p&&s){let E=M(d,s);if(V(E))try{let l=z(E,"utf-8"),{parsed:T}=S(l);if(r){let v=`DOTENV_PRIVATE_KEY_${r.toUpperCase()}`;p=T[v]}else p=T.DOTENV_PRIVATE_KEY}catch(l){u.push(`Failed to load keys file: ${l instanceof Error?l.message:"Unknown error"}`)}}if(!p)p=q(r||"");for(let E of c){let l=M(d,E);if(!V(l)){if(!o)u.push(`File not found: ${l}`);continue}try{let T=z(l,"utf-8"),{parsed:v,errors:_,skippedEncrypted:y}=S(T,{privateKey:p,processEnv:process.env});if(u.push(..._),y.length>0){for(let D of y)if(U(process.env[D]))delete process.env[D];let R=r?`DOTENV_PRIVATE_KEY_${r.toUpperCase()}`:"DOTENV_PRIVATE_KEY",L=y.slice(0,5).join(", "),P=y.length>5?`, \u2026 +${y.length-5} more`:"";console.warn(`[env] warning: skipped ${y.length} encrypted value(s) in ${E} (${R} not set; defaults apply): ${L}${P}`)}let m=0;for(let[R,L]of Object.entries(v)){if(R==="DOTENV_PUBLIC_KEY")continue;let P=process.env[R],D=U(P)&&L!==P;if(t||!f.has(R)||D)process.env[R]=L,a++,m++}if(!o&&!process.env.__ENV_LOADED__)console.error(`[env] loaded ${m}/${Object.keys(v).length} variables from ${E}`),process.env.__ENV_LOADED__="1"}catch(T){u.push(`Failed to load ${l}: ${T instanceof Error?T.message:"Unknown error"}`)}}return{loaded:a,errors:u}}function en(e={}){return{name:"env-plugin",setup(n){le(e)}}}function Bn(e={}){let n=b(e.env)||b("development")||b(process.env.DOTENV_ENV)||b(process.env.APP_ENV)||"development",t=e.cwd||process.cwd();if(W!==n)W=n,F=null,Y=void 0;let r=[],i=(d)=>{if(!r.includes(d)&&V(M(t,d)))r.push(d)};i(".env"),i(".env.local");let s=`.env.${n}`,o=`.env.${n}.local`;return i(s),i(o),le({...e,path:r,env:n})}var Mn=en;var pe={APP_ENV:["local","dev","development","staging","prod","production"],DB_CONNECTION:["mysql","sqlite","postgres","singlestore","vitess","dynamodb"],DB_MIGRATE_FRESH:["allow","confirm","disabled"],MAIL_MAILER:["smtp","mailgun","ses","log","sendgrid","mailtrap","capture"],SEARCH_ENGINE_DRIVER:["opensearch","meilisearch","algolia","typesense"],FRONTEND_APP_ENV:["development","staging","production"]};function Fn(e){return e}import{existsSync as I,readFileSync as A,renameSync as ge,rmSync as _e,writeFileSync as N}from"fs";import{basename as Te,dirname as ye,resolve as O}from"path";function Xn(e,n){if(e)return e;let t=String(n??"").trim();if(!t||t==="development"||t==="dev"||t==="local")return"";if(!/^[\w.-]+$/.test(t))return"";return`.env.${t}`}function Re(e,n){return(!n.key||e.includes(n.key))&&(!n.excludeKey||!e.includes(n.excludeKey))}function nn(e,n){let t=[];for(let r of e.split(`
|
|
5
|
+
`)){let i=r.trim();if(!i||i.startsWith("#"))continue;if(i.startsWith("DOTENV_PUBLIC_KEY"))continue;let s=i.match(/^([^=]+)=(.*)$/);if(!s||s[1]===void 0)continue;let o=s[1].trim();if(Re(o,n))t.push(o)}return t}function me(e,n,t,r){let i=["#/-------------------[DOTENV_PUBLIC_KEY]--------------------/","#/ versioned X25519 encryption for .env files /","#/ [how it works](https://stacksjs.com/encryption) /","#/----------------------------------------------------------/",`${t}="${n}"`,""],s=!1;for(let o of e.split(`
|
|
6
|
+
`)){let d=o.trim();if(d.startsWith("#/"))continue;if(d.startsWith("DOTENV_PUBLIC_KEY"))continue;if(!d&&!s)continue;if(!d||d.startsWith("#")){s=!0,i.push(o);continue}s=!0;let c=d.match(/^([^=]+)=(.*)$/);if(!c||c[1]===void 0||c[2]===void 0){i.push(o);continue}let u=c[1].trim(),a=c[2].trim();if(a.startsWith('"')&&a.endsWith('"')||a.startsWith("'")&&a.endsWith("'"))a=a.slice(1,-1);if(Re(u,r)&&!a.startsWith("encrypted:"))a=B(a,n);i.push(`${u}="${a}"`)}return i.join(`
|
|
7
|
+
`)}function w(e){let t=((e||".env").split("/").pop()||"").replace(/^\.env\./,"").replace(/^\.env$/,"").toUpperCase();return{publicKeyName:t?`DOTENV_PUBLIC_KEY_${t}`:"DOTENV_PUBLIC_KEY",privateKeyName:t?`DOTENV_PRIVATE_KEY_${t}`:"DOTENV_PRIVATE_KEY"}}function ve(e,n){let t,r=!1;for(let i of e.split(`
|
|
8
|
+
`)){let s=i.trim();if(!s||s.startsWith("#"))continue;let o=s.match(/^([^=]+)=(.*)$/);if(!o?.[1]||o[2]===void 0)continue;let d=o[1].trim(),c=o[2].trim().replace(/^["']|["']$/g,"");if(d===n)t=c;else if(c.startsWith("encrypted:")||c.startsWith("enc:"))r=!0}return t&&r?t:void 0}function Qn(e={}){let n=e.cwd||process.cwd(),t=O(n,e.file||".env"),r=O(n,e.keysFile||".env.keys");if(!I(t))return{success:!1,error:`File not found: ${t}`};try{let i,s,o=ve(A(t,"utf-8"),w(e.file).publicKeyName);if(o)i=o;else if(I(r)){let u=A(r,"utf-8"),{parsed:a}=S(u),{publicKeyName:f,privateKeyName:p}=w(e.file);if(i=a[f]||"",s=a[p]||"",!i||!s){let E=k();i=E.publicKey,s=E.privateKey;let l=`
|
|
9
9
|
${f}="${i}"
|
|
10
10
|
${p}="${s}"
|
|
11
11
|
`;N(r,u+l,"utf-8")}}else{let u=k();i=u.publicKey,s=u.privateKey;let{publicKeyName:a,privateKeyName:f}=w(e.file),p=`# .env.keys - Keep this file secure and never commit to source control
|
|
12
12
|
${a}="${i}"
|
|
13
13
|
${f}="${s}"
|
|
14
|
-
`;N(r,p,"utf-8")}let d=A(t,"utf-8"),c=
|
|
14
|
+
`;N(r,p,"utf-8")}let d=A(t,"utf-8"),c=me(d,i,w(e.file).publicKeyName,e);if(e.stdout)return{success:!0,output:c};return N(t,c,"utf-8"),{success:!0,output:`\u2714 encrypted (${e.file||".env"})
|
|
15
15
|
\u2714 key added to ${e.keysFile||".env.keys"}`}}catch(i){return{success:!1,error:`Failed to encrypt: ${i instanceof Error?i.message:"Unknown error"}`}}}function tn(e={}){let n=e.cwd||process.cwd(),t=O(n,e.file||".env"),r=O(n,e.keysFile||".env.keys");if(!I(t))return{success:!1,error:`File not found: ${t}`};if(!I(r))return{success:!1,error:`Keys file not found: ${r}`};try{let i=A(r,"utf-8"),{parsed:s}=S(i),c=((e.file||".env").split("/").pop()||"").replace(/^\.env\./,"").replace(/^\.env$/,"").toUpperCase(),u=c?`DOTENV_PRIVATE_KEY_${c}`:"DOTENV_PRIVATE_KEY",a=s[u];if(!a)return{success:!1,error:`Private key not found: ${u}`};let f=[a];if(u!=="DOTENV_PRIVATE_KEY"&&s.DOTENV_PRIVATE_KEY&&s.DOTENV_PRIVATE_KEY!==a)f.push(s.DOTENV_PRIVATE_KEY);let E=A(t,"utf-8").split(`
|
|
16
16
|
`),l=[];for(let v of E){let _=v.trim();if(!_||_.startsWith("#")){l.push(v);continue}if(_.startsWith("DOTENV_PUBLIC_KEY"))continue;let y=_.match(/^([^=]+)=(.*)$/);if(!y||y[1]===void 0||y[2]===void 0){l.push(v);continue}let m=y[1].trim(),R=y[2].trim();if(R.startsWith('"')&&R.endsWith('"')||R.startsWith("'")&&R.endsWith("'"))R=R.slice(1,-1);let L=R.startsWith("encrypted:");if(e.key&&!m.includes(e.key))L=!1;if(L){let P,D;for(let De of f)try{P=K(R,De);break}catch(Ce){D=Ce}if(P===void 0)throw D instanceof Error?D:Error(`Unable to decrypt ${m}`);R=P}l.push(`${m}="${R}"`)}let T=l.join(`
|
|
17
|
-
`);if(e.stdout)return{success:!0,output:T};return N(t,T,"utf-8"),{success:!0,output:`\u2714 decrypted (${e.file||".env"})`}}catch(i){return{success:!1,error:`Failed to decrypt: ${i instanceof Error?i.message:"Unknown error"}`}}}function
|
|
18
|
-
`),c=!1,u,p=((t.file||".env").split("/").pop()||"").replace(/^\.env\./,"").replace(/^\.env$/,"").toUpperCase(),E=p?`DOTENV_PUBLIC_KEY_${p}`:"DOTENV_PUBLIC_KEY",l=p?`DOTENV_PRIVATE_KEY_${p}`:"DOTENV_PRIVATE_KEY";for(let _ of d){let y=_.trim();if(y.startsWith(`${E}=`)){let m=y.match(/^[^=]+=["']?([^"'\n]+)["']?/);if(m)u=m[1];break}}if(u){let _=!1;if(I(s)){let y=A(s,"utf-8"),{parsed:m}=S(y);_=Boolean(m[l])}if(!_&&!process.env[l]&&!
|
|
17
|
+
`);if(e.stdout)return{success:!0,output:T};return N(t,T,"utf-8"),{success:!0,output:`\u2714 decrypted (${e.file||".env"})`}}catch(i){return{success:!1,error:`Failed to decrypt: ${i instanceof Error?i.message:"Unknown error"}`}}}function qn(e,n,t={}){let r=t.cwd||process.cwd(),i=O(r,t.file||".env"),s=O(r,t.keysFile||".env.keys");try{let o="";if(I(i))o=A(i,"utf-8");let d=o.split(`
|
|
18
|
+
`),c=!1,u,p=((t.file||".env").split("/").pop()||"").replace(/^\.env\./,"").replace(/^\.env$/,"").toUpperCase(),E=p?`DOTENV_PUBLIC_KEY_${p}`:"DOTENV_PUBLIC_KEY",l=p?`DOTENV_PRIVATE_KEY_${p}`:"DOTENV_PRIVATE_KEY";for(let _ of d){let y=_.trim();if(y.startsWith(`${E}=`)){let m=y.match(/^[^=]+=["']?([^"'\n]+)["']?/);if(m)u=m[1];break}}if(u){let _=!1;if(I(s)){let y=A(s,"utf-8"),{parsed:m}=S(y);_=Boolean(m[l])}if(!_&&!process.env[l]&&!ve(o,E))u=void 0}if(!t.plain&&!u){let _=k();u=_.publicKey;let y="";if(I(s))y=A(s,"utf-8");y+=`
|
|
19
19
|
${E}="${_.publicKey}"
|
|
20
20
|
${l}="${_.privateKey}"
|
|
21
21
|
`,N(s,y,"utf-8");for(let m=d.length-1;m>=0;m--){let R=d[m];if(R!==void 0&&R.trim().startsWith(`${E}=`))d.splice(m,1)}d.unshift(`${E}="${u}"`)}let T=n;if(!t.plain&&u)T=B(n,u);for(let _=0;_<d.length;_++){let y=d[_];if(y===void 0)continue;if(y.trim().startsWith(`${e}=`)){d[_]=`${e}="${T}"`,c=!0;break}}if(!c)d.push(`${e}="${T}"`);let v=d.join(`
|
|
22
|
-
`);return N(i,v,"utf-8"),{success:!0,output:`set ${e}${t.plain?"":" with encryption"} (${t.file||".env"})`}}catch(o){return{success:!1,error:`Failed to set: ${o instanceof Error?o.message:"Unknown error"}`}}}function
|
|
23
|
-
`);break;case"json":default:E=n.prettyPrint?JSON.stringify(p,null,2):JSON.stringify(p);break}return{success:!0,output:E}}catch(i){return{success:!1,error:`Failed to get: ${i instanceof Error?i.message:"Unknown error"}`}}}function
|
|
22
|
+
`);return N(i,v,"utf-8"),{success:!0,output:`set ${e}${t.plain?"":" with encryption"} (${t.file||".env"})`}}catch(o){return{success:!1,error:`Failed to set: ${o instanceof Error?o.message:"Unknown error"}`}}}function zn(e,n={}){let t=n.cwd||process.cwd(),r=O(t,n.file||".env");if(!I(r))return{success:!1,error:`File not found: ${r}`};try{let i,s=O(t,n.keysFile||".env.keys"),c=((n.file||".env").split("/").pop()||"").replace(/^\.env\./,"").replace(/^\.env$/,"").toUpperCase(),u=c?`DOTENV_PRIVATE_KEY_${c}`:"DOTENV_PRIVATE_KEY";if(I(s)){let l=A(s,"utf-8"),{parsed:T}=S(l);i=T[u]}if(!i)i=process.env[u];let a=A(r,"utf-8"),{parsed:f}=S(a,{privateKey:i});if(e&&!n.all){let l=f[e];if(l===void 0)return{success:!1,error:`Key not found: ${e}`};return{success:!0,output:l}}let p=n.all?{...process.env,...f}:f,E;switch(n.format){case"shell":E=Object.entries(p).map(([l,T])=>`${l}=${T}`).join(" ");break;case"eval":E=Object.entries(p).map(([l,T])=>`${l}="${T}"`).join(`
|
|
23
|
+
`);break;case"json":default:E=n.prettyPrint?JSON.stringify(p,null,2):JSON.stringify(p);break}return{success:!0,output:E}}catch(i){return{success:!1,error:`Failed to get: ${i instanceof Error?i.message:"Unknown error"}`}}}function Jn(e,n={}){let t=n.cwd||process.cwd(),r=O(t,n.keysFile||".env.keys");if(!I(r))return{success:!1,error:`Keys file not found: ${r}`};try{let i=A(r,"utf-8"),{parsed:s}=S(i),c=((n.file||".env").split("/").pop()||"").replace(/^\.env\./,"").replace(/^\.env$/,"").toUpperCase(),u=c?`DOTENV_PUBLIC_KEY_${c}`:"DOTENV_PUBLIC_KEY",a=c?`DOTENV_PRIVATE_KEY_${c}`:"DOTENV_PRIVATE_KEY";if(e){let E=s[e];if(!E)return{success:!1,error:`Key not found: ${e}`};return{success:!0,output:E}}let f={[u]:s[u],[a]:s[a]};return{success:!0,output:n.format==="shell"?`${u}=${f[u]} ${a}=${f[a]}`:JSON.stringify(f)}}catch(i){return{success:!1,error:`Failed to get keypair: ${i instanceof Error?i.message:"Unknown error"}`}}}function rn(e,n,t,r){let i=e.split(`
|
|
24
24
|
`),s=!1,o=!1;for(let d=0;d<i.length;d++){let c=i[d];if(c===void 0)continue;if(c.startsWith(`${t}=`))i[d]=`${t}="${n.publicKey}"`,s=!0;else if(c.startsWith(`${r}=`))i[d]=`${r}="${n.privateKey}"`,o=!0}if(!s)i.push(`${t}="${n.publicKey}"`);if(!o)i.push(`${r}="${n.privateKey}"`);return`${i.join(`
|
|
25
25
|
`).replace(/\n+$/,"")}
|
|
26
|
-
`}function
|
|
27
|
-
`)}}let u=k(),a=
|
|
28
|
-
`)};let f=A(s),p=A(o),E=rn(p.toString("utf8"),u,d,c),l=`${process.pid}-${Date.now()}`,T=O(
|
|
29
|
-
`).map((n)=>n.trim()).filter(Boolean).filter((n)=>n!==".env.example").filter((n)=>/(?:^|\/)\.env(?:\.|$)/.test(n)).filter((n)=>!n.endsWith(".env.keys"))}function
|
|
26
|
+
`}function Zn(e={}){let n=tn({file:e.file,keysFile:e.keysFile,stdout:!0,cwd:e.cwd});if(!n.success)return n;if(n.output===void 0)return{success:!1,error:"Rotation produced no decrypted content"};let t=e.cwd||process.cwd(),r=e.file||".env",i=e.keysFile||".env.keys",s=O(t,r),o=O(t,i),{publicKeyName:d,privateKeyName:c}=w(e.file);if(e.dryRun){let _=nn(n.output,e);return{success:!0,output:["Dry run: nothing was written.",`${r}: ${_.length} value${_.length===1?"":"s"} would be re-encrypted under a new ${d}.`,`${i}: ${d} and ${c} would be replaced.`,`The current ${c} decrypts nothing once that happens, so keep a copy until the rotation is verified.`].join(`
|
|
27
|
+
`)}}let u=k(),a=me(n.output,u.publicKey,d,e);if(e.stdout)return{success:!0,output:a,notice:[`Nothing was written. To adopt the output above, put this keypair in ${i}:`,"",`${d}="${u.publicKey}"`,`${c}="${u.privateKey}"`,"","Without it that output cannot be decrypted. Run without --stdout to have both applied together."].join(`
|
|
28
|
+
`)};let f=A(s),p=A(o),E=rn(p.toString("utf8"),u,d,c),l=`${process.pid}-${Date.now()}`,T=O(ye(s),`.${Te(s)}.${l}.rotate`),v=O(ye(o),`.${Te(o)}.${l}.rotate`);try{N(T,a,{encoding:"utf8",mode:384}),N(v,E,{encoding:"utf8",mode:384}),ge(T,s);try{ge(v,o)}catch(_){throw N(s,f),_}return{success:!0,output:`\u2714 rotated (${r}) to encrypted:v2`}}catch(_){if(!I(o))N(o,p,{mode:384});return{success:!1,error:`Failed to rotate without exposing plaintext: ${_ instanceof Error?_.message:"Unknown error"}`}}finally{_e(T,{force:!0}),_e(v,{force:!0})}}function sn(e){return typeof e==="string"&&(e.startsWith("encrypted:")||e.startsWith("enc:"))}var on=/(?:^|_)(?:PASSWORD|PASSWD|SECRET|TOKEN|APIKEY|API_KEY|CREDENTIAL|CREDENTIALS|PRIVATE|SALT|DSN|CERT|CIPHER|SIGNATURE|WEBHOOK)(?:_|$)|(?:^|_)(?:ACCESS|SECRET)_KEY(?:_|$)|_KEY$/,dn=/^DOTENV_(?:PUBLIC|PRIVATE)_KEY/,cn=/^\$\{[^}]+\}$/;function nt(e,n={}){let{placeholders:t={},strict:r=!1}=n,i=[];for(let[s,o]of Object.entries(e)){if(!o||o.trim()==="")continue;if(sn(o))continue;if(dn.test(s))continue;if(cn.test(o.trim()))continue;let d=on.test(s),c=Object.prototype.hasOwnProperty.call(t,s)&&t[s]===o;if(d&&!c){i.push({key:s,reason:"plaintext-secret"});continue}if(r)i.push({key:s,reason:"plaintext-value"})}return i}function tt(e){return e.split(`
|
|
29
|
+
`).map((n)=>n.trim()).filter(Boolean).filter((n)=>n!==".env.example").filter((n)=>/(?:^|\/)\.env(?:\.|$)/.test(n)).filter((n)=>!n.endsWith(".env.keys"))}function Oe(e){return`${e.replace(/[^a-z0-9]/gi,"").toUpperCase()}_`}function an(e,n={}){let t=n.self?Oe(n.self):void 0,r=(n.tenants??[]).filter((o)=>typeof o==="string"&&o.trim().length>0).map((o)=>({slug:o,prefix:Oe(o)})).filter(({prefix:o})=>o!==t).sort((o,d)=>d.prefix.length-o.prefix.length),i={},s={};for(let[o,d]of Object.entries(e)){let c=r.find(({prefix:u})=>o.startsWith(u));if(c){(s[c.slug]??={})[o]=d;continue}i[o]=d}return{own:i,foreign:s}}function it(e,n={}){return an(e,n).own}function st(e){return Object.entries(e.foreign).map(([n,t])=>({tenant:n,keys:Object.keys(t).sort()})).sort((n,t)=>n.tenant.localeCompare(t.tenant))}import g from"process";import{platform as un}from"os";var Ae=typeof Bun<"u",Se=typeof g<"u"&&g.versions?.node!==void 0,fn=Ae?"bun":Se?"node":"unknown",at={name:fn,version:Ae?Bun.version:Se?g.version:void 0},ee=un(),ut=ee==="win32",ft=ee==="darwin",Et=ee==="linux",Ie=Boolean(g.stdout?.isTTY),lt=typeof globalThis.window<"u",En=Boolean(g.env.CI||g.env.CONTINUOUS_INTEGRATION||g.env.BUILD_NUMBER||g.env.RUN_ID),pt=Boolean(g.env.DEBUG||g.env.VERBOSE||g.argv.includes("--debug")||g.argv.includes("--verbose")),ln=En||!Ie,gt=Boolean(!ln&&(Ie||g.env.COLORTERM||g.env.FORCE_COLOR||g.env.TERM&&g.env.TERM!=="dumb")),Z={github:{name:"GitHub Actions",detected:Boolean(g.env.GITHUB_ACTIONS)},gitlab:{name:"GitLab CI",detected:Boolean(g.env.GITLAB_CI)},circle:{name:"CircleCI",detected:Boolean(g.env.CIRCLECI)},travis:{name:"Travis CI",detected:Boolean(g.env.TRAVIS)},jenkins:{name:"Jenkins",detected:Boolean(g.env.JENKINS_URL)},vercel:{name:"Vercel",detected:Boolean(g.env.VERCEL)},netlify:{name:"Netlify",detected:Boolean(g.env.NETLIFY)},heroku:{name:"Heroku",detected:Boolean(g.env.DYNO)},aws:{name:"AWS",detected:Boolean(g.env.AWS_REGION||g.env.AWS_LAMBDA_FUNCTION_NAME)},azure:{name:"Azure",detected:Boolean(g.env.AZURE_HTTP_USER_AGENT)},cloudflare:{name:"Cloudflare",detected:Boolean(g.env.CF_PAGES)},railway:{name:"Railway",detected:Boolean(g.env.RAILWAY_ENVIRONMENT)},render:{name:"Render",detected:Boolean(g.env.RENDER)}},pn=Object.keys(Z).find((e)=>{let n=Z[e];return n!==void 0&&n.detected})||"unknown",_t=Z[pn]||{name:"Unknown",detected:!1};var he=new Set;function Tn(e){if(he.has(e))return;he.add(e);let n=J();console.warn(`[env] warning: "${e}" is encrypted but no usable private key was found for the "${n}" environment; falling back to its default. Set DOTENV_PRIVATE_KEY_${n.toUpperCase()} or ship .env.keys.`)}var yn={get:(e,n)=>{let t=e,r=t[n];if(typeof r==="string"&&(r.startsWith("encrypted:")||r.startsWith("enc:"))){let s=Ee(r);if(s===void 0){Tn(n),delete t[n];return}t[n]=s,r=s}let i=["_PORT","_TIMEOUT","_TTL","_SIZE","_LIMIT","_MAX","_MIN","_INTERVAL","_RETRIES","_CONCURRENCY","_WORKERS","_CONNECTIONS"];if(typeof r==="string"&&/^\d+$/.test(r)&&!r.startsWith("0")&&i.some((s)=>n.endsWith(s)))return Number(r);if(typeof r==="string"){let s=r.toLowerCase();if(s==="true")return!0;if(s==="false")return!1}return r},set:(e,n,t)=>Reflect.set(e,n,t,e),deleteProperty:(e,n)=>Reflect.deleteProperty(e,n)};function Rn(){return typeof Bun<"u"?Bun.env:gn.env}var Pe=new Proxy(Rn(),yn);function At(e,n,t){let r=t?.path||_n(".env"),s=Ne.readFileSync(r,"utf-8").split(`
|
|
30
30
|
`),o=s.findIndex((u)=>u.startsWith(`${e}=`)),c=/[\s"'#$\\]/.test(n)?`"${n.replace(/"/g,"\\\"")}"`:n;if(o!==-1)s[o]=`${e}=${c}`;else s.push(`${e}=${c}`);Ne.writeFileSync(r,s.join(`
|
|
31
|
-
`))}function St(e=Pe){let n=[],t=e;for(let[r,i]of Object.entries(
|
|
31
|
+
`))}function St(e=Pe){let n=[],t=e;for(let[r,i]of Object.entries(pe)){let s=t[r];if(s!==void 0&&s!==""&&!i.includes(String(s)))n.push(`${r}="${s}" is not valid. Allowed values: ${i.join(", ")}`)}return n}function It(e,n=Pe){let t=[],r=n;for(let i of e){let s=r[i];if(s===void 0||s===""||s===null)t.push(i)}if(t.length>0)throw Error(`[env] Missing required environment variable(s): ${t.join(", ")}. Set them in .env or your process environment before booting.`);return n}export{on as SECRET_NAME_PATTERN,J as activeEnvName,Le as aesDecrypt,vn as aesEncrypt,Bn as autoLoadEnv,tn as decryptEnv,Ee as decryptEnvValue,K as decryptValue,Fn as defineEnv,Qn as encryptEnv,B as encryptValue,Pe as env,pe as envEnum,w as envKeyNames,en as envPlugin,st as foreignTenantKeys,k as generateKeypair,zn as getEnv,Jn as getKeypair,q as getPrivateKey,Ie as hasTTY,lt as hasWindow,Ae as isBun,En as isCI,gt as isColorSupported,pt as isDebug,sn as isEncryptedValue,On as isLegacyEncryptedValue,Et as isLinux,ft as isMacOS,ln as isMinimal,Se as isNode,ut as isWindows,le as loadEnv,bn as loadEnvFiles,An as migrateEncryptedValue,S as parse,Sn as parseEnvFromKey,an as partitionTenantEnv,nt as plaintextSecrets,ee as platform,Rn as process,pn as provider,_t as providerInfo,It as requireEnv,xn as resetPrivateKeyCache,Xn as resolveEnvFile,Ze as resolvePrivateKey,ve as reusableEnvPublicKey,Zn as rotateKeypair,fn as runtime,at as runtimeInfo,qn as setEnv,it as stripForeignTenantEnv,Oe as tenantEnvPrefix,tt as trackedEnvFiles,St as validateEnv,At as writeEnv};
|
package/dist/parser.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{createCipheriv as k,createDecipheriv as b,createHash as m,createPrivateKey as T,createPublicKey as K,diffieHellman as B,generateKeyPairSync as P,hkdfSync as _,randomBytes as y}from"crypto";var E="x25519-public:",w="x25519-private:",g="encrypted:v2:",v="encrypted:",S=Buffer.from("stacks-env:v2","utf8"),R="Environment decryption failed: authentication or format error";function V(t){if(t.length===32)return t;return m("sha256").update(t).digest()}function ie(t,r){let e=y(16),n=k("aes-256-gcm",V(r),e);return{ciphertext:Buffer.concat([n.update(t,"utf8"),n.final()]).toString("hex"),iv:e.toString("hex"),authTag:n.getAuthTag().toString("hex")}}function D(t,r,e,n){try{let i=b("aes-256-gcm",V(r),Buffer.from(e,"hex"));return i.setAuthTag(Buffer.from(n,"hex")),Buffer.concat([i.update(Buffer.from(t,"hex")),i.final()]).toString("utf8")}catch{throw Error("Decryption failed: authentication or format error")}}function l(t){return t.toString("base64url")}function d(t,r,e){if(typeof t!=="string"||t.length>0&&!/^[A-Za-z0-9_-]+$/.test(t))throw Error(`${r} is not canonical base64url`);let n=Buffer.from(t,"base64url");if(l(n)!==t)throw Error(`${r} is not canonical base64url`);if(e!==void 0&&n.length!==e)throw Error(`${r} has an invalid length`);return n}function A(t){if(!t.startsWith(E))throw Error("Legacy or invalid public key. Run buddy env:rotate before creating new ciphertext.");let r=K({key:d(t.slice(E.length),"public key"),format:"der",type:"spki"});if(r.asymmetricKeyType!=="x25519")throw Error("Public key is not X25519");return r}function W(t){if(!t.startsWith(w))throw Error("Private key is not a version 2 X25519 key");let r=T({key:d(t.slice(w.length),"private key"),format:"der",type:"pkcs8"});if(r.asymmetricKeyType!=="x25519")throw Error("Private key is not X25519");return r}function N(t){return Buffer.from(`stacks-env:v2;${t.epk};${t.salt};${t.nonce}`,"utf8")}function se(){let{publicKey:t,privateKey:r}=P("x25519"),e=t.export({format:"der",type:"spki"}),n=r.export({format:"der",type:"pkcs8"});return{publicKey:`${E}${l(e)}`,privateKey:`${w}${l(n)}`}}function C(t,r){let e=A(r),n=P("x25519"),i=l(n.publicKey.export({format:"der",type:"spki"})),s=y(16),a=y(12),c=B({privateKey:n.privateKey,publicKey:e}),f=Buffer.from(_("sha256",c,s,S,32)),u={epk:i,salt:l(s),nonce:l(a)};try{let o=k("aes-256-gcm",f,a);o.setAAD(N(u));let p=Buffer.concat([o.update(t,"utf8"),o.final()]),h={v:2,...u,ciphertext:l(p),tag:l(o.getAuthTag())};return`${g}${l(Buffer.from(JSON.stringify(h),"utf8"))}`}finally{c.fill(0),f.fill(0)}}function I(t){let r=d(t.slice(g.length),"envelope").toString("utf8"),e=JSON.parse(r);if(!e||typeof e!=="object"||Array.isArray(e))throw Error("envelope is not an object");let n=Object.keys(e).sort(),i=["ciphertext","epk","nonce","salt","tag","v"];if(n.length!==i.length||n.some((s,a)=>s!==i[a]))throw Error("envelope fields are invalid");if(e.v!==2)throw Error("envelope version is unsupported");for(let s of["epk","salt","nonce","ciphertext","tag"])if(typeof e[s]!=="string")throw Error(`${s} is invalid`);return e}function F(t,r){try{let e=I(t),n=W(r),i=K({key:d(e.epk,"ephemeral public key"),format:"der",type:"spki"});if(i.asymmetricKeyType!=="x25519")throw Error("ephemeral key is not X25519");let s=d(e.salt,"salt",16),a=d(e.nonce,"nonce",12),c=d(e.ciphertext,"ciphertext"),f=d(e.tag,"tag",16),u=B({privateKey:n,publicKey:i}),o=Buffer.from(_("sha256",u,s,S,32));try{let p=b("aes-256-gcm",o,a);return p.setAAD(N(e)),p.setAuthTag(f),Buffer.concat([p.update(c),p.final()]).toString("utf8")}finally{u.fill(0),o.fill(0)}}catch{throw Error(R)}}function L(t,r){try{if(!/^[0-9a-f]{64}$/.test(r))throw Error("invalid legacy private key");let e=Buffer.from(t.slice(v.length),"base64");if(e.length<32)throw Error("invalid legacy payload");let n=m("sha256").update(Buffer.from(r,"hex")).digest(),i=m("sha256").update(n).digest();return D(e.subarray(32).toString("hex"),i,e.subarray(0,16).toString("hex"),e.subarray(16,32).toString("hex"))}catch{throw Error(R)}}function oe(t){return t.startsWith(v)&&!t.startsWith(g)}function x(t,r){if(!t.startsWith(v))return t;return t.startsWith(g)?F(t,r):L(t,r)}function ae(t,r,e){return C(x(t,r),e)}function ce(t){let r=t.match(/^DOTENV_PRIVATE_KEY_(.+)$/);return r&&r[1]?r[1].toLowerCase():""}function fe(t=""){return t?process.env[`DOTENV_PRIVATE_KEY_${t.toUpperCase()}`]:process.env.DOTENV_PRIVATE_KEY}
|
|
2
|
+
import{spawnSync as Y}from"child_process";import{readFileSync as X}from"fs";import{arch as j,hostname as U,platform as O,release as H,userInfo as z}from"os";import{basename as M,dirname as q,resolve as G}from"path";import{createCipheriv as k,createDecipheriv as b,createHash as m,createPrivateKey as T,createPublicKey as K,diffieHellman as B,generateKeyPairSync as P,hkdfSync as _,randomBytes as y}from"crypto";var E="x25519-public:",w="x25519-private:",g="encrypted:v2:",v="encrypted:",S=Buffer.from("stacks-env:v2","utf8"),R="Environment decryption failed: authentication or format error";function V(t){if(t.length===32)return t;return m("sha256").update(t).digest()}function ie(t,r){let e=y(16),n=k("aes-256-gcm",V(r),e);return{ciphertext:Buffer.concat([n.update(t,"utf8"),n.final()]).toString("hex"),iv:e.toString("hex"),authTag:n.getAuthTag().toString("hex")}}function D(t,r,e,n){try{let i=b("aes-256-gcm",V(r),Buffer.from(e,"hex"));return i.setAuthTag(Buffer.from(n,"hex")),Buffer.concat([i.update(Buffer.from(t,"hex")),i.final()]).toString("utf8")}catch{throw Error("Decryption failed: authentication or format error")}}function l(t){return t.toString("base64url")}function d(t,r,e){if(typeof t!=="string"||t.length>0&&!/^[A-Za-z0-9_-]+$/.test(t))throw Error(`${r} is not canonical base64url`);let n=Buffer.from(t,"base64url");if(l(n)!==t)throw Error(`${r} is not canonical base64url`);if(e!==void 0&&n.length!==e)throw Error(`${r} has an invalid length`);return n}function A(t){if(!t.startsWith(E))throw Error("Legacy or invalid public key. Run buddy env:rotate before creating new ciphertext.");let r=K({key:d(t.slice(E.length),"public key"),format:"der",type:"spki"});if(r.asymmetricKeyType!=="x25519")throw Error("Public key is not X25519");return r}function W(t){if(!t.startsWith(w))throw Error("Private key is not a version 2 X25519 key");let r=T({key:d(t.slice(w.length),"private key"),format:"der",type:"pkcs8"});if(r.asymmetricKeyType!=="x25519")throw Error("Private key is not X25519");return r}function N(t){return Buffer.from(`stacks-env:v2;${t.epk};${t.salt};${t.nonce}`,"utf8")}function se(){let{publicKey:t,privateKey:r}=P("x25519"),e=t.export({format:"der",type:"spki"}),n=r.export({format:"der",type:"pkcs8"});return{publicKey:`${E}${l(e)}`,privateKey:`${w}${l(n)}`}}function C(t,r){let e=A(r),n=P("x25519"),i=l(n.publicKey.export({format:"der",type:"spki"})),s=y(16),a=y(12),c=B({privateKey:n.privateKey,publicKey:e}),f=Buffer.from(_("sha256",c,s,S,32)),u={epk:i,salt:l(s),nonce:l(a)};try{let o=k("aes-256-gcm",f,a);o.setAAD(N(u));let p=Buffer.concat([o.update(t,"utf8"),o.final()]),h={v:2,...u,ciphertext:l(p),tag:l(o.getAuthTag())};return`${g}${l(Buffer.from(JSON.stringify(h),"utf8"))}`}finally{c.fill(0),f.fill(0)}}function I(t){let r=d(t.slice(g.length),"envelope").toString("utf8"),e=JSON.parse(r);if(!e||typeof e!=="object"||Array.isArray(e))throw Error("envelope is not an object");let n=Object.keys(e).sort(),i=["ciphertext","epk","nonce","salt","tag","v"];if(n.length!==i.length||n.some((s,a)=>s!==i[a]))throw Error("envelope fields are invalid");if(e.v!==2)throw Error("envelope version is unsupported");for(let s of["epk","salt","nonce","ciphertext","tag"])if(typeof e[s]!=="string")throw Error(`${s} is invalid`);return e}function F(t,r){try{let e=I(t),n=W(r),i=K({key:d(e.epk,"ephemeral public key"),format:"der",type:"spki"});if(i.asymmetricKeyType!=="x25519")throw Error("ephemeral key is not X25519");let s=d(e.salt,"salt",16),a=d(e.nonce,"nonce",12),c=d(e.ciphertext,"ciphertext"),f=d(e.tag,"tag",16),u=B({privateKey:n,publicKey:i}),o=Buffer.from(_("sha256",u,s,S,32));try{let p=b("aes-256-gcm",o,a);return p.setAAD(N(e)),p.setAuthTag(f),Buffer.concat([p.update(c),p.final()]).toString("utf8")}finally{u.fill(0),o.fill(0)}}catch{throw Error(R)}}function L(t,r){try{if(!/^[0-9a-f]{64}$/.test(r))throw Error("invalid legacy private key");let e=Buffer.from(t.slice(v.length),"base64");if(e.length<32)throw Error("invalid legacy payload");let n=m("sha256").update(Buffer.from(r,"hex")).digest(),i=m("sha256").update(n).digest();return D(e.subarray(32).toString("hex"),i,e.subarray(0,16).toString("hex"),e.subarray(16,32).toString("hex"))}catch{throw Error(R)}}function oe(t){return t.startsWith(v)&&!t.startsWith(g)}function x(t,r){if(!t.startsWith(v))return t;return t.startsWith(g)?F(t,r):L(t,r)}function ae(t,r,e){return C(x(t,r),e)}function ce(t){let r=t.match(/^DOTENV_PRIVATE_KEY_(.+)$/);return r&&r[1]?r[1].toLowerCase():""}function fe(t=""){return t?process.env[`DOTENV_PRIVATE_KEY_${t.toUpperCase()}`]:process.env.DOTENV_PRIVATE_KEY}function J(t,r={}){let e={},n=[],i=[],s=t.split(`
|
|
3
3
|
`);for(let a of s){let c=a.trim();if(!c||c.startsWith("#"))continue;if(c.startsWith("DOTENV_PUBLIC_KEY=")){let p=c.match(/^DOTENV_PUBLIC_KEY=["']?([^"'\n]+)["']?/);if(p&&p[1]!==void 0)e.DOTENV_PUBLIC_KEY=p[1];continue}let f=c.match(/^([^=]+)=(.*)$/);if(!f||f[1]===void 0||f[2]===void 0)continue;let u=f[1].trim(),o=f[2].trim();if(o.startsWith('"')&&o.endsWith('"')||o.startsWith("'")&&o.endsWith("'")){if(o=o.slice(1,-1),o.includes("\\n"))o=o.replace(/\\n/g,`
|
|
4
4
|
`)}if(o.startsWith("encrypted:")||o.startsWith("enc:")){if(!r.privateKey){i.push(u);continue}try{let p=o.startsWith("enc:")?`encrypted:${o.slice(4)}`:o;o=x(p,r.privateKey)}catch(p){n.push(`Failed to decrypt ${u}: ${p instanceof Error?p.message:"Unknown error"}`)}}o=Z(o,{...r.processEnv||process.env,...e}),o=re(o),e[u]=o}return{parsed:e,errors:n,skippedEncrypted:i}}function Z(t,r){return t.replace(/\$\{([^}]+)\}/g,(e,n)=>{let i=n.match(/^([^:\-+]+)(:-|-)(.+)$/);if(i){let[,a,c,f]=i,u=r[a];if(c===":-")return u||f;else return u!==void 0?u:f}let s=n.match(/^([^:\-+]+)(:?\+)(.+)$/);if(s){let[,a,c,f]=s,u=r[a];if(c===":+")return u?f:"";else return u!==void 0?f:""}return r[n]||""})}var Q=new Set(["date","hostname","whoami","uname","pwd","echo","printf","cat","basename","dirname"]);function ee(t){let r=[],e="",n=null,i=!1;for(let s of t.trim()){if(i){e+=s,i=!1;continue}if(s==="\\"&&n!=="'"){i=!0;continue}if(n){if(s===n)n=null;else e+=s;continue}if(s==='"'||s==="'"){n=s;continue}if(/\s/.test(s)){if(e)r.push(e),e="";continue}e+=s}if(i||n)throw Error("Command substitution contains an unterminated escape or quote");if(e)r.push(e);return r}function te(t){let[r,...e]=t,n=e.some((i)=>i.startsWith("-"));if(r==="echo"&&!n)return e.join(" ");if(r==="printf"&&e.length===1&&!e[0]?.includes("%"))return e[0];if(r==="hostname"&&e.length===0)return U();if(r==="whoami"&&e.length===0)return z().username;if(r==="pwd"&&e.length===0)return process.cwd();if(r==="basename"&&e.length===1)return M(e[0]??"");if(r==="dirname"&&e.length===1)return q(e[0]??"");if(r==="cat"&&e.length>0&&!n)return e.map((i)=>X(G(process.cwd(),i),"utf8")).join("");if(r==="uname"){let i=e[0]??"-s";if(e.length<=1&&i==="-m")return j();if(e.length<=1&&i==="-r")return H();if(e.length<=1&&i==="-s")return{aix:"AIX",android:"Android",cygwin:"CYGWIN",darwin:"Darwin",freebsd:"FreeBSD",haiku:"Haiku",linux:"Linux",netbsd:"NetBSD",openbsd:"OpenBSD",sunos:"SunOS",win32:"Windows_NT"}[O()]??O()}return}function re(t){return t.replace(/\$\(([^)]+)\)/g,(r,e)=>{try{let n=ee(e),i=n[0];if(!i||!Q.has(i))return console.warn(`[env] Blocked command substitution for disallowed command: ${i}`),"";let s=te(n);if(s!==void 0)return s.trim();let a=Y(i,n.slice(1),{encoding:"utf8",env:process.env});if(a.status===0)return a.stdout.trim();let c=a.stderr.trim();console.warn(`[env] Command substitution failed (exit code ${a.status??"unknown"}): ${i}${c?`: ${c}`:""}`)}catch(n){console.warn(`[env] Command substitution error: ${n instanceof Error?n.message:String(n)}`)}return""})}async function me(t,r={}){let e={},n=[],i=[];for(let s of t)try{let a=Bun.file(s);if(!a.size)continue;let c=await a.text(),{parsed:f,errors:u,skippedEncrypted:o}=J(c,r);n.push(...u),i.push(...o);for(let[p,h]of Object.entries(f)){if(!r.overload&&e[p]!==void 0)continue;e[p]=h}}catch(a){if(a?.code==="ENOENT")continue;n.push(`Failed to read ${s}: ${a instanceof Error?a.message:String(a)}`)}return{parsed:e,errors:n,skippedEncrypted:i}}export{me as loadEnvFiles,J as parse};
|
package/dist/plugin.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{createCipheriv as U,createDecipheriv as j,createHash as R,createPrivateKey as ne,createPublicKey as X,diffieHellman as z,generateKeyPairSync as H,hkdfSync as q,randomBytes as S}from"crypto";var I="x25519-public:",C="x25519-private:",N="encrypted:v2:",F="encrypted:",M=Buffer.from("stacks-env:v2","utf8"),G="Environment decryption failed: authentication or format error";function J(e){if(e.length===32)return e;return R("sha256").update(e).digest()}function Ne(e,t){let n=S(16),r=U("aes-256-gcm",J(t),n);return{ciphertext:Buffer.concat([r.update(e,"utf8"),r.final()]).toString("hex"),iv:n.toString("hex"),authTag:r.getAuthTag().toString("hex")}}function re(e,t,n,r){try{let s=j("aes-256-gcm",J(t),Buffer.from(n,"hex"));return s.setAuthTag(Buffer.from(r,"hex")),Buffer.concat([s.update(Buffer.from(e,"hex")),s.final()]).toString("utf8")}catch{throw Error("Decryption failed: authentication or format error")}}function h(e){return e.toString("base64url")}function y(e,t,n){if(typeof e!=="string"||e.length>0&&!/^[A-Za-z0-9_-]+$/.test(e))throw Error(`${t} is not canonical base64url`);let r=Buffer.from(e,"base64url");if(h(r)!==e)throw Error(`${t} is not canonical base64url`);if(n!==void 0&&r.length!==n)throw Error(`${t} has an invalid length`);return r}function se(e){if(!e.startsWith(I))throw Error("Legacy or invalid public key. Run buddy env:rotate before creating new ciphertext.");let t=X({key:y(e.slice(I.length),"public key"),format:"der",type:"spki"});if(t.asymmetricKeyType!=="x25519")throw Error("Public key is not X25519");return t}function ie(e){if(!e.startsWith(C))throw Error("Private key is not a version 2 X25519 key");let t=ne({key:y(e.slice(C.length),"private key"),format:"der",type:"pkcs8"});if(t.asymmetricKeyType!=="x25519")throw Error("Private key is not X25519");return t}function Z(e){return Buffer.from(`stacks-env:v2;${e.epk};${e.salt};${e.nonce}`,"utf8")}function Oe(){let{publicKey:e,privateKey:t}=H("x25519"),n=e.export({format:"der",type:"spki"}),r=t.export({format:"der",type:"pkcs8"});return{publicKey:`${I}${h(n)}`,privateKey:`${C}${h(r)}`}}function oe(e,t){let n=se(t),r=H("x25519"),s=h(r.publicKey.export({format:"der",type:"spki"})),i=S(16),c=S(12),a=z({privateKey:r.privateKey,publicKey:n}),u=Buffer.from(q("sha256",a,i,M,32)),f={epk:s,salt:h(i),nonce:h(c)};try{let o=U("aes-256-gcm",u,c);o.setAAD(Z(f));let p=Buffer.concat([o.update(e,"utf8"),o.final()]),l={v:2,...f,ciphertext:h(p),tag:h(o.getAuthTag())};return`${N}${h(Buffer.from(JSON.stringify(l),"utf8"))}`}finally{a.fill(0),u.fill(0)}}function ce(e){let t=y(e.slice(N.length),"envelope").toString("utf8"),n=JSON.parse(t);if(!n||typeof n!=="object"||Array.isArray(n))throw Error("envelope is not an object");let r=Object.keys(n).sort(),s=["ciphertext","epk","nonce","salt","tag","v"];if(r.length!==s.length||r.some((i,c)=>i!==s[c]))throw Error("envelope fields are invalid");if(n.v!==2)throw Error("envelope version is unsupported");for(let i of["epk","salt","nonce","ciphertext","tag"])if(typeof n[i]!=="string")throw Error(`${i} is invalid`);return n}function ae(e,t){try{let n=ce(e),r=ie(t),s=X({key:y(n.epk,"ephemeral public key"),format:"der",type:"spki"});if(s.asymmetricKeyType!=="x25519")throw Error("ephemeral key is not X25519");let i=y(n.salt,"salt",16),c=y(n.nonce,"nonce",12),a=y(n.ciphertext,"ciphertext"),u=y(n.tag,"tag",16),f=z({privateKey:r,publicKey:s}),o=Buffer.from(q("sha256",f,i,M,32));try{let p=j("aes-256-gcm",o,c);return p.setAAD(Z(n)),p.setAuthTag(u),Buffer.concat([p.update(a),p.final()]).toString("utf8")}finally{f.fill(0),o.fill(0)}}catch{throw Error(G)}}function fe(e,t){try{if(!/^[0-9a-f]{64}$/.test(t))throw Error("invalid legacy private key");let n=Buffer.from(e.slice(F.length),"base64");if(n.length<32)throw Error("invalid legacy payload");let r=R("sha256").update(Buffer.from(t,"hex")).digest(),s=R("sha256").update(r).digest();return re(n.subarray(32).toString("hex"),s,n.subarray(0,16).toString("hex"),n.subarray(16,32).toString("hex"))}catch{throw Error(G)}}function Te(e){return e.startsWith(F)&&!e.startsWith(N)}function k(e,t){if(!e.startsWith(F))return e;return e.startsWith(N)?ae(e,t):fe(e,t)}function De(e,t,n){return oe(k(e,t),n)}function Be(e){let t=e.match(/^DOTENV_PRIVATE_KEY_(.+)$/);return t&&t[1]?t[1].toLowerCase():""}function W(e=""){return e?process.env[`DOTENV_PRIVATE_KEY_${e.toUpperCase()}`]:process.env.DOTENV_PRIVATE_KEY}import{spawnSync as ue}from"child_process";import{readFileSync as pe}from"fs";import{arch as de,hostname as le,platform as Q,release as ge,userInfo as he}from"os";import{basename as ye,dirname as me,resolve as ve}from"path";function x(e,t={}){let n={},r=[],s=[],i=e.split(`
|
|
2
|
+
import{existsSync as O}from"fs";import{readFileSync as L}from"fs";import{resolve as T}from"path";import{createCipheriv as U,createDecipheriv as j,createHash as R,createPrivateKey as ne,createPublicKey as X,diffieHellman as z,generateKeyPairSync as H,hkdfSync as q,randomBytes as S}from"crypto";var I="x25519-public:",C="x25519-private:",N="encrypted:v2:",F="encrypted:",M=Buffer.from("stacks-env:v2","utf8"),G="Environment decryption failed: authentication or format error";function J(e){if(e.length===32)return e;return R("sha256").update(e).digest()}function Ne(e,t){let n=S(16),r=U("aes-256-gcm",J(t),n);return{ciphertext:Buffer.concat([r.update(e,"utf8"),r.final()]).toString("hex"),iv:n.toString("hex"),authTag:r.getAuthTag().toString("hex")}}function re(e,t,n,r){try{let s=j("aes-256-gcm",J(t),Buffer.from(n,"hex"));return s.setAuthTag(Buffer.from(r,"hex")),Buffer.concat([s.update(Buffer.from(e,"hex")),s.final()]).toString("utf8")}catch{throw Error("Decryption failed: authentication or format error")}}function h(e){return e.toString("base64url")}function y(e,t,n){if(typeof e!=="string"||e.length>0&&!/^[A-Za-z0-9_-]+$/.test(e))throw Error(`${t} is not canonical base64url`);let r=Buffer.from(e,"base64url");if(h(r)!==e)throw Error(`${t} is not canonical base64url`);if(n!==void 0&&r.length!==n)throw Error(`${t} has an invalid length`);return r}function se(e){if(!e.startsWith(I))throw Error("Legacy or invalid public key. Run buddy env:rotate before creating new ciphertext.");let t=X({key:y(e.slice(I.length),"public key"),format:"der",type:"spki"});if(t.asymmetricKeyType!=="x25519")throw Error("Public key is not X25519");return t}function ie(e){if(!e.startsWith(C))throw Error("Private key is not a version 2 X25519 key");let t=ne({key:y(e.slice(C.length),"private key"),format:"der",type:"pkcs8"});if(t.asymmetricKeyType!=="x25519")throw Error("Private key is not X25519");return t}function Z(e){return Buffer.from(`stacks-env:v2;${e.epk};${e.salt};${e.nonce}`,"utf8")}function Oe(){let{publicKey:e,privateKey:t}=H("x25519"),n=e.export({format:"der",type:"spki"}),r=t.export({format:"der",type:"pkcs8"});return{publicKey:`${I}${h(n)}`,privateKey:`${C}${h(r)}`}}function oe(e,t){let n=se(t),r=H("x25519"),s=h(r.publicKey.export({format:"der",type:"spki"})),i=S(16),c=S(12),a=z({privateKey:r.privateKey,publicKey:n}),u=Buffer.from(q("sha256",a,i,M,32)),f={epk:s,salt:h(i),nonce:h(c)};try{let o=U("aes-256-gcm",u,c);o.setAAD(Z(f));let p=Buffer.concat([o.update(e,"utf8"),o.final()]),l={v:2,...f,ciphertext:h(p),tag:h(o.getAuthTag())};return`${N}${h(Buffer.from(JSON.stringify(l),"utf8"))}`}finally{a.fill(0),u.fill(0)}}function ce(e){let t=y(e.slice(N.length),"envelope").toString("utf8"),n=JSON.parse(t);if(!n||typeof n!=="object"||Array.isArray(n))throw Error("envelope is not an object");let r=Object.keys(n).sort(),s=["ciphertext","epk","nonce","salt","tag","v"];if(r.length!==s.length||r.some((i,c)=>i!==s[c]))throw Error("envelope fields are invalid");if(n.v!==2)throw Error("envelope version is unsupported");for(let i of["epk","salt","nonce","ciphertext","tag"])if(typeof n[i]!=="string")throw Error(`${i} is invalid`);return n}function ae(e,t){try{let n=ce(e),r=ie(t),s=X({key:y(n.epk,"ephemeral public key"),format:"der",type:"spki"});if(s.asymmetricKeyType!=="x25519")throw Error("ephemeral key is not X25519");let i=y(n.salt,"salt",16),c=y(n.nonce,"nonce",12),a=y(n.ciphertext,"ciphertext"),u=y(n.tag,"tag",16),f=z({privateKey:r,publicKey:s}),o=Buffer.from(q("sha256",f,i,M,32));try{let p=j("aes-256-gcm",o,c);return p.setAAD(Z(n)),p.setAuthTag(u),Buffer.concat([p.update(a),p.final()]).toString("utf8")}finally{f.fill(0),o.fill(0)}}catch{throw Error(G)}}function fe(e,t){try{if(!/^[0-9a-f]{64}$/.test(t))throw Error("invalid legacy private key");let n=Buffer.from(e.slice(F.length),"base64");if(n.length<32)throw Error("invalid legacy payload");let r=R("sha256").update(Buffer.from(t,"hex")).digest(),s=R("sha256").update(r).digest();return re(n.subarray(32).toString("hex"),s,n.subarray(0,16).toString("hex"),n.subarray(16,32).toString("hex"))}catch{throw Error(G)}}function Te(e){return e.startsWith(F)&&!e.startsWith(N)}function k(e,t){if(!e.startsWith(F))return e;return e.startsWith(N)?ae(e,t):fe(e,t)}function De(e,t,n){return oe(k(e,t),n)}function Be(e){let t=e.match(/^DOTENV_PRIVATE_KEY_(.+)$/);return t&&t[1]?t[1].toLowerCase():""}function W(e=""){return e?process.env[`DOTENV_PRIVATE_KEY_${e.toUpperCase()}`]:process.env.DOTENV_PRIVATE_KEY}import{spawnSync as ue}from"child_process";import{readFileSync as pe}from"fs";import{arch as de,hostname as le,platform as Q,release as ge,userInfo as he}from"os";import{basename as ye,dirname as me,resolve as ve}from"path";function x(e,t={}){let n={},r=[],s=[],i=e.split(`
|
|
3
3
|
`);for(let c of i){let a=c.trim();if(!a||a.startsWith("#"))continue;if(a.startsWith("DOTENV_PUBLIC_KEY=")){let p=a.match(/^DOTENV_PUBLIC_KEY=["']?([^"'\n]+)["']?/);if(p&&p[1]!==void 0)n.DOTENV_PUBLIC_KEY=p[1];continue}let u=a.match(/^([^=]+)=(.*)$/);if(!u||u[1]===void 0||u[2]===void 0)continue;let f=u[1].trim(),o=u[2].trim();if(o.startsWith('"')&&o.endsWith('"')||o.startsWith("'")&&o.endsWith("'")){if(o=o.slice(1,-1),o.includes("\\n"))o=o.replace(/\\n/g,`
|
|
4
|
-
`)}if(o.startsWith("encrypted:")||o.startsWith("enc:")){if(!t.privateKey){s.push(f);continue}try{let p=o.startsWith("enc:")?`encrypted:${o.slice(4)}`:o;o=k(p,t.privateKey)}catch(p){r.push(`Failed to decrypt ${f}: ${p instanceof Error?p.message:"Unknown error"}`)}}o=Ee(o,{...t.processEnv||process.env,...n}),o=_e(o),n[f]=o}return{parsed:n,errors:r,skippedEncrypted:s}}function Ee(e,t){return e.replace(/\$\{([^}]+)\}/g,(n,r)=>{let s=r.match(/^([^:\-+]+)(:-|-)(.+)$/);if(s){let[,c,a,u]=s,f=t[c];if(a===":-")return f||u;else return f!==void 0?f:u}let i=r.match(/^([^:\-+]+)(:?\+)(.+)$/);if(i){let[,c,a,u]=i,f=t[c];if(a===":+")return f?u:"";else return f!==void 0?u:""}return t[r]||""})}var we=new Set(["date","hostname","whoami","uname","pwd","echo","printf","cat","basename","dirname"]);function ke(e){let t=[],n="",r=null,s=!1;for(let i of e.trim()){if(s){n+=i,s=!1;continue}if(i==="\\"&&r!=="'"){s=!0;continue}if(r){if(i===r)r=null;else n+=i;continue}if(i==='"'||i==="'"){r=i;continue}if(/\s/.test(i)){if(n)t.push(n),n="";continue}n+=i}if(s||r)throw Error("Command substitution contains an unterminated escape or quote");if(n)t.push(n);return t}function xe(e){let[t,...n]=e,r=n.some((s)=>s.startsWith("-"));if(t==="echo"&&!r)return n.join(" ");if(t==="printf"&&n.length===1&&!n[0]?.includes("%"))return n[0];if(t==="hostname"&&n.length===0)return le();if(t==="whoami"&&n.length===0)return he().username;if(t==="pwd"&&n.length===0)return process.cwd();if(t==="basename"&&n.length===1)return ye(n[0]??"");if(t==="dirname"&&n.length===1)return me(n[0]??"");if(t==="cat"&&n.length>0&&!r)return n.map((s)=>pe(ve(process.cwd(),s),"utf8")).join("");if(t==="uname"){let s=n[0]??"-s";if(n.length<=1&&s==="-m")return de();if(n.length<=1&&s==="-r")return ge();if(n.length<=1&&s==="-s")return{aix:"AIX",android:"Android",cygwin:"CYGWIN",darwin:"Darwin",freebsd:"FreeBSD",haiku:"Haiku",linux:"Linux",netbsd:"NetBSD",openbsd:"OpenBSD",sunos:"SunOS",win32:"Windows_NT"}[Q()]??Q()}return}function _e(e){return e.replace(/\$\(([^)]+)\)/g,(t,n)=>{try{let r=ke(n),s=r[0];if(!s||!we.has(s))return console.warn(`[env] Blocked command substitution for disallowed command: ${s}`),"";let i=xe(r);if(i!==void 0)return i.trim();let c=ue(s,r.slice(1),{encoding:"utf8",env:process.env});if(c.status===0)return c.stdout.trim();let a=c.stderr.trim();console.warn(`[env] Command substitution failed (exit code ${c.status??"unknown"}): ${s}${a?`: ${a}`:""}`)}catch(r){console.warn(`[env] Command substitution error: ${r instanceof Error?r.message:String(r)}`)}return""})}async function We(e,t={}){let n={},r=[],s=[];for(let i of e)try{let c=Bun.file(i);if(!c.size)continue;let a=await c.text(),{parsed:u,errors:f,skippedEncrypted:o}=x(a,t);r.push(...f),s.push(...o);for(let[p,l]of Object.entries(u)){if(!t.overload&&n[p]!==void 0)continue;n[p]=l}}catch(c){if(c?.code==="ENOENT")continue;r.push(`Failed to read ${i}: ${c instanceof Error?c.message:String(c)}`)}return{parsed:n,errors:r,skippedEncrypted:s}}
|
|
4
|
+
`)}if(o.startsWith("encrypted:")||o.startsWith("enc:")){if(!t.privateKey){s.push(f);continue}try{let p=o.startsWith("enc:")?`encrypted:${o.slice(4)}`:o;o=k(p,t.privateKey)}catch(p){r.push(`Failed to decrypt ${f}: ${p instanceof Error?p.message:"Unknown error"}`)}}o=Ee(o,{...t.processEnv||process.env,...n}),o=_e(o),n[f]=o}return{parsed:n,errors:r,skippedEncrypted:s}}function Ee(e,t){return e.replace(/\$\{([^}]+)\}/g,(n,r)=>{let s=r.match(/^([^:\-+]+)(:-|-)(.+)$/);if(s){let[,c,a,u]=s,f=t[c];if(a===":-")return f||u;else return f!==void 0?f:u}let i=r.match(/^([^:\-+]+)(:?\+)(.+)$/);if(i){let[,c,a,u]=i,f=t[c];if(a===":+")return f?u:"";else return f!==void 0?u:""}return t[r]||""})}var we=new Set(["date","hostname","whoami","uname","pwd","echo","printf","cat","basename","dirname"]);function ke(e){let t=[],n="",r=null,s=!1;for(let i of e.trim()){if(s){n+=i,s=!1;continue}if(i==="\\"&&r!=="'"){s=!0;continue}if(r){if(i===r)r=null;else n+=i;continue}if(i==='"'||i==="'"){r=i;continue}if(/\s/.test(i)){if(n)t.push(n),n="";continue}n+=i}if(s||r)throw Error("Command substitution contains an unterminated escape or quote");if(n)t.push(n);return t}function xe(e){let[t,...n]=e,r=n.some((s)=>s.startsWith("-"));if(t==="echo"&&!r)return n.join(" ");if(t==="printf"&&n.length===1&&!n[0]?.includes("%"))return n[0];if(t==="hostname"&&n.length===0)return le();if(t==="whoami"&&n.length===0)return he().username;if(t==="pwd"&&n.length===0)return process.cwd();if(t==="basename"&&n.length===1)return ye(n[0]??"");if(t==="dirname"&&n.length===1)return me(n[0]??"");if(t==="cat"&&n.length>0&&!r)return n.map((s)=>pe(ve(process.cwd(),s),"utf8")).join("");if(t==="uname"){let s=n[0]??"-s";if(n.length<=1&&s==="-m")return de();if(n.length<=1&&s==="-r")return ge();if(n.length<=1&&s==="-s")return{aix:"AIX",android:"Android",cygwin:"CYGWIN",darwin:"Darwin",freebsd:"FreeBSD",haiku:"Haiku",linux:"Linux",netbsd:"NetBSD",openbsd:"OpenBSD",sunos:"SunOS",win32:"Windows_NT"}[Q()]??Q()}return}function _e(e){return e.replace(/\$\(([^)]+)\)/g,(t,n)=>{try{let r=ke(n),s=r[0];if(!s||!we.has(s))return console.warn(`[env] Blocked command substitution for disallowed command: ${s}`),"";let i=xe(r);if(i!==void 0)return i.trim();let c=ue(s,r.slice(1),{encoding:"utf8",env:process.env});if(c.status===0)return c.stdout.trim();let a=c.stderr.trim();console.warn(`[env] Command substitution failed (exit code ${c.status??"unknown"}): ${s}${a?`: ${a}`:""}`)}catch(r){console.warn(`[env] Command substitution error: ${r instanceof Error?r.message:String(r)}`)}return""})}async function We(e,t={}){let n={},r=[],s=[];for(let i of e)try{let c=Bun.file(i);if(!c.size)continue;let a=await c.text(),{parsed:u,errors:f,skippedEncrypted:o}=x(a,t);r.push(...f),s.push(...o);for(let[p,l]of Object.entries(u)){if(!t.overload&&n[p]!==void 0)continue;n[p]=l}}catch(c){if(c?.code==="ENOENT")continue;r.push(`Failed to read ${i}: ${c instanceof Error?c.message:String(c)}`)}return{parsed:n,errors:r,skippedEncrypted:s}}function _(e){return typeof e==="string"&&(e.startsWith("encrypted:")||e.startsWith("enc:"))}function m(e){if(!e||_(e))return;let t=e.trim().toLowerCase();if(!/^[a-z0-9_-]+$/.test(t))return;if(t==="prod")return"production";if(t==="stage")return"staging";if(t==="dev")return"development";return t}var D=null,B,A;function Pe(e,t,n=".env.keys"){let r=T(t,n);if(!O(r))return;try{let{parsed:s}=x(L(r,"utf-8"));if(e){let i=s[`DOTENV_PRIVATE_KEY_${e.toUpperCase()}`];if(i)return i}return s.DOTENV_PRIVATE_KEY}catch{return}}function be(e={}){return m(e.env)||A||m("development")||m(process.env.DOTENV_ENV)||m(process.env.APP_ENV)||"development"}function Ke(e={}){let t=be(e),n=e.cwd||process.cwd();if(D===t)return B;let r=W(t);if(!r)r=process.env.DOTENV_PRIVATE_KEY;if(!r)r=Pe(t,n);return D=t,B=r,r}function He(){D=null,B=void 0,A=void 0}function qe(e,t={}){if(!_(e))return e;let n=Ke(t);if(!n)return;try{let r=e.startsWith("enc:")?`encrypted:${e.slice(4)}`:e;return k(r,n)}catch{return}}function ee(e={}){let{path:t=[".env"],overload:n=!1,env:r,privateKey:s,keysFile:i=".env.keys",quiet:c=!1,cwd:a=process.cwd()}=e,u=Array.isArray(t)?t:[t],f=[],o=0,p=new Set(Object.entries(process.env).filter(([,d])=>d!==void 0&&!_(d)).map(([d])=>d)),l=s;if(!l&&i){let d=T(a,i);if(O(d))try{let g=L(d,"utf-8"),{parsed:v}=x(g);if(r){let P=`DOTENV_PRIVATE_KEY_${r.toUpperCase()}`;l=v[P]}else l=v.DOTENV_PRIVATE_KEY}catch(g){f.push(`Failed to load keys file: ${g instanceof Error?g.message:"Unknown error"}`)}}if(!l)l=W(r||"");for(let d of u){let g=T(a,d);if(!O(g)){if(!c)f.push(`File not found: ${g}`);continue}try{let v=L(g,"utf-8"),{parsed:P,errors:te,skippedEncrypted:E}=x(v,{privateKey:l,processEnv:process.env});if(f.push(...te),E.length>0){for(let V of E)if(_(process.env[V]))delete process.env[V];let w=r?`DOTENV_PRIVATE_KEY_${r.toUpperCase()}`:"DOTENV_PRIVATE_KEY",b=E.slice(0,5).join(", "),K=E.length>5?`, \u2026 +${E.length-5} more`:"";console.warn(`[env] warning: skipped ${E.length} encrypted value(s) in ${d} (${w} not set; defaults apply): ${b}${K}`)}let Y=0;for(let[w,b]of Object.entries(P)){if(w==="DOTENV_PUBLIC_KEY")continue;let K=process.env[w],V=_(K)&&b!==K;if(n||!p.has(w)||V)process.env[w]=b,o++,Y++}if(!c&&!process.env.__ENV_LOADED__)console.error(`[env] loaded ${Y}/${Object.keys(P).length} variables from ${d}`),process.env.__ENV_LOADED__="1"}catch(v){f.push(`Failed to load ${g}: ${v instanceof Error?v.message:"Unknown error"}`)}}return{loaded:o,errors:f}}function $e(e={}){return{name:"env-plugin",setup(t){ee(e)}}}function Me(e={}){let t=m(e.env)||m("development")||m(process.env.DOTENV_ENV)||m(process.env.APP_ENV)||"development",n=e.cwd||process.cwd();if(A!==t)A=t,D=null,B=void 0;let r=[],s=(a)=>{if(!r.includes(a)&&O(T(n,a)))r.push(a)};s(".env"),s(".env.local");let i=`.env.${t}`,c=`.env.${t}.local`;return s(i),s(c),ee({...e,path:r,env:t})}var Je=$e;export{be as activeEnvName,Me as autoLoadEnv,qe as decryptEnvValue,Je as default,$e as envPlugin,ee as loadEnv,He as resetPrivateKeyCache,Ke as resolvePrivateKey};
|
package/package.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"name": "@stacksjs/env",
|
|
3
3
|
"type": "module",
|
|
4
4
|
"sideEffects": false,
|
|
5
|
-
"version": "0.74.
|
|
5
|
+
"version": "0.74.22",
|
|
6
6
|
"description": "Stacks env helper methods.",
|
|
7
7
|
"author": "Chris Breuer",
|
|
8
8
|
"contributors": [
|
|
@@ -56,10 +56,10 @@
|
|
|
56
56
|
"prepublishOnly": "bun run build"
|
|
57
57
|
},
|
|
58
58
|
"dependencies": {
|
|
59
|
-
"@stacksjs/path": "0.74.
|
|
59
|
+
"@stacksjs/path": "0.74.22"
|
|
60
60
|
},
|
|
61
61
|
"devDependencies": {
|
|
62
62
|
"better-dx": "^0.2.24",
|
|
63
|
-
"@stacksjs/validation": "0.74.
|
|
63
|
+
"@stacksjs/validation": "0.74.22"
|
|
64
64
|
}
|
|
65
65
|
}
|