@clear-capabilities/agentic-security-scanner 0.175.0 → 0.177.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/CHANGELOG.md +25 -0
- package/bin/agentic-security.js +206 -28
- package/dist/1919.index.js +1 -1
- package/dist/2066.index.js +851 -0
- package/dist/2199.index.js +1 -1
- package/dist/2584.index.js +3350 -0
- package/dist/2923.index.js +13 -0
- package/dist/2946.index.js +81 -0
- package/dist/3196.index.js +27 -0
- package/dist/3727.index.js +292 -0
- package/dist/37d64df006576248d0d8.json +286 -0
- package/dist/4168.index.js +509 -0
- package/dist/4281.index.js +993 -0
- package/dist/5099.index.js +96 -0
- package/dist/5456.index.js +291 -0
- package/dist/5616.index.js +1471 -0
- package/dist/5620.index.js +2494 -0
- package/dist/5817.index.js +714 -0
- package/dist/5937.index.js +672 -0
- package/dist/6333.index.js +98 -0
- package/dist/6655.index.js +3221 -0
- package/dist/7838.index.js +491 -974
- package/dist/818.index.js +4 -3
- package/dist/83.index.js +159 -0
- package/dist/8551.index.js +82 -0
- package/dist/8633.index.js +93 -0
- package/dist/8714.index.js +76 -76
- package/dist/8825.index.js +84 -0
- package/dist/932.index.js +186 -0
- package/dist/9560.index.js +358 -19
- package/dist/9800.index.js +6 -1
- package/dist/agentic-security.mjs +10 -10
- package/dist/agentic-security.mjs.sha256 +1 -1
- package/dist/b4289e728659450b5e19.js +32 -0
- package/package.json +8 -4
- package/src/artifact/CLAUDE.md +4 -0
- package/src/artifact/artifact-evidence.js +63 -0
- package/src/artifact/cosign.js +61 -0
- package/src/artifact/engine-source.js +72 -0
- package/src/artifact/oci-layout.js +47 -0
- package/src/artifact/registry.js +213 -0
- package/src/capabilities/tool-registry.js +2 -0
- package/src/lineage/CLAUDE.md +4 -0
- package/src/lineage/identity-token.js +11 -0
- package/src/lineage/observation-adapters.js +13 -0
- package/src/lineage/runtime-edge-states.js +139 -0
- package/src/lineage/runtime-explorer-view.js +82 -0
- package/src/lineage/runtime-observation.js +11 -0
- package/src/mcp/CLAUDE.md +3 -1
- package/src/mcp/proof-tools.js +132 -0
- package/src/mcp/server.js +1 -1
- package/src/mcp/tools.js +3 -1
- package/src/posture/CLAUDE.md +23 -0
- package/src/posture/artifact-registry.js +4 -0
- package/src/posture/custom-rules.js +54 -8
- package/src/posture/dnr/attack-facts.js +31 -0
- package/src/posture/dnr/cli.js +138 -0
- package/src/posture/dnr/detection-ir.js +123 -0
- package/src/posture/dnr/exploit-correlation.js +25 -0
- package/src/posture/dnr/exposure-window.js +134 -0
- package/src/posture/dnr/hunt.js +84 -0
- package/src/posture/dnr/log-reader.js +189 -0
- package/src/posture/dnr/matchers.js +90 -0
- package/src/posture/dnr/outputs.js +262 -0
- package/src/posture/dnr/payload-classes.js +120 -0
- package/src/posture/dnr/redact.js +25 -0
- package/src/posture/dnr/store.js +57 -0
- package/src/posture/dnr/validate.js +64 -0
- package/src/posture/dnr/view.js +51 -0
- package/src/posture/evaluation/lab/arm-ollama.js +88 -0
- package/src/posture/evaluation/lab/arms.js +142 -0
- package/src/posture/evaluation/lab/cli.js +135 -0
- package/src/posture/evaluation/lab/dataset.js +139 -0
- package/src/posture/evaluation/lab/materialize.js +44 -0
- package/src/posture/evaluation/lab/neutralize.js +144 -0
- package/src/posture/evaluation/lab/report.js +194 -0
- package/src/posture/evaluation/lab/run.js +225 -0
- package/src/posture/evaluation/lab/score.js +135 -0
- package/src/posture/evaluation/lab/scoreboard.js +48 -0
- package/src/posture/evaluation/lab/stats.js +41 -0
- package/src/posture/evaluation/lab/store.js +53 -0
- package/src/posture/fleet/cli.js +260 -63
- package/src/posture/fleet/discover-edges.js +135 -0
- package/src/posture/fleet/enterprise-graph.js +189 -0
- package/src/posture/fleet/fleet-graph.js +9 -4
- package/src/posture/fleet/fleet-manifest.js +50 -5
- package/src/posture/fleet/job-runner.js +153 -0
- package/src/posture/fleet/job-store.js +138 -0
- package/src/posture/fleet/lineage-summary.js +55 -0
- package/src/posture/fleet/org-health.js +56 -0
- package/src/posture/fleet/scan-cache.js +112 -0
- package/src/posture/fleet/scan-child.js +32 -0
- package/src/posture/proof-fabric/cli.js +34 -6
- package/src/posture/proof-fabric/container.js +57 -0
- package/src/posture/proof-fabric/fix-proof.js +2 -1
- package/src/posture/proof-fabric/generate-python.js +129 -0
- package/src/posture/proof-fabric/generate.js +214 -0
- package/src/posture/proof-fabric/reproducer.js +3 -0
- package/src/posture/proof-fabric/runner.js +44 -13
- package/src/posture/proof-fabric/siblings.js +77 -0
- package/src/posture/routing/policy-router.js +103 -0
- package/src/posture/rule-compiler/cli.js +101 -9
- package/src/posture/rule-compiler/corpus.js +13 -9
- package/src/posture/rule-compiler/ir.js +52 -9
- package/src/posture/rule-compiler/mutation.js +72 -1
- package/src/posture/rule-compiler/promotion.js +21 -5
- package/src/posture/rule-compiler/proposal.js +137 -0
- package/src/posture/rule-compiler/regression.js +95 -0
- package/src/posture/rule-compiler/store.js +45 -1
- package/src/posture/rule-pack-signing.js +4 -2
|
@@ -0,0 +1,851 @@
|
|
|
1
|
+
export const id = 2066;
|
|
2
|
+
export const ids = [2066,2199];
|
|
3
|
+
export const modules = {
|
|
4
|
+
|
|
5
|
+
/***/ 92066:
|
|
6
|
+
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
7
|
+
|
|
8
|
+
// ESM COMPAT FLAG
|
|
9
|
+
__webpack_require__.r(__webpack_exports__);
|
|
10
|
+
|
|
11
|
+
// EXPORTS
|
|
12
|
+
__webpack_require__.d(__webpack_exports__, {
|
|
13
|
+
cmdProof: () => (/* binding */ cmdProof),
|
|
14
|
+
cmdProve: () => (/* binding */ cmdProve),
|
|
15
|
+
resolveReproducer: () => (/* binding */ resolveReproducer)
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
// EXTERNAL MODULE: external "node:fs"
|
|
19
|
+
var external_node_fs_ = __webpack_require__(73024);
|
|
20
|
+
// EXTERNAL MODULE: external "node:os"
|
|
21
|
+
var external_node_os_ = __webpack_require__(48161);
|
|
22
|
+
// EXTERNAL MODULE: external "node:path"
|
|
23
|
+
var external_node_path_ = __webpack_require__(76760);
|
|
24
|
+
// EXTERNAL MODULE: ./src/posture/state-dir.js
|
|
25
|
+
var state_dir = __webpack_require__(31174);
|
|
26
|
+
// EXTERNAL MODULE: ./src/posture/proof-fabric/orchestrator.js
|
|
27
|
+
var orchestrator = __webpack_require__(3740);
|
|
28
|
+
// EXTERNAL MODULE: ./src/posture/proof-fabric/store.js
|
|
29
|
+
var store = __webpack_require__(62199);
|
|
30
|
+
// EXTERNAL MODULE: ./src/posture/proof-fabric/runner.js + 1 modules
|
|
31
|
+
var runner = __webpack_require__(23081);
|
|
32
|
+
// EXTERNAL MODULE: ./src/posture/proof-fabric/reproducer.js
|
|
33
|
+
var proof_fabric_reproducer = __webpack_require__(37055);
|
|
34
|
+
// EXTERNAL MODULE: external "node:module"
|
|
35
|
+
var external_node_module_ = __webpack_require__(98995);
|
|
36
|
+
// EXTERNAL MODULE: ./node_modules/@babel/parser/lib/index.js
|
|
37
|
+
var lib = __webpack_require__(46411);
|
|
38
|
+
// EXTERNAL MODULE: external "node:child_process"
|
|
39
|
+
var external_node_child_process_ = __webpack_require__(31421);
|
|
40
|
+
;// CONCATENATED MODULE: ./src/posture/proof-fabric/generate-python.js
|
|
41
|
+
// Reproducer generation for Python (PRD 1), the second language of `generate.js`. Same contract: a DETERMINISTIC proposal built
|
|
42
|
+
// from the flagged file alone, then run through the ordinary runner, oracle, 3-of-3 repetition and independent replay. A generated
|
|
43
|
+
// reproducer is a proposal that execution either confirms or does not.
|
|
44
|
+
//
|
|
45
|
+
// Python is parsed by Python itself (`python3 -I -c`, the standard `ast` module, source on stdin, JSON on stdout) with a timeout, so
|
|
46
|
+
// the shape rules follow the real grammar. Two shapes, as in JavaScript:
|
|
47
|
+
// script the file reads `sys.argv[1]`: it is run with the payload as its argument (whether the flagged line is reached is then
|
|
48
|
+
// decided by execution, not assumed);
|
|
49
|
+
// function a module-level `def` around the flagged line: a generated harness imports the file (never as `__main__`, so its main
|
|
50
|
+
// guard does not run) and calls the function with the payload in every parameter.
|
|
51
|
+
// Only the standard library and sibling `.py` files in the flagged file's directory can be satisfied; any other import is refused,
|
|
52
|
+
// with the package named. Anything outside returns `{ ok: false }` with the reason, and nothing is executed.
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
const MAX_SOURCE = 256 * 1024;
|
|
59
|
+
const MAX_FILES = 8;
|
|
60
|
+
const fail = (reason, extra = {}) => ({ ok: false, reason, ...extra });
|
|
61
|
+
|
|
62
|
+
const ANALYZER = `
|
|
63
|
+
import ast, json, sys
|
|
64
|
+
src = sys.stdin.read()
|
|
65
|
+
try:
|
|
66
|
+
tree = ast.parse(src)
|
|
67
|
+
except SyntaxError as e:
|
|
68
|
+
print(json.dumps({"error": "syntax"})); sys.exit(0)
|
|
69
|
+
line = int(sys.argv[1])
|
|
70
|
+
imports = []
|
|
71
|
+
for n in ast.walk(tree):
|
|
72
|
+
if isinstance(n, ast.Import):
|
|
73
|
+
for a in n.names: imports.append({"module": a.name, "level": 0})
|
|
74
|
+
elif isinstance(n, ast.ImportFrom):
|
|
75
|
+
imports.append({"module": n.module or "", "level": n.level or 0, "names": [a.name for a in n.names]})
|
|
76
|
+
fns = []
|
|
77
|
+
for n in ast.walk(tree):
|
|
78
|
+
if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef)) and n.lineno <= line <= (n.end_lineno or n.lineno):
|
|
79
|
+
args = [a.arg for a in n.args.posonlyargs + n.args.args + n.args.kwonlyargs]
|
|
80
|
+
fns.append({"name": n.name, "start": n.lineno, "end": n.end_lineno, "args": args, "async": isinstance(n, ast.AsyncFunctionDef), "decorated": bool(n.decorator_list), "toplevel": n in tree.body, "defaults": len(n.args.defaults)})
|
|
81
|
+
fns.sort(key=lambda f: f["end"] - f["start"])
|
|
82
|
+
main_guard = any(isinstance(n, ast.If) and "__name__" in ast.dump(n.test) for n in tree.body)
|
|
83
|
+
print(json.dumps({"imports": imports, "functions": fns, "mainGuard": main_guard, "stdlib": sorted(sys.stdlib_module_names) if hasattr(sys, "stdlib_module_names") else None}))
|
|
84
|
+
`;
|
|
85
|
+
|
|
86
|
+
function analyze(text, line) {
|
|
87
|
+
const r = (0,external_node_child_process_.spawnSync)('python3', ['-I', '-c', ANALYZER, String(line)], { input: text, encoding: 'utf8', timeout: 10_000, maxBuffer: 4 * 1024 * 1024 });
|
|
88
|
+
if (r.error || r.status !== 0) return null;
|
|
89
|
+
try { return JSON.parse(r.stdout); } catch { return null; }
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function readInside(root, rel) {
|
|
93
|
+
let real; try { real = external_node_fs_.realpathSync(external_node_path_.resolve(root, rel)); } catch { return null; }
|
|
94
|
+
const base = external_node_fs_.realpathSync(root);
|
|
95
|
+
if (!(real === base || real.startsWith(base + external_node_path_.sep))) return null;
|
|
96
|
+
const st = external_node_fs_.statSync(real);
|
|
97
|
+
return st.isFile() && st.size <= MAX_SOURCE ? { real, text: external_node_fs_.readFileSync(real, 'utf8') } : null;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const HARNESS = (entry, name, args) => `# Generated by the proof fabric from the finding's own evidence. It imports the flagged module (never as __main__) and calls the function.
|
|
101
|
+
import importlib.util, sys, asyncio, inspect
|
|
102
|
+
payload = sys.argv[1] if len(sys.argv) > 1 else ""
|
|
103
|
+
spec = importlib.util.spec_from_file_location("target", ${JSON.stringify(entry)})
|
|
104
|
+
mod = importlib.util.module_from_spec(spec)
|
|
105
|
+
sys.modules["target"] = mod
|
|
106
|
+
spec.loader.exec_module(mod)
|
|
107
|
+
fn = getattr(mod, ${JSON.stringify(name)}, None)
|
|
108
|
+
if not callable(fn):
|
|
109
|
+
print("the function is not defined at module level", file=sys.stderr); sys.exit(3)
|
|
110
|
+
try:
|
|
111
|
+
res = fn(${args.join(', ')})
|
|
112
|
+
if inspect.isawaitable(res): asyncio.run(asyncio.wait_for(res, 5))
|
|
113
|
+
except Exception as e:
|
|
114
|
+
print("target raised:", str(e)[:200], file=sys.stderr)
|
|
115
|
+
`;
|
|
116
|
+
|
|
117
|
+
/** @param {{finding: object, root: string, cls: {name: string, payload: string, oracle: object, network?: string, watch?: object, needsPy?: RegExp}}} o */
|
|
118
|
+
function generatePythonReproducer({ finding, root, cls }) {
|
|
119
|
+
const rel = String(finding.file);
|
|
120
|
+
const src = readInside(root, rel);
|
|
121
|
+
if (!src) return fail('the flagged file is missing, outside the repository, or too large');
|
|
122
|
+
const info = analyze(src.text, finding.line);
|
|
123
|
+
if (!info || info.error) return fail('the flagged file could not be parsed by Python (is python3 installed and is the file valid Python 3?)');
|
|
124
|
+
const lines = src.text.split('\n');
|
|
125
|
+
const sinkLine = lines[finding.line - 1] ?? '';
|
|
126
|
+
const around = lines.slice(Math.max(0, finding.line - 3), finding.line + 2).join('\n');
|
|
127
|
+
if (cls.needsPy && !cls.needsPy.test(sinkLine) && !cls.needsPy.test(around)) return fail(`${cls.name}: the flagged code is not a write, and this class is only proven for write sinks`);
|
|
128
|
+
|
|
129
|
+
const stdlib = new Set(info.stdlib ?? []);
|
|
130
|
+
if (!info.stdlib) return fail('this Python is too old to list its standard library (3.10 or newer is needed), so imports cannot be classified');
|
|
131
|
+
const dir = external_node_path_.dirname(src.real); const rootReal = external_node_fs_.realpathSync(root);
|
|
132
|
+
const sources = {}; const external = [];
|
|
133
|
+
for (const imp of info.imports) {
|
|
134
|
+
const top = imp.module.split('.')[0];
|
|
135
|
+
if (imp.level === 0 && stdlib.has(top)) continue;
|
|
136
|
+
const sibling = imp.level <= 1 ? external_node_path_.join(dir, `${top || (imp.names?.[0] ?? '')}.py`) : null;
|
|
137
|
+
if (sibling && external_node_fs_.existsSync(sibling)) {
|
|
138
|
+
const dep = readInside(root, external_node_path_.relative(rootReal, external_node_fs_.realpathSync(sibling)));
|
|
139
|
+
if (!dep) return fail(`"${top}" is too large or outside the repository`);
|
|
140
|
+
const destRel = external_node_path_.relative(dir, dep.real);
|
|
141
|
+
if (!sources[destRel]) { if (Object.keys(sources).length >= MAX_FILES) return fail(`the file pulls in more than ${MAX_FILES} repository files`); sources[destRel] = external_node_path_.relative(rootReal, dep.real); }
|
|
142
|
+
continue;
|
|
143
|
+
}
|
|
144
|
+
external.push(top || '.'.repeat(imp.level));
|
|
145
|
+
}
|
|
146
|
+
if (external.length) return fail(`the flagged code needs ${[...new Set(external)].slice(0, 4).join(', ')}, which is not available in the proof environment; only the standard library and sibling files in the same directory can be satisfied`);
|
|
147
|
+
|
|
148
|
+
const entry = 'target.py';
|
|
149
|
+
sources[entry] = rel;
|
|
150
|
+
const assumptions = [];
|
|
151
|
+
const base = { schema: 'agentic-security/reproducer', version: 1, findingId: String(finding.stableId ?? finding.id ?? 'generated'), lang: 'python', oracle: cls.oracle, network: cls.network ?? 'none', ...(cls.watch ? { watch: cls.watch } : {}) };
|
|
152
|
+
if (cls.watch) assumptions.push('the write target is assumed to be one directory below the working directory (the payload is ../escaped.txt); if the code uses another base, the proof will not confirm it');
|
|
153
|
+
|
|
154
|
+
if (/sys\.argv\s*\[\s*1\s*\]/.test(src.text)) {
|
|
155
|
+
const reproducer = { ...base, sources, run: ['{{PYTHON}}', entry, cls.payload] };
|
|
156
|
+
const errs = (0,proof_fabric_reproducer/* validateReproducer */.mC)(reproducer);
|
|
157
|
+
return errs.length ? fail(`the generated reproducer is invalid: ${errs[0]}`) : { ok: true, reproducer, basis: { shape: 'script', class: cls.name, entry: rel, line: finding.line, assumptions } };
|
|
158
|
+
}
|
|
159
|
+
const fn = info.functions.find((f) => f.toplevel);
|
|
160
|
+
if (!fn) return fail('the flagged line is not inside a module-level function, and the file does not read sys.argv[1]');
|
|
161
|
+
if (fn.decorated) return fail(`${fn.name} is decorated (a web framework route, a cache, a wrapper): calling it directly would not match how it is reached, and the framework is not available`);
|
|
162
|
+
if (!fn.args.length) return fail('the function around the flagged line takes no parameters, so the payload has no way in');
|
|
163
|
+
if (fn.async) assumptions.push('the function is a coroutine; the harness awaits it for at most 5 seconds');
|
|
164
|
+
assumptions.push('the payload is passed in every parameter (a Python parameter has no request-like stand-in), which is an approximation of how the function is really called');
|
|
165
|
+
const harness = HARNESS(entry, fn.name, fn.args.map(() => 'payload'));
|
|
166
|
+
const reproducer = { ...base, sources, files: { 'harness.py': harness }, run: ['{{PYTHON}}', 'harness.py', cls.payload] };
|
|
167
|
+
const errs = (0,proof_fabric_reproducer/* validateReproducer */.mC)(reproducer);
|
|
168
|
+
return errs.length ? fail(`the generated reproducer is invalid: ${errs[0]}`) : { ok: true, reproducer, basis: { shape: 'function', class: cls.name, entry: rel, line: finding.line, function: `${fn.name}(${fn.args.join(', ')})`, assumptions } };
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
;// CONCATENATED MODULE: ./src/posture/proof-fabric/generate.js
|
|
172
|
+
// Reproducer generation from a finding's own evidence (PRD 1: `triage exploit --prove` with no hand-written reproducer).
|
|
173
|
+
//
|
|
174
|
+
// What this is: a DETERMINISTIC harness builder for the cases where a harness can be built from the source alone. It reads the
|
|
175
|
+
// flagged file, finds the function around the flagged line, decides how that function is reached, picks the payload for the
|
|
176
|
+
// weakness class, and emits an ordinary reproducer, which then goes through exactly the same runner, oracle, 3-of-3 repetition and
|
|
177
|
+
// independent replay as any other. A generated reproducer is not a verdict; it is a proposal that is either confirmed by execution
|
|
178
|
+
// or not.
|
|
179
|
+
//
|
|
180
|
+
// What this is not: a general exploit generator. It handles JavaScript (here) and Python (`generate-python.js`), and only code the proof environment can actually load:
|
|
181
|
+
// the file's imports must be Node built-ins or relative files inside the repository (a package from node_modules is not there in
|
|
182
|
+
// the sandbox, so a handler that needs `express` is refused, with the package named). Anything outside that returns `{ ok: false }`
|
|
183
|
+
// with the reason, and nothing is executed.
|
|
184
|
+
//
|
|
185
|
+
// Two shapes:
|
|
186
|
+
// script the file reads `process.argv[2]`: it is run with the payload as its argument;
|
|
187
|
+
// function the file exports (or declares at top level and exports) the function around the flagged line: a generated harness
|
|
188
|
+
// loads it and calls it, filling the tainted parameter with the payload. A parameter that is a request-like object
|
|
189
|
+
// (`req`) gets a stand-in whose `body`/`query`/`params` answer every property with the payload.
|
|
190
|
+
//
|
|
191
|
+
// Weakness classes with a payload and an oracle that can SEE the effect: CWE-78 (a canary file created by the injected command),
|
|
192
|
+
// CWE-22 (a write that lands outside the working directory, only for write sinks), CWE-918 (a request reaching the runner's loopback
|
|
193
|
+
// listener). Others (injection into a database, deserialization, memory safety) need an environment or a native harness this does not
|
|
194
|
+
// build, and are refused by name rather than approximated.
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
const CLASSES = {
|
|
203
|
+
'CWE-78': { name: 'command-injection', payload: 'x; touch {{CANARY:command}}', oracle: { type: 'command_execution', params: { canary: 'command' } } },
|
|
204
|
+
'CWE-22': { needsPy: /\bopen\s*\([^)]*['"][wax]b?\+?['"]|\.write_(?:text|bytes)\s*\(|\bshutil\.(?:copy|move)/, name: 'path-traversal', payload: '../escaped.txt', oracle: { type: 'filesystem_mutation', params: { canary: 'fs' } }, watch: { fs: 'escaped.txt' }, needs: /\b(?:writeFile|writeFileSync|appendFile|appendFileSync|createWriteStream)\b/ },
|
|
205
|
+
'CWE-918': { name: 'ssrf', payload: '{{CALLBACK_URL}}', oracle: { type: 'outbound_callback' }, network: 'callback' },
|
|
206
|
+
};
|
|
207
|
+
const generate_MAX_SOURCE = 256 * 1024;
|
|
208
|
+
const generate_MAX_FILES = 8;
|
|
209
|
+
const EXTS = ['', '.js', '.mjs', '.cjs', '/index.js'];
|
|
210
|
+
const BUILTINS = new Set(external_node_module_.builtinModules.flatMap((m) => [m, `node:${m}`]));
|
|
211
|
+
const MODULE_SYNTAX = /^\s*(?:import\s[^('"]|import\s*['"{*]|export\s)/m;
|
|
212
|
+
|
|
213
|
+
const generate_fail = (reason, extra = {}) => ({ ok: false, reason, ...extra });
|
|
214
|
+
const normCwe = (c) => { const m = /(\d{1,5})/.exec(String(c ?? '')); return m ? `CWE-${Number(m[1])}` : null; };
|
|
215
|
+
|
|
216
|
+
function inside(root, rel) {
|
|
217
|
+
if (typeof rel !== 'string' || !rel || rel.includes('\0')) return null;
|
|
218
|
+
let real;
|
|
219
|
+
try { real = external_node_fs_.realpathSync(external_node_path_.resolve(root, rel)); } catch { return null; }
|
|
220
|
+
const base = external_node_fs_.realpathSync(root);
|
|
221
|
+
return real === base || real.startsWith(base + external_node_path_.sep) ? real : null;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
function readSource(root, rel) {
|
|
225
|
+
const real = inside(root, rel);
|
|
226
|
+
if (!real) return null;
|
|
227
|
+
const st = external_node_fs_.statSync(real);
|
|
228
|
+
if (!st.isFile() || st.size > generate_MAX_SOURCE) return null;
|
|
229
|
+
return { real, text: external_node_fs_.readFileSync(real, 'utf8') };
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
function parseSource(text) {
|
|
233
|
+
try { return (0,lib/* parse */.qg)(text, { sourceType: 'unambiguous', errorRecovery: false, plugins: ['topLevelAwait'], allowReturnOutsideFunction: true }); } catch { return null; }
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
function* walk(node, parent = null) {
|
|
237
|
+
if (!node || typeof node !== 'object') return;
|
|
238
|
+
if (Array.isArray(node)) { for (const n of node) yield* walk(n, parent); return; }
|
|
239
|
+
if (typeof node.type !== 'string') return;
|
|
240
|
+
yield { node, parent };
|
|
241
|
+
for (const [k, v] of Object.entries(node)) if (k !== 'loc' && k !== 'leadingComments' && k !== 'trailingComments' && v && typeof v === 'object') yield* walk(v, node);
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/** Every module this file loads: built-ins pass, relative files are collected, anything else is a dependency the proof cannot provide. */
|
|
245
|
+
function dependencies(ast) {
|
|
246
|
+
const specs = [];
|
|
247
|
+
for (const { node } of walk(ast.program)) {
|
|
248
|
+
if (node.type === 'ImportDeclaration' || ((node.type === 'ExportNamedDeclaration' || node.type === 'ExportAllDeclaration') && node.source)) specs.push(node.source.value);
|
|
249
|
+
else if (node.type === 'CallExpression' && node.callee.type === 'Identifier' && node.callee.name === 'require' && node.arguments[0]?.type === 'StringLiteral') specs.push(node.arguments[0].value);
|
|
250
|
+
else if (node.type === 'ImportExpression' && node.source?.type === 'StringLiteral') specs.push(node.source.value);
|
|
251
|
+
}
|
|
252
|
+
return specs;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/** Every function that contains the line, innermost first: the flagged call is often inside a callback of the function that can be called. */
|
|
256
|
+
function functionsAround(ast, line) {
|
|
257
|
+
const all = [];
|
|
258
|
+
for (const { node, parent } of walk(ast.program)) {
|
|
259
|
+
if (!/^(?:FunctionDeclaration|FunctionExpression|ArrowFunctionExpression|ObjectMethod|ClassMethod)$/.test(node.type)) continue;
|
|
260
|
+
if (node.loc && node.loc.start.line <= line && node.loc.end.line >= line) all.push({ node, parent });
|
|
261
|
+
}
|
|
262
|
+
return all.sort((a, b) => (a.node.loc.end.line - a.node.loc.start.line) - (b.node.loc.end.line - b.node.loc.start.line) || (b.node.loc.start.line - a.node.loc.start.line));
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
const paramNames = (fn) => fn.params.map((p) => (p.type === 'Identifier' ? p.name : p.type === 'AssignmentPattern' && p.left.type === 'Identifier' ? p.left.name : null));
|
|
266
|
+
|
|
267
|
+
/** How the function is reachable from outside: its exported name, or null. */
|
|
268
|
+
function exportName(ast, fnInfo) {
|
|
269
|
+
const { node, parent } = fnInfo;
|
|
270
|
+
const idName = node.id?.name ?? (parent?.type === 'VariableDeclarator' && parent.id.type === 'Identifier' ? parent.id.name : null);
|
|
271
|
+
let found = null;
|
|
272
|
+
for (const { node: n } of walk(ast.program)) {
|
|
273
|
+
if (n.type === 'ExportNamedDeclaration' && n.declaration) {
|
|
274
|
+
if (n.declaration === node || (n.declaration.type === 'FunctionDeclaration' && n.declaration.id?.name === idName)) found = { kind: 'named', name: idName };
|
|
275
|
+
if (n.declaration.type === 'VariableDeclaration' && n.declaration.declarations.some((d) => d.init === node)) found = { kind: 'named', name: n.declaration.declarations.find((d) => d.init === node).id.name };
|
|
276
|
+
}
|
|
277
|
+
if (n.type === 'ExportNamedDeclaration' && n.specifiers?.length && idName) for (const s of n.specifiers) if (s.local?.name === idName) found = { kind: 'named', name: s.exported.name };
|
|
278
|
+
if (n.type === 'ExportDefaultDeclaration' && (n.declaration === node || n.declaration?.name === idName)) found = { kind: 'default' };
|
|
279
|
+
if (n.type === 'AssignmentExpression' && n.left.type === 'MemberExpression') {
|
|
280
|
+
const l = n.left; const obj = l.object; const prop = l.property?.name ?? l.property?.value;
|
|
281
|
+
const isModuleExports = obj.type === 'Identifier' && obj.name === 'module' && prop === 'exports';
|
|
282
|
+
if (isModuleExports && (n.right === node || (n.right.type === 'Identifier' && n.right.name === idName))) found = { kind: 'module' };
|
|
283
|
+
if (isModuleExports && n.right.type === 'ObjectExpression') for (const p of n.right.properties) if ((p.value === node || p.value?.name === idName || (p.shorthand && p.key.name === idName)) && p.key) found = { kind: 'named', name: p.key.name ?? p.key.value };
|
|
284
|
+
const isExportsProp = (obj.type === 'Identifier' && obj.name === 'exports') || (obj.type === 'MemberExpression' && obj.object?.name === 'module' && obj.property?.name === 'exports');
|
|
285
|
+
if (isExportsProp && prop && (n.right === node || (n.right.type === 'Identifier' && n.right.name === idName))) found = { kind: 'named', name: prop };
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
return found;
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
function harness({ esm, entry, exp, args }) {
|
|
292
|
+
const load = esm ? `const mod = await import('./${entry}');` : `import { createRequire } from 'node:module';\nconst require = createRequire(import.meta.url);\nconst mod = require('./${entry}');`;
|
|
293
|
+
const pick = exp.kind === 'named' ? `mod[${JSON.stringify(exp.name)}] ?? mod.default?.[${JSON.stringify(exp.name)}]` : exp.kind === 'default' ? 'mod.default ?? mod' : 'typeof mod === \'function\' ? mod : mod.default';
|
|
294
|
+
return `// Generated by the proof fabric from the finding's own evidence. It loads the flagged function and calls it with the payload.
|
|
295
|
+
${load}
|
|
296
|
+
const payload = process.argv[2] ?? '';
|
|
297
|
+
const P = new Proxy({}, { get: (_t, k) => (k === Symbol.toPrimitive ? () => payload : k === 'toString' ? () => payload : payload), has: () => true });
|
|
298
|
+
const res = new Proxy(function () {}, { get: () => res, apply: () => res });
|
|
299
|
+
const fn = ${pick};
|
|
300
|
+
if (typeof fn !== 'function') { console.error('the exported value is not a function'); process.exit(3); }
|
|
301
|
+
let timer; try { await Promise.race([Promise.resolve(fn(${args.join(', ')})), new Promise((r) => { timer = setTimeout(r, 5000); })]); } catch (e) { console.error('target threw:', String(e && e.message).slice(0, 200)); }
|
|
302
|
+
clearTimeout(timer);
|
|
303
|
+
`;
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
function generateReproducer({ finding, root }) {
|
|
307
|
+
const cwe = normCwe(finding?.cwe);
|
|
308
|
+
const cls = CLASSES[cwe];
|
|
309
|
+
if (!cls) return generate_fail(`no payload and oracle exist for ${cwe ?? 'this finding'}; supported: ${Object.keys(CLASSES).join(', ')} (others need a database, a deserializer or a native harness)`);
|
|
310
|
+
const rel = String(finding?.file ?? '');
|
|
311
|
+
const isPy = /\.py$/i.test(rel);
|
|
312
|
+
if (!isPy && !/\.(?:js|mjs|cjs)$/i.test(rel)) return generate_fail(`no harness builder for ${external_node_path_.extname(rel) || 'this file type'}; JavaScript and Python only`);
|
|
313
|
+
if (!Number.isInteger(finding?.line)) return generate_fail('the finding has no line number');
|
|
314
|
+
if (isPy) return generatePythonReproducer({ finding, root, cls });
|
|
315
|
+
const src = readSource(root, rel);
|
|
316
|
+
if (!src) return generate_fail('the flagged file is missing, outside the repository, or too large');
|
|
317
|
+
const ast = parseSource(src.text);
|
|
318
|
+
if (!ast) return generate_fail('the flagged file could not be parsed');
|
|
319
|
+
const lines = src.text.split('\n');
|
|
320
|
+
const sinkLine = lines[finding.line - 1] ?? '';
|
|
321
|
+
if (cls.needs && !cls.needs.test(sinkLine) && !cls.needs.test(lines.slice(Math.max(0, finding.line - 3), finding.line + 2).join('\n'))) return generate_fail(`${cls.name}: the flagged code is not a write, and the oracle can only observe a write (a read leaves no trace unless the program prints it)`);
|
|
322
|
+
|
|
323
|
+
// dependencies the sandbox can satisfy
|
|
324
|
+
const sources = {}; const external = [];
|
|
325
|
+
const entryDir = external_node_path_.dirname(src.real);
|
|
326
|
+
const rootReal = external_node_fs_.realpathSync(root); // the repository root as the filesystem names it (a temp dir can sit behind a symlink)
|
|
327
|
+
const collect = (realFile, ast0, count) => {
|
|
328
|
+
for (const spec of dependencies(ast0)) {
|
|
329
|
+
if (BUILTINS.has(spec)) continue;
|
|
330
|
+
if (!spec.startsWith('.')) { external.push(spec); continue; }
|
|
331
|
+
let found = null;
|
|
332
|
+
for (const e of EXTS) { const cand = inside(root, external_node_path_.relative(rootReal, external_node_path_.resolve(external_node_path_.dirname(realFile), spec + e))); if (cand && external_node_fs_.statSync(cand).isFile()) { found = cand; break; } }
|
|
333
|
+
if (!found) return generate_fail(`the relative import "${spec}" was not found inside the repository`);
|
|
334
|
+
const destRel = external_node_path_.relative(entryDir, found);
|
|
335
|
+
if (destRel.startsWith('..')) return generate_fail(`"${spec}" lives outside the flagged file's directory, which a proof workspace cannot mirror`);
|
|
336
|
+
if (sources[destRel] || found === src.real) continue;
|
|
337
|
+
if (Object.keys(sources).length >= generate_MAX_FILES) return generate_fail(`the file pulls in more than ${generate_MAX_FILES} repository files`);
|
|
338
|
+
const dep = readSource(root, external_node_path_.relative(rootReal, found));
|
|
339
|
+
if (!dep) return generate_fail(`"${spec}" is too large or unreadable`);
|
|
340
|
+
sources[destRel] = external_node_path_.relative(rootReal, found);
|
|
341
|
+
const depAst = parseSource(dep.text);
|
|
342
|
+
if (!depAst) return generate_fail(`"${spec}" could not be parsed`);
|
|
343
|
+
const r = collect(found, depAst, count + 1); if (r) return r;
|
|
344
|
+
}
|
|
345
|
+
return null;
|
|
346
|
+
};
|
|
347
|
+
const bad = collect(src.real, ast, 0);
|
|
348
|
+
if (bad) return bad;
|
|
349
|
+
if (external.length) return generate_fail(`the flagged code needs ${[...new Set(external)].slice(0, 4).join(', ')}, which is not installed in the proof environment; only Node built-ins and repository files can be loaded`, { missing: [...new Set(external)] });
|
|
350
|
+
|
|
351
|
+
const esm = MODULE_SYNTAX.test(src.text) || external_node_path_.extname(rel).toLowerCase() === '.mjs';
|
|
352
|
+
const entry = `target${esm ? '.mjs' : '.cjs'}`;
|
|
353
|
+
sources[entry] = rel;
|
|
354
|
+
const assumptions = [];
|
|
355
|
+
const base = { schema: 'agentic-security/reproducer', version: 1, findingId: String(finding.stableId ?? finding.id ?? 'generated'), lang: 'javascript', oracle: cls.oracle, network: cls.network ?? 'none', ...(cls.watch ? { watch: cls.watch } : {}) };
|
|
356
|
+
if (cls.watch) assumptions.push('the write target is assumed to be one directory below the working directory (the payload is ../escaped.txt); if the code uses another base, the proof will not confirm');
|
|
357
|
+
|
|
358
|
+
// shape 1: a script that reads its payload from argv
|
|
359
|
+
if (/process\.argv\s*\[\s*2\s*\]|process\.argv\.slice\(\s*2\s*\)/.test(src.text) && !/\bmodule\.exports\b|^\s*export\s/m.test(src.text)) {
|
|
360
|
+
const reproducer = { ...base, sources, run: ['{{NODE}}', entry, cls.payload] };
|
|
361
|
+
const errs = (0,proof_fabric_reproducer/* validateReproducer */.mC)(reproducer);
|
|
362
|
+
return errs.length ? generate_fail(`the generated reproducer is invalid: ${errs[0]}`) : { ok: true, reproducer, basis: { shape: 'script', class: cls.name, entry: rel, line: finding.line, assumptions } };
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
// shape 2: an exported function around the flagged line
|
|
366
|
+
const candidates = functionsAround(ast, finding.line);
|
|
367
|
+
if (!candidates.length) return generate_fail('the flagged line is not inside a function, and the file does not read its payload from process.argv[2]');
|
|
368
|
+
let around = null; let exp = null;
|
|
369
|
+
for (const c of candidates) { const e = exportName(ast, c); if (e) { around = c; exp = e; break; } }
|
|
370
|
+
if (!around) return generate_fail('the function around the flagged line is not exported, so nothing outside the file can call it');
|
|
371
|
+
const names = paramNames(around.node);
|
|
372
|
+
if (!names.length) return generate_fail('the function around the flagged line takes no parameters, so the payload has no way in');
|
|
373
|
+
const window = lines.slice(Math.max(0, around.node.loc.start.line - 1), Math.min(lines.length, finding.line + 1)).join('\n');
|
|
374
|
+
const requestLike = names.findIndex((n) => n && /^(?:req|request)$/.test(n) && new RegExp(`\\b${n}\\.(?:body|query|params)\\b`).test(sinkLine));
|
|
375
|
+
const direct = requestLike >= 0 ? -1 : names.findIndex((n) => n && new RegExp(`\\b${n}\\b`).test(sinkLine));
|
|
376
|
+
const fallback = direct < 0 && requestLike < 0 ? names.findIndex((n) => n && new RegExp(`\\b${n}\\b`).test(window)) : -1;
|
|
377
|
+
const idx = requestLike >= 0 ? requestLike : direct >= 0 ? direct : fallback;
|
|
378
|
+
if (idx < 0) return generate_fail('none of the function\'s parameters appears in the flagged code, so there is no tainted parameter to fill');
|
|
379
|
+
if (fallback >= 0) assumptions.push(`the tainted parameter "${names[idx]}" was chosen because it appears in the function body near the flagged line, not on the line itself`);
|
|
380
|
+
const args = names.map((_, i) => (i !== idx ? (/^(?:res|response)$/.test(names[i] ?? '') ? 'res' : 'undefined') : requestLike >= 0 ? '{ body: P, query: P, params: P, headers: P, cookies: P }' : 'payload'));
|
|
381
|
+
const files = { 'harness.mjs': harness({ esm, entry, exp, args }) };
|
|
382
|
+
const reproducer = { ...base, sources, files, run: ['{{NODE}}', 'harness.mjs', cls.payload] };
|
|
383
|
+
const errs = (0,proof_fabric_reproducer/* validateReproducer */.mC)(reproducer);
|
|
384
|
+
return errs.length ? generate_fail(`the generated reproducer is invalid: ${errs[0]}`) : { ok: true, reproducer, basis: { shape: 'function', class: cls.name, entry: rel, line: finding.line, function: names.length ? `${exp.kind === 'named' ? exp.name : exp.kind}(${names.join(', ')})` : exp.kind, taintedParameter: names[idx], requestLike: requestLike >= 0, assumptions } };
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
;// CONCATENATED MODULE: ./src/posture/proof-fabric/cli.js
|
|
388
|
+
// CLI surface for the proof fabric: `proof show|replay|doctor`, `triage exploit|validate`. Non-interactive by design: no
|
|
389
|
+
// command reads stdin, every run is bounded by the policy timeouts, and a missing reproducer is a typed exit code, not a
|
|
390
|
+
// prompt. Exit codes: 0 confirmed/ok, 1 not confirmed (any reason), 4 usage/precondition.
|
|
391
|
+
|
|
392
|
+
|
|
393
|
+
|
|
394
|
+
|
|
395
|
+
|
|
396
|
+
|
|
397
|
+
|
|
398
|
+
|
|
399
|
+
|
|
400
|
+
|
|
401
|
+
|
|
402
|
+
function loadFinding(root, id) {
|
|
403
|
+
const p = (0,state_dir.statePath)(root, 'last-scan.json');
|
|
404
|
+
if (!external_node_fs_.existsSync(p)) return null;
|
|
405
|
+
const last = JSON.parse(external_node_fs_.readFileSync(p, 'utf8'));
|
|
406
|
+
return (last.findings || []).find((f) => f.id === id || f.stableId === id) ?? null;
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
/**
|
|
410
|
+
* The reproducer for a finding: the one the person or agent supplied (or stored), else one built from the finding's own evidence.
|
|
411
|
+
* A generated reproducer is a proposal; it earns nothing until it is executed, and the result says it was generated.
|
|
412
|
+
*/
|
|
413
|
+
function resolveReproducer(root, finding, flagPath) {
|
|
414
|
+
const supplied = loadReproducer(root, finding.stableId ?? finding.id, flagPath) ?? (finding.stableId && finding.id !== finding.stableId ? loadReproducer(root, finding.id, flagPath) : null);
|
|
415
|
+
if (supplied) return { ...supplied, generated: null };
|
|
416
|
+
const g = generateReproducer({ finding, root });
|
|
417
|
+
if (!g.ok) return { reproducer: null, reason: g.reason };
|
|
418
|
+
return { reproducer: g.reproducer, file: null, generated: g.basis };
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
function loadReproducer(root, id, flagPath) {
|
|
422
|
+
const candidates = [flagPath && external_node_path_.resolve(String(flagPath)), (0,state_dir.statePath)(root, 'reproducers', `${(0,store.findingKey)(id)}.json`)].filter(Boolean);
|
|
423
|
+
for (const c of candidates) {
|
|
424
|
+
try { return { reproducer: JSON.parse(external_node_fs_.readFileSync(c, 'utf8')), file: c }; } catch { /* next */ }
|
|
425
|
+
}
|
|
426
|
+
return null;
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
function formatResult(r) {
|
|
430
|
+
const env = r.environment ? `${r.environment.mode} (${r.environment.assurance} assurance)` : 'none';
|
|
431
|
+
return [
|
|
432
|
+
`Finding: ${r.findingId}`,
|
|
433
|
+
`Evidence: ${r.state}`,
|
|
434
|
+
`Oracle: ${r.oracle}`,
|
|
435
|
+
`Reproductions: ${r.attempts?.successes ?? 0}/${r.attempts?.run ?? 0} (required ${r.attempts?.required})`,
|
|
436
|
+
`Independent replay: ${r.independentReplay?.status ?? 'not-run'}`,
|
|
437
|
+
`Environment: ${env}`,
|
|
438
|
+
`Completeness: ${r.completeness}`,
|
|
439
|
+
`Duration: ${(r.timing.proofMs / 1000).toFixed(1)}s`,
|
|
440
|
+
...(r.degradation?.length ? [`Degraded: ${r.degradation.join(', ')}`] : []),
|
|
441
|
+
...(r.note ? [`Note: ${r.note}`] : []),
|
|
442
|
+
].join('\n');
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
async function cmdProve(args, root, { json = false } = {}) {
|
|
446
|
+
const id = String(args._[2] ?? '');
|
|
447
|
+
if (!id) { console.error('usage: triage exploit <finding-id> --prove [--reproducer file] [--attempts N] [--required N]'); return 4; }
|
|
448
|
+
const finding = loadFinding(root, id);
|
|
449
|
+
if (!finding) { console.error(`Finding ${id} not found in last scan.`); return 4; }
|
|
450
|
+
const loaded = resolveReproducer(root, finding, args.flags.reproducer);
|
|
451
|
+
if (!loaded.reproducer) { console.error(`No reproducer for ${id}, and none could be generated from the finding: ${loaded.reason}. Supply one with --reproducer <file> or place it at .agentic-security/reproducers/. Nothing was executed.`); return 4; }
|
|
452
|
+
if (loaded.generated) console.error(`Generated a reproducer from the finding (${loaded.generated.shape}, ${loaded.generated.class}). It is a proposal: it counts only if executing it confirms the exploit.`);
|
|
453
|
+
const errs = (0,proof_fabric_reproducer/* validateReproducer */.mC)(loaded.reproducer);
|
|
454
|
+
if (errs.length) { console.error(`Invalid reproducer: ${errs.join('; ')}`); return 4; }
|
|
455
|
+
const policy = {};
|
|
456
|
+
if (args.flags.attempts) policy.attempts = Number(args.flags.attempts);
|
|
457
|
+
if (args.flags.required) policy.required = Number(args.flags.required);
|
|
458
|
+
if (args.flags.timeout) policy.timeoutMs = Number(args.flags.timeout) * 1000;
|
|
459
|
+
if (args.flags['require-container']) policy.requireContainer = true;
|
|
460
|
+
const ac = new AbortController();
|
|
461
|
+
const onSig = () => ac.abort();
|
|
462
|
+
process.once('SIGINT', onSig);
|
|
463
|
+
let result;
|
|
464
|
+
try { result = await (0,orchestrator/* proveFinding */.kO)({ finding, reproducer: loaded.reproducer, revision: args.flags.revision ?? null, policy, signal: ac.signal, sourceRoot: root }); } finally { process.off('SIGINT', onSig); }
|
|
465
|
+
const saved = (0,store.saveProof)(root, { ...result, reproducer: loaded.reproducer, ...(loaded.generated ? { generatedFrom: loaded.generated } : {}) });
|
|
466
|
+
// Printed output gets the same secret-scrubbing pass as what is persisted (defense in depth: a free-text reason/note
|
|
467
|
+
// field that captured something from stdout/stderr should never reach a terminal unredacted either).
|
|
468
|
+
if (json || args.flags.json) console.log(JSON.stringify((0,store.scrubDeep)({ ...result, stored: saved.ok ? saved.file : null }), null, 2));
|
|
469
|
+
else { console.log(formatResult(result)); if (!saved.ok) console.log(`(proof not stored: ${saved.reason})`); }
|
|
470
|
+
return result.state === 'EXPLOIT_CONFIRMED' ? 0 : 1;
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
async function cmdProof(args, root) {
|
|
474
|
+
const sub = args._[1];
|
|
475
|
+
if (sub === 'doctor') return doctor(args);
|
|
476
|
+
if (sub === 'generate') {
|
|
477
|
+
const gid = String(args._[2] ?? '');
|
|
478
|
+
const finding = gid ? loadFinding(root, gid) : null;
|
|
479
|
+
if (!finding) { console.error(gid ? `Finding ${gid} not found in last scan.` : 'usage: proof generate <finding-id> [--out file]'); return 4; }
|
|
480
|
+
const g = generateReproducer({ finding, root });
|
|
481
|
+
if (!g.ok) { console.error(`No reproducer could be generated: ${g.reason}`); return 1; }
|
|
482
|
+
const text = JSON.stringify({ ...g.reproducer, findingId: gid }, null, 2);
|
|
483
|
+
if (args.flags.out) { external_node_fs_.writeFileSync(external_node_path_.resolve(String(args.flags.out)), `${text}\n`); console.log(`Wrote ${external_node_path_.resolve(String(args.flags.out))} (${g.basis.shape}, ${g.basis.class}). Nothing was executed.`); } else console.log(text);
|
|
484
|
+
for (const a of g.basis.assumptions) console.error(`assumption: ${a}`);
|
|
485
|
+
return 0;
|
|
486
|
+
}
|
|
487
|
+
const id = String(args._[2] ?? '');
|
|
488
|
+
if (!id) { console.error('usage: proof show <finding-id> | proof replay <finding-id> | proof generate <finding-id> | proof doctor'); return 4; }
|
|
489
|
+
if (sub === 'show') {
|
|
490
|
+
const all = (0,store.listProofs)(root, id);
|
|
491
|
+
if (!all.length) { console.error(`No stored proof for ${id}.`); return 4; }
|
|
492
|
+
const latest = all.find((p) => p.record);
|
|
493
|
+
if (all.some((p) => p.tampered)) console.error(`WARNING: ${all.filter((p) => p.tampered).length} stored record(s) failed their integrity check and are not trusted.`);
|
|
494
|
+
const good = all.find((p) => p.record && !p.tampered);
|
|
495
|
+
if (!good) { console.error('No intact proof record.'); return 1; }
|
|
496
|
+
if (args.flags.json) console.log(JSON.stringify(good.record, null, 2)); else console.log(formatResult(good.record));
|
|
497
|
+
// the detection generated from this finding's proof (detection-and-response loop), when there is one
|
|
498
|
+
try {
|
|
499
|
+
const det = (await __webpack_require__.e(/* import() */ 8551).then(__webpack_require__.bind(__webpack_require__, 58551))).latestRecord(root, id, 'detection');
|
|
500
|
+
if (det && !args.flags.json) console.log(`Detection: ${det.record.ir?.id ?? 'unknown'} (${det.record.validation?.status ?? 'not validated'}${det.record.enabled ? ', enabled' : ''})`);
|
|
501
|
+
} catch { /* the proof output does not depend on it */ }
|
|
502
|
+
void latest;
|
|
503
|
+
return 0;
|
|
504
|
+
}
|
|
505
|
+
if (sub === 'replay') {
|
|
506
|
+
const stored = (0,store.latestProof)(root, id);
|
|
507
|
+
if (!stored?.record?.reproducer) { console.error(`No stored reproducer for ${id}.`); return 4; }
|
|
508
|
+
const tmpDir = external_node_fs_.mkdtempSync(external_node_path_.join(external_node_os_.tmpdir(), 'proof-replay-'));
|
|
509
|
+
const tmp = external_node_path_.join(tmpDir, 'reproducer.json');
|
|
510
|
+
external_node_fs_.writeFileSync(tmp, JSON.stringify(stored.record.reproducer));
|
|
511
|
+
args.flags.reproducer = tmp;
|
|
512
|
+
args._ = ['triage', 'exploit', id];
|
|
513
|
+
try { return await cmdProve(args, root); } finally { external_node_fs_.rmSync(tmpDir, { recursive: true, force: true }); }
|
|
514
|
+
}
|
|
515
|
+
console.error('usage: proof show|replay <finding-id> | proof doctor');
|
|
516
|
+
return 4;
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
function doctor(args) {
|
|
520
|
+
const tools = (0,runner/* hostTools */.qV)();
|
|
521
|
+
const rows = proof_fabric_reproducer/* LANGUAGES */.Yj.map((l) => ({ lang: l, ...(0,runner/* languageSupport */.ql)(l, tools) }));
|
|
522
|
+
const envs = ['javascript', 'python'].map((l) => ({ lang: l, ...(0,runner/* selectEnvironment */.aP)({ lang: l }) }));
|
|
523
|
+
if (args.flags.json) { console.log(JSON.stringify({ tools, languages: rows, environments: envs }, null, 2)); return 0; }
|
|
524
|
+
console.log('Proof fabric doctor');
|
|
525
|
+
for (const r of rows) console.log(` ${r.lang.padEnd(11)} ${r.supported ? 'supported' : `unsupported (${r.reason})`}`);
|
|
526
|
+
for (const e of envs) console.log(` environment for ${e.lang}: ${e.mode}, ${e.assurance} assurance${e.reason ? ` (${e.reason})` : ''}${e.containerSkipped ? `; container skipped: ${e.containerSkipped}` : ''}`);
|
|
527
|
+
const usable = envs.some((e) => e.mode !== 'unavailable');
|
|
528
|
+
if (!usable) console.log(' RESULT: no execution environment available; proofs will report blocked, never clean.');
|
|
529
|
+
return usable ? 0 : 1;
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
|
|
533
|
+
/***/ }),
|
|
534
|
+
|
|
535
|
+
/***/ 3740:
|
|
536
|
+
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
537
|
+
|
|
538
|
+
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
|
|
539
|
+
/* harmony export */ kO: () => (/* binding */ proveFinding)
|
|
540
|
+
/* harmony export */ });
|
|
541
|
+
/* unused harmony exports independentVerify, applySeverityPolicy, _newRunId */
|
|
542
|
+
/* harmony import */ var node_crypto__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(77598);
|
|
543
|
+
/* harmony import */ var _states_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(12090);
|
|
544
|
+
/* harmony import */ var _runner_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(23081);
|
|
545
|
+
/* harmony import */ var _reproducer_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(37055);
|
|
546
|
+
/* harmony import */ var _proof_tier_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(40216);
|
|
547
|
+
// Proof orchestration: finding + revision + reproducer + policy -> structured evidence.
|
|
548
|
+
//
|
|
549
|
+
// Rules that make this safe to trust:
|
|
550
|
+
// * The model may propose a reproducer and select an oracle. The oracle (oracles.js) judges. Never a model.
|
|
551
|
+
// * An attempt that did not complete (timeout, build failure, blocked, unsupported, error) is NOT a negative and NOT a
|
|
552
|
+
// positive: it is degraded evidence, it never advances the state, and it makes the result INCOMPLETE.
|
|
553
|
+
// * EXPLOIT_CONFIRMED needs `required` successes in `attempts` completed attempts AND a pass from an independent
|
|
554
|
+
// verifier that receives only {revision, reproducer, findingId, oracle} in a fresh environment.
|
|
555
|
+
// * "Not reproduced" is reported as such; it is never reported as safe.
|
|
556
|
+
|
|
557
|
+
|
|
558
|
+
|
|
559
|
+
|
|
560
|
+
|
|
561
|
+
|
|
562
|
+
const PROOF_POLICY_DEFAULTS = Object.freeze({ attempts: 3, required: 3, independentReplay: true, timeoutMs: 20_000, cpus: 1, memoryMb: 512, network: 'none', requireContainer: false });
|
|
563
|
+
const RESULT_SCHEMA = 'agentic-security/proof-result';
|
|
564
|
+
|
|
565
|
+
function normalizePolicy(p = {}) {
|
|
566
|
+
const x = { ...PROOF_POLICY_DEFAULTS, ...p };
|
|
567
|
+
x.attempts = Math.max(1, Math.min(10, Math.trunc(Number(x.attempts)) || PROOF_POLICY_DEFAULTS.attempts));
|
|
568
|
+
x.required = Math.max(1, Math.min(x.attempts, Math.trunc(Number(x.required)) || x.attempts));
|
|
569
|
+
x.timeoutMs = Math.max(1000, Math.min(120_000, Number(x.timeoutMs) || PROOF_POLICY_DEFAULTS.timeoutMs));
|
|
570
|
+
return x;
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
const summarize = (a) => ({ status: a.status, fired: a.oracle?.fired === true, inconclusive: a.oracle?.inconclusive === true, reason: a.oracle?.reason ?? a.reasons?.[0] ?? null, durationMs: a.durationMs, degraded: a.degraded });
|
|
574
|
+
|
|
575
|
+
/**
|
|
576
|
+
* Independent verifier. Takes a verifierView ONLY; any extra property (a model's reasoning, prior results) is rejected so
|
|
577
|
+
* the isolation of its inputs is checkable rather than a convention.
|
|
578
|
+
*/
|
|
579
|
+
async function independentVerify(view, opts = {}) {
|
|
580
|
+
const allowed = new Set(['revision', 'reproducer', 'findingId', 'oracle']);
|
|
581
|
+
const extra = Object.keys(view || {}).filter((k) => !allowed.has(k));
|
|
582
|
+
if (extra.length) return { status: 'rejected', reason: `verifier input must be exactly revision, reproducer, findingId, oracle; got extra: ${extra.join(', ')}` };
|
|
583
|
+
const attempt = await (opts.attemptFn ?? _runner_js__WEBPACK_IMPORTED_MODULE_2__/* .runAttempt */ .Tm)(structuredClone(view.reproducer), { ...opts, preferContainer: opts.preferContainer });
|
|
584
|
+
return { status: attempt.status === 'completed' ? (attempt.oracle?.fired ? 'confirmed' : 'not-reproduced') : 'incomplete', attempt: summarize(attempt), environment: attempt.environment ?? null };
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
/**
|
|
588
|
+
* @param {object} a
|
|
589
|
+
* @param {object} a.finding the finding (id/stableId, severity, proofTier ...)
|
|
590
|
+
* @param {string} [a.revision] commit the proof applies to
|
|
591
|
+
* @param {object} a.reproducer serialized reproducer
|
|
592
|
+
* @param {object} [a.policy]
|
|
593
|
+
* @param {object} [a.deps] test seams: { attemptFn }
|
|
594
|
+
*/
|
|
595
|
+
async function proveFinding({ finding, revision = null, reproducer, policy = {}, signal, deps = {}, sourceState = null, sourceRoot = null, overlay = null } = {}) {
|
|
596
|
+
const started = Date.now();
|
|
597
|
+
const pol = normalizePolicy(policy);
|
|
598
|
+
const attemptFn = deps.attemptFn ?? _runner_js__WEBPACK_IMPORTED_MODULE_2__/* .runAttempt */ .Tm;
|
|
599
|
+
const findingId = finding?.stableId ?? finding?.id ?? reproducer?.findingId ?? 'unknown';
|
|
600
|
+
const degradation = [];
|
|
601
|
+
let state = sourceState ?? (0,_states_js__WEBPACK_IMPORTED_MODULE_1__/* .fromProofTier */ .jn)((0,_proof_tier_js__WEBPACK_IMPORTED_MODULE_4__/* .proofTierOf */ .gx)(finding || {}));
|
|
602
|
+
if (state === 'REPRODUCED') state = 'STATICALLY_CORROBORATED'; // an old single-run marker proof must be re-earned here
|
|
603
|
+
const startState = state;
|
|
604
|
+
|
|
605
|
+
const result = (extra) => ({
|
|
606
|
+
schema: RESULT_SCHEMA, version: 1, findingId, revision, startState, state, staticCorroboration: (0,_states_js__WEBPACK_IMPORTED_MODULE_1__/* .stateRank */ .g3)(startState) >= 1, tier: (0,_states_js__WEBPACK_IMPORTED_MODULE_1__/* .toProofTier */ .KF)(state),
|
|
607
|
+
oracle: reproducer?.oracle?.type ?? null, policy: pol,
|
|
608
|
+
reproducerDigest: reproducer ? safeDigest(reproducer) : null,
|
|
609
|
+
degradation, timing: { proofMs: Date.now() - started }, ...extra,
|
|
610
|
+
});
|
|
611
|
+
|
|
612
|
+
const errs = reproducer ? (0,_reproducer_js__WEBPACK_IMPORTED_MODULE_3__/* .validateReproducer */ .mC)(reproducer) : ['no reproducer supplied'];
|
|
613
|
+
if (errs.length) { degradation.push('invalid-reproducer'); return result({ completeness: 'INCOMPLETE', outcome: 'invalid-reproducer', reasons: errs, attempts: { required: pol.required, run: 0, successes: 0, incomplete: 0 }, independentReplay: { status: 'not-run' } }); }
|
|
614
|
+
|
|
615
|
+
// A valid reproducer is itself the REPRODUCER_GENERATED rung. Static corroboration is recorded, not required: an exploit
|
|
616
|
+
// that reproduces under an independent oracle is deterministic corroboration in its own right, and a pattern-only finding
|
|
617
|
+
// must not be unable to earn proof merely because the taint engine never saw it. The record says which it was.
|
|
618
|
+
const staticCorroboration = (0,_states_js__WEBPACK_IMPORTED_MODULE_1__/* .stateRank */ .g3)(startState) >= (0,_states_js__WEBPACK_IMPORTED_MODULE_1__/* .stateRank */ .g3)('STATICALLY_CORROBORATED');
|
|
619
|
+
if (!staticCorroboration) degradation.push('no-static-corroboration');
|
|
620
|
+
state = 'REPRODUCER_GENERATED';
|
|
621
|
+
|
|
622
|
+
const attempts = [];
|
|
623
|
+
for (let i = 0; i < pol.attempts; i++) {
|
|
624
|
+
if (signal?.aborted) { degradation.push('cancelled'); break; }
|
|
625
|
+
const a = await attemptFn(structuredClone(reproducer), { limits: { timeoutMs: pol.timeoutMs }, signal, requireContainer: pol.requireContainer, preferContainer: pol.preferContainer, force: pol.force, sourceRoot, overlay });
|
|
626
|
+
attempts.push(a);
|
|
627
|
+
// Stop early once the threshold can no longer be met only if every attempt is a decisive negative; incomplete runs continue.
|
|
628
|
+
}
|
|
629
|
+
const completed = attempts.filter((a) => a.status === 'completed' && !a.oracle?.inconclusive);
|
|
630
|
+
const successes = completed.filter((a) => a.oracle?.fired).length;
|
|
631
|
+
const incomplete = attempts.length - completed.length;
|
|
632
|
+
for (const a of attempts) for (const d of a.degraded || []) if (!degradation.includes(d)) degradation.push(d);
|
|
633
|
+
if (incomplete) degradation.push(`incomplete-attempts:${incomplete}`);
|
|
634
|
+
const env = attempts.find((a) => a.environment)?.environment ?? null;
|
|
635
|
+
const base = {
|
|
636
|
+
environment: env && { mode: env.mode, assurance: env.assurance, backend: env.backend ?? null, note: env.note ?? null },
|
|
637
|
+
build: attempts.some((a) => a.status === 'build-failed') ? 'failed' : attempts.length ? 'ok' : 'not-run',
|
|
638
|
+
attempts: { required: pol.required, run: attempts.length, successes, incomplete, detail: attempts.map(summarize) },
|
|
639
|
+
artifactHashes: { reproducer: safeDigest(reproducer), observations: (0,_reproducer_js__WEBPACK_IMPORTED_MODULE_3__/* .sha256 */ .sc)((0,_reproducer_js__WEBPACK_IMPORTED_MODULE_3__/* .canonicalize */ .dw)(attempts.map((a) => a.observation ?? null))) },
|
|
640
|
+
};
|
|
641
|
+
|
|
642
|
+
if (successes > 0) {
|
|
643
|
+
const r = (0,_states_js__WEBPACK_IMPORTED_MODULE_1__/* .advance */ .np)(state, 'REPRODUCED'); if (r.ok) state = r.state;
|
|
644
|
+
}
|
|
645
|
+
if (!attempts.length) return result({ ...base, completeness: 'INCOMPLETE', outcome: 'not-run', independentReplay: { status: 'not-run' } });
|
|
646
|
+
if (successes === 0) {
|
|
647
|
+
const decisive = completed.length === attempts.length;
|
|
648
|
+
return result({ ...base, completeness: decisive ? 'FULL' : 'INCOMPLETE', outcome: decisive ? 'not-reproduced' : 'inconclusive', note: 'not reproduced is not proof of safety', independentReplay: { status: 'not-run' } });
|
|
649
|
+
}
|
|
650
|
+
if (successes < pol.required || incomplete) {
|
|
651
|
+
return result({ ...base, completeness: incomplete ? 'INCOMPLETE' : 'DEGRADED', outcome: 'reproduced-below-threshold', independentReplay: { status: 'not-run' } });
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
let independent = { status: 'skipped' };
|
|
655
|
+
if (pol.independentReplay) {
|
|
656
|
+
independent = await independentVerify((0,_reproducer_js__WEBPACK_IMPORTED_MODULE_3__/* .verifierView */ .IW)({ revision, reproducer, findingId, oracle: reproducer.oracle }), { attemptFn, limits: { timeoutMs: pol.timeoutMs }, signal, requireContainer: pol.requireContainer, force: pol.force, sourceRoot, overlay });
|
|
657
|
+
if (independent.status !== 'confirmed') degradation.push(`independent-replay:${independent.status}`);
|
|
658
|
+
} else degradation.push('independent-replay-disabled');
|
|
659
|
+
if (independent.status === 'confirmed') {
|
|
660
|
+
const r = (0,_states_js__WEBPACK_IMPORTED_MODULE_1__/* .advance */ .np)(state, 'EXPLOIT_CONFIRMED'); if (r.ok) state = r.state;
|
|
661
|
+
}
|
|
662
|
+
const full = state === 'EXPLOIT_CONFIRMED' && base.environment?.assurance !== 'none';
|
|
663
|
+
return result({ ...base, independentReplay: independent, completeness: full ? (base.environment.assurance === 'lower' ? 'DEGRADED' : 'FULL') : 'INCOMPLETE', outcome: full ? 'exploit-confirmed' : 'reproduced-unverified' });
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
const safeDigest = (r) => { try { return (0,_reproducer_js__WEBPACK_IMPORTED_MODULE_3__/* .reproducerDigest */ .we)(r); } catch { return null; } };
|
|
667
|
+
|
|
668
|
+
/** Severity policy: optional, never on by default. Returns the finding unchanged unless the policy asks to demote. */
|
|
669
|
+
function applySeverityPolicy(finding, evidenceState, policy) {
|
|
670
|
+
const req = policy?.criticalRequires;
|
|
671
|
+
if (!Array.isArray(req) || !req.length || finding?.severity !== 'critical') return finding;
|
|
672
|
+
const ok = req.some((s) => stateRankOf(evidenceState ?? 'CANDIDATE') >= stateRankOf(s));
|
|
673
|
+
return ok ? finding : { ...finding, severity: 'high', severityPolicy: { demotedFrom: 'critical', reason: `critical requires ${req.join(' or ')}; evidence state is ${evidenceState ?? 'CANDIDATE'}` } };
|
|
674
|
+
}
|
|
675
|
+
const _newRunId = () => randomBytes(6).toString('hex');
|
|
676
|
+
|
|
677
|
+
|
|
678
|
+
/***/ }),
|
|
679
|
+
|
|
680
|
+
/***/ 12090:
|
|
681
|
+
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
682
|
+
|
|
683
|
+
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
|
|
684
|
+
/* harmony export */ KF: () => (/* binding */ toProofTier),
|
|
685
|
+
/* harmony export */ g3: () => (/* binding */ stateRank),
|
|
686
|
+
/* harmony export */ jn: () => (/* binding */ fromProofTier),
|
|
687
|
+
/* harmony export */ np: () => (/* binding */ advance)
|
|
688
|
+
/* harmony export */ });
|
|
689
|
+
/* unused harmony exports EVIDENCE_STATES, COMPLETENESS */
|
|
690
|
+
// Evidence state ladder for the Universal Exploit Proof Fabric.
|
|
691
|
+
//
|
|
692
|
+
// Evidence state is SEPARATE from severity and confidence. It extends, never replaces, the vocabulary that already
|
|
693
|
+
// exists: `proof-tier.js` (execution-proven / proof-failed / taint-proven / unproven) and the fix-verify legs
|
|
694
|
+
// (`verifiedFull`, `degradedLegs`). `toProofTier` / `fromProofTier` are the explicit bridges.
|
|
695
|
+
//
|
|
696
|
+
// Transitions are guarded: a state can only be reached from the state directly before it (or by dropping back), so no
|
|
697
|
+
// caller can jump a finding to EXPLOIT_CONFIRMED without passing REPRODUCED, or to FIX_VERIFIED without
|
|
698
|
+
// FIX_REPLAY_BLOCKED. A degraded or incomplete run NEVER advances a state.
|
|
699
|
+
const EVIDENCE_STATES = Object.freeze([
|
|
700
|
+
'CANDIDATE',
|
|
701
|
+
'STATICALLY_CORROBORATED',
|
|
702
|
+
'REPRODUCER_GENERATED',
|
|
703
|
+
'REPRODUCED',
|
|
704
|
+
'EXPLOIT_CONFIRMED',
|
|
705
|
+
'FIX_REPLAY_BLOCKED',
|
|
706
|
+
'FIX_VERIFIED',
|
|
707
|
+
]);
|
|
708
|
+
|
|
709
|
+
const stateRank = (s) => EVIDENCE_STATES.indexOf(s);
|
|
710
|
+
|
|
711
|
+
const REQUIRES_PREDECESSOR = Object.freeze(Object.fromEntries(EVIDENCE_STATES.map((s, i) => [s, i === 0 ? null : EVIDENCE_STATES[i - 1]])));
|
|
712
|
+
|
|
713
|
+
/**
|
|
714
|
+
* Advance `from` to `to`. Returns { ok, state, reason }. Moving up requires `to` to be exactly the next rung; moving
|
|
715
|
+
* down or staying is always allowed (evidence can be lost, never invented). Unknown states are rejected.
|
|
716
|
+
*/
|
|
717
|
+
function advance(from, to) {
|
|
718
|
+
if (!EVIDENCE_STATES.includes(from)) return { ok: false, state: 'CANDIDATE', reason: `unknown current state: ${String(from)}` };
|
|
719
|
+
if (!EVIDENCE_STATES.includes(to)) return { ok: false, state: from, reason: `unknown target state: ${String(to)}` };
|
|
720
|
+
if (stateRank(to) <= stateRank(from)) return { ok: true, state: to, reason: null };
|
|
721
|
+
if (REQUIRES_PREDECESSOR[to] !== from) return { ok: false, state: from, reason: `cannot reach ${to} from ${from}: ${REQUIRES_PREDECESSOR[to]} is required first` };
|
|
722
|
+
return { ok: true, state: to, reason: null };
|
|
723
|
+
}
|
|
724
|
+
|
|
725
|
+
// Bridges to the older vocabulary so existing consumers keep working.
|
|
726
|
+
function toProofTier(state) {
|
|
727
|
+
const r = stateRank(state);
|
|
728
|
+
if (r >= stateRank('EXPLOIT_CONFIRMED')) return 'execution-proven';
|
|
729
|
+
if (r >= stateRank('STATICALLY_CORROBORATED')) return 'taint-proven';
|
|
730
|
+
return 'unproven';
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
function fromProofTier(tier) {
|
|
734
|
+
if (tier === 'taint-proven') return 'STATICALLY_CORROBORATED';
|
|
735
|
+
// execution-proven under the older single-run marker path is one run, not the 3/3 + independent replay the fabric
|
|
736
|
+
// requires, so it maps to REPRODUCED and never to EXPLOIT_CONFIRMED.
|
|
737
|
+
if (tier === 'execution-proven') return 'REPRODUCED';
|
|
738
|
+
return 'CANDIDATE';
|
|
739
|
+
}
|
|
740
|
+
|
|
741
|
+
// Completeness vocabulary shared with fix-verify: FULL only when nothing was skipped.
|
|
742
|
+
const COMPLETENESS = Object.freeze(['FULL', 'DEGRADED', 'INCOMPLETE']);
|
|
743
|
+
|
|
744
|
+
|
|
745
|
+
/***/ }),
|
|
746
|
+
|
|
747
|
+
/***/ 62199:
|
|
748
|
+
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
749
|
+
|
|
750
|
+
__webpack_require__.r(__webpack_exports__);
|
|
751
|
+
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
|
|
752
|
+
/* harmony export */ findingKey: () => (/* binding */ findingKey),
|
|
753
|
+
/* harmony export */ latestProof: () => (/* binding */ latestProof),
|
|
754
|
+
/* harmony export */ listProofs: () => (/* binding */ listProofs),
|
|
755
|
+
/* harmony export */ saveProof: () => (/* binding */ saveProof),
|
|
756
|
+
/* harmony export */ scrubDeep: () => (/* binding */ scrubDeep)
|
|
757
|
+
/* harmony export */ });
|
|
758
|
+
/* harmony import */ var node_fs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(73024);
|
|
759
|
+
/* harmony import */ var node_path__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(76760);
|
|
760
|
+
/* harmony import */ var _state_dir_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(31174);
|
|
761
|
+
/* harmony import */ var _encryption_provider_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(39984);
|
|
762
|
+
/* harmony import */ var _llm_validator_redact_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(65388);
|
|
763
|
+
/* harmony import */ var _reproducer_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(37055);
|
|
764
|
+
// Proof artifact store: `.agentic-security/proofs/<findingKey>/<recordDigest>.json`.
|
|
765
|
+
//
|
|
766
|
+
// Reuses the existing state machinery rather than adding another: `safeWriteState` (refuses unsafe dirs and symlinks),
|
|
767
|
+
// `maybeEncryptForWrite` / `maybeDecryptForRead` (the `proofs` artifact is registered `confidential`), retention
|
|
768
|
+
// (evidence class) and legal holds (a hold on `proofs` blocks purge). Nothing persisted contains a plaintext credential:
|
|
769
|
+
// records are passed through a recursive secret filter first, and the runner never returns its per-run nonce or secrets.
|
|
770
|
+
|
|
771
|
+
|
|
772
|
+
|
|
773
|
+
|
|
774
|
+
|
|
775
|
+
|
|
776
|
+
|
|
777
|
+
const PROOF_RECORD_SCHEMA = 'agentic-security/proof-record';
|
|
778
|
+
const PROOFS_DIR = 'proofs';
|
|
779
|
+
const MAX_RECORD_BYTES = 512 * 1024;
|
|
780
|
+
|
|
781
|
+
const findingKey = (id) => `${String(id).replace(/[^A-Za-z0-9._-]/g, '_').slice(0, 80)}-${(0,_reproducer_js__WEBPACK_IMPORTED_MODULE_5__/* .sha256 */ .sc)(String(id)).slice(0, 8)}`;
|
|
782
|
+
|
|
783
|
+
// The shared redactor catches key=value shapes; bare tokens need their own pass, so persisted evidence cannot carry one.
|
|
784
|
+
const BARE_SECRET_RES = [
|
|
785
|
+
/\b(?:ghp|gho|ghu|ghs|ghr|github_pat)_[A-Za-z0-9_]{20,}\b/g, /\b(?:AKIA|ASIA)[A-Z0-9]{16}\b/g, /\bsk-[A-Za-z0-9_-]{20,}\b/g,
|
|
786
|
+
/\bxox[abprs]-[A-Za-z0-9-]{10,}\b/g, /\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\b/g,
|
|
787
|
+
/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z ]*PRIVATE KEY-----|$)/g, /\bSECRET-[0-9a-f]{24}-[a-z0-9_-]+\b/g,
|
|
788
|
+
];
|
|
789
|
+
function scrubString(text) {
|
|
790
|
+
let t = String(text);
|
|
791
|
+
try { t = (0,_llm_validator_redact_js__WEBPACK_IMPORTED_MODULE_4__/* .redactSecrets */ .f)(t).text; } catch { return '[unredactable]'; }
|
|
792
|
+
for (const re of BARE_SECRET_RES) t = t.replace(re, '[REDACTED-SECRET]');
|
|
793
|
+
return t;
|
|
794
|
+
}
|
|
795
|
+
|
|
796
|
+
/** Deep-copy `v` with every string passed through the secret redactor. */
|
|
797
|
+
function scrubDeep(v) {
|
|
798
|
+
if (typeof v === 'string') return scrubString(v);
|
|
799
|
+
if (Array.isArray(v)) return v.map(scrubDeep);
|
|
800
|
+
if (v && typeof v === 'object') return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, scrubDeep(x)]));
|
|
801
|
+
return v;
|
|
802
|
+
}
|
|
803
|
+
|
|
804
|
+
function recordDigest(record) {
|
|
805
|
+
const { recordDigest: _omit, ...rest } = record;
|
|
806
|
+
return (0,_reproducer_js__WEBPACK_IMPORTED_MODULE_5__/* .sha256 */ .sc)((0,_reproducer_js__WEBPACK_IMPORTED_MODULE_5__/* .canonicalize */ .dw)(rest));
|
|
807
|
+
}
|
|
808
|
+
|
|
809
|
+
function saveProof(scanRoot, record) {
|
|
810
|
+
const safe = scrubDeep(record);
|
|
811
|
+
safe.schema = PROOF_RECORD_SCHEMA;
|
|
812
|
+
safe.recordDigest = recordDigest(safe);
|
|
813
|
+
const text = JSON.stringify(safe, null, 2);
|
|
814
|
+
if (Buffer.byteLength(text) > MAX_RECORD_BYTES) return { ok: false, reason: 'proof record exceeds the size limit' };
|
|
815
|
+
if (!(0,_state_dir_js__WEBPACK_IMPORTED_MODULE_2__.ensureStateDir)(scanRoot)) return { ok: false, reason: 'no safe state directory for this project' };
|
|
816
|
+
const enc = (0,_encryption_provider_js__WEBPACK_IMPORTED_MODULE_3__/* .maybeEncryptForWrite */ .v2)(scanRoot, PROOFS_DIR, text);
|
|
817
|
+
if (!enc.ok) return { ok: false, reason: enc.reason };
|
|
818
|
+
const file = (0,_state_dir_js__WEBPACK_IMPORTED_MODULE_2__.statePath)(scanRoot, PROOFS_DIR, findingKey(record.findingId), `${safe.recordDigest}.json`);
|
|
819
|
+
if (!(0,_state_dir_js__WEBPACK_IMPORTED_MODULE_2__.safeWriteState)(file, enc.content)) return { ok: false, reason: 'state write refused' };
|
|
820
|
+
return { ok: true, file, digest: safe.recordDigest, encrypted: enc.encrypted };
|
|
821
|
+
}
|
|
822
|
+
|
|
823
|
+
function readRecord(file) {
|
|
824
|
+
const text = (0,_encryption_provider_js__WEBPACK_IMPORTED_MODULE_3__.maybeDecryptForRead)(node_fs__WEBPACK_IMPORTED_MODULE_0__.readFileSync(file, 'utf8'));
|
|
825
|
+
const rec = JSON.parse(text);
|
|
826
|
+
// A record whose content no longer matches its own digest was modified after it was written.
|
|
827
|
+
if (rec.recordDigest !== recordDigest(rec)) return { tampered: true, record: rec };
|
|
828
|
+
return { tampered: false, record: rec };
|
|
829
|
+
}
|
|
830
|
+
|
|
831
|
+
/** Newest-first records for a finding. Tampered records are returned flagged, never silently dropped or trusted. */
|
|
832
|
+
function listProofs(scanRoot, findingId) {
|
|
833
|
+
const dir = (0,_state_dir_js__WEBPACK_IMPORTED_MODULE_2__.statePath)(scanRoot, PROOFS_DIR, findingKey(findingId));
|
|
834
|
+
let names = [];
|
|
835
|
+
try { names = node_fs__WEBPACK_IMPORTED_MODULE_0__.readdirSync(dir).filter((n) => n.endsWith('.json')); } catch { return []; }
|
|
836
|
+
const out = [];
|
|
837
|
+
for (const n of names) {
|
|
838
|
+
const f = node_path__WEBPACK_IMPORTED_MODULE_1__.join(dir, n);
|
|
839
|
+
try { const { tampered, record } = readRecord(f); out.push({ file: f, tampered, record, mtime: node_fs__WEBPACK_IMPORTED_MODULE_0__.statSync(f).mtimeMs }); } catch { out.push({ file: f, tampered: true, record: null, mtime: 0 }); }
|
|
840
|
+
}
|
|
841
|
+
return out.sort((a, b) => b.mtime - a.mtime);
|
|
842
|
+
}
|
|
843
|
+
|
|
844
|
+
function latestProof(scanRoot, findingId) {
|
|
845
|
+
return listProofs(scanRoot, findingId).find((p) => p.record) ?? null;
|
|
846
|
+
}
|
|
847
|
+
|
|
848
|
+
|
|
849
|
+
/***/ })
|
|
850
|
+
|
|
851
|
+
};
|