faultmesh 1.0.0 → 1.1.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 (43) hide show
  1. package/README.md +61 -19
  2. package/dist/dashboard/app.js +1906 -139
  3. package/dist/dashboard/index.html +393 -99
  4. package/dist/dashboard/styles.css +1191 -23
  5. package/dist/engine/ControlApi.d.ts +13 -1
  6. package/dist/engine/ControlApi.js +304 -14
  7. package/dist/engine/FaultMeshProxy.d.ts +2 -0
  8. package/dist/engine/FaultMeshProxy.js +41 -5
  9. package/dist/engine/TelemetryHub.d.ts +1 -0
  10. package/dist/engine/TelemetryHub.js +3 -0
  11. package/dist/engine/ToxicPipeline.d.ts +5 -4
  12. package/dist/engine/ToxicPipeline.js +17 -4
  13. package/dist/healer/AiHealer.d.ts +30 -0
  14. package/dist/healer/AiHealer.js +188 -0
  15. package/dist/healer/AutoHealer.d.ts +24 -0
  16. package/dist/healer/AutoHealer.js +503 -0
  17. package/dist/healer/DiffGenerator.d.ts +10 -0
  18. package/dist/healer/DiffGenerator.js +63 -0
  19. package/dist/healer/DiffUtil.d.ts +6 -0
  20. package/dist/healer/DiffUtil.js +67 -0
  21. package/dist/healer/transformers/ExpressTransformers.d.ts +43 -0
  22. package/dist/healer/transformers/ExpressTransformers.js +228 -0
  23. package/dist/healer/transformers/FastApiTransformers.d.ts +19 -0
  24. package/dist/healer/transformers/FastApiTransformers.js +93 -0
  25. package/dist/healer/transformers/GoTransformers.d.ts +19 -0
  26. package/dist/healer/transformers/GoTransformers.js +106 -0
  27. package/dist/healer/types.d.ts +59 -0
  28. package/dist/healer/types.js +1 -0
  29. package/dist/redteam/EccAgentBridge.d.ts +20 -0
  30. package/dist/redteam/EccAgentBridge.js +303 -0
  31. package/dist/redteam/RedTeamEngine.d.ts +56 -0
  32. package/dist/redteam/RedTeamEngine.js +709 -0
  33. package/dist/redteam/types.d.ts +117 -0
  34. package/dist/redteam/types.js +5 -0
  35. package/dist/scorer/ResilienceScorer.d.ts +5 -0
  36. package/dist/scorer/ResilienceScorer.js +323 -7
  37. package/dist/scorer/SecurityAuditor.d.ts +8 -0
  38. package/dist/scorer/SecurityAuditor.js +471 -69
  39. package/dist/scorer/TrafficStormAuditor.d.ts +5 -0
  40. package/dist/scorer/TrafficStormAuditor.js +328 -69
  41. package/dist/server.js +17 -10
  42. package/dist/types.d.ts +7 -3
  43. package/package.json +2 -1
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Express / Node.js Remediation Transformers
3
+ * Surgically injects defensive middleware and parameters into Express applications.
4
+ */
5
+ export interface TransformerResult {
6
+ modified: boolean;
7
+ content: string;
8
+ description: string;
9
+ }
10
+ export declare class ExpressTransformers {
11
+ /**
12
+ * 1. Defensive Security Headers (Helmet)
13
+ */
14
+ static applyDefensiveHeaders(content: string): TransformerResult;
15
+ /**
16
+ * 2. Oversized Payload & Buffer OOM Defense (express.json limit)
17
+ */
18
+ static applyPayloadLimit(content: string): TransformerResult;
19
+ /**
20
+ * 3. CORS & Origin Validation
21
+ */
22
+ static applyCorsLockdown(content: string): TransformerResult;
23
+ /**
24
+ * 4. Error Sanitization & Stack Trace Exposure
25
+ */
26
+ static applyErrorSanitization(content: string): TransformerResult;
27
+ /**
28
+ * 5. Slowloris & Request Socket Timeout
29
+ */
30
+ static applySocketTimeouts(content: string): TransformerResult;
31
+ /**
32
+ * 6. Strict Host Header Whitelist Validation
33
+ */
34
+ static applyHostHeaderValidation(content: string): TransformerResult;
35
+ /**
36
+ * 7. Path Traversal & Unsanitized Directory Escape Guard
37
+ */
38
+ static applyPathTraversalGuard(content: string): TransformerResult;
39
+ /**
40
+ * 8. Duplicate Request Idempotency & Concurrency Race Protection
41
+ */
42
+ static applyIdempotencyProtection(content: string): TransformerResult;
43
+ }
@@ -0,0 +1,228 @@
1
+ /**
2
+ * Express / Node.js Remediation Transformers
3
+ * Surgically injects defensive middleware and parameters into Express applications.
4
+ */
5
+ export class ExpressTransformers {
6
+ /**
7
+ * 1. Defensive Security Headers (Helmet)
8
+ */
9
+ static applyDefensiveHeaders(content) {
10
+ // Check if already using helmet or security headers
11
+ if (content.includes('helmet') || (content.includes('X-Content-Type-Options') && content.includes('X-Frame-Options'))) {
12
+ return { modified: false, content, description: 'Defensive headers already configured' };
13
+ }
14
+ let modifiedContent = content;
15
+ const isESM = content.includes('import ') && content.includes('from ');
16
+ // 1. Add import/require
17
+ if (isESM) {
18
+ modifiedContent = `import helmet from 'helmet';\n${modifiedContent}`;
19
+ }
20
+ else {
21
+ modifiedContent = `const helmet = require('helmet');\n${modifiedContent}`;
22
+ }
23
+ // 2. Insert app.use(helmet()) right after app initialization
24
+ const appMatch = modifiedContent.match(/(const|let|var)\s+([a-zA-Z0-9_$]+)\s*=\s*(express\s*\(\)|createApp\s*\(\))/);
25
+ if (appMatch) {
26
+ const appVar = appMatch[2];
27
+ const targetStr = appMatch[0];
28
+ const cleanTarget = targetStr.replace(/;+$/, '');
29
+ const injection = `${cleanTarget};\n${appVar}.use(helmet());`;
30
+ modifiedContent = modifiedContent.replace(targetStr, injection);
31
+ return {
32
+ modified: true,
33
+ content: modifiedContent,
34
+ description: `Injected helmet security headers into Express app (${appVar}.use(helmet()))`,
35
+ };
36
+ }
37
+ return { modified: false, content, description: 'Could not find Express app instance to inject helmet' };
38
+ }
39
+ /**
40
+ * 2. Oversized Payload & Buffer OOM Defense (express.json limit)
41
+ */
42
+ static applyPayloadLimit(content) {
43
+ // Check if express.json or bodyParser already has a 1mb limit
44
+ if (content.includes("express.json({ limit: '1mb' })") || content.includes('express.json({ limit: "1mb" })') || content.includes("express.json({limit: '1mb'})")) {
45
+ return { modified: false, content, description: 'JSON payload limit (1mb) already configured' };
46
+ }
47
+ let modifiedContent = content;
48
+ let modified = false;
49
+ // Replace express.json(...) with express.json({ limit: '1mb' })
50
+ if (/express\.json\(\s*(\{[^}]*\})?\s*\)/.test(modifiedContent)) {
51
+ modifiedContent = modifiedContent.replace(/express\.json\(\s*(\{[^}]*\})?\s*\)/g, "express.json({ limit: '1mb' })");
52
+ modified = true;
53
+ }
54
+ // Replace express.urlencoded(...) with limit
55
+ if (modifiedContent.includes('express.urlencoded(') && !modifiedContent.includes("express.urlencoded({ limit:")) {
56
+ modifiedContent = modifiedContent.replace(/express\.urlencoded\(\{([^}]+)\}\)/g, "express.urlencoded({ $1, limit: '1mb' })");
57
+ modified = true;
58
+ }
59
+ // Fallback: If app.use is found but express.json is not called at all
60
+ if (!modified) {
61
+ const appMatch = modifiedContent.match(/([a-zA-Z0-9_$]+)\.use\(/);
62
+ if (appMatch) {
63
+ const appVar = appMatch[1];
64
+ modifiedContent = modifiedContent.replace(`${appVar}.use(`, `${appVar}.use(express.json({ limit: '1mb' }));\n${appVar}.use(`);
65
+ modified = true;
66
+ }
67
+ }
68
+ return {
69
+ modified,
70
+ content: modifiedContent,
71
+ description: modified ? "Enforced 1MB request payload limit (express.json({ limit: '1mb' }))" : 'Payload limit not applicable',
72
+ };
73
+ }
74
+ /**
75
+ * 3. CORS & Origin Validation
76
+ */
77
+ static applyCorsLockdown(content) {
78
+ // If wildcard CORS without validation is found
79
+ const openCorsPattern = /cors\(\s*\)/g;
80
+ const wildcardOriginPattern = /origin:\s*['"]\*['"]/g;
81
+ let modifiedContent = content;
82
+ let modified = false;
83
+ const safeCorsConfig = `{
84
+ origin: (origin, callback) => {
85
+ const allowed = (process.env.ALLOWED_ORIGINS || 'http://localhost:3000').split(',');
86
+ if (!origin || allowed.includes(origin)) return callback(null, true);
87
+ callback(new Error('CORS origin blocked by policy'));
88
+ },
89
+ credentials: true
90
+ }`;
91
+ if (openCorsPattern.test(modifiedContent)) {
92
+ modifiedContent = modifiedContent.replace(openCorsPattern, `cors(${safeCorsConfig})`);
93
+ modified = true;
94
+ }
95
+ else if (wildcardOriginPattern.test(modifiedContent)) {
96
+ modifiedContent = modifiedContent.replace(wildcardOriginPattern, `origin: (origin, cb) => cb(null, origin || true)`);
97
+ modified = true;
98
+ }
99
+ return {
100
+ modified,
101
+ content: modifiedContent,
102
+ description: modified ? 'Locked down open CORS wildcard with strict origin validation' : 'CORS configuration already restricted',
103
+ };
104
+ }
105
+ /**
106
+ * 4. Error Sanitization & Stack Trace Exposure
107
+ */
108
+ static applyErrorSanitization(content) {
109
+ if (/\.use\s*\(\s*(\(\s*err|\s*function\s*\(\s*err)/.test(content)) {
110
+ return { modified: false, content, description: 'Error handling middleware already present' };
111
+ }
112
+ let modifiedContent = content;
113
+ const listenRegex = /(?:const|let|var)?\s*[a-zA-Z0-9_$]*\s*=?\s*([a-zA-Z0-9_$]+)\.listen\(/;
114
+ const listenMatch = modifiedContent.match(listenRegex);
115
+ if (listenMatch) {
116
+ const appVar = listenMatch[1];
117
+ const fullMatch = listenMatch[0];
118
+ const errorMiddleware = `
119
+ // Centralized Error Sanitization Middleware
120
+ ${appVar}.use((err, req, res, next) => {
121
+ const statusCode = err.status || err.statusCode || 500;
122
+ res.status(statusCode).json({
123
+ error: statusCode >= 500 ? 'Internal Server Error' : err.message,
124
+ timestamp: Date.now()
125
+ });
126
+ });
127
+ `;
128
+ modifiedContent = modifiedContent.replace(fullMatch, `${errorMiddleware}\n${fullMatch}`);
129
+ return {
130
+ modified: true,
131
+ content: modifiedContent,
132
+ description: 'Injected centralized error sanitization middleware to prevent stack trace leaks',
133
+ };
134
+ }
135
+ return { modified: false, content, description: 'Could not locate app.listen to inject error handler' };
136
+ }
137
+ /**
138
+ * 5. Slowloris & Request Socket Timeout
139
+ */
140
+ static applySocketTimeouts(content) {
141
+ if (/\.headersTimeout\s*=\s*\d+/.test(content) && /\.requestTimeout\s*=\s*\d+/.test(content)) {
142
+ return { modified: false, content, description: 'Server timeouts already configured' };
143
+ }
144
+ let modifiedContent = content;
145
+ // Match const server = app.listen(...) or server = http.createServer(...)
146
+ const serverMatch = modifiedContent.match(/(const|let|var)\s+([a-zA-Z0-9_$]+)\s*=\s*([a-zA-Z0-9_$]+)\.listen\(/);
147
+ if (serverMatch) {
148
+ const serverVar = serverMatch[2];
149
+ const injection = `\n// Enforce strict socket timeouts to mitigate slowloris attacks\n${serverVar}.headersTimeout = 5000;\n${serverVar}.requestTimeout = 10000;\n`;
150
+ modifiedContent = modifiedContent.trimEnd() + '\n' + injection;
151
+ return {
152
+ modified: true,
153
+ content: modifiedContent,
154
+ description: `Configured socket timeouts (${serverVar}.headersTimeout = 5s, ${serverVar}.requestTimeout = 10s)`,
155
+ };
156
+ }
157
+ return { modified: false, content, description: 'Could not locate HTTP server instance for timeout configuration' };
158
+ }
159
+ /**
160
+ * 6. Strict Host Header Whitelist Validation
161
+ */
162
+ static applyHostHeaderValidation(content) {
163
+ if (content.includes('allowedHosts') || content.includes('Host header validation guard') || content.includes('Blocked: Unrecognized or untrusted Host header')) {
164
+ return { modified: false, content, description: 'Host header whitelist validation already present' };
165
+ }
166
+ let modifiedContent = content;
167
+ const appMatch = modifiedContent.match(/([a-zA-Z0-9_$]+)\s*=\s*(express\s*\(\)|createApp\s*\(\))/);
168
+ if (appMatch) {
169
+ const appVar = appMatch[1];
170
+ const middleware = `\n// Host Header Whitelist Validation Guard\n${appVar}.use((req, res, next) => {\n const rawHost = req.headers['host'] || req.headers['x-forwarded-host'] || '';\n const host = String(Array.isArray(rawHost) ? rawHost[0] : rawHost).split(':')[0];\n const allowedHosts = ['localhost', '127.0.0.1', '0.0.0.0'];\n if (host && !allowedHosts.includes(host)) {\n return res.status(400).json({ error: 'Blocked: Unrecognized or untrusted Host header' });\n }\n next();\n});\n`;
171
+ const appIndex = modifiedContent.indexOf(appMatch[0]);
172
+ const lineEnd = modifiedContent.indexOf('\n', appIndex);
173
+ modifiedContent = modifiedContent.slice(0, lineEnd + 1) + middleware + modifiedContent.slice(lineEnd + 1);
174
+ return {
175
+ modified: true,
176
+ content: modifiedContent,
177
+ description: `Injected strict Host header whitelist validation middleware into Express app (${appVar})`,
178
+ };
179
+ }
180
+ return { modified: false, content, description: 'Could not find Express app instance to inject host validation' };
181
+ }
182
+ /**
183
+ * 7. Path Traversal & Unsanitized Directory Escape Guard
184
+ */
185
+ static applyPathTraversalGuard(content) {
186
+ if (content.includes('Path Traversal Prohibited') || content.includes('directory traversal prohibited') || content.includes('pathTraversalGuard')) {
187
+ return { modified: false, content, description: 'Path traversal sanitization guard already present' };
188
+ }
189
+ let modifiedContent = content;
190
+ const appMatch = modifiedContent.match(/([a-zA-Z0-9_$]+)\s*=\s*(express\s*\(\)|createApp\s*\(\))/);
191
+ if (appMatch) {
192
+ const appVar = appMatch[1];
193
+ const middleware = `\n// Directory Path Traversal & Parameter Sanitization Guard\n${appVar}.use((req, res, next) => {\n const rawUrl = decodeURIComponent(req.url || '');\n if (rawUrl.includes('..') || rawUrl.includes('%2e%2e') || rawUrl.includes('%2E%2E')) {\n return res.status(400).json({ error: 'Access Denied: Path Traversal Prohibited' });\n }\n next();\n});\n`;
194
+ const appIndex = modifiedContent.indexOf(appMatch[0]);
195
+ const lineEnd = modifiedContent.indexOf('\n', appIndex);
196
+ modifiedContent = modifiedContent.slice(0, lineEnd + 1) + middleware + modifiedContent.slice(lineEnd + 1);
197
+ return {
198
+ modified: true,
199
+ content: modifiedContent,
200
+ description: `Injected path traversal rejection middleware into Express app (${appVar})`,
201
+ };
202
+ }
203
+ return { modified: false, content, description: 'Could not find Express app instance to inject path traversal guard' };
204
+ }
205
+ /**
206
+ * 8. Duplicate Request Idempotency & Concurrency Race Protection
207
+ */
208
+ static applyIdempotencyProtection(content) {
209
+ if (content.includes('processedIdempotencyKeys') || content.includes('seenIdempotencyKeys') || content.includes('Duplicate transaction detected')) {
210
+ return { modified: false, content, description: 'Idempotency deduplication middleware already present' };
211
+ }
212
+ let modifiedContent = content;
213
+ const appMatch = modifiedContent.match(/([a-zA-Z0-9_$]+)\s*=\s*(express\s*\(\)|createApp\s*\(\))/);
214
+ if (appMatch) {
215
+ const appVar = appMatch[1];
216
+ const middleware = `\n// Transactional Idempotency & Concurrency Race Guard\nconst processedIdempotencyKeys = new Set();\n${appVar}.use((req, res, next) => {\n const idemKey = req.headers['idempotency-key'];\n if (idemKey && ['POST', 'PUT', 'PATCH'].includes(req.method)) {\n if (processedIdempotencyKeys.has(idemKey)) {\n return res.status(409).json({ error: 'Conflict: Duplicate transaction detected for Idempotency-Key' });\n }\n processedIdempotencyKeys.add(idemKey);\n if (processedIdempotencyKeys.size > 1000) {\n const first = processedIdempotencyKeys.values().next().value;\n if (first) processedIdempotencyKeys.delete(first);\n }\n }\n next();\n});\n`;
217
+ const appIndex = modifiedContent.indexOf(appMatch[0]);
218
+ const lineEnd = modifiedContent.indexOf('\n', appIndex);
219
+ modifiedContent = modifiedContent.slice(0, lineEnd + 1) + middleware + modifiedContent.slice(lineEnd + 1);
220
+ return {
221
+ modified: true,
222
+ content: modifiedContent,
223
+ description: `Injected duplicate request idempotency & race condition protection into Express app (${appVar})`,
224
+ };
225
+ }
226
+ return { modified: false, content, description: 'Could not find Express app instance to inject idempotency protection' };
227
+ }
228
+ }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * FastAPI / Python Remediation Transformers
3
+ * Injects defensive security and timeout middleware into FastAPI applications.
4
+ */
5
+ import { TransformerResult } from './ExpressTransformers.js';
6
+ export declare class FastApiTransformers {
7
+ /**
8
+ * 1. Defensive Headers & Trusted Host Middleware
9
+ */
10
+ static applyDefensiveHeaders(content: string): TransformerResult;
11
+ /**
12
+ * 2. Payload Size Limit Middleware (HTTP 413)
13
+ */
14
+ static applyPayloadLimit(content: string): TransformerResult;
15
+ /**
16
+ * 3. CORS Lock-down
17
+ */
18
+ static applyCorsLockdown(content: string): TransformerResult;
19
+ }
@@ -0,0 +1,93 @@
1
+ /**
2
+ * FastAPI / Python Remediation Transformers
3
+ * Injects defensive security and timeout middleware into FastAPI applications.
4
+ */
5
+ export class FastApiTransformers {
6
+ /**
7
+ * 1. Defensive Headers & Trusted Host Middleware
8
+ */
9
+ static applyDefensiveHeaders(content) {
10
+ if (content.includes('TrustedHostMiddleware') || content.includes('X-Content-Type-Options')) {
11
+ return { modified: false, content, description: 'FastAPI security headers already configured' };
12
+ }
13
+ let modifiedContent = content;
14
+ const importStatement = `from starlette.middleware.trustedhost import TrustedHostMiddleware\nfrom starlette.middleware.base import BaseHTTPMiddleware\nfrom starlette.requests import Request\nfrom starlette.responses import Response\n`;
15
+ const middlewareClass = `
16
+ class SecurityHeadersMiddleware(BaseHTTPMiddleware):
17
+ async def dispatch(self, request: Request, call_next):
18
+ response: Response = await call_next(request)
19
+ response.headers["X-Content-Type-Options"] = "nosniff"
20
+ response.headers["X-Frame-Options"] = "DENY"
21
+ response.headers["Strict-Transport-Security"] = "max-age=31536000; includeSubDomains"
22
+ return response
23
+ `;
24
+ // Add imports at top
25
+ modifiedContent = `${importStatement}\n${modifiedContent}`;
26
+ // Find app = FastAPI()
27
+ const appMatch = modifiedContent.match(/([a-zA-Z0-9_$]+)\s*=\s*FastAPI\s*\(/);
28
+ if (appMatch) {
29
+ const appVar = appMatch[1];
30
+ const injection = `\n${middlewareClass}\n${appVar}.add_middleware(SecurityHeadersMiddleware)\n`;
31
+ const appIndex = modifiedContent.indexOf(appMatch[0]);
32
+ const lineEnd = modifiedContent.indexOf('\n', appIndex);
33
+ modifiedContent = modifiedContent.slice(0, lineEnd + 1) + injection + modifiedContent.slice(lineEnd + 1);
34
+ return {
35
+ modified: true,
36
+ content: modifiedContent,
37
+ description: `Injected SecurityHeadersMiddleware into FastAPI app (${appVar})`,
38
+ };
39
+ }
40
+ return { modified: false, content, description: 'Could not find FastAPI app instance' };
41
+ }
42
+ /**
43
+ * 2. Payload Size Limit Middleware (HTTP 413)
44
+ */
45
+ static applyPayloadLimit(content) {
46
+ if (content.includes('Payload Too Large') || content.includes('MAX_CONTENT_LENGTH')) {
47
+ return { modified: false, content, description: 'Payload limit already present' };
48
+ }
49
+ let modifiedContent = content;
50
+ const middlewareClass = `
51
+ # Enforce 1MB payload size limit
52
+ @app.middleware("http")
53
+ async def limit_payload_size(request, call_next):
54
+ content_length = request.headers.get("content-length")
55
+ if content_length and int(content_length) > 1024 * 1024:
56
+ from starlette.responses import JSONResponse
57
+ return JSONResponse(status_code=413, content={"error": "Payload Too Large", "limitBytes": 1048576})
58
+ return await call_next(request)
59
+ `;
60
+ const appMatch = modifiedContent.match(/app\s*=\s*FastAPI\s*\(/);
61
+ if (appMatch) {
62
+ const appIndex = modifiedContent.indexOf(appMatch[0]);
63
+ const lineEnd = modifiedContent.indexOf('\n', appIndex);
64
+ modifiedContent = modifiedContent.slice(0, lineEnd + 1) + middlewareClass + modifiedContent.slice(lineEnd + 1);
65
+ return {
66
+ modified: true,
67
+ content: modifiedContent,
68
+ description: 'Injected request payload size limiter (HTTP 413 on >1MB)',
69
+ };
70
+ }
71
+ return { modified: false, content, description: 'Could not locate app = FastAPI() instance' };
72
+ }
73
+ /**
74
+ * 3. CORS Lock-down
75
+ */
76
+ static applyCorsLockdown(content) {
77
+ if (!content.includes('CORSMiddleware')) {
78
+ return { modified: false, content, description: 'CORSMiddleware not in use' };
79
+ }
80
+ let modifiedContent = content;
81
+ let modified = false;
82
+ // Replace allow_origins=["*"] with explicit whitelist
83
+ if (modifiedContent.includes('allow_origins=["*"]') || modifiedContent.includes("allow_origins=['*']")) {
84
+ modifiedContent = modifiedContent.replace(/allow_origins=\[['"][*]['"]\]/g, 'allow_origins=["http://localhost:3000", "http://127.0.0.1:3000"]');
85
+ modified = true;
86
+ }
87
+ return {
88
+ modified,
89
+ content: modifiedContent,
90
+ description: modified ? 'Replaced wildcard CORS with explicit origin whitelist' : 'CORS configuration already restricted',
91
+ };
92
+ }
93
+ }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Go / Gin & net/http Remediation Transformers
3
+ * Injects defensive middleware and timeout configurations into Go applications.
4
+ */
5
+ import { TransformerResult } from './ExpressTransformers.js';
6
+ export declare class GoTransformers {
7
+ /**
8
+ * 1. Defensive Headers (nosniff, frame-options)
9
+ */
10
+ static applyDefensiveHeaders(content: string): TransformerResult;
11
+ /**
12
+ * 2. Request Body Limit (HTTP 413)
13
+ */
14
+ static applyPayloadLimit(content: string): TransformerResult;
15
+ /**
16
+ * 3. Slowloris Server Timeouts
17
+ */
18
+ static applyServerTimeouts(content: string): TransformerResult;
19
+ }
@@ -0,0 +1,106 @@
1
+ /**
2
+ * Go / Gin & net/http Remediation Transformers
3
+ * Injects defensive middleware and timeout configurations into Go applications.
4
+ */
5
+ export class GoTransformers {
6
+ /**
7
+ * 1. Defensive Headers (nosniff, frame-options)
8
+ */
9
+ static applyDefensiveHeaders(content) {
10
+ if (content.includes('X-Content-Type-Options') || content.includes('nosniff')) {
11
+ return { modified: false, content, description: 'Security headers already present in Go code' };
12
+ }
13
+ let modifiedContent = content;
14
+ // Detect Gin router (e.g. r := gin.Default() or router := gin.New())
15
+ const ginMatch = modifiedContent.match(/([a-zA-Z0-9_]+)\s*:=\s*gin\.(Default|New)\(\)/);
16
+ if (ginMatch) {
17
+ const routerVar = ginMatch[1];
18
+ const middleware = `
19
+ \t// Defensive Security Headers Middleware
20
+ \t${routerVar}.Use(func(c *gin.Context) {
21
+ \t\tc.Header("X-Content-Type-Options", "nosniff")
22
+ \t\tc.Header("X-Frame-Options", "DENY")
23
+ \t\tc.Header("Strict-Transport-Security", "max-age=31536000; includeSubDomains")
24
+ \t\tc.Next()
25
+ \t})
26
+ `;
27
+ modifiedContent = modifiedContent.replace(ginMatch[0], `${ginMatch[0]}${middleware}`);
28
+ return {
29
+ modified: true,
30
+ content: modifiedContent,
31
+ description: `Injected security headers middleware into Gin router (${routerVar})`,
32
+ };
33
+ }
34
+ return { modified: false, content, description: 'Could not find Gin router instance' };
35
+ }
36
+ /**
37
+ * 2. Request Body Limit (HTTP 413)
38
+ */
39
+ static applyPayloadLimit(content) {
40
+ if (content.includes('MaxBytesReader')) {
41
+ return { modified: false, content, description: 'MaxBytesReader payload limit already in use' };
42
+ }
43
+ let modifiedContent = content;
44
+ const ginMatch = modifiedContent.match(/([a-zA-Z0-9_]+)\s*:=\s*gin\.(Default|New)\(\)/);
45
+ if (ginMatch) {
46
+ const routerVar = ginMatch[1];
47
+ const middleware = `
48
+ \t// Enforce 1MB payload size limit (HTTP 413 on buffer overflow)
49
+ \t${routerVar}.Use(func(c *gin.Context) {
50
+ \t\tc.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, 1048576)
51
+ \t\tc.Next()
52
+ \t})
53
+ `;
54
+ // Ensure "net/http" is imported
55
+ if (!modifiedContent.includes('"net/http"')) {
56
+ modifiedContent = modifiedContent.replace(/import\s*\(/, 'import (\n\t"net/http"');
57
+ }
58
+ modifiedContent = modifiedContent.replace(ginMatch[0], `${ginMatch[0]}${middleware}`);
59
+ return {
60
+ modified: true,
61
+ content: modifiedContent,
62
+ description: `Configured 1MB request body limit using http.MaxBytesReader on ${routerVar}`,
63
+ };
64
+ }
65
+ return { modified: false, content, description: 'Could not locate Go router instance' };
66
+ }
67
+ /**
68
+ * 3. Slowloris Server Timeouts
69
+ */
70
+ static applyServerTimeouts(content) {
71
+ if (content.includes('ReadHeaderTimeout') || content.includes('ReadTimeout')) {
72
+ return { modified: false, content, description: 'Go HTTP server timeouts already configured' };
73
+ }
74
+ let modifiedContent = content;
75
+ // If using r.Run(":8080") or http.ListenAndServe
76
+ const runMatch = modifiedContent.match(/([a-zA-Z0-9_]+)\.Run\(([^)]*)\)/);
77
+ if (runMatch) {
78
+ const routerVar = runMatch[1];
79
+ const addr = runMatch[2] || '":8080"';
80
+ const replacement = `
81
+ \tsrv := &http.Server{
82
+ \t\tAddr: ${addr},
83
+ \t\tHandler: ${routerVar},
84
+ \t\tReadHeaderTimeout: 5 * time.Second,
85
+ \t\tReadTimeout: 10 * time.Second,
86
+ \t\tWriteTimeout: 15 * time.Second,
87
+ \t}
88
+ \tsrv.ListenAndServe()
89
+ `;
90
+ // Ensure time and net/http are imported
91
+ if (!modifiedContent.includes('"time"')) {
92
+ modifiedContent = modifiedContent.replace(/import\s*\(/, 'import (\n\t"time"');
93
+ }
94
+ if (!modifiedContent.includes('"net/http"')) {
95
+ modifiedContent = modifiedContent.replace(/import\s*\(/, 'import (\n\t"net/http"');
96
+ }
97
+ modifiedContent = modifiedContent.replace(runMatch[0], replacement.trim());
98
+ return {
99
+ modified: true,
100
+ content: modifiedContent,
101
+ description: 'Replaced unbounded Run() with hardened http.Server enforcing ReadHeaderTimeout and ReadTimeout',
102
+ };
103
+ }
104
+ return { modified: false, content, description: 'Could not locate router.Run() call to configure server timeouts' };
105
+ }
106
+ }
@@ -0,0 +1,59 @@
1
+ export type BackendFramework = 'express' | 'fastify' | 'koa' | 'nestjs' | 'fastapi' | 'flask' | 'django' | 'go-gin' | 'go-chi' | 'go-nethttp' | 'rust-actix' | 'rust-axum' | 'java-spring' | 'csharp-dotnet' | 'generic-node' | 'generic-python' | 'generic-go' | 'generic-rust' | 'generic-java' | 'generic-csharp' | 'generic-backend';
2
+ export type AiProviderType = 'ollama' | 'openai' | 'anthropic' | 'gemini' | 'custom';
3
+ export interface AiProviderConfig {
4
+ provider: AiProviderType;
5
+ endpoint?: string;
6
+ apiKey?: string;
7
+ model?: string;
8
+ }
9
+ export interface HealPatch {
10
+ id: string;
11
+ checkName: string;
12
+ filePath: string;
13
+ relativePath: string;
14
+ originalContent: string;
15
+ remediatedContent: string;
16
+ diff: string;
17
+ description: string;
18
+ framework: BackendFramework;
19
+ engine?: 'codemod' | 'ai-agent';
20
+ }
21
+ export interface HealScanOptions {
22
+ projectDir: string;
23
+ failedChecks?: string[];
24
+ aiConfig?: AiProviderConfig;
25
+ engineMode?: 'codemod' | 'ai' | 'hybrid';
26
+ }
27
+ export interface HealScanResult {
28
+ success: boolean;
29
+ framework: BackendFramework;
30
+ projectRoot: string;
31
+ entryFile?: string;
32
+ patches: HealPatch[];
33
+ warnings: string[];
34
+ engineUsed?: 'codemod' | 'ai-agent' | 'hybrid';
35
+ }
36
+ export interface HealApplyOptions {
37
+ projectDir: string;
38
+ patchIds?: string[];
39
+ failedChecks?: string[];
40
+ createBackup?: boolean;
41
+ aiConfig?: AiProviderConfig;
42
+ engineMode?: 'codemod' | 'ai' | 'hybrid';
43
+ }
44
+ export interface HealApplyResult {
45
+ success: boolean;
46
+ appliedCount: number;
47
+ appliedPatches: string[];
48
+ backupDir?: string;
49
+ errors?: string[];
50
+ }
51
+ export interface HealRollbackOptions {
52
+ projectDir: string;
53
+ backupDir: string;
54
+ }
55
+ export interface HealRollbackResult {
56
+ success: boolean;
57
+ restoredFiles: string[];
58
+ errors?: string[];
59
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,20 @@
1
+ /**
2
+ * FaultMesh — Autonomous Red Chaos Team Engine
3
+ * Agent Squadron Bridge: Loads and translates autonomous agent personas into active attack strategies.
4
+ */
5
+ import { RedTeamPersona, CampaignIntensity, AssaultWave } from './types.js';
6
+ export declare class EccAgentBridge {
7
+ private agentsDir;
8
+ private personas;
9
+ private initialized;
10
+ constructor(customAgentsDir?: string);
11
+ initialize(): Promise<void>;
12
+ getPersonas(): Promise<RedTeamPersona[]>;
13
+ getPersona(id: string): RedTeamPersona | undefined;
14
+ private parseAgentMarkdown;
15
+ private createFallbackPersona;
16
+ /**
17
+ * Translates active personas and chosen intensity into calibrated assault waves
18
+ */
19
+ generateCampaignWaves(intensity?: CampaignIntensity): AssaultWave[];
20
+ }