dvalincode 0.21.0 → 0.23.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 (144) hide show
  1. package/README.md +261 -27
  2. package/README.zh-CN.md +203 -23
  3. package/dist/agent/compact.d.ts +8 -0
  4. package/dist/agent/compact.js +44 -5
  5. package/dist/agent/compact.js.map +1 -1
  6. package/dist/agent/loop.d.ts +5 -0
  7. package/dist/agent/loop.js +18 -9
  8. package/dist/agent/loop.js.map +1 -1
  9. package/dist/agent/runner.d.ts +15 -3
  10. package/dist/agent/runner.js +99 -9
  11. package/dist/agent/runner.js.map +1 -1
  12. package/dist/agent/session.d.ts +7 -0
  13. package/dist/agent/session.js +32 -4
  14. package/dist/agent/session.js.map +1 -1
  15. package/dist/agent/types.d.ts +5 -1
  16. package/dist/agent/types.js.map +1 -1
  17. package/dist/audit/log.d.ts +5 -1
  18. package/dist/audit/log.js.map +1 -1
  19. package/dist/cli.js +2 -0
  20. package/dist/cli.js.map +1 -1
  21. package/dist/commands/agents.d.ts +11 -0
  22. package/dist/commands/agents.js +223 -0
  23. package/dist/commands/agents.js.map +1 -0
  24. package/dist/commands/dvalin.d.ts +7 -1
  25. package/dist/commands/dvalin.js +209 -9
  26. package/dist/commands/dvalin.js.map +1 -1
  27. package/dist/commands/mcpInstall.d.ts +24 -0
  28. package/dist/commands/mcpInstall.js +62 -17
  29. package/dist/commands/mcpInstall.js.map +1 -1
  30. package/dist/commands/provider.js +6 -1
  31. package/dist/commands/provider.js.map +1 -1
  32. package/dist/commands/run.js +4 -2
  33. package/dist/commands/run.js.map +1 -1
  34. package/dist/commands/security.d.ts +15 -0
  35. package/dist/commands/security.js +273 -22
  36. package/dist/commands/security.js.map +1 -1
  37. package/dist/dvalinCli.js +2 -0
  38. package/dist/dvalinCli.js.map +1 -1
  39. package/dist/harness/run.d.ts +8 -2
  40. package/dist/harness/run.js +1 -1
  41. package/dist/harness/run.js.map +1 -1
  42. package/dist/mcp/agents.d.ts +41 -0
  43. package/dist/mcp/agents.js +129 -0
  44. package/dist/mcp/agents.js.map +1 -0
  45. package/dist/mcp/install.d.ts +43 -6
  46. package/dist/mcp/install.js +104 -1
  47. package/dist/mcp/install.js.map +1 -1
  48. package/dist/mcp/server.js +10 -2
  49. package/dist/mcp/server.js.map +1 -1
  50. package/dist/providers/anthropic.js +14 -2
  51. package/dist/providers/anthropic.js.map +1 -1
  52. package/dist/providers/openaiCompatible.js +7 -6
  53. package/dist/providers/openaiCompatible.js.map +1 -1
  54. package/dist/providers/retry.d.ts +32 -0
  55. package/dist/providers/retry.js +150 -0
  56. package/dist/providers/retry.js.map +1 -0
  57. package/dist/providers/trustedBaseUrls.js +1 -1
  58. package/dist/providers/trustedBaseUrls.js.map +1 -1
  59. package/dist/providers/types.d.ts +10 -0
  60. package/dist/remediation/automate.d.ts +1 -1
  61. package/dist/remediation/automate.js +2 -1
  62. package/dist/remediation/automate.js.map +1 -1
  63. package/dist/remediation/cases.d.ts +1 -0
  64. package/dist/remediation/cases.js +1 -0
  65. package/dist/remediation/cases.js.map +1 -1
  66. package/dist/remediation/codeQualityExport.d.ts +25 -0
  67. package/dist/remediation/codeQualityExport.js +24 -0
  68. package/dist/remediation/codeQualityExport.js.map +1 -0
  69. package/dist/remediation/codexSecurity.d.ts +54 -0
  70. package/dist/remediation/codexSecurity.js +366 -0
  71. package/dist/remediation/codexSecurity.js.map +1 -0
  72. package/dist/remediation/evasion.d.ts +61 -0
  73. package/dist/remediation/evasion.js +190 -0
  74. package/dist/remediation/evasion.js.map +1 -0
  75. package/dist/remediation/fixLoop.d.ts +255 -0
  76. package/dist/remediation/fixLoop.js +639 -0
  77. package/dist/remediation/fixLoop.js.map +1 -0
  78. package/dist/remediation/fixLoopStats.d.ts +93 -0
  79. package/dist/remediation/fixLoopStats.js +244 -0
  80. package/dist/remediation/fixLoopStats.js.map +1 -0
  81. package/dist/remediation/rebase.d.ts +44 -0
  82. package/dist/remediation/rebase.js +114 -0
  83. package/dist/remediation/rebase.js.map +1 -0
  84. package/dist/remediation/reproduce.d.ts +47 -0
  85. package/dist/remediation/reproduce.js +75 -0
  86. package/dist/remediation/reproduce.js.map +1 -0
  87. package/dist/remediation/sarif.d.ts +14 -1
  88. package/dist/remediation/sarif.js +21 -3
  89. package/dist/remediation/sarif.js.map +1 -1
  90. package/dist/remediation/scannerSuite.d.ts +52 -3
  91. package/dist/remediation/scannerSuite.js +347 -88
  92. package/dist/remediation/scannerSuite.js.map +1 -1
  93. package/dist/remediation/verify.d.ts +8 -0
  94. package/dist/remediation/verify.js +24 -11
  95. package/dist/remediation/verify.js.map +1 -1
  96. package/dist/security/config.d.ts +8 -2
  97. package/dist/security/config.js +10 -3
  98. package/dist/security/config.js.map +1 -1
  99. package/dist/security/contracts.js +15 -0
  100. package/dist/security/contracts.js.map +1 -1
  101. package/dist/security/fixRecord.d.ts +103 -8
  102. package/dist/security/fixRecord.js +113 -11
  103. package/dist/security/fixRecord.js.map +1 -1
  104. package/dist/security/fixRecordFile.d.ts +11 -2
  105. package/dist/security/fixRecordFile.js +20 -2
  106. package/dist/security/fixRecordFile.js.map +1 -1
  107. package/dist/security/fixRecordSignature.d.ts +104 -0
  108. package/dist/security/fixRecordSignature.js +227 -0
  109. package/dist/security/fixRecordSignature.js.map +1 -0
  110. package/dist/security/guardedScan.d.ts +39 -0
  111. package/dist/security/guardedScan.js +45 -0
  112. package/dist/security/guardedScan.js.map +1 -0
  113. package/dist/security/onboarding.d.ts +28 -0
  114. package/dist/security/onboarding.js +124 -0
  115. package/dist/security/onboarding.js.map +1 -0
  116. package/dist/security/reproduceInCi.d.ts +44 -0
  117. package/dist/security/reproduceInCi.js +96 -0
  118. package/dist/security/reproduceInCi.js.map +1 -0
  119. package/dist/security/reverify.d.ts +130 -0
  120. package/dist/security/reverify.js +361 -0
  121. package/dist/security/reverify.js.map +1 -0
  122. package/dist/security/suppressionGuard.d.ts +58 -0
  123. package/dist/security/suppressionGuard.js +216 -0
  124. package/dist/security/suppressionGuard.js.map +1 -0
  125. package/dist/security/verifyRun.js +14 -3
  126. package/dist/security/verifyRun.js.map +1 -1
  127. package/dist/security/workflow.d.ts +11 -1
  128. package/dist/security/workflow.js +2 -0
  129. package/dist/security/workflow.js.map +1 -1
  130. package/dist/server/routes/config.js +2 -0
  131. package/dist/server/routes/config.js.map +1 -1
  132. package/dist/server/routes/remediation.js +6 -5
  133. package/dist/server/routes/remediation.js.map +1 -1
  134. package/dist/tools/editFile.js +9 -2
  135. package/dist/tools/editFile.js.map +1 -1
  136. package/dist/tools/registry.d.ts +4 -1
  137. package/dist/tools/registry.js +29 -9
  138. package/dist/tools/registry.js.map +1 -1
  139. package/dist/tools/runSecuritySuite.d.ts +3 -0
  140. package/dist/tools/runSecuritySuite.js +2 -2
  141. package/dist/tools/runSecuritySuite.js.map +1 -1
  142. package/dist/version.d.ts +1 -1
  143. package/dist/version.js +1 -1
  144. package/package.json +1 -1
@@ -0,0 +1,366 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { lstat, readFile, realpath, stat } from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { resolveWorkspaceRoot } from '../core/workspace.js';
5
+ import { buildRemediationPrompt, normalizeSarifPath, readSnippet } from './sarif.js';
6
+ const MAX_MANIFEST_BYTES = 4 * 1024 * 1024;
7
+ const MAX_FINDINGS_BYTES = 64 * 1024 * 1024;
8
+ const MAX_COVERAGE_BYTES = 16 * 1024 * 1024;
9
+ const MAX_FINDINGS = 200;
10
+ /**
11
+ * Read a completed Codex Security scan through its documented portable
12
+ * artifacts. This deliberately does not inspect Codex Security's private state
13
+ * or invoke its model runtime: the sealed manifest is the handoff boundary.
14
+ */
15
+ export async function importCodexSecurityScan(scanDirectory, workspace) {
16
+ const root = await resolveWorkspaceRoot(workspace);
17
+ const scanRoot = await realpath(path.resolve(scanDirectory)).catch(() => undefined);
18
+ if (!scanRoot || !(await stat(scanRoot).catch(() => undefined))?.isDirectory()) {
19
+ throw new Error(`Codex Security scan directory does not exist or is not a directory: ${path.resolve(scanDirectory)}`);
20
+ }
21
+ const manifestPath = path.join(scanRoot, 'scan-manifest.json');
22
+ const manifestInfo = await lstat(manifestPath).catch(() => undefined);
23
+ if (!manifestInfo?.isFile() || manifestInfo.isSymbolicLink()) {
24
+ throw new Error(`Codex Security scan manifest is missing or not a regular file: ${manifestPath}`);
25
+ }
26
+ const manifest = await readJson(manifestPath, MAX_MANIFEST_BYTES, 'scan manifest');
27
+ if (manifest.documentType !== 'codex-security.scan-manifest' || manifest.schemaVersion !== '1.0') {
28
+ throw new Error('Unsupported Codex Security scan manifest; expected codex-security.scan-manifest schema 1.0');
29
+ }
30
+ const scan = objectAt(manifest, 'scan', 'Codex Security scan manifest');
31
+ const scanId = requiredString(scan, 'id', 'Codex Security scan manifest');
32
+ const status = requiredString(scan, 'status', 'Codex Security scan manifest');
33
+ if (status !== 'completed') {
34
+ throw new Error(`Codex Security scan ${scanId} is ${status}; only completed, sealed scans can be imported`);
35
+ }
36
+ const sealedAt = requiredString(scan, 'sealedAt', 'Codex Security scan manifest');
37
+ const producerObject = objectAt(scan, 'producer', 'Codex Security scan manifest');
38
+ const producer = {
39
+ name: requiredString(producerObject, 'name', 'Codex Security producer'),
40
+ version: requiredString(producerObject, 'version', 'Codex Security producer'),
41
+ };
42
+ const artifacts = parseArtifacts(scan.artifacts);
43
+ const findingsRef = requiredString(scan, 'findingsRef', 'Codex Security scan manifest');
44
+ const findingsArtifact = artifactFor(artifacts, findingsRef);
45
+ const findingsFile = await verifyArtifact(scanRoot, findingsArtifact, MAX_FINDINGS_BYTES);
46
+ const findingsDocument = parseJson(findingsFile.bytes, findingsFile.path, 'findings artifact');
47
+ validateFindingsDocument(findingsDocument, scanId);
48
+ const verifiedArtifacts = [{ path: findingsArtifact.path, sha256: findingsArtifact.sha256 }];
49
+ let coverageDocument;
50
+ let coveragePath;
51
+ const coverageRef = optionalString(scan.coverageRef);
52
+ if (coverageRef) {
53
+ const coverageArtifact = artifactFor(artifacts, coverageRef);
54
+ const coverageFile = await verifyArtifact(scanRoot, coverageArtifact, MAX_COVERAGE_BYTES);
55
+ coverageDocument = parseJson(coverageFile.bytes, coverageFile.path, 'coverage artifact');
56
+ validateCoverageDocument(coverageDocument, scanId);
57
+ coveragePath = coverageFile.path;
58
+ verifiedArtifacts.push({ path: coverageArtifact.path, sha256: coverageArtifact.sha256 });
59
+ }
60
+ const converted = await convertFindings(findingsDocument, root, scanId);
61
+ return {
62
+ source: 'Codex Security',
63
+ scanDirectory: scanRoot,
64
+ manifestPath,
65
+ findingsPath: findingsFile.path,
66
+ ...(coveragePath ? { coveragePath } : {}),
67
+ scan: {
68
+ id: scanId,
69
+ status: 'completed',
70
+ sealedAt,
71
+ producer,
72
+ ...(optionalString(scan.mode) ? { mode: optionalString(scan.mode) } : {}),
73
+ ...(asObject(scan.target) ? { target: asObject(scan.target) } : {}),
74
+ },
75
+ integrity: { sealed: true, verifiedArtifacts },
76
+ coverage: coverageFromArtifacts(scan, coverageDocument),
77
+ findings: converted.findings,
78
+ totalResults: converted.totalResults,
79
+ skippedResults: converted.skippedResults,
80
+ };
81
+ }
82
+ async function convertFindings(document, root, scanId) {
83
+ const rawFindings = document.findings;
84
+ const findings = [];
85
+ let skippedResults = 0;
86
+ for (const raw of rawFindings) {
87
+ if (findings.length >= MAX_FINDINGS) {
88
+ skippedResults += 1;
89
+ continue;
90
+ }
91
+ const finding = asObject(raw);
92
+ const locations = Array.isArray(finding?.locations) ? finding.locations : [];
93
+ const location = asObject(locations[0]);
94
+ const findingPath = await normalizeSarifPath(optionalString(location?.path), root);
95
+ if (!finding || !findingPath) {
96
+ skippedResults += 1;
97
+ continue;
98
+ }
99
+ const severity = asObject(finding.severity);
100
+ const level = optionalString(severity?.level) ?? 'medium';
101
+ const findingId = requiredString(finding, 'findingId', 'Codex Security finding');
102
+ const occurrenceId = optionalString(finding.occurrenceId);
103
+ const ruleId = requiredString(finding, 'ruleId', 'Codex Security finding');
104
+ const title = requiredString(finding, 'title', 'Codex Security finding');
105
+ const summary = requiredString(finding, 'summary', 'Codex Security finding');
106
+ const startLine = positiveInteger(location?.startLine);
107
+ const endLine = positiveInteger(location?.endLine);
108
+ const taxonomy = asObject(finding.taxonomy);
109
+ const confidence = asObject(finding.confidence);
110
+ const fingerprints = asObject(finding.fingerprints);
111
+ const tags = uniqueStrings([
112
+ 'security',
113
+ optionalString(taxonomy?.category),
114
+ ...stringArray(taxonomy?.cwe),
115
+ optionalString(confidence?.level) ? `confidence:${optionalString(confidence?.level)}` : undefined,
116
+ ]);
117
+ const snippet = await readSnippet(root, findingPath, startLine);
118
+ const score = typeof severity?.score === 'number' && Number.isFinite(severity.score)
119
+ ? String(severity.score)
120
+ : scoreForLevel(level);
121
+ const message = title === summary ? summary : `${title}: ${summary}`;
122
+ const base = {
123
+ id: occurrenceId ?? findingId,
124
+ source: 'Codex Security',
125
+ ruleId,
126
+ ruleName: title,
127
+ severity: sarifLevel(level),
128
+ securitySeverity: score,
129
+ message,
130
+ path: findingPath,
131
+ startLine,
132
+ endLine,
133
+ tags,
134
+ snippet,
135
+ external: {
136
+ provider: 'codex-security',
137
+ scanId,
138
+ findingId,
139
+ ...(occurrenceId ? { occurrenceId } : {}),
140
+ ...(optionalString(fingerprints?.primary) ? { fingerprint: optionalString(fingerprints?.primary) } : {}),
141
+ },
142
+ };
143
+ const guidance = optionalString(finding.remediation);
144
+ const remediationTests = stringArray(finding.remediationTests);
145
+ const evidence = [
146
+ guidance ? `Codex Security remediation guidance: ${guidance}` : undefined,
147
+ remediationTests.length ? `Suggested regression checks:\n${remediationTests.map(test => `- ${test}`).join('\n')}` : undefined,
148
+ ].filter(Boolean).join('\n\n');
149
+ findings.push({
150
+ ...base,
151
+ prompt: [buildRemediationPrompt(base), evidence].filter(Boolean).join('\n\n'),
152
+ });
153
+ }
154
+ return { findings, totalResults: rawFindings.length, skippedResults };
155
+ }
156
+ function coverageFromArtifacts(scan, coverage) {
157
+ const scope = asObject(scan.scope);
158
+ const review = asObject(scan.review);
159
+ const includePaths = uniqueStrings([
160
+ ...stringArray(scope?.includePaths),
161
+ ...stringArray(coverage?.includePaths),
162
+ ]);
163
+ const excludePaths = uniqueStrings([
164
+ ...stringArray(scope?.excludePaths),
165
+ ...stringArray(review?.excludedPaths),
166
+ ...stringArray(coverage?.excludePaths),
167
+ ]);
168
+ const explicitExclusions = Array.isArray(coverage?.explicitExclusions)
169
+ ? coverage.explicitExclusions.map(asObject).filter(Boolean)
170
+ : [];
171
+ const exclusions = uniqueStrings([
172
+ ...excludePaths.map(entry => `${entry} (path excluded)`),
173
+ ...explicitExclusions.map(entry => {
174
+ const pattern = optionalString(entry.pattern) ?? 'unspecified path';
175
+ const reason = optionalString(entry.reason);
176
+ return reason ? `${pattern} — ${reason}` : pattern;
177
+ }),
178
+ ]);
179
+ const deferredEntries = Array.isArray(coverage?.deferred)
180
+ ? coverage.deferred.map(asObject).filter(Boolean)
181
+ : [];
182
+ const surfaces = Array.isArray(coverage?.surfaces)
183
+ ? coverage.surfaces.map(asObject).filter((surface) => Boolean(surface)).map(surface => ({
184
+ id: optionalString(surface.id) ?? 'unknown',
185
+ label: optionalString(surface.label) ?? optionalString(surface.id) ?? 'unknown',
186
+ disposition: optionalString(surface.disposition) ?? 'unknown',
187
+ }))
188
+ : [];
189
+ const openQuestionObjects = Array.isArray(coverage?.openQuestions)
190
+ ? coverage.openQuestions.map(asObject).filter(Boolean)
191
+ : [];
192
+ const openQuestions = uniqueStrings(openQuestionObjects.map(entry => optionalString(entry.question)));
193
+ const deferred = uniqueStrings([
194
+ ...deferredEntries.map(entry => {
195
+ const id = optionalString(entry.id);
196
+ const reason = optionalString(entry.reason) ?? 'deferred';
197
+ const paths = stringArray(entry.paths);
198
+ return `${id ? `${id}: ` : ''}${reason}${paths.length ? ` (${paths.join(', ')})` : ''}`;
199
+ }),
200
+ ...surfaces.filter(surface => surface.disposition === 'needs_follow_up').map(surface => `${surface.label}: needs follow-up`),
201
+ ...stringArray(scope?.limitations),
202
+ ]);
203
+ const notes = uniqueStrings([
204
+ ...stringArray(scan.warnings),
205
+ coverage ? undefined : 'The sealed scan did not include coverage.json; review scope is retained but completeness is unknown.',
206
+ openQuestions.length ? `${openQuestions.length} open review question(s) remain.` : undefined,
207
+ ]);
208
+ let status;
209
+ const declared = optionalString(coverage?.completeness);
210
+ if (!coverage || declared === 'unknown')
211
+ status = 'unknown';
212
+ else if (declared === 'partial' || deferred.length || openQuestions.length)
213
+ status = 'partial';
214
+ else
215
+ status = 'complete';
216
+ return {
217
+ status,
218
+ mode: optionalString(coverage?.mode) ?? optionalString(scan.mode),
219
+ includePaths,
220
+ excludePaths,
221
+ exclusions,
222
+ deferred,
223
+ openQuestions,
224
+ surfaces,
225
+ notes,
226
+ };
227
+ }
228
+ function validateFindingsDocument(document, scanId) {
229
+ if (document.documentType !== 'codex-security.findings' || document.schemaVersion !== '1.0') {
230
+ throw new Error('Unsupported Codex Security findings artifact; expected codex-security.findings schema 1.0');
231
+ }
232
+ if (document.scanId !== scanId)
233
+ throw new Error('Codex Security findings scanId does not match the sealed manifest');
234
+ if (!Array.isArray(document.findings))
235
+ throw new Error('Invalid Codex Security findings artifact: findings must be an array');
236
+ }
237
+ function validateCoverageDocument(document, scanId) {
238
+ if (document.documentType !== 'codex-security.coverage' || document.schemaVersion !== '1.0') {
239
+ throw new Error('Unsupported Codex Security coverage artifact; expected codex-security.coverage schema 1.0');
240
+ }
241
+ if (document.scanId !== scanId)
242
+ throw new Error('Codex Security coverage scanId does not match the sealed manifest');
243
+ }
244
+ function parseArtifacts(value) {
245
+ if (!Array.isArray(value) || value.length === 0)
246
+ throw new Error('Codex Security scan manifest has no sealed artifacts');
247
+ return value.map((raw, index) => {
248
+ const artifact = asObject(raw);
249
+ if (!artifact)
250
+ throw new Error(`Invalid sealed artifact at index ${index}`);
251
+ const artifactPath = requiredString(artifact, 'path', `sealed artifact ${index}`);
252
+ const sha256 = requiredString(artifact, 'sha256', `sealed artifact ${index}`);
253
+ if (!/^[a-f0-9]{64}$/.test(sha256))
254
+ throw new Error(`Invalid SHA-256 for sealed artifact ${artifactPath}`);
255
+ return { path: artifactPath, sha256, mediaType: optionalString(artifact.mediaType) };
256
+ });
257
+ }
258
+ function artifactFor(artifacts, reference) {
259
+ const matches = artifacts.filter(artifact => artifact.path === reference);
260
+ if (matches.length !== 1)
261
+ throw new Error(`Codex Security manifest must seal exactly one ${reference} artifact`);
262
+ return matches[0];
263
+ }
264
+ async function verifyArtifact(scanRoot, artifact, maxBytes) {
265
+ const artifactPath = await containedArtifactPath(scanRoot, artifact.path);
266
+ const bytes = await readBytesWithLimit(artifactPath, maxBytes, `Codex Security artifact ${artifact.path}`);
267
+ const actual = createHash('sha256').update(bytes).digest('hex');
268
+ if (actual !== artifact.sha256)
269
+ throw new Error(`Codex Security artifact hash mismatch: ${artifact.path}`);
270
+ return { path: artifactPath, bytes };
271
+ }
272
+ async function containedArtifactPath(scanRoot, artifactPath) {
273
+ if (!artifactPath || artifactPath.includes('\\') || artifactPath.includes('\0') || path.posix.isAbsolute(artifactPath)) {
274
+ throw new Error(`Unsafe Codex Security artifact path: ${artifactPath}`);
275
+ }
276
+ const parts = artifactPath.split('/');
277
+ if (parts.some(part => !part || part === '.' || part === '..'))
278
+ throw new Error(`Unsafe Codex Security artifact path: ${artifactPath}`);
279
+ const candidate = path.resolve(scanRoot, ...parts);
280
+ const relative = path.relative(scanRoot, candidate);
281
+ if (!relative || relative === '..' || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {
282
+ throw new Error(`Unsafe Codex Security artifact path: ${artifactPath}`);
283
+ }
284
+ const info = await lstat(candidate).catch(() => undefined);
285
+ if (!info?.isFile() || info.isSymbolicLink())
286
+ throw new Error(`Codex Security artifact is missing or not a regular file: ${artifactPath}`);
287
+ const canonical = await realpath(candidate);
288
+ const canonicalRelative = path.relative(scanRoot, canonical);
289
+ if (canonicalRelative === '..' || canonicalRelative.startsWith(`..${path.sep}`) || path.isAbsolute(canonicalRelative)) {
290
+ throw new Error(`Codex Security artifact escapes the scan directory: ${artifactPath}`);
291
+ }
292
+ return canonical;
293
+ }
294
+ async function readJson(file, maxBytes, label) {
295
+ const bytes = await readBytesWithLimit(file, maxBytes, label);
296
+ return parseJson(bytes, file, label);
297
+ }
298
+ async function readBytesWithLimit(file, maxBytes, label) {
299
+ const info = await stat(file).catch(() => undefined);
300
+ if (!info?.isFile())
301
+ throw new Error(`Cannot read ${label}: ${file}`);
302
+ if (info.size > maxBytes)
303
+ throw new Error(`${label} exceeds the ${Math.floor(maxBytes / 1024 / 1024)} MiB import limit: ${file}`);
304
+ return readFile(file);
305
+ }
306
+ function parseJson(bytes, file, label) {
307
+ let value;
308
+ try {
309
+ value = JSON.parse(bytes.toString('utf8'));
310
+ }
311
+ catch (error) {
312
+ throw new Error(`Invalid JSON in ${label} ${file}: ${error instanceof Error ? error.message : String(error)}`);
313
+ }
314
+ const object = asObject(value);
315
+ if (!object)
316
+ throw new Error(`Invalid ${label}: expected a JSON object`);
317
+ return object;
318
+ }
319
+ function asObject(value) {
320
+ return value && typeof value === 'object' && !Array.isArray(value) ? value : undefined;
321
+ }
322
+ function objectAt(parent, key, label) {
323
+ const value = asObject(parent[key]);
324
+ if (!value)
325
+ throw new Error(`Invalid ${label}: ${key} must be an object`);
326
+ return value;
327
+ }
328
+ function requiredString(parent, key, label) {
329
+ const value = optionalString(parent[key]);
330
+ if (!value)
331
+ throw new Error(`Invalid ${label}: ${key} must be a non-empty string`);
332
+ return value;
333
+ }
334
+ function optionalString(value) {
335
+ return typeof value === 'string' && value.trim() ? value.trim() : undefined;
336
+ }
337
+ function stringArray(value) {
338
+ return Array.isArray(value) ? value.filter(item => typeof item === 'string' && item.trim()).map(item => item.trim()) : [];
339
+ }
340
+ function uniqueStrings(values) {
341
+ return [...new Set(values.filter((value) => Boolean(value)))];
342
+ }
343
+ function positiveInteger(value) {
344
+ return Number.isInteger(value) && Number(value) > 0 ? Number(value) : undefined;
345
+ }
346
+ function sarifLevel(level) {
347
+ if (level === 'critical' || level === 'high')
348
+ return 'error';
349
+ if (level === 'medium')
350
+ return 'warning';
351
+ if (level === 'low' || level === 'informational')
352
+ return 'note';
353
+ return 'warning';
354
+ }
355
+ function scoreForLevel(level) {
356
+ if (level === 'critical')
357
+ return '9.5';
358
+ if (level === 'high')
359
+ return '8.0';
360
+ if (level === 'medium')
361
+ return '5.0';
362
+ if (level === 'low')
363
+ return '2.0';
364
+ return '0.0';
365
+ }
366
+ //# sourceMappingURL=codexSecurity.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"codexSecurity.js","sourceRoot":"","sources":["../../src/remediation/codexSecurity.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,kBAAkB,CAAC;AACnE,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,oBAAoB,EAAE,MAAM,sBAAsB,CAAC;AAE5D,OAAO,EAAE,sBAAsB,EAAE,kBAAkB,EAAE,WAAW,EAA2B,MAAM,YAAY,CAAC;AAE9G,MAAM,kBAAkB,GAAG,CAAC,GAAG,IAAI,GAAG,IAAI,CAAC;AAC3C,MAAM,kBAAkB,GAAG,EAAE,GAAG,IAAI,GAAG,IAAI,CAAC;AAC5C,MAAM,kBAAkB,GAAG,EAAE,GAAG,IAAI,GAAG,IAAI,CAAC;AAC5C,MAAM,YAAY,GAAG,GAAG,CAAC;AA8CzB;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,uBAAuB,CAC3C,aAAqB,EACrB,SAAiB;IAEjB,MAAM,IAAI,GAAG,MAAM,oBAAoB,CAAC,SAAS,CAAC,CAAC;IACnD,MAAM,QAAQ,GAAG,MAAM,QAAQ,CAAC,IAAI,CAAC,OAAO,CAAC,aAAa,CAAC,CAAC,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC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,CAAC,KAAc;IACrC,OAAO,MAAM,CAAC,SAAS,CAAC,KAAK,CAAC,IAAI,MAAM,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;AAClF,CAAC;AAED,SAAS,UAAU,CAAC,KAAa;IAC/B,IAAI,KAAK,KAAK,UAAU,IAAI,KAAK,KAAK,MAAM;QAAE,OAAO,OAAO,CAAC;IAC7D,IAAI,KAAK,KAAK,QAAQ;QAAE,OAAO,SAAS,CAAC;IACzC,IAAI,KAAK,KAAK,KAAK,IAAI,KAAK,KAAK,eAAe;QAAE,OAAO,MAAM,CAAC;IAChE,OAAO,SAAS,CAAC;AACnB,CAAC;AAED,SAAS,aAAa,CAAC,KAAa;IAClC,IAAI,KAAK,KAAK,UAAU;QAAE,OAAO,KAAK,CAAC;IACvC,IAAI,KAAK,KAAK,MAAM;QAAE,OAAO,KAAK,CAAC;IACnC,IAAI,KAAK,KAAK,QAAQ;QAAE,OAAO,KAAK,CAAC;IACrC,IAAI,KAAK,KAAK,KAAK;QAAE,OAAO,KAAK,CAAC;IAClC,OAAO,KAAK,CAAC;AACf,CAAC"}
@@ -0,0 +1,61 @@
1
+ import type { SecurityFindingSnapshot } from '../security/contracts.js';
2
+ import type { FixRecordEvasion } from '../security/fixRecord.js';
3
+ /**
4
+ * Ways to make a finding stop being reported without fixing it.
5
+ *
6
+ * The suppression guard handles the bluntest one — telling the scanner to
7
+ * look away. These are the next ones an agent under "until the scanner is
8
+ * clean" pressure reaches for, and each is visible in the diff:
9
+ *
10
+ * - **equivalent sink**: the dangerous call is rewritten into a sibling the
11
+ * rule does not match — `eval(x)` becomes `new Function(x)()`, `exec(cmd)`
12
+ * becomes `spawn(cmd, { shell: true })`. The vulnerability is the same; only
13
+ * the spelling moved. Flagged when the change adds a sink of the same family
14
+ * as a target it claims to fix.
15
+ * - **target file deleted**: the finding is gone because the code is. Removing
16
+ * functionality may be right, but it is a product decision, not a repair, and
17
+ * it is made by a person in its own change.
18
+ * - **tests deleted or assertions removed**: the checks pass because they ask
19
+ * less. A fix that needs a test to stop asserting is not a fix.
20
+ *
21
+ * These are heuristics, and say so: a signal is a reason the loop will not
22
+ * call the change verified, with the evidence attached, not a claim of intent.
23
+ * What is not detected here — a sink in a family not listed, logic deleted
24
+ * inside a file that survives, untested changed lines — is not detected.
25
+ */
26
+ export type EvasionSignal = {
27
+ kind: 'equivalent-sink';
28
+ path: string;
29
+ line: number;
30
+ family: SinkFamily;
31
+ text: string;
32
+ } | {
33
+ kind: 'target-file-deleted';
34
+ path: string;
35
+ ruleId: string;
36
+ } | {
37
+ kind: 'test-deleted';
38
+ path: string;
39
+ } | {
40
+ kind: 'assertions-removed';
41
+ path: string;
42
+ removed: number;
43
+ };
44
+ export type SinkFamily = 'code-execution' | 'command-execution' | 'sql' | 'html' | 'deserialization';
45
+ export declare function isTestPath(file: string): boolean;
46
+ export declare function sinkFamilyOf(finding: Pick<SecurityFindingSnapshot, 'ruleId' | 'message'>): SinkFamily | undefined;
47
+ export declare function detectEvasion(cwd: string, baseCommit: string, targets: SecurityFindingSnapshot[], options?: {
48
+ exempt?: string[];
49
+ }): Promise<EvasionSignal[]>;
50
+ /** The record's form of a signal: location and kind, no code (FV-15). */
51
+ export declare function toRecordEvasion(signal: EvasionSignal): FixRecordEvasion;
52
+ export declare function describeEvasion(signal: EvasionSignal): string;
53
+ export declare function evasionKey(signal: EvasionSignal): string;
54
+ /** Added and removed lines per file from a zero-context diff, new-side line numbers for additions. */
55
+ export declare function parseDiff(diff: string): {
56
+ added: Map<string, Array<{
57
+ line: number;
58
+ text: string;
59
+ }>>;
60
+ removed: Map<string, string[]>;
61
+ };
@@ -0,0 +1,190 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { readFile } from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { promisify } from 'node:util';
5
+ const execFileAsync = promisify(execFile);
6
+ /** Which family a finding belongs to, read from its rule and message. */
7
+ const FAMILY_OF_FINDING = [
8
+ { family: 'code-execution', pattern: /\beval\b|code[-_ ]?injection|dynamic code|function constructor/i },
9
+ { family: 'command-execution', pattern: /command[-_ ]?injection|os[-_ ]?command|shell|child[-_ ]?process|subprocess/i },
10
+ { family: 'sql', pattern: /\bsql\b|sqli/i },
11
+ { family: 'html', pattern: /xss|cross[-_ ]?site|html[-_ ]?injection|innerhtml|dangerously/i },
12
+ { family: 'deserialization', pattern: /deserializ|pickle|unserialize|yaml\.load/i },
13
+ ];
14
+ /** Dangerous calls per family. A fix for that family that adds one of these has moved the sink, not removed it. */
15
+ const SINKS = {
16
+ 'code-execution': [
17
+ /\beval\s*\(/,
18
+ /\bnew\s+Function\s*\(/,
19
+ /\b(?:setTimeout|setInterval)\s*\(\s*['"`]/,
20
+ /\bvm\.(?:runIn\w*|compileFunction)\s*\(/,
21
+ /\bexec\s*\(\s*compile\s*\(/,
22
+ ],
23
+ 'command-execution': [
24
+ /\bshell\s*:\s*true\b/,
25
+ /\bshell\s*=\s*True\b/,
26
+ /\bexecSync\s*\(/,
27
+ /\bchild_process\.exec\s*\(/,
28
+ /\bos\.(?:system|popen)\s*\(/,
29
+ /\bRuntime\.getRuntime\(\)\.exec\s*\(/,
30
+ ],
31
+ sql: [
32
+ /['"`]\s*(?:SELECT|INSERT|UPDATE|DELETE)\b[^'"`]*['"`]\s*\+/i,
33
+ /\$\{[^}]+\}[^`]*\b(?:FROM|WHERE|VALUES|SET)\b|\b(?:SELECT|INSERT|UPDATE|DELETE)\b[^`]*\$\{/i,
34
+ /\.(?:raw|unsafe|queryRaw|executeRaw)\w*\s*\(/,
35
+ /\bf['"]\s*(?:SELECT|INSERT|UPDATE|DELETE)\b/i,
36
+ ],
37
+ html: [
38
+ /\b(?:innerHTML|outerHTML)\s*=/,
39
+ /\bdangerouslySetInnerHTML\b/,
40
+ /\binsertAdjacentHTML\s*\(/,
41
+ /\bdocument\.write(?:ln)?\s*\(/,
42
+ /\bv-html\b/,
43
+ /\|\s*safe\b|\bmark_safe\s*\(/,
44
+ ],
45
+ deserialization: [
46
+ /\bpickle\.loads?\s*\(/,
47
+ /\byaml\.load\s*\((?![^)]*SafeLoader)/,
48
+ /\bunserialize\s*\(/,
49
+ /\bObjectInputStream\b/,
50
+ /\bMarshal\.load\b/,
51
+ ],
52
+ };
53
+ const TEST_PATH = /(?:^|\/)(?:tests?|specs?|__tests__|testdata)\/|(?:^|\/)[^/]*\.(?:test|spec)\.[cm]?[jt]sx?$|(?:^|\/)test_[^/]*\.py$|(?:^|\/)[^/]*_test\.(?:py|go)$|(?:^|\/)[^/]*Tests?\.(?:java|kt|cs)$/i;
54
+ const ASSERTION = /\b(?:expect|assert\w*|should|t\.(?:Error|Fatal)\w*|require\.\w+|verify)\b/;
55
+ export function isTestPath(file) {
56
+ return TEST_PATH.test(file.split('\\').join('/'));
57
+ }
58
+ export function sinkFamilyOf(finding) {
59
+ const text = `${finding.ruleId} ${finding.message}`;
60
+ return FAMILY_OF_FINDING.find(entry => entry.pattern.test(text))?.family;
61
+ }
62
+ export async function detectEvasion(cwd, baseCommit, targets, options = {}) {
63
+ const exempt = new Set(options.exempt ?? []);
64
+ const signals = [];
65
+ const status = await git(cwd, ['diff', '--name-status', '--no-renames', '--relative', baseCommit, '--', '.']);
66
+ const deleted = new Set();
67
+ for (const line of status.split('\n').filter(Boolean)) {
68
+ const [code, file] = line.split('\t');
69
+ if (code?.startsWith('D') && file)
70
+ deleted.add(file);
71
+ }
72
+ for (const target of targets) {
73
+ if (deleted.has(target.path))
74
+ signals.push({ kind: 'target-file-deleted', path: target.path, ruleId: target.ruleId });
75
+ }
76
+ for (const file of deleted) {
77
+ if (isTestPath(file) && !exempt.has(file))
78
+ signals.push({ kind: 'test-deleted', path: file });
79
+ }
80
+ const diff = parseDiff(await git(cwd, ['diff', '--unified=0', '--no-color', '--no-ext-diff', '--relative', baseCommit, '--', '.']));
81
+ const untracked = (await git(cwd, ['ls-files', '--others', '--exclude-standard'])).split('\n').filter(Boolean);
82
+ const families = new Set(targets.map(sinkFamilyOf).filter((family) => Boolean(family)));
83
+ const addedLines = new Map(diff.added);
84
+ for (const file of untracked) {
85
+ if (addedLines.has(file))
86
+ continue;
87
+ const content = await readTracked(cwd, file);
88
+ addedLines.set(file, content.split('\n').map((text, index) => ({ line: index + 1, text })));
89
+ }
90
+ for (const [file, lines] of addedLines) {
91
+ // A test that exercises the vulnerable call is how reproduction works.
92
+ if (isTestPath(file) || exempt.has(file))
93
+ continue;
94
+ for (const { line, text } of lines) {
95
+ for (const family of families) {
96
+ if (SINKS[family].some(pattern => pattern.test(text))) {
97
+ signals.push({ kind: 'equivalent-sink', path: file, line, family, text: text.trim().slice(0, 160) });
98
+ break;
99
+ }
100
+ }
101
+ }
102
+ }
103
+ for (const [file, removed] of diff.removed) {
104
+ if (!isTestPath(file) || exempt.has(file) || deleted.has(file))
105
+ continue;
106
+ const lostAssertions = removed.filter(text => ASSERTION.test(text)).length
107
+ - (diff.added.get(file) ?? []).filter(({ text }) => ASSERTION.test(text)).length;
108
+ if (lostAssertions > 0)
109
+ signals.push({ kind: 'assertions-removed', path: file, removed: lostAssertions });
110
+ }
111
+ return signals;
112
+ }
113
+ /** The record's form of a signal: location and kind, no code (FV-15). */
114
+ export function toRecordEvasion(signal) {
115
+ switch (signal.kind) {
116
+ case 'equivalent-sink': return { kind: signal.kind, path: signal.path, line: signal.line, family: signal.family };
117
+ case 'target-file-deleted': return { kind: signal.kind, path: signal.path, ruleId: signal.ruleId };
118
+ case 'test-deleted': return { kind: signal.kind, path: signal.path };
119
+ case 'assertions-removed': return { kind: signal.kind, path: signal.path, removed: signal.removed };
120
+ }
121
+ }
122
+ export function describeEvasion(signal) {
123
+ switch (signal.kind) {
124
+ case 'equivalent-sink':
125
+ return `${signal.path}:${signal.line} adds a ${signal.family} sink (\`${signal.text}\`) — the same kind of call the fix was meant to remove`;
126
+ case 'target-file-deleted':
127
+ return `${signal.path} was deleted; ${signal.ruleId} is gone because the code is, which is a product decision for a person, not a repair`;
128
+ case 'test-deleted':
129
+ return `${signal.path} (a test) was deleted`;
130
+ case 'assertions-removed':
131
+ return `${signal.path} lost ${signal.removed} assertion(s)`;
132
+ }
133
+ }
134
+ export function evasionKey(signal) {
135
+ return signal.kind === 'equivalent-sink'
136
+ ? `evasion:${signal.kind}:${signal.path}:${signal.text}`
137
+ : `evasion:${signal.kind}:${signal.path}`;
138
+ }
139
+ /** Added and removed lines per file from a zero-context diff, new-side line numbers for additions. */
140
+ export function parseDiff(diff) {
141
+ const added = new Map();
142
+ const removed = new Map();
143
+ let oldFile;
144
+ let newFile;
145
+ let next = 0;
146
+ let inHeader = false;
147
+ for (const raw of diff.split('\n')) {
148
+ if (raw.startsWith('diff --git ')) {
149
+ inHeader = true;
150
+ oldFile = newFile = undefined;
151
+ continue;
152
+ }
153
+ if (inHeader) {
154
+ if (raw.startsWith('--- ')) {
155
+ const name = raw.slice(4).trim();
156
+ oldFile = name === '/dev/null' ? undefined : name.replace(/^a\//, '');
157
+ continue;
158
+ }
159
+ if (raw.startsWith('+++ ')) {
160
+ const name = raw.slice(4).trim();
161
+ newFile = name === '/dev/null' ? undefined : name.replace(/^b\//, '');
162
+ continue;
163
+ }
164
+ if (!raw.startsWith('@@'))
165
+ continue;
166
+ }
167
+ const hunk = /^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@/.exec(raw);
168
+ if (hunk) {
169
+ inHeader = false;
170
+ next = Number(hunk[1]);
171
+ continue;
172
+ }
173
+ if (raw.startsWith('+') && newFile) {
174
+ added.set(newFile, [...(added.get(newFile) ?? []), { line: next, text: raw.slice(1) }]);
175
+ next += 1;
176
+ }
177
+ else if (raw.startsWith('-') && oldFile) {
178
+ removed.set(oldFile, [...(removed.get(oldFile) ?? []), raw.slice(1)]);
179
+ }
180
+ }
181
+ return { added, removed };
182
+ }
183
+ async function readTracked(cwd, file) {
184
+ return readFile(path.join(cwd, file), 'utf8').catch(() => '');
185
+ }
186
+ async function git(cwd, args) {
187
+ const { stdout } = await execFileAsync('git', args, { cwd, maxBuffer: 64 * 1024 * 1024 });
188
+ return stdout;
189
+ }
190
+ //# sourceMappingURL=evasion.js.map