@devshub198211/devguard 2.0.1

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/CHANGELOG.md ADDED
@@ -0,0 +1,35 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ ## [2.0.0] - 2025-05-08
6
+
7
+ ### Added
8
+ - **Production Hardening**: Complete security audit and fix of all 14 core modules.
9
+ - **Path Traversal Prevention**: Added `safeResolve` and path hashing across `lockfile-guardian`, `agent-memory`, and `hook-scanner`.
10
+ - **SSRF Mitigation**: Implemented hostname whitelisting and protocol validation for all outgoing HTTPS requests in `token-rotator`, `dep-pincer`, and `zero-trust-jwt`.
11
+ - **DoS Protection**: Added buffer size limits, file size limits, and CBOR depth limits across all input parsers.
12
+ - **ReDoS Safety**: Implemented script content truncation and regex optimization in `hook-scanner`.
13
+ - **Atomic Writes**: Added atomic file write patterns (tmp -> rename) for all persistence modules to prevent data corruption.
14
+ - **Prototype Pollution Protection**: Switched to `Object.create(null)` and added key blacklisting in all object parsers.
15
+ - **JWKS Auto-Pruning**: Implemented a bounded, auto-pruning cache for JWKS keys in `zero-trust-jwt`.
16
+ - **BotFence Hardening**: Added IP normalization, lazy block cleanup (serverless-safe), and memory-bounded tracking.
17
+ - **MCP Security**: Added input schema validation, handler timeouts, and sequential message processing.
18
+ - **CLI v2**: Improved CLI with better error reporting, `--version` flag, and process exit code handling.
19
+
20
+ ### Fixed
21
+ - Fixed 8 TypeScript compilation errors including duplicate identifiers and missing exports.
22
+ - Fixed token value leaks in error messages and log outputs.
23
+ - Fixed JWT padding calculation and HMAC algorithm confusion vulnerabilities.
24
+ - Fixed CBOR decoder out-of-bounds read vulnerabilities.
25
+ - Fixed structural JSON repair logic to prevent string corruption.
26
+
27
+ ### Changed
28
+ - Switched to SHA-512 for lockfile integrity.
29
+ - Standardized all module exports and resolved naming collisions.
30
+ - Updated `package.json` with production metadata and repository links.
31
+ - Set `type: module` for modern ESM support.
32
+
33
+ ### Security
34
+ - Comprehensive audit performed: 30+ vulnerabilities resolved.
35
+ - Hardened input validation across all entry points.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 DevGuard Contributors
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,207 @@
1
+ # devguard
2
+
3
+ > **One install. 14 features. Zero external dependencies.**
4
+ > Security · AI Tooling · Auth · DX — everything a production Node.js/TypeScript project needs.
5
+
6
+ ```bash
7
+ npm install devguard
8
+ npx devguard # instant security scan — no install needed
9
+ ```
10
+
11
+ [![npm](https://img.shields.io/npm/v/devguard)](https://www.npmjs.com/package/devguard)
12
+ [![license](https://img.shields.io/npm/l/devguard)](LICENSE)
13
+ [![node](https://img.shields.io/node/v/devguard)](package.json)
14
+
15
+ ---
16
+
17
+ ## Features
18
+
19
+ | Category | Feature | What it does |
20
+ |----------|---------|-------------|
21
+ | 🔒 Security | `lockfile-guardian` | SHA-512 tamper detection for npm/yarn/pnpm lockfiles |
22
+ | 🔒 Security | `hook-scanner` | 23-rule malware scanner for install scripts (obfuscation-aware) |
23
+ | 🔒 Security | `token-rotator` | Live API verification + age alerts for npm/GitHub tokens |
24
+ | 🔒 Security | `dep-pincer` | Enforce exact version pins + SRI hash verification |
25
+ | 🤖 AI | `agent-schema` | Validate LLM JSON output, auto-retry on malformed responses |
26
+ | 🤖 AI | `mcp-server-kit` | Build Claude-compatible MCP tool servers in minutes |
27
+ | 🤖 AI | `agent-memory` | Durable agent state: Memory / FileSystem / Redis / DynamoDB |
28
+ | 🤖 AI | `llm-budget` | Token counting + cost tracking for OpenAI/Anthropic/Gemini |
29
+ | 🔑 Auth | `zero-trust-jwt` | JWT verify (HS256/RS256/JWKS), revocation, anomaly detection |
30
+ | 🔑 Auth | `bot-fence` | Multi-signal bot detection middleware for Express/Fastify |
31
+ | 🔑 Auth | `passkey-node` | Production WebAuthn passkey registration & authentication |
32
+ | 🛠 DX | `env-safe` | Typed .env validation with built-in parser — fail fast |
33
+ | 🛠 DX | `log-otlp` | Structured JSON logger with OpenTelemetry trace injection |
34
+ | 🛠 DX | `api-contract` | Zero-dep schema builder with full TypeScript type inference |
35
+
36
+ ---
37
+
38
+ ## Quick Start
39
+
40
+ ### CLI
41
+ ```bash
42
+ npx devguard # full security scan + score
43
+ npx devguard lockfile snapshot # create baseline after clean install
44
+ npx devguard lockfile verify # check integrity
45
+ npx devguard hooks # scan node_modules for malware
46
+ npx devguard pins --fix # auto-pin unpinned dependencies
47
+ npx devguard tokens --live # verify tokens via API
48
+ npx devguard --json # machine-readable output for CI
49
+ ```
50
+
51
+ ### Programmatic
52
+ ```typescript
53
+ import { runAllChecks } from 'devguard';
54
+
55
+ const report = await runAllChecks();
56
+ // { score: 94, passedAll: true, lockfile: {...}, hooks: {...}, ... }
57
+ if (!report.passedAll) process.exit(1);
58
+ ```
59
+
60
+ ### Tree-shakeable sub-path imports
61
+ ```typescript
62
+ import { verifyLockfile } from 'devguard/security';
63
+ import { LLMBudget } from 'devguard/ai';
64
+ import { JWTVerifier } from 'devguard/auth';
65
+ import { loadEnv } from 'devguard/dx';
66
+ ```
67
+
68
+ ---
69
+
70
+ ## Examples
71
+
72
+ ### Security — run all checks
73
+ ```typescript
74
+ import { runAllChecks } from 'devguard';
75
+ const report = await runAllChecks();
76
+ console.log(`Security score: ${report.score}/100`);
77
+ ```
78
+
79
+ ### AI — validate LLM output
80
+ ```typescript
81
+ import { c, parseWithRetry } from 'devguard';
82
+
83
+ const TaskSchema = c.object({
84
+ title: c.string().min(1),
85
+ priority: c.string().enum(["high","medium","low"]),
86
+ dueDate: c.string().optional(),
87
+ });
88
+
89
+ const result = await parseWithRetry(TaskSchema, async (ctx) => {
90
+ return await callYourLLM(ctx); // your LLM call here
91
+ });
92
+ // result.data is fully typed: { title: string; priority: "high"|"medium"|"low"; dueDate?: string }
93
+ ```
94
+
95
+ ### AI — agent with durable memory
96
+ ```typescript
97
+ import { createMemory } from 'devguard';
98
+
99
+ // Persists across serverless invocations
100
+ const memory = createMemory({ agentId: 'agent-001', adapter: 'fs', ttl: 7200 });
101
+ await memory.setState({ step: 3, context: 'processing order' });
102
+ await memory.appendHistory('user', 'Cancel my order');
103
+ const history = await memory.getHistory(10); // last 10 messages
104
+ ```
105
+
106
+ ### AI — build an MCP tool server
107
+ ```typescript
108
+ import { MCPServerBuilder } from 'devguard';
109
+
110
+ new MCPServerBuilder('my-tools', '1.0.0')
111
+ .addTool({
112
+ name: 'get_weather',
113
+ description: 'Get weather for a city',
114
+ inputSchema: { type:'object', properties:{ city:{type:'string'} }, required:['city'] },
115
+ handler: async ({ city }) => ({ temp: '22°C', city })
116
+ })
117
+ .startStdio(); // works with Claude Desktop + any MCP client
118
+ ```
119
+
120
+ ### Auth — JWT verification
121
+ ```typescript
122
+ import { JWTVerifier } from 'devguard';
123
+
124
+ const verifier = new JWTVerifier({ secret: process.env.JWT_SECRET! });
125
+ const { valid, payload, anomalies } = await verifier.verify(token);
126
+ // anomalies: { score: 0, level: 'safe', warnings: [] }
127
+ ```
128
+
129
+ ### Auth — bot detection middleware
130
+ ```typescript
131
+ import express from 'express';
132
+ import { createMiddleware, IPRateLimiter } from 'devguard';
133
+
134
+ const app = express();
135
+ app.use(createMiddleware({
136
+ blockThreshold: 70,
137
+ rateLimiter: new IPRateLimiter(100, 60_000)
138
+ }));
139
+ ```
140
+
141
+ ### DX — typed .env validation
142
+ ```typescript
143
+ import { loadEnv } from 'devguard';
144
+
145
+ const env = loadEnv({
146
+ DATABASE_URL: { type: 'url', required: true },
147
+ PORT: { type: 'integer', default: '3000', min: 1, max: 65535 },
148
+ NODE_ENV: { type: 'string', enum: ['development','production','test'] },
149
+ API_KEY: { type: 'string', required: true, minLength: 32, secret: true },
150
+ });
151
+ // Throws with clear message if invalid. env.PORT is typed as number.
152
+ ```
153
+
154
+ ### DX — structured logging
155
+ ```typescript
156
+ import { createLogger } from 'devguard';
157
+
158
+ const log = createLogger({ service: 'api', level: 'info' });
159
+ log.info('Request received', { userId: 'u-123', path: '/orders' });
160
+ log.error('Payment failed', { orderId: 'o-456', reason: 'declined' });
161
+
162
+ // Child logger inherits bindings
163
+ const reqLog = log.child({ requestId: 'req-789' });
164
+ reqLog.info('Processing');
165
+ ```
166
+
167
+ ---
168
+
169
+ ## CI/CD Integration
170
+
171
+ ```yaml
172
+ name: DevGuard Security
173
+ on: [push, pull_request]
174
+ jobs:
175
+ security:
176
+ runs-on: ubuntu-latest
177
+ steps:
178
+ - uses: actions/checkout@v4
179
+ - uses: actions/setup-node@v4
180
+ with: { node-version: '20' }
181
+ - run: npm ci
182
+ - run: npx devguard --json > devguard-report.json
183
+ env:
184
+ DEVGUARD_TOKENS: NPM_TOKEN,GITHUB_TOKEN
185
+ NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
186
+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
187
+ - uses: actions/upload-artifact@v4
188
+ with: { name: security-report, path: devguard-report.json }
189
+ - run: node -e "const r=require('./devguard-report.json'); if(!r.passedAll) process.exit(1)"
190
+ ```
191
+
192
+ ---
193
+
194
+ ## Security
195
+
196
+ - ✅ **Zero external runtime dependencies** — only Node.js built-ins
197
+ - ✅ **No network calls** at runtime except token inspection (opt-in)
198
+ - ✅ **No telemetry, no tracking, no phone-home**
199
+ - ✅ **Constant-time JWT comparison** — prevents timing attacks
200
+ - ✅ **Sign-count replay protection** in WebAuthn
201
+ - ✅ **Works fully offline** — all security checks are local
202
+
203
+ ---
204
+
205
+ ## License
206
+
207
+ MIT © DevGuard Contributors