@clear-capabilities/agentic-security-scanner 0.189.0 → 0.191.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.
@@ -0,0 +1,477 @@
1
+ export const id = 9926;
2
+ export const ids = [9926];
3
+ export const modules = {
4
+
5
+ /***/ 29926:
6
+ /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
7
+
8
+ /* harmony export */ __webpack_require__.d(__webpack_exports__, {
9
+ /* harmony export */ Bu: () => (/* binding */ haskellRefusal),
10
+ /* harmony export */ hp: () => (/* binding */ bootModuleSet),
11
+ /* harmony export */ nD: () => (/* binding */ generateHaskellReproducer)
12
+ /* harmony export */ });
13
+ /* harmony import */ var node_fs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(73024);
14
+ /* harmony import */ var node_path__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(76760);
15
+ /* harmony import */ var node_child_process__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(31421);
16
+ /* harmony import */ var _language_haskell_parser_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(99864);
17
+ /* harmony import */ var _reproducer_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(37055);
18
+ /* harmony import */ var _runner_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(23081);
19
+ // Reproducer generation for Haskell (PRD 1), the third language of `generate.js`. Same contract as JavaScript and Python: a
20
+ // DETERMINISTIC proposal built from the flagged file alone, then run through the ordinary runner, oracle, 3-of-3 repetition and
21
+ // independent replay. A generated reproducer is a proposal that execution either confirms or does not.
22
+ //
23
+ // The program is run by GHC's interpreter (`ghc -e`), not compiled. Why: it needs no C compiler and no linker (so no dependence on
24
+ // the platform's developer tools), it leaves no object files or binaries to account for, it starts in about half a second where a
25
+ // compile-then-run takes a second or more, and there is one process tree to confine instead of a build stage followed by a run
26
+ // stage. Interpreted bytecode calls the same installed libraries a compiled program would, so a shell string reaches the same
27
+ // `System.Process` either way. The tradeoff is stated, not hidden: a program whose behaviour depends on compiled code (FFI, an
28
+ // optimisation-sensitive race) is refused, and `-O` is never in play. A hand-written reproducer may still use `build`/`run` with
29
+ // `{{GHC}}` to compile; both paths run under the same sandbox, timeout and output cap.
30
+ //
31
+ // Two shapes, as in the other languages:
32
+ // script the file reads `getArgs`: it is run as `:main "<payload>"`, so the payload arrives as the first argument;
33
+ // function a top-level function around the flagged line that has a type signature of `String`/`FilePath` parameters and an `IO`
34
+ // result: `ghc -e 'fn "<payload>" ...'` loads the module with every top-level name in scope (the module need not export
35
+ // it) and calls it with the payload in every parameter.
36
+ //
37
+ // Only what the proof environment can load is accepted: the file's imports must be modules of the packages that ship with GHC (the
38
+ // global package database, read from the installed GHC) or other `.hs` files in the repository. A web framework, a database binding
39
+ // or any Hackage package is refused with the package named where it is known. Template Haskell, quasi-quotes, CPP, the foreign
40
+ // function interface and compiler-plugin options are refused too: they run code at load time, before the payload is involved.
41
+ //
42
+ // Classes, each with an oracle that sees its effect and nothing else:
43
+ // command injection (CWE-78) a nonce-named canary file the injected command alone could create;
44
+ // path traversal by a WRITE a file created or changed outside the directory the program writes to (CWE-22);
45
+ // path traversal by a READ a per-run secret, planted in a file one directory above the program's base directory, appears in the
46
+ // program's output (stdout, stderr or, for a function, its printed result). A read whose content never
47
+ // reaches the output leaves nothing to see and stays unproven;
48
+ // argument injection (CWE-88) the called program is replaced by a harness stand-in that acts on one planted option, but only when that
49
+ // option is its FIRST argument; the canary exists only if attacker data reached the first position of the
50
+ // argument vector. It shows the option position is attacker-controlled, not that the real program has a
51
+ // dangerous option, and the generated reproducer says so in its assumptions.
52
+ // Refused on purpose, with the construct named and the way to supply a hand-written reproducer: SSRF (no HTTP client ships with GHC), SQL
53
+ // (no database binding ships with GHC), deserialization, XSS, code injection, argument injection past the first argument, reads and writes
54
+ // whose base directory the file does not state, and any function the proof cannot fill or call. Nothing is executed on a refusal.
55
+
56
+
57
+
58
+
59
+
60
+
61
+
62
+ const MAX_SOURCE = 256 * 1024;
63
+ const MAX_FILES = 8;
64
+ const fail = (reason, extra = {}) => ({ ok: false, reason, ...extra });
65
+
66
+ // Well-known packages that are NOT part of a GHC install, by module prefix, so a refusal can name the package to install.
67
+ const THIRD_PARTY = [
68
+ ['Web.Scotty', 'scotty'], ['Network.Wai', 'wai'], ['Network.HTTP.Types', 'http-types'], ['Network.HTTP.Client', 'http-client'],
69
+ ['Network.HTTP.Simple', 'http-conduit'], ['Network.HTTP.Conduit', 'http-conduit'], ['Network.Wreq', 'wreq'], ['Network.Socket', 'network'],
70
+ ['Servant', 'servant'], ['Yesod', 'yesod'], ['Snap', 'snap'], ['Happstack', 'happstack-server'], ['Data.Aeson', 'aeson'],
71
+ ['Database.SQLite.Simple', 'sqlite-simple'], ['Database.PostgreSQL.Simple', 'postgresql-simple'], ['Database.Persist', 'persistent'],
72
+ ['Database.MySQL', 'mysql-simple'], ['System.Random', 'random'], ['Data.Vector', 'vector'], ['Data.Hashable', 'hashable'],
73
+ ['Data.HashMap', 'unordered-containers'], ['Control.Lens', 'lens'], ['Test.', 'a test framework'], ['Turtle', 'turtle'],
74
+ ['Shelly', 'shelly'], ['System.Process.Typed', 'typed-process'], ['Conduit', 'conduit'], ['Control.Monad.Logger', 'monad-logger'],
75
+ ['Options.Applicative', 'optparse-applicative'], ['Data.Text.Lazy.Builder', null],
76
+ ];
77
+
78
+ const libCache = new Map();
79
+ /** The modules the installed GHC exposes from its global package database (what a program can import with no extra packages). */
80
+ function bootModuleSet(ghc) {
81
+ if (libCache.has(ghc)) return libCache.get(ghc);
82
+ let set = null;
83
+ try {
84
+ const r = (0,node_child_process__WEBPACK_IMPORTED_MODULE_2__.spawnSync)(ghc, ['--print-libdir'], { encoding: 'utf8', timeout: 10_000 });
85
+ const dir = r.status === 0 ? node_path__WEBPACK_IMPORTED_MODULE_1__.join(r.stdout.trim(), 'package.conf.d') : null;
86
+ if (dir && node_fs__WEBPACK_IMPORTED_MODULE_0__.existsSync(dir)) {
87
+ set = new Set();
88
+ for (const f of node_fs__WEBPACK_IMPORTED_MODULE_0__.readdirSync(dir)) {
89
+ if (!f.endsWith('.conf')) continue;
90
+ const text = node_fs__WEBPACK_IMPORTED_MODULE_0__.readFileSync(node_path__WEBPACK_IMPORTED_MODULE_1__.join(dir, f), 'utf8');
91
+ if (/^exposed:\s*False/m.test(text)) continue;
92
+ const m = /^exposed-modules:\s*\n?([\s\S]*?)(?=^\S)/m.exec(text);
93
+ if (!m) continue;
94
+ for (const tok of m[1].split(/[\s,]+/)) if (/^[A-Z][\w']*(?:\.[A-Z][\w']*)*$/.test(tok)) set.add(tok);
95
+ }
96
+ if (!set.has('Prelude')) set = null; // a database that does not even list Prelude was not read correctly
97
+ }
98
+ } catch { set = null; }
99
+ libCache.set(ghc, set);
100
+ return set;
101
+ }
102
+
103
+ function readInside(root, rel) {
104
+ let real; try { real = node_fs__WEBPACK_IMPORTED_MODULE_0__.realpathSync(node_path__WEBPACK_IMPORTED_MODULE_1__.resolve(root, rel)); } catch { return null; }
105
+ const base = node_fs__WEBPACK_IMPORTED_MODULE_0__.realpathSync(root);
106
+ if (!(real === base || real.startsWith(base + node_path__WEBPACK_IMPORTED_MODULE_1__.sep))) return null;
107
+ const st = node_fs__WEBPACK_IMPORTED_MODULE_0__.statSync(real);
108
+ return st.isFile() && st.size <= MAX_SOURCE ? { real, text: node_fs__WEBPACK_IMPORTED_MODULE_0__.readFileSync(real, 'utf8') } : null;
109
+ }
110
+
111
+ /** Split a type on its top-level arrows (arrows inside parentheses or brackets belong to a function-typed argument). */
112
+ function splitArrows(type) {
113
+ const parts = []; let depth = 0; let cur = '';
114
+ for (let i = 0; i < type.length; i++) {
115
+ const c = type[i];
116
+ if ('([{'.includes(c)) depth++; else if (')]}'.includes(c)) depth--;
117
+ if (depth === 0 && c === '-' && type[i + 1] === '>') { parts.push(cur.trim()); cur = ''; i++; continue; }
118
+ cur += c;
119
+ }
120
+ parts.push(cur.trim());
121
+ return parts;
122
+ }
123
+
124
+ // Compile-time code execution and options that change what runs before the payload is involved.
125
+ function loadTimeHazard(text) {
126
+ if (/\{-#\s*LANGUAGE[^#]*\b(?:TemplateHaskell|TemplateHaskellQuotes|QuasiQuotes|CPP|ForeignFunctionInterface|CApiFFI)\b/i.test(text)) return 'it enables Template Haskell, quasi-quotes, CPP or the foreign function interface, which run or require code at load time';
127
+ if (/\{-#\s*OPTIONS(?:_GHC)?\b[^#]*(?:-fplugin|-pgm|-opt[a-zA-Z]|-F\b|-cpp|-fobject-code)/i.test(text)) return 'its OPTIONS_GHC pragma names a plugin, a preprocessor or an external program';
128
+ if (/^\s*foreign\s+(?:import|export)\b/m.test(text)) return 'it uses the foreign function interface';
129
+ return null;
130
+ }
131
+
132
+ function classify(mod, pkg, boot) {
133
+ if (pkg) return { ok: false, name: String(pkg).replace(/^"|"$/g, '') };
134
+ if (boot.has(mod)) return { ok: true };
135
+ for (const [prefix, name] of THIRD_PARTY) if (mod === prefix || mod.startsWith(prefix.endsWith('.') ? prefix : `${prefix}.`)) return { ok: false, name: name ?? mod };
136
+ return { ok: false, name: mod };
137
+ }
138
+
139
+ // ---------------------------------------------------------------------------------------------------------------- parameter types
140
+
141
+ const STRING_TYPES = /^(?:String|Prelude\.String|FilePath|System\.IO\.FilePath|\[Char\])$/;
142
+ const unparen = (t) => { let x = t.trim(); while (x.startsWith('(') && x.endsWith(')') && splitArrows(x.slice(1, -1)).length === 1 && !x.slice(1, -1).includes(',')) x = x.slice(1, -1).trim(); return x; };
143
+
144
+ /** What the file means by `Text` and `ByteString` (an import of the real module, not a local type of the same name) and its one-line `type` aliases. */
145
+ function typeResolver(info, text) {
146
+ const textQ = new Set(); const bytesQ = new Set(); let textBare = false; let bytesBare = false;
147
+ for (const imp of info.imports ?? []) {
148
+ const isText = /^Data\.Text(?:\.Lazy)?$/.test(imp.module);
149
+ const isBytes = /^Data\.ByteString(?:\.(?:Char8|Lazy|Lazy\.Char8))?$/.test(imp.module);
150
+ if (!isText && !isBytes) continue;
151
+ const bare = !imp.qualified && !imp.hiding && (imp.items == null || imp.items.some((i) => /^(?:Text|ByteString)\b/.test(i)));
152
+ if (isText) { textQ.add(imp.as ?? imp.module); textBare ||= bare; } else { bytesQ.add(imp.as ?? imp.module); bytesBare ||= bare; }
153
+ }
154
+ const localDef = (n) => new RegExp(`^(?:data|newtype)\\s+${n}\\b`, 'm').test(text);
155
+ if (localDef('Text')) textBare = false;
156
+ if (localDef('ByteString')) bytesBare = false;
157
+ const aliases = new Map();
158
+ for (const m of text.matchAll(/^type\s+([A-Z][\w']*)\s*=\s*([^\n=]+?)\s*(?:--.*)?$/gm)) aliases.set(m[1], m[2]);
159
+ const resolve = (t, depth = 0) => {
160
+ const x = unparen(t);
161
+ if (depth < 4 && aliases.has(x)) return resolve(aliases.get(x), depth + 1);
162
+ return x;
163
+ };
164
+ const stringish = (t) => {
165
+ const x = resolve(t);
166
+ if (STRING_TYPES.test(x)) return 'string';
167
+ const q = /^(?:([A-Z][\w.]*)\.)?(Text|ByteString)$/.exec(x);
168
+ if (!q) return null;
169
+ if (q[2] === 'Text') return q[1] ? (textQ.has(q[1]) ? 'overloaded' : null) : (textBare ? 'overloaded' : null);
170
+ return q[1] ? (bytesQ.has(q[1]) ? 'overloaded' : null) : (bytesBare ? 'overloaded' : null);
171
+ };
172
+ /** `{lit}` is the Haskell expression for a value of this type holding `value`, `{needsOverloaded}` whether it relies on OverloadedStrings. */
173
+ const fill = (t, value) => {
174
+ const x = resolve(t);
175
+ const one = stringish(x);
176
+ if (one) return { expr: value, overloaded: one === 'overloaded' };
177
+ const list = /^\[\s*(.+?)\s*\]$/.exec(x);
178
+ if (list) { const e = stringish(list[1]); if (e) return { expr: `[${value}]`, overloaded: e === 'overloaded' }; }
179
+ const maybe = /^Maybe\s+(.+)$/.exec(x);
180
+ if (maybe) { const e = stringish(maybe[1]); if (e) return { expr: `(Just ${value})`, overloaded: e === 'overloaded' }; }
181
+ return null;
182
+ };
183
+ /** The result can be shown by `print` and carries the content a read returned (String, Text, ByteString, lists and Maybe of them). */
184
+ const printable = (t) => {
185
+ const x = resolve(t);
186
+ return !!(stringish(x) || (/^\[\s*(.+?)\s*\]$/.exec(x) && stringish(/^\[\s*(.+?)\s*\]$/.exec(x)[1])) || (/^Maybe\s+(.+)$/.exec(x) && stringish(/^Maybe\s+(.+)$/.exec(x)[1])));
187
+ };
188
+ return { fill, printable, resolve };
189
+ }
190
+
191
+ // ---------------------------------------------------------------------------------------------------------------- path traversal: write or read
192
+
193
+ const READ_SINK = /\b(?:readFile'?|readFileBinary)\b|\b(?:openFile|withFile|openBinaryFile|withBinaryFile)\b[^\n]*\bReadMode\b/;
194
+ const READ_PAYLOAD = '../agentic-proof-secret.txt';
195
+ const READ_SECRET_FILE = 'agentic-proof-secret.txt';
196
+ const READ_ORACLE = { type: 'file_disclosure', params: { secret: 'file' } };
197
+ const WRITE_CONSTRUCTS = 'writeFile, appendFile, copyFile, renameFile, or openFile/withFile in WriteMode/AppendMode';
198
+ const READ_CONSTRUCTS = 'readFile, or openFile/withFile in ReadMode';
199
+
200
+ /** Which path operation the flagged line is: its own line first, then the lines around it. */
201
+ function pathKind(sinkLine, around, writeRe) {
202
+ if (writeRe.test(sinkLine)) return 'write';
203
+ if (READ_SINK.test(sinkLine)) return 'read';
204
+ if (writeRe.test(around)) return 'write';
205
+ if (READ_SINK.test(around)) return 'read';
206
+ return null;
207
+ }
208
+
209
+ /**
210
+ * The directories a read is meant to stay under, as far as the source says: a literal that ends in a slash, or sits next to `</>`, or is
211
+ * bound to a name that says directory. The proof creates them (empty) so that `dir/../secret` resolves; a program whose base is not a
212
+ * relative literal cannot be modelled and is refused rather than guessed.
213
+ */
214
+ function readBaseDirs(text) {
215
+ const found = [];
216
+ const add = (lit) => {
217
+ if (!lit || lit.startsWith('/') || lit.includes('..') || lit.includes('\\') || /[{}\s:*?"<>|]/.test(lit)) return;
218
+ const seg = lit.split('/').filter(Boolean)[0];
219
+ if (!seg || seg === '.' || ['canary', 'tmp'].includes(seg) || !/^[A-Za-z0-9._-]{1,32}$/.test(seg) || seg.startsWith('__oracle_')) return;
220
+ if (!found.includes(seg)) found.push(seg);
221
+ };
222
+ for (const m of text.matchAll(/"([^"\\\n]+\/)"/g)) add(m[1]);
223
+ for (const m of text.matchAll(/"([^"\\\n]+)"\s*<\/>/g)) add(m[1]);
224
+ for (const m of text.matchAll(/<\/>\s*"([^"\\\n]+)"/g)) add(m[1]);
225
+ for (const m of text.matchAll(/\b[a-z]\w*(?:Dir|Base|Root|Folder|Path|Directory)\w*'?\s*=\s*"([^"\\\n]+)"/gi)) add(m[1]);
226
+ return found.slice(0, 4);
227
+ }
228
+
229
+ // ---------------------------------------------------------------------------------------------------------------- argument injection
230
+
231
+ // Shells and the tools the proof itself runs are never stood in for: an argument to a shell is command injection (CWE-78), and shadowing
232
+ // a toolchain program on PATH would break the proof rather than test the finding.
233
+ const NEVER_STAND_IN = new Set(['sh', 'bash', 'dash', 'zsh', 'csh', 'tcsh', 'ksh', 'fish', 'env', 'ghc', 'runghc', 'ghci', 'cc', 'gcc', 'clang', 'c++', 'g++', 'ld', 'as', 'ar', 'make', 'cabal', 'stack', 'nix', 'sudo', 'su', 'ssh', 'xargs', 'chmod', 'touch', 'node', 'python', 'python3']);
234
+ const PROCESS_CALL = /\b(callProcess|readProcess|readProcessWithExitCode|spawnProcess|rawSystem|proc)\s+(?:\$\s*)?"([^"\\\s]+)"\s*/;
235
+ const STAND_IN = `#!/bin/sh
236
+ # Stand-in for the program the code under test calls. It is planted by the proof runner, never by the target.
237
+ # It acts on exactly one option, and only when that option is its FIRST argument, by creating the file the option names.
238
+ case "$1" in
239
+ --agentic-proof-write=*) : > "\${1#--agentic-proof-write=}" ;;
240
+ esac
241
+ exit 0
242
+ `;
243
+ // PATH puts the stand-in directory first and keeps the system and toolchain directories after it
244
+ const STAND_IN_PATH = '{{ROOT}}/bin:/opt/ghc/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/opt/homebrew/bin';
245
+
246
+ /** What stands in first position of the argument vector at the call: a named element, a whole list, a fixed string, or something else. */
247
+ function firstArgument(rest) {
248
+ if (rest.startsWith('[')) {
249
+ const inner = rest.slice(1).trimStart();
250
+ if (inner.startsWith('"')) return { kind: 'literal' };
251
+ if (inner.startsWith(']')) return { kind: 'empty' };
252
+ const m = /^([a-z_][\w']*)\s*(?:,|\])/.exec(inner);
253
+ return m ? { kind: 'element', name: m[1] } : { kind: 'complex' };
254
+ }
255
+ if (rest.startsWith('(')) {
256
+ const m = /^\(\s*([a-z_][\w']*)\s*:/.exec(rest);
257
+ return m ? { kind: 'element', name: m[1] } : { kind: 'complex' };
258
+ }
259
+ const m = /^([a-z_][\w']*)\s*(?:$|\)|"|--)/.exec(rest);
260
+ return m ? { kind: 'list', name: m[1] } : { kind: 'complex' };
261
+ }
262
+
263
+ const HINT = 'To prove it anyway, write a reproducer for lang "haskell" (run: ["{{GHC}}", "-ignore-dot-ghci", "-e", "<expression that calls the code>", "<File>.hs"], with an oracle such as command_execution, filesystem_mutation or file_disclosure) and pass it with --reproducer <file>; see the Haskell section of the exploit proof guide. Nothing was executed.';
264
+
265
+ /** What the flagged line is, in words, for a refusal message. */
266
+ function describeLine(finding, root) {
267
+ const src = (() => { try { return readInside(root, String(finding.file)); } catch { return null; } })();
268
+ const line = src ? (src.text.split('\n')[finding.line - 1] ?? '').trim().replace(/\s+/g, ' ').slice(0, 90) : '';
269
+ return line ? `the flagged line \`${line}\`` : 'the flagged code';
270
+ }
271
+
272
+ const REFUSALS = {
273
+ 'CWE-89': (what) => `sql-injection: ${what} reaches a database, and GHC ships no database binding, so a program that queries one imports a package outside the proof environment; a program that shells out to the sqlite3 command-line tool depends on a schema, a table and a column count the proof cannot know and a sqlite3 binary this host may not have. A SQL injection is not proven for Haskell.`,
274
+ 'CWE-502': (what) => `deserialization: ${what} decodes data, and nothing observable happens when a decoder reads hostile bytes unless a gadget exists in the program; the decoders in common use (aeson, yaml, cereal) are packages outside GHC's own. A deserialization flaw is not proven for Haskell.`,
275
+ 'CWE-79': (what) => `cross-site scripting: ${what} builds markup, and the effect is in a browser's DOM, which a command-line run cannot observe. XSS is not proven for Haskell.`,
276
+ 'CWE-94': (what) => `code injection: ${what} evaluates code at run time through an interpreter package (hint, plugins) that does not ship with GHC. Code injection is not proven for Haskell.`,
277
+ 'CWE-918': (what) => `ssrf: ${what} makes a request, and no HTTP client ships with GHC, so any program that makes one imports a package outside the proof environment. SSRF is not proven for Haskell.`,
278
+ 'CWE-1427': (what) => `prompt injection: ${what} builds a model prompt, whose effect needs a model endpoint the proof does not have. Not proven for Haskell.`,
279
+ };
280
+
281
+ /**
282
+ * The reason a Haskell finding of a class this generator does not cover is refused, naming the construct and the way out.
283
+ * @param {{finding: object, root: string, cwe: string|null}} o
284
+ */
285
+ function haskellRefusal({ finding, root, cwe }) {
286
+ const what = describeLine(finding, root);
287
+ const body = REFUSALS[cwe]?.(what) ?? `${cwe ?? 'this class'}: no payload and oracle exist for ${cwe ?? 'it'} in Haskell (${what}). Generated reproducers cover command injection (CWE-78), path traversal by a write or a read (CWE-22) and argument injection into a process call (CWE-88).`;
288
+ return fail(`${body} ${HINT}`);
289
+ }
290
+
291
+ // ---------------------------------------------------------------------------------------------------------------- generation
292
+
293
+ /** @param {{finding: object, root: string, cls: {name: string, payload: string, oracle: object, network?: string, watch?: object, needsHs?: RegExp}, bootModules?: Set<string>}} o */
294
+ function generateHaskellReproducer(o) {
295
+ const r = generateInner(o);
296
+ if (r.ok || r.reason.includes('Nothing was executed.')) return r;
297
+ return { ...r, reason: `${r.reason.replace(/\.$/, '')}. ${HINT}` };
298
+ }
299
+
300
+ function generateInner({ finding, root, cls, bootModules }) {
301
+ const rel = String(finding.file);
302
+ if (cls.name === 'ssrf') return haskellRefusal({ finding, root, cwe: 'CWE-918' });
303
+ const src = readInside(root, rel);
304
+ if (!src) return fail('the flagged file is missing, outside the repository, or too large');
305
+ const hazard = loadTimeHazard(src.text);
306
+ if (hazard) return fail(`the flagged file is refused: ${hazard}`);
307
+ if (/\{\{[A-Z_]+(?::[a-z0-9_-]{1,32})?\}\}/.test(src.text)) return fail('the flagged file contains text shaped like a proof placeholder ({{NAME}}), which the runner would substitute inside the program');
308
+ const info = (0,_language_haskell_parser_js__WEBPACK_IMPORTED_MODULE_3__/* .parseHaskell */ .cX)(src.text);
309
+ if (!info || info.status !== 'parsed') return fail('the flagged file could not be parsed as Haskell');
310
+ const lines = src.text.split('\n');
311
+ const sinkLine = lines[finding.line - 1] ?? '';
312
+ const around = lines.slice(Math.max(0, finding.line - 3), finding.line + 2).join('\n');
313
+
314
+ // the class decides what is planted and what is watched; for a path operation the flagged line decides which of two it is
315
+ let spec = cls;
316
+ let kind = cls.name;
317
+ if (cls.name === 'path-traversal') {
318
+ const k = pathKind(sinkLine, around, cls.needsHs);
319
+ if (!k) return fail(`path-traversal: ${describeLine(finding, root)} is not a write (${WRITE_CONSTRUCTS}) or a read (${READ_CONSTRUCTS}); other file operations (removeFile, createDirectory, listDirectory, doesFileExist, and the like) leave nothing the oracle can observe`);
320
+ if (k === 'read') { kind = 'path-traversal-read'; spec = { name: 'path-traversal-read', payload: READ_PAYLOAD, oracle: READ_ORACLE }; }
321
+ }
322
+
323
+ const tools = (0,_runner_js__WEBPACK_IMPORTED_MODULE_5__/* .hostTools */ .qV)();
324
+ const boot = bootModules ?? (tools.ghc ? bootModuleSet(tools.ghc) : null);
325
+ if (!boot) return fail('no working GHC was found to list the modules the proof environment can import (install ghc, or run `agentic-security proof doctor`)');
326
+
327
+ // the entry module is placed at its module path so that other modules can import it; Main goes to Main.hs
328
+ const modName = info.module?.name ?? 'Main';
329
+ const entry = `${modName.replaceAll('.', '/')}.hs`;
330
+ const rootReal = node_fs__WEBPACK_IMPORTED_MODULE_0__.realpathSync(root);
331
+ const entryDir = node_path__WEBPACK_IMPORTED_MODULE_1__.dirname(src.real);
332
+ const modRel = modName.replaceAll('.', node_path__WEBPACK_IMPORTED_MODULE_1__.sep);
333
+ const srcRoot = src.real.endsWith(`${modRel}.hs`) ? src.real.slice(0, src.real.length - modRel.length - 3) : `${entryDir}${node_path__WEBPACK_IMPORTED_MODULE_1__.sep}`;
334
+ const searchRoots = [...new Set([srcRoot.replace(/[\\/]$/, ''), ...['src', 'app', 'lib', ''].map((d) => node_path__WEBPACK_IMPORTED_MODULE_1__.join(rootReal, d))])];
335
+ const sources = {}; const external = []; const seen = new Set([modName]);
336
+ let count = 0;
337
+ const visit = (imports) => {
338
+ for (const imp of imports) {
339
+ const mod = imp.module;
340
+ if (seen.has(mod)) continue;
341
+ seen.add(mod);
342
+ let local = null;
343
+ for (const base of searchRoots) { const cand = node_path__WEBPACK_IMPORTED_MODULE_1__.join(base, `${mod.replaceAll('.', '/')}.hs`); const r = readInside(root, node_path__WEBPACK_IMPORTED_MODULE_1__.relative(rootReal, cand)); if (r) { local = r; break; } }
344
+ if (local && !imp.package) {
345
+ if (++count > MAX_FILES) return fail(`the file pulls in more than ${MAX_FILES} repository modules`);
346
+ const dep = (0,_language_haskell_parser_js__WEBPACK_IMPORTED_MODULE_3__/* .parseHaskell */ .cX)(local.text);
347
+ if (!dep || dep.status !== 'parsed') return fail(`the module ${mod} could not be parsed as Haskell`);
348
+ const h = loadTimeHazard(local.text); if (h) return fail(`the module ${mod} is refused: ${h}`);
349
+ if (/\{\{[A-Z_]+(?::[a-z0-9_-]{1,32})?\}\}/.test(local.text)) return fail(`the module ${mod} contains text shaped like a proof placeholder ({{NAME}})`);
350
+ sources[`${mod.replaceAll('.', '/')}.hs`] = node_path__WEBPACK_IMPORTED_MODULE_1__.relative(rootReal, local.real);
351
+ const r = visit(dep.imports ?? []); if (r) return r;
352
+ continue;
353
+ }
354
+ const c = classify(mod, imp.package, boot);
355
+ if (!c.ok) external.push(c.name);
356
+ }
357
+ return null;
358
+ };
359
+ const bad = visit(info.imports ?? []);
360
+ if (bad) return bad;
361
+ 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 packages that ship with GHC and files in the repository can be loaded`, { missing: [...new Set(external)] });
362
+ sources[entry] = rel;
363
+
364
+ const assumptions = [];
365
+ const base = { schema: 'agentic-security/reproducer', version: 1, findingId: String(finding.stableId ?? finding.id ?? 'generated'), lang: 'haskell', oracle: spec.oracle, network: spec.network ?? 'none', ...(spec.watch ? { watch: spec.watch } : {}) };
366
+ if (spec.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');
367
+ const ghcRun = (expr, overloaded = false) => ['{{GHC}}', '-ignore-dot-ghci', ...(overloaded ? ['-e', ':set -XOverloadedStrings'] : []), '-e', expr, entry];
368
+ const literal = (s) => JSON.stringify(s); // payloads are fixed strings with no quote or backslash; this is a plain Haskell string literal
369
+ const resolver = typeResolver(info, src.text);
370
+
371
+ // what the class plants beside the program
372
+ const extras = { files: {}, build: undefined, env: undefined };
373
+ if (kind === 'path-traversal-read') {
374
+ const dirs = readBaseDirs(src.text);
375
+ if (!dirs.length) return fail(`path-traversal: ${describeLine(finding, root)} reads a path whose base directory is not a relative literal in the file (a path built from getCurrentDirectory, an environment variable, an absolute directory or a configuration value), so the proof cannot plant the file it would escape to`);
376
+ extras.files = { [READ_SECRET_FILE]: '{{SECRET:file}}', ...Object.fromEntries(dirs.map((d) => [`${d}/.keep`, ''])) };
377
+ assumptions.push(`the read is assumed to be confined under ${dirs.map((d) => `"${d}"`).join(' or ')}, one directory below the working directory; the proof plants a file one level up (${READ_PAYLOAD}) and sees it only if it reaches the program's output (stdout, stderr or, for a function, its printed result)`);
378
+ }
379
+
380
+ // shape 1: a program that reads its payload from the command line
381
+ const hasMain = (info.functions ?? []).some((f) => f.scope === 'top' && f.name === 'main');
382
+ if (/\bgetArgs\b/.test(src.text) && hasMain) {
383
+ if (kind === 'argument-injection') {
384
+ const call = argumentCall(lines, finding);
385
+ if (!call.ok) return call;
386
+ if (call.first.kind !== 'list' || !new RegExp(`\\b${call.first.name}\\s*<-\\s*getArgs\\b`).test(src.text)) return fail(`argument-injection: the first argument of the call to ${call.exe} is ${describeFirst(call.first)}, and the proof can place the payload only where the whole argument vector comes straight from getArgs (\`args <- getArgs\` then the call with \`args\`)`);
387
+ Object.assign(extras, standIn(call.exe));
388
+ assumptions.push(...standInAssumptions(call.exe));
389
+ }
390
+ assumptions.push('the payload is passed as the first and only command-line argument; a program that expects other arguments will not reach the flagged line');
391
+ const reproducer = { ...base, sources, ...(Object.keys(extras.files).length ? { files: extras.files } : {}), ...(extras.build ? { build: extras.build } : {}), ...(extras.env ? { env: extras.env } : {}), run: ghcRun(`:main ${literal(spec.payload)}`) };
392
+ const errs = (0,_reproducer_js__WEBPACK_IMPORTED_MODULE_4__/* .validateReproducer */ .mC)(reproducer);
393
+ return errs.length ? fail(`the generated reproducer is invalid: ${errs[0]}`) : { ok: true, reproducer, basis: { shape: 'script', class: spec.name, entry: rel, line: finding.line, assumptions } };
394
+ }
395
+
396
+ // shape 2: a top-level function around the flagged line
397
+ const fn = (info.functions ?? []).filter((f) => f.scope === 'top' && f.name !== 'main' && /^[a-z_][\w']*$/.test(f.name)).find((f) => {
398
+ const end = Math.max(f.span.endLine, ...(f.clauses ?? []).map((c) => c.span?.endLine ?? 0));
399
+ return f.span.startLine <= finding.line && end >= finding.line;
400
+ });
401
+ if (!fn) return fail('the flagged line is not inside a top-level function, and the file does not read getArgs in a main');
402
+ const sig = (info.signatures ?? []).find((s) => s.scope === 'top' && s.names.includes(fn.name));
403
+ if (!sig) return fail(`${fn.name} has no type signature, so the proof cannot tell what to pass it`);
404
+ const sigText = lines.slice(sig.span.startLine - 1, sig.span.endLine).join(' ');
405
+ const m = new RegExp(`${fn.name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}[^:]*::\\s*([\\s\\S]*)$`).exec(sigText);
406
+ if (!m) return fail(`the type signature of ${fn.name} could not be read`);
407
+ const type = m[1].replace(/--.*$/, '').trim();
408
+ if (type.includes('=>') || /\bforall\b/.test(type)) return fail(`${fn.name} is polymorphic or constrained (${type.slice(0, 60)}), so the proof cannot choose its arguments`);
409
+ const parts = splitArrows(type);
410
+ const result = parts[parts.length - 1]; const params = parts.slice(0, -1);
411
+ if (!/^IO\b/.test(result)) return fail(`${fn.name} returns ${result.slice(0, 40)}, not IO, so calling it would not perform the flagged operation`);
412
+ if (!params.length) return fail(`${fn.name} takes no parameters, so the payload has no way in`);
413
+ const resultInner = result.replace(/^IO\s*/, '').trim();
414
+ if (kind === 'path-traversal-read' && resultInner !== '()' && !resolver.printable(resultInner)) return fail(`${fn.name} returns IO ${resultInner.slice(0, 40)}, whose content the proof cannot print; a read is observed only in the output, so the result must be (), String, Text, ByteString or a list or Maybe of them`);
415
+
416
+ let payloadFor = () => spec.payload; // which parameters get the payload (all, unless the class says which)
417
+ if (kind === 'argument-injection') {
418
+ const call = argumentCall(lines, finding);
419
+ if (!call.ok) return call;
420
+ const headLine = lines[fn.span.startLine - 1] ?? '';
421
+ const head = new RegExp(`^${fn.name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}((?:\\s+[a-z_][\\w']*)*)\\s*(?:=|\\|)`).exec(headLine);
422
+ const names = head ? head[1].trim().split(/\s+/).filter(Boolean) : null;
423
+ if (!names || names.length !== params.length) return fail(`argument-injection: the parameters of ${fn.name} are patterns or the definition is point-free, so the proof cannot tell which parameter reaches the call`);
424
+ if (call.first.kind !== 'element' && call.first.kind !== 'list') return fail(`argument-injection: the first argument of the call to ${call.exe} is ${describeFirst(call.first)}, and the proof can place the payload only where a plain parameter of ${fn.name} stands first in the argument vector`);
425
+ const at = names.indexOf(call.first.name);
426
+ if (at < 0) return fail(`argument-injection: the first argument of the call to ${call.exe} is \`${call.first.name}\`, which is not a parameter of ${fn.name}, so the proof cannot place the payload there`);
427
+ const shape = resolver.fill(params[at], 'x');
428
+ if (!shape) return fail(`${fn.name} takes a parameter of type ${params[at].slice(0, 40)}; only String, FilePath, Text, ByteString and lists or Maybe of them can be filled with a payload`);
429
+ if (call.first.kind === 'list' && !/^\[/.test(shape.expr)) return fail(`argument-injection: ${call.first.name} is passed as the whole argument vector but has type ${params[at].slice(0, 40)}, not a list of strings`);
430
+ if (call.first.kind === 'element' && /^\[/.test(shape.expr)) return fail(`argument-injection: ${call.first.name} is a list but stands as one element of the argument vector`);
431
+ payloadFor = (i) => (i === at ? spec.payload : 'benign');
432
+ Object.assign(extras, standIn(call.exe));
433
+ assumptions.push(...standInAssumptions(call.exe), `the payload is placed in the parameter \`${call.first.name}\` only; the other parameters get the value "benign"`);
434
+ } else assumptions.push('the payload is passed in every parameter (a String has no request-like stand-in), which is an approximation of how the function is really called');
435
+
436
+ const filled = [];
437
+ let overloaded = false;
438
+ for (let i = 0; i < params.length; i++) {
439
+ const f = resolver.fill(params[i], literal(payloadFor(i)));
440
+ if (!f) return fail(`${fn.name} takes a parameter of type ${params[i].slice(0, 40)}; only String, FilePath, Text, ByteString and lists or Maybe of them can be filled with a payload`);
441
+ filled.push(f.expr); overloaded ||= f.overloaded;
442
+ }
443
+ if (overloaded) assumptions.push('Text and ByteString arguments are written as string literals under OverloadedStrings, set for the call only, not for the program');
444
+ const tail = kind === 'path-traversal-read' && resultInner !== '()' ? '>>= print' : '>>= \\_ -> return ()';
445
+ const call = `${fn.name} ${filled.join(' ')} ${tail}`;
446
+ const reproducer = { ...base, sources, ...(Object.keys(extras.files).length ? { files: extras.files } : {}), ...(extras.build ? { build: extras.build } : {}), ...(extras.env ? { env: extras.env } : {}), run: ghcRun(call, overloaded) };
447
+ const errs = (0,_reproducer_js__WEBPACK_IMPORTED_MODULE_4__/* .validateReproducer */ .mC)(reproducer);
448
+ return errs.length ? fail(`the generated reproducer is invalid: ${errs[0]}`) : { ok: true, reproducer, basis: { shape: 'function', class: spec.name, entry: rel, line: finding.line, function: `${fn.name}(${params.length} ${params.every((p) => STRING_TYPES.test(p.trim())) ? 'String' : params.length === 1 ? 'parameter' : 'parameters'})`, assumptions } };
449
+ }
450
+
451
+ function describeFirst(first) {
452
+ return { literal: 'a fixed string', empty: 'absent (an empty list)', complex: 'an expression the proof cannot read as a plain parameter', element: 'a parameter', list: 'a list' }[first.kind] ?? 'unreadable';
453
+ }
454
+
455
+ /** Find the process call at the flagged line and what stands first in its argument vector. */
456
+ function argumentCall(lines, finding) {
457
+ const window = lines.slice(Math.max(0, finding.line - 1), finding.line + 2).join(' ').replace(/\s+/g, ' ');
458
+ const m = PROCESS_CALL.exec(window);
459
+ if (!m) return fail('argument-injection: the flagged line is not a call to callProcess, readProcess, readProcessWithExitCode, spawnProcess, rawSystem or proc with the program named by a string literal, so the proof cannot tell which program receives the arguments');
460
+ const exe = m[2];
461
+ if (NEVER_STAND_IN.has(exe) || !/^[A-Za-z0-9][A-Za-z0-9._+-]{0,31}$/.test(exe)) return fail(`argument-injection: the program is \`${exe}\`, which the proof does not stand in for (a shell, an interpreter or a toolchain program; an argument to a shell is command injection, CWE-78)`);
462
+ const rest = window.slice(m.index + m[0].length).trimStart();
463
+ const first = firstArgument(rest);
464
+ if (first.kind === 'literal' || first.kind === 'empty') return fail(`argument-injection: the first argument of the call to ${exe} is ${describeFirst(first)}, and the proof covers only attacker data in the FIRST position, where every conventional option parser reads a leading dash as an option; later positions depend on the program's own grammar (an option such as -f takes the next word as its value)`);
465
+ return { ok: true, exe, first };
466
+ }
467
+
468
+ /** The stand-in program, its permission and the PATH that finds it. */
469
+ function standIn(exe) {
470
+ return { files: { [`bin/${exe}`]: STAND_IN }, build: ['/bin/chmod', '755', `bin/${exe}`], env: { PATH: STAND_IN_PATH } };
471
+ }
472
+ const standInAssumptions = (exe) => [`the program \`${exe}\` is replaced by a harness stand-in that acts on one planted option when it is the FIRST argument; a confirmation shows attacker data reaches the first argument unseparated and unvalidated, not that the real ${exe} has a dangerous option`];
473
+
474
+
475
+ /***/ })
476
+
477
+ };