@claude-flow/security 3.0.0-alpha.1 → 3.0.0-alpha.11

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 (150) hide show
  1. package/README.md +292 -234
  2. package/__tests__/acceptance/security-compliance.test.ts +674 -674
  3. package/__tests__/authorization-propagator.test.ts +155 -0
  4. package/__tests__/credential-generator.test.ts +310 -310
  5. package/__tests__/fixtures/configurations.ts +425 -419
  6. package/__tests__/fixtures/index.ts +21 -21
  7. package/__tests__/helpers/create-mock.ts +469 -469
  8. package/__tests__/helpers/index.ts +32 -32
  9. package/__tests__/input-validator.test.ts +382 -381
  10. package/__tests__/integration/security-flow.test.ts +606 -606
  11. package/__tests__/keychain-adapter.test.ts +60 -0
  12. package/__tests__/oauth-browser.test.ts +13 -0
  13. package/__tests__/oauth-export-surface.test.ts +21 -0
  14. package/__tests__/oauth-pkce.test.ts +37 -0
  15. package/__tests__/password-hasher.test.ts +239 -239
  16. package/__tests__/path-validator.test.ts +302 -302
  17. package/__tests__/plugin-integrity-verifier.test.ts +199 -0
  18. package/__tests__/safe-executor.test.ts +292 -292
  19. package/__tests__/token-generator.test.ts +371 -371
  20. package/__tests__/tool-output-guardrail.test.ts +256 -0
  21. package/__tests__/unit/credential-generator.test.ts +182 -182
  22. package/__tests__/unit/password-hasher.test.ts +359 -359
  23. package/__tests__/unit/path-validator.test.ts +509 -509
  24. package/__tests__/unit/safe-executor.test.ts +667 -667
  25. package/__tests__/unit/token-generator.test.ts +310 -310
  26. package/dist/CVE-REMEDIATION.d.ts +17 -6
  27. package/dist/CVE-REMEDIATION.d.ts.map +1 -1
  28. package/dist/CVE-REMEDIATION.js +328 -12
  29. package/dist/CVE-REMEDIATION.js.map +1 -1
  30. package/dist/authorization/propagator.d.ts +148 -0
  31. package/dist/authorization/propagator.d.ts.map +1 -0
  32. package/dist/authorization/propagator.js +182 -0
  33. package/dist/authorization/propagator.js.map +1 -0
  34. package/dist/credential-generator.js +9 -9
  35. package/dist/domain/services/security-domain-service.js +1 -1
  36. package/dist/domain/services/security-domain-service.js.map +1 -1
  37. package/dist/index.d.ts +9 -1
  38. package/dist/index.d.ts.map +1 -1
  39. package/dist/index.js +21 -1
  40. package/dist/index.js.map +1 -1
  41. package/dist/keychain-adapter.d.ts +48 -0
  42. package/dist/keychain-adapter.d.ts.map +1 -0
  43. package/dist/keychain-adapter.js +0 -0
  44. package/dist/keychain-adapter.js.map +1 -0
  45. package/dist/oauth/browser.d.ts +31 -0
  46. package/dist/oauth/browser.d.ts.map +1 -0
  47. package/dist/oauth/browser.js +55 -0
  48. package/dist/oauth/browser.js.map +1 -0
  49. package/dist/oauth/callback-server.d.ts +37 -0
  50. package/dist/oauth/callback-server.d.ts.map +1 -0
  51. package/dist/oauth/callback-server.js +86 -0
  52. package/dist/oauth/callback-server.js.map +1 -0
  53. package/dist/oauth/client.d.ts +57 -0
  54. package/dist/oauth/client.d.ts.map +1 -0
  55. package/dist/oauth/client.js +120 -0
  56. package/dist/oauth/client.js.map +1 -0
  57. package/dist/oauth/pkce.d.ts +25 -0
  58. package/dist/oauth/pkce.d.ts.map +1 -0
  59. package/dist/oauth/pkce.js +36 -0
  60. package/dist/oauth/pkce.js.map +1 -0
  61. package/dist/password-hasher.d.ts.map +1 -1
  62. package/dist/password-hasher.js +8 -1
  63. package/dist/password-hasher.js.map +1 -1
  64. package/dist/plugins/integrity-verifier.d.ts +125 -0
  65. package/dist/plugins/integrity-verifier.d.ts.map +1 -0
  66. package/dist/plugins/integrity-verifier.js +186 -0
  67. package/dist/plugins/integrity-verifier.js.map +1 -0
  68. package/dist/safe-executor.d.ts +7 -0
  69. package/dist/safe-executor.d.ts.map +1 -1
  70. package/dist/safe-executor.js +21 -1
  71. package/dist/safe-executor.js.map +1 -1
  72. package/dist/tool-output-guardrail.d.ts +126 -0
  73. package/dist/tool-output-guardrail.d.ts.map +1 -0
  74. package/dist/tool-output-guardrail.js +257 -0
  75. package/dist/tool-output-guardrail.js.map +1 -0
  76. package/node_modules-incomplete-release-test/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +1 -0
  77. package/package.json +33 -28
  78. package/scripts/verify-oauth-exports.mjs +29 -0
  79. package/src/CVE-REMEDIATION.ts +591 -251
  80. package/src/application/index.ts +10 -10
  81. package/src/application/services/security-application-service.ts +193 -193
  82. package/src/authorization/propagator.ts +279 -0
  83. package/src/credential-generator.ts +368 -368
  84. package/src/domain/entities/security-context.ts +173 -173
  85. package/src/domain/index.ts +17 -17
  86. package/src/domain/services/security-domain-service.ts +296 -296
  87. package/src/index.ts +340 -271
  88. package/src/input-validator.ts +466 -466
  89. package/src/keychain-adapter.ts +0 -0
  90. package/src/oauth/browser.ts +58 -0
  91. package/src/oauth/callback-server.ts +97 -0
  92. package/src/oauth/client.ts +153 -0
  93. package/src/oauth/pkce.ts +45 -0
  94. package/src/password-hasher.ts +277 -270
  95. package/src/path-validator.ts +525 -525
  96. package/src/plugins/integrity-verifier.ts +265 -0
  97. package/src/safe-executor.ts +546 -525
  98. package/src/token-generator.ts +463 -463
  99. package/src/tool-output-guardrail.ts +360 -0
  100. package/tmp.json +0 -0
  101. package/tsconfig.json +9 -9
  102. package/tsconfig.tsbuildinfo +1 -1
  103. package/vitest.config.ts +20 -0
  104. package/.agentic-flow/intelligence.json +0 -16
  105. package/__tests__/coverage/base.css +0 -224
  106. package/__tests__/coverage/block-navigation.js +0 -87
  107. package/__tests__/coverage/coverage-final.json +0 -11
  108. package/__tests__/coverage/favicon.png +0 -0
  109. package/__tests__/coverage/index.html +0 -161
  110. package/__tests__/coverage/lcov-report/base.css +0 -224
  111. package/__tests__/coverage/lcov-report/block-navigation.js +0 -87
  112. package/__tests__/coverage/lcov-report/favicon.png +0 -0
  113. package/__tests__/coverage/lcov-report/index.html +0 -161
  114. package/__tests__/coverage/lcov-report/prettify.css +0 -1
  115. package/__tests__/coverage/lcov-report/prettify.js +0 -2
  116. package/__tests__/coverage/lcov-report/sort-arrow-sprite.png +0 -0
  117. package/__tests__/coverage/lcov-report/sorter.js +0 -210
  118. package/__tests__/coverage/lcov-report/src/CVE-REMEDIATION.ts.html +0 -838
  119. package/__tests__/coverage/lcov-report/src/application/services/index.html +0 -116
  120. package/__tests__/coverage/lcov-report/src/application/services/security-application-service.ts.html +0 -664
  121. package/__tests__/coverage/lcov-report/src/credential-generator.ts.html +0 -1189
  122. package/__tests__/coverage/lcov-report/src/domain/entities/index.html +0 -116
  123. package/__tests__/coverage/lcov-report/src/domain/entities/security-context.ts.html +0 -604
  124. package/__tests__/coverage/lcov-report/src/domain/services/index.html +0 -116
  125. package/__tests__/coverage/lcov-report/src/domain/services/security-domain-service.ts.html +0 -973
  126. package/__tests__/coverage/lcov-report/src/index.html +0 -206
  127. package/__tests__/coverage/lcov-report/src/input-validator.ts.html +0 -1483
  128. package/__tests__/coverage/lcov-report/src/password-hasher.ts.html +0 -895
  129. package/__tests__/coverage/lcov-report/src/path-validator.ts.html +0 -1660
  130. package/__tests__/coverage/lcov-report/src/safe-executor.ts.html +0 -1660
  131. package/__tests__/coverage/lcov-report/src/token-generator.ts.html +0 -1474
  132. package/__tests__/coverage/lcov.info +0 -3650
  133. package/__tests__/coverage/prettify.css +0 -1
  134. package/__tests__/coverage/prettify.js +0 -2
  135. package/__tests__/coverage/sort-arrow-sprite.png +0 -0
  136. package/__tests__/coverage/sorter.js +0 -210
  137. package/__tests__/coverage/src/CVE-REMEDIATION.ts.html +0 -838
  138. package/__tests__/coverage/src/application/services/index.html +0 -116
  139. package/__tests__/coverage/src/application/services/security-application-service.ts.html +0 -664
  140. package/__tests__/coverage/src/credential-generator.ts.html +0 -1189
  141. package/__tests__/coverage/src/domain/entities/index.html +0 -116
  142. package/__tests__/coverage/src/domain/entities/security-context.ts.html +0 -604
  143. package/__tests__/coverage/src/domain/services/index.html +0 -116
  144. package/__tests__/coverage/src/domain/services/security-domain-service.ts.html +0 -973
  145. package/__tests__/coverage/src/index.html +0 -206
  146. package/__tests__/coverage/src/input-validator.ts.html +0 -1483
  147. package/__tests__/coverage/src/password-hasher.ts.html +0 -895
  148. package/__tests__/coverage/src/path-validator.ts.html +0 -1660
  149. package/__tests__/coverage/src/safe-executor.ts.html +0 -1660
  150. package/__tests__/coverage/src/token-generator.ts.html +0 -1474
@@ -1,296 +1,296 @@
1
- /**
2
- * Security Domain Service - Domain Layer
3
- *
4
- * Contains security logic for validation, policy enforcement, and threat detection.
5
- *
6
- * @module v3/security/domain/services
7
- */
8
-
9
- import { SecurityContext, PermissionLevel } from '../entities/security-context.js';
10
-
11
- /**
12
- * Validation result
13
- */
14
- export interface ValidationResult {
15
- valid: boolean;
16
- errors: string[];
17
- warnings: string[];
18
- sanitized?: string;
19
- }
20
-
21
- /**
22
- * Threat detection result
23
- */
24
- export interface ThreatDetectionResult {
25
- safe: boolean;
26
- threats: Array<{
27
- type: string;
28
- severity: 'low' | 'medium' | 'high' | 'critical';
29
- description: string;
30
- location?: string;
31
- }>;
32
- }
33
-
34
- /**
35
- * Security Domain Service
36
- */
37
- export class SecurityDomainService {
38
- // Dangerous patterns for path traversal
39
- private static readonly PATH_TRAVERSAL_PATTERNS = [
40
- /\.\./,
41
- /~\//,
42
- /^\/etc\//,
43
- /^\/tmp\//,
44
- /^\/var\/log\//,
45
- /^C:\\Windows/i,
46
- /^C:\\Users\\[^\\]+\\AppData/i,
47
- ];
48
-
49
- // Dangerous command patterns
50
- private static readonly DANGEROUS_COMMANDS = [
51
- /^rm\s+-rf\s+\//,
52
- /^rm\s+-rf\s+\*/,
53
- /^dd\s+if=/,
54
- /^mkfs\./,
55
- /^format\s+/i,
56
- /^del\s+\/s\s+\/q/i,
57
- />\s*\/dev\/sd[a-z]/,
58
- /\|\s*bash$/,
59
- /\|\s*sh$/,
60
- /eval\s*\(/,
61
- /exec\s*\(/,
62
- ];
63
-
64
- // SQL injection patterns
65
- private static readonly SQL_INJECTION_PATTERNS = [
66
- /'\s*OR\s+'1'\s*=\s*'1/i,
67
- /'\s*OR\s+1\s*=\s*1/i,
68
- /;\s*DROP\s+TABLE/i,
69
- /;\s*DELETE\s+FROM/i,
70
- /UNION\s+SELECT/i,
71
- /--\s*$/,
72
- ];
73
-
74
- // XSS patterns
75
- private static readonly XSS_PATTERNS = [
76
- /<script[\s>]/i,
77
- /javascript:/i,
78
- /on\w+\s*=/i,
79
- /<iframe/i,
80
- /<object/i,
81
- /<embed/i,
82
- ];
83
-
84
- /**
85
- * Validate a file path
86
- */
87
- validatePath(path: string, context: SecurityContext): ValidationResult {
88
- const errors: string[] = [];
89
- const warnings: string[] = [];
90
-
91
- // Check path traversal
92
- for (const pattern of SecurityDomainService.PATH_TRAVERSAL_PATTERNS) {
93
- if (pattern.test(path)) {
94
- errors.push(`Path traversal detected: ${pattern.source}`);
95
- }
96
- }
97
-
98
- // Check context permissions
99
- if (!context.canAccessPath(path)) {
100
- errors.push(`Access denied to path: ${path}`);
101
- }
102
-
103
- // Check for suspicious paths
104
- if (path.includes('..')) {
105
- warnings.push('Path contains parent directory reference');
106
- }
107
-
108
- return {
109
- valid: errors.length === 0,
110
- errors,
111
- warnings,
112
- sanitized: this.sanitizePath(path),
113
- };
114
- }
115
-
116
- /**
117
- * Validate a command
118
- */
119
- validateCommand(command: string, context: SecurityContext): ValidationResult {
120
- const errors: string[] = [];
121
- const warnings: string[] = [];
122
-
123
- // Check dangerous commands
124
- for (const pattern of SecurityDomainService.DANGEROUS_COMMANDS) {
125
- if (pattern.test(command)) {
126
- errors.push(`Dangerous command pattern detected: ${pattern.source}`);
127
- }
128
- }
129
-
130
- // Check context permissions
131
- if (!context.canExecuteCommand(command)) {
132
- errors.push(`Command execution denied: ${command}`);
133
- }
134
-
135
- if (!context.hasPermission('execute')) {
136
- errors.push('Execute permission required');
137
- }
138
-
139
- // Check for shell injection
140
- if (/[;&|`$(){}]/.test(command)) {
141
- warnings.push('Command contains shell metacharacters');
142
- }
143
-
144
- return {
145
- valid: errors.length === 0,
146
- errors,
147
- warnings,
148
- sanitized: this.sanitizeCommand(command),
149
- };
150
- }
151
-
152
- /**
153
- * Validate user input
154
- */
155
- validateInput(input: string): ValidationResult {
156
- const errors: string[] = [];
157
- const warnings: string[] = [];
158
-
159
- // Check for SQL injection
160
- for (const pattern of SecurityDomainService.SQL_INJECTION_PATTERNS) {
161
- if (pattern.test(input)) {
162
- errors.push(`SQL injection pattern detected`);
163
- break;
164
- }
165
- }
166
-
167
- // Check for XSS
168
- for (const pattern of SecurityDomainService.XSS_PATTERNS) {
169
- if (pattern.test(input)) {
170
- errors.push(`XSS pattern detected`);
171
- break;
172
- }
173
- }
174
-
175
- // Check length
176
- if (input.length > 10000) {
177
- warnings.push('Input exceeds recommended length');
178
- }
179
-
180
- return {
181
- valid: errors.length === 0,
182
- errors,
183
- warnings,
184
- sanitized: this.sanitizeInput(input),
185
- };
186
- }
187
-
188
- /**
189
- * Detect threats in content
190
- */
191
- detectThreats(content: string): ThreatDetectionResult {
192
- const threats: ThreatDetectionResult['threats'] = [];
193
-
194
- // Check for various threat patterns
195
- if (/<script/i.test(content)) {
196
- threats.push({
197
- type: 'xss',
198
- severity: 'high',
199
- description: 'Script tag detected',
200
- });
201
- }
202
-
203
- if (/password\s*[:=]\s*["'][^"']+["']/i.test(content)) {
204
- threats.push({
205
- type: 'credential-exposure',
206
- severity: 'critical',
207
- description: 'Hardcoded password detected',
208
- });
209
- }
210
-
211
- if (/api[_-]?key\s*[:=]\s*["'][^"']+["']/i.test(content)) {
212
- threats.push({
213
- type: 'credential-exposure',
214
- severity: 'critical',
215
- description: 'API key detected',
216
- });
217
- }
218
-
219
- if (/eval\s*\(/.test(content)) {
220
- threats.push({
221
- type: 'code-injection',
222
- severity: 'high',
223
- description: 'Eval statement detected',
224
- });
225
- }
226
-
227
- return {
228
- safe: threats.length === 0,
229
- threats,
230
- };
231
- }
232
-
233
- /**
234
- * Sanitize path
235
- */
236
- private sanitizePath(path: string): string {
237
- return path
238
- .replace(/\.\./g, '')
239
- .replace(/\/\//g, '/')
240
- .replace(/^~\//, '')
241
- .trim();
242
- }
243
-
244
- /**
245
- * Sanitize command
246
- */
247
- private sanitizeCommand(command: string): string {
248
- return command
249
- .replace(/[;&|`$]/g, '')
250
- .replace(/\$\([^)]*\)/g, '')
251
- .trim();
252
- }
253
-
254
- /**
255
- * Sanitize user input
256
- */
257
- private sanitizeInput(input: string): string {
258
- return input
259
- .replace(/</g, '&lt;')
260
- .replace(/>/g, '&gt;')
261
- .replace(/"/g, '&quot;')
262
- .replace(/'/g, '&#x27;')
263
- .replace(/\//g, '&#x2F;');
264
- }
265
-
266
- /**
267
- * Create security context for agent
268
- */
269
- createAgentContext(
270
- agentId: string,
271
- role: string,
272
- customPaths?: string[]
273
- ): SecurityContext {
274
- // Default permissions based on role
275
- const rolePermissions: Record<string, PermissionLevel[]> = {
276
- 'queen-coordinator': ['read', 'write', 'execute', 'admin'],
277
- 'security-architect': ['read', 'write', 'execute', 'admin'],
278
- 'coder': ['read', 'write', 'execute'],
279
- 'reviewer': ['read'],
280
- 'tester': ['read', 'execute'],
281
- default: ['read'],
282
- };
283
-
284
- const permissions = rolePermissions[role] ?? rolePermissions.default;
285
-
286
- return SecurityContext.create({
287
- principalId: agentId,
288
- principalType: 'agent',
289
- permissions,
290
- allowedPaths: customPaths ?? ['./src', './tests', './docs'],
291
- blockedPaths: ['/etc', '/var', '~/', '../'],
292
- allowedCommands: ['npm', 'npx', 'node', 'git', 'vitest'],
293
- blockedCommands: ['rm -rf /', 'dd', 'mkfs', 'format'],
294
- });
295
- }
296
- }
1
+ /**
2
+ * Security Domain Service - Domain Layer
3
+ *
4
+ * Contains security logic for validation, policy enforcement, and threat detection.
5
+ *
6
+ * @module v3/security/domain/services
7
+ */
8
+
9
+ import { SecurityContext, PermissionLevel } from '../entities/security-context.js';
10
+
11
+ /**
12
+ * Validation result
13
+ */
14
+ export interface ValidationResult {
15
+ valid: boolean;
16
+ errors: string[];
17
+ warnings: string[];
18
+ sanitized?: string;
19
+ }
20
+
21
+ /**
22
+ * Threat detection result
23
+ */
24
+ export interface ThreatDetectionResult {
25
+ safe: boolean;
26
+ threats: Array<{
27
+ type: string;
28
+ severity: 'low' | 'medium' | 'high' | 'critical';
29
+ description: string;
30
+ location?: string;
31
+ }>;
32
+ }
33
+
34
+ /**
35
+ * Security Domain Service
36
+ */
37
+ export class SecurityDomainService {
38
+ // Dangerous patterns for path traversal
39
+ private static readonly PATH_TRAVERSAL_PATTERNS = [
40
+ /\.\./,
41
+ /~\//,
42
+ /^\/etc\//,
43
+ /^\/tmp\//,
44
+ /^\/var\/log\//,
45
+ /^C:\\Windows/i,
46
+ /^C:\\Users\\[^\\]+\\AppData/i,
47
+ ];
48
+
49
+ // Dangerous command patterns
50
+ private static readonly DANGEROUS_COMMANDS = [
51
+ /^rm\s+-rf\s+\//,
52
+ /^rm\s+-rf\s+\*/,
53
+ /^dd\s+if=/,
54
+ /^mkfs\./,
55
+ /^format\s+/i,
56
+ /^del\s+\/s\s+\/q/i,
57
+ />\s*\/dev\/sd[a-z]/,
58
+ /\|\s*bash$/,
59
+ /\|\s*sh$/,
60
+ /eval\s*\(/,
61
+ /exec\s*\(/,
62
+ ];
63
+
64
+ // SQL injection patterns
65
+ private static readonly SQL_INJECTION_PATTERNS = [
66
+ /'\s*OR\s+'1'\s*=\s*'1/i,
67
+ /'\s*OR\s+1\s*=\s*1/i,
68
+ /;\s*DROP\s+TABLE/i,
69
+ /;\s*DELETE\s+FROM/i,
70
+ /UNION\s+SELECT/i,
71
+ /--\s*$/,
72
+ ];
73
+
74
+ // XSS patterns
75
+ private static readonly XSS_PATTERNS = [
76
+ /<script[\s>]/i,
77
+ /javascript:/i,
78
+ /on\w+\s*=/i,
79
+ /<iframe/i,
80
+ /<object/i,
81
+ /<embed/i,
82
+ ];
83
+
84
+ /**
85
+ * Validate a file path
86
+ */
87
+ validatePath(path: string, context: SecurityContext): ValidationResult {
88
+ const errors: string[] = [];
89
+ const warnings: string[] = [];
90
+
91
+ // Check path traversal
92
+ for (const pattern of SecurityDomainService.PATH_TRAVERSAL_PATTERNS) {
93
+ if (pattern.test(path)) {
94
+ errors.push(`Path traversal detected: ${pattern.source}`);
95
+ }
96
+ }
97
+
98
+ // Check context permissions
99
+ if (!context.canAccessPath(path)) {
100
+ errors.push(`Access denied to path: ${path}`);
101
+ }
102
+
103
+ // Check for suspicious paths
104
+ if (path.includes('..')) {
105
+ warnings.push('Path contains parent directory reference');
106
+ }
107
+
108
+ return {
109
+ valid: errors.length === 0,
110
+ errors,
111
+ warnings,
112
+ sanitized: this.sanitizePath(path),
113
+ };
114
+ }
115
+
116
+ /**
117
+ * Validate a command
118
+ */
119
+ validateCommand(command: string, context: SecurityContext): ValidationResult {
120
+ const errors: string[] = [];
121
+ const warnings: string[] = [];
122
+
123
+ // Check dangerous commands
124
+ for (const pattern of SecurityDomainService.DANGEROUS_COMMANDS) {
125
+ if (pattern.test(command)) {
126
+ errors.push(`Dangerous command pattern detected: ${pattern.source}`);
127
+ }
128
+ }
129
+
130
+ // Check context permissions
131
+ if (!context.canExecuteCommand(command)) {
132
+ errors.push(`Command execution denied: ${command}`);
133
+ }
134
+
135
+ if (!context.hasPermission('execute')) {
136
+ errors.push('Execute permission required');
137
+ }
138
+
139
+ // Check for shell injection
140
+ if (/[;&|`$(){}]/.test(command)) {
141
+ warnings.push('Command contains shell metacharacters');
142
+ }
143
+
144
+ return {
145
+ valid: errors.length === 0,
146
+ errors,
147
+ warnings,
148
+ sanitized: this.sanitizeCommand(command),
149
+ };
150
+ }
151
+
152
+ /**
153
+ * Validate user input
154
+ */
155
+ validateInput(input: string): ValidationResult {
156
+ const errors: string[] = [];
157
+ const warnings: string[] = [];
158
+
159
+ // Check for SQL injection
160
+ for (const pattern of SecurityDomainService.SQL_INJECTION_PATTERNS) {
161
+ if (pattern.test(input)) {
162
+ errors.push(`SQL injection pattern detected`);
163
+ break;
164
+ }
165
+ }
166
+
167
+ // Check for XSS
168
+ for (const pattern of SecurityDomainService.XSS_PATTERNS) {
169
+ if (pattern.test(input)) {
170
+ errors.push(`XSS pattern detected`);
171
+ break;
172
+ }
173
+ }
174
+
175
+ // Check length
176
+ if (input.length > 10000) {
177
+ warnings.push('Input exceeds recommended length');
178
+ }
179
+
180
+ return {
181
+ valid: errors.length === 0,
182
+ errors,
183
+ warnings,
184
+ sanitized: this.sanitizeInput(input),
185
+ };
186
+ }
187
+
188
+ /**
189
+ * Detect threats in content
190
+ */
191
+ detectThreats(content: string): ThreatDetectionResult {
192
+ const threats: ThreatDetectionResult['threats'] = [];
193
+
194
+ // Check for various threat patterns
195
+ if (/<script/i.test(content)) {
196
+ threats.push({
197
+ type: 'xss',
198
+ severity: 'high',
199
+ description: 'Script tag detected',
200
+ });
201
+ }
202
+
203
+ if (/password\s*[:=]\s*["'][^"']+["']/i.test(content)) {
204
+ threats.push({
205
+ type: 'credential-exposure',
206
+ severity: 'critical',
207
+ description: 'Hardcoded password detected',
208
+ });
209
+ }
210
+
211
+ if (/api[_-]?key\s*[:=]\s*["'][^"']+["']/i.test(content)) {
212
+ threats.push({
213
+ type: 'credential-exposure',
214
+ severity: 'critical',
215
+ description: 'API key detected',
216
+ });
217
+ }
218
+
219
+ if (/eval\s*\(/.test(content)) {
220
+ threats.push({
221
+ type: 'code-injection',
222
+ severity: 'high',
223
+ description: 'Eval statement detected',
224
+ });
225
+ }
226
+
227
+ return {
228
+ safe: threats.length === 0,
229
+ threats,
230
+ };
231
+ }
232
+
233
+ /**
234
+ * Sanitize path
235
+ */
236
+ private sanitizePath(path: string): string {
237
+ return path
238
+ .replace(/\.\./g, '')
239
+ .replace(/\/\//g, '/')
240
+ .replace(/^~\//, '')
241
+ .trim();
242
+ }
243
+
244
+ /**
245
+ * Sanitize command
246
+ */
247
+ private sanitizeCommand(command: string): string {
248
+ return command
249
+ .replace(/[;&|`$]/g, '')
250
+ .replace(/\$\([^)]*\)/g, '')
251
+ .trim();
252
+ }
253
+
254
+ /**
255
+ * Sanitize user input
256
+ */
257
+ private sanitizeInput(input: string): string {
258
+ return input
259
+ .replace(/</g, '&lt;')
260
+ .replace(/>/g, '&gt;')
261
+ .replace(/"/g, '&quot;')
262
+ .replace(/'/g, '&#x27;')
263
+ .replace(/\//g, '&#x2F;');
264
+ }
265
+
266
+ /**
267
+ * Create security context for agent
268
+ */
269
+ createAgentContext(
270
+ agentId: string,
271
+ role: string,
272
+ customPaths?: string[]
273
+ ): SecurityContext {
274
+ // Default permissions based on role
275
+ const rolePermissions: Record<string, PermissionLevel[]> = {
276
+ 'queen-coordinator': ['read', 'write', 'execute', 'admin'],
277
+ 'security-architect': ['read', 'write', 'execute', 'admin'],
278
+ 'coder': ['read', 'write', 'execute'],
279
+ 'reviewer': ['read'],
280
+ 'tester': ['read', 'execute'],
281
+ default: ['read'],
282
+ };
283
+
284
+ const permissions = rolePermissions[role] ?? rolePermissions.default;
285
+
286
+ return SecurityContext.create({
287
+ principalId: agentId,
288
+ principalType: 'agent',
289
+ permissions,
290
+ allowedPaths: customPaths ?? ['./src', './tests', './docs'],
291
+ blockedPaths: ['/etc', '/var', '~/', '../'],
292
+ allowedCommands: ['npm', 'node', 'git', 'vitest'],
293
+ blockedCommands: ['rm -rf /', 'dd', 'mkfs', 'format'],
294
+ });
295
+ }
296
+ }