@scuton/dotenv-guard 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/.github/ISSUE_TEMPLATE/bug_report.md +22 -0
- package/.github/ISSUE_TEMPLATE/feature_request.md +15 -0
- package/.github/workflows/ci.yml +31 -0
- package/CONTRIBUTING.md +40 -0
- package/LICENSE +21 -0
- package/README.md +85 -0
- package/dist/auto.d.mts +2 -0
- package/dist/auto.d.ts +2 -0
- package/dist/auto.js +81 -0
- package/dist/auto.mjs +30 -0
- package/dist/chunk-QXZQR35R.mjs +222 -0
- package/dist/chunk-RLNPDDSP.mjs +19 -0
- package/dist/chunk-YYFNUR7Y.mjs +54 -0
- package/dist/cli.d.mts +1 -0
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +466 -0
- package/dist/cli.mjs +211 -0
- package/dist/index.d.mts +64 -0
- package/dist/index.d.ts +64 -0
- package/dist/index.js +331 -0
- package/dist/index.mjs +50 -0
- package/package.json +49 -0
- package/src/auto.ts +28 -0
- package/src/cli.ts +225 -0
- package/src/core/generator.ts +49 -0
- package/src/core/leak.ts +115 -0
- package/src/core/parser.ts +50 -0
- package/src/core/sync.ts +34 -0
- package/src/core/validator.ts +126 -0
- package/src/index.ts +42 -0
- package/src/utils/colors.ts +13 -0
- package/src/utils/helpers.ts +20 -0
- package/tests/generator.test.ts +104 -0
- package/tests/leak.test.ts +52 -0
- package/tests/parser.test.ts +82 -0
- package/tests/sync.test.ts +78 -0
- package/tests/validator.test.ts +127 -0
- package/tsconfig.json +21 -0
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: Bug Report
|
|
3
|
+
about: Report a bug in dotenv-guard
|
|
4
|
+
title: "[Bug] "
|
|
5
|
+
labels: bug
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
**Describe the bug**
|
|
9
|
+
A clear description of what the bug is.
|
|
10
|
+
|
|
11
|
+
**To Reproduce**
|
|
12
|
+
Steps to reproduce:
|
|
13
|
+
1. ...
|
|
14
|
+
2. ...
|
|
15
|
+
|
|
16
|
+
**Expected behavior**
|
|
17
|
+
What you expected to happen.
|
|
18
|
+
|
|
19
|
+
**Environment**
|
|
20
|
+
- Node.js version:
|
|
21
|
+
- dotenv-guard version:
|
|
22
|
+
- OS:
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: Feature Request
|
|
3
|
+
about: Suggest a feature for dotenv-guard
|
|
4
|
+
title: "[Feature] "
|
|
5
|
+
labels: enhancement
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
**Problem**
|
|
9
|
+
What problem does this solve?
|
|
10
|
+
|
|
11
|
+
**Proposed solution**
|
|
12
|
+
How should it work?
|
|
13
|
+
|
|
14
|
+
**Alternatives considered**
|
|
15
|
+
Any other approaches you've thought about.
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
name: CI
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
push:
|
|
5
|
+
branches: [main]
|
|
6
|
+
pull_request:
|
|
7
|
+
branches: [main]
|
|
8
|
+
|
|
9
|
+
jobs:
|
|
10
|
+
test:
|
|
11
|
+
runs-on: ubuntu-latest
|
|
12
|
+
strategy:
|
|
13
|
+
matrix:
|
|
14
|
+
node-version: [16, 18, 20, 22]
|
|
15
|
+
|
|
16
|
+
steps:
|
|
17
|
+
- uses: actions/checkout@v4
|
|
18
|
+
|
|
19
|
+
- name: Use Node.js ${{ matrix.node-version }}
|
|
20
|
+
uses: actions/setup-node@v4
|
|
21
|
+
with:
|
|
22
|
+
node-version: ${{ matrix.node-version }}
|
|
23
|
+
|
|
24
|
+
- name: Install dependencies
|
|
25
|
+
run: npm install
|
|
26
|
+
|
|
27
|
+
- name: Build
|
|
28
|
+
run: npm run build
|
|
29
|
+
|
|
30
|
+
- name: Test
|
|
31
|
+
run: npm test -- --run
|
package/CONTRIBUTING.md
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
# Contributing to dotenv-guard
|
|
2
|
+
|
|
3
|
+
Thanks for your interest in contributing!
|
|
4
|
+
|
|
5
|
+
## Setup
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
git clone https://github.com/scuton-technology/dotenv-guard.git
|
|
9
|
+
cd dotenv-guard
|
|
10
|
+
npm install
|
|
11
|
+
npm run build
|
|
12
|
+
npm test
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
## Development
|
|
16
|
+
|
|
17
|
+
```bash
|
|
18
|
+
npm run dev # Watch mode
|
|
19
|
+
npm test # Run tests
|
|
20
|
+
npm run build # Production build
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
## Guidelines
|
|
24
|
+
|
|
25
|
+
- Zero runtime dependencies — use Node.js built-ins only
|
|
26
|
+
- Write tests for new features
|
|
27
|
+
- Follow existing code style
|
|
28
|
+
- Keep it simple and fast
|
|
29
|
+
|
|
30
|
+
## Pull Requests
|
|
31
|
+
|
|
32
|
+
1. Fork the repo
|
|
33
|
+
2. Create a feature branch (`git checkout -b feature/my-feature`)
|
|
34
|
+
3. Commit changes (`git commit -m 'feat: add my feature'`)
|
|
35
|
+
4. Push (`git push origin feature/my-feature`)
|
|
36
|
+
5. Open a PR
|
|
37
|
+
|
|
38
|
+
## Reporting Issues
|
|
39
|
+
|
|
40
|
+
Use [GitHub Issues](https://github.com/scuton-technology/dotenv-guard/issues) with the provided templates.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Scuton Technology
|
|
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,85 @@
|
|
|
1
|
+
<div align="center">
|
|
2
|
+
|
|
3
|
+
# dotenv-guard
|
|
4
|
+
|
|
5
|
+
**Validate env vars. Sync .env files. Prevent secret leaks.**
|
|
6
|
+
|
|
7
|
+
**Zero dependencies.** Works with any Node.js project.
|
|
8
|
+
|
|
9
|
+
[](https://www.npmjs.com/package/dotenv-guard)
|
|
10
|
+
[](LICENSE)
|
|
11
|
+
[](package.json)
|
|
12
|
+
|
|
13
|
+
</div>
|
|
14
|
+
|
|
15
|
+
---
|
|
16
|
+
|
|
17
|
+
## Install
|
|
18
|
+
|
|
19
|
+
```bash
|
|
20
|
+
npm install dotenv-guard
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
## Quick Start
|
|
24
|
+
|
|
25
|
+
Add one line to your app entry:
|
|
26
|
+
|
|
27
|
+
```typescript
|
|
28
|
+
import 'dotenv-guard/auto'; // App won't start if .env is missing required variables
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
Or use the CLI:
|
|
32
|
+
|
|
33
|
+
```bash
|
|
34
|
+
npx dotenv-guard sync # .env vs .env.example
|
|
35
|
+
npx dotenv-guard validate # Check types
|
|
36
|
+
npx dotenv-guard leak-check # Find leaked secrets
|
|
37
|
+
npx dotenv-guard init # Create .env.example + .gitignore
|
|
38
|
+
npx dotenv-guard install-hook # Pre-commit hook
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
## Type Hints
|
|
42
|
+
|
|
43
|
+
Add type hints in .env.example comments:
|
|
44
|
+
|
|
45
|
+
```bash
|
|
46
|
+
DATABASE_URL=postgresql://... # type:url
|
|
47
|
+
PORT=3000 # type:port
|
|
48
|
+
DEBUG=false # type:boolean
|
|
49
|
+
NODE_ENV=development # enum:development,staging,production
|
|
50
|
+
REDIS_URL= # type:url optional
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
## Programmatic API
|
|
54
|
+
|
|
55
|
+
```typescript
|
|
56
|
+
import { guard, syncCheck, validate, checkLeaks } from 'dotenv-guard';
|
|
57
|
+
|
|
58
|
+
// Quick guard — exits if missing vars
|
|
59
|
+
guard();
|
|
60
|
+
|
|
61
|
+
// Detailed sync check
|
|
62
|
+
const sync = syncCheck();
|
|
63
|
+
console.log(sync.missing); // ['API_KEY', 'SECRET']
|
|
64
|
+
|
|
65
|
+
// Custom validation
|
|
66
|
+
const errors = validate(process.env, [
|
|
67
|
+
{ key: 'PORT', type: 'port', required: true },
|
|
68
|
+
{ key: 'NODE_ENV', type: 'enum', enum: ['dev', 'staging', 'prod'] },
|
|
69
|
+
]);
|
|
70
|
+
|
|
71
|
+
// Leak detection
|
|
72
|
+
const leaks = checkLeaks();
|
|
73
|
+
if (leaks.leaks.length > 0) console.warn('Secrets leaked!');
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
## Why?
|
|
77
|
+
|
|
78
|
+
- **Missing env vars** crash your app at runtime -> dotenv-guard catches them at startup
|
|
79
|
+
- **Type mismatches** (port as string, URL without protocol) -> dotenv-guard validates
|
|
80
|
+
- **.env committed to git** -> dotenv-guard blocks it with pre-commit hook
|
|
81
|
+
- **Zero dependencies** -> no supply chain risk, tiny bundle
|
|
82
|
+
|
|
83
|
+
## License
|
|
84
|
+
|
|
85
|
+
MIT - [Scuton Technology](https://scuton.com)
|
package/dist/auto.d.mts
ADDED
package/dist/auto.d.ts
ADDED
package/dist/auto.js
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
// src/core/sync.ts
|
|
4
|
+
var import_fs = require("fs");
|
|
5
|
+
|
|
6
|
+
// src/core/parser.ts
|
|
7
|
+
function parseEnvFile(content) {
|
|
8
|
+
const entries = [];
|
|
9
|
+
const lines = content.split("\n");
|
|
10
|
+
for (let i = 0; i < lines.length; i++) {
|
|
11
|
+
const raw = lines[i];
|
|
12
|
+
const trimmed = raw.trim();
|
|
13
|
+
if (!trimmed || trimmed.startsWith("#")) continue;
|
|
14
|
+
const match = trimmed.match(/^([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)/);
|
|
15
|
+
if (!match) continue;
|
|
16
|
+
const key = match[1];
|
|
17
|
+
let value = match[2];
|
|
18
|
+
if (value.startsWith('"') && value.endsWith('"') || value.startsWith("'") && value.endsWith("'")) {
|
|
19
|
+
value = value.slice(1, -1);
|
|
20
|
+
}
|
|
21
|
+
const commentMatch = value.match(/\s+#\s/);
|
|
22
|
+
let comment;
|
|
23
|
+
if (commentMatch && !match[2].startsWith('"') && !match[2].startsWith("'")) {
|
|
24
|
+
comment = value.slice(commentMatch.index + commentMatch[0].length);
|
|
25
|
+
value = value.slice(0, commentMatch.index);
|
|
26
|
+
}
|
|
27
|
+
entries.push({ key, value, line: i + 1, comment, raw });
|
|
28
|
+
}
|
|
29
|
+
return entries;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// src/core/sync.ts
|
|
33
|
+
function syncCheck(envPath = ".env", examplePath = ".env.example") {
|
|
34
|
+
if (!(0, import_fs.existsSync)(examplePath)) {
|
|
35
|
+
throw new Error(`${examplePath} not found. Run "dotenv-guard init" to create one.`);
|
|
36
|
+
}
|
|
37
|
+
const exampleContent = (0, import_fs.readFileSync)(examplePath, "utf-8");
|
|
38
|
+
const exampleKeys = new Set(parseEnvFile(exampleContent).map((e) => e.key));
|
|
39
|
+
let envKeys = /* @__PURE__ */ new Set();
|
|
40
|
+
if ((0, import_fs.existsSync)(envPath)) {
|
|
41
|
+
const envContent = (0, import_fs.readFileSync)(envPath, "utf-8");
|
|
42
|
+
envKeys = new Set(parseEnvFile(envContent).map((e) => e.key));
|
|
43
|
+
}
|
|
44
|
+
const missing = [...exampleKeys].filter((k) => !envKeys.has(k));
|
|
45
|
+
const extra = [...envKeys].filter((k) => !exampleKeys.has(k));
|
|
46
|
+
const synced = [...exampleKeys].filter((k) => envKeys.has(k));
|
|
47
|
+
return { missing, extra, synced, examplePath, envPath };
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// src/utils/colors.ts
|
|
51
|
+
var isColorSupported = process.env.NO_COLOR === void 0 && process.stdout.isTTY;
|
|
52
|
+
var wrap = (code, resetCode) => (str) => isColorSupported ? `\x1B[${code}m${str}\x1B[${resetCode}m` : str;
|
|
53
|
+
var red = wrap(31, 39);
|
|
54
|
+
var green = wrap(32, 39);
|
|
55
|
+
var yellow = wrap(33, 39);
|
|
56
|
+
var blue = wrap(34, 39);
|
|
57
|
+
var gray = wrap(90, 39);
|
|
58
|
+
var bold = wrap(1, 22);
|
|
59
|
+
var dim = wrap(2, 22);
|
|
60
|
+
|
|
61
|
+
// src/auto.ts
|
|
62
|
+
try {
|
|
63
|
+
const result = syncCheck();
|
|
64
|
+
if (result.missing.length > 0) {
|
|
65
|
+
console.error("");
|
|
66
|
+
console.error(red(bold(" \u2716 dotenv-guard: Missing environment variables")));
|
|
67
|
+
console.error("");
|
|
68
|
+
for (const key of result.missing) {
|
|
69
|
+
console.error(yellow(` \u2192 ${key}`));
|
|
70
|
+
}
|
|
71
|
+
console.error("");
|
|
72
|
+
console.error(` These variables are in ${result.examplePath} but missing from ${result.envPath}`);
|
|
73
|
+
console.error(` Run: ${bold("dotenv-guard sync")} to see details`);
|
|
74
|
+
console.error("");
|
|
75
|
+
process.exit(1);
|
|
76
|
+
}
|
|
77
|
+
} catch (err) {
|
|
78
|
+
if (!err.message.includes("not found")) {
|
|
79
|
+
console.warn(yellow(` \u26A0 dotenv-guard: ${err.message}`));
|
|
80
|
+
}
|
|
81
|
+
}
|
package/dist/auto.mjs
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import {
|
|
2
|
+
bold,
|
|
3
|
+
red,
|
|
4
|
+
yellow
|
|
5
|
+
} from "./chunk-RLNPDDSP.mjs";
|
|
6
|
+
import {
|
|
7
|
+
syncCheck
|
|
8
|
+
} from "./chunk-YYFNUR7Y.mjs";
|
|
9
|
+
|
|
10
|
+
// src/auto.ts
|
|
11
|
+
try {
|
|
12
|
+
const result = syncCheck();
|
|
13
|
+
if (result.missing.length > 0) {
|
|
14
|
+
console.error("");
|
|
15
|
+
console.error(red(bold(" \u2716 dotenv-guard: Missing environment variables")));
|
|
16
|
+
console.error("");
|
|
17
|
+
for (const key of result.missing) {
|
|
18
|
+
console.error(yellow(` \u2192 ${key}`));
|
|
19
|
+
}
|
|
20
|
+
console.error("");
|
|
21
|
+
console.error(` These variables are in ${result.examplePath} but missing from ${result.envPath}`);
|
|
22
|
+
console.error(` Run: ${bold("dotenv-guard sync")} to see details`);
|
|
23
|
+
console.error("");
|
|
24
|
+
process.exit(1);
|
|
25
|
+
}
|
|
26
|
+
} catch (err) {
|
|
27
|
+
if (!err.message.includes("not found")) {
|
|
28
|
+
console.warn(yellow(` \u26A0 dotenv-guard: ${err.message}`));
|
|
29
|
+
}
|
|
30
|
+
}
|
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
import {
|
|
2
|
+
parseEnvFile
|
|
3
|
+
} from "./chunk-YYFNUR7Y.mjs";
|
|
4
|
+
|
|
5
|
+
// src/core/validator.ts
|
|
6
|
+
function validate(env, rules) {
|
|
7
|
+
const errors = [];
|
|
8
|
+
for (const rule of rules) {
|
|
9
|
+
const value = env[rule.key];
|
|
10
|
+
if (rule.required !== false && (value === void 0 || value === "")) {
|
|
11
|
+
errors.push({ key: rule.key, message: "is required but missing or empty" });
|
|
12
|
+
continue;
|
|
13
|
+
}
|
|
14
|
+
if (value === void 0 || value === "") continue;
|
|
15
|
+
switch (rule.type) {
|
|
16
|
+
case "number": {
|
|
17
|
+
const num = Number(value);
|
|
18
|
+
if (isNaN(num)) {
|
|
19
|
+
errors.push({ key: rule.key, value, message: `must be a number, got "${value}"` });
|
|
20
|
+
} else {
|
|
21
|
+
if (rule.min !== void 0 && num < rule.min)
|
|
22
|
+
errors.push({ key: rule.key, value, message: `must be >= ${rule.min}` });
|
|
23
|
+
if (rule.max !== void 0 && num > rule.max)
|
|
24
|
+
errors.push({ key: rule.key, value, message: `must be <= ${rule.max}` });
|
|
25
|
+
}
|
|
26
|
+
break;
|
|
27
|
+
}
|
|
28
|
+
case "boolean":
|
|
29
|
+
if (!["true", "false", "1", "0", "yes", "no"].includes(value.toLowerCase()))
|
|
30
|
+
errors.push({ key: rule.key, value, message: "must be a boolean (true/false/1/0/yes/no)" });
|
|
31
|
+
break;
|
|
32
|
+
case "url":
|
|
33
|
+
try {
|
|
34
|
+
new URL(value);
|
|
35
|
+
} catch {
|
|
36
|
+
errors.push({ key: rule.key, value, message: "must be a valid URL" });
|
|
37
|
+
}
|
|
38
|
+
break;
|
|
39
|
+
case "email":
|
|
40
|
+
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value))
|
|
41
|
+
errors.push({ key: rule.key, value, message: "must be a valid email" });
|
|
42
|
+
break;
|
|
43
|
+
case "port": {
|
|
44
|
+
const port = Number(value);
|
|
45
|
+
if (isNaN(port) || port < 1 || port > 65535)
|
|
46
|
+
errors.push({ key: rule.key, value, message: "must be a valid port (1-65535)" });
|
|
47
|
+
break;
|
|
48
|
+
}
|
|
49
|
+
case "enum":
|
|
50
|
+
if (rule.enum && !rule.enum.includes(value))
|
|
51
|
+
errors.push({ key: rule.key, value, message: `must be one of: ${rule.enum.join(", ")}` });
|
|
52
|
+
break;
|
|
53
|
+
}
|
|
54
|
+
if (rule.pattern && !rule.pattern.test(value))
|
|
55
|
+
errors.push({ key: rule.key, value, message: `does not match required pattern` });
|
|
56
|
+
}
|
|
57
|
+
return errors;
|
|
58
|
+
}
|
|
59
|
+
function inferRules(exampleContent) {
|
|
60
|
+
const lines = exampleContent.split("\n");
|
|
61
|
+
const rules = [];
|
|
62
|
+
for (const line of lines) {
|
|
63
|
+
const match = line.match(/^([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)/);
|
|
64
|
+
if (!match) continue;
|
|
65
|
+
const key = match[1];
|
|
66
|
+
const rest = match[2];
|
|
67
|
+
const rule = { key, required: true };
|
|
68
|
+
const commentMatch = rest.match(/#\s*type:\s*(\w+)/i);
|
|
69
|
+
if (commentMatch) {
|
|
70
|
+
rule.type = commentMatch[1].toLowerCase();
|
|
71
|
+
}
|
|
72
|
+
if (rest.match(/#.*optional/i)) {
|
|
73
|
+
rule.required = false;
|
|
74
|
+
}
|
|
75
|
+
const enumMatch = rest.match(/#\s*enum:\s*([^\s]+)/i);
|
|
76
|
+
if (enumMatch) {
|
|
77
|
+
rule.type = "enum";
|
|
78
|
+
rule.enum = enumMatch[1].split(",");
|
|
79
|
+
}
|
|
80
|
+
if (!rule.type) {
|
|
81
|
+
const value = rest.split("#")[0].trim().replace(/^["']|["']$/g, "");
|
|
82
|
+
if (value.match(/^https?:\/\//)) rule.type = "url";
|
|
83
|
+
else if (value.match(/^\d+$/) && key.match(/PORT/i)) rule.type = "port";
|
|
84
|
+
else if (value.match(/^(true|false)$/i)) rule.type = "boolean";
|
|
85
|
+
else if (value.match(/^\d+$/)) rule.type = "number";
|
|
86
|
+
}
|
|
87
|
+
rules.push(rule);
|
|
88
|
+
}
|
|
89
|
+
return rules;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// src/core/leak.ts
|
|
93
|
+
import { execSync } from "child_process";
|
|
94
|
+
import { readFileSync, existsSync, mkdirSync, writeFileSync, chmodSync } from "fs";
|
|
95
|
+
var SENSITIVE_PATTERNS = [
|
|
96
|
+
/API[_-]?KEY/i,
|
|
97
|
+
/SECRET/i,
|
|
98
|
+
/PASSWORD/i,
|
|
99
|
+
/TOKEN/i,
|
|
100
|
+
/PRIVATE[_-]?KEY/i,
|
|
101
|
+
/DATABASE[_-]?URL/i,
|
|
102
|
+
/MONGO[_-]?URI/i,
|
|
103
|
+
/REDIS[_-]?URL/i,
|
|
104
|
+
/AWS[_-]?ACCESS/i,
|
|
105
|
+
/STRIPE/i,
|
|
106
|
+
/SENDGRID/i,
|
|
107
|
+
/TWILIO/i,
|
|
108
|
+
/ANTHROPIC/i,
|
|
109
|
+
/OPENAI/i
|
|
110
|
+
];
|
|
111
|
+
function checkLeaks(dir = ".") {
|
|
112
|
+
const leaks = [];
|
|
113
|
+
let gitignoreHasEnv = false;
|
|
114
|
+
const gitignorePath = `${dir}/.gitignore`;
|
|
115
|
+
if (existsSync(gitignorePath)) {
|
|
116
|
+
const content = readFileSync(gitignorePath, "utf-8");
|
|
117
|
+
gitignoreHasEnv = content.split("\n").some(
|
|
118
|
+
(line) => line.trim() === ".env" || line.trim() === ".env*" || line.trim() === ".env.local"
|
|
119
|
+
);
|
|
120
|
+
}
|
|
121
|
+
try {
|
|
122
|
+
const tracked = execSync("git ls-files", { cwd: dir, encoding: "utf-8" });
|
|
123
|
+
const envFiles = tracked.split("\n").filter(
|
|
124
|
+
(f) => f.match(/^\.env($|\.)/) && !f.endsWith(".example") && !f.endsWith(".template")
|
|
125
|
+
);
|
|
126
|
+
for (const file of envFiles) {
|
|
127
|
+
const content = readFileSync(`${dir}/${file}`, "utf-8");
|
|
128
|
+
const lines = content.split("\n");
|
|
129
|
+
for (let i = 0; i < lines.length; i++) {
|
|
130
|
+
const match = lines[i].match(/^([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.+)/);
|
|
131
|
+
if (match && match[2].trim().length > 0) {
|
|
132
|
+
const key = match[1];
|
|
133
|
+
const severity = SENSITIVE_PATTERNS.some((p) => p.test(key)) ? "high" : "medium";
|
|
134
|
+
leaks.push({ file, line: i + 1, key, severity });
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
} catch {
|
|
139
|
+
}
|
|
140
|
+
let preCommitHookInstalled = false;
|
|
141
|
+
const hookPath = `${dir}/.git/hooks/pre-commit`;
|
|
142
|
+
if (existsSync(hookPath)) {
|
|
143
|
+
const hookContent = readFileSync(hookPath, "utf-8");
|
|
144
|
+
preCommitHookInstalled = hookContent.includes("dotenv-guard");
|
|
145
|
+
}
|
|
146
|
+
return { leaks, gitignoreHasEnv, preCommitHookInstalled };
|
|
147
|
+
}
|
|
148
|
+
function installPreCommitHook(dir = ".") {
|
|
149
|
+
const hookDir = `${dir}/.git/hooks`;
|
|
150
|
+
const hookPath = `${hookDir}/pre-commit`;
|
|
151
|
+
const hookScript = `#!/bin/sh
|
|
152
|
+
# dotenv-guard pre-commit hook \u2014 prevent .env leaks
|
|
153
|
+
# Installed by: npx dotenv-guard install-hook
|
|
154
|
+
|
|
155
|
+
ENV_FILES=$(git diff --cached --name-only | grep -E '^\\.env' | grep -v '\\.example$' | grep -v '\\.template$')
|
|
156
|
+
|
|
157
|
+
if [ -n "$ENV_FILES" ]; then
|
|
158
|
+
echo ""
|
|
159
|
+
echo "\\033[31m\u2716 dotenv-guard: Blocked commit \u2014 .env file(s) detected:\\033[0m"
|
|
160
|
+
echo ""
|
|
161
|
+
for f in $ENV_FILES; do
|
|
162
|
+
echo " \\033[33m\u2192 $f\\033[0m"
|
|
163
|
+
done
|
|
164
|
+
echo ""
|
|
165
|
+
echo " Remove with: git reset HEAD <file>"
|
|
166
|
+
echo " Or force commit: git commit --no-verify"
|
|
167
|
+
echo ""
|
|
168
|
+
exit 1
|
|
169
|
+
fi
|
|
170
|
+
`;
|
|
171
|
+
mkdirSync(hookDir, { recursive: true });
|
|
172
|
+
writeFileSync(hookPath, hookScript, "utf-8");
|
|
173
|
+
try {
|
|
174
|
+
chmodSync(hookPath, "755");
|
|
175
|
+
} catch {
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
// src/core/generator.ts
|
|
180
|
+
import { readFileSync as readFileSync2, writeFileSync as writeFileSync2, existsSync as existsSync2, appendFileSync } from "fs";
|
|
181
|
+
function generateExample(envPath = ".env", outputPath = ".env.example") {
|
|
182
|
+
if (!existsSync2(envPath)) throw new Error(`${envPath} not found`);
|
|
183
|
+
const content = readFileSync2(envPath, "utf-8");
|
|
184
|
+
const entries = parseEnvFile(content);
|
|
185
|
+
const lines = ["# Environment Variables", "# Copy this file to .env and fill in the values", ""];
|
|
186
|
+
for (const entry of entries) {
|
|
187
|
+
let placeholder = "";
|
|
188
|
+
if (entry.value.match(/^https?:\/\//)) placeholder = "https://... # type:url";
|
|
189
|
+
else if (entry.value.match(/^\d+$/)) placeholder = "0 # type:number";
|
|
190
|
+
else if (entry.value.match(/^(true|false)$/i)) placeholder = "false # type:boolean";
|
|
191
|
+
else placeholder = "# type:string";
|
|
192
|
+
lines.push(`${entry.key}=${placeholder}`);
|
|
193
|
+
}
|
|
194
|
+
const output = lines.join("\n") + "\n";
|
|
195
|
+
writeFileSync2(outputPath, output, "utf-8");
|
|
196
|
+
return output;
|
|
197
|
+
}
|
|
198
|
+
function ensureGitignore(dir = ".") {
|
|
199
|
+
const gitignorePath = `${dir}/.gitignore`;
|
|
200
|
+
const envEntries = [".env", ".env.local", ".env.*.local"];
|
|
201
|
+
let content = "";
|
|
202
|
+
if (existsSync2(gitignorePath)) {
|
|
203
|
+
content = readFileSync2(gitignorePath, "utf-8");
|
|
204
|
+
}
|
|
205
|
+
const lines = content.split("\n");
|
|
206
|
+
const toAdd = envEntries.filter((e) => !lines.some((l) => l.trim() === e));
|
|
207
|
+
if (toAdd.length > 0) {
|
|
208
|
+
const addition = "\n# Environment variables\n" + toAdd.join("\n") + "\n";
|
|
209
|
+
appendFileSync(gitignorePath, addition, "utf-8");
|
|
210
|
+
return true;
|
|
211
|
+
}
|
|
212
|
+
return false;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
export {
|
|
216
|
+
validate,
|
|
217
|
+
inferRules,
|
|
218
|
+
checkLeaks,
|
|
219
|
+
installPreCommitHook,
|
|
220
|
+
generateExample,
|
|
221
|
+
ensureGitignore
|
|
222
|
+
};
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
// src/utils/colors.ts
|
|
2
|
+
var isColorSupported = process.env.NO_COLOR === void 0 && process.stdout.isTTY;
|
|
3
|
+
var wrap = (code, resetCode) => (str) => isColorSupported ? `\x1B[${code}m${str}\x1B[${resetCode}m` : str;
|
|
4
|
+
var red = wrap(31, 39);
|
|
5
|
+
var green = wrap(32, 39);
|
|
6
|
+
var yellow = wrap(33, 39);
|
|
7
|
+
var blue = wrap(34, 39);
|
|
8
|
+
var gray = wrap(90, 39);
|
|
9
|
+
var bold = wrap(1, 22);
|
|
10
|
+
var dim = wrap(2, 22);
|
|
11
|
+
|
|
12
|
+
export {
|
|
13
|
+
red,
|
|
14
|
+
green,
|
|
15
|
+
yellow,
|
|
16
|
+
gray,
|
|
17
|
+
bold,
|
|
18
|
+
dim
|
|
19
|
+
};
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
// src/core/parser.ts
|
|
2
|
+
function parseEnvFile(content) {
|
|
3
|
+
const entries = [];
|
|
4
|
+
const lines = content.split("\n");
|
|
5
|
+
for (let i = 0; i < lines.length; i++) {
|
|
6
|
+
const raw = lines[i];
|
|
7
|
+
const trimmed = raw.trim();
|
|
8
|
+
if (!trimmed || trimmed.startsWith("#")) continue;
|
|
9
|
+
const match = trimmed.match(/^([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)/);
|
|
10
|
+
if (!match) continue;
|
|
11
|
+
const key = match[1];
|
|
12
|
+
let value = match[2];
|
|
13
|
+
if (value.startsWith('"') && value.endsWith('"') || value.startsWith("'") && value.endsWith("'")) {
|
|
14
|
+
value = value.slice(1, -1);
|
|
15
|
+
}
|
|
16
|
+
const commentMatch = value.match(/\s+#\s/);
|
|
17
|
+
let comment;
|
|
18
|
+
if (commentMatch && !match[2].startsWith('"') && !match[2].startsWith("'")) {
|
|
19
|
+
comment = value.slice(commentMatch.index + commentMatch[0].length);
|
|
20
|
+
value = value.slice(0, commentMatch.index);
|
|
21
|
+
}
|
|
22
|
+
entries.push({ key, value, line: i + 1, comment, raw });
|
|
23
|
+
}
|
|
24
|
+
return entries;
|
|
25
|
+
}
|
|
26
|
+
function parseEnvFileToMap(content) {
|
|
27
|
+
const entries = parseEnvFile(content);
|
|
28
|
+
return new Map(entries.map((e) => [e.key, e.value]));
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
// src/core/sync.ts
|
|
32
|
+
import { readFileSync, existsSync } from "fs";
|
|
33
|
+
function syncCheck(envPath = ".env", examplePath = ".env.example") {
|
|
34
|
+
if (!existsSync(examplePath)) {
|
|
35
|
+
throw new Error(`${examplePath} not found. Run "dotenv-guard init" to create one.`);
|
|
36
|
+
}
|
|
37
|
+
const exampleContent = readFileSync(examplePath, "utf-8");
|
|
38
|
+
const exampleKeys = new Set(parseEnvFile(exampleContent).map((e) => e.key));
|
|
39
|
+
let envKeys = /* @__PURE__ */ new Set();
|
|
40
|
+
if (existsSync(envPath)) {
|
|
41
|
+
const envContent = readFileSync(envPath, "utf-8");
|
|
42
|
+
envKeys = new Set(parseEnvFile(envContent).map((e) => e.key));
|
|
43
|
+
}
|
|
44
|
+
const missing = [...exampleKeys].filter((k) => !envKeys.has(k));
|
|
45
|
+
const extra = [...envKeys].filter((k) => !exampleKeys.has(k));
|
|
46
|
+
const synced = [...exampleKeys].filter((k) => envKeys.has(k));
|
|
47
|
+
return { missing, extra, synced, examplePath, envPath };
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export {
|
|
51
|
+
parseEnvFile,
|
|
52
|
+
parseEnvFileToMap,
|
|
53
|
+
syncCheck
|
|
54
|
+
};
|
package/dist/cli.d.mts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
package/dist/cli.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
#!/usr/bin/env node
|