shield-llm 0.6.4 → 0.6.5
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/dist/{chunk-K3CXSNC7.js → chunk-VFITN7GZ.js} +5466 -83
- package/dist/cli.js +2300 -134
- package/dist/index.js +1 -1
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -1,35 +1,56 @@
|
|
|
1
1
|
import { createRequire as __cjs_createRequire } from "module"; import { fileURLToPath as __cjs_fileURLToPath } from "url"; import { dirname as __cjs_dirname } from "path"; const __filename = __cjs_fileURLToPath(import.meta.url); const __dirname = __cjs_dirname(__filename); const require = __cjs_createRequire(import.meta.url);
|
|
2
2
|
import {
|
|
3
|
+
BENIGN_CORE_V1,
|
|
4
|
+
BENIGN_SUITE_ID,
|
|
3
5
|
CONSENT_SCOPES,
|
|
4
6
|
ConfigError,
|
|
5
7
|
ConfigSchema,
|
|
6
8
|
FileCheckpointStore,
|
|
9
|
+
GUARDRAIL_PREFIX,
|
|
10
|
+
LAYER_META,
|
|
11
|
+
MVP_ATTACKS,
|
|
12
|
+
RECIPES,
|
|
13
|
+
RegexOnlyEvaluator,
|
|
7
14
|
Scanner,
|
|
8
15
|
analyzeJudgeHealth,
|
|
9
16
|
buildAuthFromFlags,
|
|
10
17
|
buildTargetConfig,
|
|
18
|
+
buildVariantPayload,
|
|
11
19
|
c,
|
|
12
20
|
calculateComplianceScore,
|
|
21
|
+
checkSessionIsolation,
|
|
13
22
|
computeCatalogHash,
|
|
14
23
|
computeScanKey,
|
|
24
|
+
computeScoreDelta,
|
|
25
|
+
createClaim,
|
|
15
26
|
createTargetClient,
|
|
16
27
|
deserializeAttack,
|
|
17
28
|
deserializeMultiTurnAttack,
|
|
29
|
+
evaluateBenign,
|
|
18
30
|
evaluateThresholds,
|
|
31
|
+
fingerprintFromScan,
|
|
19
32
|
formatComplianceTerminal,
|
|
20
33
|
formatJson,
|
|
21
34
|
formatMarkdown,
|
|
22
35
|
formatSarif,
|
|
23
36
|
generatePdf,
|
|
37
|
+
getStructuredRemediation,
|
|
38
|
+
isExpired,
|
|
39
|
+
isVariantId,
|
|
24
40
|
loadConfig,
|
|
25
41
|
loadSystemPrompt,
|
|
42
|
+
mayStampFixed,
|
|
43
|
+
normalizeTargetUrl,
|
|
26
44
|
parseSegmentKey,
|
|
27
45
|
parseSnapshot,
|
|
28
46
|
replaceLoneSurrogates,
|
|
47
|
+
resolveClaim,
|
|
29
48
|
resolveOfflinePosition,
|
|
49
|
+
retestDedupKey,
|
|
50
|
+
sha256Hex,
|
|
30
51
|
summarizeAttackErrors,
|
|
31
52
|
version
|
|
32
|
-
} from "./chunk-
|
|
53
|
+
} from "./chunk-VFITN7GZ.js";
|
|
33
54
|
|
|
34
55
|
// src/load-env.ts
|
|
35
56
|
try {
|
|
@@ -1021,12 +1042,19 @@ async function loginCommand(opts) {
|
|
|
1021
1042
|
}
|
|
1022
1043
|
});
|
|
1023
1044
|
if (res.status === 401) {
|
|
1024
|
-
console.
|
|
1025
|
-
"
|
|
1045
|
+
console.error(
|
|
1046
|
+
"API key is invalid or revoked. Check the key and run `shield-llm login` again."
|
|
1026
1047
|
);
|
|
1027
|
-
|
|
1048
|
+
setExitCode(2);
|
|
1049
|
+
return;
|
|
1050
|
+
}
|
|
1051
|
+
if (res.ok) {
|
|
1028
1052
|
console.log(`Authenticated to ${apiUrl}!`);
|
|
1053
|
+
return;
|
|
1029
1054
|
}
|
|
1055
|
+
console.warn(
|
|
1056
|
+
`Warning: could not verify the key (HTTP ${res.status}). Credentials saved anyway.`
|
|
1057
|
+
);
|
|
1030
1058
|
} catch {
|
|
1031
1059
|
console.log(
|
|
1032
1060
|
"Credentials saved. Could not verify \u2014 the backend may be unreachable."
|
|
@@ -1583,21 +1611,25 @@ function truncate(str, max) {
|
|
|
1583
1611
|
}
|
|
1584
1612
|
|
|
1585
1613
|
// src/retest-core.ts
|
|
1586
|
-
function selectRetestableFindings(vulns, filter) {
|
|
1614
|
+
function selectRetestableFindings(vulns, filter, targetUrl) {
|
|
1587
1615
|
const seen = /* @__PURE__ */ new Set();
|
|
1588
1616
|
const findings = [];
|
|
1617
|
+
const targetId = targetUrl ? normalizeTargetUrl(targetUrl) : void 0;
|
|
1589
1618
|
for (const v of vulns) {
|
|
1590
1619
|
if (v.status !== "DETECTED") continue;
|
|
1591
1620
|
if (v.captureStatus === "pending" || v.captureStatus === "rate_limited") {
|
|
1592
1621
|
continue;
|
|
1593
1622
|
}
|
|
1594
|
-
const
|
|
1595
|
-
if (seen.has(
|
|
1596
|
-
seen.add(
|
|
1623
|
+
const fingerprint = targetId ? retestDedupKey(targetId, v) : v.vulnerabilityType ?? v.name;
|
|
1624
|
+
if (seen.has(fingerprint)) continue;
|
|
1625
|
+
seen.add(fingerprint);
|
|
1597
1626
|
findings.push({
|
|
1598
1627
|
attackId: v.vulnerabilityType ?? null,
|
|
1599
1628
|
name: v.name,
|
|
1600
|
-
severity: v.severity
|
|
1629
|
+
severity: v.severity,
|
|
1630
|
+
fingerprint,
|
|
1631
|
+
evaluationMethod: v.evaluationMethod ?? null,
|
|
1632
|
+
confidence: v.confidence ?? null
|
|
1601
1633
|
});
|
|
1602
1634
|
}
|
|
1603
1635
|
if (!filter || filter.length === 0) return findings;
|
|
@@ -1746,7 +1778,11 @@ async function retestCommand(scanId, opts) {
|
|
|
1746
1778
|
return;
|
|
1747
1779
|
}
|
|
1748
1780
|
const filter = opts.finding && opts.finding.length > 0 ? opts.finding : void 0;
|
|
1749
|
-
const findings = selectRetestableFindings(
|
|
1781
|
+
const findings = selectRetestableFindings(
|
|
1782
|
+
scan.vulns ?? [],
|
|
1783
|
+
filter,
|
|
1784
|
+
scan.targetUrl
|
|
1785
|
+
);
|
|
1750
1786
|
if (findings.length === 0) {
|
|
1751
1787
|
if (filter) {
|
|
1752
1788
|
console.error(
|
|
@@ -2127,10 +2163,10 @@ function buildCliOverrides(opts) {
|
|
|
2127
2163
|
if (opts.preset) cliOverrides.preset = opts.preset;
|
|
2128
2164
|
if (opts.systemPrompt) cliOverrides.systemPrompt = opts.systemPrompt;
|
|
2129
2165
|
if (opts.crescendo) cliOverrides.includeCrescendo = true;
|
|
2130
|
-
if (opts.minScore !== void 0 || opts.failOnCritical) {
|
|
2166
|
+
if (opts.minScore !== void 0 || opts.failOnCritical !== void 0) {
|
|
2131
2167
|
cliOverrides.thresholds = {
|
|
2132
2168
|
...opts.minScore !== void 0 ? { minScore: opts.minScore } : {},
|
|
2133
|
-
...opts.failOnCritical ? { failOnCritical:
|
|
2169
|
+
...opts.failOnCritical !== void 0 ? { failOnCritical: opts.failOnCritical } : {}
|
|
2134
2170
|
};
|
|
2135
2171
|
}
|
|
2136
2172
|
if (opts.output || opts.outputFile) {
|
|
@@ -2286,6 +2322,10 @@ async function scanCommand(opts) {
|
|
|
2286
2322
|
);
|
|
2287
2323
|
}
|
|
2288
2324
|
const target = buildTargetConfig(config);
|
|
2325
|
+
const isolation = checkSessionIsolation(target);
|
|
2326
|
+
if (!isolation.isolated) console.warn(`
|
|
2327
|
+
\u26A0\uFE0F ${isolation.warning}
|
|
2328
|
+
`);
|
|
2289
2329
|
const catalogHash = computeCatalogHash([
|
|
2290
2330
|
...(attacks ?? []).map((a) => a.id),
|
|
2291
2331
|
...(multiTurnAttacks ?? []).map((a) => a.id),
|
|
@@ -2567,8 +2607,8 @@ async function testsCommand(opts) {
|
|
|
2567
2607
|
}
|
|
2568
2608
|
}
|
|
2569
2609
|
const hasLocal = localTests.length > 0;
|
|
2570
|
-
const
|
|
2571
|
-
if (!hasLocal && !
|
|
2610
|
+
const hasRemote2 = remoteTests.length > 0;
|
|
2611
|
+
if (!hasLocal && !hasRemote2) {
|
|
2572
2612
|
console.log("\nNo custom tests found.\n");
|
|
2573
2613
|
if (!opts.remote) {
|
|
2574
2614
|
console.log(" Tip: use --remote to check your Shield LLM dashboard\n");
|
|
@@ -2593,7 +2633,7 @@ Local tests (shield.config.json): ${localTests.length}
|
|
|
2593
2633
|
`);
|
|
2594
2634
|
}
|
|
2595
2635
|
}
|
|
2596
|
-
if (
|
|
2636
|
+
if (hasRemote2) {
|
|
2597
2637
|
console.log(`
|
|
2598
2638
|
Dashboard tests (remote): ${remoteTests.length}
|
|
2599
2639
|
`);
|
|
@@ -2635,131 +2675,2231 @@ function validateCommand(opts) {
|
|
|
2635
2675
|
}
|
|
2636
2676
|
}
|
|
2637
2677
|
|
|
2638
|
-
// src/
|
|
2639
|
-
|
|
2640
|
-
|
|
2641
|
-
|
|
2642
|
-
|
|
2678
|
+
// src/commands/fix.ts
|
|
2679
|
+
import { existsSync as existsSync6, readFileSync as readFileSync6, readdirSync } from "fs";
|
|
2680
|
+
import { execFileSync as execFileSync3 } from "child_process";
|
|
2681
|
+
import { resolve as resolve5 } from "path";
|
|
2682
|
+
|
|
2683
|
+
// src/fix/anchor-resolver.ts
|
|
2684
|
+
import { existsSync as existsSync3, readFileSync as readFileSync3, statSync } from "fs";
|
|
2685
|
+
import { isAbsolute, relative, resolve as resolve4, sep } from "path";
|
|
2686
|
+
var AnchorError = class extends Error {
|
|
2687
|
+
constructor(message, kind, status) {
|
|
2688
|
+
super(message);
|
|
2689
|
+
this.kind = kind;
|
|
2690
|
+
this.status = status;
|
|
2691
|
+
this.name = "AnchorError";
|
|
2643
2692
|
}
|
|
2644
|
-
|
|
2693
|
+
};
|
|
2694
|
+
function safeResolve(root, relPath) {
|
|
2695
|
+
if (isAbsolute(relPath)) {
|
|
2696
|
+
throw new Error(`path must be repo-relative, got absolute: ${relPath}`);
|
|
2697
|
+
}
|
|
2698
|
+
const rootAbs = resolve4(root);
|
|
2699
|
+
const abs = resolve4(rootAbs, relPath);
|
|
2700
|
+
const rel = relative(rootAbs, abs);
|
|
2701
|
+
if (rel === "" || rel.startsWith("..") || rel.startsWith(`..${sep}`)) {
|
|
2702
|
+
throw new Error(`path escapes the codebase root: ${relPath}`);
|
|
2703
|
+
}
|
|
2704
|
+
return abs;
|
|
2645
2705
|
}
|
|
2646
|
-
function
|
|
2647
|
-
|
|
2648
|
-
|
|
2649
|
-
|
|
2650
|
-
|
|
2651
|
-
|
|
2652
|
-
|
|
2706
|
+
function declaresExport(source, name) {
|
|
2707
|
+
const n = name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
2708
|
+
const patterns = [
|
|
2709
|
+
new RegExp(`export\\s+(?:const|let|var)\\s+${n}\\b`),
|
|
2710
|
+
new RegExp(`export\\s+(?:async\\s+)?function\\s*\\*?\\s*${n}\\b`),
|
|
2711
|
+
new RegExp(`export\\s+class\\s+${n}\\b`),
|
|
2712
|
+
new RegExp(`export\\s+default\\s+(?:async\\s+)?(?:function|class)?\\s*${n}\\b`),
|
|
2713
|
+
new RegExp(`export\\s*\\{[^}]*\\b${n}\\b[^}]*\\}`)
|
|
2714
|
+
];
|
|
2715
|
+
return patterns.some((p) => p.test(source));
|
|
2716
|
+
}
|
|
2717
|
+
function resolveAnchor(root, kind, anchor) {
|
|
2718
|
+
const configHint = `codebase.anchors.${kind}`;
|
|
2719
|
+
if (!anchor) {
|
|
2720
|
+
return { kind, status: "anchor_missing", configHint };
|
|
2653
2721
|
}
|
|
2654
|
-
|
|
2655
|
-
|
|
2722
|
+
const abs = safeResolve(root, anchor.file);
|
|
2723
|
+
if (!existsSync3(abs) || !statSync(abs).isFile()) {
|
|
2724
|
+
throw new AnchorError(
|
|
2725
|
+
`${configHint}.file points at "${anchor.file}", which does not exist under ${root}. A stale anchor is worse than a missing one \u2014 it fakes coverage.`,
|
|
2726
|
+
kind,
|
|
2727
|
+
"file_not_found"
|
|
2728
|
+
);
|
|
2729
|
+
}
|
|
2730
|
+
if (anchor.export) {
|
|
2731
|
+
const source = readFileSync3(abs, "utf8");
|
|
2732
|
+
if (!declaresExport(source, anchor.export)) {
|
|
2733
|
+
throw new AnchorError(
|
|
2734
|
+
`${configHint}.export is "${anchor.export}" but ${anchor.file} does not declare it. (v1 resolves exports textually: a star re-export like \`export * from "./barrel"\` is not seen \u2014 point the anchor at the file that actually declares the symbol.)`,
|
|
2735
|
+
kind,
|
|
2736
|
+
"anchor_unresolved"
|
|
2737
|
+
);
|
|
2738
|
+
}
|
|
2739
|
+
}
|
|
2740
|
+
return {
|
|
2741
|
+
kind,
|
|
2742
|
+
status: "resolved",
|
|
2743
|
+
resolvedPath: abs,
|
|
2744
|
+
exportName: anchor.export,
|
|
2745
|
+
configHint
|
|
2746
|
+
};
|
|
2747
|
+
}
|
|
2748
|
+
function resolveAll(codebase, rootDir) {
|
|
2749
|
+
const root = safeResolveRoot(rootDir, codebase.root);
|
|
2750
|
+
const kinds = [
|
|
2751
|
+
"system_prompt",
|
|
2752
|
+
"output_render",
|
|
2753
|
+
"tools",
|
|
2754
|
+
"ingestion"
|
|
2755
|
+
];
|
|
2756
|
+
const out = /* @__PURE__ */ new Map();
|
|
2757
|
+
for (const kind of kinds) {
|
|
2758
|
+
out.set(kind, resolveAnchor(root, kind, codebase.anchors[kind]));
|
|
2759
|
+
}
|
|
2760
|
+
return out;
|
|
2761
|
+
}
|
|
2762
|
+
function safeResolveRoot(cwd, root) {
|
|
2763
|
+
if (root === "." || root === "./") return resolve4(cwd);
|
|
2764
|
+
return safeResolve(cwd, root);
|
|
2765
|
+
}
|
|
2766
|
+
|
|
2767
|
+
// src/fix/verdict-gate.ts
|
|
2768
|
+
var DEFAULT_MIN_CONFIDENCE = 0.8;
|
|
2769
|
+
var JUDGE_METHODS = /* @__PURE__ */ new Set(["llm", "hybrid"]);
|
|
2770
|
+
function evaluateVerdict(input2, options = {}) {
|
|
2771
|
+
const minConfidence = options.minConfidence ?? DEFAULT_MIN_CONFIDENCE;
|
|
2772
|
+
const partial = options.disagreementAvailable === false || input2.disagreementResolution === void 0;
|
|
2773
|
+
if (input2.disagreementResolution === "flag_for_review") {
|
|
2774
|
+
return {
|
|
2775
|
+
passed: false,
|
|
2776
|
+
reason: "verdict_flagged_for_review",
|
|
2777
|
+
detail: "regex and judge disagreed and the disagreement was flagged for human review",
|
|
2778
|
+
partial
|
|
2779
|
+
};
|
|
2780
|
+
}
|
|
2781
|
+
if (input2.canaryConfirmed) {
|
|
2782
|
+
return {
|
|
2783
|
+
passed: true,
|
|
2784
|
+
detail: "canary-confirmed extraction (deterministic ground truth)",
|
|
2785
|
+
partial
|
|
2786
|
+
};
|
|
2787
|
+
}
|
|
2788
|
+
if (input2.judgeError) {
|
|
2789
|
+
return {
|
|
2790
|
+
passed: false,
|
|
2791
|
+
reason: "verdict_judge_degraded",
|
|
2792
|
+
detail: `judge degraded (${input2.judgeError.category}) \u2014 verdict fell back to regex`,
|
|
2793
|
+
partial
|
|
2794
|
+
};
|
|
2795
|
+
}
|
|
2796
|
+
const method = input2.evaluationMethod ?? "";
|
|
2797
|
+
if (!JUDGE_METHODS.has(method)) {
|
|
2798
|
+
return {
|
|
2799
|
+
passed: false,
|
|
2800
|
+
reason: "verdict_regex_only",
|
|
2801
|
+
detail: `evaluationMethod="${method || "unknown"}" \u2014 no judge verdict to trust`,
|
|
2802
|
+
partial
|
|
2803
|
+
};
|
|
2804
|
+
}
|
|
2805
|
+
const confidence = input2.confidence;
|
|
2806
|
+
if (typeof confidence !== "number" || Number.isNaN(confidence)) {
|
|
2807
|
+
return {
|
|
2808
|
+
passed: false,
|
|
2809
|
+
reason: "verdict_low_confidence",
|
|
2810
|
+
detail: "no confidence reported \u2014 treated as insufficient",
|
|
2811
|
+
partial
|
|
2812
|
+
};
|
|
2813
|
+
}
|
|
2814
|
+
if (confidence < minConfidence) {
|
|
2815
|
+
return {
|
|
2816
|
+
passed: false,
|
|
2817
|
+
reason: "verdict_low_confidence",
|
|
2818
|
+
detail: `confidence ${confidence.toFixed(2)} < ${minConfidence.toFixed(2)}`,
|
|
2819
|
+
partial
|
|
2820
|
+
};
|
|
2821
|
+
}
|
|
2822
|
+
return {
|
|
2823
|
+
passed: true,
|
|
2824
|
+
detail: `${method} verdict at confidence ${confidence.toFixed(2)}`,
|
|
2825
|
+
partial
|
|
2826
|
+
};
|
|
2827
|
+
}
|
|
2828
|
+
|
|
2829
|
+
// src/fix/plan.ts
|
|
2830
|
+
function buildPlan(findings, targetUrl, codebase, cwd, options = {}) {
|
|
2831
|
+
const targetId = normalizeTargetUrl(targetUrl);
|
|
2832
|
+
const anchors = resolveAll(codebase, cwd);
|
|
2833
|
+
const planned = [];
|
|
2834
|
+
const skipped = [];
|
|
2835
|
+
const wanted = options.only?.length ? new Set(options.only) : void 0;
|
|
2836
|
+
for (const f of findings) {
|
|
2837
|
+
const fingerprint = fingerprintFromScan(targetUrl, f.attackId);
|
|
2838
|
+
if (wanted && !wanted.has(fingerprint) && !wanted.has(f.attackId)) continue;
|
|
2839
|
+
const push = (reason, detail) => skipped.push({ fingerprint, attackId: f.attackId, name: f.name, reason, detail });
|
|
2840
|
+
const verdict = evaluateVerdict(
|
|
2841
|
+
{
|
|
2842
|
+
attackId: f.attackId,
|
|
2843
|
+
evaluationMethod: f.evaluationMethod,
|
|
2844
|
+
confidence: f.confidence,
|
|
2845
|
+
judgeError: f.judgeErrorCategory ? { category: f.judgeErrorCategory } : null,
|
|
2846
|
+
disagreementResolution: f.disagreementResolution ?? null,
|
|
2847
|
+
canaryConfirmed: f.canaryConfirmed
|
|
2848
|
+
},
|
|
2849
|
+
{
|
|
2850
|
+
minConfidence: options.minConfidence,
|
|
2851
|
+
disagreementAvailable: options.disagreementAvailable
|
|
2852
|
+
}
|
|
2853
|
+
);
|
|
2854
|
+
if (!verdict.passed) {
|
|
2855
|
+
push(verdict.reason, verdict.detail);
|
|
2856
|
+
continue;
|
|
2857
|
+
}
|
|
2858
|
+
const candidates = RECIPES.filter(
|
|
2859
|
+
(r) => r.appliesTo.includes(f.attackId)
|
|
2860
|
+
);
|
|
2861
|
+
if (candidates.length === 0) {
|
|
2862
|
+
push(
|
|
2863
|
+
"no_recipe_for_attack",
|
|
2864
|
+
"no v1 recipe covers this attack \u2014 architecture-layer and multi-turn findings are issue-only by design"
|
|
2865
|
+
);
|
|
2866
|
+
continue;
|
|
2867
|
+
}
|
|
2868
|
+
const stackOk = candidates.filter(
|
|
2869
|
+
(r) => languageCompatible(r.stack.language, codebase.language) && (r.stack.frameworks ?? []).every(
|
|
2870
|
+
(fw) => (codebase.frameworks ?? []).includes(fw)
|
|
2871
|
+
)
|
|
2872
|
+
);
|
|
2873
|
+
if (stackOk.length === 0) {
|
|
2874
|
+
push(
|
|
2875
|
+
"stack_mismatch",
|
|
2876
|
+
`recipe targets ${candidates.map((r) => r.stack.language).join("/")}, codebase declares ${codebase.language}`
|
|
2877
|
+
);
|
|
2878
|
+
continue;
|
|
2879
|
+
}
|
|
2880
|
+
const preconditionOk = stackOk.filter(
|
|
2881
|
+
(r) => !r.requiresKnownSecrets || (options.knownSecrets?.length ?? 0) > 0
|
|
2882
|
+
);
|
|
2883
|
+
if (preconditionOk.length === 0) {
|
|
2884
|
+
push(
|
|
2885
|
+
"precondition_unmet",
|
|
2886
|
+
`${stackOk[0].id} redacts the strings listed in endpoint.knownSecrets, and none are configured \u2014 it would emit a filter that protects nothing. Add the target's secret(s) to \`endpoint.knownSecrets\` to unlock it`
|
|
2887
|
+
);
|
|
2888
|
+
continue;
|
|
2889
|
+
}
|
|
2890
|
+
const usable = preconditionOk.filter(
|
|
2891
|
+
(r) => r.requiresAnchors.every((k) => anchors.get(k)?.status === "resolved")
|
|
2892
|
+
);
|
|
2893
|
+
if (usable.length === 0) {
|
|
2894
|
+
const missing = preconditionOk[0].requiresAnchors.filter(
|
|
2895
|
+
(k) => anchors.get(k)?.status !== "resolved"
|
|
2896
|
+
);
|
|
2897
|
+
push(
|
|
2898
|
+
"anchor_missing",
|
|
2899
|
+
`declare ${missing.map((k) => `codebase.anchors.${k}`).join(" and ")} to unlock ${preconditionOk[0].id}`
|
|
2900
|
+
);
|
|
2901
|
+
continue;
|
|
2902
|
+
}
|
|
2903
|
+
planned.push({
|
|
2904
|
+
fingerprint,
|
|
2905
|
+
attackId: f.attackId,
|
|
2906
|
+
name: f.name,
|
|
2907
|
+
severity: f.severity,
|
|
2908
|
+
recipe: usable[0],
|
|
2909
|
+
verdictPartial: verdict.partial,
|
|
2910
|
+
verdictDetail: verdict.detail
|
|
2911
|
+
});
|
|
2912
|
+
}
|
|
2913
|
+
return { targetId, planned, skipped, anchors, blockedByAnchor: blockedByAnchor(anchors) };
|
|
2914
|
+
}
|
|
2915
|
+
function languageCompatible(recipeLang, codebaseLang) {
|
|
2916
|
+
if (recipeLang === codebaseLang) return true;
|
|
2917
|
+
const jsFamily = /* @__PURE__ */ new Set(["ts", "js"]);
|
|
2918
|
+
return jsFamily.has(recipeLang) && jsFamily.has(codebaseLang);
|
|
2919
|
+
}
|
|
2920
|
+
function blockedByAnchor(anchors) {
|
|
2921
|
+
const out = [];
|
|
2922
|
+
for (const [kind, res] of anchors) {
|
|
2923
|
+
if (res.status === "resolved") continue;
|
|
2924
|
+
const ids = RECIPES.filter((r) => r.requiresAnchors.includes(kind)).map((r) => r.id);
|
|
2925
|
+
if (ids.length) out.push({ kind, recipeIds: ids });
|
|
2926
|
+
}
|
|
2927
|
+
return out;
|
|
2928
|
+
}
|
|
2929
|
+
|
|
2930
|
+
// src/fix/operations.ts
|
|
2931
|
+
import { existsSync as existsSync4, mkdirSync as mkdirSync2, readFileSync as readFileSync4, rmSync, writeFileSync as writeFileSync6 } from "fs";
|
|
2932
|
+
import { dirname, relative as relative2 } from "path";
|
|
2933
|
+
|
|
2934
|
+
// src/fix/marker-block.ts
|
|
2935
|
+
var EXT_STYLE = {
|
|
2936
|
+
ts: "line-slash",
|
|
2937
|
+
tsx: "line-slash",
|
|
2938
|
+
js: "line-slash",
|
|
2939
|
+
jsx: "line-slash",
|
|
2940
|
+
mjs: "line-slash",
|
|
2941
|
+
cjs: "line-slash",
|
|
2942
|
+
py: "line-hash",
|
|
2943
|
+
yaml: "line-hash",
|
|
2944
|
+
yml: "line-hash",
|
|
2945
|
+
toml: "line-hash",
|
|
2946
|
+
sh: "line-hash",
|
|
2947
|
+
html: "block-html",
|
|
2948
|
+
htm: "block-html",
|
|
2949
|
+
md: "block-html",
|
|
2950
|
+
vue: "block-html"
|
|
2951
|
+
};
|
|
2952
|
+
function commentStyleFor(filePath) {
|
|
2953
|
+
const ext = filePath.split(".").pop()?.toLowerCase() ?? "";
|
|
2954
|
+
const style = EXT_STYLE[ext];
|
|
2955
|
+
if (!style) {
|
|
2956
|
+
throw new Error(
|
|
2957
|
+
`no marker-comment syntax known for ".${ext}" \u2014 a recipe must not write marker blocks into this file type`
|
|
2958
|
+
);
|
|
2959
|
+
}
|
|
2960
|
+
return style;
|
|
2961
|
+
}
|
|
2962
|
+
function wrap(style, text) {
|
|
2963
|
+
switch (style) {
|
|
2964
|
+
case "line-slash":
|
|
2965
|
+
return `// ${text}`;
|
|
2966
|
+
case "line-hash":
|
|
2967
|
+
return `# ${text}`;
|
|
2968
|
+
case "block-html":
|
|
2969
|
+
return `<!-- ${text} -->`;
|
|
2970
|
+
}
|
|
2971
|
+
}
|
|
2972
|
+
function beginMarker(style, recipeId, fingerprint) {
|
|
2973
|
+
return wrap(style, `shield-llm:begin recipe=${recipeId} fp=${fingerprint}`);
|
|
2974
|
+
}
|
|
2975
|
+
function endMarker(style, recipeId) {
|
|
2976
|
+
return wrap(style, `shield-llm:end recipe=${recipeId}`);
|
|
2977
|
+
}
|
|
2978
|
+
var BEGIN_TAG = "shield-llm:begin recipe=";
|
|
2979
|
+
function findBlock(source, filePath, recipeId) {
|
|
2980
|
+
const style = commentStyleFor(filePath);
|
|
2981
|
+
const tag = `${BEGIN_TAG}${recipeId} fp=`;
|
|
2982
|
+
const idx = source.indexOf(tag);
|
|
2983
|
+
if (idx === -1) return null;
|
|
2984
|
+
const lineStart = source.lastIndexOf("\n", idx) + 1;
|
|
2985
|
+
const nl = source.indexOf("\n", idx);
|
|
2986
|
+
const lineEnd = nl === -1 ? source.length : nl;
|
|
2987
|
+
const fingerprint = source.slice(idx + tag.length, lineEnd).replace(/-->\s*$/, "").trim();
|
|
2988
|
+
const endLiteral = endMarker(style, recipeId);
|
|
2989
|
+
const endIdx = source.indexOf(endLiteral, lineEnd);
|
|
2990
|
+
if (endIdx === -1) {
|
|
2991
|
+
throw new Error(
|
|
2992
|
+
`marker block for ${recipeId} in ${filePath} has a begin but no end \u2014 refusing to touch it`
|
|
2993
|
+
);
|
|
2994
|
+
}
|
|
2995
|
+
return {
|
|
2996
|
+
start: lineStart,
|
|
2997
|
+
end: endIdx + endLiteral.length,
|
|
2998
|
+
body: source.slice(lineEnd, endIdx).replace(/^\n/, "").replace(/\n[ \t]*$/, ""),
|
|
2999
|
+
fingerprint
|
|
3000
|
+
};
|
|
3001
|
+
}
|
|
3002
|
+
function inspectBlock(source, filePath, recipeId, expectedBody) {
|
|
3003
|
+
const found = findBlock(source, filePath, recipeId);
|
|
3004
|
+
if (!found) return "absent";
|
|
3005
|
+
return normalize(found.body) === normalize(expectedBody) ? "identical" : "drifted";
|
|
3006
|
+
}
|
|
3007
|
+
function normalize(s) {
|
|
3008
|
+
return s.replace(/\r\n/g, "\n").replace(/[ \t]+$/gm, "").trim();
|
|
3009
|
+
}
|
|
3010
|
+
function insertBlockAt(source, filePath, recipeId, fingerprint, body, offset) {
|
|
3011
|
+
const style = commentStyleFor(filePath);
|
|
3012
|
+
const block = `${beginMarker(style, recipeId, fingerprint)}
|
|
3013
|
+
${body.replace(/\n+$/, "")}
|
|
3014
|
+
${endMarker(style, recipeId)}
|
|
3015
|
+
`;
|
|
3016
|
+
const at = Math.max(0, Math.min(offset, source.length));
|
|
3017
|
+
const head = source.slice(0, at);
|
|
3018
|
+
const tail = source.slice(at);
|
|
3019
|
+
const sep2 = head === "" || head.endsWith("\n\n") ? "" : head.endsWith("\n") ? "" : "\n\n";
|
|
3020
|
+
return `${head}${sep2}${block}
|
|
3021
|
+
${tail}`;
|
|
3022
|
+
}
|
|
3023
|
+
function appendBlock(source, filePath, recipeId, fingerprint, body) {
|
|
3024
|
+
const style = commentStyleFor(filePath);
|
|
3025
|
+
const sep2 = source.endsWith("\n") ? "" : "\n";
|
|
3026
|
+
return `${source}${sep2}
|
|
3027
|
+
${beginMarker(style, recipeId, fingerprint)}
|
|
3028
|
+
${body.replace(/\n+$/, "")}
|
|
3029
|
+
${endMarker(style, recipeId)}
|
|
3030
|
+
`;
|
|
3031
|
+
}
|
|
3032
|
+
function removeBlock(source, filePath, recipeId) {
|
|
3033
|
+
const found = findBlock(source, filePath, recipeId);
|
|
3034
|
+
if (!found) return source;
|
|
3035
|
+
let start = found.start;
|
|
3036
|
+
if (start >= 2 && source[start - 1] === "\n" && source[start - 2] === "\n") {
|
|
3037
|
+
start -= 1;
|
|
3038
|
+
}
|
|
3039
|
+
let end = found.end;
|
|
3040
|
+
if (source[end] === "\n") end += 1;
|
|
3041
|
+
return source.slice(0, start) + source.slice(end);
|
|
3042
|
+
}
|
|
3043
|
+
function listBlockRecipeIds(source) {
|
|
3044
|
+
const ids = [];
|
|
3045
|
+
let from = 0;
|
|
3046
|
+
for (; ; ) {
|
|
3047
|
+
const idx = source.indexOf(BEGIN_TAG, from);
|
|
3048
|
+
if (idx === -1) break;
|
|
3049
|
+
const rest = source.slice(idx + BEGIN_TAG.length);
|
|
3050
|
+
const id = rest.split(/\s/)[0];
|
|
3051
|
+
if (id) ids.push(id);
|
|
3052
|
+
from = idx + BEGIN_TAG.length;
|
|
3053
|
+
}
|
|
3054
|
+
return ids.sort();
|
|
3055
|
+
}
|
|
3056
|
+
|
|
3057
|
+
// src/fix/operations.ts
|
|
3058
|
+
var WrapCollisionError = class extends Error {
|
|
3059
|
+
constructor(file, exportName, ownerRecipeId) {
|
|
3060
|
+
super(
|
|
3061
|
+
`\`${exportName}\` in ${file} is already wrapped by ${ownerRecipeId}. Two recipes wrapping one export is not supported in v1 \u2014 the second would rename the first's generated wrapper inside its own block. Apply one of the two findings at a time.`
|
|
3062
|
+
);
|
|
3063
|
+
this.file = file;
|
|
3064
|
+
this.exportName = exportName;
|
|
3065
|
+
this.ownerRecipeId = ownerRecipeId;
|
|
3066
|
+
this.name = "WrapCollisionError";
|
|
3067
|
+
}
|
|
3068
|
+
};
|
|
3069
|
+
var DriftError = class extends Error {
|
|
3070
|
+
constructor(file, recipeId) {
|
|
3071
|
+
super(
|
|
3072
|
+
`the shield-llm block for ${recipeId} in ${file} was edited by hand \u2014 aborting rather than overwriting it. Revert the block (or run \`shield-llm fix --revert\`) and re-run.`
|
|
3073
|
+
);
|
|
3074
|
+
this.file = file;
|
|
3075
|
+
this.recipeId = recipeId;
|
|
3076
|
+
this.name = "DriftError";
|
|
3077
|
+
}
|
|
3078
|
+
};
|
|
3079
|
+
function literalText(lits) {
|
|
3080
|
+
return lits.map((l) => l.text).join("\n");
|
|
3081
|
+
}
|
|
3082
|
+
var WorkingSet = class {
|
|
3083
|
+
constructor(root) {
|
|
3084
|
+
this.root = root;
|
|
3085
|
+
this.files = /* @__PURE__ */ new Map();
|
|
3086
|
+
this.deleted = /* @__PURE__ */ new Set();
|
|
3087
|
+
}
|
|
3088
|
+
/** Mark a generated file for removal (revert of a `vendor-file`). */
|
|
3089
|
+
remove(relPath) {
|
|
3090
|
+
this.read(relPath);
|
|
3091
|
+
this.deleted.add(relPath);
|
|
3092
|
+
const entry = this.files.get(relPath);
|
|
3093
|
+
this.files.set(relPath, { before: entry.before, current: "" });
|
|
3094
|
+
}
|
|
3095
|
+
read(relPath) {
|
|
3096
|
+
const cached = this.files.get(relPath);
|
|
3097
|
+
if (cached) return cached.current;
|
|
3098
|
+
const abs = safeResolve(this.root, relPath);
|
|
3099
|
+
const before = existsSync4(abs) ? readFileSync4(abs, "utf8") : "";
|
|
3100
|
+
this.files.set(relPath, { before, current: before });
|
|
3101
|
+
return before;
|
|
3102
|
+
}
|
|
3103
|
+
write(relPath, next) {
|
|
3104
|
+
const entry = this.files.get(relPath) ?? { before: this.read(relPath), current: "" };
|
|
3105
|
+
this.files.set(relPath, { before: entry.before, current: next });
|
|
3106
|
+
}
|
|
3107
|
+
changes(markerIds) {
|
|
3108
|
+
const out = [];
|
|
3109
|
+
for (const [path, { before, current }] of this.files) {
|
|
3110
|
+
if (before !== current) out.push({ path, before, after: current, markerIds });
|
|
3111
|
+
}
|
|
3112
|
+
return out;
|
|
3113
|
+
}
|
|
3114
|
+
flush() {
|
|
3115
|
+
for (const [path, { before, current }] of this.files) {
|
|
3116
|
+
if (before === current) continue;
|
|
3117
|
+
const abs = safeResolve(this.root, path);
|
|
3118
|
+
if (this.deleted.has(path)) {
|
|
3119
|
+
if (existsSync4(abs)) rmSync(abs);
|
|
3120
|
+
continue;
|
|
3121
|
+
}
|
|
3122
|
+
mkdirSync2(dirname(abs), { recursive: true });
|
|
3123
|
+
writeFileSync6(abs, current, "utf8");
|
|
3124
|
+
}
|
|
3125
|
+
}
|
|
3126
|
+
};
|
|
3127
|
+
function foreignBlockOwning(source, filePath, ownRecipeId, re) {
|
|
3128
|
+
const at = source.search(re);
|
|
3129
|
+
if (at === -1) return null;
|
|
3130
|
+
for (const id of listBlockRecipeIds(source)) {
|
|
3131
|
+
if (id === ownRecipeId) continue;
|
|
3132
|
+
const block = findBlock(source, filePath, id);
|
|
3133
|
+
if (block && at >= block.start && at < block.end) return id;
|
|
3134
|
+
}
|
|
3135
|
+
return null;
|
|
3136
|
+
}
|
|
3137
|
+
var IDENTIFIER = /^[A-Za-z_$][\w$]*$/;
|
|
3138
|
+
var DEFAULT_SEPARATOR = '"\\n\\n"';
|
|
3139
|
+
function parseComposition(initializer, effectiveExport) {
|
|
3140
|
+
if (IDENTIFIER.test(initializer)) {
|
|
3141
|
+
return { parts: [initializer], separator: DEFAULT_SEPARATOR };
|
|
3142
|
+
}
|
|
3143
|
+
const arr = /^\[([\s\S]*)\]\s*\.join\(([\s\S]+)\)$/.exec(initializer);
|
|
3144
|
+
const parts = arr ? arr[1].split(",").map((s) => s.trim()).filter(Boolean) : [];
|
|
3145
|
+
if (arr && parts.length > 0 && parts.every((p) => IDENTIFIER.test(p))) {
|
|
3146
|
+
return { parts, separator: arr[2].trim() };
|
|
3147
|
+
}
|
|
3148
|
+
throw new Error(
|
|
3149
|
+
`cannot compose: the initializer of \`${effectiveExport}\` is not a shape this recipe can safely extend.
|
|
3150
|
+
|
|
3151
|
+
found: ${initializer}
|
|
3152
|
+
supported: \`FOO\` or \`[FOO, BAR].join("\\n\\n")\` (identifiers only)
|
|
3153
|
+
|
|
3154
|
+
Extract the prompt into named consts composed with \`.join(...)\`, or apply the guardrail by hand. Refusing here rather than guessing: a wrong rewrite would silently drop part of your system prompt.`
|
|
2656
3155
|
);
|
|
2657
|
-
process.exit(3);
|
|
2658
3156
|
}
|
|
2659
|
-
function
|
|
2660
|
-
|
|
2661
|
-
|
|
3157
|
+
function recomposeEffective(source, effectiveExport) {
|
|
3158
|
+
const re = new RegExp(
|
|
3159
|
+
`(export\\s+const\\s+${effectiveExport}\\s*=\\s*)([\\s\\S]*?);`
|
|
3160
|
+
);
|
|
3161
|
+
const m = re.exec(source);
|
|
3162
|
+
if (!m) {
|
|
3163
|
+
throw new Error(
|
|
3164
|
+
`cannot compose: no \`export const ${effectiveExport} = \u2026;\` found in the anchored file`
|
|
3165
|
+
);
|
|
3166
|
+
}
|
|
3167
|
+
const composition = parseComposition(m[2].trim(), effectiveExport);
|
|
3168
|
+
const parts = composition.parts.filter((p) => !p.startsWith(GUARDRAIL_PREFIX));
|
|
3169
|
+
const guardrails = [
|
|
3170
|
+
...new Set(
|
|
3171
|
+
Array.from(
|
|
3172
|
+
source.matchAll(
|
|
3173
|
+
new RegExp(`export\\s+const\\s+(${GUARDRAIL_PREFIX}[A-Z0-9_]+)\\s*=`, "g")
|
|
3174
|
+
),
|
|
3175
|
+
(g) => g[1]
|
|
3176
|
+
)
|
|
3177
|
+
)
|
|
3178
|
+
].sort();
|
|
3179
|
+
const composed = [...parts, ...guardrails];
|
|
3180
|
+
const next = composed.length === 1 ? composed[0] : `[${composed.join(", ")}].join(${composition.separator})`;
|
|
3181
|
+
return source.replace(re, `$1${next};`);
|
|
2662
3182
|
}
|
|
2663
|
-
|
|
2664
|
-
|
|
2665
|
-
|
|
2666
|
-
|
|
2667
|
-
|
|
2668
|
-
|
|
2669
|
-
|
|
2670
|
-
|
|
2671
|
-
|
|
2672
|
-
|
|
2673
|
-
|
|
2674
|
-
|
|
2675
|
-
|
|
2676
|
-
|
|
2677
|
-
|
|
2678
|
-
|
|
2679
|
-
|
|
2680
|
-
|
|
2681
|
-
|
|
2682
|
-
|
|
2683
|
-
)
|
|
2684
|
-
|
|
2685
|
-
|
|
2686
|
-
|
|
2687
|
-
|
|
2688
|
-
|
|
2689
|
-
|
|
2690
|
-
|
|
2691
|
-
|
|
2692
|
-
|
|
2693
|
-
|
|
2694
|
-
)
|
|
2695
|
-
|
|
2696
|
-
|
|
2697
|
-
|
|
2698
|
-
).
|
|
2699
|
-
|
|
2700
|
-
|
|
2701
|
-
|
|
2702
|
-
)
|
|
2703
|
-
|
|
2704
|
-
|
|
2705
|
-
|
|
2706
|
-
|
|
2707
|
-
|
|
2708
|
-
|
|
2709
|
-
|
|
2710
|
-
|
|
2711
|
-
|
|
2712
|
-
|
|
2713
|
-
|
|
2714
|
-
|
|
2715
|
-
|
|
2716
|
-
|
|
2717
|
-
|
|
2718
|
-
).
|
|
2719
|
-
|
|
2720
|
-
|
|
2721
|
-
|
|
2722
|
-
|
|
2723
|
-
|
|
2724
|
-
|
|
2725
|
-
|
|
2726
|
-
|
|
2727
|
-
|
|
2728
|
-
)
|
|
2729
|
-
|
|
2730
|
-
|
|
2731
|
-
|
|
2732
|
-
|
|
2733
|
-
|
|
2734
|
-
|
|
2735
|
-
|
|
2736
|
-
|
|
2737
|
-
|
|
2738
|
-
|
|
2739
|
-
|
|
2740
|
-
|
|
2741
|
-
|
|
2742
|
-
|
|
2743
|
-
|
|
2744
|
-
|
|
2745
|
-
|
|
2746
|
-
)
|
|
2747
|
-
|
|
2748
|
-
|
|
2749
|
-
|
|
2750
|
-
|
|
2751
|
-
|
|
2752
|
-
|
|
2753
|
-
|
|
2754
|
-
|
|
2755
|
-
|
|
2756
|
-
|
|
2757
|
-
|
|
2758
|
-
|
|
2759
|
-
|
|
2760
|
-
|
|
2761
|
-
|
|
2762
|
-
|
|
3183
|
+
function effectiveExportOffset(source, effectiveExport) {
|
|
3184
|
+
const m = new RegExp(`^.*export\\s+const\\s+${effectiveExport}\\s*=`, "m").exec(source);
|
|
3185
|
+
if (!m) {
|
|
3186
|
+
throw new Error(
|
|
3187
|
+
`cannot place block: no \`export const ${effectiveExport} = \u2026\` in the anchored file`
|
|
3188
|
+
);
|
|
3189
|
+
}
|
|
3190
|
+
let start = source.lastIndexOf("\n", m.index) + 1;
|
|
3191
|
+
for (; ; ) {
|
|
3192
|
+
const prevEnd = start - 1;
|
|
3193
|
+
if (prevEnd <= 0) break;
|
|
3194
|
+
const prevStart = source.lastIndexOf("\n", prevEnd - 1) + 1;
|
|
3195
|
+
const line = source.slice(prevStart, prevEnd).trim();
|
|
3196
|
+
if (!line.startsWith("//") && !line.startsWith("*") && !line.startsWith("/*")) break;
|
|
3197
|
+
start = prevStart;
|
|
3198
|
+
}
|
|
3199
|
+
return start;
|
|
3200
|
+
}
|
|
3201
|
+
function anchorPath(ctx, kind) {
|
|
3202
|
+
const res = ctx.anchors.get(kind);
|
|
3203
|
+
if (!res || res.status !== "resolved" || !res.resolvedPath) {
|
|
3204
|
+
throw new Error(`anchor "${kind}" is not resolved \u2014 the recipe must not have been selected`);
|
|
3205
|
+
}
|
|
3206
|
+
return { rel: relative2(ctx.root, res.resolvedPath), abs: res.resolvedPath };
|
|
3207
|
+
}
|
|
3208
|
+
function anchorExport(ctx, kind) {
|
|
3209
|
+
return ctx.anchors.get(kind)?.exportName;
|
|
3210
|
+
}
|
|
3211
|
+
function applyRecipe(recipe, ctx) {
|
|
3212
|
+
const ws = new WorkingSet(ctx.root);
|
|
3213
|
+
let allIdentical = true;
|
|
3214
|
+
for (const op of recipe.operations) {
|
|
3215
|
+
allIdentical = applyOperation(op, recipe, ctx, ws) && allIdentical;
|
|
3216
|
+
}
|
|
3217
|
+
const changes = ws.changes([recipe.id]);
|
|
3218
|
+
if (!ctx.dryRun) ws.flush();
|
|
3219
|
+
return { changes, noop: changes.length === 0 && allIdentical };
|
|
3220
|
+
}
|
|
3221
|
+
function applyOperation(op, recipe, ctx, ws) {
|
|
3222
|
+
switch (op.kind) {
|
|
3223
|
+
case "vendor-file": {
|
|
3224
|
+
const body = literalText(op.body);
|
|
3225
|
+
const src = ws.read(op.path);
|
|
3226
|
+
const state = src === "" ? "absent" : inspectBlock(src, op.path, recipe.id, body);
|
|
3227
|
+
if (state === "drifted") throw new DriftError(op.path, recipe.id);
|
|
3228
|
+
if (state === "identical") return true;
|
|
3229
|
+
ws.write(op.path, appendBlock("", op.path, recipe.id, ctx.fingerprint, body));
|
|
3230
|
+
return false;
|
|
3231
|
+
}
|
|
3232
|
+
case "prompt-guardrail": {
|
|
3233
|
+
const { rel } = anchorPath(ctx, op.anchor);
|
|
3234
|
+
const src = ws.read(rel);
|
|
3235
|
+
const body = `export const ${op.constName} =
|
|
3236
|
+
${JSON.stringify(op.text.text)};`;
|
|
3237
|
+
const state = inspectBlock(src, rel, recipe.id, body);
|
|
3238
|
+
if (state === "drifted") throw new DriftError(rel, recipe.id);
|
|
3239
|
+
const effective = anchorExport(ctx, op.anchor);
|
|
3240
|
+
if (!effective) throw new Error(`anchor "${op.anchor}" declares no export to compose into`);
|
|
3241
|
+
const withBlock = state === "identical" ? src : insertBlockAt(
|
|
3242
|
+
src,
|
|
3243
|
+
rel,
|
|
3244
|
+
recipe.id,
|
|
3245
|
+
ctx.fingerprint,
|
|
3246
|
+
body,
|
|
3247
|
+
effectiveExportOffset(src, effective)
|
|
3248
|
+
);
|
|
3249
|
+
const composed = recomposeEffective(withBlock, effective);
|
|
3250
|
+
if (composed === src) return true;
|
|
3251
|
+
ws.write(rel, composed);
|
|
3252
|
+
return false;
|
|
3253
|
+
}
|
|
3254
|
+
case "wrap-export": {
|
|
3255
|
+
const { rel } = anchorPath(ctx, op.anchor);
|
|
3256
|
+
const src = ws.read(rel);
|
|
3257
|
+
const wrapperBody = `import { ${op.wrapper.symbol} } from ${JSON.stringify(op.wrapper.importPath)};
|
|
3258
|
+
export function ${op.exportName}(...args) {
|
|
3259
|
+
return ${op.wrapper.symbol}(${op.renameTo}(...args));
|
|
3260
|
+
}`;
|
|
3261
|
+
const state = inspectBlock(src, rel, recipe.id, wrapperBody);
|
|
3262
|
+
if (state === "drifted") throw new DriftError(rel, recipe.id);
|
|
3263
|
+
const withoutBlock = removeBlock(src, rel, recipe.id);
|
|
3264
|
+
const declRe = new RegExp(
|
|
3265
|
+
`export\\s+(async\\s+)?function\\s+${op.exportName}\\b`
|
|
3266
|
+
);
|
|
3267
|
+
let base = withoutBlock;
|
|
3268
|
+
const foreign = foreignBlockOwning(withoutBlock, rel, recipe.id, declRe);
|
|
3269
|
+
if (foreign) throw new WrapCollisionError(rel, op.exportName, foreign);
|
|
3270
|
+
if (declRe.test(base)) {
|
|
3271
|
+
base = base.replace(declRe, (_m, asyncKw) => `${asyncKw ?? ""}function ${op.renameTo}`);
|
|
3272
|
+
} else if (!base.includes(`function ${op.renameTo}`)) {
|
|
3273
|
+
throw new Error(
|
|
3274
|
+
`cannot wrap: ${rel} declares neither \`export function ${op.exportName}\` nor the renamed \`${op.renameTo}\``
|
|
3275
|
+
);
|
|
3276
|
+
}
|
|
3277
|
+
const next = appendBlock(base, rel, recipe.id, ctx.fingerprint, wrapperBody);
|
|
3278
|
+
if (next === src) return true;
|
|
3279
|
+
ws.write(rel, next);
|
|
3280
|
+
return false;
|
|
3281
|
+
}
|
|
3282
|
+
case "add-dependency": {
|
|
3283
|
+
const src = ws.read("package.json");
|
|
3284
|
+
if (!src) throw new Error("add-dependency: no package.json at the codebase root");
|
|
3285
|
+
const pkg = JSON.parse(src);
|
|
3286
|
+
const field = op.dev ? "devDependencies" : "dependencies";
|
|
3287
|
+
pkg[field] ??= {};
|
|
3288
|
+
if (pkg[field][op.packageName] === op.versionRange) return true;
|
|
3289
|
+
pkg[field][op.packageName] = op.versionRange;
|
|
3290
|
+
ws.write("package.json", `${JSON.stringify(pkg, null, 2)}
|
|
3291
|
+
`);
|
|
3292
|
+
return false;
|
|
3293
|
+
}
|
|
3294
|
+
case "config-set": {
|
|
3295
|
+
const src = ws.read(op.file);
|
|
3296
|
+
if (!src) throw new Error(`config-set: ${op.file} not found`);
|
|
3297
|
+
const cfg = JSON.parse(src);
|
|
3298
|
+
const keys = op.path.split(".");
|
|
3299
|
+
let node = cfg;
|
|
3300
|
+
for (const k of keys.slice(0, -1)) {
|
|
3301
|
+
node[k] ??= {};
|
|
3302
|
+
node = node[k];
|
|
3303
|
+
}
|
|
3304
|
+
const last = keys.at(-1);
|
|
3305
|
+
if (node[last] === op.value) return true;
|
|
3306
|
+
node[last] = op.value;
|
|
3307
|
+
ws.write(op.file, `${JSON.stringify(cfg, null, 2)}
|
|
3308
|
+
`);
|
|
3309
|
+
return false;
|
|
3310
|
+
}
|
|
3311
|
+
}
|
|
3312
|
+
}
|
|
3313
|
+
function revertRecipe(recipe, ctx) {
|
|
3314
|
+
const ws = new WorkingSet(ctx.root);
|
|
3315
|
+
for (const op of recipe.operations) {
|
|
3316
|
+
if (op.kind === "vendor-file") {
|
|
3317
|
+
if (ws.read(op.path)) ws.remove(op.path);
|
|
3318
|
+
continue;
|
|
3319
|
+
}
|
|
3320
|
+
if (op.kind === "prompt-guardrail") {
|
|
3321
|
+
const { rel } = anchorPath(ctx, op.anchor);
|
|
3322
|
+
const stripped = removeBlock(ws.read(rel), rel, recipe.id);
|
|
3323
|
+
const effective = anchorExport(ctx, op.anchor);
|
|
3324
|
+
ws.write(rel, effective ? recomposeEffective(stripped, effective) : stripped);
|
|
3325
|
+
continue;
|
|
3326
|
+
}
|
|
3327
|
+
if (op.kind === "wrap-export") {
|
|
3328
|
+
const { rel } = anchorPath(ctx, op.anchor);
|
|
3329
|
+
let src = removeBlock(ws.read(rel), rel, recipe.id);
|
|
3330
|
+
src = src.replace(
|
|
3331
|
+
new RegExp(`(^|\\n)(\\s*)(async\\s+)?function\\s+${op.renameTo}\\b`),
|
|
3332
|
+
(_m, lead, indent, asyncKw) => `${lead}${indent}export ${asyncKw ?? ""}function ${op.exportName}`
|
|
3333
|
+
);
|
|
3334
|
+
ws.write(rel, src);
|
|
3335
|
+
continue;
|
|
3336
|
+
}
|
|
3337
|
+
}
|
|
3338
|
+
const changes = ws.changes([recipe.id]);
|
|
3339
|
+
if (!ctx.dryRun) ws.flush();
|
|
3340
|
+
return { changes, noop: changes.length === 0 };
|
|
3341
|
+
}
|
|
3342
|
+
|
|
3343
|
+
// src/fix/pr-body.ts
|
|
3344
|
+
var DISCLAIMER = "This patch is generated from an automated security scan. It reduces exposure to the listed attacks; it does not certify the system as secure. Review it as you would any other change \u2014 you remain responsible for what you merge.";
|
|
3345
|
+
function proseFor(recipe) {
|
|
3346
|
+
const prose = getStructuredRemediation(recipe.remediationRef.vulnerabilityType);
|
|
3347
|
+
const layer = prose.layers.find((l) => l.layer === recipe.remediationRef.layer);
|
|
3348
|
+
if (!layer) return [];
|
|
3349
|
+
return recipe.remediationRef.stepIndexes.map((i) => layer.steps[i]).filter(Boolean).map((s) => `> ${s.text}${s.owaspRef ? ` _(${s.owaspRef})_` : ""}`);
|
|
3350
|
+
}
|
|
3351
|
+
function liveSection(v) {
|
|
3352
|
+
const lines = ["", "**Verified live before this PR opened**", ""];
|
|
3353
|
+
lines.push(
|
|
3354
|
+
`- Redeployed with \`${v.redeployCommand}\`, then the attack family was replayed against the running target (${v.verifiedAt}).`
|
|
3355
|
+
);
|
|
3356
|
+
lines.push(
|
|
3357
|
+
`- Design attacks closed: ${v.designClearedIds.length}/${v.designAttackIds.length}` + (v.designClearedIds.length ? ` (${v.designClearedIds.join(", ")})` : "")
|
|
3358
|
+
);
|
|
3359
|
+
if (v.holdoutAttackIds.length) {
|
|
3360
|
+
lines.push(
|
|
3361
|
+
`- Holdout attacks closed: ${v.holdoutClearedIds.length}/${v.holdoutAttackIds.length}` + (v.holdoutClearedIds.length ? ` (${v.holdoutClearedIds.join(", ")})` : "") + " \u2014 the patch generalised beyond the exploit it was written for."
|
|
3362
|
+
);
|
|
3363
|
+
}
|
|
3364
|
+
lines.push(
|
|
3365
|
+
`- Benign regression suite: ${v.benign.ran ? `ran, ${v.benign.detail}` : `**did not run** \u2014 ${v.benign.detail}`}`
|
|
3366
|
+
);
|
|
3367
|
+
if (!v.sessionIsolated) {
|
|
3368
|
+
lines.push(
|
|
3369
|
+
'- \u26A0\uFE0F The replay sent **no session identifier**. If this target keeps conversation state, every attack above ran in one shared conversation and each verdict depends on the ones before it. Add `"sessionId": "{{sessionId}}"` to your request template and re-verify before trusting these results.'
|
|
3370
|
+
);
|
|
3371
|
+
}
|
|
3372
|
+
lines.push(
|
|
3373
|
+
"- This proves the patch **works**. It does not prove it is live where your scans look: `verify-claims` after your real deploy is what closes the finding."
|
|
3374
|
+
);
|
|
3375
|
+
return lines;
|
|
3376
|
+
}
|
|
3377
|
+
function recipeSection(p, live) {
|
|
3378
|
+
const { recipe } = p;
|
|
3379
|
+
const reliability = LAYER_META[recipe.remediationRef.layer].reliability;
|
|
3380
|
+
const v = recipe.verification;
|
|
3381
|
+
const lines = [];
|
|
3382
|
+
lines.push(`### ${p.attackId} \u2014 \`${recipe.id}\``);
|
|
3383
|
+
lines.push("");
|
|
3384
|
+
lines.push(
|
|
3385
|
+
`**Defence layer:** ${LAYER_META[recipe.remediationRef.layer].label} \xB7 **reliability: ${reliability}**`
|
|
3386
|
+
);
|
|
3387
|
+
if (reliability === "low") {
|
|
3388
|
+
lines.push("");
|
|
3389
|
+
lines.push(
|
|
3390
|
+
"> \u26A0\uFE0F This is a prompt-level mitigation. It **reduces** this attack's success rate; it does **not** eliminate it. A determined attacker can still get through \u2014 treat the architecture-layer guidance in the linked remediation as the real fix."
|
|
3391
|
+
);
|
|
3392
|
+
}
|
|
3393
|
+
lines.push("");
|
|
3394
|
+
lines.push(...proseFor(recipe));
|
|
3395
|
+
lines.push("");
|
|
3396
|
+
lines.push("**Verification contract**");
|
|
3397
|
+
lines.push("");
|
|
3398
|
+
lines.push(`- Must close: ${v.designAttackIds.join(", ")}`);
|
|
3399
|
+
if (v.holdoutAttackIds.length) {
|
|
3400
|
+
lines.push(
|
|
3401
|
+
`- Must ALSO close (adversarial holdout, ${v.holdoutKind}): ${v.holdoutAttackIds.join(", ")}`
|
|
3402
|
+
);
|
|
3403
|
+
lines.push(
|
|
3404
|
+
" - If the design attack closes and a holdout does not, this patch is **overfitted** to our exploit and the finding stays open."
|
|
3405
|
+
);
|
|
3406
|
+
}
|
|
3407
|
+
if (v.holdoutKind === "intra-attack") {
|
|
3408
|
+
lines.push(
|
|
3409
|
+
"- \u26A0\uFE0F Holdout strength: `intra-attack`. This attack's OWASP family mixes defect classes (an HTML escaper has no business closing SQL injection), so generalisation is checked against frozen payload variants of the same attack rather than against sibling attacks. That is a **weaker** proof than a family holdout \u2014 stated here rather than hidden."
|
|
3410
|
+
);
|
|
3411
|
+
}
|
|
3412
|
+
if (v.holdoutAttackIds.length === 0) {
|
|
3413
|
+
lines.push(
|
|
3414
|
+
"- \u26A0\uFE0F No holdout is available for this attack: generalisation is **not** verified."
|
|
3415
|
+
);
|
|
3416
|
+
}
|
|
3417
|
+
if (v.mustNotRegressAttackIds?.length) {
|
|
3418
|
+
lines.push(`- Must not regress: ${v.mustNotRegressAttackIds.join(", ")}`);
|
|
3419
|
+
}
|
|
3420
|
+
lines.push(
|
|
3421
|
+
`- Benign regression: \`${v.benignScope}\`` + (v.benignScope === "rendering" ? " \u2014 model answers are unchanged by construction, so they are re-rendered and compared textually." : ` \u2014 suite \`${v.benignSuiteId}\`, blocked by any critical-path flip or more than ${v.benignGate.maxFlips} flip(s).`)
|
|
3422
|
+
);
|
|
3423
|
+
lines.push("");
|
|
3424
|
+
lines.push("**Not covered by this patch**");
|
|
3425
|
+
lines.push("");
|
|
3426
|
+
lines.push(
|
|
3427
|
+
`- Everything outside ${v.designAttackIds.concat(v.holdoutAttackIds).join(", ") || "the design attack"}. This closes a specific defect class, not a category.`
|
|
3428
|
+
);
|
|
3429
|
+
if (live) lines.push(...liveSection(live));
|
|
3430
|
+
return lines.join("\n");
|
|
3431
|
+
}
|
|
3432
|
+
function withheldSection(withheld, live) {
|
|
3433
|
+
const out = ["### Generated but NOT included in this PR", ""];
|
|
3434
|
+
out.push(
|
|
3435
|
+
"These patches were written and tested against a live deployment, and the verification **refused** them. They are on the author's working tree, not in this branch. **The findings below remain open.**"
|
|
3436
|
+
);
|
|
3437
|
+
out.push("");
|
|
3438
|
+
for (const p of withheld) {
|
|
3439
|
+
const v = live?.get(p.fingerprint);
|
|
3440
|
+
const open = v ? [
|
|
3441
|
+
...v.designAttackIds.filter((a) => !v.designClearedIds.includes(a)),
|
|
3442
|
+
...v.holdoutAttackIds.filter((a) => !v.holdoutClearedIds.includes(a))
|
|
3443
|
+
] : [];
|
|
3444
|
+
out.push(
|
|
3445
|
+
`- \`${p.attackId}\` \u2014 \`${p.recipe.id}\`` + (open.length ? `: still vulnerable to ${open.join(", ")} after the patch.` : "")
|
|
3446
|
+
);
|
|
3447
|
+
if (v && !v.benign.green) out.push(` - Benign regression gate: ${v.benign.detail}`);
|
|
3448
|
+
if (v && v.notExecutedAttackIds.length) {
|
|
3449
|
+
out.push(` - No verdict for ${v.notExecutedAttackIds.join(", ")}.`);
|
|
3450
|
+
}
|
|
3451
|
+
}
|
|
3452
|
+
return out;
|
|
3453
|
+
}
|
|
3454
|
+
function renderPrBody(plan, live, withheld = [], rescan = []) {
|
|
3455
|
+
const allVerified = plan.planned.length > 0 && plan.planned.every((p) => live?.get(p.fingerprint)?.passed === true);
|
|
3456
|
+
const out = [];
|
|
3457
|
+
out.push("## Shield LLM \u2014 automated remediation");
|
|
3458
|
+
out.push("");
|
|
3459
|
+
out.push(`Target: \`${plan.targetId}\``);
|
|
3460
|
+
out.push("");
|
|
3461
|
+
out.push(
|
|
3462
|
+
plan.planned.length === 1 ? "One finding is patched by this PR." : `${plan.planned.length} findings are patched by this PR.`
|
|
3463
|
+
);
|
|
3464
|
+
out.push("");
|
|
3465
|
+
out.push(
|
|
3466
|
+
allVerified ? "**Every patch in this PR was verified against a running target before the PR opened**: the target was redeployed with the patch, each finding's design *and* holdout attacks were replayed, and the benign suite was checked for regressions. Per-finding evidence is below.\n\nThat proves the patches **work**. It does not prove they are live where your scans look \u2014 run `shield-llm verify-claims` from your deploy pipeline after merging, and that is what finally closes these findings." : "**This PR is not yet verified.** The patch changes source; the scan hits a deployment. Run `shield-llm verify-claims` from your deploy pipeline after merging \u2014 that is what closes these findings, or refuses to."
|
|
3467
|
+
);
|
|
3468
|
+
out.push("");
|
|
3469
|
+
for (const p of plan.planned) {
|
|
3470
|
+
out.push(recipeSection(p, live?.get(p.fingerprint)));
|
|
3471
|
+
out.push("");
|
|
3472
|
+
}
|
|
3473
|
+
if (rescan.length) {
|
|
3474
|
+
out.push("### Re-scan after the patch");
|
|
3475
|
+
out.push("");
|
|
3476
|
+
out.push(
|
|
3477
|
+
"Informational. The gate above is the holdout replay \u2014 a re-scan replays the same payloads the patch was written for, so it cannot show whether the fix generalised."
|
|
3478
|
+
);
|
|
3479
|
+
out.push("");
|
|
3480
|
+
for (const line of rescan) out.push(`- ${line}`);
|
|
3481
|
+
out.push("");
|
|
3482
|
+
}
|
|
3483
|
+
if (withheld.length) {
|
|
3484
|
+
out.push(...withheldSection(withheld, live));
|
|
3485
|
+
out.push("");
|
|
3486
|
+
}
|
|
3487
|
+
if (plan.skipped.length) {
|
|
3488
|
+
out.push("### Findings this PR does NOT address");
|
|
3489
|
+
out.push("");
|
|
3490
|
+
for (const s of plan.skipped) {
|
|
3491
|
+
out.push(`- \`${s.attackId}\` \u2014 ${s.reason}: ${s.detail}`);
|
|
3492
|
+
}
|
|
3493
|
+
out.push("");
|
|
3494
|
+
}
|
|
3495
|
+
if (plan.planned.some((p) => p.verdictPartial)) {
|
|
3496
|
+
out.push(
|
|
3497
|
+
"> \u2139\uFE0F The verdict-quality gate ran on 3 of its 4 conditions (regex\u2194judge disagreement was not available in this report)."
|
|
3498
|
+
);
|
|
3499
|
+
out.push("");
|
|
3500
|
+
}
|
|
3501
|
+
out.push("---");
|
|
3502
|
+
out.push("");
|
|
3503
|
+
out.push(`_${DISCLAIMER}_`);
|
|
3504
|
+
return out.join("\n");
|
|
3505
|
+
}
|
|
3506
|
+
|
|
3507
|
+
// src/fix/claim-store.ts
|
|
3508
|
+
import { existsSync as existsSync5, mkdirSync as mkdirSync3, readFileSync as readFileSync5, writeFileSync as writeFileSync7 } from "fs";
|
|
3509
|
+
import { dirname as dirname2, join as join2 } from "path";
|
|
3510
|
+
var DEFAULT_CLAIM_FILE = ".shield-llm/claims.json";
|
|
3511
|
+
var ClaimStore = class _ClaimStore {
|
|
3512
|
+
constructor(path) {
|
|
3513
|
+
this.path = path;
|
|
3514
|
+
}
|
|
3515
|
+
static at(root, file = DEFAULT_CLAIM_FILE) {
|
|
3516
|
+
return new _ClaimStore(join2(root, file));
|
|
3517
|
+
}
|
|
3518
|
+
load() {
|
|
3519
|
+
if (!existsSync5(this.path)) return null;
|
|
3520
|
+
return JSON.parse(readFileSync5(this.path, "utf8"));
|
|
3521
|
+
}
|
|
3522
|
+
list() {
|
|
3523
|
+
return this.load()?.claims ?? [];
|
|
3524
|
+
}
|
|
3525
|
+
/**
|
|
3526
|
+
* Claims a verification run should look at.
|
|
3527
|
+
*
|
|
3528
|
+
* `refuted_or_not_deployed` is included ON PURPOSE. That status means exactly
|
|
3529
|
+
* "still vulnerable, and we cannot tell whether the patch failed or was
|
|
3530
|
+
* simply not live yet" — so treating it as terminal would make the normal
|
|
3531
|
+
* sequence (patch → verify → deploy → verify again) impossible: the second
|
|
3532
|
+
* verification would find nothing to check. `inconclusive` is included for
|
|
3533
|
+
* the same reason: the family was not executed, so nothing was decided.
|
|
3534
|
+
*
|
|
3535
|
+
* Terminal, and therefore excluded: `confirmed`, `confirmed_overfit`,
|
|
3536
|
+
* `expired`.
|
|
3537
|
+
*/
|
|
3538
|
+
openForVerification() {
|
|
3539
|
+
return this.list().filter(
|
|
3540
|
+
(c2) => c2.status === "pending" || c2.status === "refuted_or_not_deployed" || c2.status === "inconclusive"
|
|
3541
|
+
);
|
|
3542
|
+
}
|
|
3543
|
+
pending() {
|
|
3544
|
+
return this.list().filter((c2) => c2.status === "pending");
|
|
3545
|
+
}
|
|
3546
|
+
/** Upsert by fingerprint+recipe: re-running `fix` refreshes, never duplicates. */
|
|
3547
|
+
upsert(targetId, claim) {
|
|
3548
|
+
const current = this.load() ?? { version: 1, targetId, claims: [] };
|
|
3549
|
+
const idx = current.claims.findIndex(
|
|
3550
|
+
(c2) => c2.findingFingerprint === claim.findingFingerprint && c2.recipeId === claim.recipeId
|
|
3551
|
+
);
|
|
3552
|
+
if (idx === -1) current.claims.push(claim);
|
|
3553
|
+
else current.claims[idx] = claim;
|
|
3554
|
+
this.write({ ...current, targetId });
|
|
3555
|
+
}
|
|
3556
|
+
replace(claim) {
|
|
3557
|
+
const current = this.load();
|
|
3558
|
+
if (!current) return;
|
|
3559
|
+
const idx = current.claims.findIndex(
|
|
3560
|
+
(c2) => c2.findingFingerprint === claim.findingFingerprint && c2.recipeId === claim.recipeId
|
|
3561
|
+
);
|
|
3562
|
+
if (idx !== -1) current.claims[idx] = claim;
|
|
3563
|
+
this.write(current);
|
|
3564
|
+
}
|
|
3565
|
+
write(file) {
|
|
3566
|
+
mkdirSync3(dirname2(this.path), { recursive: true });
|
|
3567
|
+
writeFileSync7(this.path, `${JSON.stringify(file, null, 2)}
|
|
3568
|
+
`, "utf8");
|
|
3569
|
+
}
|
|
3570
|
+
};
|
|
3571
|
+
|
|
3572
|
+
// src/benign/runner.ts
|
|
3573
|
+
async function captureBenign(target, cases, opts = {}) {
|
|
3574
|
+
const client = createTargetClient(target);
|
|
3575
|
+
const out = [];
|
|
3576
|
+
for (const c2 of cases) {
|
|
3577
|
+
let response = "";
|
|
3578
|
+
try {
|
|
3579
|
+
response = await client.sendMessage(c2.prompt);
|
|
3580
|
+
} catch (e) {
|
|
3581
|
+
response = `__SHIELD_CAPTURE_ERROR__:${e instanceof Error ? e.message : "unknown"}`;
|
|
3582
|
+
}
|
|
3583
|
+
out.push({
|
|
3584
|
+
name: c2.name,
|
|
3585
|
+
hash: sha256Hex(response),
|
|
3586
|
+
...opts.keepResponses ? { response } : {}
|
|
3587
|
+
});
|
|
3588
|
+
if (opts.delayMs) await new Promise((r) => setTimeout(r, opts.delayMs));
|
|
3589
|
+
}
|
|
3590
|
+
return out;
|
|
3591
|
+
}
|
|
3592
|
+
function isCaptureError(capture) {
|
|
3593
|
+
return capture.response?.startsWith("__SHIELD_CAPTURE_ERROR__") ?? false;
|
|
3594
|
+
}
|
|
3595
|
+
function toRunResults(baseline, after) {
|
|
3596
|
+
const byName = new Map(baseline.map((b) => [b.name, b.hash]));
|
|
3597
|
+
return after.map((a) => ({ name: a.name, passed: byName.get(a.name) === a.hash }));
|
|
3598
|
+
}
|
|
3599
|
+
function baselineRunResults(run1, run2) {
|
|
3600
|
+
const r1 = new Map(run1.map((b) => [b.name, b.hash]));
|
|
3601
|
+
const stable = (c2) => r1.get(c2.name) === c2.hash;
|
|
3602
|
+
return [
|
|
3603
|
+
run1.map((c2) => ({ name: c2.name, passed: true })),
|
|
3604
|
+
run2.map((c2) => ({ name: c2.name, passed: stable(c2) }))
|
|
3605
|
+
];
|
|
3606
|
+
}
|
|
3607
|
+
async function judgeBenign(captures, cases, evaluator) {
|
|
3608
|
+
const byName = new Map(cases.map((c2) => [c2.name, c2]));
|
|
3609
|
+
const out = [];
|
|
3610
|
+
for (const cap of captures) {
|
|
3611
|
+
const c2 = byName.get(cap.name);
|
|
3612
|
+
if (!c2 || cap.response === void 0) {
|
|
3613
|
+
out.push({ name: cap.name, passed: true });
|
|
3614
|
+
continue;
|
|
3615
|
+
}
|
|
3616
|
+
if (isCaptureError(cap)) {
|
|
3617
|
+
out.push({ name: cap.name, passed: true });
|
|
3618
|
+
continue;
|
|
3619
|
+
}
|
|
3620
|
+
const verdict = await evaluator.evaluate({
|
|
3621
|
+
attackId: `benign_${c2.name}`,
|
|
3622
|
+
attackName: c2.name,
|
|
3623
|
+
attackPrompt: c2.prompt,
|
|
3624
|
+
severity: "LOW",
|
|
3625
|
+
response: cap.response,
|
|
3626
|
+
regexResult: { vulnerable: false },
|
|
3627
|
+
customTest: { name: c2.name, acceptanceCriteria: c2.acceptanceCriteria }
|
|
3628
|
+
});
|
|
3629
|
+
out.push({ name: cap.name, passed: !verdict.vulnerable });
|
|
3630
|
+
}
|
|
3631
|
+
return out;
|
|
3632
|
+
}
|
|
3633
|
+
|
|
3634
|
+
// src/fix/live-verify.ts
|
|
3635
|
+
async function runBenignGate(input2) {
|
|
3636
|
+
const { baseline, contract, target } = input2;
|
|
3637
|
+
const scope = baseline?.scope ?? contract.benignScope;
|
|
3638
|
+
if (scope === "none") return { green: true, detail: "no benign surface", ran: false };
|
|
3639
|
+
const cannotRun = !baseline || scope === "model-behaviour" && !input2.evaluator;
|
|
3640
|
+
if (cannotRun && input2.assumeGreen) {
|
|
3641
|
+
console.warn(
|
|
3642
|
+
"\u26A0\uFE0F --assume-benign-green: the benign gate was NOT run. You are asserting that the patch did not break the product; nothing verified it."
|
|
3643
|
+
);
|
|
3644
|
+
return {
|
|
3645
|
+
green: true,
|
|
3646
|
+
ran: false,
|
|
3647
|
+
detail: "BYPASSED by --assume-benign-green (not verified)"
|
|
3648
|
+
};
|
|
3649
|
+
}
|
|
3650
|
+
if (!baseline) {
|
|
3651
|
+
return {
|
|
3652
|
+
green: false,
|
|
3653
|
+
ran: false,
|
|
3654
|
+
detail: "no benign baseline was captured before patching \u2014 the gate cannot run, so it does not pass"
|
|
3655
|
+
};
|
|
3656
|
+
}
|
|
3657
|
+
const cases = BENIGN_CORE_V1.filter(
|
|
3658
|
+
(c2) => baseline.run1.some((b) => b.name === c2.name)
|
|
3659
|
+
);
|
|
3660
|
+
if (scope === "rendering") {
|
|
3661
|
+
const after2 = await captureBenign(target, cases);
|
|
3662
|
+
const report2 = evaluateBenign({
|
|
3663
|
+
suiteId: baseline.suiteId,
|
|
3664
|
+
cases,
|
|
3665
|
+
baselineRuns: baselineRunResults(baseline.run1, baseline.run2),
|
|
3666
|
+
afterRun: toRunResults(baseline.run1, after2),
|
|
3667
|
+
gate: contract.benignGate
|
|
3668
|
+
});
|
|
3669
|
+
return {
|
|
3670
|
+
green: !report2.blocked,
|
|
3671
|
+
ran: true,
|
|
3672
|
+
detail: report2.blocked ? `blocked: ${report2.flips.map((f) => f.name + (f.criticalPath ? "*" : "")).join(", ")}` : `${cases.length} cases, ${report2.flips.length} flip(s), ${report2.flakyCaseNames.length} flaky`
|
|
3673
|
+
};
|
|
3674
|
+
}
|
|
3675
|
+
const judge = input2.evaluator;
|
|
3676
|
+
if (!judge) {
|
|
3677
|
+
return {
|
|
3678
|
+
green: false,
|
|
3679
|
+
ran: false,
|
|
3680
|
+
detail: "benignScope is `model-behaviour` but no judge is available \u2014 the answers legitimately changed, so only a judge could rule and the gate did not run. Configure a judge, or accept the risk explicitly with --assume-benign-green."
|
|
3681
|
+
};
|
|
3682
|
+
}
|
|
3683
|
+
const after = await captureBenign(target, cases, { keepResponses: true });
|
|
3684
|
+
const report = evaluateBenign({
|
|
3685
|
+
suiteId: baseline.suiteId,
|
|
3686
|
+
cases,
|
|
3687
|
+
baselineRuns: baselineRunResults(baseline.run1, baseline.run2),
|
|
3688
|
+
afterRun: await judgeBenign(after, cases, judge),
|
|
3689
|
+
gate: contract.benignGate
|
|
3690
|
+
});
|
|
3691
|
+
return {
|
|
3692
|
+
green: !report.blocked,
|
|
3693
|
+
ran: true,
|
|
3694
|
+
detail: report.blocked ? `blocked: ${report.flips.map((f) => f.name + (f.criticalPath ? "*" : "")).join(", ")}` : `${cases.length} cases judged, ${report.flips.length} flip(s)`
|
|
3695
|
+
};
|
|
3696
|
+
}
|
|
3697
|
+
async function replayFamily(contract, target, catalogue, evaluator) {
|
|
3698
|
+
const wanted = /* @__PURE__ */ new Set([
|
|
3699
|
+
...contract.designAttackIds,
|
|
3700
|
+
...contract.holdoutAttackIds
|
|
3701
|
+
]);
|
|
3702
|
+
const attacks = [
|
|
3703
|
+
...catalogue.filter((a) => wanted.has(a.id)),
|
|
3704
|
+
...Array.from(wanted).filter(isVariantId).map((id) => buildVariantPayload(id, catalogue)).filter((a) => a !== null)
|
|
3705
|
+
];
|
|
3706
|
+
const report = await new Scanner({
|
|
3707
|
+
target,
|
|
3708
|
+
preset: "dev",
|
|
3709
|
+
attacks,
|
|
3710
|
+
evaluator,
|
|
3711
|
+
concurrency: 1,
|
|
3712
|
+
delayMs: 0
|
|
3713
|
+
}).run();
|
|
3714
|
+
const verdicts = /* @__PURE__ */ new Map();
|
|
3715
|
+
for (const a of report.attacks) {
|
|
3716
|
+
if (a.error || a.rateLimited) continue;
|
|
3717
|
+
verdicts.set(a.id, a.vulnerable);
|
|
3718
|
+
}
|
|
3719
|
+
return { verdicts, judgeDegraded: analyzeJudgeHealth(report).degraded };
|
|
3720
|
+
}
|
|
3721
|
+
async function verifyLive(input2) {
|
|
3722
|
+
const { contract } = input2;
|
|
3723
|
+
const { verdicts, judgeDegraded } = await replayFamily(
|
|
3724
|
+
contract,
|
|
3725
|
+
input2.target,
|
|
3726
|
+
input2.catalogue,
|
|
3727
|
+
input2.evaluator
|
|
3728
|
+
);
|
|
3729
|
+
const cleared = (id) => verdicts.get(id) === false;
|
|
3730
|
+
const executed = (id) => verdicts.has(id);
|
|
3731
|
+
const all = [...contract.designAttackIds, ...contract.holdoutAttackIds];
|
|
3732
|
+
const designClearedIds = contract.designAttackIds.filter(cleared);
|
|
3733
|
+
const holdoutClearedIds = contract.holdoutAttackIds.filter(cleared);
|
|
3734
|
+
const notExecutedAttackIds = all.filter((id) => !executed(id));
|
|
3735
|
+
const benign = await runBenignGate({
|
|
3736
|
+
baseline: input2.baseline,
|
|
3737
|
+
contract,
|
|
3738
|
+
target: input2.target,
|
|
3739
|
+
evaluator: input2.judgeAvailable ? input2.evaluator : void 0,
|
|
3740
|
+
assumeGreen: input2.assumeBenignGreen
|
|
3741
|
+
});
|
|
3742
|
+
const passed = designClearedIds.length === contract.designAttackIds.length && holdoutClearedIds.length === contract.holdoutAttackIds.length && notExecutedAttackIds.length === 0 && benign.green && !judgeDegraded;
|
|
3743
|
+
return {
|
|
3744
|
+
verifiedAt: new Date(input2.nowMs).toISOString(),
|
|
3745
|
+
redeployCommand: input2.redeployCommand,
|
|
3746
|
+
designAttackIds: contract.designAttackIds,
|
|
3747
|
+
designClearedIds,
|
|
3748
|
+
holdoutAttackIds: contract.holdoutAttackIds,
|
|
3749
|
+
holdoutClearedIds,
|
|
3750
|
+
notExecutedAttackIds,
|
|
3751
|
+
benign: { ran: benign.ran, green: benign.green, detail: benign.detail },
|
|
3752
|
+
judgeDegraded,
|
|
3753
|
+
sessionIsolated: checkSessionIsolation(input2.target).isolated,
|
|
3754
|
+
passed
|
|
3755
|
+
};
|
|
3756
|
+
}
|
|
3757
|
+
function describeLiveVerification(v) {
|
|
3758
|
+
if (v.passed) {
|
|
3759
|
+
return `design ${v.designClearedIds.length}/${v.designAttackIds.length} closed, holdout ${v.holdoutClearedIds.length}/${v.holdoutAttackIds.length} closed, benign ${v.benign.ran ? "green" : v.benign.detail}`;
|
|
3760
|
+
}
|
|
3761
|
+
const why = [];
|
|
3762
|
+
const designOpen = v.designAttackIds.filter((a) => !v.designClearedIds.includes(a));
|
|
3763
|
+
const holdoutOpen = v.holdoutAttackIds.filter((a) => !v.holdoutClearedIds.includes(a));
|
|
3764
|
+
if (designOpen.length) why.push(`still vulnerable: ${designOpen.join(", ")}`);
|
|
3765
|
+
if (holdoutOpen.length) {
|
|
3766
|
+
why.push(
|
|
3767
|
+
designOpen.length === 0 ? `OVERFITTED \u2014 the design attack closed but the holdout did not: ${holdoutOpen.join(", ")}` : `holdout still open: ${holdoutOpen.join(", ")}`
|
|
3768
|
+
);
|
|
3769
|
+
}
|
|
3770
|
+
if (v.notExecutedAttackIds.length) {
|
|
3771
|
+
why.push(`no verdict for ${v.notExecutedAttackIds.join(", ")}`);
|
|
3772
|
+
}
|
|
3773
|
+
if (designOpen.length > 0 && holdoutOpen.length === 0 && v.holdoutAttackIds.length > 0) {
|
|
3774
|
+
why.push(
|
|
3775
|
+
"note: every holdout closed and only the design attack did not \u2014 re-read the judge's verdict on it before assuming the patch is ineffective"
|
|
3776
|
+
);
|
|
3777
|
+
}
|
|
3778
|
+
if (!v.benign.green) why.push(`benign gate: ${v.benign.detail}`);
|
|
3779
|
+
if (v.judgeDegraded) why.push("the judge degraded mid-replay, so no verdict is trustworthy");
|
|
3780
|
+
return why.join(" \xB7 ");
|
|
3781
|
+
}
|
|
3782
|
+
|
|
3783
|
+
// src/fix/rescan.ts
|
|
3784
|
+
async function rescanAndDiff(input2) {
|
|
3785
|
+
const wanted = new Set(input2.before.map((a) => a.id));
|
|
3786
|
+
const attacks = input2.catalogue.filter((a) => wanted.has(a.id));
|
|
3787
|
+
if (attacks.length === 0) return null;
|
|
3788
|
+
const report = await new Scanner({
|
|
3789
|
+
target: input2.target,
|
|
3790
|
+
preset: "dev",
|
|
3791
|
+
attacks,
|
|
3792
|
+
evaluator: input2.evaluator,
|
|
3793
|
+
concurrency: input2.concurrency ?? 1,
|
|
3794
|
+
delayMs: input2.delayMs ?? 0
|
|
3795
|
+
}).run();
|
|
3796
|
+
const after = report.attacks.map((a) => ({
|
|
3797
|
+
id: a.id,
|
|
3798
|
+
severity: a.severity,
|
|
3799
|
+
vulnerable: a.vulnerable,
|
|
3800
|
+
error: a.error,
|
|
3801
|
+
rateLimited: a.rateLimited
|
|
3802
|
+
}));
|
|
3803
|
+
const delta = computeScoreDelta(input2.before, after);
|
|
3804
|
+
const beforeById = new Map(input2.before.map((a) => [a.id, a]));
|
|
3805
|
+
const afterById = new Map(after.map((a) => [a.id, a]));
|
|
3806
|
+
const closed = delta.comparableAttackIds.filter(
|
|
3807
|
+
(id) => beforeById.get(id)?.vulnerable && !afterById.get(id)?.vulnerable
|
|
3808
|
+
);
|
|
3809
|
+
const opened = delta.comparableAttackIds.filter(
|
|
3810
|
+
(id) => !beforeById.get(id)?.vulnerable && afterById.get(id)?.vulnerable
|
|
3811
|
+
);
|
|
3812
|
+
return { delta, closed, opened };
|
|
3813
|
+
}
|
|
3814
|
+
function describeRescan(r) {
|
|
3815
|
+
const d = r.delta;
|
|
3816
|
+
const sign = d.delta > 0 ? "+" : "";
|
|
3817
|
+
const lines = [
|
|
3818
|
+
`Score ${d.scoreBefore} \u2192 ${d.scoreAfter} (${sign}${d.delta}), grade ${d.gradeBefore} \u2192 ${d.gradeAfter}, over the ${d.comparableAttackIds.length} attack(s) with a real verdict in both runs.`
|
|
3819
|
+
];
|
|
3820
|
+
if (r.closed.length) lines.push(`Closed: ${r.closed.join(", ")}`);
|
|
3821
|
+
if (r.opened.length) lines.push(`\u26A0\uFE0F NEWLY vulnerable: ${r.opened.join(", ")}`);
|
|
3822
|
+
if (d.excluded.length) {
|
|
3823
|
+
lines.push(
|
|
3824
|
+
`Excluded from the comparison: ${d.excluded.map((e) => `${e.attackId} (${e.reason})`).join(", ")}`
|
|
3825
|
+
);
|
|
3826
|
+
}
|
|
3827
|
+
if (d.wafShapedFixSuspected) {
|
|
3828
|
+
lines.push(
|
|
3829
|
+
"\u26A0\uFE0F More payloads were REJECTED after the patch than before. A fix that makes attacks fail to run removes them from the denominator and inflates the score without improving anything \u2014 check this before trusting the delta."
|
|
3830
|
+
);
|
|
3831
|
+
} else if (d.exclusionCountRose) {
|
|
3832
|
+
lines.push(
|
|
3833
|
+
"\u26A0\uFE0F More attacks were excluded after the patch than before (timeouts, errors). The denominator shrank, so the delta rests on fewer tests than it looks."
|
|
3834
|
+
);
|
|
3835
|
+
}
|
|
3836
|
+
lines.push(
|
|
3837
|
+
`Raw per-run scores, for reference: ${d.rawScoreBefore} \u2192 ${d.rawScoreAfter}. These are NOT comparable to each other \u2014 they are what the dashboard shows.`
|
|
3838
|
+
);
|
|
3839
|
+
return lines;
|
|
3840
|
+
}
|
|
3841
|
+
|
|
3842
|
+
// src/fix/redeploy.ts
|
|
3843
|
+
import { spawn } from "child_process";
|
|
3844
|
+
function runCommand(command, cwd, timeoutMs) {
|
|
3845
|
+
return new Promise((resolvePromise) => {
|
|
3846
|
+
const child = spawn(command, {
|
|
3847
|
+
cwd,
|
|
3848
|
+
shell: true,
|
|
3849
|
+
stdio: ["ignore", "pipe", "pipe"]
|
|
3850
|
+
});
|
|
3851
|
+
let out = "";
|
|
3852
|
+
const capture = (b) => {
|
|
3853
|
+
out = (out + b.toString()).slice(-4e3);
|
|
3854
|
+
};
|
|
3855
|
+
child.stdout.on("data", capture);
|
|
3856
|
+
child.stderr.on("data", capture);
|
|
3857
|
+
const timer = setTimeout(() => {
|
|
3858
|
+
child.kill("SIGKILL");
|
|
3859
|
+
resolvePromise({
|
|
3860
|
+
ok: false,
|
|
3861
|
+
detail: `redeploy command did not return within ${timeoutMs}ms. It must start the target and exit \u2014 background it (\`&\`, \`-d\`, \`nohup\`) rather than running the server in the foreground.`
|
|
3862
|
+
});
|
|
3863
|
+
}, timeoutMs);
|
|
3864
|
+
child.on("error", (e) => {
|
|
3865
|
+
clearTimeout(timer);
|
|
3866
|
+
resolvePromise({ ok: false, detail: `could not run redeploy command: ${e.message}` });
|
|
3867
|
+
});
|
|
3868
|
+
child.on("close", (code) => {
|
|
3869
|
+
clearTimeout(timer);
|
|
3870
|
+
resolvePromise(
|
|
3871
|
+
code === 0 ? { ok: true, detail: "redeploy command exited 0" } : { ok: false, detail: `redeploy command exited ${code}
|
|
3872
|
+
${out.trim()}` }
|
|
3873
|
+
);
|
|
3874
|
+
});
|
|
3875
|
+
});
|
|
3876
|
+
}
|
|
3877
|
+
async function waitForHealthy(target, timeoutMs) {
|
|
3878
|
+
const client = createTargetClient(target);
|
|
3879
|
+
const deadline = Date.now() + timeoutMs;
|
|
3880
|
+
let last = "never reached";
|
|
3881
|
+
let attempts = 0;
|
|
3882
|
+
while (Date.now() < deadline) {
|
|
3883
|
+
attempts++;
|
|
3884
|
+
try {
|
|
3885
|
+
await client.sendMessage("ping");
|
|
3886
|
+
return { ok: true, detail: `healthy after ${attempts} probe(s)` };
|
|
3887
|
+
} catch (e) {
|
|
3888
|
+
last = e instanceof Error ? e.message : String(e);
|
|
3889
|
+
await new Promise((r) => setTimeout(r, 500));
|
|
3890
|
+
}
|
|
3891
|
+
}
|
|
3892
|
+
return {
|
|
3893
|
+
ok: false,
|
|
3894
|
+
detail: `target did not answer within ${timeoutMs}ms (${attempts} probes, last error: ${last})`
|
|
3895
|
+
};
|
|
3896
|
+
}
|
|
3897
|
+
async function redeploy(cfg, target, cwd) {
|
|
3898
|
+
const started = Date.now();
|
|
3899
|
+
console.log(`
|
|
3900
|
+
Redeploying so the patch is live:
|
|
3901
|
+
$ ${cfg.command}`);
|
|
3902
|
+
const ran = await runCommand(cfg.command, cwd, cfg.timeoutMs);
|
|
3903
|
+
if (!ran.ok) return { ok: false, detail: ran.detail, elapsedMs: Date.now() - started };
|
|
3904
|
+
const healthy = await waitForHealthy(target, cfg.healthTimeoutMs);
|
|
3905
|
+
return {
|
|
3906
|
+
ok: healthy.ok,
|
|
3907
|
+
detail: healthy.ok ? `${ran.detail}, ${healthy.detail}` : healthy.detail,
|
|
3908
|
+
elapsedMs: Date.now() - started
|
|
3909
|
+
};
|
|
3910
|
+
}
|
|
3911
|
+
|
|
3912
|
+
// src/fix/git.ts
|
|
3913
|
+
import { execFileSync } from "child_process";
|
|
3914
|
+
var GitError = class extends Error {
|
|
3915
|
+
};
|
|
3916
|
+
function git(cwd, args, opts = {}) {
|
|
3917
|
+
try {
|
|
3918
|
+
const out = execFileSync("git", args, {
|
|
3919
|
+
cwd,
|
|
3920
|
+
encoding: "utf8",
|
|
3921
|
+
stdio: ["ignore", "pipe", "pipe"]
|
|
3922
|
+
});
|
|
3923
|
+
return opts.trim === false ? out.replace(/\n$/, "") : out.trim();
|
|
3924
|
+
} catch (e) {
|
|
3925
|
+
const err = e;
|
|
3926
|
+
const stderr = typeof err.stderr === "string" ? err.stderr : err.stderr?.toString() ?? "";
|
|
3927
|
+
throw new GitError(`git ${args[0]} failed: ${(stderr || err.message || "").trim()}`);
|
|
3928
|
+
}
|
|
3929
|
+
}
|
|
3930
|
+
function isGitRepo(cwd) {
|
|
3931
|
+
try {
|
|
3932
|
+
return git(cwd, ["rev-parse", "--is-inside-work-tree"]) === "true";
|
|
3933
|
+
} catch {
|
|
3934
|
+
return false;
|
|
3935
|
+
}
|
|
3936
|
+
}
|
|
3937
|
+
function currentBranch(cwd) {
|
|
3938
|
+
const name = git(cwd, ["rev-parse", "--abbrev-ref", "HEAD"]);
|
|
3939
|
+
if (name === "HEAD") {
|
|
3940
|
+
throw new GitError(
|
|
3941
|
+
"HEAD is detached, so there is no branch to open a PR against. Check out a branch first."
|
|
3942
|
+
);
|
|
3943
|
+
}
|
|
3944
|
+
return name;
|
|
3945
|
+
}
|
|
3946
|
+
function branchExists(cwd, name) {
|
|
3947
|
+
try {
|
|
3948
|
+
git(cwd, ["show-ref", "--verify", "--quiet", `refs/heads/${name}`]);
|
|
3949
|
+
return true;
|
|
3950
|
+
} catch {
|
|
3951
|
+
return false;
|
|
3952
|
+
}
|
|
3953
|
+
}
|
|
3954
|
+
function createBranch(cwd, name) {
|
|
3955
|
+
if (branchExists(cwd, name)) {
|
|
3956
|
+
throw new GitError(
|
|
3957
|
+
`branch \`${name}\` already exists. Delete it (\`git branch -D ${name}\`) or pass --pr-branch <name> to use another one.`
|
|
3958
|
+
);
|
|
3959
|
+
}
|
|
3960
|
+
git(cwd, ["checkout", "-b", name]);
|
|
3961
|
+
}
|
|
3962
|
+
function checkoutBranch(cwd, name) {
|
|
3963
|
+
git(cwd, ["checkout", name]);
|
|
3964
|
+
}
|
|
3965
|
+
function commitPaths(cwd, paths, message) {
|
|
3966
|
+
if (paths.length === 0) throw new GitError("nothing to commit: no file was patched");
|
|
3967
|
+
git(cwd, ["add", "--", ...paths]);
|
|
3968
|
+
const staged = git(cwd, ["diff", "--cached", "--name-only"]).split("\n").filter(Boolean);
|
|
3969
|
+
if (staged.length === 0) {
|
|
3970
|
+
throw new GitError(
|
|
3971
|
+
"the patched files produced no staged change \u2014 the patch is probably already committed"
|
|
3972
|
+
);
|
|
3973
|
+
}
|
|
3974
|
+
git(cwd, ["commit", "--no-verify", "-m", message]);
|
|
3975
|
+
return { sha: git(cwd, ["rev-parse", "HEAD"]), committed: staged };
|
|
3976
|
+
}
|
|
3977
|
+
function hasRemote(cwd, remote = "origin") {
|
|
3978
|
+
try {
|
|
3979
|
+
return git(cwd, ["remote"]).split("\n").includes(remote);
|
|
3980
|
+
} catch {
|
|
3981
|
+
return false;
|
|
3982
|
+
}
|
|
3983
|
+
}
|
|
3984
|
+
function pushBranch(cwd, branch, remote = "origin") {
|
|
3985
|
+
git(cwd, ["push", "-u", remote, branch]);
|
|
3986
|
+
}
|
|
3987
|
+
function dirtyPathsExcluding(cwd, ours) {
|
|
3988
|
+
const mine = new Set(ours);
|
|
3989
|
+
return git(cwd, ["status", "--porcelain"], { trim: false }).split("\n").filter(Boolean).map((l) => l.slice(3).trim()).filter((p) => !mine.has(p)).filter((p) => !(p.endsWith("/") && ours.some((o) => o.startsWith(p))));
|
|
3990
|
+
}
|
|
3991
|
+
|
|
3992
|
+
// src/fix/pr.ts
|
|
3993
|
+
import { execFileSync as execFileSync2 } from "child_process";
|
|
3994
|
+
import { mkdtempSync, writeFileSync as writeFileSync8 } from "fs";
|
|
3995
|
+
import { tmpdir } from "os";
|
|
3996
|
+
import { join as join3 } from "path";
|
|
3997
|
+
function ghStatus(cwd) {
|
|
3998
|
+
try {
|
|
3999
|
+
execFileSync2("gh", ["--version"], { cwd, stdio: "ignore" });
|
|
4000
|
+
} catch {
|
|
4001
|
+
return {
|
|
4002
|
+
available: false,
|
|
4003
|
+
authenticated: false,
|
|
4004
|
+
detail: "the `gh` CLI is not installed (https://cli.github.com)"
|
|
4005
|
+
};
|
|
4006
|
+
}
|
|
4007
|
+
try {
|
|
4008
|
+
execFileSync2("gh", ["auth", "status"], { cwd, stdio: "ignore" });
|
|
4009
|
+
return { available: true, authenticated: true, detail: "gh authenticated" };
|
|
4010
|
+
} catch {
|
|
4011
|
+
return {
|
|
4012
|
+
available: true,
|
|
4013
|
+
authenticated: false,
|
|
4014
|
+
detail: "`gh` is installed but not logged in \u2014 run `gh auth login`"
|
|
4015
|
+
};
|
|
4016
|
+
}
|
|
4017
|
+
}
|
|
4018
|
+
function createPullRequest(input2) {
|
|
4019
|
+
const dir = mkdtempSync(join3(tmpdir(), "shield-pr-"));
|
|
4020
|
+
const bodyFile = join3(dir, "body.md");
|
|
4021
|
+
writeFileSync8(bodyFile, input2.body, "utf8");
|
|
4022
|
+
const args = [
|
|
4023
|
+
"pr",
|
|
4024
|
+
"create",
|
|
4025
|
+
"--head",
|
|
4026
|
+
input2.branch,
|
|
4027
|
+
"--base",
|
|
4028
|
+
input2.base,
|
|
4029
|
+
"--title",
|
|
4030
|
+
input2.title,
|
|
4031
|
+
"--body-file",
|
|
4032
|
+
bodyFile,
|
|
4033
|
+
...input2.draft ? ["--draft"] : []
|
|
4034
|
+
];
|
|
4035
|
+
try {
|
|
4036
|
+
const out = execFileSync2("gh", args, {
|
|
4037
|
+
cwd: input2.cwd,
|
|
4038
|
+
encoding: "utf8",
|
|
4039
|
+
stdio: ["ignore", "pipe", "pipe"]
|
|
4040
|
+
});
|
|
4041
|
+
const url = out.split("\n").map((l) => l.trim()).filter((l) => l.startsWith("http")).pop();
|
|
4042
|
+
return { ok: true, url, detail: url ?? out.trim() };
|
|
4043
|
+
} catch (e) {
|
|
4044
|
+
const err = e;
|
|
4045
|
+
const stderr = typeof err.stderr === "string" ? err.stderr : err.stderr?.toString() ?? "";
|
|
4046
|
+
return { ok: false, detail: (stderr || err.message || "gh pr create failed").trim() };
|
|
4047
|
+
}
|
|
4048
|
+
}
|
|
4049
|
+
function manualPrInstructions(branch, base) {
|
|
4050
|
+
return `The branch \`${branch}\` is committed locally. To finish:
|
|
4051
|
+
git push -u origin ${branch}
|
|
4052
|
+
gh pr create --head ${branch} --base ${base} --fill`;
|
|
4053
|
+
}
|
|
4054
|
+
|
|
4055
|
+
// src/fix/open-pr.ts
|
|
4056
|
+
function branchNameFor(plan) {
|
|
4057
|
+
const key = plan.planned.map((p) => p.fingerprint).sort().join("|");
|
|
4058
|
+
return `shield/fix-${sha256Hex(key).slice(0, 8)}`;
|
|
4059
|
+
}
|
|
4060
|
+
function commitMessage(plan, live) {
|
|
4061
|
+
const n = plan.planned.length;
|
|
4062
|
+
const head = `fix(security): patch ${n} finding${n === 1 ? "" : "s"} found by Shield LLM`;
|
|
4063
|
+
const lines = [head, ""];
|
|
4064
|
+
for (const p of plan.planned) {
|
|
4065
|
+
const v = live?.get(p.fingerprint);
|
|
4066
|
+
lines.push(
|
|
4067
|
+
`- ${p.attackId} (${p.severity}) via ${p.recipe.id}` + (v?.passed ? ` \u2014 verified live: design ${v.designClearedIds.length}/${v.designAttackIds.length}, holdout ${v.holdoutClearedIds.length}/${v.holdoutAttackIds.length}` : "")
|
|
4068
|
+
);
|
|
4069
|
+
}
|
|
4070
|
+
lines.push("");
|
|
4071
|
+
lines.push(
|
|
4072
|
+
"Generated by `shield-llm fix`. The patch changes source; run `shield-llm verify-claims` after deploying to close the findings."
|
|
4073
|
+
);
|
|
4074
|
+
return lines.join("\n");
|
|
4075
|
+
}
|
|
4076
|
+
function branchAndCommit(cwd, branch, base, opts) {
|
|
4077
|
+
let created = false;
|
|
4078
|
+
try {
|
|
4079
|
+
createBranch(cwd, branch);
|
|
4080
|
+
created = true;
|
|
4081
|
+
const { committed } = commitPaths(
|
|
4082
|
+
cwd,
|
|
4083
|
+
opts.touchedPaths,
|
|
4084
|
+
commitMessage(opts.plan, opts.live)
|
|
4085
|
+
);
|
|
4086
|
+
console.log(`
|
|
4087
|
+
Committed on \`${branch}\`: ${committed.join(", ")}`);
|
|
4088
|
+
return { ok: true, branch, detail: committed.join(", ") };
|
|
4089
|
+
} catch (e) {
|
|
4090
|
+
if (created) {
|
|
4091
|
+
try {
|
|
4092
|
+
checkoutBranch(cwd, base);
|
|
4093
|
+
} catch {
|
|
4094
|
+
}
|
|
4095
|
+
}
|
|
4096
|
+
return {
|
|
4097
|
+
ok: false,
|
|
4098
|
+
branch: created && branchExists(cwd, branch) ? branch : void 0,
|
|
4099
|
+
detail: e instanceof GitError ? e.message : String(e)
|
|
4100
|
+
};
|
|
4101
|
+
}
|
|
4102
|
+
}
|
|
4103
|
+
function openPullRequest(opts) {
|
|
4104
|
+
const { cwd } = opts;
|
|
4105
|
+
if (!isGitRepo(cwd)) {
|
|
4106
|
+
return { ok: false, detail: "not a git repository \u2014 nothing to open a PR from" };
|
|
4107
|
+
}
|
|
4108
|
+
let base;
|
|
4109
|
+
try {
|
|
4110
|
+
base = opts.base ?? currentBranch(cwd);
|
|
4111
|
+
} catch (e) {
|
|
4112
|
+
return { ok: false, detail: e instanceof GitError ? e.message : String(e) };
|
|
4113
|
+
}
|
|
4114
|
+
const branch = opts.branch ?? branchNameFor(opts.plan);
|
|
4115
|
+
const otherDirty = dirtyPathsExcluding(cwd, opts.touchedPaths);
|
|
4116
|
+
if (otherDirty.length) {
|
|
4117
|
+
console.log(
|
|
4118
|
+
`
|
|
4119
|
+
Not included in this PR (unrelated local changes, left untouched): ${otherDirty.join(", ")}`
|
|
4120
|
+
);
|
|
4121
|
+
}
|
|
4122
|
+
const landed = branchAndCommit(cwd, branch, base, opts);
|
|
4123
|
+
if (!landed.ok) return landed;
|
|
4124
|
+
if (!opts.push) {
|
|
4125
|
+
return { ok: true, branch, detail: manualPrInstructions(branch, base) };
|
|
4126
|
+
}
|
|
4127
|
+
if (!hasRemote(cwd)) {
|
|
4128
|
+
return {
|
|
4129
|
+
ok: true,
|
|
4130
|
+
branch,
|
|
4131
|
+
detail: `no \`origin\` remote \u2014 the commit is local.
|
|
4132
|
+
${manualPrInstructions(branch, base)}`
|
|
4133
|
+
};
|
|
4134
|
+
}
|
|
4135
|
+
const gh = ghStatus(cwd);
|
|
4136
|
+
try {
|
|
4137
|
+
pushBranch(cwd, branch);
|
|
4138
|
+
} catch (e) {
|
|
4139
|
+
return {
|
|
4140
|
+
ok: false,
|
|
4141
|
+
branch,
|
|
4142
|
+
detail: `${e instanceof GitError ? e.message : String(e)}
|
|
4143
|
+
${manualPrInstructions(branch, base)}`
|
|
4144
|
+
};
|
|
4145
|
+
}
|
|
4146
|
+
if (!gh.authenticated) {
|
|
4147
|
+
return {
|
|
4148
|
+
ok: true,
|
|
4149
|
+
branch,
|
|
4150
|
+
detail: `pushed, but ${gh.detail}.
|
|
4151
|
+
${manualPrInstructions(branch, base)}`
|
|
4152
|
+
};
|
|
4153
|
+
}
|
|
4154
|
+
const n = opts.plan.planned.length;
|
|
4155
|
+
const pr = createPullRequest({
|
|
4156
|
+
cwd,
|
|
4157
|
+
branch,
|
|
4158
|
+
base,
|
|
4159
|
+
title: `Shield LLM \u2014 patch ${n} security finding${n === 1 ? "" : "s"}`,
|
|
4160
|
+
body: opts.body,
|
|
4161
|
+
draft: opts.draft
|
|
4162
|
+
});
|
|
4163
|
+
return pr.ok ? { ok: true, branch, url: pr.url, detail: pr.url ?? pr.detail } : {
|
|
4164
|
+
ok: false,
|
|
4165
|
+
branch,
|
|
4166
|
+
detail: `${pr.detail}
|
|
4167
|
+
${manualPrInstructions(branch, base)}`
|
|
4168
|
+
};
|
|
4169
|
+
}
|
|
4170
|
+
|
|
4171
|
+
// src/commands/fix.ts
|
|
4172
|
+
function resolveEvaluator(opts) {
|
|
4173
|
+
if (opts.evaluator) return { evaluator: opts.evaluator, judgeAvailable: true };
|
|
4174
|
+
const creds = loadCredentials();
|
|
4175
|
+
if (creds?.apiKey && creds.apiUrl) {
|
|
4176
|
+
return {
|
|
4177
|
+
evaluator: new BackendEvaluator(creds.apiUrl, creds.apiKey),
|
|
4178
|
+
judgeAvailable: true
|
|
4179
|
+
};
|
|
4180
|
+
}
|
|
4181
|
+
console.warn(
|
|
4182
|
+
"\u26A0\uFE0F Not logged in: the replay will use regex-only detection and the benign gate cannot run. Run `shield-llm login` for a judged verification."
|
|
4183
|
+
);
|
|
4184
|
+
return { evaluator: new RegexOnlyEvaluator(), judgeAvailable: false };
|
|
4185
|
+
}
|
|
4186
|
+
function findingsFromLocalReport(path) {
|
|
4187
|
+
const parsed = JSON.parse(readFileSync6(path, "utf8"));
|
|
4188
|
+
const r = parsed.report;
|
|
4189
|
+
if (!r?.attacks) throw new Error(`${path} is not a shield-llm --write-json report`);
|
|
4190
|
+
return {
|
|
4191
|
+
allAttacks: r.attacks.map((a) => ({
|
|
4192
|
+
id: a.id,
|
|
4193
|
+
severity: a.severity,
|
|
4194
|
+
vulnerable: a.vulnerable,
|
|
4195
|
+
error: a.error,
|
|
4196
|
+
rateLimited: a.rateLimited
|
|
4197
|
+
})),
|
|
4198
|
+
targetUrl: r.target,
|
|
4199
|
+
findings: r.attacks.filter((a) => a.vulnerable).map((a) => ({
|
|
4200
|
+
attackId: a.id,
|
|
4201
|
+
name: a.name,
|
|
4202
|
+
severity: a.severity,
|
|
4203
|
+
evaluationMethod: a.llmEvaluation?.evaluationMethod ?? null,
|
|
4204
|
+
confidence: a.llmEvaluation?.confidence ?? null,
|
|
4205
|
+
judgeErrorCategory: a.llmEvaluation?.judgeError?.category ?? null,
|
|
4206
|
+
disagreementResolution: a.disagreement?.resolution ?? null
|
|
4207
|
+
}))
|
|
4208
|
+
};
|
|
4209
|
+
}
|
|
4210
|
+
var CODE_EXT = /\.(ts|tsx|js|jsx|mjs|cjs|py|rb|go|java|php)$/;
|
|
4211
|
+
function uncommittedCode(cwd) {
|
|
4212
|
+
try {
|
|
4213
|
+
return execFileSync3("git", ["status", "--porcelain"], { cwd, encoding: "utf8" }).split("\n").filter(Boolean).map((l) => l.slice(3).trim()).filter((p) => CODE_EXT.test(p));
|
|
4214
|
+
} catch {
|
|
4215
|
+
return [];
|
|
4216
|
+
}
|
|
4217
|
+
}
|
|
4218
|
+
function gitIsClean(cwd) {
|
|
4219
|
+
try {
|
|
4220
|
+
return execFileSync3("git", ["status", "--porcelain"], { cwd, encoding: "utf8" }).trim().length === 0;
|
|
4221
|
+
} catch {
|
|
4222
|
+
return true;
|
|
4223
|
+
}
|
|
4224
|
+
}
|
|
4225
|
+
function printPlan(plan) {
|
|
4226
|
+
console.log(`Target: ${plan.targetId}
|
|
4227
|
+
`);
|
|
4228
|
+
if (plan.planned.length) {
|
|
4229
|
+
console.log(`Patchable (${plan.planned.length}):`);
|
|
4230
|
+
for (const p of plan.planned) {
|
|
4231
|
+
console.log(
|
|
4232
|
+
` \u2713 ${p.attackId.padEnd(24)} ${p.recipe.id} [${p.verdictDetail}]` + (p.verdictPartial ? " (verdict gate partial)" : "")
|
|
4233
|
+
);
|
|
4234
|
+
}
|
|
4235
|
+
console.log();
|
|
4236
|
+
}
|
|
4237
|
+
if (plan.skipped.length) {
|
|
4238
|
+
console.log(`Not patchable (${plan.skipped.length}) \u2014 these become issues, not PRs:`);
|
|
4239
|
+
for (const s of plan.skipped) {
|
|
4240
|
+
console.log(` \xB7 ${s.attackId.padEnd(24)} ${s.reason}: ${s.detail}`);
|
|
4241
|
+
}
|
|
4242
|
+
console.log();
|
|
4243
|
+
}
|
|
4244
|
+
if (plan.blockedByAnchor.length) {
|
|
4245
|
+
console.log("Anchors that would unlock more recipes:");
|
|
4246
|
+
for (const b of plan.blockedByAnchor) {
|
|
4247
|
+
console.log(` codebase.anchors.${b.kind} \u2192 ${b.recipeIds.join(", ")}`);
|
|
4248
|
+
}
|
|
4249
|
+
console.log();
|
|
4250
|
+
}
|
|
4251
|
+
}
|
|
4252
|
+
function printDiff(changes) {
|
|
4253
|
+
for (const c2 of changes) {
|
|
4254
|
+
console.log(`
|
|
4255
|
+
--- a/${c2.path}
|
|
4256
|
+
+++ b/${c2.path}`);
|
|
4257
|
+
const before = c2.before.split("\n");
|
|
4258
|
+
const after = c2.after.split("\n");
|
|
4259
|
+
let head = 0;
|
|
4260
|
+
while (head < before.length && head < after.length && before[head] === after[head]) head++;
|
|
4261
|
+
let tail = 0;
|
|
4262
|
+
while (tail < before.length - head && tail < after.length - head && before[before.length - 1 - tail] === after[after.length - 1 - tail])
|
|
4263
|
+
tail++;
|
|
4264
|
+
for (const line of before.slice(head, before.length - tail)) console.log(`-${line}`);
|
|
4265
|
+
for (const line of after.slice(head, after.length - tail)) console.log(`+${line}`);
|
|
4266
|
+
}
|
|
4267
|
+
}
|
|
4268
|
+
async function fixCommand(opts) {
|
|
4269
|
+
const cwd = process.cwd();
|
|
4270
|
+
let config;
|
|
4271
|
+
try {
|
|
4272
|
+
config = loadConfig({ configPath: opts.config });
|
|
4273
|
+
} catch (e) {
|
|
4274
|
+
console.error(e instanceof ConfigError ? e.message : `Failed to load config: ${String(e)}`);
|
|
4275
|
+
setExitCode(2);
|
|
4276
|
+
return;
|
|
4277
|
+
}
|
|
4278
|
+
const codebase = config.codebase;
|
|
4279
|
+
if (!codebase) {
|
|
4280
|
+
console.error(
|
|
4281
|
+
'No `codebase` block in the config. `shield-llm fix` needs to know where your system prompt and renderer live.\n\nAdd e.g.:\n "codebase": { "root": ".", "language": "ts", "anchors": { "system_prompt": { "file": "src/ai/system-prompt.ts", "export": "SYSTEM_PROMPT_EFFECTIVE" } } }'
|
|
4282
|
+
);
|
|
4283
|
+
setExitCode(2);
|
|
4284
|
+
return;
|
|
4285
|
+
}
|
|
4286
|
+
let targetUrl;
|
|
4287
|
+
let findings;
|
|
4288
|
+
let beforeAttacks = [];
|
|
4289
|
+
try {
|
|
4290
|
+
if (opts.report) {
|
|
4291
|
+
const local = findingsFromLocalReport(resolve5(cwd, opts.report));
|
|
4292
|
+
targetUrl = local.targetUrl;
|
|
4293
|
+
findings = local.findings;
|
|
4294
|
+
beforeAttacks = local.allAttacks;
|
|
4295
|
+
} else {
|
|
4296
|
+
console.error(
|
|
4297
|
+
"Provide --report <shield-report.json>. (Dashboard mode via --scan lands with the claim API.)"
|
|
4298
|
+
);
|
|
4299
|
+
setExitCode(2);
|
|
4300
|
+
return;
|
|
4301
|
+
}
|
|
4302
|
+
} catch (e) {
|
|
4303
|
+
console.error(e instanceof Error ? e.message : String(e));
|
|
4304
|
+
setExitCode(2);
|
|
4305
|
+
return;
|
|
4306
|
+
}
|
|
4307
|
+
let plan;
|
|
4308
|
+
try {
|
|
4309
|
+
plan = buildPlan(findings, targetUrl, codebase, cwd, {
|
|
4310
|
+
minConfidence: opts.minConfidence,
|
|
4311
|
+
disagreementAvailable: findings.some((f) => f.disagreementResolution != null),
|
|
4312
|
+
knownSecrets: config.endpoint?.knownSecrets
|
|
4313
|
+
});
|
|
4314
|
+
} catch (e) {
|
|
4315
|
+
console.error(
|
|
4316
|
+
e instanceof AnchorError ? `Anchor error (${e.status}): ${e.message}` : e instanceof Error ? e.message : String(e)
|
|
4317
|
+
);
|
|
4318
|
+
setExitCode(2);
|
|
4319
|
+
return;
|
|
4320
|
+
}
|
|
4321
|
+
if (opts.json) {
|
|
4322
|
+
console.log(
|
|
4323
|
+
JSON.stringify(
|
|
4324
|
+
{
|
|
4325
|
+
targetId: plan.targetId,
|
|
4326
|
+
planned: plan.planned.map((p) => ({
|
|
4327
|
+
fingerprint: p.fingerprint,
|
|
4328
|
+
attackId: p.attackId,
|
|
4329
|
+
recipeId: p.recipe.id,
|
|
4330
|
+
layerReliability: layerReliability(p.recipe.remediationRef.layer)
|
|
4331
|
+
})),
|
|
4332
|
+
skipped: plan.skipped,
|
|
4333
|
+
blockedByAnchor: plan.blockedByAnchor
|
|
4334
|
+
},
|
|
4335
|
+
null,
|
|
4336
|
+
2
|
|
4337
|
+
)
|
|
4338
|
+
);
|
|
4339
|
+
return;
|
|
4340
|
+
}
|
|
4341
|
+
printPlan(plan);
|
|
4342
|
+
if (opts.explain) return;
|
|
4343
|
+
if (opts.revert) {
|
|
4344
|
+
for (const p of plan.planned) {
|
|
4345
|
+
const res = revertRecipe(p.recipe, {
|
|
4346
|
+
root: cwd,
|
|
4347
|
+
fingerprint: p.fingerprint,
|
|
4348
|
+
anchors: plan.anchors,
|
|
4349
|
+
dryRun: opts.dryRun
|
|
4350
|
+
});
|
|
4351
|
+
if (res.changes.length) console.log(`Reverted ${p.recipe.id}`);
|
|
4352
|
+
}
|
|
4353
|
+
return;
|
|
4354
|
+
}
|
|
4355
|
+
if (!opts.dryRun && !opts.allowDirty && !gitIsClean(cwd)) {
|
|
4356
|
+
console.error(
|
|
4357
|
+
"Working tree is dirty. `fix` writes into your files \u2014 commit or stash first, or pass --allow-dirty if you know what you are doing."
|
|
4358
|
+
);
|
|
4359
|
+
setExitCode(2);
|
|
4360
|
+
return;
|
|
4361
|
+
}
|
|
4362
|
+
if (!opts.dryRun && opts.openPr) {
|
|
4363
|
+
const dirtyCode = uncommittedCode(cwd);
|
|
4364
|
+
if (dirtyCode.length) {
|
|
4365
|
+
console.error(
|
|
4366
|
+
`\`--open-pr\` needs the source tree committed. Uncommitted code: ${dirtyCode.join(", ")}
|
|
4367
|
+
|
|
4368
|
+
Verification redeploys your WORKING TREE, so those files are part of what gets tested \u2014 while the PR would carry only the files the recipes wrote. A passing result would not be evidence about the branch.
|
|
4369
|
+
|
|
4370
|
+
Commit or stash them first. (Non-code changes are fine and are named in the PR body.)`
|
|
4371
|
+
);
|
|
4372
|
+
setExitCode(2);
|
|
4373
|
+
return;
|
|
4374
|
+
}
|
|
4375
|
+
}
|
|
4376
|
+
let benignBaseline;
|
|
4377
|
+
if (!opts.dryRun && plan.planned.length && opts.benignBaseline !== false) {
|
|
4378
|
+
const scope = plan.planned.some(
|
|
4379
|
+
(p) => p.recipe.verification.benignScope === "model-behaviour"
|
|
4380
|
+
) ? "model-behaviour" : "rendering";
|
|
4381
|
+
try {
|
|
4382
|
+
const target = buildTargetConfig(config);
|
|
4383
|
+
console.log(
|
|
4384
|
+
`Capturing the benign baseline (${BENIGN_CORE_V1.length} cases \xD7 2 runs) before patching\u2026`
|
|
4385
|
+
);
|
|
4386
|
+
const run1 = await captureBenign(target, BENIGN_CORE_V1);
|
|
4387
|
+
const run2 = await captureBenign(target, BENIGN_CORE_V1);
|
|
4388
|
+
benignBaseline = {
|
|
4389
|
+
suiteId: BENIGN_SUITE_ID,
|
|
4390
|
+
scope,
|
|
4391
|
+
run1: run1.map((c2) => ({ name: c2.name, hash: c2.hash })),
|
|
4392
|
+
run2: run2.map((c2) => ({ name: c2.name, hash: c2.hash }))
|
|
4393
|
+
};
|
|
4394
|
+
} catch (e) {
|
|
4395
|
+
console.warn(
|
|
4396
|
+
`\u26A0\uFE0F Could not capture the benign baseline (${e instanceof Error ? e.message : e}). Claims will record no baseline, and verification will refuse to confirm them.`
|
|
4397
|
+
);
|
|
4398
|
+
}
|
|
4399
|
+
}
|
|
4400
|
+
const touchedByFinding = /* @__PURE__ */ new Map();
|
|
4401
|
+
const collided = /* @__PURE__ */ new Set();
|
|
4402
|
+
for (const p of plan.planned) {
|
|
4403
|
+
try {
|
|
4404
|
+
const res = applyRecipe(p.recipe, {
|
|
4405
|
+
root: cwd,
|
|
4406
|
+
fingerprint: p.fingerprint,
|
|
4407
|
+
anchors: plan.anchors,
|
|
4408
|
+
dryRun: opts.dryRun
|
|
4409
|
+
});
|
|
4410
|
+
touchedByFinding.set(p.fingerprint, res.changes.map((c2) => c2.path));
|
|
4411
|
+
if (res.noop) {
|
|
4412
|
+
console.log(`${p.recipe.id}: already applied (no-op)`);
|
|
4413
|
+
continue;
|
|
4414
|
+
}
|
|
4415
|
+
console.log(
|
|
4416
|
+
`${p.recipe.id}: ${opts.dryRun ? "would touch" : "patched"} ${res.changes.map((c2) => c2.path).join(", ")}`
|
|
4417
|
+
);
|
|
4418
|
+
if (opts.dryRun) printDiff(res.changes);
|
|
4419
|
+
} catch (e) {
|
|
4420
|
+
if (e instanceof DriftError) {
|
|
4421
|
+
console.error(`
|
|
4422
|
+
${e.message}`);
|
|
4423
|
+
setExitCode(1);
|
|
4424
|
+
return;
|
|
4425
|
+
}
|
|
4426
|
+
if (e instanceof WrapCollisionError) {
|
|
4427
|
+
console.warn(`
|
|
4428
|
+
\u26A0\uFE0F ${p.attackId} skipped \u2014 ${e.message}`);
|
|
4429
|
+
plan.skipped.push({
|
|
4430
|
+
fingerprint: p.fingerprint,
|
|
4431
|
+
attackId: p.attackId,
|
|
4432
|
+
name: p.name,
|
|
4433
|
+
reason: "recipe_conflict",
|
|
4434
|
+
detail: e.message
|
|
4435
|
+
});
|
|
4436
|
+
collided.add(p.fingerprint);
|
|
4437
|
+
continue;
|
|
4438
|
+
}
|
|
4439
|
+
throw e;
|
|
4440
|
+
}
|
|
4441
|
+
}
|
|
4442
|
+
plan.planned = plan.planned.filter((p) => !collided.has(p.fingerprint));
|
|
4443
|
+
if (opts.dryRun || plan.planned.length === 0) return;
|
|
4444
|
+
let live = await liveVerificationPhase(plan, config, codebase, cwd, opts, benignBaseline);
|
|
4445
|
+
if (live === "aborted") return;
|
|
4446
|
+
if (opts.openPr) {
|
|
4447
|
+
const refined = await reverifyShippedSubset(
|
|
4448
|
+
plan,
|
|
4449
|
+
config,
|
|
4450
|
+
codebase,
|
|
4451
|
+
cwd,
|
|
4452
|
+
opts,
|
|
4453
|
+
benignBaseline,
|
|
4454
|
+
live
|
|
4455
|
+
);
|
|
4456
|
+
if (refined === "aborted") return;
|
|
4457
|
+
live = refined;
|
|
4458
|
+
}
|
|
4459
|
+
recordClaims(plan, cwd, benignBaseline, live);
|
|
4460
|
+
let rescanLines = [];
|
|
4461
|
+
if (opts.rescan && beforeAttacks.length) {
|
|
4462
|
+
const { evaluator } = resolveEvaluator(opts);
|
|
4463
|
+
console.log(`
|
|
4464
|
+
Re-scanning the ${beforeAttacks.length} attack(s) of the original scan\u2026`);
|
|
4465
|
+
const result = await rescanAndDiff({
|
|
4466
|
+
before: beforeAttacks,
|
|
4467
|
+
target: buildTargetConfig(config),
|
|
4468
|
+
catalogue: opts.attacks ?? MVP_ATTACKS,
|
|
4469
|
+
evaluator
|
|
4470
|
+
});
|
|
4471
|
+
if (result) {
|
|
4472
|
+
rescanLines = describeRescan(result);
|
|
4473
|
+
console.log(rescanLines.map((l) => ` ${l}`).join("\n"));
|
|
4474
|
+
} else {
|
|
4475
|
+
console.warn(" none of the original attacks are in the catalogue \u2014 no comparison possible");
|
|
4476
|
+
}
|
|
4477
|
+
}
|
|
4478
|
+
if (opts.openPr) {
|
|
4479
|
+
prPhase(plan, cwd, touchedByFinding, live, opts, rescanLines);
|
|
4480
|
+
return;
|
|
4481
|
+
}
|
|
4482
|
+
console.log("\n\u2500\u2500\u2500 PR body \u2500\u2500\u2500\n");
|
|
4483
|
+
console.log(renderPrBody(plan, live, [], rescanLines));
|
|
4484
|
+
}
|
|
4485
|
+
async function liveVerificationPhase(plan, config, codebase, cwd, opts, baseline) {
|
|
4486
|
+
const evidence = /* @__PURE__ */ new Map();
|
|
4487
|
+
if (!opts.verify && !opts.openPr) return evidence;
|
|
4488
|
+
if (!codebase.redeploy) {
|
|
4489
|
+
console.error(
|
|
4490
|
+
'\n--verify needs to make the patch live, and no redeploy command is configured.\n\nAdd to shield.config.json:\n "codebase": { \u2026, "redeploy": { "command": "docker compose up -d --build" } }\n\nThe command must start your target and RETURN (background long-running servers).\nWithout it the patch is on disk but the old code is still serving, so a replay would test the bug and not the fix.'
|
|
4491
|
+
);
|
|
4492
|
+
setExitCode(2);
|
|
4493
|
+
return "aborted";
|
|
4494
|
+
}
|
|
4495
|
+
const target = buildTargetConfig(config);
|
|
4496
|
+
const result = await redeploy(codebase.redeploy, target, cwd);
|
|
4497
|
+
if (!result.ok) {
|
|
4498
|
+
console.error(`
|
|
4499
|
+
Redeploy failed: ${result.detail}
|
|
4500
|
+
The patch is applied but UNVERIFIED.`);
|
|
4501
|
+
setExitCode(3);
|
|
4502
|
+
return "aborted";
|
|
4503
|
+
}
|
|
4504
|
+
console.log(`Redeployed in ${result.elapsedMs}ms \u2014 ${result.detail}`);
|
|
4505
|
+
const isolation = checkSessionIsolation(target);
|
|
4506
|
+
if (!isolation.isolated) console.warn(`
|
|
4507
|
+
\u26A0\uFE0F ${isolation.warning}
|
|
4508
|
+
`);
|
|
4509
|
+
const { evaluator, judgeAvailable } = resolveEvaluator(opts);
|
|
4510
|
+
const catalogue = opts.attacks ?? MVP_ATTACKS;
|
|
4511
|
+
console.log("\nReplaying each finding's design + holdout attacks against the live target\u2026\n");
|
|
4512
|
+
for (const p of plan.planned) {
|
|
4513
|
+
const v = await verifyLive({
|
|
4514
|
+
contract: p.recipe.verification,
|
|
4515
|
+
target,
|
|
4516
|
+
catalogue,
|
|
4517
|
+
evaluator,
|
|
4518
|
+
judgeAvailable,
|
|
4519
|
+
baseline,
|
|
4520
|
+
assumeBenignGreen: opts.assumeBenignGreen,
|
|
4521
|
+
redeployCommand: codebase.redeploy.command,
|
|
4522
|
+
nowMs: Date.now()
|
|
4523
|
+
});
|
|
4524
|
+
evidence.set(p.fingerprint, v);
|
|
4525
|
+
console.log(
|
|
4526
|
+
` ${v.passed ? "\u2713" : "\u2717"} ${p.attackId.padEnd(24)} ${describeLiveVerification(v)}`
|
|
4527
|
+
);
|
|
4528
|
+
}
|
|
4529
|
+
return evidence;
|
|
4530
|
+
}
|
|
4531
|
+
async function reverifyShippedSubset(plan, config, codebase, cwd, opts, baseline, live) {
|
|
4532
|
+
if (opts.allowUnverified) return live;
|
|
4533
|
+
const withheld = plan.planned.filter((p) => live.get(p.fingerprint)?.passed !== true);
|
|
4534
|
+
const shipping = plan.planned.filter((p) => live.get(p.fingerprint)?.passed === true);
|
|
4535
|
+
if (withheld.length === 0 || shipping.length === 0) return live;
|
|
4536
|
+
console.log(
|
|
4537
|
+
`
|
|
4538
|
+
Re-verifying the ${shipping.length} passing patch(es) ALONE \u2014 ${withheld.length} withheld patch(es) are being reverted first, so what gets verified is exactly what the PR will carry.`
|
|
4539
|
+
);
|
|
4540
|
+
for (const p of withheld) {
|
|
4541
|
+
revertRecipe(p.recipe, {
|
|
4542
|
+
root: cwd,
|
|
4543
|
+
fingerprint: p.fingerprint,
|
|
4544
|
+
anchors: plan.anchors
|
|
4545
|
+
});
|
|
4546
|
+
}
|
|
4547
|
+
const second = await liveVerificationPhase(
|
|
4548
|
+
{ ...plan, planned: shipping },
|
|
4549
|
+
config,
|
|
4550
|
+
codebase,
|
|
4551
|
+
cwd,
|
|
4552
|
+
opts,
|
|
4553
|
+
baseline
|
|
4554
|
+
);
|
|
4555
|
+
if (second === "aborted") return "aborted";
|
|
4556
|
+
const merged = new Map(live);
|
|
4557
|
+
for (const [fp, v] of second) merged.set(fp, v);
|
|
4558
|
+
const lost = shipping.filter((p) => merged.get(p.fingerprint)?.passed !== true);
|
|
4559
|
+
if (lost.length) {
|
|
4560
|
+
console.warn(
|
|
4561
|
+
`
|
|
4562
|
+
\u26A0\uFE0F ${lost.length} patch(es) passed alongside the others and FAILED on their own: ${lost.map((p) => p.attackId).join(", ")}. The first result was an artefact of the patches that are not shipping. Going with the second.`
|
|
4563
|
+
);
|
|
4564
|
+
}
|
|
4565
|
+
return merged;
|
|
4566
|
+
}
|
|
4567
|
+
function recordClaims(plan, cwd, baseline, live) {
|
|
4568
|
+
const store = ClaimStore.at(cwd);
|
|
4569
|
+
const noClosurePath = !closurePathConfigured(cwd);
|
|
4570
|
+
for (const p of plan.planned) {
|
|
4571
|
+
store.upsert(plan.targetId, {
|
|
4572
|
+
...createClaim({
|
|
4573
|
+
findingFingerprint: p.fingerprint,
|
|
4574
|
+
recipeId: p.recipe.id,
|
|
4575
|
+
contract: p.recipe.verification,
|
|
4576
|
+
nowMs: Date.now(),
|
|
4577
|
+
noClosurePathConfigured: noClosurePath
|
|
4578
|
+
}),
|
|
4579
|
+
benignBaseline: baseline,
|
|
4580
|
+
liveVerification: live.get(p.fingerprint)
|
|
4581
|
+
});
|
|
4582
|
+
}
|
|
4583
|
+
if (noClosurePath) {
|
|
4584
|
+
console.warn(
|
|
4585
|
+
"\n\u26A0\uFE0F No closure path is wired for this target: neither `shield-llm verify-claims` in a deploy workflow nor a scheduled scan. These findings will stay open indefinitely \u2014 the PR would promise a verification nothing can deliver."
|
|
4586
|
+
);
|
|
4587
|
+
}
|
|
4588
|
+
}
|
|
4589
|
+
function prPhase(plan, cwd, touchedByFinding, live, opts, rescanLines = []) {
|
|
4590
|
+
const verified = plan.planned.filter((p) => live.get(p.fingerprint)?.passed === true);
|
|
4591
|
+
const withheld = plan.planned.filter((p) => live.get(p.fingerprint)?.passed !== true);
|
|
4592
|
+
const shipping = opts.allowUnverified ? plan.planned : verified;
|
|
4593
|
+
const holding = opts.allowUnverified ? [] : withheld;
|
|
4594
|
+
for (const p of withheld) {
|
|
4595
|
+
const v = live.get(p.fingerprint);
|
|
4596
|
+
console.error(
|
|
4597
|
+
`
|
|
4598
|
+
\u2717 ${p.attackId} \u2014 ${v ? describeLiveVerification(v) : "no live verification ran"}`
|
|
4599
|
+
);
|
|
4600
|
+
}
|
|
4601
|
+
if (shipping.length === 0) {
|
|
4602
|
+
console.error(
|
|
4603
|
+
`
|
|
4604
|
+
No PR opened: none of the ${plan.planned.length} patch(es) could be verified.
|
|
4605
|
+
They stay on your working tree so you can inspect them. Fix the cause, or open the PR anyway with --allow-unverified (the body will say it is unverified).`
|
|
4606
|
+
);
|
|
4607
|
+
setExitCode(1);
|
|
4608
|
+
return;
|
|
4609
|
+
}
|
|
4610
|
+
const pathsOf = (list) => new Set(list.flatMap((p) => touchedByFinding.get(p.fingerprint) ?? []));
|
|
4611
|
+
const shippingPaths = pathsOf(shipping);
|
|
4612
|
+
const overlap = Array.from(pathsOf(holding)).filter((f) => shippingPaths.has(f));
|
|
4613
|
+
if (overlap.length) {
|
|
4614
|
+
console.error(
|
|
4615
|
+
`
|
|
4616
|
+
No PR opened. A verified and an unverified patch both changed ${overlap.join(", ")}, so they cannot be separated \u2014 committing that file would smuggle the unproven change into the PR. Re-run against one finding at a time, or use --allow-unverified.`
|
|
4617
|
+
);
|
|
4618
|
+
setExitCode(1);
|
|
4619
|
+
return;
|
|
4620
|
+
}
|
|
4621
|
+
if (holding.length) {
|
|
4622
|
+
console.warn(
|
|
4623
|
+
`
|
|
4624
|
+
\u26A0\uFE0F Opening a PR for the ${shipping.length} verified patch(es) only. ${holding.length} unverified patch(es) stay on your working tree, out of the PR.`
|
|
4625
|
+
);
|
|
4626
|
+
}
|
|
4627
|
+
if (opts.allowUnverified && withheld.length) {
|
|
4628
|
+
console.warn(
|
|
4629
|
+
`
|
|
4630
|
+
\u26A0\uFE0F --allow-unverified: including ${withheld.length} patch(es) nothing verified.`
|
|
4631
|
+
);
|
|
4632
|
+
}
|
|
4633
|
+
const shippedPlan = { ...plan, planned: shipping };
|
|
4634
|
+
const res = openPullRequest({
|
|
4635
|
+
cwd,
|
|
4636
|
+
plan: shippedPlan,
|
|
4637
|
+
touchedPaths: Array.from(shippingPaths),
|
|
4638
|
+
body: renderPrBody(shippedPlan, live, holding, rescanLines),
|
|
4639
|
+
live,
|
|
4640
|
+
branch: opts.prBranch,
|
|
4641
|
+
base: opts.prBase,
|
|
4642
|
+
push: opts.push !== false,
|
|
4643
|
+
draft: opts.draft
|
|
4644
|
+
});
|
|
4645
|
+
if (res.ok) {
|
|
4646
|
+
console.log(res.url ? `
|
|
4647
|
+
Pull request opened: ${res.url}` : `
|
|
4648
|
+
${res.detail}`);
|
|
4649
|
+
} else {
|
|
4650
|
+
console.error(`
|
|
4651
|
+
Could not open the PR: ${res.detail}`);
|
|
4652
|
+
setExitCode(1);
|
|
4653
|
+
}
|
|
4654
|
+
if (holding.length) setExitCode(1);
|
|
4655
|
+
}
|
|
4656
|
+
function closurePathConfigured(root) {
|
|
4657
|
+
const dir = resolve5(root, ".github/workflows");
|
|
4658
|
+
if (!existsSync6(dir)) return false;
|
|
4659
|
+
try {
|
|
4660
|
+
return readdirSync(dir).some(
|
|
4661
|
+
(f) => readFileSync6(resolve5(dir, f), "utf8").includes("verify-claims")
|
|
4662
|
+
);
|
|
4663
|
+
} catch {
|
|
4664
|
+
return false;
|
|
4665
|
+
}
|
|
4666
|
+
}
|
|
4667
|
+
function layerReliability(layer) {
|
|
4668
|
+
return layer === "architecture" ? "high" : layer === "system_prompt" ? "low" : "medium";
|
|
4669
|
+
}
|
|
4670
|
+
|
|
4671
|
+
// src/commands/verify-claims.ts
|
|
4672
|
+
var TERMINAL = /* @__PURE__ */ new Set(["confirmed", "confirmed_overfit", "expired"]);
|
|
4673
|
+
async function verifyClaimsCommand(opts) {
|
|
4674
|
+
const cwd = process.cwd();
|
|
4675
|
+
let config;
|
|
4676
|
+
try {
|
|
4677
|
+
config = loadConfig({ configPath: opts.config });
|
|
4678
|
+
} catch (e) {
|
|
4679
|
+
console.error(e instanceof ConfigError ? e.message : `Failed to load config: ${String(e)}`);
|
|
4680
|
+
setExitCode(2);
|
|
4681
|
+
return [];
|
|
4682
|
+
}
|
|
4683
|
+
const store = ClaimStore.at(cwd);
|
|
4684
|
+
const pending = store.openForVerification();
|
|
4685
|
+
if (pending.length === 0) {
|
|
4686
|
+
if (!opts.json) console.log("No remediation claims awaiting verification.");
|
|
4687
|
+
return [];
|
|
4688
|
+
}
|
|
4689
|
+
const target = buildTargetConfig(config);
|
|
4690
|
+
const catalogue = opts.attacks ?? MVP_ATTACKS;
|
|
4691
|
+
const evaluator = opts.evaluator ?? new RegexOnlyEvaluator();
|
|
4692
|
+
const now = opts.now ?? Date.now();
|
|
4693
|
+
const results = [];
|
|
4694
|
+
for (const claim of pending) {
|
|
4695
|
+
if (isExpired(claim, now)) {
|
|
4696
|
+
const expired = { ...claim, status: "expired", resolvedAt: new Date(now).toISOString() };
|
|
4697
|
+
store.replace(expired);
|
|
4698
|
+
results.push({
|
|
4699
|
+
fingerprint: claim.findingFingerprint,
|
|
4700
|
+
recipeId: claim.recipeId,
|
|
4701
|
+
status: "expired",
|
|
4702
|
+
reason: `no verification within the claim TTL (expired ${claim.expiresAt})`,
|
|
4703
|
+
stamped: false
|
|
4704
|
+
});
|
|
4705
|
+
continue;
|
|
4706
|
+
}
|
|
4707
|
+
const { verdicts, judgeDegraded } = await replayFamily(
|
|
4708
|
+
claim.contract,
|
|
4709
|
+
target,
|
|
4710
|
+
catalogue,
|
|
4711
|
+
evaluator
|
|
4712
|
+
);
|
|
4713
|
+
const benign = await runBenignGate({
|
|
4714
|
+
baseline: claim.benignBaseline,
|
|
4715
|
+
contract: claim.contract,
|
|
4716
|
+
target,
|
|
4717
|
+
evaluator: opts.evaluator,
|
|
4718
|
+
assumeGreen: opts.assumeBenignGreen
|
|
4719
|
+
});
|
|
4720
|
+
const outcome = resolveClaim({
|
|
4721
|
+
claim,
|
|
4722
|
+
verdicts,
|
|
4723
|
+
benignGreen: opts.benignGreen ?? benign.green,
|
|
4724
|
+
judgeDegraded,
|
|
4725
|
+
// Running THIS command from a deploy job is itself the deploy signal.
|
|
4726
|
+
trigger: "verify-claims",
|
|
4727
|
+
nowMs: now
|
|
4728
|
+
});
|
|
4729
|
+
const updated = {
|
|
4730
|
+
...claim,
|
|
4731
|
+
status: outcome.status,
|
|
4732
|
+
deployedAt: claim.deployedAt ?? opts.deployedAt ?? new Date(now).toISOString(),
|
|
4733
|
+
// Only a TERMINAL status closes a claim. `refuted_or_not_deployed` and
|
|
4734
|
+
// `inconclusive` stay open so a later run (after the actual deploy) can
|
|
4735
|
+
// still confirm them.
|
|
4736
|
+
closedBy: TERMINAL.has(outcome.status) ? "verify-claims" : void 0,
|
|
4737
|
+
resolvedAt: TERMINAL.has(outcome.status) ? new Date(now).toISOString() : void 0,
|
|
4738
|
+
notExecutedAttackIds: outcome.notExecutedAttackIds.length ? outcome.notExecutedAttackIds : void 0,
|
|
4739
|
+
benignBypassed: benign.detail.startsWith("BYPASSED") || void 0
|
|
4740
|
+
};
|
|
4741
|
+
store.replace(updated);
|
|
4742
|
+
results.push({
|
|
4743
|
+
fingerprint: claim.findingFingerprint,
|
|
4744
|
+
recipeId: claim.recipeId,
|
|
4745
|
+
status: outcome.status,
|
|
4746
|
+
reason: outcome.reason,
|
|
4747
|
+
stamped: mayStampFixed(outcome.status),
|
|
4748
|
+
benign: benign.detail
|
|
4749
|
+
});
|
|
4750
|
+
}
|
|
4751
|
+
if (opts.json || opts.ci) {
|
|
4752
|
+
console.log(JSON.stringify({ results }, null, 2));
|
|
4753
|
+
} else {
|
|
4754
|
+
for (const r of results) {
|
|
4755
|
+
const mark = r.status === "confirmed" ? "\u2713" : r.status === "pending" ? "\xB7" : "\u2717";
|
|
4756
|
+
console.log(`${mark} ${r.recipeId}
|
|
4757
|
+
${r.status}: ${r.reason}`);
|
|
4758
|
+
}
|
|
4759
|
+
}
|
|
4760
|
+
if (results.some(
|
|
4761
|
+
(r) => r.status === "refuted_or_not_deployed" || r.status === "confirmed_overfit"
|
|
4762
|
+
)) {
|
|
4763
|
+
setExitCode(1);
|
|
4764
|
+
}
|
|
4765
|
+
return results;
|
|
4766
|
+
}
|
|
4767
|
+
|
|
4768
|
+
// src/cli.ts
|
|
4769
|
+
function parseIntArg(value) {
|
|
4770
|
+
const n = Number.parseInt(value, 10);
|
|
4771
|
+
if (Number.isNaN(n)) {
|
|
4772
|
+
throw new InvalidArgumentError("Expected an integer.");
|
|
4773
|
+
}
|
|
4774
|
+
return n;
|
|
4775
|
+
}
|
|
4776
|
+
function parseFloatArg(value) {
|
|
4777
|
+
const n = Number.parseFloat(value);
|
|
4778
|
+
if (Number.isNaN(n)) {
|
|
4779
|
+
throw new InvalidArgumentError("Expected a number.");
|
|
4780
|
+
}
|
|
4781
|
+
return n;
|
|
4782
|
+
}
|
|
4783
|
+
function reportFatal(label, err) {
|
|
4784
|
+
console.error(`
|
|
4785
|
+
${label}:`);
|
|
4786
|
+
if (err instanceof Error) {
|
|
4787
|
+
console.error(err.stack ?? err.message);
|
|
4788
|
+
} else {
|
|
4789
|
+
console.error(String(err));
|
|
4790
|
+
}
|
|
4791
|
+
console.error(
|
|
4792
|
+
"\nThis is an unexpected error. Please rerun with the stack trace above attached if you report it."
|
|
4793
|
+
);
|
|
4794
|
+
process.exit(3);
|
|
4795
|
+
}
|
|
4796
|
+
function exitWithConfigError(err) {
|
|
4797
|
+
console.error(`Configuration error: ${err.message}`);
|
|
4798
|
+
process.exit(2);
|
|
4799
|
+
}
|
|
4800
|
+
process.on("unhandledRejection", (reason) => {
|
|
4801
|
+
if (reason instanceof ConfigError) exitWithConfigError(reason);
|
|
4802
|
+
reportFatal("Unhandled promise rejection", reason);
|
|
4803
|
+
});
|
|
4804
|
+
process.on("uncaughtException", (err) => {
|
|
4805
|
+
if (err instanceof ConfigError) exitWithConfigError(err);
|
|
4806
|
+
reportFatal("Uncaught exception", err);
|
|
4807
|
+
});
|
|
4808
|
+
var program = new Command();
|
|
4809
|
+
program.exitOverride();
|
|
4810
|
+
program.name("shield-llm").description("AI chatbot security scanner \u2014 automated red teaming for LLMs").version(version);
|
|
4811
|
+
program.command("scan").description("Run a security scan against a target chatbot").option("-c, --config <path>", "Path to shield.config.json").option("-e, --endpoint <url>", "Target chatbot HTTP endpoint URL").option("--auth <type>", "Auth type: bearer, api-key, oauth2").option("--token <value>", "Bearer token or API key value").option("--auth-header <name>", "Custom auth header name (for api-key auth)").option(
|
|
4812
|
+
"--response-field <path>",
|
|
4813
|
+
"Dot-notation path to response text in JSON (default: response)"
|
|
4814
|
+
).option(
|
|
4815
|
+
"--request-body <json>",
|
|
4816
|
+
"JSON request body template (use {{prompt}} placeholder)"
|
|
4817
|
+
).option(
|
|
4818
|
+
"--allow-private-urls",
|
|
4819
|
+
"Allow a localhost / private-IP target (local testing only; quick mode -e)"
|
|
4820
|
+
).option(
|
|
4821
|
+
"--preset <name>",
|
|
4822
|
+
"Scan preset (dev, quick, owasp, frontier, standard, full)"
|
|
4823
|
+
).option("--system-prompt <text>", "System prompt for target chatbot").option("--system-prompt-file <path>", "Path to system prompt file").option("--crescendo", "Include crescendo (multi-turn) attacks").option(
|
|
4824
|
+
"--concurrency <n>",
|
|
4825
|
+
"Max parallel single-turn attacks (AIMD backs off on throttling; default 4, set 1 for sequential)",
|
|
4826
|
+
parseIntArg
|
|
4827
|
+
).option(
|
|
4828
|
+
"--delay <ms>",
|
|
4829
|
+
"Base inter-request delay in ms (the adaptive pacing floor)",
|
|
4830
|
+
parseIntArg
|
|
4831
|
+
).option(
|
|
4832
|
+
"--max-delay <ms>",
|
|
4833
|
+
"Ceiling for the adaptive inter-request delay in ms (default 5000)",
|
|
4834
|
+
parseIntArg
|
|
4835
|
+
).option(
|
|
4836
|
+
"--retries <n>",
|
|
4837
|
+
"Max retries on a 429 / gateway 5xx before giving up an attack (default 3)",
|
|
4838
|
+
parseIntArg
|
|
4839
|
+
).option(
|
|
4840
|
+
"--max-floor-throttles <n>",
|
|
4841
|
+
"Consecutive throttles at the pacing floor before hard-stopping (default 3)",
|
|
4842
|
+
parseIntArg
|
|
4843
|
+
).option("--min-score <n>", "Minimum score threshold", parseFloat).option("--fail-on-critical", "Fail if any CRITICAL vulnerability found").option(
|
|
4844
|
+
"--no-fail-on-critical",
|
|
4845
|
+
"Report CRITICAL findings without failing the run"
|
|
4846
|
+
).option("-o, --output <format>", "Output format (json, markdown, sarif, pdf)").option("--output-file <path>", "Write report to file").option(
|
|
4847
|
+
"--write-json <path>",
|
|
4848
|
+
"Always write a parseable JSON copy here, regardless of --output (useful for CI to extract score/grade alongside SARIF)"
|
|
4849
|
+
).option(
|
|
4850
|
+
"--include-full-payloads",
|
|
4851
|
+
"Keep full chatbot responses / LLM reasoning in the on-disk JSON (default: truncate to protect against artifact leaks in public CI runs)"
|
|
4852
|
+
).option("--no-progress", "Disable progress spinner").option(
|
|
4853
|
+
"--ci",
|
|
4854
|
+
"CI mode: JSON to stdout, no spinner. Exit 0=pass, 1=threshold, 2=config/auth, 3=infra"
|
|
4855
|
+
).option(
|
|
4856
|
+
"--load-custom-tests",
|
|
4857
|
+
"Fetch custom tests from your Shield LLM dashboard"
|
|
4858
|
+
).option(
|
|
4859
|
+
"--custom-only",
|
|
4860
|
+
"Run ONLY custom tests \u2014 send no preset attack payloads to the target"
|
|
4861
|
+
).option("--eu-ai-act", "Show EU AI Act compliance assessment after scan").option(
|
|
4862
|
+
"--compliance-threshold <n>",
|
|
4863
|
+
"Minimum compliance score (0-100)",
|
|
4864
|
+
parseFloat
|
|
4865
|
+
).option(
|
|
4866
|
+
"--api-url <url>",
|
|
4867
|
+
"Backend API URL (overrides SHIELD_API_URL env var and stored credentials)"
|
|
4868
|
+
).option(
|
|
4869
|
+
"--consent",
|
|
4870
|
+
"After the scan, offer to contribute an anonymous aggregate to a benchmark cohort (interactive preview + explicit confirmation)"
|
|
4871
|
+
).option(
|
|
4872
|
+
"--no-resume",
|
|
4873
|
+
"Ignore any saved checkpoint and start fresh (the scan still checkpoints so it can resume if THIS run is interrupted)"
|
|
4874
|
+
).option(
|
|
4875
|
+
"--checkpoint-dir <path>",
|
|
4876
|
+
"Directory for resumable scan checkpoints (default: .shield-llm/checkpoints)"
|
|
4877
|
+
).action(scanCommand);
|
|
4878
|
+
var benchmark = program.command("benchmark").description("Cohort benchmarking \u2014 consent, submission, relative position");
|
|
4879
|
+
benchmark.command("cohorts").description("List your cohorts, or create one with --create").option(
|
|
4880
|
+
"--create <name>",
|
|
4881
|
+
"Create a cohort pinned to the current attack pack version"
|
|
4882
|
+
).option("--k-min <n>", "K-anonymity threshold for --create (default 5)").option("--api-url <url>", "Backend API URL override").action(cohortsCommand);
|
|
4883
|
+
var consent = benchmark.command("consent").description("Manage an organization's contribution consent");
|
|
4884
|
+
consent.command("show").description(
|
|
4885
|
+
"Preview the EXACT payload a submission would send (nothing is sent)"
|
|
4886
|
+
).requiredOption("--cohort <id>", "Cohort id").requiredOption("--target <id>", "Organization (target) id in the cohort").requiredOption("--scan <id>", "Scan id to build the preview from").option("--api-url <url>", "Backend API URL override").action(consentShowCommand);
|
|
4887
|
+
consent.command("grant").description("Record an organization's consent (append-only ledger)").requiredOption("--cohort <id>", "Cohort id").requiredOption("--target <id>", "Organization (target) id in the cohort").requiredOption(
|
|
4888
|
+
"--scope <scopes>",
|
|
4889
|
+
"Comma-separated: global_score,category_scores,segment_metadata"
|
|
4890
|
+
).requiredOption(
|
|
4891
|
+
"--by <identity>",
|
|
4892
|
+
"Identity/role with authority granting the consent"
|
|
4893
|
+
).option("--api-url <url>", "Backend API URL override").action(consentGrantCommand);
|
|
4894
|
+
consent.command("revoke").description("Revoke the organization's active consent").requiredOption("--cohort <id>", "Cohort id").requiredOption("--target <id>", "Organization (target) id in the cohort").option("--api-url <url>", "Backend API URL override").action(consentRevokeCommand);
|
|
4895
|
+
benchmark.command("submit").description(
|
|
4896
|
+
"Contribute a scan's anonymous aggregate (preview + confirmation)"
|
|
4897
|
+
).requiredOption("--cohort <id>", "Cohort id").requiredOption("--target <id>", "Organization (target) id in the cohort").requiredOption("--scan <id>", "Scan id to contribute").option("--yes", "Skip the interactive confirmation (CI use)").option("--api-url <url>", "Backend API URL override").action(submitCommand);
|
|
4898
|
+
benchmark.command("position").description(
|
|
4899
|
+
"Relative position of a score within the cohort (read-only; --offline for air-gapped)"
|
|
4900
|
+
).option("--cohort <id>", "Cohort id (online mode)").option("--scan <id>", "Scan id (with --target)").option("--target <id>", "Organization (target) id (with --scan)").option("--score <n>", "Explicit score 0-100 (with --segment-key)").option("--segment-key <key>", "Canonical segment key (with --score)").option("--offline", "Compute locally from a signed snapshot \u2014 no network").option("--snapshot <file>", "Snapshot file (offline mode)").option("--sig <file>", "Signature file (default: <snapshot>.sig)").option(
|
|
4901
|
+
"--public-key <pem>",
|
|
4902
|
+
"Issuer public key PEM, pinned out-of-band (offline mode, REQUIRED)"
|
|
2763
4903
|
).option("--api-url <url>", "Backend API URL override").action(positionCommand);
|
|
2764
4904
|
var snapshot = benchmark.command("snapshot").description("Signed distribution snapshots for air-gapped positioning");
|
|
2765
4905
|
snapshot.command("export").description(
|
|
@@ -2772,6 +4912,32 @@ program.command("tests").description("List custom tests (local config and/or rem
|
|
|
2772
4912
|
"--api-url <url>",
|
|
2773
4913
|
"Backend API URL (overrides SHIELD_API_URL env var)"
|
|
2774
4914
|
).action(testsCommand);
|
|
4915
|
+
program.command("fix").description(
|
|
4916
|
+
"Patch findings from a scan report using declarative remediation recipes"
|
|
4917
|
+
).option("-c, --config <path>", "Path to config file").option("--report <path>", "Scan report JSON (from `scan --write-json`)").option("--dry-run", "Print the diff, write nothing").option("--explain", "Show which recipes apply and which anchors would unlock more").option("--revert", "Remove every shield-llm block this recipe set owns").option("--min-confidence <n>", "Override the verdict-gate threshold", parseFloatArg).option("--allow-dirty", "Apply even if the git working tree is dirty").option("--json", "Machine-readable plan (implies --explain)").option("--no-benign-baseline", "Skip the pre-patch benign capture").option(
|
|
4918
|
+
"--verify",
|
|
4919
|
+
"Redeploy the target (codebase.redeploy) and replay each finding's design + holdout attacks against it"
|
|
4920
|
+
).option(
|
|
4921
|
+
"--open-pr",
|
|
4922
|
+
"Branch, commit, push and open a PR \u2014 only if every patch passed the live verification (implies --verify)"
|
|
4923
|
+
).option(
|
|
4924
|
+
"--allow-unverified",
|
|
4925
|
+
"Open the PR even though nothing verified the patch (the body says so)"
|
|
4926
|
+
).option("--pr-branch <name>", "Branch name (default: shield/fix-<hash of findings>)").option("--pr-base <name>", "PR base branch (default: the branch you are on)").option("--draft", "Open the PR as a draft").option("--no-push", "Commit locally and print the push / PR commands instead").option(
|
|
4927
|
+
"--assume-benign-green",
|
|
4928
|
+
"Confirm without running the benign gate when no judge is configured (recorded on the claim)"
|
|
4929
|
+
).option(
|
|
4930
|
+
"--rescan",
|
|
4931
|
+
"After verifying, replay the original scan's attacks and report the score delta over a frozen denominator (informational \u2014 the holdout replay stays the gate)"
|
|
4932
|
+
).action(fixCommand);
|
|
4933
|
+
program.command("verify-claims").description(
|
|
4934
|
+
"Replay the attack family of every pending remediation claim and close (or refuse to close) it"
|
|
4935
|
+
).option("-c, --config <path>", "Path to config file").option("--deployed-at <iso>", "Explicit deploy timestamp (implicit when run post-deploy)").option("--ci", "JSON output for pipelines").option(
|
|
4936
|
+
"--assume-benign-green",
|
|
4937
|
+
"Confirm without running the benign gate when no judge is configured (recorded on the claim)"
|
|
4938
|
+
).action(async (o) => {
|
|
4939
|
+
await verifyClaimsCommand(o);
|
|
4940
|
+
});
|
|
2775
4941
|
program.command("validate").description("Validate a shield.config.json file").option("-c, --config <path>", "Path to config file").action(validateCommand);
|
|
2776
4942
|
program.command("test-connection").description(
|
|
2777
4943
|
"Send one benign message to the configured chatbot and print its reply (config plumbing check, no scan)"
|