@stacksjs/env 0.72.57 → 0.72.61
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 +23 -23
- package/dist/crypto.js +1 -1
- package/dist/index.js +26 -26
- package/dist/parser.js +3 -3
- package/dist/plugin.js +3 -3
- package/dist/types.d.ts +94 -1
- package/dist/utils.js +1 -1
- package/package.json +3 -3
package/dist/cli.js
CHANGED
|
@@ -1,25 +1,25 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{createCipheriv as
|
|
3
|
-
`);for(let
|
|
4
|
-
`)}if(
|
|
5
|
-
`)){let
|
|
6
|
-
`)}function
|
|
7
|
-
`)){let
|
|
8
|
-
${
|
|
9
|
-
${
|
|
10
|
-
`;
|
|
11
|
-
${
|
|
12
|
-
${
|
|
13
|
-
`;
|
|
14
|
-
\u2714 key added to ${
|
|
15
|
-
`),
|
|
16
|
-
`);if(
|
|
17
|
-
`),
|
|
18
|
-
${
|
|
19
|
-
${
|
|
20
|
-
`,
|
|
21
|
-
`);return
|
|
22
|
-
`);break;case"json":default:
|
|
23
|
-
`),
|
|
2
|
+
import{createCipheriv as j,createDecipheriv as X,createHash as R,createPrivateKey as ce,createPublicKey as H,diffieHellman as J,generateKeyPairSync as M,hkdfSync as z,randomBytes as W}from"crypto";var S="x25519-public:",Y="x25519-private:",D="encrypted:v2:",A="encrypted:",G=Buffer.from("stacks-env:v2","utf8"),q="Environment decryption failed: authentication or format error";function Z(t){if(t.length===32)return t;return R("sha256").update(t).digest()}function Te(t,n){let e=W(16),s=j("aes-256-gcm",Z(n),e);return{ciphertext:Buffer.concat([s.update(t,"utf8"),s.final()]).toString("hex"),iv:e.toString("hex"),authTag:s.getAuthTag().toString("hex")}}function ae(t,n,e,s){try{let r=X("aes-256-gcm",Z(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 P(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 ue(t){if(!t.startsWith(S))throw Error("Legacy or invalid public key. Run buddy env:rotate before creating new ciphertext.");let n=H({key:P(t.slice(S.length),"public key"),format:"der",type:"spki"});if(n.asymmetricKeyType!=="x25519")throw Error("Public key is not X25519");return n}function fe(t){if(!t.startsWith(Y))throw Error("Private key is not a version 2 X25519 key");let n=ce({key:P(t.slice(Y.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 T(){let{publicKey:t,privateKey:n}=M("x25519"),e=t.export({format:"der",type:"spki"}),s=n.export({format:"der",type:"pkcs8"});return{publicKey:`${S}${_(e)}`,privateKey:`${Y}${_(s)}`}}function F(t,n){let e=ue(n),s=M("x25519"),r=_(s.publicKey.export({format:"der",type:"spki"})),i=W(16),u=W(12),f=J({privateKey:s.privateKey,publicKey:e}),c=Buffer.from(z("sha256",f,i,G,32)),a={epk:r,salt:_(i),nonce:_(u)};try{let o=j("aes-256-gcm",c,u);o.setAAD(Q(a));let l=Buffer.concat([o.update(t,"utf8"),o.final()]),p={v:2,...a,ciphertext:_(l),tag:_(o.getAuthTag())};return`${D}${_(Buffer.from(JSON.stringify(p),"utf8"))}`}finally{f.fill(0),c.fill(0)}}function le(t){let n=P(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,u)=>i!==r[u]))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 pe(t,n){try{let e=le(t),s=fe(n),r=H({key:P(e.epk,"ephemeral public key"),format:"der",type:"spki"});if(r.asymmetricKeyType!=="x25519")throw Error("ephemeral key is not X25519");let i=P(e.salt,"salt",16),u=P(e.nonce,"nonce",12),f=P(e.ciphertext,"ciphertext"),c=P(e.tag,"tag",16),a=J({privateKey:s,publicKey:r}),o=Buffer.from(z("sha256",a,i,G,32));try{let l=X("aes-256-gcm",o,u);return l.setAAD(Q(e)),l.setAuthTag(c),Buffer.concat([l.update(f),l.final()]).toString("utf8")}finally{a.fill(0),o.fill(0)}}catch{throw Error(q)}}function de(t,n){try{if(!/^[0-9a-f]{64}$/.test(n))throw Error("invalid legacy private key");let e=Buffer.from(t.slice(A.length),"base64");if(e.length<32)throw Error("invalid legacy payload");let s=R("sha256").update(Buffer.from(n,"hex")).digest(),r=R("sha256").update(s).digest();return ae(e.subarray(32).toString("hex"),r,e.subarray(0,16).toString("hex"),e.subarray(16,32).toString("hex"))}catch{throw Error(q)}}function Oe(t){return t.startsWith(A)&&!t.startsWith(D)}function O(t,n){if(!t.startsWith(A))return t;return t.startsWith(D)?pe(t,n):de(t,n)}function De(t,n,e){return F(O(t,n),e)}function Fe(t){let n=t.match(/^DOTENV_PRIVATE_KEY_(.+)$/);return n&&n[1]?n[1].toLowerCase():""}function Ce(t=""){return t?process.env[`DOTENV_PRIVATE_KEY_${t.toUpperCase()}`]:process.env.DOTENV_PRIVATE_KEY}import{spawnSync as ye}from"child_process";import{readFileSync as ge}from"fs";import{arch as he,hostname as me,platform as ee,release as ve,userInfo as Ee}from"os";import{basename as $e,dirname as ke,resolve as Ke}from"path";function x(t,n={}){let e={},s=[],r=[],i=t.split(`
|
|
3
|
+
`);for(let u of i){let f=u.trim();if(!f||f.startsWith("#"))continue;if(f.startsWith("DOTENV_PUBLIC_KEY=")){let l=f.match(/^DOTENV_PUBLIC_KEY=["']?([^"'\n]+)["']?/);if(l&&l[1]!==void 0)e.DOTENV_PUBLIC_KEY=l[1];continue}let c=f.match(/^([^=]+)=(.*)$/);if(!c||c[1]===void 0||c[2]===void 0)continue;let a=c[1].trim(),o=c[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(a);continue}try{let l=o.startsWith("enc:")?`encrypted:${o.slice(4)}`:o;o=O(l,n.privateKey)}catch(l){s.push(`Failed to decrypt ${a}: ${l instanceof Error?l.message:"Unknown error"}`)}}o=we(o,{...n.processEnv||process.env,...e}),o=Pe(o),e[a]=o}return{parsed:e,errors:s,skippedEncrypted:r}}function we(t,n){return t.replace(/\$\{([^}]+)\}/g,(e,s)=>{let r=s.match(/^([^:\-+]+)(:-|-)(.+)$/);if(r){let[,u,f,c]=r,a=n[u];if(f===":-")return a||c;else return a!==void 0?a:c}let i=s.match(/^([^:\-+]+)(:?\+)(.+)$/);if(i){let[,u,f,c]=i,a=n[u];if(f===":+")return a?c:"";else return a!==void 0?c:""}return n[s]||""})}var be=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 Ne(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 me();if(n==="whoami"&&e.length===0)return Ee().username;if(n==="pwd"&&e.length===0)return process.cwd();if(n==="basename"&&e.length===1)return $e(e[0]??"");if(n==="dirname"&&e.length===1)return ke(e[0]??"");if(n==="cat"&&e.length>0&&!s)return e.map((r)=>ge(Ke(process.cwd(),r),"utf8")).join("");if(n==="uname"){let r=e[0]??"-s";if(e.length<=1&&r==="-m")return he();if(e.length<=1&&r==="-r")return ve();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"}[ee()]??ee()}return}function Pe(t){return t.replace(/\$\(([^)]+)\)/g,(n,e)=>{try{let s=_e(e),r=s[0];if(!r||!be.has(r))return console.warn(`[env] Blocked command substitution for disallowed command: ${r}`),"";let i=Ne(s);if(i!==void 0)return i.trim();let u=ye(r,s.slice(1),{encoding:"utf8",env:process.env});if(u.status===0)return u.stdout.trim();let f=u.stderr.trim();console.warn(`[env] Command substitution failed (exit code ${u.status??"unknown"}): ${r}${f?`: ${f}`:""}`)}catch(s){console.warn(`[env] Command substitution error: ${s instanceof Error?s.message:String(s)}`)}return""})}async function Ae(t,n={}){let e={},s=[],r=[];for(let i of t)try{let u=Bun.file(i);if(!u.size)continue;let f=await u.text(),{parsed:c,errors:a,skippedEncrypted:o}=x(f,n);s.push(...a),r.push(...o);for(let[l,p]of Object.entries(c)){if(!n.overload&&e[l]!==void 0)continue;e[l]=p}}catch(u){if(u?.code==="ENOENT")continue;s.push(`Failed to read ${i}: ${u instanceof Error?u.message:String(u)}`)}return{parsed:e,errors:s,skippedEncrypted:r}}import{existsSync as w,readFileSync as K,renameSync as U,rmSync as te,writeFileSync as b}from"fs";import{basename as L,dirname as ne,resolve as k}from"path";function Je(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,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 u of t.split(`
|
|
5
|
+
`)){let f=u.trim();if(f.startsWith("#/"))continue;if(f.startsWith("DOTENV_PUBLIC_KEY"))continue;if(!f&&!i)continue;if(!f||f.startsWith("#")){i=!0,r.push(u);continue}i=!0;let c=f.match(/^([^=]+)=(.*)$/);if(!c||c[1]===void 0||c[2]===void 0){r.push(u);continue}let a=c[1].trim(),o=c[2].trim();if(o.startsWith('"')&&o.endsWith('"')||o.startsWith("'")&&o.endsWith("'"))o=o.slice(1,-1);if((!s.key||a.includes(s.key))&&(!s.excludeKey||!a.includes(s.excludeKey))&&!o.startsWith("encrypted:"))o=F(o,n);r.push(`${a}="${o}"`)}return r.join(`
|
|
6
|
+
`)}function C(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 se(t,n){let e,s=!1;for(let r of t.split(`
|
|
7
|
+
`)){let i=r.trim();if(!i||i.startsWith("#"))continue;let u=i.match(/^([^=]+)=(.*)$/);if(!u?.[1]||u[2]===void 0)continue;let f=u[1].trim(),c=u[2].trim().replace(/^["']|["']$/g,"");if(f===n)e=c;else if(c.startsWith("encrypted:")||c.startsWith("enc:"))s=!0}return e&&s?e:void 0}function Me(t={}){let n=t.cwd||process.cwd(),e=k(n,t.file||".env"),s=k(n,t.keysFile||".env.keys");if(!w(e))return{success:!1,error:`File not found: ${e}`};try{let r,i,u=se(K(e,"utf-8"),C(t.file).publicKeyName);if(u)r=u;else if(w(s)){let a=K(s,"utf-8"),{parsed:o}=x(a),{publicKeyName:l,privateKeyName:p}=C(t.file);if(r=o[l]||"",i=o[p]||"",!r||!i){let g=T();r=g.publicKey,i=g.privateKey;let y=`
|
|
8
|
+
${l}="${r}"
|
|
9
|
+
${p}="${i}"
|
|
10
|
+
`;b(s,a+y,"utf-8")}}else{let a=T();r=a.publicKey,i=a.privateKey;let{publicKeyName:o,privateKeyName:l}=C(t.file),p=`# .env.keys - Keep this file secure and never commit to source control
|
|
11
|
+
${o}="${r}"
|
|
12
|
+
${l}="${i}"
|
|
13
|
+
`;b(s,p,"utf-8")}let f=K(e,"utf-8"),c=re(f,r,C(t.file).publicKeyName,t);if(t.stdout)return{success:!0,output:c};return b(e,c,"utf-8"),{success:!0,output:`\u2714 encrypted (${t.file||".env"})
|
|
14
|
+
\u2714 key added to ${t.keysFile||".env.keys"}`}}catch(r){return{success:!1,error:`Failed to encrypt: ${r instanceof Error?r.message:"Unknown error"}`}}}function xe(t={}){let n=t.cwd||process.cwd(),e=k(n,t.file||".env"),s=k(n,t.keysFile||".env.keys");if(!w(e))return{success:!1,error:`File not found: ${e}`};if(!w(s))return{success:!1,error:`Keys file not found: ${s}`};try{let r=K(s,"utf-8"),{parsed:i}=x(r),c=((t.file||".env").split("/").pop()||"").replace(/^\.env\./,"").replace(/^\.env$/,"").toUpperCase(),a=c?`DOTENV_PRIVATE_KEY_${c}`:"DOTENV_PRIVATE_KEY",o=i[a];if(!o)return{success:!1,error:`Private key not found: ${a}`};let l=[o];if(a!=="DOTENV_PRIVATE_KEY"&&i.DOTENV_PRIVATE_KEY&&i.DOTENV_PRIVATE_KEY!==o)l.push(i.DOTENV_PRIVATE_KEY);let g=K(e,"utf-8").split(`
|
|
15
|
+
`),y=[];for(let N of g){let h=N.trim();if(!h||h.startsWith("#")){y.push(N);continue}if(h.startsWith("DOTENV_PUBLIC_KEY"))continue;let m=h.match(/^([^=]+)=(.*)$/);if(!m||m[1]===void 0||m[2]===void 0){y.push(N);continue}let v=m[1].trim(),d=m[2].trim();if(d.startsWith('"')&&d.endsWith('"')||d.startsWith("'")&&d.endsWith("'"))d=d.slice(1,-1);let V=d.startsWith("encrypted:");if(t.key&&!v.includes(t.key))V=!1;if(V){let B,I;for(let ie of l)try{B=O(d,ie);break}catch(oe){I=oe}if(B===void 0)throw I instanceof Error?I:Error(`Unable to decrypt ${v}`);d=B}y.push(`${v}="${d}"`)}let E=y.join(`
|
|
16
|
+
`);if(t.stdout)return{success:!0,output:E};return b(e,E,"utf-8"),{success:!0,output:`\u2714 decrypted (${t.file||".env"})`}}catch(r){return{success:!1,error:`Failed to decrypt: ${r instanceof Error?r.message:"Unknown error"}`}}}function ze(t,n,e={}){let s=e.cwd||process.cwd(),r=k(s,e.file||".env"),i=k(s,e.keysFile||".env.keys");try{let u="";if(w(r))u=K(r,"utf-8");let f=u.split(`
|
|
17
|
+
`),c=!1,a,p=((e.file||".env").split("/").pop()||"").replace(/^\.env\./,"").replace(/^\.env$/,"").toUpperCase(),g=p?`DOTENV_PUBLIC_KEY_${p}`:"DOTENV_PUBLIC_KEY",y=p?`DOTENV_PRIVATE_KEY_${p}`:"DOTENV_PRIVATE_KEY";for(let h of f){let m=h.trim();if(m.startsWith(`${g}=`)){let v=m.match(/^[^=]+=["']?([^"'\n]+)["']?/);if(v)a=v[1];break}}if(a){let h=!1;if(w(i)){let m=K(i,"utf-8"),{parsed:v}=x(m);h=Boolean(v[y])}if(!h&&!process.env[y]&&!se(u,g))a=void 0}if(!e.plain&&!a){let h=T();a=h.publicKey;let m="";if(w(i))m=K(i,"utf-8");m+=`
|
|
18
|
+
${g}="${h.publicKey}"
|
|
19
|
+
${y}="${h.privateKey}"
|
|
20
|
+
`,b(i,m,"utf-8");for(let v=f.length-1;v>=0;v--){let d=f[v];if(d!==void 0&&d.trim().startsWith(`${g}=`))f.splice(v,1)}f.unshift(`${g}="${a}"`)}let E=n;if(!e.plain&&a)E=F(n,a);for(let h=0;h<f.length;h++){let m=f[h];if(m===void 0)continue;if(m.trim().startsWith(`${t}=`)){f[h]=`${t}="${E}"`,c=!0;break}}if(!c)f.push(`${t}="${E}"`);let N=f.join(`
|
|
21
|
+
`);return b(r,N,"utf-8"),{success:!0,output:`set ${t}${e.plain?"":" with encryption"} (${e.file||".env"})`}}catch(u){return{success:!1,error:`Failed to set: ${u instanceof Error?u.message:"Unknown error"}`}}}function Ge(t,n={}){let e=n.cwd||process.cwd(),s=k(e,n.file||".env");if(!w(s))return{success:!1,error:`File not found: ${s}`};try{let r,i=k(e,n.keysFile||".env.keys"),c=((n.file||".env").split("/").pop()||"").replace(/^\.env\./,"").replace(/^\.env$/,"").toUpperCase(),a=c?`DOTENV_PRIVATE_KEY_${c}`:"DOTENV_PRIVATE_KEY";if(w(i)){let y=K(i,"utf-8"),{parsed:E}=x(y);r=E[a]}if(!r)r=process.env[a];let o=K(s,"utf-8"),{parsed:l}=x(o,{privateKey:r});if(t&&!n.all){let y=l[t];if(y===void 0)return{success:!1,error:`Key not found: ${t}`};return{success:!0,output:y}}let p=n.all?{...process.env,...l}:l,g;switch(n.format){case"shell":g=Object.entries(p).map(([y,E])=>`${y}=${E}`).join(" ");break;case"eval":g=Object.entries(p).map(([y,E])=>`${y}="${E}"`).join(`
|
|
22
|
+
`);break;case"json":default:g=n.prettyPrint?JSON.stringify(p,null,2):JSON.stringify(p);break}return{success:!0,output:g}}catch(r){return{success:!1,error:`Failed to get: ${r instanceof Error?r.message:"Unknown error"}`}}}function qe(t,n={}){let e=n.cwd||process.cwd(),s=k(e,n.keysFile||".env.keys");if(!w(s))return{success:!1,error:`Keys file not found: ${s}`};try{let r=K(s,"utf-8"),{parsed:i}=x(r),c=((n.file||".env").split("/").pop()||"").replace(/^\.env\./,"").replace(/^\.env$/,"").toUpperCase(),a=c?`DOTENV_PUBLIC_KEY_${c}`:"DOTENV_PUBLIC_KEY",o=c?`DOTENV_PRIVATE_KEY_${c}`:"DOTENV_PRIVATE_KEY";if(t){let g=i[t];if(!g)return{success:!1,error:`Key not found: ${t}`};return{success:!0,output:g}}let l={[a]:i[a],[o]:i[o]};return{success:!0,output:n.format==="shell"?`${a}=${l[a]} ${o}=${l[o]}`:JSON.stringify(l)}}catch(r){return{success:!1,error:`Failed to get keypair: ${r instanceof Error?r.message:"Unknown error"}`}}}function Ze(t={}){let n=xe({file:t.file,keysFile:t.keysFile,stdout:!0,cwd:t.cwd});if(!n.success)return n;let e=t.cwd||process.cwd(),s=k(e,t.file||".env"),r=k(e,t.keysFile||".env.keys");if(n.output===void 0)return{success:!1,error:"Rotation produced no decrypted content"};let i=T(),u=K(s),f=K(r),c=f.toString("utf8").split(`
|
|
23
|
+
`),a=t.file||".env",o=L(a).replace(/^\.env\./,"").replace(/^\.env$/,"").toUpperCase(),l=o?`DOTENV_PUBLIC_KEY_${o}`:"DOTENV_PUBLIC_KEY",p=o?`DOTENV_PRIVATE_KEY_${o}`:"DOTENV_PRIVATE_KEY",g=!1,y=!1;for(let d=0;d<c.length;d++){let V=c[d];if(V===void 0)continue;if(V.startsWith(`${l}=`))c[d]=`${l}="${i.publicKey}"`,g=!0;else if(V.startsWith(`${p}=`))c[d]=`${p}="${i.privateKey}"`,y=!0}if(!g)c.push(`${l}="${i.publicKey}"`);if(!y)c.push(`${p}="${i.privateKey}"`);let E=`${c.join(`
|
|
24
24
|
`).replace(/\n+$/,"")}
|
|
25
|
-
`,
|
|
25
|
+
`,N=re(n.output,i.publicKey,l,t),h=`${process.pid}-${Date.now()}`,m=k(ne(s),`.${L(s)}.${h}.rotate`),v=k(ne(r),`.${L(r)}.${h}.rotate`);try{if(b(m,N,{encoding:"utf8",mode:384}),b(v,E,{encoding:"utf8",mode:384}),t.stdout)return U(v,r),{success:!0,output:N};U(m,s);try{U(v,r)}catch(d){throw b(s,u),d}return{success:!0,output:`\u2714 rotated (${t.file||".env"}) to encrypted:v2`}}catch(d){if(!w(r))b(r,f,{mode:384});return{success:!1,error:`Failed to rotate without exposing plaintext: ${d instanceof Error?d.message:"Unknown error"}`}}finally{te(m,{force:!0}),te(v,{force:!0})}}export{xe as decryptEnv,Me as encryptEnv,C as envKeyNames,Ge as getEnv,qe as getKeypair,Je as resolveEnvFile,se as reusableEnvPublicKey,Ze as rotateKeypair,ze as setEnv};
|
package/dist/crypto.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{createCipheriv as x,createDecipheriv as w,createHash as l,createPrivateKey as S,createPublicKey as k,diffieHellman as
|
|
2
|
+
import{createCipheriv as x,createDecipheriv as w,createHash as l,createPrivateKey as S,createPublicKey as k,diffieHellman as K,generateKeyPairSync as b,hkdfSync as B,randomBytes as d}from"crypto";var E="x25519-public:",m="x25519-private:",h="encrypted:v2:",v="encrypted:",P=Buffer.from("stacks-env:v2","utf8"),T="Environment decryption failed: authentication or format error";function _(t){if(t.length===32)return t;return l("sha256").update(t).digest()}function L(t,e){let r=d(16),n=x("aes-256-gcm",_(e),r);return{ciphertext:Buffer.concat([n.update(t,"utf8"),n.final()]).toString("hex"),iv:r.toString("hex"),authTag:n.getAuthTag().toString("hex")}}function V(t,e,r,n){try{let i=w("aes-256-gcm",_(e),Buffer.from(r,"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 s(t){return t.toString("base64url")}function c(t,e,r){if(typeof t!=="string"||t.length>0&&!/^[A-Za-z0-9_-]+$/.test(t))throw Error(`${e} is not canonical base64url`);let n=Buffer.from(t,"base64url");if(s(n)!==t)throw Error(`${e} is not canonical base64url`);if(r!==void 0&&n.length!==r)throw Error(`${e} has an invalid length`);return n}function D(t){if(!t.startsWith(E))throw Error("Legacy or invalid public key. Run buddy env:rotate before creating new ciphertext.");let e=k({key:c(t.slice(E.length),"public key"),format:"der",type:"spki"});if(e.asymmetricKeyType!=="x25519")throw Error("Public key is not X25519");return e}function I(t){if(!t.startsWith(m))throw Error("Private key is not a version 2 X25519 key");let e=S({key:c(t.slice(m.length),"private key"),format:"der",type:"pkcs8"});if(e.asymmetricKeyType!=="x25519")throw Error("Private key is not X25519");return e}function A(t){return Buffer.from(`stacks-env:v2;${t.epk};${t.salt};${t.nonce}`,"utf8")}function W(){let{publicKey:t,privateKey:e}=b("x25519"),r=t.export({format:"der",type:"spki"}),n=e.export({format:"der",type:"pkcs8"});return{publicKey:`${E}${s(r)}`,privateKey:`${m}${s(n)}`}}function O(t,e){let r=D(e),n=b("x25519"),i=s(n.publicKey.export({format:"der",type:"spki"})),o=d(16),f=d(12),g=K({privateKey:n.privateKey,publicKey:r}),y=Buffer.from(B("sha256",g,o,P,32)),u={epk:i,salt:s(o),nonce:s(f)};try{let a=x("aes-256-gcm",y,f);a.setAAD(A(u));let p=Buffer.concat([a.update(t,"utf8"),a.final()]),R={v:2,...u,ciphertext:s(p),tag:s(a.getAuthTag())};return`${h}${s(Buffer.from(JSON.stringify(R),"utf8"))}`}finally{g.fill(0),y.fill(0)}}function N(t){let e=c(t.slice(h.length),"envelope").toString("utf8"),r=JSON.parse(e);if(!r||typeof r!=="object"||Array.isArray(r))throw Error("envelope is not an object");let n=Object.keys(r).sort(),i=["ciphertext","epk","nonce","salt","tag","v"];if(n.length!==i.length||n.some((o,f)=>o!==i[f]))throw Error("envelope fields are invalid");if(r.v!==2)throw Error("envelope version is unsupported");for(let o of["epk","salt","nonce","ciphertext","tag"])if(typeof r[o]!=="string")throw Error(`${o} is invalid`);return r}function X(t,e){try{let r=N(t),n=I(e),i=k({key:c(r.epk,"ephemeral public key"),format:"der",type:"spki"});if(i.asymmetricKeyType!=="x25519")throw Error("ephemeral key is not X25519");let o=c(r.salt,"salt",16),f=c(r.nonce,"nonce",12),g=c(r.ciphertext,"ciphertext"),y=c(r.tag,"tag",16),u=K({privateKey:n,publicKey:i}),a=Buffer.from(B("sha256",u,o,P,32));try{let p=w("aes-256-gcm",a,f);return p.setAAD(A(r)),p.setAuthTag(y),Buffer.concat([p.update(g),p.final()]).toString("utf8")}finally{u.fill(0),a.fill(0)}}catch{throw Error(T)}}function F(t,e){try{if(!/^[0-9a-f]{64}$/.test(e))throw Error("invalid legacy private key");let r=Buffer.from(t.slice(v.length),"base64");if(r.length<32)throw Error("invalid legacy payload");let n=l("sha256").update(Buffer.from(e,"hex")).digest(),i=l("sha256").update(n).digest();return V(r.subarray(32).toString("hex"),i,r.subarray(0,16).toString("hex"),r.subarray(16,32).toString("hex"))}catch{throw Error(T)}}function H(t){return t.startsWith(v)&&!t.startsWith(h)}function Y(t,e){if(!t.startsWith(v))return t;return t.startsWith(h)?X(t,e):F(t,e)}function j(t,e,r){return O(Y(t,e),r)}function z(t){let e=t.match(/^DOTENV_PRIVATE_KEY_(.+)$/);return e&&e[1]?e[1].toLowerCase():""}function J(t=""){return t?process.env[`DOTENV_PRIVATE_KEY_${t.toUpperCase()}`]:process.env.DOTENV_PRIVATE_KEY}export{V as aesDecrypt,L as aesEncrypt,Y as decryptValue,O as encryptValue,W as generateKeypair,J as getPrivateKey,H as isLegacyEncryptedValue,j as migrateEncryptedValue,z as parseEnvFromKey};
|
package/dist/index.js
CHANGED
|
@@ -1,28 +1,28 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{createCipheriv as
|
|
3
|
-
`);for(let
|
|
4
|
-
`)}if(
|
|
5
|
-
`)){let
|
|
6
|
-
`)}function
|
|
7
|
-
`)){let
|
|
8
|
-
${
|
|
9
|
-
${
|
|
10
|
-
`;
|
|
11
|
-
${
|
|
12
|
-
${
|
|
13
|
-
`;
|
|
14
|
-
\u2714 key added to ${
|
|
15
|
-
`),
|
|
16
|
-
`);if(
|
|
17
|
-
`),
|
|
18
|
-
${
|
|
19
|
-
${
|
|
20
|
-
`,
|
|
21
|
-
`);return
|
|
22
|
-
`);break;case"json":default:
|
|
23
|
-
`),
|
|
2
|
+
import{createCipheriv as re,createDecipheriv as ie,createHash as G,createPrivateKey as Ce,createPublicKey as se,diffieHellman as oe,generateKeyPairSync as de,hkdfSync as ce,randomBytes as H}from"crypto";var X="x25519-public:",j="x25519-private:",w="encrypted:v2:",Q="encrypted:",ae=Buffer.from("stacks-env:v2","utf8"),ue="Environment decryption failed: authentication or format error";function fe(e){if(e.length===32)return e;return G("sha256").update(e).digest()}function Rn(e,n){let t=H(16),r=re("aes-256-gcm",fe(n),t);return{ciphertext:Buffer.concat([r.update(e,"utf8"),r.final()]).toString("hex"),iv:t.toString("hex"),authTag:r.getAuthTag().toString("hex")}}function be(e,n,t,r){try{let i=ie("aes-256-gcm",fe(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 P(e){return e.toString("base64url")}function b(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(P(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 Le(e){if(!e.startsWith(X))throw Error("Legacy or invalid public key. Run buddy env:rotate before creating new ciphertext.");let n=se({key:b(e.slice(X.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(j))throw Error("Private key is not a version 2 X25519 key");let n=Ce({key:b(e.slice(j.length),"private key"),format:"der",type:"pkcs8"});if(n.asymmetricKeyType!=="x25519")throw Error("Private key is not X25519");return n}function Ee(e){return Buffer.from(`stacks-env:v2;${e.epk};${e.salt};${e.nonce}`,"utf8")}function k(){let{publicKey:e,privateKey:n}=de("x25519"),t=e.export({format:"der",type:"spki"}),r=n.export({format:"der",type:"pkcs8"});return{publicKey:`${X}${P(t)}`,privateKey:`${j}${P(r)}`}}function B(e,n){let t=Le(n),r=de("x25519"),i=P(r.publicKey.export({format:"der",type:"spki"})),s=H(16),o=H(12),a=oe({privateKey:r.privateKey,publicKey:t}),c=Buffer.from(ce("sha256",a,s,ae,32)),u={epk:i,salt:P(s),nonce:P(o)};try{let d=re("aes-256-gcm",c,o);d.setAAD(Ee(u));let f=Buffer.concat([d.update(e,"utf8"),d.final()]),p={v:2,...u,ciphertext:P(f),tag:P(d.getAuthTag())};return`${w}${P(Buffer.from(JSON.stringify(p),"utf8"))}`}finally{a.fill(0),c.fill(0)}}function ke(e){let n=b(e.slice(w.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=ke(e),r=Ke(n),i=se({key:b(t.epk,"ephemeral public key"),format:"der",type:"spki"});if(i.asymmetricKeyType!=="x25519")throw Error("ephemeral key is not X25519");let s=b(t.salt,"salt",16),o=b(t.nonce,"nonce",12),a=b(t.ciphertext,"ciphertext"),c=b(t.tag,"tag",16),u=oe({privateKey:r,publicKey:i}),d=Buffer.from(ce("sha256",u,s,ae,32));try{let f=ie("aes-256-gcm",d,o);return f.setAAD(Ee(t)),f.setAuthTag(c),Buffer.concat([f.update(a),f.final()]).toString("utf8")}finally{u.fill(0),d.fill(0)}}catch{throw Error(ue)}}function Ue(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 be(t.subarray(32).toString("hex"),i,t.subarray(0,16).toString("hex"),t.subarray(16,32).toString("hex"))}catch{throw Error(ue)}}function yn(e){return e.startsWith(Q)&&!e.startsWith(w)}function K(e,n){if(!e.startsWith(Q))return e;return e.startsWith(w)?$e(e,n):Ue(e,n)}function Tn(e,n,t){return B(K(e,n),t)}function vn(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 we}from"child_process";import{readFileSync as Be}from"fs";import{arch as xe,hostname as Ve,platform as le,release as Me,userInfo as Fe}from"os";import{basename as Ye,dirname as We,resolve as Ge}from"path";function O(e,n={}){let t={},r=[],i=[],s=e.split(`
|
|
3
|
+
`);for(let o of s){let a=o.trim();if(!a||a.startsWith("#"))continue;if(a.startsWith("DOTENV_PUBLIC_KEY=")){let f=a.match(/^DOTENV_PUBLIC_KEY=["']?([^"'\n]+)["']?/);if(f&&f[1]!==void 0)t.DOTENV_PUBLIC_KEY=f[1];continue}let c=a.match(/^([^=]+)=(.*)$/);if(!c||c[1]===void 0||c[2]===void 0)continue;let u=c[1].trim(),d=c[2].trim();if(d.startsWith('"')&&d.endsWith('"')||d.startsWith("'")&&d.endsWith("'")){if(d=d.slice(1,-1),d.includes("\\n"))d=d.replace(/\\n/g,`
|
|
4
|
+
`)}if(d.startsWith("encrypted:")||d.startsWith("enc:")){if(!n.privateKey){i.push(u);continue}try{let f=d.startsWith("enc:")?`encrypted:${d.slice(4)}`:d;d=K(f,n.privateKey)}catch(f){r.push(`Failed to decrypt ${u}: ${f instanceof Error?f.message:"Unknown error"}`)}}d=He(d,{...n.processEnv||process.env,...t}),d=qe(d),t[u]=d}return{parsed:t,errors:r,skippedEncrypted:i}}function He(e,n){return e.replace(/\$\{([^}]+)\}/g,(t,r)=>{let i=r.match(/^([^:\-+]+)(:-|-)(.+)$/);if(i){let[,o,a,c]=i,u=n[o];if(a===":-")return u||c;else return u!==void 0?u:c}let s=r.match(/^([^:\-+]+)(:?\+)(.+)$/);if(s){let[,o,a,c]=s,u=n[o];if(a===":+")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 je(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 Ve();if(n==="whoami"&&t.length===0)return Fe().username;if(n==="pwd"&&t.length===0)return process.cwd();if(n==="basename"&&t.length===1)return Ye(t[0]??"");if(n==="dirname"&&t.length===1)return We(t[0]??"");if(n==="cat"&&t.length>0&&!r)return t.map((i)=>Be(Ge(process.cwd(),i),"utf8")).join("");if(n==="uname"){let i=t[0]??"-s";if(t.length<=1&&i==="-m")return xe();if(t.length<=1&&i==="-r")return Me();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"}[le()]??le()}return}function qe(e){return e.replace(/\$\(([^)]+)\)/g,(n,t)=>{try{let r=je(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=we(i,r.slice(1),{encoding:"utf8",env:process.env});if(o.status===0)return o.stdout.trim();let a=o.stderr.trim();console.warn(`[env] Command substitution failed (exit code ${o.status??"unknown"}): ${i}${a?`: ${a}`:""}`)}catch(r){console.warn(`[env] Command substitution error: ${r instanceof Error?r.message:String(r)}`)}return""})}async function Pn(e,n={}){let t={},r=[],i=[];for(let s of e)try{let o=Bun.file(s);if(!o.size)continue;let a=await o.text(),{parsed:c,errors:u,skippedEncrypted:d}=O(a,n);r.push(...u),i.push(...d);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}}import{existsSync as x}from"fs";import{readFileSync as z}from"fs";import{resolve as V}from"path";function U(e){return typeof e==="string"&&(e.startsWith("encrypted:")||e.startsWith("enc:"))}function L(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 M=null,F,Y;function ze(e,n,t=".env.keys"){let r=V(n,t);if(!x(r))return;try{let{parsed:i}=O(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 L(e.env)||Y||L("development")||L(process.env.DOTENV_ENV)||L(process.env.APP_ENV)||"development"}function Je(e={}){let n=J(e),t=e.cwd||process.cwd();if(M===n)return F;let r=q(n);if(!r)r=process.env.DOTENV_PRIVATE_KEY;if(!r)r=ze(n,t);return M=n,F=r,r}function $n(){M=null,F=void 0,Y=void 0}function pe(e,n={}){if(!U(e))return e;let t=Je(n);if(!t)return;try{let r=e.startsWith("enc:")?`encrypted:${e.slice(4)}`:e;return K(r,t)}catch{return}}function ge(e={}){let{path:n=[".env"],overload:t=!1,env:r,privateKey:i,keysFile:s=".env.keys",quiet:o=!1,cwd:a=process.cwd()}=e,c=Array.isArray(n)?n:[n],u=[],d=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=V(a,s);if(x(E))try{let l=z(E,"utf-8"),{parsed:y}=O(l);if(r){let v=`DOTENV_PRIVATE_KEY_${r.toUpperCase()}`;p=y[v]}else p=y.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=V(a,E);if(!x(l)){if(!o)u.push(`File not found: ${l}`);continue}try{let y=z(l,"utf-8"),{parsed:v,errors:R,skippedEncrypted:m}=O(y,{privateKey:p,processEnv:process.env});if(u.push(...R),m.length>0){for(let C of m)if(U(process.env[C]))delete process.env[C];let g=r?`DOTENV_PRIVATE_KEY_${r.toUpperCase()}`:"DOTENV_PRIVATE_KEY",N=m.slice(0,5).join(", "),D=m.length>5?`, \u2026 +${m.length-5} more`:"";console.warn(`[env] warning: skipped ${m.length} encrypted value(s) in ${E} (${g} not set; defaults apply): ${N}${D}`)}let T=0;for(let[g,N]of Object.entries(v)){if(g==="DOTENV_PUBLIC_KEY")continue;let D=process.env[g],C=U(D)&&N!==D;if(t||!f.has(g)||C)process.env[g]=N,d++,T++}if(!o&&!process.env.__ENV_LOADED__)console.error(`[env] loaded ${T}/${Object.keys(v).length} variables from ${E}`),process.env.__ENV_LOADED__="1"}catch(y){u.push(`Failed to load ${l}: ${y instanceof Error?y.message:"Unknown error"}`)}}return{loaded:d,errors:u}}function Ze(e={}){return{name:"env-plugin",setup(n){ge(e)}}}function Un(e={}){let n=L(e.env)||L("development")||L(process.env.DOTENV_ENV)||L(process.env.APP_ENV)||"development",t=e.cwd||process.cwd();if(Y!==n)Y=n,M=null,F=void 0;let r=[],i=(a)=>{if(!r.includes(a)&&x(V(t,a)))r.push(a)};i(".env"),i(".env.local");let s=`.env.${n}`,o=`.env.${n}.local`;return i(s),i(o),ge({...e,path:r,env:n})}var Bn=Ze;import{existsSync as S,readFileSync as I,renameSync as Z,rmSync as _e,writeFileSync as h}from"fs";import{basename as ee,dirname as me,resolve as A}from"path";function Yn(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,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(`
|
|
5
|
+
`)){let a=o.trim();if(a.startsWith("#/"))continue;if(a.startsWith("DOTENV_PUBLIC_KEY"))continue;if(!a&&!s)continue;if(!a||a.startsWith("#")){s=!0,i.push(o);continue}s=!0;let c=a.match(/^([^=]+)=(.*)$/);if(!c||c[1]===void 0||c[2]===void 0){i.push(o);continue}let u=c[1].trim(),d=c[2].trim();if(d.startsWith('"')&&d.endsWith('"')||d.startsWith("'")&&d.endsWith("'"))d=d.slice(1,-1);if((!r.key||u.includes(r.key))&&(!r.excludeKey||!u.includes(r.excludeKey))&&!d.startsWith("encrypted:"))d=B(d,n);i.push(`${u}="${d}"`)}return i.join(`
|
|
6
|
+
`)}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 ye(e,n){let t,r=!1;for(let i of e.split(`
|
|
7
|
+
`)){let s=i.trim();if(!s||s.startsWith("#"))continue;let o=s.match(/^([^=]+)=(.*)$/);if(!o?.[1]||o[2]===void 0)continue;let a=o[1].trim(),c=o[2].trim().replace(/^["']|["']$/g,"");if(a===n)t=c;else if(c.startsWith("encrypted:")||c.startsWith("enc:"))r=!0}return t&&r?t:void 0}function Wn(e={}){let n=e.cwd||process.cwd(),t=A(n,e.file||".env"),r=A(n,e.keysFile||".env.keys");if(!S(t))return{success:!1,error:`File not found: ${t}`};try{let i,s,o=ye(I(t,"utf-8"),W(e.file).publicKeyName);if(o)i=o;else if(S(r)){let u=I(r,"utf-8"),{parsed:d}=O(u),{publicKeyName:f,privateKeyName:p}=W(e.file);if(i=d[f]||"",s=d[p]||"",!i||!s){let E=k();i=E.publicKey,s=E.privateKey;let l=`
|
|
8
|
+
${f}="${i}"
|
|
9
|
+
${p}="${s}"
|
|
10
|
+
`;h(r,u+l,"utf-8")}}else{let u=k();i=u.publicKey,s=u.privateKey;let{publicKeyName:d,privateKeyName:f}=W(e.file),p=`# .env.keys - Keep this file secure and never commit to source control
|
|
11
|
+
${d}="${i}"
|
|
12
|
+
${f}="${s}"
|
|
13
|
+
`;h(r,p,"utf-8")}let a=I(t,"utf-8"),c=Re(a,i,W(e.file).publicKeyName,e);if(e.stdout)return{success:!0,output:c};return h(t,c,"utf-8"),{success:!0,output:`\u2714 encrypted (${e.file||".env"})
|
|
14
|
+
\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 en(e={}){let n=e.cwd||process.cwd(),t=A(n,e.file||".env"),r=A(n,e.keysFile||".env.keys");if(!S(t))return{success:!1,error:`File not found: ${t}`};if(!S(r))return{success:!1,error:`Keys file not found: ${r}`};try{let i=I(r,"utf-8"),{parsed:s}=O(i),c=((e.file||".env").split("/").pop()||"").replace(/^\.env\./,"").replace(/^\.env$/,"").toUpperCase(),u=c?`DOTENV_PRIVATE_KEY_${c}`:"DOTENV_PRIVATE_KEY",d=s[u];if(!d)return{success:!1,error:`Private key not found: ${u}`};let f=[d];if(u!=="DOTENV_PRIVATE_KEY"&&s.DOTENV_PRIVATE_KEY&&s.DOTENV_PRIVATE_KEY!==d)f.push(s.DOTENV_PRIVATE_KEY);let E=I(t,"utf-8").split(`
|
|
15
|
+
`),l=[];for(let v of E){let R=v.trim();if(!R||R.startsWith("#")){l.push(v);continue}if(R.startsWith("DOTENV_PUBLIC_KEY"))continue;let m=R.match(/^([^=]+)=(.*)$/);if(!m||m[1]===void 0||m[2]===void 0){l.push(v);continue}let T=m[1].trim(),g=m[2].trim();if(g.startsWith('"')&&g.endsWith('"')||g.startsWith("'")&&g.endsWith("'"))g=g.slice(1,-1);let N=g.startsWith("encrypted:");if(e.key&&!T.includes(e.key))N=!1;if(N){let D,C;for(let Pe of f)try{D=K(g,Pe);break}catch(De){C=De}if(D===void 0)throw C instanceof Error?C:Error(`Unable to decrypt ${T}`);g=D}l.push(`${T}="${g}"`)}let y=l.join(`
|
|
16
|
+
`);if(e.stdout)return{success:!0,output:y};return h(t,y,"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 Gn(e,n,t={}){let r=t.cwd||process.cwd(),i=A(r,t.file||".env"),s=A(r,t.keysFile||".env.keys");try{let o="";if(S(i))o=I(i,"utf-8");let a=o.split(`
|
|
17
|
+
`),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 R of a){let m=R.trim();if(m.startsWith(`${E}=`)){let T=m.match(/^[^=]+=["']?([^"'\n]+)["']?/);if(T)u=T[1];break}}if(u){let R=!1;if(S(s)){let m=I(s,"utf-8"),{parsed:T}=O(m);R=Boolean(T[l])}if(!R&&!process.env[l]&&!ye(o,E))u=void 0}if(!t.plain&&!u){let R=k();u=R.publicKey;let m="";if(S(s))m=I(s,"utf-8");m+=`
|
|
18
|
+
${E}="${R.publicKey}"
|
|
19
|
+
${l}="${R.privateKey}"
|
|
20
|
+
`,h(s,m,"utf-8");for(let T=a.length-1;T>=0;T--){let g=a[T];if(g!==void 0&&g.trim().startsWith(`${E}=`))a.splice(T,1)}a.unshift(`${E}="${u}"`)}let y=n;if(!t.plain&&u)y=B(n,u);for(let R=0;R<a.length;R++){let m=a[R];if(m===void 0)continue;if(m.trim().startsWith(`${e}=`)){a[R]=`${e}="${y}"`,c=!0;break}}if(!c)a.push(`${e}="${y}"`);let v=a.join(`
|
|
21
|
+
`);return h(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 Hn(e,n={}){let t=n.cwd||process.cwd(),r=A(t,n.file||".env");if(!S(r))return{success:!1,error:`File not found: ${r}`};try{let i,s=A(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(S(s)){let l=I(s,"utf-8"),{parsed:y}=O(l);i=y[u]}if(!i)i=process.env[u];let d=I(r,"utf-8"),{parsed:f}=O(d,{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,y])=>`${l}=${y}`).join(" ");break;case"eval":E=Object.entries(p).map(([l,y])=>`${l}="${y}"`).join(`
|
|
22
|
+
`);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 Xn(e,n={}){let t=n.cwd||process.cwd(),r=A(t,n.keysFile||".env.keys");if(!S(r))return{success:!1,error:`Keys file not found: ${r}`};try{let i=I(r,"utf-8"),{parsed:s}=O(i),c=((n.file||".env").split("/").pop()||"").replace(/^\.env\./,"").replace(/^\.env$/,"").toUpperCase(),u=c?`DOTENV_PUBLIC_KEY_${c}`:"DOTENV_PUBLIC_KEY",d=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],[d]:s[d]};return{success:!0,output:n.format==="shell"?`${u}=${f[u]} ${d}=${f[d]}`:JSON.stringify(f)}}catch(i){return{success:!1,error:`Failed to get keypair: ${i instanceof Error?i.message:"Unknown error"}`}}}function jn(e={}){let n=en({file:e.file,keysFile:e.keysFile,stdout:!0,cwd:e.cwd});if(!n.success)return n;let t=e.cwd||process.cwd(),r=A(t,e.file||".env"),i=A(t,e.keysFile||".env.keys");if(n.output===void 0)return{success:!1,error:"Rotation produced no decrypted content"};let s=k(),o=I(r),a=I(i),c=a.toString("utf8").split(`
|
|
23
|
+
`),u=e.file||".env",d=ee(u).replace(/^\.env\./,"").replace(/^\.env$/,"").toUpperCase(),f=d?`DOTENV_PUBLIC_KEY_${d}`:"DOTENV_PUBLIC_KEY",p=d?`DOTENV_PRIVATE_KEY_${d}`:"DOTENV_PRIVATE_KEY",E=!1,l=!1;for(let g=0;g<c.length;g++){let N=c[g];if(N===void 0)continue;if(N.startsWith(`${f}=`))c[g]=`${f}="${s.publicKey}"`,E=!0;else if(N.startsWith(`${p}=`))c[g]=`${p}="${s.privateKey}"`,l=!0}if(!E)c.push(`${f}="${s.publicKey}"`);if(!l)c.push(`${p}="${s.privateKey}"`);let y=`${c.join(`
|
|
24
24
|
`).replace(/\n+$/,"")}
|
|
25
|
-
`,
|
|
26
|
-
`).map((
|
|
27
|
-
`),
|
|
28
|
-
`))}function
|
|
25
|
+
`,v=Re(n.output,s.publicKey,f,e),R=`${process.pid}-${Date.now()}`,m=A(me(r),`.${ee(r)}.${R}.rotate`),T=A(me(i),`.${ee(i)}.${R}.rotate`);try{if(h(m,v,{encoding:"utf8",mode:384}),h(T,y,{encoding:"utf8",mode:384}),e.stdout)return Z(T,i),{success:!0,output:v};Z(m,r);try{Z(T,i)}catch(g){throw h(r,o),g}return{success:!0,output:`\u2714 rotated (${e.file||".env"}) to encrypted:v2`}}catch(g){if(!S(i))h(i,a,{mode:384});return{success:!1,error:`Failed to rotate without exposing plaintext: ${g instanceof Error?g.message:"Unknown error"}`}}finally{_e(m,{force:!0}),_e(T,{force:!0})}}import _ from"process";import{platform as nn}from"os";var Te=typeof Bun<"u",ve=typeof _<"u"&&_.versions?.node!==void 0,tn=Te?"bun":ve?"node":"unknown",Jn={name:tn,version:Te?Bun.version:ve?_.version:void 0},te=nn(),Zn=te==="win32",et=te==="darwin",nt=te==="linux",Ae=Boolean(_.stdout?.isTTY),tt=typeof globalThis.window<"u",rn=Boolean(_.env.CI||_.env.CONTINUOUS_INTEGRATION||_.env.BUILD_NUMBER||_.env.RUN_ID),rt=Boolean(_.env.DEBUG||_.env.VERBOSE||_.argv.includes("--debug")||_.argv.includes("--verbose")),sn=rn||!Ae,it=Boolean(!sn&&(Ae||_.env.COLORTERM||_.env.FORCE_COLOR||_.env.TERM&&_.env.TERM!=="dumb")),ne={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)}},on=Object.keys(ne).find((e)=>{let n=ne[e];return n!==void 0&&n.detected})||"unknown",st=ne[on]||{name:"Unknown",detected:!1};import En from"process";import{projectPath as ln}from"@stacksjs/path";import Ne from"fs";var Ie={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 dn(e){return typeof e==="string"&&(e.startsWith("encrypted:")||e.startsWith("enc:"))}var cn=/(?:^|_)(?:PASSWORD|PASSWD|SECRET|TOKEN|APIKEY|API_KEY|CREDENTIAL|CREDENTIALS|PRIVATE|SALT|DSN|CERT|CIPHER|SIGNATURE|WEBHOOK)(?:_|$)|(?:^|_)(?:ACCESS|SECRET)_KEY(?:_|$)|_KEY$/,an=/^DOTENV_(?:PUBLIC|PRIVATE)_KEY/,un=/^\$\{[^}]+\}$/;function ct(e,n={}){let{placeholders:t={},strict:r=!1}=n,i=[];for(let[s,o]of Object.entries(e)){if(!o||o.trim()==="")continue;if(dn(o))continue;if(an.test(s))continue;if(un.test(o.trim()))continue;let a=cn.test(s),c=Object.prototype.hasOwnProperty.call(t,s)&&t[s]===o;if(a&&!c){i.push({key:s,reason:"plaintext-secret"});continue}if(r)i.push({key:s,reason:"plaintext-value"})}return i}function at(e){return e.split(`
|
|
26
|
+
`).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 fn(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,a)=>a.prefix.length-o.prefix.length),i={},s={};for(let[o,a]of Object.entries(e)){let c=r.find(({prefix:u})=>o.startsWith(u));if(c){(s[c.slug]??={})[o]=a;continue}i[o]=a}return{own:i,foreign:s}}function ft(e,n={}){return fn(e,n).own}function Et(e){return Object.entries(e.foreign).map(([n,t])=>({tenant:n,keys:Object.keys(t).sort()})).sort((n,t)=>n.tenant.localeCompare(t.tenant))}var Se=new Set;function pn(e){if(Se.has(e))return;Se.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 gn={get:(e,n)=>{let t=e,r=t[n];if(typeof r==="string"&&(r.startsWith("encrypted:")||r.startsWith("enc:"))){let s=pe(r);if(s===void 0){pn(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}};function _n(){return typeof Bun<"u"?Bun.env:En.env}var he=new Proxy(_n(),gn);function yt(e,n,t){let r=t?.path||ln(".env"),s=Ne.readFileSync(r,"utf-8").split(`
|
|
27
|
+
`),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(`
|
|
28
|
+
`))}function Tt(e=he){let n=[],t=e;for(let[r,i]of Object.entries(Ie)){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 vt(e,n=he){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{cn as SECRET_NAME_PATTERN,J as activeEnvName,be as aesDecrypt,Rn as aesEncrypt,Un as autoLoadEnv,en as decryptEnv,pe as decryptEnvValue,K as decryptValue,Wn as encryptEnv,B as encryptValue,he as env,Ie as envEnum,W as envKeyNames,Ze as envPlugin,Et as foreignTenantKeys,k as generateKeypair,Hn as getEnv,Xn as getKeypair,q as getPrivateKey,Ae as hasTTY,tt as hasWindow,Te as isBun,rn as isCI,it as isColorSupported,rt as isDebug,dn as isEncryptedValue,yn as isLegacyEncryptedValue,nt as isLinux,et as isMacOS,sn as isMinimal,ve as isNode,Zn as isWindows,ge as loadEnv,Pn as loadEnvFiles,Tn as migrateEncryptedValue,O as parse,vn as parseEnvFromKey,fn as partitionTenantEnv,ct as plaintextSecrets,te as platform,_n as process,on as provider,st as providerInfo,vt as requireEnv,$n as resetPrivateKeyCache,Yn as resolveEnvFile,Je as resolvePrivateKey,ye as reusableEnvPublicKey,jn as rotateKeypair,tn as runtime,Jn as runtimeInfo,Gn as setEnv,ft as stripForeignTenantEnv,Oe as tenantEnvPrefix,at as trackedEnvFiles,Tt as validateEnv,yt as writeEnv};
|
package/dist/parser.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{createCipheriv as
|
|
3
|
-
`);for(let
|
|
4
|
-
`)}if(
|
|
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}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";function J(t,r={}){let e={},n=[],i=[],s=t.split(`
|
|
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
|
+
`)}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
|
|
3
|
-
`);for(let
|
|
4
|
-
`)}if(
|
|
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(`
|
|
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}}import{existsSync as O}from"fs";import{readFileSync as L}from"fs";import{resolve as T}from"path";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/dist/types.d.ts
CHANGED
|
@@ -140,7 +140,100 @@ export declare interface StacksEnv {
|
|
|
140
140
|
AUTH_TOKEN_ROTATION: number | undefined
|
|
141
141
|
AUTH_PASSWORD_RESET_EXPIRE: number | undefined
|
|
142
142
|
AUTH_PASSWORD_RESET_THROTTLE: number | undefined
|
|
143
|
-
|
|
143
|
+
ANTHROPIC_API_KEY: string | undefined
|
|
144
|
+
ANTHROPIC_MAX_TOKENS: string | undefined
|
|
145
|
+
ANTHROPIC_MODEL: string | undefined
|
|
146
|
+
APPLE_CLIENT_ID: string | undefined
|
|
147
|
+
APPLE_KEY_ID: string | undefined
|
|
148
|
+
APPLE_PRIVATE_KEY: string | undefined
|
|
149
|
+
APPLE_REDIRECT_URL: string | undefined
|
|
150
|
+
APPLE_TEAM_ID: string | undefined
|
|
151
|
+
AWS_ENDPOINT: string | undefined
|
|
152
|
+
AWS_USE_PATH_STYLE_ENDPOINT: boolean | undefined
|
|
153
|
+
DB_SSL: string | undefined
|
|
154
|
+
DISCORD_BOT_TOKEN: string | undefined
|
|
155
|
+
DISCORD_MAX_RETRIES: string | undefined
|
|
156
|
+
DISCORD_RETRY_TIMEOUT: string | undefined
|
|
157
|
+
DISCORD_WEBHOOK_URL: string | undefined
|
|
158
|
+
EXPO_ACCESS_TOKEN: string | undefined
|
|
159
|
+
FACEBOOK_CLIENT_ID: string | undefined
|
|
160
|
+
FACEBOOK_CLIENT_SECRET: string | undefined
|
|
161
|
+
FACEBOOK_REDIRECT_URL: string | undefined
|
|
162
|
+
FCM_CLIENT_EMAIL: string | undefined
|
|
163
|
+
FCM_PRIVATE_KEY: string | undefined
|
|
164
|
+
FCM_PROJECT_ID: string | undefined
|
|
165
|
+
FCM_SERVER_KEY: string | undefined
|
|
166
|
+
GITHUB_CLIENT_ID: string | undefined
|
|
167
|
+
GITHUB_CLIENT_SECRET: string | undefined
|
|
168
|
+
GITHUB_REDIRECT_URL: string | undefined
|
|
169
|
+
GOOGLE_CLIENT_ID: string | undefined
|
|
170
|
+
GOOGLE_CLIENT_SECRET: string | undefined
|
|
171
|
+
GOOGLE_REDIRECT_URL: string | undefined
|
|
172
|
+
MAILGUN_API_KEY: string | undefined
|
|
173
|
+
MAILGUN_DOMAIN: string | undefined
|
|
174
|
+
MAILGUN_ENDPOINT: string | undefined
|
|
175
|
+
MAILGUN_MAX_RETRIES: string | undefined
|
|
176
|
+
MAILGUN_RETRY_TIMEOUT: string | undefined
|
|
177
|
+
MAILTRAP_HOST: string | undefined
|
|
178
|
+
MAILTRAP_INBOX_ID: string | undefined
|
|
179
|
+
MAILTRAP_MAX_RETRIES: string | undefined
|
|
180
|
+
MAILTRAP_RETRY_TIMEOUT: string | undefined
|
|
181
|
+
MAILTRAP_TOKEN: string | undefined
|
|
182
|
+
MAIL_MAX_RETRIES: string | undefined
|
|
183
|
+
MAIL_RETRY_TIMEOUT: string | undefined
|
|
184
|
+
OLLAMA_EMBEDDING_MODEL: string | undefined
|
|
185
|
+
OLLAMA_HOST: string | undefined
|
|
186
|
+
OLLAMA_MODEL: string | undefined
|
|
187
|
+
OPENAI_API_KEY: string | undefined
|
|
188
|
+
OPENAI_BASE_URL: string | undefined
|
|
189
|
+
OPENAI_EMBEDDING_MODEL: string | undefined
|
|
190
|
+
OPENAI_MODEL: string | undefined
|
|
191
|
+
PREDICTHQ_DB_PASSWORD: string | undefined
|
|
192
|
+
QUEUE_CONCURRENCY: string | undefined
|
|
193
|
+
QUEUE_DLQ_ENABLED: string | undefined
|
|
194
|
+
QUEUE_DLQ_MAX_RETRIES: string | undefined
|
|
195
|
+
QUEUE_FAILED_DRIVER: string | undefined
|
|
196
|
+
QUEUE_HORIZONTAL_SCALING_ENABLED: string | undefined
|
|
197
|
+
QUEUE_JOBS_PER_WORKER: string | undefined
|
|
198
|
+
QUEUE_LOG_LEVEL: string | undefined
|
|
199
|
+
QUEUE_MAX_WORKERS: string | undefined
|
|
200
|
+
QUEUE_METRICS_ENABLED: string | undefined
|
|
201
|
+
QUEUE_PREFIX: string | undefined
|
|
202
|
+
QUEUE_RATE_LIMIT_DURATION: string | undefined
|
|
203
|
+
QUEUE_RATE_LIMIT_ENABLED: string | undefined
|
|
204
|
+
QUEUE_RATE_LIMIT_MAX: string | undefined
|
|
205
|
+
QUEUE_WORKER_CONCURRENCY: string | undefined
|
|
206
|
+
REDIS_DB: string | undefined
|
|
207
|
+
REDIS_URL: string | undefined
|
|
208
|
+
SENDGRID_API_KEY: string | undefined
|
|
209
|
+
SENDGRID_MAX_RETRIES: string | undefined
|
|
210
|
+
SENDGRID_RETRY_TIMEOUT: string | undefined
|
|
211
|
+
SLACK_APP_ID: string | undefined
|
|
212
|
+
SLACK_BOT_TOKEN: string | undefined
|
|
213
|
+
SLACK_CLIENT_ID: string | undefined
|
|
214
|
+
SLACK_MAX_RETRIES: string | undefined
|
|
215
|
+
SLACK_RETRY_TIMEOUT: string | undefined
|
|
216
|
+
SLACK_SECRET_KEY: string | undefined
|
|
217
|
+
SLACK_WEBHOOK_URL: string | undefined
|
|
218
|
+
SMS_FROM_NUMBER: string | undefined
|
|
219
|
+
SMS_ORIGINATION_NUMBER: string | undefined
|
|
220
|
+
SMS_SENDER_ID: string | undefined
|
|
221
|
+
SQS_PREFIX: string | undefined
|
|
222
|
+
SQS_SUFFIX: string | undefined
|
|
223
|
+
TEAMS_MAX_RETRIES: string | undefined
|
|
224
|
+
TEAMS_RETRY_TIMEOUT: string | undefined
|
|
225
|
+
TEAMS_WEBHOOK_URL: string | undefined
|
|
226
|
+
TWILIO_ACCOUNT_SID: string | undefined
|
|
227
|
+
TWILIO_AUTH_TOKEN: string | undefined
|
|
228
|
+
TWILIO_FROM_NUMBER: string | undefined
|
|
229
|
+
TWILIO_MESSAGING_SERVICE_SID: string | undefined
|
|
230
|
+
TWILIO_VERIFY_SERVICE_SID: string | undefined
|
|
231
|
+
TWITTER_CLIENT_ID: string | undefined
|
|
232
|
+
TWITTER_CLIENT_SECRET: string | undefined
|
|
233
|
+
TWITTER_REDIRECT_URL: string | undefined
|
|
234
|
+
VONAGE_API_KEY: string | undefined
|
|
235
|
+
VONAGE_API_SECRET: string | undefined
|
|
236
|
+
VONAGE_FROM_NUMBER: string | undefined
|
|
144
237
|
}
|
|
145
238
|
export declare interface FrontendEnv {
|
|
146
239
|
FRONTEND_APP_ENV: 'local' | 'development' | 'staging' | 'production'
|
package/dist/utils.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import
|
|
2
|
+
import e from"process";import{platform as s}from"os";var a=typeof Bun<"u",d=typeof e<"u"&&e.versions?.node!==void 0,l=a?"bun":d?"node":"unknown",B={name:l,version:a?Bun.version:d?e.version:void 0},o=s(),b=o==="win32",I=o==="darwin",f=o==="linux",r=Boolean(e.stdout?.isTTY),E=typeof globalThis.window<"u",c=Boolean(e.env.CI||e.env.CONTINUOUS_INTEGRATION||e.env.BUILD_NUMBER||e.env.RUN_ID),R=Boolean(e.env.DEBUG||e.env.VERBOSE||e.argv.includes("--debug")||e.argv.includes("--verbose")),v=c||!r,N=Boolean(!v&&(r||e.env.COLORTERM||e.env.FORCE_COLOR||e.env.TERM&&e.env.TERM!=="dumb")),n={github:{name:"GitHub Actions",detected:Boolean(e.env.GITHUB_ACTIONS)},gitlab:{name:"GitLab CI",detected:Boolean(e.env.GITLAB_CI)},circle:{name:"CircleCI",detected:Boolean(e.env.CIRCLECI)},travis:{name:"Travis CI",detected:Boolean(e.env.TRAVIS)},jenkins:{name:"Jenkins",detected:Boolean(e.env.JENKINS_URL)},vercel:{name:"Vercel",detected:Boolean(e.env.VERCEL)},netlify:{name:"Netlify",detected:Boolean(e.env.NETLIFY)},heroku:{name:"Heroku",detected:Boolean(e.env.DYNO)},aws:{name:"AWS",detected:Boolean(e.env.AWS_REGION||e.env.AWS_LAMBDA_FUNCTION_NAME)},azure:{name:"Azure",detected:Boolean(e.env.AZURE_HTTP_USER_AGENT)},cloudflare:{name:"Cloudflare",detected:Boolean(e.env.CF_PAGES)},railway:{name:"Railway",detected:Boolean(e.env.RAILWAY_ENVIRONMENT)},render:{name:"Render",detected:Boolean(e.env.RENDER)}},u=Object.keys(n).find((i)=>{let t=n[i];return t!==void 0&&t.detected})||"unknown",T=n[u]||{name:"Unknown",detected:!1};export{r as hasTTY,E as hasWindow,a as isBun,c as isCI,N as isColorSupported,R as isDebug,f as isLinux,I as isMacOS,v as isMinimal,d as isNode,b as isWindows,o as platform,u as provider,T as providerInfo,l as runtime,B as runtimeInfo};
|
package/package.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"name": "@stacksjs/env",
|
|
3
3
|
"type": "module",
|
|
4
4
|
"sideEffects": false,
|
|
5
|
-
"version": "0.72.
|
|
5
|
+
"version": "0.72.61",
|
|
6
6
|
"description": "Stacks env helper methods.",
|
|
7
7
|
"author": "Chris Breuer",
|
|
8
8
|
"contributors": [
|
|
@@ -55,10 +55,10 @@
|
|
|
55
55
|
"prepublishOnly": "bun run build"
|
|
56
56
|
},
|
|
57
57
|
"dependencies": {
|
|
58
|
-
"@stacksjs/path": "0.72.
|
|
58
|
+
"@stacksjs/path": "0.72.61"
|
|
59
59
|
},
|
|
60
60
|
"devDependencies": {
|
|
61
61
|
"better-dx": "^0.2.24",
|
|
62
|
-
"@stacksjs/validation": "0.72.
|
|
62
|
+
"@stacksjs/validation": "0.72.61"
|
|
63
63
|
}
|
|
64
64
|
}
|