@claude-flow/cli 3.0.0-alpha.63 → 3.0.0-alpha.65
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/.claude/agents/v3/aidefence-guardian.md +282 -0
- package/.claude/agents/v3/injection-analyst.md +236 -0
- package/.claude/agents/v3/pii-detector.md +151 -0
- package/.claude/agents/v3/security-architect-aidefence.md +410 -0
- package/.claude/helpers/statusline-hook.sh +3 -3
- package/.claude/helpers/statusline.cjs +320 -0
- package/.claude/settings.json +2 -2
- package/.claude/skills/aidefence-scan.md +151 -0
- package/.claude/skills/aidefence.yaml +297 -0
- package/.claude/skills/secure-review.md +181 -0
- package/dist/src/commands/security.d.ts.map +1 -1
- package/dist/src/commands/security.js +142 -2
- package/dist/src/commands/security.js.map +1 -1
- package/dist/src/init/claudemd-generator.d.ts.map +1 -1
- package/dist/src/init/claudemd-generator.js +46 -6
- package/dist/src/init/claudemd-generator.js.map +1 -1
- package/dist/src/mcp-tools/index.d.ts +1 -0
- package/dist/src/mcp-tools/index.d.ts.map +1 -1
- package/dist/src/mcp-tools/index.js +1 -0
- package/dist/src/mcp-tools/index.js.map +1 -1
- package/dist/src/mcp-tools/security-tools.d.ts +18 -0
- package/dist/src/mcp-tools/security-tools.d.ts.map +1 -0
- package/dist/src/mcp-tools/security-tools.js +386 -0
- package/dist/src/mcp-tools/security-tools.js.map +1 -0
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/package.json +3 -2
|
@@ -0,0 +1,297 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: aidefence
|
|
3
|
+
version: 1.0.0
|
|
4
|
+
description: |
|
|
5
|
+
AI Manipulation Defense System (AIMDS) integration for Claude Flow V3.
|
|
6
|
+
Provides real-time threat detection, behavioral analysis, and adaptive
|
|
7
|
+
mitigation with 25-level meta-learning capabilities.
|
|
8
|
+
|
|
9
|
+
author: rUv
|
|
10
|
+
license: MIT
|
|
11
|
+
homepage: https://ruv.io/aimds
|
|
12
|
+
repository: https://github.com/ruvnet/midstream/tree/main/AIMDS
|
|
13
|
+
|
|
14
|
+
# Package reference
|
|
15
|
+
package: aidefence@^2.1.1
|
|
16
|
+
|
|
17
|
+
# Capabilities provided by this skill
|
|
18
|
+
capabilities:
|
|
19
|
+
# Detection capabilities
|
|
20
|
+
- prompt_injection_detection # 50+ prompt injection patterns
|
|
21
|
+
- jailbreak_detection # AI jailbreak attempt detection
|
|
22
|
+
- pii_detection # PII identification (emails, SSNs, API keys)
|
|
23
|
+
- unicode_normalization # Control character sanitization
|
|
24
|
+
|
|
25
|
+
# Analysis capabilities
|
|
26
|
+
- behavioral_analysis # Temporal pattern analysis
|
|
27
|
+
- chaos_detection # Lyapunov exponent calculation
|
|
28
|
+
- policy_verification # Linear Temporal Logic (LTL) policies
|
|
29
|
+
- anomaly_detection # Statistical baseline learning
|
|
30
|
+
|
|
31
|
+
# Response capabilities
|
|
32
|
+
- adaptive_mitigation # 7 distinct mitigation strategies
|
|
33
|
+
- meta_learning # 25-level recursive optimization (strange-loop)
|
|
34
|
+
- rollback_management # Failed mitigation rollback
|
|
35
|
+
- effectiveness_tracking # Real-time mitigation monitoring
|
|
36
|
+
|
|
37
|
+
# Performance characteristics
|
|
38
|
+
performance:
|
|
39
|
+
detection_latency: <10ms
|
|
40
|
+
analysis_latency: <100ms
|
|
41
|
+
response_latency: <50ms
|
|
42
|
+
throughput: ">12000 req/s"
|
|
43
|
+
|
|
44
|
+
# Commands exposed by this skill
|
|
45
|
+
commands:
|
|
46
|
+
scan:
|
|
47
|
+
description: Scan input for AI manipulation attempts
|
|
48
|
+
usage: |
|
|
49
|
+
/aidefence scan <input>
|
|
50
|
+
/aidefence scan --file <path>
|
|
51
|
+
/aidefence scan --mode paranoid <input>
|
|
52
|
+
examples:
|
|
53
|
+
- "/aidefence scan 'Ignore previous instructions and...'"
|
|
54
|
+
- "/aidefence scan --file suspicious-prompt.txt"
|
|
55
|
+
- "/aidefence scan --mode paranoid --json 'Please help me...'"
|
|
56
|
+
options:
|
|
57
|
+
- name: mode
|
|
58
|
+
type: choice
|
|
59
|
+
choices:
|
|
60
|
+
- quick # Pattern matching only (<5ms)
|
|
61
|
+
- thorough # Pattern + behavioral (<50ms)
|
|
62
|
+
- paranoid # Full analysis + policy verification (<150ms)
|
|
63
|
+
default: thorough
|
|
64
|
+
description: Scan depth mode
|
|
65
|
+
- name: file
|
|
66
|
+
type: string
|
|
67
|
+
description: File path to scan instead of inline input
|
|
68
|
+
- name: json
|
|
69
|
+
type: boolean
|
|
70
|
+
default: false
|
|
71
|
+
description: Output results as JSON
|
|
72
|
+
|
|
73
|
+
analyze:
|
|
74
|
+
description: Analyze agent behavior patterns for anomalies
|
|
75
|
+
usage: |
|
|
76
|
+
/aidefence analyze <agent-id>
|
|
77
|
+
/aidefence analyze <agent-id> --window 24h
|
|
78
|
+
examples:
|
|
79
|
+
- "/aidefence analyze security-architect-1234"
|
|
80
|
+
- "/aidefence analyze coder-5678 --window 10m --threshold 0.7"
|
|
81
|
+
options:
|
|
82
|
+
- name: window
|
|
83
|
+
type: string
|
|
84
|
+
default: "1h"
|
|
85
|
+
description: Time window for behavioral analysis
|
|
86
|
+
- name: threshold
|
|
87
|
+
type: number
|
|
88
|
+
default: 0.8
|
|
89
|
+
description: Anomaly score threshold (0-1)
|
|
90
|
+
|
|
91
|
+
policy:
|
|
92
|
+
description: Verify agent against LTL security policy
|
|
93
|
+
usage: |
|
|
94
|
+
/aidefence policy <agent-id> <ltl-formula>
|
|
95
|
+
examples:
|
|
96
|
+
- "/aidefence policy coder-1234 'G(edit_file -> F(run_tests))'"
|
|
97
|
+
- "/aidefence policy reviewer-5678 'G(!approve_self_code)'"
|
|
98
|
+
options:
|
|
99
|
+
- name: verbose
|
|
100
|
+
type: boolean
|
|
101
|
+
default: false
|
|
102
|
+
description: Show detailed policy evaluation trace
|
|
103
|
+
|
|
104
|
+
learn:
|
|
105
|
+
description: Record successful mitigation for meta-learning
|
|
106
|
+
usage: |
|
|
107
|
+
/aidefence learn <threat-type> <strategy> --effectiveness <score>
|
|
108
|
+
examples:
|
|
109
|
+
- "/aidefence learn prompt_injection sanitize --effectiveness 0.95"
|
|
110
|
+
- "/aidefence learn jailbreak reject --effectiveness 1.0"
|
|
111
|
+
options:
|
|
112
|
+
- name: effectiveness
|
|
113
|
+
type: number
|
|
114
|
+
required: true
|
|
115
|
+
description: Mitigation effectiveness score (0-1)
|
|
116
|
+
|
|
117
|
+
status:
|
|
118
|
+
description: Show aidefence system status and metrics
|
|
119
|
+
usage: |
|
|
120
|
+
/aidefence status
|
|
121
|
+
/aidefence status --metrics
|
|
122
|
+
options:
|
|
123
|
+
- name: metrics
|
|
124
|
+
type: boolean
|
|
125
|
+
default: false
|
|
126
|
+
description: Include Prometheus metrics
|
|
127
|
+
|
|
128
|
+
# Hook integrations
|
|
129
|
+
hooks:
|
|
130
|
+
# Pre-agent-input: Scan all agent inputs for manipulation
|
|
131
|
+
pre-agent-input:
|
|
132
|
+
enabled: true
|
|
133
|
+
description: Scan agent inputs before processing
|
|
134
|
+
config:
|
|
135
|
+
block_critical: true # Block inputs with critical threats
|
|
136
|
+
block_high: false # Allow high severity with logging
|
|
137
|
+
log_all: true # Log all threat detections
|
|
138
|
+
mode: thorough # Default scan mode
|
|
139
|
+
|
|
140
|
+
# Post-agent-action: Learn from agent behaviors
|
|
141
|
+
post-agent-action:
|
|
142
|
+
enabled: true
|
|
143
|
+
description: Record agent actions for behavioral modeling
|
|
144
|
+
config:
|
|
145
|
+
sampling_rate: 0.1 # Sample 10% of actions for analysis
|
|
146
|
+
anomaly_threshold: 0.8 # Alert threshold for anomaly score
|
|
147
|
+
store_embeddings: true # Store action embeddings in AgentDB
|
|
148
|
+
|
|
149
|
+
# Pre-swarm-init: Verify swarm security policies
|
|
150
|
+
pre-swarm-init:
|
|
151
|
+
enabled: true
|
|
152
|
+
description: Verify swarm topology against security policies
|
|
153
|
+
config:
|
|
154
|
+
require_security_agent: true # Require security-architect in swarm
|
|
155
|
+
validate_topology: true # Validate topology security
|
|
156
|
+
|
|
157
|
+
# Integration with claude-flow systems
|
|
158
|
+
integration:
|
|
159
|
+
# AgentDB integration for shared threat patterns
|
|
160
|
+
agentdb:
|
|
161
|
+
enabled: true
|
|
162
|
+
namespace: security_threats
|
|
163
|
+
hnsw_enabled: true
|
|
164
|
+
config:
|
|
165
|
+
vector_dimension: 384
|
|
166
|
+
m: 16
|
|
167
|
+
ef_construction: 200
|
|
168
|
+
ef_search: 100
|
|
169
|
+
|
|
170
|
+
# ReasoningBank integration for pattern learning
|
|
171
|
+
reasoningbank:
|
|
172
|
+
enabled: true
|
|
173
|
+
store_patterns: true
|
|
174
|
+
learn_mitigations: true
|
|
175
|
+
config:
|
|
176
|
+
min_effectiveness: 0.8 # Only store high-effectiveness patterns
|
|
177
|
+
consolidation_interval: 1h
|
|
178
|
+
|
|
179
|
+
# Prometheus metrics
|
|
180
|
+
prometheus:
|
|
181
|
+
enabled: true
|
|
182
|
+
metrics:
|
|
183
|
+
- aidefence_threats_detected_total
|
|
184
|
+
- aidefence_detection_latency_ms
|
|
185
|
+
- aidefence_analysis_latency_ms
|
|
186
|
+
- aidefence_anomaly_score
|
|
187
|
+
- aidefence_mitigations_applied_total
|
|
188
|
+
- aidefence_meta_learning_depth
|
|
189
|
+
|
|
190
|
+
# MCP tool registrations
|
|
191
|
+
mcp_tools:
|
|
192
|
+
- name: aidefence_scan
|
|
193
|
+
description: Scan input for AI manipulation attempts
|
|
194
|
+
input_schema:
|
|
195
|
+
type: object
|
|
196
|
+
properties:
|
|
197
|
+
input:
|
|
198
|
+
type: string
|
|
199
|
+
description: Input text to scan
|
|
200
|
+
mode:
|
|
201
|
+
type: string
|
|
202
|
+
enum: [quick, thorough, paranoid]
|
|
203
|
+
default: thorough
|
|
204
|
+
required: [input]
|
|
205
|
+
|
|
206
|
+
- name: aidefence_analyze_behavior
|
|
207
|
+
description: Analyze agent behavioral patterns for anomalies
|
|
208
|
+
input_schema:
|
|
209
|
+
type: object
|
|
210
|
+
properties:
|
|
211
|
+
agentId:
|
|
212
|
+
type: string
|
|
213
|
+
description: Agent ID to analyze
|
|
214
|
+
timeWindow:
|
|
215
|
+
type: string
|
|
216
|
+
default: "1h"
|
|
217
|
+
description: Time window for analysis
|
|
218
|
+
required: [agentId]
|
|
219
|
+
|
|
220
|
+
- name: aidefence_verify_policy
|
|
221
|
+
description: Verify agent behavior against LTL security policies
|
|
222
|
+
input_schema:
|
|
223
|
+
type: object
|
|
224
|
+
properties:
|
|
225
|
+
agentId:
|
|
226
|
+
type: string
|
|
227
|
+
policy:
|
|
228
|
+
type: string
|
|
229
|
+
description: LTL policy formula
|
|
230
|
+
required: [agentId, policy]
|
|
231
|
+
|
|
232
|
+
- name: aidefence_learn_pattern
|
|
233
|
+
description: Store successful threat pattern for meta-learning
|
|
234
|
+
input_schema:
|
|
235
|
+
type: object
|
|
236
|
+
properties:
|
|
237
|
+
threatType:
|
|
238
|
+
type: string
|
|
239
|
+
mitigation:
|
|
240
|
+
type: string
|
|
241
|
+
effectiveness:
|
|
242
|
+
type: number
|
|
243
|
+
minimum: 0
|
|
244
|
+
maximum: 1
|
|
245
|
+
required: [threatType, mitigation, effectiveness]
|
|
246
|
+
|
|
247
|
+
# Threat detection patterns (reference)
|
|
248
|
+
threat_patterns:
|
|
249
|
+
prompt_injection:
|
|
250
|
+
count: 50+
|
|
251
|
+
categories:
|
|
252
|
+
- instruction_override # "Ignore previous instructions"
|
|
253
|
+
- role_switching # "You are now DAN"
|
|
254
|
+
- context_manipulation # Fake system messages
|
|
255
|
+
- delimiter_abuse # Using special tokens
|
|
256
|
+
|
|
257
|
+
jailbreak:
|
|
258
|
+
categories:
|
|
259
|
+
- dan_variants # Do Anything Now variants
|
|
260
|
+
- hypothetical # "Hypothetically, if..."
|
|
261
|
+
- roleplay # Character-based bypasses
|
|
262
|
+
- encoding # Base64/ROT13 encoded prompts
|
|
263
|
+
|
|
264
|
+
pii:
|
|
265
|
+
types:
|
|
266
|
+
- email_addresses
|
|
267
|
+
- social_security_numbers
|
|
268
|
+
- credit_card_numbers
|
|
269
|
+
- api_keys
|
|
270
|
+
- passwords
|
|
271
|
+
|
|
272
|
+
# Behavioral analysis configuration
|
|
273
|
+
behavioral_analysis:
|
|
274
|
+
temporal:
|
|
275
|
+
window_sizes: [1m, 10m, 1h, 24h]
|
|
276
|
+
attractor_types:
|
|
277
|
+
- point # Stable single point
|
|
278
|
+
- cycle # Periodic behavior
|
|
279
|
+
- torus # Quasi-periodic
|
|
280
|
+
- strange # Chaotic (suspicious)
|
|
281
|
+
|
|
282
|
+
lyapunov:
|
|
283
|
+
threshold: 0.1 # Positive = chaotic behavior
|
|
284
|
+
embedding_dimension: 3
|
|
285
|
+
time_delay: 1
|
|
286
|
+
|
|
287
|
+
baseline:
|
|
288
|
+
learning_period: 24h
|
|
289
|
+
update_frequency: 1h
|
|
290
|
+
deviation_threshold: 3.0 # Standard deviations
|
|
291
|
+
|
|
292
|
+
# Documentation links
|
|
293
|
+
documentation:
|
|
294
|
+
readme: https://github.com/ruvnet/midstream/blob/main/AIMDS/README.md
|
|
295
|
+
api: https://ruv.io/aimds/api
|
|
296
|
+
patterns: https://ruv.io/aimds/patterns
|
|
297
|
+
integration: /v3/implementation/adrs/ADR-022-aidefence-integration.md
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: secure-review
|
|
3
|
+
version: 1.0.0
|
|
4
|
+
description: Security-focused code review with AI manipulation detection
|
|
5
|
+
author: rUv
|
|
6
|
+
tags: [security, code-review, aidefence]
|
|
7
|
+
|
|
8
|
+
invocation:
|
|
9
|
+
- /secure-review
|
|
10
|
+
- /security-review
|
|
11
|
+
|
|
12
|
+
requires:
|
|
13
|
+
- "@claude-flow/aidefence"
|
|
14
|
+
---
|
|
15
|
+
|
|
16
|
+
# Secure Review Skill
|
|
17
|
+
|
|
18
|
+
Perform security-focused code reviews that include AI manipulation detection, credential scanning, and security best practice validation.
|
|
19
|
+
|
|
20
|
+
## Commands
|
|
21
|
+
|
|
22
|
+
### `/secure-review <file-or-directory>`
|
|
23
|
+
Review code for security issues including:
|
|
24
|
+
- Hardcoded credentials
|
|
25
|
+
- Prompt injection vulnerabilities
|
|
26
|
+
- Unsafe input handling
|
|
27
|
+
- Security anti-patterns
|
|
28
|
+
|
|
29
|
+
### `/secure-review --quick <file>`
|
|
30
|
+
Quick security scan without detailed analysis.
|
|
31
|
+
|
|
32
|
+
### `/secure-review --fix <file>`
|
|
33
|
+
Review and suggest fixes for security issues.
|
|
34
|
+
|
|
35
|
+
---
|
|
36
|
+
|
|
37
|
+
## Execution Instructions
|
|
38
|
+
|
|
39
|
+
When `/secure-review` is invoked:
|
|
40
|
+
|
|
41
|
+
### Step 1: Initialize Security Tools
|
|
42
|
+
|
|
43
|
+
```typescript
|
|
44
|
+
import { createAIDefence } from '@claude-flow/aidefence';
|
|
45
|
+
|
|
46
|
+
const aidefence = createAIDefence({ enableLearning: true });
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
### Step 2: Read and Analyze Files
|
|
50
|
+
|
|
51
|
+
For each file to review:
|
|
52
|
+
|
|
53
|
+
1. **Read the file** using the Read tool
|
|
54
|
+
2. **Scan for PII/Credentials**:
|
|
55
|
+
```typescript
|
|
56
|
+
const piiResult = aidefence.hasPII(fileContent);
|
|
57
|
+
if (piiResult) {
|
|
58
|
+
findings.push({
|
|
59
|
+
type: 'pii',
|
|
60
|
+
severity: 'high',
|
|
61
|
+
message: 'Potential credentials or PII detected',
|
|
62
|
+
file: filePath
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
3. **Check for dangerous patterns**:
|
|
68
|
+
```typescript
|
|
69
|
+
const dangerousPatterns = [
|
|
70
|
+
{ pattern: /eval\s*\(/, message: 'Unsafe eval() usage', severity: 'critical' },
|
|
71
|
+
{ pattern: /innerHTML\s*=/, message: 'Potential XSS via innerHTML', severity: 'high' },
|
|
72
|
+
{ pattern: /shell:\s*true/, message: 'Shell injection risk', severity: 'critical' },
|
|
73
|
+
{ pattern: /dangerouslySetInnerHTML/, message: 'Dangerous HTML injection', severity: 'high' },
|
|
74
|
+
{ pattern: /password.*=.*['"][^'"]+['"]/, message: 'Hardcoded password', severity: 'critical' },
|
|
75
|
+
];
|
|
76
|
+
|
|
77
|
+
for (const { pattern, message, severity } of dangerousPatterns) {
|
|
78
|
+
const match = fileContent.match(pattern);
|
|
79
|
+
if (match) {
|
|
80
|
+
findings.push({ type: 'security', severity, message, file: filePath, line: getLineNumber(match) });
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
4. **Scan for prompt injection in AI code**:
|
|
86
|
+
```typescript
|
|
87
|
+
// If file contains AI/LLM related code
|
|
88
|
+
if (/openai|anthropic|llm|prompt|chat/i.test(fileContent)) {
|
|
89
|
+
// Check for unsafe prompt construction
|
|
90
|
+
const unsafePromptPatterns = [
|
|
91
|
+
/\$\{.*user.*\}/i, // Template literal with user input
|
|
92
|
+
/\+ .*input/i, // String concatenation with input
|
|
93
|
+
/prompt.*=.*request/i, // Direct request to prompt
|
|
94
|
+
];
|
|
95
|
+
|
|
96
|
+
for (const pattern of unsafePromptPatterns) {
|
|
97
|
+
if (pattern.test(fileContent)) {
|
|
98
|
+
findings.push({
|
|
99
|
+
type: 'prompt_injection_risk',
|
|
100
|
+
severity: 'high',
|
|
101
|
+
message: 'Potential prompt injection vulnerability - user input directly in prompt',
|
|
102
|
+
file: filePath
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
### Step 3: Generate Report
|
|
110
|
+
|
|
111
|
+
```markdown
|
|
112
|
+
## Security Review Report
|
|
113
|
+
|
|
114
|
+
### Summary
|
|
115
|
+
- Files reviewed: X
|
|
116
|
+
- Critical issues: X
|
|
117
|
+
- High severity: X
|
|
118
|
+
- Medium severity: X
|
|
119
|
+
- Low severity: X
|
|
120
|
+
|
|
121
|
+
### Findings
|
|
122
|
+
|
|
123
|
+
#### Critical
|
|
124
|
+
1. **[file.ts:42]** Hardcoded API key detected
|
|
125
|
+
- **Risk**: Credential exposure
|
|
126
|
+
- **Fix**: Move to environment variable
|
|
127
|
+
|
|
128
|
+
#### High
|
|
129
|
+
1. **[api.ts:108]** User input directly concatenated to prompt
|
|
130
|
+
- **Risk**: Prompt injection vulnerability
|
|
131
|
+
- **Fix**: Sanitize and validate user input before including in prompts
|
|
132
|
+
|
|
133
|
+
### Recommendations
|
|
134
|
+
1. Enable input validation at all API boundaries
|
|
135
|
+
2. Use environment variables for all credentials
|
|
136
|
+
3. Implement prompt injection defenses for AI code
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
### Step 4: Learn from Review
|
|
140
|
+
|
|
141
|
+
```typescript
|
|
142
|
+
// Store review patterns for learning
|
|
143
|
+
for (const finding of findings) {
|
|
144
|
+
await aidefence.learnFromDetection(
|
|
145
|
+
finding.context,
|
|
146
|
+
{ safe: false, threats: [{ type: finding.type, severity: finding.severity }] }
|
|
147
|
+
);
|
|
148
|
+
}
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
## Example Output
|
|
152
|
+
|
|
153
|
+
```
|
|
154
|
+
🔍 Security Review: src/api/
|
|
155
|
+
|
|
156
|
+
Scanning 12 files...
|
|
157
|
+
|
|
158
|
+
❌ CRITICAL: src/api/config.ts:15
|
|
159
|
+
Hardcoded API key: sk-ant-api03...
|
|
160
|
+
→ Move to .env file and use process.env.ANTHROPIC_API_KEY
|
|
161
|
+
|
|
162
|
+
⚠️ HIGH: src/api/chat.ts:42
|
|
163
|
+
User input directly in prompt template
|
|
164
|
+
→ Sanitize input: const sanitized = sanitizeForPrompt(userInput)
|
|
165
|
+
|
|
166
|
+
⚠️ HIGH: src/api/chat.ts:67
|
|
167
|
+
No input length validation
|
|
168
|
+
→ Add: if (input.length > MAX_INPUT_LENGTH) throw new Error('...')
|
|
169
|
+
|
|
170
|
+
ℹ️ MEDIUM: src/api/utils.ts:23
|
|
171
|
+
Using eval() for JSON parsing
|
|
172
|
+
→ Use JSON.parse() instead
|
|
173
|
+
|
|
174
|
+
📊 Summary: 1 critical, 2 high, 1 medium issues found
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+
## Integration Notes
|
|
178
|
+
|
|
179
|
+
- Works with `reviewer` agent for comprehensive code reviews
|
|
180
|
+
- Findings are stored in memory for pattern learning
|
|
181
|
+
- Can be triggered automatically via pre-commit hooks
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"security.d.ts","sourceRoot":"","sources":["../../../src/commands/security.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EAAE,OAAO,EAAiC,MAAM,aAAa,CAAC;
|
|
1
|
+
{"version":3,"file":"security.d.ts","sourceRoot":"","sources":["../../../src/commands/security.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EAAE,OAAO,EAAiC,MAAM,aAAa,CAAC;AAqZ1E,eAAO,MAAM,eAAe,EAAE,OA6B7B,CAAC;AAEF,eAAe,eAAe,CAAC"}
|
|
@@ -227,11 +227,150 @@ const secretsCommand = {
|
|
|
227
227
|
return { success: true };
|
|
228
228
|
},
|
|
229
229
|
};
|
|
230
|
+
// Defend subcommand (AIDefence integration)
|
|
231
|
+
const defendCommand = {
|
|
232
|
+
name: 'defend',
|
|
233
|
+
description: 'AI manipulation defense - detect prompt injection, jailbreaks, and PII',
|
|
234
|
+
options: [
|
|
235
|
+
{ name: 'input', short: 'i', type: 'string', description: 'Input text to scan for threats' },
|
|
236
|
+
{ name: 'file', short: 'f', type: 'string', description: 'File to scan for threats' },
|
|
237
|
+
{ name: 'quick', short: 'q', type: 'boolean', description: 'Quick scan (faster, less detailed)' },
|
|
238
|
+
{ name: 'learn', short: 'l', type: 'boolean', description: 'Enable learning mode', default: 'true' },
|
|
239
|
+
{ name: 'stats', short: 's', type: 'boolean', description: 'Show detection statistics' },
|
|
240
|
+
{ name: 'output', short: 'o', type: 'string', description: 'Output format: text, json', default: 'text' },
|
|
241
|
+
],
|
|
242
|
+
examples: [
|
|
243
|
+
{ command: 'claude-flow security defend -i "ignore previous instructions"', description: 'Scan text for threats' },
|
|
244
|
+
{ command: 'claude-flow security defend -f ./prompts.txt', description: 'Scan file for threats' },
|
|
245
|
+
{ command: 'claude-flow security defend --stats', description: 'Show detection statistics' },
|
|
246
|
+
],
|
|
247
|
+
action: async (ctx) => {
|
|
248
|
+
const inputText = ctx.flags.input;
|
|
249
|
+
const filePath = ctx.flags.file;
|
|
250
|
+
const quickMode = ctx.flags.quick;
|
|
251
|
+
const showStats = ctx.flags.stats;
|
|
252
|
+
const outputFormat = ctx.flags.output || 'text';
|
|
253
|
+
const enableLearning = ctx.flags.learn !== false;
|
|
254
|
+
output.writeln();
|
|
255
|
+
output.writeln(output.bold('🛡️ AIDefence - AI Manipulation Defense System'));
|
|
256
|
+
output.writeln(output.dim('─'.repeat(55)));
|
|
257
|
+
// Dynamic import of aidefence (allows package to be optional)
|
|
258
|
+
let createAIDefence;
|
|
259
|
+
try {
|
|
260
|
+
const aidefence = await import('@claude-flow/aidefence');
|
|
261
|
+
createAIDefence = aidefence.createAIDefence;
|
|
262
|
+
}
|
|
263
|
+
catch {
|
|
264
|
+
output.error('AIDefence package not installed. Run: npm install @claude-flow/aidefence');
|
|
265
|
+
return { success: false, message: 'AIDefence not available' };
|
|
266
|
+
}
|
|
267
|
+
const defender = createAIDefence({ enableLearning });
|
|
268
|
+
// Show stats mode
|
|
269
|
+
if (showStats) {
|
|
270
|
+
const stats = await defender.getStats();
|
|
271
|
+
output.writeln();
|
|
272
|
+
output.printBox([
|
|
273
|
+
`Detection Count: ${stats.detectionCount}`,
|
|
274
|
+
`Avg Detection Time: ${stats.avgDetectionTimeMs.toFixed(3)}ms`,
|
|
275
|
+
`Learned Patterns: ${stats.learnedPatterns}`,
|
|
276
|
+
`Mitigation Strategies: ${stats.mitigationStrategies}`,
|
|
277
|
+
`Avg Mitigation Effectiveness: ${(stats.avgMitigationEffectiveness * 100).toFixed(1)}%`,
|
|
278
|
+
].join('\n'), 'Detection Statistics');
|
|
279
|
+
return { success: true };
|
|
280
|
+
}
|
|
281
|
+
// Get input to scan
|
|
282
|
+
let textToScan = inputText;
|
|
283
|
+
if (filePath) {
|
|
284
|
+
try {
|
|
285
|
+
const fs = await import('fs/promises');
|
|
286
|
+
textToScan = await fs.readFile(filePath, 'utf-8');
|
|
287
|
+
output.writeln(output.dim(`Reading file: ${filePath}`));
|
|
288
|
+
}
|
|
289
|
+
catch (err) {
|
|
290
|
+
output.error(`Failed to read file: ${filePath}`);
|
|
291
|
+
return { success: false, message: 'File not found' };
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
if (!textToScan) {
|
|
295
|
+
output.writeln('Usage: claude-flow security defend -i "<text>" or -f <file>');
|
|
296
|
+
output.writeln();
|
|
297
|
+
output.writeln('Options:');
|
|
298
|
+
output.printList([
|
|
299
|
+
'-i, --input Text to scan for AI manipulation attempts',
|
|
300
|
+
'-f, --file File path to scan',
|
|
301
|
+
'-q, --quick Quick scan mode (faster)',
|
|
302
|
+
'-s, --stats Show detection statistics',
|
|
303
|
+
'--learn Enable pattern learning (default: true)',
|
|
304
|
+
]);
|
|
305
|
+
return { success: true };
|
|
306
|
+
}
|
|
307
|
+
const spinner = output.createSpinner({ text: 'Scanning for threats...', spinner: 'dots' });
|
|
308
|
+
spinner.start();
|
|
309
|
+
// Perform scan
|
|
310
|
+
const startTime = performance.now();
|
|
311
|
+
const result = quickMode
|
|
312
|
+
? { ...defender.quickScan(textToScan), threats: [], piiFound: false, detectionTimeMs: 0, inputHash: '', safe: !defender.quickScan(textToScan).threat }
|
|
313
|
+
: await defender.detect(textToScan);
|
|
314
|
+
const scanTime = performance.now() - startTime;
|
|
315
|
+
spinner.stop();
|
|
316
|
+
// JSON output
|
|
317
|
+
if (outputFormat === 'json') {
|
|
318
|
+
output.writeln(JSON.stringify({
|
|
319
|
+
safe: result.safe,
|
|
320
|
+
threats: result.threats || [],
|
|
321
|
+
piiFound: result.piiFound,
|
|
322
|
+
detectionTimeMs: scanTime,
|
|
323
|
+
}, null, 2));
|
|
324
|
+
return { success: true };
|
|
325
|
+
}
|
|
326
|
+
// Text output
|
|
327
|
+
output.writeln();
|
|
328
|
+
if (result.safe && !result.piiFound) {
|
|
329
|
+
output.writeln(output.success('✅ No threats detected'));
|
|
330
|
+
}
|
|
331
|
+
else {
|
|
332
|
+
if (!result.safe && result.threats) {
|
|
333
|
+
output.writeln(output.error(`⚠️ ${result.threats.length} threat(s) detected:`));
|
|
334
|
+
output.writeln();
|
|
335
|
+
for (const threat of result.threats) {
|
|
336
|
+
const severityColor = {
|
|
337
|
+
critical: output.error,
|
|
338
|
+
high: output.warning,
|
|
339
|
+
medium: output.info,
|
|
340
|
+
low: output.dim,
|
|
341
|
+
}[threat.severity] || output.dim;
|
|
342
|
+
output.writeln(` ${severityColor(`[${threat.severity.toUpperCase()}]`)} ${threat.type}`);
|
|
343
|
+
output.writeln(` ${output.dim(threat.description)}`);
|
|
344
|
+
output.writeln(` Confidence: ${(threat.confidence * 100).toFixed(1)}%`);
|
|
345
|
+
output.writeln();
|
|
346
|
+
}
|
|
347
|
+
// Show mitigation recommendations
|
|
348
|
+
const criticalThreats = result.threats.filter(t => t.severity === 'critical');
|
|
349
|
+
if (criticalThreats.length > 0 && enableLearning) {
|
|
350
|
+
output.writeln(output.bold('Recommended Mitigations:'));
|
|
351
|
+
for (const threat of criticalThreats) {
|
|
352
|
+
const mitigation = await defender.getBestMitigation(threat.type);
|
|
353
|
+
if (mitigation) {
|
|
354
|
+
output.writeln(` ${threat.type}: ${output.bold(mitigation.strategy)} (${(mitigation.effectiveness * 100).toFixed(0)}% effective)`);
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
output.writeln();
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
if (result.piiFound) {
|
|
361
|
+
output.writeln(output.warning('⚠️ PII detected (emails, SSNs, API keys, etc.)'));
|
|
362
|
+
output.writeln();
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
output.writeln(output.dim(`Detection time: ${scanTime.toFixed(3)}ms`));
|
|
366
|
+
return { success: result.safe };
|
|
367
|
+
},
|
|
368
|
+
};
|
|
230
369
|
// Main security command
|
|
231
370
|
export const securityCommand = {
|
|
232
371
|
name: 'security',
|
|
233
|
-
description: 'Security scanning, CVE detection, threat modeling,
|
|
234
|
-
subcommands: [scanCommand, cveCommand, threatsCommand, auditCommand, secretsCommand],
|
|
372
|
+
description: 'Security scanning, CVE detection, threat modeling, AI defense',
|
|
373
|
+
subcommands: [scanCommand, cveCommand, threatsCommand, auditCommand, secretsCommand, defendCommand],
|
|
235
374
|
examples: [
|
|
236
375
|
{ command: 'claude-flow security scan', description: 'Run security scan' },
|
|
237
376
|
{ command: 'claude-flow security cve --list', description: 'List known CVEs' },
|
|
@@ -249,6 +388,7 @@ export const securityCommand = {
|
|
|
249
388
|
'threats - Threat modeling (STRIDE, DREAD, PASTA)',
|
|
250
389
|
'audit - Security audit logging and compliance',
|
|
251
390
|
'secrets - Detect and manage secrets in codebase',
|
|
391
|
+
'defend - AI manipulation defense (prompt injection, jailbreaks, PII)',
|
|
252
392
|
]);
|
|
253
393
|
output.writeln();
|
|
254
394
|
output.writeln('Use --help with subcommands for more info');
|