@bhargavratnala/build-env 1.0.0

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Bhargav Ratnala
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,183 @@
1
+ # 🔐 Build-Env
2
+
3
+ **Secure runtime environment variables for frontend applications — without build-time replacement.**
4
+
5
+ `build-env` allows frontend apps (React, Vite, etc.) to **load environment variables at runtime** using encrypted configuration, enabling **one build for multiple environments**.
6
+
7
+ ---
8
+
9
+ ## 🚀 Problem
10
+
11
+ Frontend frameworks normally:
12
+ - Replace env variables **at build time**
13
+ - Require **rebuilding for each environment**
14
+ - Expose values directly in the JS bundle
15
+
16
+ Browsers cannot read `.env` files at runtime.
17
+
18
+ ---
19
+
20
+ ## ✅ Solution
21
+
22
+ `build-env` introduces a **secure runtime env system** using encryption:
23
+
24
+ - 🔒 Encrypted env config
25
+ - ⚙️ Runtime loading (post-build)
26
+ - 🔁 No rebuilds per environment
27
+ - 🛡️ No plaintext env values in bundle
28
+
29
+ ---
30
+
31
+ ## 🧠 How It Works
32
+
33
+ 1. Generate a **public/private key pair**
34
+ 2. Store the **private key** securely in `.env`
35
+ 3. Encrypt environment variables into a config file
36
+ 4. Load & decrypt envs **at runtime**
37
+ 5. Access variables using a `get()` method
38
+
39
+ ---
40
+
41
+ ## 📦 Installation
42
+
43
+ ```bash
44
+ npm install build-env
45
+ ```
46
+
47
+ ## 🪜 Step-by-Step Usage
48
+
49
+ Step 1: Generate Encryption Keys
50
+
51
+ ```bash
52
+ npx build-env generate
53
+ ```
54
+
55
+
56
+ This generates:
57
+ ```text
58
+ private_key # Private key (DO NOT COMMIT)
59
+ public_key.pem # Public key used for encryption
60
+ ```
61
+
62
+ ## Step 2: Store Private Key in .env
63
+
64
+ Add the private key and config path to your .env file:
65
+
66
+ ```env
67
+ VITE_PRIVATE_KEY=your_private_key_here
68
+ VITE_BUILD_ENV_CONFIG=/build-env.config
69
+ ```
70
+
71
+
72
+ > ⚠️ Never commit the private_key file or private key value.
73
+
74
+ ## Step 3: Build Encrypted Environment Config
75
+
76
+ ```bash
77
+ npx build-env build
78
+ ```
79
+
80
+
81
+ This command:
82
+
83
+ Encrypts all environment variables
84
+
85
+ Generates an encrypted config file
86
+
87
+ Saves it inside the `public/directory`
88
+
89
+ Example:
90
+
91
+ public/build-env.config
92
+
93
+ ## Step 4: Load Environment Variables at Runtime
94
+
95
+ Add this code at the root of your application (before rendering the app):
96
+
97
+ ```js
98
+ const [ready, setReady] = useState(false);
99
+
100
+ useEffect(() => {
101
+ async function init() {
102
+ await loadEncryptedEnv(
103
+ import.meta.env.VITE_PRIVATE_KEY,
104
+ import.meta.env.VITE_BUILD_ENV_CONFIG
105
+ );
106
+ setReady(true);
107
+ }
108
+
109
+ init();
110
+ }, []);
111
+ ```
112
+
113
+ Ensure the app renders only after envs are loaded:
114
+
115
+ ```js
116
+ if (!ready) return null;
117
+ ```
118
+
119
+ ## Step 5: Access Environment Variables
120
+
121
+ Use the get method provided by build-env anywhere in your app:
122
+
123
+ ```js
124
+ import { get } from "build-env";
125
+
126
+ const apiUrl = get("API_URL");
127
+ const appMode = get("APP_MODE");
128
+ ```
129
+
130
+ ✔ No process.env
131
+ ✔ No build-time replacement
132
+
133
+
134
+ ## 🧩 Supported Frameworks
135
+
136
+ ✅ React (CRA, Vite)
137
+
138
+ ✅ Vite-based frameworks
139
+
140
+ ✅ Any SPA that supports runtime JavaScript loading
141
+
142
+ ## 🔒 Security Notes
143
+
144
+ All environment variables are encrypted
145
+
146
+ The private key is never shipped in the build
147
+
148
+ Suitable for:
149
+ - API URLs
150
+ - Feature flags
151
+ - Public keys
152
+ - Environment identifiers
153
+
154
+ > ❌ Do not store secrets such as database credentials or private tokens.
155
+
156
+ ## 🏗️ Deployment Workflow
157
+ ```mermaid
158
+ graph TD;
159
+ A[Build once] --> B[Deploy static assets]
160
+ B --> C[Set PRIVATE_KEY in environment]
161
+ C --> D[Serve encrypted config]
162
+ D --> E[App decrypts variables at runtime]
163
+ ```
164
+
165
+ ## Works well with:
166
+
167
+ - Docker
168
+ - Kubernetes
169
+ - Netlify
170
+ - Vercel
171
+ - Nginx / CDN hosting
172
+
173
+ ## 🎯 When to Use build-env
174
+
175
+ Use build-env if you want:
176
+ - A single frontend build
177
+ - Runtime environment configuration
178
+ - No rebuilds per environment
179
+ - Secure environment variable handling
180
+
181
+ ## 📄 License
182
+
183
+ MIT
@@ -0,0 +1,62 @@
1
+ #!/usr/bin/env node
2
+
3
+ import fs from "fs";
4
+ import path from "path";
5
+ import { fileURLToPath } from "url";
6
+ import { generateKeyPair, encryptEnv } from "../src/crypto.js";
7
+
8
+ const __filename = fileURLToPath(import.meta.url);
9
+ const __dirname = path.dirname(__filename);
10
+
11
+ const [command, inputFile] = process.argv.slice(2);
12
+
13
+ function usage() {
14
+ console.log(`
15
+ build-env CLI
16
+
17
+ Usage:
18
+ build-env generate
19
+ build-env build [.env]
20
+
21
+ Examples:
22
+ build-env generate
23
+ build-env build .env
24
+ `);
25
+ }
26
+
27
+ export function saveKeyPair(privateKey, publicKey) {
28
+ fs.writeFileSync("private_key", privateKey);
29
+ fs.writeFileSync("public_key.pem", publicKey);
30
+ }
31
+
32
+ export function readPublicKey() {
33
+ return fs.readFileSync("public_key.pem", "utf8");
34
+ }
35
+
36
+ switch (command) {
37
+ case "generate": {
38
+ const { privateKey, publicKey } = generateKeyPair();
39
+ saveKeyPair(privateKey, publicKey);
40
+ console.log("✅ RSA key pair generated");
41
+ break;
42
+ }
43
+
44
+ case "build": {
45
+ const envFile = inputFile || "build.env";
46
+ if (!fs.existsSync(envFile)) {
47
+ console.error(`❌ File not found: ${envFile}`);
48
+ process.exit(1);
49
+ }
50
+
51
+ const envText = fs.readFileSync(envFile, "utf8");
52
+ const publicKeyPem = readPublicKey();
53
+ const encrypted = encryptEnv(envText, publicKeyPem);
54
+ fs.writeFileSync("public/build.env.json", encrypted);
55
+
56
+ console.log("✅ Encrypted env written to public/build.env.json");
57
+ break;
58
+ }
59
+
60
+ default:
61
+ usage();
62
+ }
package/package.json ADDED
@@ -0,0 +1,18 @@
1
+ {
2
+ "name": "@bhargavratnala/build-env",
3
+ "type": "module",
4
+ "version": "1.0.0",
5
+ "description": "",
6
+ "main": "src/index.js",
7
+ "scripts": {
8
+ "start": "node src/index.js"
9
+ },
10
+ "bin": {
11
+ "build-env": "./bin/build-env.js"
12
+ },
13
+ "author": "",
14
+ "license": "MIT",
15
+ "dependencies": {
16
+ "node-forge": "^1.3.3"
17
+ }
18
+ }
package/src/crypto.js ADDED
@@ -0,0 +1,79 @@
1
+ import forge from "node-forge";
2
+
3
+ /* ---------- KEY MANAGEMENT ---------- */
4
+
5
+ export function generateKeyPair() {
6
+ const { privateKey, publicKey } = forge.pki.rsa.generateKeyPair({ bits: 2048, e: 0x10001 });
7
+ const asn1 = forge.pki.privateKeyToAsn1(privateKey);
8
+ const der = forge.asn1.toDer(asn1).getBytes();
9
+ const base64Key = forge.util.encode64(der);
10
+ return { privateKey: base64Key, publicKey: forge.pki.publicKeyToPem(publicKey) };
11
+ }
12
+
13
+ export function loadPublicKey(publicKeyPem) {
14
+ return forge.pki.publicKeyFromPem(
15
+ publicKeyPem
16
+ );
17
+ }
18
+
19
+ export function loadPrivateKey(privateKeyValue) {
20
+ const der = forge.util.decode64(privateKeyValue);
21
+ const asn1 = forge.asn1.fromDer(der);
22
+ const privateKey = forge.pki.privateKeyFromAsn1(asn1);
23
+ return privateKey;
24
+ }
25
+
26
+ /* ---------- HYBRID ENCRYPTION ---------- */
27
+
28
+ export function encryptEnv(envText, publicKeyPem) {
29
+ const publicKey = loadPublicKey(publicKeyPem);
30
+
31
+ // AES key
32
+ const aesKey = forge.random.getBytesSync(32);
33
+ const iv = forge.random.getBytesSync(12);
34
+
35
+ // Encrypt env using AES-GCM
36
+ const cipher = forge.cipher.createCipher("AES-GCM", aesKey);
37
+ cipher.start({ iv });
38
+ cipher.update(forge.util.createBuffer(envText, "utf8"));
39
+ cipher.finish();
40
+
41
+ const encryptedEnv = cipher.output.getBytes();
42
+ const tag = cipher.mode.tag.getBytes();
43
+
44
+ // Encrypt AES key using RSA
45
+ const encryptedKey = publicKey.encrypt(aesKey, "RSA-OAEP", {
46
+ md: forge.md.sha256.create(),
47
+ });
48
+
49
+ return JSON.stringify({
50
+ key: forge.util.encode64(encryptedKey),
51
+ iv: forge.util.encode64(iv),
52
+ tag: forge.util.encode64(tag),
53
+ data: forge.util.encode64(encryptedEnv),
54
+ });
55
+ }
56
+
57
+ export function decryptEnv(privateKeyValue, payload) {
58
+ const privateKey = loadPrivateKey(privateKeyValue);
59
+
60
+ const parsed = JSON.parse(payload);
61
+
62
+ const aesKey = privateKey.decrypt(
63
+ forge.util.decode64(parsed.key),
64
+ "RSA-OAEP",
65
+ { md: forge.md.sha256.create() }
66
+ );
67
+
68
+ const decipher = forge.cipher.createDecipher("AES-GCM", aesKey);
69
+ decipher.start({
70
+ iv: forge.util.decode64(parsed.iv),
71
+ tag: forge.util.decode64(parsed.tag),
72
+ });
73
+ decipher.update(
74
+ forge.util.createBuffer(forge.util.decode64(parsed.data))
75
+ );
76
+ decipher.finish();
77
+
78
+ return decipher.output.toString("utf8");
79
+ }
package/src/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export { loadEncryptedEnv } from "./loader.js";
2
+ export { get, has, getEnvObject } from "./store.js";
package/src/loader.js ADDED
@@ -0,0 +1,24 @@
1
+ import { decryptEnv } from "./crypto.js";
2
+ import { setEnvObject } from "./store.js";
3
+
4
+ export async function loadEncryptedEnv(privateKey, filename = "build.env.json") {
5
+ const config = await fetch(filename).then((res) => res.text());
6
+ const decrypted = decryptEnv(privateKey, config);
7
+
8
+ const envObject = Object.create(null);
9
+
10
+ decrypted.split("\n").forEach((line) => {
11
+ if (!line || line.startsWith("#")) return;
12
+
13
+ const idx = line.indexOf("=");
14
+ if (idx === -1) return;
15
+
16
+ const key = line.slice(0, idx).trim();
17
+ const value = line.slice(idx + 1).trim();
18
+
19
+ envObject[key] = value;
20
+ });
21
+
22
+ setEnvObject(envObject);
23
+ return envObject;
24
+ }
package/src/store.js ADDED
@@ -0,0 +1,17 @@
1
+ let envStore = Object.create(null);
2
+
3
+ export function setEnvObject(obj) {
4
+ envStore = Object.freeze({ ...obj });
5
+ }
6
+
7
+ export function getEnvObject() {
8
+ return envStore;
9
+ }
10
+
11
+ export function get(key, defaultValue = undefined) {
12
+ return envStore[key] ?? defaultValue;
13
+ }
14
+
15
+ export function has(key) {
16
+ return Object.prototype.hasOwnProperty.call(envStore, key);
17
+ }