@shubh000/macrc 0.0.0-stage → 1.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.
- package/README.md +278 -2
- package/cli/lib/context-verifier.mjs +247 -0
- package/cli/lib/heuristic.mjs +440 -0
- package/cli/lib/output.mjs +109 -0
- package/cli/lib/policy.mjs +104 -0
- package/cli/lib/remediator.mjs +656 -0
- package/cli/lib/syntax-queries.mjs +169 -0
- package/cli/lib/targeted-llm.mjs +233 -0
- package/cli/macrc.js +2 -0
- package/cli/macrc.mjs +299 -0
- package/demo/bad-express-app/package.json +14 -0
- package/demo/bad-express-app/src/index.js +19 -0
- package/demo/bad-express-app/src/routes/users.js +16 -0
- package/demo/bad-express-app/src/services/api.js +21 -0
- package/package.json +42 -4
- package/tests/context-verifier.test.mjs +184 -0
- package/tests/fixtures/diff-after.json +36 -0
- package/tests/fixtures/diff-before.json +36 -0
- package/tests/integration.test.mjs +82 -0
- package/tests/remediator.test.mjs +181 -0
- package/tests/syntax-queries.test.mjs +98 -0
|
@@ -0,0 +1,656 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* MACRC Remediator: auto-patch generator for absent/partial Tier-1 dims.
|
|
3
|
+
*
|
|
4
|
+
* Each patch is a { file, description, search, replace } object.
|
|
5
|
+
* "search" is a string or regex to find the insertion point.
|
|
6
|
+
* "replace" is the replacement/insertion text.
|
|
7
|
+
*
|
|
8
|
+
* Exports:
|
|
9
|
+
* detectLanguage(cloneDir) → 'ts'|'js'|'py'|'go'|'rust'
|
|
10
|
+
* buildPatches(auditResult, cloneDir) → Patch[]
|
|
11
|
+
* applyPatches(patches, cloneDir, dryRun) → PatchReport
|
|
12
|
+
* formatPatchReport(report, {color}) → string
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import { readFileSync, writeFileSync, existsSync, readdirSync } from 'fs';
|
|
16
|
+
import { resolve, basename, extname, relative } from 'path';
|
|
17
|
+
import { execSync } from 'child_process';
|
|
18
|
+
|
|
19
|
+
// ── Language detection ────────────────────────────────────────────────────────
|
|
20
|
+
|
|
21
|
+
export function detectLanguage(cloneDir) {
|
|
22
|
+
if (existsSync(resolve(cloneDir, 'package.json'))) {
|
|
23
|
+
try {
|
|
24
|
+
const pkg = JSON.parse(readFileSync(resolve(cloneDir, 'package.json'), 'utf8'));
|
|
25
|
+
const all = { ...pkg.dependencies, ...pkg.devDependencies };
|
|
26
|
+
if (all['typescript'] || all['ts-node'] || all['@types/node']) return 'ts';
|
|
27
|
+
} catch {}
|
|
28
|
+
return 'js';
|
|
29
|
+
}
|
|
30
|
+
if (existsSync(resolve(cloneDir, 'requirements.txt')) ||
|
|
31
|
+
existsSync(resolve(cloneDir, 'pyproject.toml'))) return 'py';
|
|
32
|
+
if (existsSync(resolve(cloneDir, 'go.mod'))) return 'go';
|
|
33
|
+
if (existsSync(resolve(cloneDir, 'Cargo.toml'))) return 'rust';
|
|
34
|
+
return 'js';
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// ── File finders ──────────────────────────────────────────────────────────────
|
|
38
|
+
|
|
39
|
+
const SRC_EXT_RE = /\.(js|ts|mjs|cjs|py|go|rs)$/;
|
|
40
|
+
|
|
41
|
+
function listFiles(cloneDir) {
|
|
42
|
+
try {
|
|
43
|
+
const gitFiles = execSync('git ls-files', { cwd: cloneDir, timeout: 10000 })
|
|
44
|
+
.toString().split('\n').filter(Boolean);
|
|
45
|
+
// Empty means untracked/non-git working tree, fall through to filesystem walk
|
|
46
|
+
if (gitFiles.length > 0) return gitFiles;
|
|
47
|
+
} catch {}
|
|
48
|
+
// Fallback: filesystem walk (untracked/non-git dirs)
|
|
49
|
+
const results = [];
|
|
50
|
+
function walk(dir, depth) {
|
|
51
|
+
if (depth > 4) return;
|
|
52
|
+
try {
|
|
53
|
+
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
|
54
|
+
if (entry.name.startsWith('.') || entry.name === 'node_modules' || entry.name === 'dist') continue;
|
|
55
|
+
const full = resolve(dir, entry.name);
|
|
56
|
+
if (entry.isDirectory()) walk(full, depth + 1);
|
|
57
|
+
else results.push(relative(cloneDir, full).replace(/\\/g, '/'));
|
|
58
|
+
}
|
|
59
|
+
} catch {}
|
|
60
|
+
}
|
|
61
|
+
walk(cloneDir, 0);
|
|
62
|
+
return results;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function findMainServerFile(cloneDir, lang) {
|
|
66
|
+
const files = listFiles(cloneDir);
|
|
67
|
+
|
|
68
|
+
if (lang === 'ts' || lang === 'js') {
|
|
69
|
+
const priorities = ['src/index.ts','src/index.js','src/app.ts','src/app.js',
|
|
70
|
+
'index.ts','index.js','app.ts','app.js','server.ts','server.js',
|
|
71
|
+
'src/server.ts','src/server.js'];
|
|
72
|
+
for (const p of priorities) {
|
|
73
|
+
if (files.includes(p)) return p;
|
|
74
|
+
}
|
|
75
|
+
// Fall back: file with app.listen
|
|
76
|
+
return files.find(f => /\.(ts|js)$/.test(f) && (() => {
|
|
77
|
+
try { return readFileSync(resolve(cloneDir, f), 'utf8').includes('app.listen'); } catch { return false; }
|
|
78
|
+
})()) || null;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
if (lang === 'py') {
|
|
82
|
+
const priorities = ['main.py','app.py','src/main.py','src/app.py','api/main.py'];
|
|
83
|
+
for (const p of priorities) {
|
|
84
|
+
if (files.includes(p)) return p;
|
|
85
|
+
}
|
|
86
|
+
return files.find(f => /\.py$/.test(f) && (() => {
|
|
87
|
+
try { const c = readFileSync(resolve(cloneDir, f), 'utf8');
|
|
88
|
+
return c.includes('@app.') || c.includes('FastAPI') || c.includes('Flask'); } catch { return false; }
|
|
89
|
+
})()) || null;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
return null;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function findHttpCallFiles(cloneDir, lang) {
|
|
96
|
+
const TEST_RE = /\.(test|spec)\.|__tests__|\/tests?\//;
|
|
97
|
+
const files = listFiles(cloneDir);
|
|
98
|
+
if (lang === 'ts' || lang === 'js') {
|
|
99
|
+
return files.filter(f => /\.(ts|js|mjs)$/.test(f) && !TEST_RE.test(f) && (() => {
|
|
100
|
+
try { const c = readFileSync(resolve(cloneDir, f), 'utf8');
|
|
101
|
+
return /fetch\s*\(|axios\.(get|post|put|patch|delete|create)\s*\(/.test(c); } catch { return false; }
|
|
102
|
+
})());
|
|
103
|
+
}
|
|
104
|
+
if (lang === 'py') {
|
|
105
|
+
return files.filter(f => /\.py$/.test(f) && !TEST_RE.test(f) && (() => {
|
|
106
|
+
try { const c = readFileSync(resolve(cloneDir, f), 'utf8');
|
|
107
|
+
return /requests\.(get|post|put|patch|delete)\s*\(|httpx\./.test(c); } catch { return false; }
|
|
108
|
+
})());
|
|
109
|
+
}
|
|
110
|
+
return [];
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// ── Patch builders per dim ────────────────────────────────────────────────────
|
|
114
|
+
|
|
115
|
+
function patchHealthChecks(cloneDir, lang, notes) {
|
|
116
|
+
const patches = [];
|
|
117
|
+
const main = findMainServerFile(cloneDir, lang);
|
|
118
|
+
if (!main) return patches;
|
|
119
|
+
|
|
120
|
+
if (lang === 'ts' || lang === 'js') {
|
|
121
|
+
const content = readFileSync(resolve(cloneDir, main), 'utf8');
|
|
122
|
+
if (/['"`]\/(health|healthz|ping)\b/.test(content)) return patches; // already exists
|
|
123
|
+
|
|
124
|
+
const listenMatch = content.match(/app\.listen\s*\(/);
|
|
125
|
+
if (!listenMatch) return patches;
|
|
126
|
+
|
|
127
|
+
patches.push({
|
|
128
|
+
file: main,
|
|
129
|
+
description: 'Inject /health endpoint returning {status,uptime}',
|
|
130
|
+
search: 'app.listen(',
|
|
131
|
+
replace:
|
|
132
|
+
`app.get('/health', (_req, res) => res.json({ status: 'ok', uptime: process.uptime() }));
|
|
133
|
+
|
|
134
|
+
app.listen(`,
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
if (lang === 'py') {
|
|
139
|
+
const content = readFileSync(resolve(cloneDir, main), 'utf8');
|
|
140
|
+
if (/['"`]\/(health|healthz|ping)\b/.test(content)) return patches;
|
|
141
|
+
|
|
142
|
+
// Insert before the last line that starts the server
|
|
143
|
+
const uvicornMatch = content.match(/if __name__ == ['"]__main__['"]/);
|
|
144
|
+
const target = uvicornMatch ? 'if __name__ == ' : null;
|
|
145
|
+
|
|
146
|
+
if (target) {
|
|
147
|
+
patches.push({
|
|
148
|
+
file: main,
|
|
149
|
+
description: 'Inject /health endpoint returning {status: "ok"}',
|
|
150
|
+
search: 'if __name__ == ',
|
|
151
|
+
replace:
|
|
152
|
+
`@app.get("/health")
|
|
153
|
+
async def health_check():
|
|
154
|
+
return {"status": "ok", "uptime": True}
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
if __name__ == `,
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
return patches;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
function patchTimeoutHandling(cloneDir, lang) {
|
|
166
|
+
const patches = [];
|
|
167
|
+
const files = findHttpCallFiles(cloneDir, lang);
|
|
168
|
+
|
|
169
|
+
for (const relPath of files.slice(0, 5)) {
|
|
170
|
+
let content;
|
|
171
|
+
try { content = readFileSync(resolve(cloneDir, relPath), 'utf8'); } catch { continue; }
|
|
172
|
+
|
|
173
|
+
if (lang === 'ts' || lang === 'js') {
|
|
174
|
+
// axios.create({}) without timeout → inject timeout
|
|
175
|
+
if (/axios\.create\s*\(\s*\{/.test(content) && !/timeout\s*:/.test(content.match(/axios\.create\s*\(\{([^}]*)\}/)?.[0] || '')) {
|
|
176
|
+
patches.push({
|
|
177
|
+
file: relPath,
|
|
178
|
+
description: `Add default timeout to axios.create in ${basename(relPath)}`,
|
|
179
|
+
search: 'axios.create({',
|
|
180
|
+
replace: 'axios.create({ timeout: 10000,',
|
|
181
|
+
});
|
|
182
|
+
continue;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
// Direct axios.get/post calls without timeout in the same file → create an axios instance with timeout
|
|
186
|
+
if (/axios\.(get|post|put|patch|delete)\s*\(/.test(content) && !content.includes('axios.create') && !/timeout\s*:/.test(content)) {
|
|
187
|
+
const axiosImportLine = content.match(/^import axios.+$/m)?.[0];
|
|
188
|
+
if (axiosImportLine) {
|
|
189
|
+
patches.push({
|
|
190
|
+
file: relPath,
|
|
191
|
+
description: `Replace bare axios calls with a timeout-configured instance in ${basename(relPath)}`,
|
|
192
|
+
search: axiosImportLine,
|
|
193
|
+
replace: `${axiosImportLine}\nconst http = axios.create({ timeout: 10000 });`,
|
|
194
|
+
note: `Replace axios.get/post/... with http.get/post/... in ${basename(relPath)}`,
|
|
195
|
+
});
|
|
196
|
+
continue;
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
// Bare fetch(url) without signal → inject AbortSignal
|
|
201
|
+
if (/fetch\s*\(\s*\w/.test(content) && !/AbortSignal|AbortController/.test(content)) {
|
|
202
|
+
patches.push({
|
|
203
|
+
file: relPath,
|
|
204
|
+
description: `Wrap fetch calls with AbortSignal.timeout(10000) in ${basename(relPath)}`,
|
|
205
|
+
search: "fetch(",
|
|
206
|
+
replace: "fetch(",
|
|
207
|
+
note: 'Manual: add `signal: AbortSignal.timeout(10_000)` to each fetch options object',
|
|
208
|
+
manual: true,
|
|
209
|
+
});
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
if (lang === 'py') {
|
|
214
|
+
// requests.get(url) without timeout=
|
|
215
|
+
if (/requests\.(get|post|put|patch|delete)\s*\([^)]*\)/.test(content) && !/timeout\s*=/.test(content)) {
|
|
216
|
+
const updated = content.replace(
|
|
217
|
+
/requests\.(get|post|put|patch|delete)\s*\(([^)]+)\)/g,
|
|
218
|
+
(m, method, args) => {
|
|
219
|
+
if (args.includes('timeout')) return m;
|
|
220
|
+
return `requests.${method}(${args.trimEnd()}, timeout=10)`;
|
|
221
|
+
}
|
|
222
|
+
);
|
|
223
|
+
if (updated !== content) {
|
|
224
|
+
patches.push({
|
|
225
|
+
file: relPath,
|
|
226
|
+
description: `Add timeout=10 to requests calls in ${basename(relPath)}`,
|
|
227
|
+
directContent: updated,
|
|
228
|
+
});
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
return patches;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
function patchRetryLogic(cloneDir, lang) {
|
|
238
|
+
const patches = [];
|
|
239
|
+
|
|
240
|
+
if (lang === 'ts' || lang === 'js') {
|
|
241
|
+
let pkgPath = null;
|
|
242
|
+
try {
|
|
243
|
+
const raw = readFileSync(resolve(cloneDir, 'package.json'), 'utf8');
|
|
244
|
+
const pkg = JSON.parse(raw);
|
|
245
|
+
const hasPkg = pkg.dependencies?.['axios-retry'] || pkg.devDependencies?.['axios-retry'];
|
|
246
|
+
pkgPath = resolve(cloneDir, 'package.json');
|
|
247
|
+
|
|
248
|
+
// Find a file that imports axios (axios.create preferred, bare import accepted)
|
|
249
|
+
const httpFiles = findHttpCallFiles(cloneDir, lang);
|
|
250
|
+
const axiosFiles = httpFiles.filter(f => {
|
|
251
|
+
try { return /import axios|require\(['"]axios/.test(readFileSync(resolve(cloneDir, f), 'utf8')); } catch { return false; }
|
|
252
|
+
});
|
|
253
|
+
|
|
254
|
+
const target = axiosFiles[0];
|
|
255
|
+
if (target) {
|
|
256
|
+
const content = readFileSync(resolve(cloneDir, target), 'utf8');
|
|
257
|
+
if (!hasPkg) {
|
|
258
|
+
// Add axios-retry to package.json
|
|
259
|
+
patches.push({
|
|
260
|
+
file: 'package.json',
|
|
261
|
+
description: 'Add axios-retry dependency',
|
|
262
|
+
search: '"dependencies": {',
|
|
263
|
+
replace: '"dependencies": {\n "axios-retry": "^4.5.0",',
|
|
264
|
+
});
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
if (!/axiosRetry\s*\(/.test(content)) {
|
|
268
|
+
// Find the axios import line exactly so we don't double-import
|
|
269
|
+
const axiosImportLine = content.match(/^import axios.+$/m)?.[0];
|
|
270
|
+
if (axiosImportLine) {
|
|
271
|
+
patches.push({
|
|
272
|
+
file: target,
|
|
273
|
+
description: `Wire axios-retry to axios instance in ${basename(target)}`,
|
|
274
|
+
search: axiosImportLine,
|
|
275
|
+
replace:
|
|
276
|
+
`${axiosImportLine}
|
|
277
|
+
import axiosRetry from 'axios-retry';
|
|
278
|
+
axiosRetry(axios, { retries: 3, retryDelay: axiosRetry.exponentialDelay, retryCondition: axiosRetry.isNetworkOrIdempotentRequestError });`,
|
|
279
|
+
});
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
} catch {}
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
if (lang === 'py') {
|
|
287
|
+
// Add tenacity decorator to functions making external calls
|
|
288
|
+
const files = findHttpCallFiles(cloneDir, lang).slice(0, 3);
|
|
289
|
+
for (const relPath of files) {
|
|
290
|
+
let content;
|
|
291
|
+
try { content = readFileSync(resolve(cloneDir, relPath), 'utf8'); } catch { continue; }
|
|
292
|
+
if (/from tenacity|import tenacity/.test(content)) continue;
|
|
293
|
+
|
|
294
|
+
patches.push({
|
|
295
|
+
file: relPath,
|
|
296
|
+
description: `Add tenacity retry import and decorator hint in ${basename(relPath)}`,
|
|
297
|
+
search: 'import requests',
|
|
298
|
+
replace:
|
|
299
|
+
`from tenacity import retry, stop_after_attempt, wait_exponential
|
|
300
|
+
import requests`,
|
|
301
|
+
note: 'Add @retry(stop=stop_after_attempt(3), wait=wait_exponential()) decorator to each function that calls requests.*',
|
|
302
|
+
});
|
|
303
|
+
break; // one file for now
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
return patches;
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
function patchInputValidation(cloneDir, lang) {
|
|
311
|
+
const patches = [];
|
|
312
|
+
|
|
313
|
+
if (lang === 'ts' || lang === 'js') {
|
|
314
|
+
const files = listFiles(cloneDir)
|
|
315
|
+
.filter(f => /route|router|controller|handler/i.test(f) && /\.(ts|js)$/.test(f));
|
|
316
|
+
const target = files[0];
|
|
317
|
+
if (!target) return patches;
|
|
318
|
+
|
|
319
|
+
const content = readFileSync(resolve(cloneDir, target), 'utf8');
|
|
320
|
+
if (/validateBody|safeParse\s*\(\s*req/.test(content)) return patches;
|
|
321
|
+
|
|
322
|
+
// Find last import line to inject helper after the import block
|
|
323
|
+
const lastImportMatch = [...content.matchAll(/^import .+$/gm)].pop();
|
|
324
|
+
if (!lastImportMatch) return patches;
|
|
325
|
+
const anchor = lastImportMatch[0];
|
|
326
|
+
|
|
327
|
+
patches.push({
|
|
328
|
+
file: target,
|
|
329
|
+
description: `Inject validateBody middleware factory in ${basename(target)}`,
|
|
330
|
+
search: anchor,
|
|
331
|
+
replace:
|
|
332
|
+
`${anchor}
|
|
333
|
+
|
|
334
|
+
// MACRC: validateBody middleware factory, enforces schema at route entry points
|
|
335
|
+
function validateBody(schema) {
|
|
336
|
+
return (req, res, next) => {
|
|
337
|
+
const result = schema.safeParse(req.body);
|
|
338
|
+
if (!result.success) return res.status(400).json({ error: result.error.errors });
|
|
339
|
+
req.body = result.data;
|
|
340
|
+
next();
|
|
341
|
+
};
|
|
342
|
+
}`,
|
|
343
|
+
note: 'Add validateBody(YourSchema) as middleware before each POST/PUT/PATCH handler',
|
|
344
|
+
});
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
if (lang === 'py') {
|
|
348
|
+
const main = findMainServerFile(cloneDir, lang);
|
|
349
|
+
if (!main) return patches;
|
|
350
|
+
const content = readFileSync(resolve(cloneDir, main), 'utf8');
|
|
351
|
+
if (/BaseModel|pydantic/.test(content)) return patches;
|
|
352
|
+
|
|
353
|
+
patches.push({
|
|
354
|
+
file: main,
|
|
355
|
+
description: 'Add Pydantic request model import and usage hint',
|
|
356
|
+
search: 'from fastapi import',
|
|
357
|
+
replace:
|
|
358
|
+
`from pydantic import BaseModel
|
|
359
|
+
from fastapi import`,
|
|
360
|
+
note: 'Add `body: YourModel` parameter to POST/PUT/PATCH route functions to enforce validation',
|
|
361
|
+
});
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
return patches;
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
function patchDistributedAssumptions(cloneDir, lang, notes) {
|
|
368
|
+
const patches = [];
|
|
369
|
+
const files = listFiles(cloneDir);
|
|
370
|
+
const TEST_RE = /\.(test|spec)\.|__tests__|\/tests?\//;
|
|
371
|
+
const LOCALHOST_RE = /https?:\/\/localhost:\d+|https?:\/\/127\.0\.0\.1:\d+/g;
|
|
372
|
+
// Matches already-patched env-var expressions so we don't double-patch
|
|
373
|
+
const ALREADY_PATCHED_RE = /process\.env\.SERVICE_URL_|os\.environ\[.SERVICE_URL_/;
|
|
374
|
+
|
|
375
|
+
for (const relPath of files) {
|
|
376
|
+
if (TEST_RE.test(relPath)) continue;
|
|
377
|
+
if (!/\.(ts|js|mjs|py|go)$/.test(relPath)) continue;
|
|
378
|
+
|
|
379
|
+
let content;
|
|
380
|
+
try { content = readFileSync(resolve(cloneDir, relPath), 'utf8'); } catch { continue; }
|
|
381
|
+
|
|
382
|
+
// Skip files that already have env-var replacements (idempotency guard)
|
|
383
|
+
if (ALREADY_PATCHED_RE.test(content)) continue;
|
|
384
|
+
|
|
385
|
+
const matches = content.match(LOCALHOST_RE);
|
|
386
|
+
if (!matches) continue;
|
|
387
|
+
|
|
388
|
+
// One search/replace patch per unique localhost URL so we compose safely with other patches
|
|
389
|
+
const uniqueUrls = [...new Set(matches)];
|
|
390
|
+
const envKeys = uniqueUrls.map(url => {
|
|
391
|
+
const port = url.match(/:(\d+)/)?.[1] || '8080';
|
|
392
|
+
return `SERVICE_URL_${port}`;
|
|
393
|
+
});
|
|
394
|
+
for (const url of uniqueUrls) {
|
|
395
|
+
const port = url.match(/:(\d+)/)?.[1] || '8080';
|
|
396
|
+
const envKey = `SERVICE_URL_${port}`;
|
|
397
|
+
const replacement = lang === 'py' ? `os.environ["${envKey}"]` : `process.env.${envKey}`;
|
|
398
|
+
// one patch per occurrence so all instances are replaced
|
|
399
|
+
let remaining = content;
|
|
400
|
+
let occurrenceCount = 0;
|
|
401
|
+
while (remaining.includes(url)) { occurrenceCount++; remaining = remaining.replace(url, ''); }
|
|
402
|
+
for (let i = 0; i < occurrenceCount; i++) {
|
|
403
|
+
patches.push({
|
|
404
|
+
file: relPath,
|
|
405
|
+
description: `Replace hardcoded ${url} with process.env.${envKey} in ${basename(relPath)}`,
|
|
406
|
+
search: url,
|
|
407
|
+
replace: replacement,
|
|
408
|
+
...(i === 0 ? { note: `Set ${envKeys.join(', ')} env var(s) to the target service URLs in your .env file` } : {}),
|
|
409
|
+
});
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
// Also create .env.example entries
|
|
415
|
+
if (patches.length > 0) {
|
|
416
|
+
const envPath = resolve(cloneDir, '.env.example');
|
|
417
|
+
const existing = existsSync(envPath) ? readFileSync(envPath, 'utf8') : '';
|
|
418
|
+
const newVars = patches.flatMap(p => p.note ? [p.note.replace('Add ', '').split(' to your')[0]] : []).join('\n');
|
|
419
|
+
if (newVars && !existing.includes('SERVICE_URL_')) {
|
|
420
|
+
patches.push({
|
|
421
|
+
file: '.env.example',
|
|
422
|
+
description: 'Add service URL env var placeholders to .env.example',
|
|
423
|
+
directContent: existing + (existing.endsWith('\n') ? '' : '\n') + '# MACRC: service URLs for deployed environment\n' + newVars + '\n',
|
|
424
|
+
});
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
return patches;
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
function patchAuth(cloneDir, lang) {
|
|
432
|
+
const patches = [];
|
|
433
|
+
if (lang !== 'ts' && lang !== 'js') return patches;
|
|
434
|
+
|
|
435
|
+
const files = listFiles(cloneDir)
|
|
436
|
+
.filter(f => /route|router/i.test(f) && /\.(ts|js)$/.test(f));
|
|
437
|
+
const target = files[0];
|
|
438
|
+
if (!target) return patches;
|
|
439
|
+
const content = readFileSync(resolve(cloneDir, target), 'utf8');
|
|
440
|
+
if (/requireAuth|authenticate|verifyToken|passport/.test(content)) return patches;
|
|
441
|
+
|
|
442
|
+
// Anchor after the last import line so the stub lands at module scope
|
|
443
|
+
const lastImport = [...content.matchAll(/^import .+$/gm)].pop();
|
|
444
|
+
if (!lastImport) return patches;
|
|
445
|
+
const anchor = lastImport[0];
|
|
446
|
+
|
|
447
|
+
patches.push({
|
|
448
|
+
file: target,
|
|
449
|
+
description: `Inject requireAuth middleware stub in ${basename(target)}`,
|
|
450
|
+
search: anchor,
|
|
451
|
+
replace:
|
|
452
|
+
`${anchor}
|
|
453
|
+
|
|
454
|
+
// MACRC: requireAuth stub, replace with your actual auth middleware
|
|
455
|
+
function requireAuth(req, res, next) {
|
|
456
|
+
const token = req.headers.authorization?.split(' ')[1];
|
|
457
|
+
if (!token) return res.status(401).json({ error: 'Unauthorized' });
|
|
458
|
+
// TODO: verify token with jwt.verify(token, process.env.JWT_SECRET)
|
|
459
|
+
next();
|
|
460
|
+
}`,
|
|
461
|
+
note: 'Wire it: router.use(requireAuth) on protected route groups',
|
|
462
|
+
});
|
|
463
|
+
|
|
464
|
+
return patches;
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
function patchStatelessness(cloneDir, lang) {
|
|
468
|
+
const patches = [];
|
|
469
|
+
if (lang !== 'ts' && lang !== 'js') return patches;
|
|
470
|
+
|
|
471
|
+
const main = findMainServerFile(cloneDir, lang);
|
|
472
|
+
if (!main) return patches;
|
|
473
|
+
|
|
474
|
+
let content;
|
|
475
|
+
try { content = readFileSync(resolve(cloneDir, main), 'utf8'); } catch { return patches; }
|
|
476
|
+
|
|
477
|
+
// Only patch if express-session with no Redis store
|
|
478
|
+
if (!/express-session|session\s*\(/.test(content)) return patches;
|
|
479
|
+
if (/connect-redis|RedisStore/.test(content)) return patches;
|
|
480
|
+
|
|
481
|
+
const isESM = /^import\s+/m.test(content);
|
|
482
|
+
const sessionImportLine = content.match(
|
|
483
|
+
isESM ? /^import session.+$/m : /^const session = require\(.+\).*$/m
|
|
484
|
+
)?.[0];
|
|
485
|
+
if (!sessionImportLine) return patches;
|
|
486
|
+
|
|
487
|
+
if (isESM) {
|
|
488
|
+
patches.push({
|
|
489
|
+
file: main,
|
|
490
|
+
description: 'Add connect-redis imports for stateless session store',
|
|
491
|
+
note: 'npm install connect-redis ioredis, then apply this patch',
|
|
492
|
+
search: sessionImportLine,
|
|
493
|
+
replace:
|
|
494
|
+
`${sessionImportLine}
|
|
495
|
+
import connectRedis from 'connect-redis';
|
|
496
|
+
import { createClient } from 'ioredis';
|
|
497
|
+
|
|
498
|
+
const redisClient = createClient({ url: process.env.REDIS_URL || 'redis://localhost:6379' });
|
|
499
|
+
const RedisStore = connectRedis(session);`,
|
|
500
|
+
});
|
|
501
|
+
} else {
|
|
502
|
+
patches.push({
|
|
503
|
+
file: main,
|
|
504
|
+
description: 'Replace in-memory session store with connect-redis for stateless scaling',
|
|
505
|
+
note: 'npm install connect-redis ioredis, then apply this patch',
|
|
506
|
+
search: sessionImportLine,
|
|
507
|
+
replace:
|
|
508
|
+
`${sessionImportLine}
|
|
509
|
+
const connectRedis = require('connect-redis');
|
|
510
|
+
const { createClient } = require('ioredis');
|
|
511
|
+
|
|
512
|
+
const redisClient = createClient({ url: process.env.REDIS_URL || 'redis://localhost:6379' });
|
|
513
|
+
const RedisStore = connectRedis(session);`,
|
|
514
|
+
});
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
patches.push({
|
|
518
|
+
file: main,
|
|
519
|
+
description: 'Wire RedisStore into session middleware',
|
|
520
|
+
search: 'app.use(session({',
|
|
521
|
+
replace:
|
|
522
|
+
`app.use(session({
|
|
523
|
+
store: new RedisStore({ client: redisClient }),`,
|
|
524
|
+
});
|
|
525
|
+
|
|
526
|
+
return patches;
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
function patchLoadBalancingAwareness(cloneDir, lang) {
|
|
530
|
+
const patches = [...patchHealthChecks(cloneDir, lang, '')];
|
|
531
|
+
|
|
532
|
+
// Also try docker-compose
|
|
533
|
+
const composeFiles = ['docker-compose.yml', 'docker-compose.yaml'].filter(f =>
|
|
534
|
+
existsSync(resolve(cloneDir, f))
|
|
535
|
+
);
|
|
536
|
+
for (const f of composeFiles) {
|
|
537
|
+
const content = readFileSync(resolve(cloneDir, f), 'utf8');
|
|
538
|
+
if (/replicas/.test(content)) continue;
|
|
539
|
+
if (!/deploy:/.test(content)) {
|
|
540
|
+
// Find service definition and add deploy block
|
|
541
|
+
const serviceMatch = content.match(/^(\s{2})(\w+):\n(\s{4})image:/m);
|
|
542
|
+
if (serviceMatch) {
|
|
543
|
+
patches.push({
|
|
544
|
+
file: f,
|
|
545
|
+
description: `Add deploy.replicas: 2 to service in ${f}`,
|
|
546
|
+
search: serviceMatch[0],
|
|
547
|
+
replace: serviceMatch[0] + `${serviceMatch[1]} deploy:\n${serviceMatch[1]} replicas: 2\n`,
|
|
548
|
+
});
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
return patches;
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
// ── Main patch builder ────────────────────────────────────────────────────────
|
|
557
|
+
|
|
558
|
+
const TIER1_BUILDERS = {
|
|
559
|
+
health_checks: (d, l, n) => patchHealthChecks(d, l, n),
|
|
560
|
+
timeout_handling: (d, l) => patchTimeoutHandling(d, l),
|
|
561
|
+
retry_logic: (d, l) => patchRetryLogic(d, l),
|
|
562
|
+
input_validation: (d, l) => patchInputValidation(d, l),
|
|
563
|
+
distributed_assumptions: (d, l, n) => patchDistributedAssumptions(d, l, n),
|
|
564
|
+
auth: (d, l) => patchAuth(d, l),
|
|
565
|
+
statelessness: (d, l) => patchStatelessness(d, l),
|
|
566
|
+
load_balancing_awareness: (d, l) => patchLoadBalancingAwareness(d, l),
|
|
567
|
+
};
|
|
568
|
+
|
|
569
|
+
export function buildPatches(auditResult, cloneDir) {
|
|
570
|
+
const lang = detectLanguage(cloneDir);
|
|
571
|
+
const patches = [];
|
|
572
|
+
|
|
573
|
+
for (const [layer, dims] of Object.entries(auditResult.layers || {})) {
|
|
574
|
+
for (const [dim, result] of Object.entries(dims)) {
|
|
575
|
+
if (result.state !== 'absent' && result.state !== 'partial') continue;
|
|
576
|
+
const builder = TIER1_BUILDERS[dim];
|
|
577
|
+
if (!builder) continue;
|
|
578
|
+
const dimPatches = builder(cloneDir, lang, result.notes || '');
|
|
579
|
+
patches.push(...dimPatches.map(p => ({ ...p, _dim: dim, _state: result.state })));
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
return patches;
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
// ── Patch application ─────────────────────────────────────────────────────────
|
|
587
|
+
|
|
588
|
+
export function applyPatches(patches, cloneDir, dryRun = false) {
|
|
589
|
+
const report = { applied: [], skipped: [], errors: [], manual: [] };
|
|
590
|
+
|
|
591
|
+
for (const patch of patches) {
|
|
592
|
+
if (patch.manual) {
|
|
593
|
+
report.manual.push(patch);
|
|
594
|
+
continue;
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
const absPath = resolve(cloneDir, patch.file);
|
|
598
|
+
try {
|
|
599
|
+
if (patch.directContent !== undefined) {
|
|
600
|
+
// Full-file replacement
|
|
601
|
+
if (!dryRun) writeFileSync(absPath, patch.directContent, 'utf8');
|
|
602
|
+
report.applied.push({ ...patch, action: dryRun ? 'would-apply' : 'applied' });
|
|
603
|
+
continue;
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
let content;
|
|
607
|
+
try { content = readFileSync(absPath, 'utf8'); } catch {
|
|
608
|
+
// File doesn't exist yet (e.g. .env.example)
|
|
609
|
+
if (!dryRun) writeFileSync(absPath, patch.replace || '', 'utf8');
|
|
610
|
+
report.applied.push({ ...patch, action: dryRun ? 'would-create' : 'created' });
|
|
611
|
+
continue;
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
if (!content.includes(patch.search)) {
|
|
615
|
+
report.skipped.push({ ...patch, reason: 'search string not found' });
|
|
616
|
+
continue;
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
const updated = content.replace(patch.search, patch.replace);
|
|
620
|
+
if (!dryRun) writeFileSync(absPath, updated, 'utf8');
|
|
621
|
+
report.applied.push({ ...patch, action: dryRun ? 'would-apply' : 'applied' });
|
|
622
|
+
|
|
623
|
+
} catch (err) {
|
|
624
|
+
report.errors.push({ ...patch, error: err.message });
|
|
625
|
+
}
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
return report;
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
// ── Formatting ────────────────────────────────────────────────────────────────
|
|
632
|
+
|
|
633
|
+
export function formatPatchReport(report, { color = true } = {}) {
|
|
634
|
+
const G = color ? '\x1b[32m' : '', R = color ? '\x1b[31m' : '',
|
|
635
|
+
Y = color ? '\x1b[33m' : '', B = color ? '\x1b[2m' : '', X = color ? '\x1b[0m' : '';
|
|
636
|
+
const lines = ['\nMARC Remediator patches\n' + '─'.repeat(50)];
|
|
637
|
+
|
|
638
|
+
for (const p of report.applied) {
|
|
639
|
+
lines.push(`${G}✓${X} ${p._dim} → ${p.file} ${B}(${p.action})${X}`);
|
|
640
|
+
if (p.note) lines.push(` ${Y}note:${X} ${p.note}`);
|
|
641
|
+
}
|
|
642
|
+
for (const p of report.manual) {
|
|
643
|
+
lines.push(`${Y}⚐${X} ${p._dim} → ${p.file} ${B}(manual)${X}`);
|
|
644
|
+
if (p.note) lines.push(` ${Y}note:${X} ${p.note}`);
|
|
645
|
+
}
|
|
646
|
+
for (const p of report.skipped) {
|
|
647
|
+
lines.push(`${B}-${X} ${p._dim} -> ${p.file} ${B}(skipped: ${p.reason})${X}`);
|
|
648
|
+
}
|
|
649
|
+
for (const p of report.errors) {
|
|
650
|
+
lines.push(`${R}✗${X} ${p._dim} → ${p.file} ${R}ERROR: ${p.error}${X}`);
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
lines.push('─'.repeat(50));
|
|
654
|
+
lines.push(` ${report.applied.length} applied ${report.manual.length} manual ${report.skipped.length} skipped ${report.errors.length} errors`);
|
|
655
|
+
return lines.join('\n');
|
|
656
|
+
}
|