ruvnet-kb-first 5.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.
Files changed (52) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +674 -0
  3. package/SKILL.md +740 -0
  4. package/bin/kb-first.js +123 -0
  5. package/install/init-project.sh +435 -0
  6. package/install/install-global.sh +257 -0
  7. package/install/kb-first-autodetect.sh +108 -0
  8. package/install/kb-first-command.md +80 -0
  9. package/install/kb-first-skill.md +262 -0
  10. package/package.json +87 -0
  11. package/phases/00-assessment.md +529 -0
  12. package/phases/01-storage.md +194 -0
  13. package/phases/01.5-hooks-setup.md +521 -0
  14. package/phases/02-kb-creation.md +413 -0
  15. package/phases/03-persistence.md +125 -0
  16. package/phases/04-visualization.md +170 -0
  17. package/phases/05-integration.md +114 -0
  18. package/phases/06-scaffold.md +130 -0
  19. package/phases/07-build.md +493 -0
  20. package/phases/08-verification.md +597 -0
  21. package/phases/09-security.md +512 -0
  22. package/phases/10-documentation.md +613 -0
  23. package/phases/11-deployment.md +670 -0
  24. package/phases/testing.md +713 -0
  25. package/scripts/1.5-hooks-verify.sh +252 -0
  26. package/scripts/8.1-code-scan.sh +58 -0
  27. package/scripts/8.2-import-check.sh +42 -0
  28. package/scripts/8.3-source-returns.sh +52 -0
  29. package/scripts/8.4-startup-verify.sh +65 -0
  30. package/scripts/8.5-fallback-check.sh +63 -0
  31. package/scripts/8.6-attribution.sh +56 -0
  32. package/scripts/8.7-confidence.sh +56 -0
  33. package/scripts/8.8-gap-logging.sh +70 -0
  34. package/scripts/9-security-audit.sh +202 -0
  35. package/scripts/init-project.sh +395 -0
  36. package/scripts/verify-enforcement.sh +167 -0
  37. package/src/commands/hooks.js +361 -0
  38. package/src/commands/init.js +315 -0
  39. package/src/commands/phase.js +372 -0
  40. package/src/commands/score.js +380 -0
  41. package/src/commands/status.js +193 -0
  42. package/src/commands/verify.js +286 -0
  43. package/src/index.js +56 -0
  44. package/src/mcp-server.js +412 -0
  45. package/templates/attention-router.ts +534 -0
  46. package/templates/code-analysis.ts +683 -0
  47. package/templates/federated-kb-learner.ts +649 -0
  48. package/templates/gnn-engine.ts +1091 -0
  49. package/templates/intentions.md +277 -0
  50. package/templates/kb-client.ts +905 -0
  51. package/templates/schema.sql +303 -0
  52. package/templates/sona-config.ts +312 -0
@@ -0,0 +1,512 @@
1
+ # Phase 9: Security Audit & Hardening
2
+
3
+ Updated: 2026-01-02 00:15:00 EST | Version 1.0.0
4
+ Created: 2026-01-02 00:15:00 EST
5
+
6
+ ## Purpose
7
+
8
+ Ensure the application has no security vulnerabilities before production deployment. This phase performs comprehensive security scanning, fixes identified issues, and verifies hardening measures.
9
+
10
+ ---
11
+
12
+ ## Prerequisites
13
+
14
+ - Phase 8 complete (all verification checks pass)
15
+ - Application compiles and runs
16
+ - All tests passing
17
+
18
+ ---
19
+
20
+ ## Why Security Is Critical for KB-First Apps
21
+
22
+ KB-First applications handle sensitive data:
23
+ - **Expert knowledge** may be proprietary
24
+ - **User queries** may contain PII or business-sensitive information
25
+ - **Gap logs** capture what users are asking
26
+ - **SONA patterns** learn from user behavior
27
+
28
+ A security breach doesn't just expose data—it undermines trust in the expert knowledge system.
29
+
30
+ ---
31
+
32
+ ## Sub-Phases
33
+
34
+ | Sub-Phase | Name | Purpose |
35
+ |-----------|------|---------|
36
+ | 9.1 | Dependency Audit | Check for vulnerable packages |
37
+ | 9.2 | OWASP Top 10 Scan | Check for common vulnerabilities |
38
+ | 9.3 | SQL Injection Prevention | Verify parameterized queries |
39
+ | 9.4 | Authentication & Authorization | Verify access controls |
40
+ | 9.5 | Secrets Management | No hardcoded secrets |
41
+ | 9.6 | API Security | Rate limiting, CORS, input validation |
42
+
43
+ ---
44
+
45
+ ## 9.1 Dependency Audit
46
+
47
+ ### Check for Known Vulnerabilities
48
+
49
+ ```bash
50
+ # Node.js projects
51
+ npm audit
52
+ npm audit --audit-level=high
53
+
54
+ # Python projects
55
+ pip-audit
56
+ safety check
57
+
58
+ # Go projects
59
+ govulncheck ./...
60
+
61
+ # Rust projects
62
+ cargo audit
63
+ ```
64
+
65
+ ### Fix Vulnerabilities
66
+
67
+ ```bash
68
+ # Auto-fix where possible
69
+ npm audit fix
70
+
71
+ # For breaking changes
72
+ npm audit fix --force # Review changes carefully!
73
+
74
+ # Update specific packages
75
+ npm update <package-name>
76
+ ```
77
+
78
+ ### Quality Gate
79
+
80
+ | Severity | Threshold |
81
+ |----------|-----------|
82
+ | Critical | 0 allowed |
83
+ | High | 0 allowed |
84
+ | Medium | Must have remediation plan |
85
+ | Low | Document and monitor |
86
+
87
+ ---
88
+
89
+ ## 9.2 OWASP Top 10 Scan
90
+
91
+ Check for the [OWASP Top 10](https://owasp.org/Top10/) vulnerabilities:
92
+
93
+ ### Automated Scanning
94
+
95
+ ```bash
96
+ # Install OWASP ZAP (Zed Attack Proxy)
97
+ brew install zaproxy # macOS
98
+ # or
99
+ docker run -t owasp/zap2docker-stable zap-baseline.py -t http://localhost:3000
100
+
101
+ # Run baseline scan
102
+ zap-baseline.py -t http://localhost:3000 -r security-report.html
103
+ ```
104
+
105
+ ### Manual Checklist
106
+
107
+ | # | Vulnerability | Check | Status |
108
+ |---|---------------|-------|--------|
109
+ | A01 | Broken Access Control | Auth on all protected routes | [ ] |
110
+ | A02 | Cryptographic Failures | HTTPS, encrypted secrets | [ ] |
111
+ | A03 | Injection | Parameterized queries, input validation | [ ] |
112
+ | A04 | Insecure Design | Threat modeling completed | [ ] |
113
+ | A05 | Security Misconfiguration | Production configs reviewed | [ ] |
114
+ | A06 | Vulnerable Components | Dependency audit passed | [ ] |
115
+ | A07 | Auth Failures | Strong password policy, rate limiting | [ ] |
116
+ | A08 | Software/Data Integrity | Signed packages, CI/CD security | [ ] |
117
+ | A09 | Logging Failures | Security events logged | [ ] |
118
+ | A10 | SSRF | URL validation, allowlists | [ ] |
119
+
120
+ ---
121
+
122
+ ## 9.3 SQL Injection Prevention
123
+
124
+ KB-First apps use PostgreSQL extensively. Every query MUST be parameterized.
125
+
126
+ ### Scan for Raw SQL
127
+
128
+ ```bash
129
+ # Find potential SQL injection points
130
+ grep -rn "SELECT.*\+" src/
131
+ grep -rn "INSERT.*\+" src/
132
+ grep -rn "UPDATE.*\+" src/
133
+ grep -rn "DELETE.*\+" src/
134
+ grep -rn "\$\{.*\}.*FROM" src/
135
+ grep -rn "query\s*(" src/ | grep -v "parameterized"
136
+ ```
137
+
138
+ ### Correct Patterns
139
+
140
+ ```typescript
141
+ // ❌ VULNERABLE - String concatenation
142
+ const query = `SELECT * FROM kb_nodes WHERE title = '${userInput}'`;
143
+
144
+ // ❌ VULNERABLE - Template literal in query
145
+ const query = `SELECT * FROM kb_nodes WHERE id = ${id}`;
146
+
147
+ // ✅ SAFE - Parameterized query
148
+ const query = `SELECT * FROM kb_nodes WHERE title = $1`;
149
+ await pool.query(query, [userInput]);
150
+
151
+ // ✅ SAFE - Using query builder
152
+ const result = await knex('kb_nodes').where({ title: userInput });
153
+ ```
154
+
155
+ ### Verification Script
156
+
157
+ ```bash
158
+ #!/bin/bash
159
+ # scripts/9.3-sql-injection.sh
160
+
161
+ echo "=== 9.3 SQL Injection Prevention ==="
162
+
163
+ VIOLATIONS=0
164
+
165
+ # Check for string concatenation in SQL
166
+ while IFS= read -r file; do
167
+ if grep -qE "(SELECT|INSERT|UPDATE|DELETE).*\\\$\{" "$file" 2>/dev/null; then
168
+ echo "VIOLATION: Template literal in SQL in $file"
169
+ grep -n "(SELECT|INSERT|UPDATE|DELETE).*\\\$\{" "$file"
170
+ VIOLATIONS=$((VIOLATIONS + 1))
171
+ fi
172
+
173
+ if grep -qE "query\s*\(\s*\`" "$file" 2>/dev/null; then
174
+ echo "WARNING: Query with template literal in $file"
175
+ grep -n "query\s*\(\s*\`" "$file"
176
+ fi
177
+ done < <(find src -name "*.ts" -o -name "*.js")
178
+
179
+ if [ $VIOLATIONS -eq 0 ]; then
180
+ echo "PASS: No SQL injection vulnerabilities found"
181
+ exit 0
182
+ else
183
+ echo "FAIL: $VIOLATIONS SQL injection vulnerability(s) found"
184
+ exit 1
185
+ fi
186
+ ```
187
+
188
+ ---
189
+
190
+ ## 9.4 Authentication & Authorization
191
+
192
+ ### Authentication Checklist
193
+
194
+ | Check | Implementation | Status |
195
+ |-------|----------------|--------|
196
+ | Password hashing | bcrypt/argon2, cost factor ≥10 | [ ] |
197
+ | Session management | Secure cookies, httpOnly, sameSite | [ ] |
198
+ | Token expiration | Short-lived access tokens (≤1 hour) | [ ] |
199
+ | Refresh tokens | Rotation on use, secure storage | [ ] |
200
+ | MFA support | TOTP/WebAuthn available | [ ] |
201
+ | Account lockout | After 5 failed attempts | [ ] |
202
+
203
+ ### Authorization Checklist
204
+
205
+ | Check | Implementation | Status |
206
+ |-------|----------------|--------|
207
+ | Role-based access | Defined roles with permissions | [ ] |
208
+ | Resource-level auth | Users can only access their data | [ ] |
209
+ | Admin functions protected | Separate admin auth required | [ ] |
210
+ | KB namespace isolation | Users can only query their namespace | [ ] |
211
+ | API key scoping | Keys limited to specific operations | [ ] |
212
+
213
+ ### Verification Script
214
+
215
+ ```bash
216
+ #!/bin/bash
217
+ # scripts/9.4-auth-check.sh
218
+
219
+ echo "=== 9.4 Authentication & Authorization ==="
220
+
221
+ PASS=0
222
+ FAIL=0
223
+
224
+ # Check for password hashing library
225
+ if grep -rq "bcrypt\|argon2\|scrypt" package.json 2>/dev/null; then
226
+ echo "✅ Password hashing library found"
227
+ PASS=$((PASS + 1))
228
+ else
229
+ echo "❌ No password hashing library found"
230
+ FAIL=$((FAIL + 1))
231
+ fi
232
+
233
+ # Check for session security
234
+ if grep -rq "httpOnly.*true\|secure.*true" src/ 2>/dev/null; then
235
+ echo "✅ Secure cookie flags found"
236
+ PASS=$((PASS + 1))
237
+ else
238
+ echo "❌ Secure cookie flags not found"
239
+ FAIL=$((FAIL + 1))
240
+ fi
241
+
242
+ # Check for auth middleware
243
+ if grep -rq "requireAuth\|isAuthenticated\|authMiddleware" src/ 2>/dev/null; then
244
+ echo "✅ Authentication middleware found"
245
+ PASS=$((PASS + 1))
246
+ else
247
+ echo "❌ No authentication middleware found"
248
+ FAIL=$((FAIL + 1))
249
+ fi
250
+
251
+ echo ""
252
+ echo "Results: $PASS passed, $FAIL failed"
253
+ [ $FAIL -eq 0 ] && exit 0 || exit 1
254
+ ```
255
+
256
+ ---
257
+
258
+ ## 9.5 Secrets Management
259
+
260
+ ### Scan for Hardcoded Secrets
261
+
262
+ ```bash
263
+ # Install secret scanner
264
+ brew install gitleaks # or
265
+ pip install detect-secrets
266
+
267
+ # Scan codebase
268
+ gitleaks detect --source . --verbose
269
+
270
+ # Or with detect-secrets
271
+ detect-secrets scan > .secrets.baseline
272
+ ```
273
+
274
+ ### Common Secret Patterns to Check
275
+
276
+ ```bash
277
+ #!/bin/bash
278
+ # scripts/9.5-secrets-scan.sh
279
+
280
+ echo "=== 9.5 Secrets Management ==="
281
+
282
+ VIOLATIONS=0
283
+
284
+ # Patterns that suggest hardcoded secrets
285
+ PATTERNS=(
286
+ "password\s*=\s*['\"][^'\"]+['\"]"
287
+ "api_key\s*=\s*['\"][^'\"]+['\"]"
288
+ "secret\s*=\s*['\"][^'\"]+['\"]"
289
+ "token\s*=\s*['\"][^'\"]+['\"]"
290
+ "AWS_SECRET"
291
+ "ANTHROPIC_API_KEY\s*=\s*['\"]sk-"
292
+ "postgres://[^:]+:[^@]+@"
293
+ )
294
+
295
+ for pattern in "${PATTERNS[@]}"; do
296
+ matches=$(grep -rn "$pattern" src/ --include="*.ts" --include="*.js" 2>/dev/null | grep -v "process.env\|\.env\|example\|template" || true)
297
+ if [ -n "$matches" ]; then
298
+ echo "VIOLATION: Potential hardcoded secret"
299
+ echo "$matches"
300
+ VIOLATIONS=$((VIOLATIONS + 1))
301
+ fi
302
+ done
303
+
304
+ # Check that .env is in .gitignore
305
+ if grep -q "^\.env$" .gitignore 2>/dev/null; then
306
+ echo "✅ .env is in .gitignore"
307
+ else
308
+ echo "❌ .env is NOT in .gitignore"
309
+ VIOLATIONS=$((VIOLATIONS + 1))
310
+ fi
311
+
312
+ # Check for .env files in git
313
+ if git ls-files | grep -q "\.env$"; then
314
+ echo "❌ .env file is tracked in git!"
315
+ VIOLATIONS=$((VIOLATIONS + 1))
316
+ fi
317
+
318
+ echo ""
319
+ if [ $VIOLATIONS -eq 0 ]; then
320
+ echo "PASS: No hardcoded secrets found"
321
+ exit 0
322
+ else
323
+ echo "FAIL: $VIOLATIONS secret management issue(s) found"
324
+ exit 1
325
+ fi
326
+ ```
327
+
328
+ ### Required Secrets Management
329
+
330
+ | Secret Type | Storage Method |
331
+ |-------------|----------------|
332
+ | Database credentials | Environment variables |
333
+ | API keys | Environment variables or secrets manager |
334
+ | JWT secrets | Environment variables, rotated regularly |
335
+ | Encryption keys | HSM or secrets manager |
336
+
337
+ ---
338
+
339
+ ## 9.6 API Security
340
+
341
+ ### Rate Limiting
342
+
343
+ ```typescript
344
+ // Required for all public endpoints
345
+ import rateLimit from 'express-rate-limit';
346
+
347
+ const limiter = rateLimit({
348
+ windowMs: 15 * 60 * 1000, // 15 minutes
349
+ max: 100, // limit each IP to 100 requests per window
350
+ message: { error: 'Too many requests, please try again later.' }
351
+ });
352
+
353
+ app.use('/api/', limiter);
354
+ ```
355
+
356
+ ### CORS Configuration
357
+
358
+ ```typescript
359
+ // Restrict to known origins
360
+ const corsOptions = {
361
+ origin: process.env.ALLOWED_ORIGINS?.split(',') || ['https://yourdomain.com'],
362
+ methods: ['GET', 'POST', 'PUT', 'DELETE'],
363
+ allowedHeaders: ['Content-Type', 'Authorization'],
364
+ credentials: true,
365
+ maxAge: 86400 // 24 hours
366
+ };
367
+
368
+ app.use(cors(corsOptions));
369
+ ```
370
+
371
+ ### Input Validation
372
+
373
+ ```typescript
374
+ import { z } from 'zod';
375
+
376
+ // Define schemas for all API inputs
377
+ const SearchQuerySchema = z.object({
378
+ query: z.string().min(1).max(500),
379
+ namespace: z.string().optional(),
380
+ limit: z.number().int().min(1).max(100).default(10)
381
+ });
382
+
383
+ // Validate before processing
384
+ app.post('/api/search', async (req, res) => {
385
+ const result = SearchQuerySchema.safeParse(req.body);
386
+ if (!result.success) {
387
+ return res.status(400).json({ error: result.error.issues });
388
+ }
389
+ // Process validated input
390
+ const { query, namespace, limit } = result.data;
391
+ // ...
392
+ });
393
+ ```
394
+
395
+ ### Verification Script
396
+
397
+ ```bash
398
+ #!/bin/bash
399
+ # scripts/9.6-api-security.sh
400
+
401
+ echo "=== 9.6 API Security ==="
402
+
403
+ PASS=0
404
+ FAIL=0
405
+
406
+ # Check for rate limiting
407
+ if grep -rq "rateLimit\|rate-limit\|throttle" src/ package.json 2>/dev/null; then
408
+ echo "✅ Rate limiting found"
409
+ PASS=$((PASS + 1))
410
+ else
411
+ echo "❌ No rate limiting found"
412
+ FAIL=$((FAIL + 1))
413
+ fi
414
+
415
+ # Check for CORS
416
+ if grep -rq "cors\|Access-Control" src/ 2>/dev/null; then
417
+ echo "✅ CORS configuration found"
418
+ PASS=$((PASS + 1))
419
+ else
420
+ echo "❌ No CORS configuration found"
421
+ FAIL=$((FAIL + 1))
422
+ fi
423
+
424
+ # Check for input validation
425
+ if grep -rq "zod\|joi\|yup\|class-validator" package.json 2>/dev/null; then
426
+ echo "✅ Input validation library found"
427
+ PASS=$((PASS + 1))
428
+ else
429
+ echo "❌ No input validation library found"
430
+ FAIL=$((FAIL + 1))
431
+ fi
432
+
433
+ # Check for helmet (security headers)
434
+ if grep -rq "helmet" package.json src/ 2>/dev/null; then
435
+ echo "✅ Helmet (security headers) found"
436
+ PASS=$((PASS + 1))
437
+ else
438
+ echo "⚠️ Helmet not found - consider adding security headers"
439
+ fi
440
+
441
+ echo ""
442
+ echo "Results: $PASS passed, $FAIL failed"
443
+ [ $FAIL -eq 0 ] && exit 0 || exit 1
444
+ ```
445
+
446
+ ---
447
+
448
+ ## Security Report Template
449
+
450
+ After completing all sub-phases, generate a security report:
451
+
452
+ ```markdown
453
+ # Security Audit Report
454
+
455
+ **Application:** [App Name]
456
+ **Version:** [Version]
457
+ **Audit Date:** [Date]
458
+ **Auditor:** [Name/Tool]
459
+
460
+ ## Summary
461
+
462
+ | Category | Status | Issues |
463
+ |----------|--------|--------|
464
+ | Dependencies | ✅ PASS | 0 critical, 0 high |
465
+ | OWASP Top 10 | ✅ PASS | All checks passed |
466
+ | SQL Injection | ✅ PASS | 0 vulnerabilities |
467
+ | Authentication | ✅ PASS | All controls in place |
468
+ | Secrets | ✅ PASS | No hardcoded secrets |
469
+ | API Security | ✅ PASS | Rate limiting, CORS, validation |
470
+
471
+ ## Detailed Findings
472
+
473
+ ### [Finding 1]
474
+ - **Severity:** [Critical/High/Medium/Low]
475
+ - **Location:** [File:Line]
476
+ - **Description:** [What was found]
477
+ - **Remediation:** [How it was fixed]
478
+ - **Status:** [Fixed/Accepted/Mitigated]
479
+
480
+ ## Recommendations
481
+
482
+ 1. [Recommendation 1]
483
+ 2. [Recommendation 2]
484
+
485
+ ## Sign-off
486
+
487
+ - [ ] Security audit complete
488
+ - [ ] All critical/high issues resolved
489
+ - [ ] Report reviewed by security lead
490
+ ```
491
+
492
+ ---
493
+
494
+ ## Quality Gate Checklist
495
+
496
+ Before proceeding to Phase 10, verify:
497
+
498
+ - [ ] `npm audit` shows 0 critical/high vulnerabilities
499
+ - [ ] OWASP ZAP baseline scan passes
500
+ - [ ] No SQL injection vulnerabilities (9.3 script passes)
501
+ - [ ] Authentication & authorization verified (9.4 script passes)
502
+ - [ ] No hardcoded secrets (9.5 script passes)
503
+ - [ ] API security controls in place (9.6 script passes)
504
+ - [ ] Security report generated and reviewed
505
+
506
+ ---
507
+
508
+ ## Exit Criteria
509
+
510
+ All security checks pass. Security report generated and signed off.
511
+
512
+ **Proceed to Phase 10: Documentation & Versioning**