shield-llm 0.13.1 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -14,13 +14,19 @@ import {
14
14
  FRAMEWORK_LABELS,
15
15
  FileCheckpointStore,
16
16
  GUARDRAIL_PREFIX,
17
+ IMPORT_LIMITS,
18
+ IMPORT_SOURCES,
17
19
  JUDGE_OUTAGE_REASON_PREFIX,
18
20
  LAYER_META,
19
21
  MUTATORS,
22
+ McpHarness,
20
23
  NOT_EXECUTED_CATEGORIES,
24
+ ObservationsSchema,
21
25
  RECIPES,
22
26
  RateLimitError,
23
27
  RegexOnlyEvaluator,
28
+ SKIP_MCP_STALE_TOOLS,
29
+ SKIP_NO_MCP_AGENT,
24
30
  Scanner,
25
31
  VULN_TO_AGENTIC,
26
32
  analyzeJudgeHealth,
@@ -66,6 +72,7 @@ import {
66
72
  mayStampFixed,
67
73
  missingForContract,
68
74
  normalizeTargetUrl,
75
+ parseImportFile,
69
76
  parseMaxUnjudgedPercent,
70
77
  recordVerification,
71
78
  redactTargetUrl,
@@ -78,13 +85,37 @@ import {
78
85
  summarizeObfuscationVariants,
79
86
  version,
80
87
  withoutScoredApartVariants
81
- } from "./chunk-AONOLAQM.js";
88
+ } from "./chunk-M7VCMWRI.js";
82
89
 
83
90
  // src/load-env.ts
84
- try {
85
- process.loadEnvFile();
86
- } catch {
91
+ var PROTECTED_ENV_KEYS = [
92
+ "SHIELD_API_URL",
93
+ "SHIELD_LLM_HOME",
94
+ "NODE_TLS_REJECT_UNAUTHORIZED",
95
+ "NODE_EXTRA_CA_CERTS",
96
+ "NODE_OPTIONS"
97
+ ];
98
+ function loadProjectEnv(env = process.env, load = () => process.loadEnvFile(), warn = (msg) => process.stderr.write(msg)) {
99
+ const before = new Set(
100
+ PROTECTED_ENV_KEYS.filter((k) => env[k] !== void 0)
101
+ );
102
+ try {
103
+ load();
104
+ } catch {
105
+ }
106
+ const dropped = PROTECTED_ENV_KEYS.filter(
107
+ (k) => !before.has(k) && env[k] !== void 0
108
+ );
109
+ for (const key of dropped) {
110
+ delete env[key];
111
+ warn(
112
+ `Ignored ${key} from .env: it decides where your API key goes or how it is protected in transit, so it comes from --api-url, your shell environment or \`shield-llm login\`, never from a project file.
113
+ `
114
+ );
115
+ }
116
+ return dropped;
87
117
  }
118
+ loadProjectEnv();
88
119
 
89
120
  // src/cli.ts
90
121
  import { Command, CommanderError, InvalidArgumentError } from "commander";
@@ -213,6 +244,9 @@ async function reportIfSuspended(res, apiUrl) {
213
244
  async function fetchAttacks(args) {
214
245
  const params = new URLSearchParams({ preset: args.preset });
215
246
  if (args.includeMultiTurn) params.set("includeMultiTurn", "true");
247
+ if (args.capabilities?.length) {
248
+ params.set("capabilities", args.capabilities.join(","));
249
+ }
216
250
  const url = `${args.apiUrl}/api/cli/attacks?${params.toString()}`;
217
251
  let res;
218
252
  try {
@@ -1115,8 +1149,10 @@ function truncateResponse(text) {
1115
1149
  ${text.slice(-TAIL_CHARS)}`;
1116
1150
  }
1117
1151
  function truncateInput(input2) {
1152
+ const observations = input2.observations && ObservationsSchema.safeParse(input2.observations).success ? input2.observations : void 0;
1118
1153
  return {
1119
1154
  ...input2,
1155
+ observations,
1120
1156
  attackPrompt: replaceLoneSurrogates(input2.attackPrompt),
1121
1157
  response: replaceLoneSurrogates(truncateResponse(input2.response)),
1122
1158
  turns: input2.turns?.map((t) => ({
@@ -1873,15 +1909,490 @@ function safeHostname(url) {
1873
1909
  }
1874
1910
  }
1875
1911
 
1912
+ // src/commands/import.ts
1913
+ import { readFileSync as readFileSync3, statSync } from "fs";
1914
+
1915
+ // src/lib/supplements-client.ts
1916
+ import { createHash } from "crypto";
1917
+ var SupplementUploadError = class extends Error {
1918
+ constructor(message, exitCode) {
1919
+ super(message);
1920
+ this.exitCode = exitCode;
1921
+ }
1922
+ };
1923
+ function batchIdFor(content) {
1924
+ return createHash("sha256").update(content).digest("base64url").slice(0, 22);
1925
+ }
1926
+ var MAX_RETRIES_429 = 4;
1927
+ var REQUEST_TIMEOUT_MS = 18e4;
1928
+ function sleep(ms) {
1929
+ return new Promise((r) => setTimeout(r, ms));
1930
+ }
1931
+ async function postSupplementBatch(credentials, scanId, body) {
1932
+ const url = `${credentials.apiUrl}/api/cli/scans/${encodeURIComponent(scanId)}/supplements`;
1933
+ for (let attempt = 0; ; attempt++) {
1934
+ let res;
1935
+ try {
1936
+ res = await fetch(url, {
1937
+ method: "POST",
1938
+ headers: {
1939
+ "Content-Type": "application/json",
1940
+ Authorization: `Bearer ${credentials.apiKey}`
1941
+ },
1942
+ body: JSON.stringify(body),
1943
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
1944
+ });
1945
+ } catch (err) {
1946
+ const msg = err instanceof Error ? err.message : String(err);
1947
+ throw new SupplementUploadError(`Failed to reach backend: ${msg}`, 3);
1948
+ }
1949
+ if (await reportIfSuspended(res, credentials.apiUrl)) {
1950
+ throw new SupplementUploadError("Account suspended.", 2);
1951
+ }
1952
+ const inFlight = res.status === 409 && res.headers.get("retry-after") !== null && (await res.clone().json().catch(() => ({}))).code === "upload_in_flight";
1953
+ if ((res.status === 429 || inFlight) && attempt < MAX_RETRIES_429) {
1954
+ const retryAfter = Number(res.headers.get("retry-after") ?? "30");
1955
+ await res.text().catch(() => void 0);
1956
+ await sleep(Math.min(Math.max(retryAfter, 1), 120) * 1e3);
1957
+ continue;
1958
+ }
1959
+ if (res.ok) return await res.json();
1960
+ const text = await res.text().catch(() => "");
1961
+ let message = text.slice(0, 300);
1962
+ try {
1963
+ message = JSON.parse(text).error ?? message;
1964
+ } catch {
1965
+ }
1966
+ if (res.status === 401) {
1967
+ message = "API key is invalid or revoked. Run `shield-llm login` to re-authenticate.";
1968
+ } else if (res.status === 404) {
1969
+ message = `Scan "${scanId}" not found, or not completed, in your account.`;
1970
+ }
1971
+ throw new SupplementUploadError(
1972
+ `HTTP ${res.status}: ${message}`,
1973
+ res.status >= 500 || res.status === 429 ? 3 : 2
1974
+ );
1975
+ }
1976
+ }
1977
+ var MAX_BATCH_BYTES = 9e5;
1978
+ function chunkBySize(items, size, maxBytes = MAX_BATCH_BYTES) {
1979
+ const out = [];
1980
+ let current = [];
1981
+ let bytes = 0;
1982
+ for (const item of items) {
1983
+ const b = Buffer.byteLength(JSON.stringify(item));
1984
+ if (current.length > 0 && (current.length >= size || bytes + b > maxBytes)) {
1985
+ out.push(current);
1986
+ current = [];
1987
+ bytes = 0;
1988
+ }
1989
+ current.push(item);
1990
+ bytes += b;
1991
+ }
1992
+ if (current.length > 0) out.push(current);
1993
+ return out;
1994
+ }
1995
+
1996
+ // src/commands/import.ts
1997
+ var MAX_FILE_BYTES = 50 * 1024 * 1024;
1998
+ function summarizeImport(scanId, batch, results, totals) {
1999
+ const tool = new Map(
2000
+ batch.attempts.map((a) => [a.externalId, a.toolVerdict])
2001
+ );
2002
+ const count = (v) => results.filter((r) => r.verdict === v).length;
2003
+ return {
2004
+ scanId,
2005
+ source: batch.source,
2006
+ sourceVersion: batch.sourceVersion ?? null,
2007
+ attempts: batch.attempts.length,
2008
+ stored: totals.stored,
2009
+ duplicates: totals.duplicates,
2010
+ vulnerable: count("vulnerable"),
2011
+ safe: count("safe"),
2012
+ notJudged: count("not_judged"),
2013
+ missedByTool: results.filter(
2014
+ (r) => r.verdict === "vulnerable" && tool.get(r.itemKey) === "safe"
2015
+ ).length,
2016
+ refutedByJudge: results.filter(
2017
+ (r) => r.verdict === "safe" && tool.get(r.itemKey) === "vulnerable"
2018
+ ).length,
2019
+ skipped: batch.skipped
2020
+ };
2021
+ }
2022
+ function readResultFile(path) {
2023
+ const size = statSync(path).size;
2024
+ if (size > MAX_FILE_BYTES) {
2025
+ throw new Error(
2026
+ `File is ${Math.round(size / 1024 / 1024)} MB; the limit is ${MAX_FILE_BYTES / 1024 / 1024} MB.`
2027
+ );
2028
+ }
2029
+ return readFileSync3(path, "utf8");
2030
+ }
2031
+ function printHuman(o, apiUrl) {
2032
+ const version2 = o.sourceVersion ? ` ${o.sourceVersion.replace(/[\u0000-\u001f\u007f-\u009f]/g, "")}` : "";
2033
+ console.log("");
2034
+ console.log(
2035
+ `Imported ${o.attempts} attempt(s) from ${o.source}${version2} into scan ${o.scanId}.`
2036
+ );
2037
+ if (o.duplicates > 0) {
2038
+ console.log(` ${o.duplicates} were already imported and were skipped.`);
2039
+ }
2040
+ console.log(
2041
+ ` Judged by Shield: ${o.vulnerable} vulnerable, ${o.safe} safe, ${o.notJudged} not judged.`
2042
+ );
2043
+ if (o.missedByTool + o.refutedByJudge > 0) {
2044
+ console.log(
2045
+ ` Disagreements with ${o.source}: ${o.missedByTool} the tool called safe, ${o.refutedByJudge} the tool called vulnerable.`
2046
+ );
2047
+ }
2048
+ for (const s of o.skipped) {
2049
+ console.log(` Not imported: ${s.count} (${s.reason.replace(/_/g, " ")}).`);
2050
+ }
2051
+ console.log("");
2052
+ console.log(
2053
+ "These results are declared by you and kept apart from the score."
2054
+ );
2055
+ console.log(`Dashboard: ${apiUrl}/scans/${o.scanId}`);
2056
+ }
2057
+ async function uploadBatch(credentials, scanId, batch, batchId, showProgress) {
2058
+ const results = [];
2059
+ const totals = { stored: 0, duplicates: 0 };
2060
+ const chunks = chunkBySize(batch.attempts, IMPORT_LIMITS.batchSize);
2061
+ try {
2062
+ for (const [i, items] of chunks.entries()) {
2063
+ const res = await postSupplementBatch(credentials, scanId, {
2064
+ kind: "import",
2065
+ batchId,
2066
+ source: batch.source,
2067
+ ...batch.sourceVersion ? { sourceVersion: batch.sourceVersion.slice(0, 50) } : {},
2068
+ items
2069
+ });
2070
+ results.push(...res.results);
2071
+ totals.stored += res.stored;
2072
+ totals.duplicates += res.duplicates;
2073
+ if (showProgress) {
2074
+ process.stdout.write(`\r ${i + 1}/${chunks.length} batch(es) judged`);
2075
+ }
2076
+ }
2077
+ } catch (err) {
2078
+ if (showProgress) process.stdout.write("\n");
2079
+ console.error(
2080
+ `Import stopped: ${err instanceof Error ? err.message : String(err)}`
2081
+ );
2082
+ if (results.length > 0) {
2083
+ console.error(
2084
+ `${results.length} attempt(s) were stored before it stopped; re-run the same command to finish (stored ones are skipped).`
2085
+ );
2086
+ }
2087
+ setExitCode(err instanceof SupplementUploadError ? err.exitCode : 3);
2088
+ return null;
2089
+ }
2090
+ if (showProgress) process.stdout.write("\n");
2091
+ return { results, ...totals };
2092
+ }
2093
+ async function importCommand(file, opts) {
2094
+ const info = (msg) => {
2095
+ if (opts.ci) console.error(msg);
2096
+ else console.log(msg);
2097
+ };
2098
+ if (!opts.scan) {
2099
+ console.error(
2100
+ "Missing --scan <scanId>: the completed scan to attach the results to."
2101
+ );
2102
+ setExitCode(2);
2103
+ return;
2104
+ }
2105
+ if (opts.format && !IMPORT_SOURCES.includes(opts.format)) {
2106
+ console.error(
2107
+ `Unknown --format "${opts.format}". Supported: ${IMPORT_SOURCES.join(", ")}.`
2108
+ );
2109
+ setExitCode(2);
2110
+ return;
2111
+ }
2112
+ const stored = loadCredentials();
2113
+ if (!stored) {
2114
+ console.error("Not logged in. Run `shield-llm login` to authenticate.");
2115
+ setExitCode(2);
2116
+ return;
2117
+ }
2118
+ const credentials = {
2119
+ ...stored,
2120
+ apiUrl: resolveApiUrl(stored.apiUrl, opts.apiUrl)
2121
+ };
2122
+ let content;
2123
+ try {
2124
+ content = readResultFile(file);
2125
+ } catch (err) {
2126
+ console.error(
2127
+ `Cannot read ${file}: ${err instanceof Error ? err.message : String(err)}`
2128
+ );
2129
+ setExitCode(2);
2130
+ return;
2131
+ }
2132
+ const parsed = parseImportFile(
2133
+ content,
2134
+ opts.format
2135
+ );
2136
+ if (!parsed.ok) {
2137
+ console.error(parsed.error);
2138
+ setExitCode(2);
2139
+ return;
2140
+ }
2141
+ const { batch } = parsed;
2142
+ const batchId = batchIdFor(content);
2143
+ info(
2144
+ `Read ${batch.attempts.length} attempt(s) from a ${batch.source} file. Sending them to Shield's judge\u2026`
2145
+ );
2146
+ const uploaded = await uploadBatch(
2147
+ credentials,
2148
+ String(opts.scan),
2149
+ batch,
2150
+ batchId,
2151
+ !opts.ci && opts.progress !== false
2152
+ );
2153
+ if (!uploaded) return;
2154
+ const outcome = summarizeImport(
2155
+ String(opts.scan),
2156
+ batch,
2157
+ uploaded.results,
2158
+ uploaded
2159
+ );
2160
+ if (opts.ci) console.log(JSON.stringify(outcome, null, 2));
2161
+ else printHuman(outcome, credentials.apiUrl);
2162
+ setExitCode(0);
2163
+ }
2164
+
1876
2165
  // src/commands/scan.ts
1877
2166
  import { resolve as resolve5 } from "path";
1878
2167
 
2168
+ // src/lib/mcp-harness.ts
2169
+ var DEFAULT_MCP_HARNESS_PORT = 4300;
2170
+ function harnessPort(flags) {
2171
+ if (flags.mcpHarness === void 0 || flags.mcpHarness === false) return null;
2172
+ if (flags.mcpHarness === true) return DEFAULT_MCP_HARNESS_PORT;
2173
+ const port = Number(flags.mcpHarness);
2174
+ if (!Number.isInteger(port) || port < 0 || port > 65535) {
2175
+ throw new Error(
2176
+ `--mcp-harness expects a port between 0 and 65535, got "${flags.mcpHarness}"`
2177
+ );
2178
+ }
2179
+ return port;
2180
+ }
2181
+ async function startHarnessIfAsked(flags, log) {
2182
+ const port = harnessPort(flags);
2183
+ if (port === null) return void 0;
2184
+ const host = flags.mcpHost ?? "127.0.0.1";
2185
+ const harness = new McpHarness({ port, host });
2186
+ const url = await harness.start();
2187
+ log(
2188
+ `MCP harness listening at ${url}
2189
+ Connect the agent under test to this MCP server (Streamable HTTP), ALONE: detach its
2190
+ other MCP servers for the scan. The harness's tools are decoys that never read a file
2191
+ or call out, but the poisoned definitions ask the agent to use whatever tools it has.
2192
+ The agent must list the tools per conversation (the harness pushes no change).`
2193
+ );
2194
+ if (!["127.0.0.1", "localhost", "::1"].includes(host)) {
2195
+ log(
2196
+ ` Warning: bound to ${host}, reachable beyond this machine. The URL path is a
2197
+ per-scan secret; share it only with the agent's configuration.`
2198
+ );
2199
+ }
2200
+ return harness;
2201
+ }
2202
+ function harnessSkipWarning(results, harness) {
2203
+ if (!harness) return null;
2204
+ const count = (error) => results.filter((r) => r.error === error).length;
2205
+ const absent = count(SKIP_NO_MCP_AGENT);
2206
+ const stale = count(SKIP_MCP_STALE_TOOLS);
2207
+ const lines = [];
2208
+ if (absent > 0) {
2209
+ lines.push(
2210
+ `${absent} MCP attack(s) not run: the agent never contacted the harness at ${harness.url}. Check the agent's MCP server configuration, then run the same command again.`
2211
+ );
2212
+ }
2213
+ if (stale > 0) {
2214
+ lines.push(
2215
+ `${stale} MCP attack(s) not run: the agent acted on a tool list it kept from earlier instead of listing the harness tools again. Give it a fresh MCP session per conversation, then run the same command again.`
2216
+ );
2217
+ }
2218
+ return lines.length > 0 ? lines.join("\n") : null;
2219
+ }
2220
+
2221
+ // src/lib/pack-run.ts
2222
+ var PackRunError = class extends Error {
2223
+ constructor(message, exitCode) {
2224
+ super(message);
2225
+ this.exitCode = exitCode;
2226
+ }
2227
+ };
2228
+ async function fetchRenderedPacks(input2) {
2229
+ const { credentials } = input2;
2230
+ let res;
2231
+ try {
2232
+ res = await fetch(`${credentials.apiUrl}/api/cli/packs`, {
2233
+ method: "POST",
2234
+ headers: {
2235
+ "Content-Type": "application/json",
2236
+ Authorization: `Bearer ${credentials.apiKey}`
2237
+ },
2238
+ body: JSON.stringify({ packIds: input2.packIds, profile: input2.profile })
2239
+ });
2240
+ } catch (err) {
2241
+ throw new PackRunError(
2242
+ `Failed to reach backend: ${err instanceof Error ? err.message : String(err)}`,
2243
+ 3
2244
+ );
2245
+ }
2246
+ if (await reportIfSuspended(res, credentials.apiUrl)) {
2247
+ throw new PackRunError("Account suspended.", 2);
2248
+ }
2249
+ if (!res.ok) {
2250
+ const body = await res.json().catch(() => ({}));
2251
+ const available = body.available?.length ? ` Available: ${body.available.join(", ")}.` : "";
2252
+ throw new PackRunError(
2253
+ `${body.error ?? `HTTP ${res.status}`}.${available}`,
2254
+ res.status >= 500 ? 3 : 2
2255
+ );
2256
+ }
2257
+ return (await res.json()).packs;
2258
+ }
2259
+ async function askTarget(input2, prompt) {
2260
+ const client = createTargetClient(input2.target, input2.systemPrompt, {
2261
+ resolveEnv: true
2262
+ });
2263
+ try {
2264
+ return await client.sendMessage(prompt, {
2265
+ abortSignal: AbortSignal.timeout(input2.timeoutMs ?? 6e4)
2266
+ });
2267
+ } catch {
2268
+ return null;
2269
+ }
2270
+ }
2271
+ async function runOnePack(input2, pack) {
2272
+ const items = [];
2273
+ let notExecuted = 0;
2274
+ for (const c2 of pack.cases) {
2275
+ if (!c2.applicable || !c2.prompt) {
2276
+ items.push({ caseId: c2.caseId, turns: [] });
2277
+ continue;
2278
+ }
2279
+ const answer = await askTarget(input2, c2.prompt);
2280
+ if (answer === null) {
2281
+ notExecuted++;
2282
+ continue;
2283
+ }
2284
+ items.push({
2285
+ caseId: c2.caseId,
2286
+ turns: [
2287
+ {
2288
+ prompt: c2.prompt,
2289
+ response: answer.slice(0, IMPORT_LIMITS.maxResponseChars)
2290
+ }
2291
+ ]
2292
+ });
2293
+ }
2294
+ const batchId = batchIdFor(`${input2.scanId}:${pack.packId}:${pack.version}`);
2295
+ const results = [];
2296
+ for (const part of chunkBySize(items, IMPORT_LIMITS.batchSize)) {
2297
+ const res = await postSupplementBatch(input2.credentials, input2.scanId, {
2298
+ kind: "pack",
2299
+ batchId,
2300
+ packId: pack.packId,
2301
+ profile: input2.profile,
2302
+ items: part
2303
+ });
2304
+ results.push(...res.results);
2305
+ }
2306
+ const names = new Map(pack.cases.map((c2) => [c2.caseId, c2.name]));
2307
+ const count = (v) => results.filter((r) => r.verdict === v).length;
2308
+ return {
2309
+ packId: pack.packId,
2310
+ version: pack.version,
2311
+ title: pack.title,
2312
+ passed: count("safe"),
2313
+ failed: count("vulnerable"),
2314
+ notJudged: count("not_judged"),
2315
+ notApplicable: count("not_applicable"),
2316
+ notExecuted,
2317
+ failedCases: results.filter((r) => r.verdict === "vulnerable").map((r) => names.get(r.itemKey) ?? r.itemKey)
2318
+ };
2319
+ }
2320
+ async function runPacks(input2) {
2321
+ const packs = await fetchRenderedPacks(input2);
2322
+ const out = [];
2323
+ for (const pack of packs) out.push(await runOnePack(input2, pack));
2324
+ return out;
2325
+ }
2326
+ function formatPackSummary(s) {
2327
+ const lines = [
2328
+ ` Pack ${s.title} (${s.packId} ${s.version}): ${s.passed} passed, ${s.failed} failed` + (s.notJudged ? `, ${s.notJudged} not judged` : "") + (s.notApplicable ? `, ${s.notApplicable} not applicable (profile incomplete)` : "") + (s.notExecuted ? `, ${s.notExecuted} not executed (no answer)` : "") + "."
2329
+ ];
2330
+ for (const name of s.failedCases) lines.push(` \u2717 ${name}`);
2331
+ return lines;
2332
+ }
2333
+ async function checkPackIds(credentials, packIds) {
2334
+ let res;
2335
+ try {
2336
+ res = await fetch(`${credentials.apiUrl}/api/cli/packs`, {
2337
+ headers: { Authorization: `Bearer ${credentials.apiKey}` }
2338
+ });
2339
+ } catch (err) {
2340
+ return {
2341
+ ok: false,
2342
+ error: `Failed to reach backend to check --pack: ${err instanceof Error ? err.message : String(err)}`
2343
+ };
2344
+ }
2345
+ if (!res.ok) {
2346
+ await res.text().catch(() => void 0);
2347
+ return { ok: false, error: `Backend returned HTTP ${res.status} listing test packs.` };
2348
+ }
2349
+ const { packs } = await res.json();
2350
+ const published = packs.filter((p) => p.status === "published").map((p) => p.id);
2351
+ const drafts = new Set(packs.filter((p) => p.status !== "published").map((p) => p.id));
2352
+ const bad = packIds.filter((id) => !published.includes(id));
2353
+ if (bad.length === 0) return { ok: true };
2354
+ const why = bad.map((id) => drafts.has(id) ? `${id} (draft, not runnable yet)` : `${id} (unknown)`).join(", ");
2355
+ return {
2356
+ ok: false,
2357
+ error: `Cannot run test pack(s): ${why}. Available: ${published.join(", ") || "none"}.`
2358
+ };
2359
+ }
2360
+ async function runRequestedPacks(args) {
2361
+ if (args.packIds.length === 0) return [];
2362
+ if (!args.uploadedScanId) {
2363
+ const line = " Test packs not run: the scan was not saved to the dashboard.";
2364
+ args.info(line);
2365
+ return [line];
2366
+ }
2367
+ args.info(`Running test pack(s): ${args.packIds.join(", ")}\u2026`);
2368
+ try {
2369
+ const summaries = await runPacks({
2370
+ credentials: args.credentials,
2371
+ scanId: args.uploadedScanId,
2372
+ packIds: args.packIds,
2373
+ profile: args.profile,
2374
+ target: args.target,
2375
+ systemPrompt: args.systemPrompt
2376
+ });
2377
+ const lines = [
2378
+ " Test packs (kept apart from the score):",
2379
+ ...summaries.flatMap(formatPackSummary)
2380
+ ];
2381
+ if (args.ci) lines.forEach((l) => args.info(l));
2382
+ return lines;
2383
+ } catch (err) {
2384
+ const line = ` Test packs not run: ${err instanceof Error ? err.message : String(err)}`;
2385
+ args.info(line);
2386
+ return [line];
2387
+ }
2388
+ }
2389
+
1879
2390
  // src/reporters/evidence.ts
1880
2391
  import { writeFileSync as writeFileSync5 } from "fs";
1881
2392
  import { resolve as resolve3 } from "path";
1882
2393
 
1883
2394
  // ../../packages/shared/src/compliance/evidence-bundle.ts
1884
- import { createHash } from "crypto";
2395
+ import { createHash as createHash2 } from "crypto";
1885
2396
 
1886
2397
  // ../../packages/shared/src/compliance/remediation-validation.ts
1887
2398
  function claimScopeForScan(scan) {
@@ -1997,7 +2508,7 @@ function sortDeep(value) {
1997
2508
  return out;
1998
2509
  }
1999
2510
  function sha256Hex2(input2) {
2000
- return createHash("sha256").update(input2, "utf8").digest("hex");
2511
+ return createHash2("sha256").update(input2, "utf8").digest("hex");
2001
2512
  }
2002
2513
  function truncate2(text, spent) {
2003
2514
  if (typeof text !== "string" || text.length === 0) return {};
@@ -2027,7 +2538,7 @@ function bundleLimitations(classification, noScoredEvidence = false) {
2027
2538
  "The SHA-256 digest is a checksum over the bundle content. It detects alteration; it does not authenticate the issuer and is not a cryptographic signature.",
2028
2539
  "Article 50(1) disclosure rendered in a user interface (a banner, a chat header, an onboarding screen) is not observable from an HTTP-level scan and is neither tested nor scored here.",
2029
2540
  "Article 50(2) machine-readable marking of synthetic content is out of scope for this scan.",
2030
- "A non-compliance with observedBreach: false is a weakness scored against its article, not a breach of it, and never floors the status. A false human-authorship label on generated content is one: the Commission's Article 50 guidelines (C(2026) 5054, paragraph 131) place advertising text and a reply seen only by its user outside Article 50(4).",
2541
+ "A non-compliance with observedBreach: false is a weakness scored against its article, not a breach of it, and never floors the status. A false human-authorship label on generated content is one: the Commission's Article 50 guidelines (C(2026) 7702, paragraph 131) place advertising text and a reply seen only by its user outside Article 50(4).",
2031
2542
  "Organizational answers in the structural assessment are self-declared and carry no attached artefact.",
2032
2543
  "This bundle grants no Article 40 presumption of conformity: that presumption comes from conformity with a harmonised standard cited in the Official Journal, not from a test result. As of 30 October 2026 the only such standard is EN 18286:2026 on the quality management system (Commission Implementing Decision (EU) 2026/2274, OJ 14.10.2026), which this bundle does not assess."
2033
2544
  ];
@@ -2305,6 +2816,24 @@ function sanitizeReportForDisk(report, opts = {}) {
2305
2816
  if (attack.error) {
2306
2817
  sanitized.error = truncateString(attack.error, cfg.errorMaxChars);
2307
2818
  }
2819
+ const mcp = attack.observations?.mcp;
2820
+ if (mcp) {
2821
+ sanitized.observations = {
2822
+ ...attack.observations,
2823
+ mcp: {
2824
+ ...mcp,
2825
+ calls: mcp.calls.map((c2) => ({
2826
+ tool: c2.tool,
2827
+ arguments: Object.fromEntries(
2828
+ Object.entries(c2.arguments).map(([k, v]) => [
2829
+ k,
2830
+ JSON.stringify(v ?? "").includes(mcp.canary) ? "[redacted: carries the scan canary]" : "[redacted]"
2831
+ ])
2832
+ )
2833
+ }))
2834
+ }
2835
+ };
2836
+ }
2308
2837
  if (attack.llmEvaluation) {
2309
2838
  const ev = attack.llmEvaluation;
2310
2839
  sanitized.llmEvaluation = {
@@ -2609,6 +3138,7 @@ async function scanCommand(opts) {
2609
3138
  let reservedScanId = null;
2610
3139
  let scanFinalized = false;
2611
3140
  let failTarget = null;
3141
+ let harness;
2612
3142
  try {
2613
3143
  if (opts.ci) {
2614
3144
  opts.output = opts.output ?? "json";
@@ -2639,6 +3169,15 @@ async function scanCommand(opts) {
2639
3169
  configPath: opts.config,
2640
3170
  cliOverrides
2641
3171
  });
3172
+ const packIds = (opts.pack?.length ? opts.pack : config.packs) ?? [];
3173
+ if (packIds.length > 0) {
3174
+ const check = await checkPackIds(credentials, packIds);
3175
+ if (!check.ok) {
3176
+ console.error(check.error);
3177
+ setExitCode(2);
3178
+ return;
3179
+ }
3180
+ }
2642
3181
  if (opts.loadCustomTests) {
2643
3182
  try {
2644
3183
  const remoteTests = await fetchCustomTests(
@@ -2698,11 +3237,13 @@ async function scanCommand(opts) {
2698
3237
  `Custom-only mode: ${config.customTests.length} custom test(s), no preset attacks sent.`
2699
3238
  );
2700
3239
  } else {
3240
+ harness = await startHarnessIfAsked(opts, info);
2701
3241
  const fetched = await fetchAttacks({
2702
3242
  apiUrl: credentials.apiUrl,
2703
3243
  apiKey: credentials.apiKey,
2704
3244
  preset: presetForScan,
2705
- includeMultiTurn: includeCrescendo
3245
+ includeMultiTurn: includeCrescendo,
3246
+ ...harness && { capabilities: ["mcp-harness"] }
2706
3247
  });
2707
3248
  attacks = fetched.attacks;
2708
3249
  multiTurnAttacks = fetched.multiTurnAttacks;
@@ -2732,7 +3273,8 @@ async function scanCommand(opts) {
2732
3273
  if (!isolation.isolated) console.warn(`
2733
3274
  \u26A0\uFE0F ${isolation.warning}
2734
3275
  `);
2735
- if (includeCrescendo && (multiTurnAttacks?.length ?? 0) > 0) {
3276
+ const runMultiTurn = includeCrescendo || Boolean(harness) && (multiTurnAttacks?.length ?? 0) > 0;
3277
+ if (runMultiTurn && (multiTurnAttacks?.length ?? 0) > 0) {
2736
3278
  const conversation = checkConversationContext(target);
2737
3279
  if (!conversation.carried) {
2738
3280
  console.warn(`
@@ -2769,7 +3311,7 @@ async function scanCommand(opts) {
2769
3311
  preset: presetForScan,
2770
3312
  attacks,
2771
3313
  multiTurnAttacks,
2772
- includeCrescendo,
3314
+ includeCrescendo: runMultiTurn,
2773
3315
  customTests: config.customTests,
2774
3316
  // Adaptive concurrency: 4-way by default (AIMD backs off on 429s),
2775
3317
  // overridable via config.concurrency. Set 1 for strictly sequential.
@@ -2785,7 +3327,8 @@ async function scanCommand(opts) {
2785
3327
  maxUnjudgedPercent: config.maxUnjudgedPercent,
2786
3328
  maxNotExecutedPercent: config.maxNotExecutedPercent,
2787
3329
  checkpoint: checkpointStore,
2788
- evaluator
3330
+ evaluator,
3331
+ ...harness && { mcpHarness: harness }
2789
3332
  };
2790
3333
  const onEvent = opts.progress !== false ? handleEvent : void 0;
2791
3334
  reservedScanId = await reserveScanSlot(
@@ -2796,6 +3339,10 @@ async function scanCommand(opts) {
2796
3339
  info("Scan started");
2797
3340
  const scanner = new Scanner(scanOptions, onEvent);
2798
3341
  const report = await scanner.run();
3342
+ const harnessWarning = harnessSkipWarning(report.attacks, harness);
3343
+ if (harnessWarning) console.warn(`
3344
+ \u26A0\uFE0F ${harnessWarning}
3345
+ `);
2799
3346
  if (evaluator.accountSuspended) {
2800
3347
  console.error(accountSuspendedMessage(credentials.apiUrl));
2801
3348
  setExitCode(2);
@@ -2877,6 +3424,16 @@ async function scanCommand(opts) {
2877
3424
  }
2878
3425
  }
2879
3426
  }
3427
+ const packLines = await runRequestedPacks({
3428
+ packIds,
3429
+ uploadedScanId,
3430
+ credentials,
3431
+ profile: config.profile ?? {},
3432
+ target,
3433
+ systemPrompt,
3434
+ info,
3435
+ ci: Boolean(opts.ci)
3436
+ });
2880
3437
  let thresholdResult = evaluateThresholds(report, config.thresholds);
2881
3438
  const thresholdsConfigured = config.thresholds !== void 0 || opts.complianceThreshold !== void 0;
2882
3439
  let evidenceBundleNote = "";
@@ -2926,6 +3483,8 @@ async function scanCommand(opts) {
2926
3483
  console.log(formatComplianceTerminal(complianceResult, report.target));
2927
3484
  }
2928
3485
  if (evidenceBundleNote) console.log(evidenceBundleNote);
3486
+ if (packLines.length > 0) console.log(`${packLines.join("\n")}
3487
+ `);
2929
3488
  if (uploadedScanId) {
2930
3489
  console.log(
2931
3490
  ` Dashboard: ${credentials.apiUrl}/scans/${uploadedScanId}
@@ -3013,6 +3572,8 @@ async function scanCommand(opts) {
3013
3572
  console.error(`Runtime error: ${msg}`);
3014
3573
  setExitCode(3);
3015
3574
  return;
3575
+ } finally {
3576
+ await harness?.stop();
3016
3577
  }
3017
3578
  }
3018
3579
 
@@ -3320,12 +3881,12 @@ function validateCommand(opts) {
3320
3881
  }
3321
3882
 
3322
3883
  // src/commands/fix.ts
3323
- import { existsSync as existsSync6, readFileSync as readFileSync5, readdirSync } from "fs";
3884
+ import { existsSync as existsSync6, readFileSync as readFileSync6, readdirSync } from "fs";
3324
3885
  import { execFileSync as execFileSync3 } from "child_process";
3325
3886
  import { resolve as resolve7 } from "path";
3326
3887
 
3327
3888
  // src/fix/anchor-resolver.ts
3328
- import { existsSync as existsSync4, readFileSync as readFileSync3, statSync } from "fs";
3889
+ import { existsSync as existsSync4, readFileSync as readFileSync4, statSync as statSync2 } from "fs";
3329
3890
  import { isAbsolute, relative, resolve as resolve6, sep } from "path";
3330
3891
  var AnchorError = class extends Error {
3331
3892
  constructor(message, kind, status) {
@@ -3364,7 +3925,7 @@ function resolveAnchor(root, kind, anchor) {
3364
3925
  return { kind, status: "anchor_missing", configHint };
3365
3926
  }
3366
3927
  const abs = safeResolve(root, anchor.file);
3367
- if (!existsSync4(abs) || !statSync(abs).isFile()) {
3928
+ if (!existsSync4(abs) || !statSync2(abs).isFile()) {
3368
3929
  throw new AnchorError(
3369
3930
  `${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.`,
3370
3931
  kind,
@@ -3372,7 +3933,7 @@ function resolveAnchor(root, kind, anchor) {
3372
3933
  );
3373
3934
  }
3374
3935
  if (anchor.export) {
3375
- const source = readFileSync3(abs, "utf8");
3936
+ const source = readFileSync4(abs, "utf8");
3376
3937
  if (!declaresExport(source, anchor.export)) {
3377
3938
  throw new AnchorError(
3378
3939
  `${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.)`,
@@ -3610,7 +4171,7 @@ function blockedByAnchor(anchors) {
3610
4171
  import {
3611
4172
  existsSync as existsSync5,
3612
4173
  mkdirSync as mkdirSync4,
3613
- readFileSync as readFileSync4,
4174
+ readFileSync as readFileSync5,
3614
4175
  rmSync,
3615
4176
  writeFileSync as writeFileSync7
3616
4177
  } from "fs";
@@ -3781,7 +4342,7 @@ var WorkingSet = class {
3781
4342
  const cached = this.files.get(relPath);
3782
4343
  if (cached) return cached.current;
3783
4344
  const abs = safeResolve(this.root, relPath);
3784
- const before = existsSync5(abs) ? readFileSync4(abs, "utf8") : "";
4345
+ const before = existsSync5(abs) ? readFileSync5(abs, "utf8") : "";
3785
4346
  this.files.set(relPath, { before, current: before });
3786
4347
  return before;
3787
4348
  }
@@ -5437,7 +5998,7 @@ async function resolveCatalogue(opts) {
5437
5998
  return pending;
5438
5999
  }
5439
6000
  function findingsFromLocalReport(path) {
5440
- const parsed = JSON.parse(readFileSync5(path, "utf8"));
6001
+ const parsed = JSON.parse(readFileSync6(path, "utf8"));
5441
6002
  const r = parsed.report;
5442
6003
  if (!r?.attacks)
5443
6004
  throw new Error(`${path} is not a shield-llm --write-json report`);
@@ -6070,7 +6631,7 @@ function closurePathConfigured(root) {
6070
6631
  if (!existsSync6(dir)) return false;
6071
6632
  try {
6072
6633
  return readdirSync(dir).some(
6073
- (f) => readFileSync5(resolve7(dir, f), "utf8").includes("verify-claims")
6634
+ (f) => readFileSync6(resolve7(dir, f), "utf8").includes("verify-claims")
6074
6635
  );
6075
6636
  } catch {
6076
6637
  return false;
@@ -6337,6 +6898,12 @@ program.command("scan").description("Run a security scan against a target chatbo
6337
6898
  "--preset <name>",
6338
6899
  "Scan preset (dev, quick, owasp, frontier, standard, full)"
6339
6900
  ).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(
6901
+ "--mcp-harness [port]",
6902
+ "Start a decoy MCP server (default port 4300) for the agent under test to connect to, and run the MCP attacks through it: the verdict rests on the tool calls the agent makes. Its tools never read a file or call out."
6903
+ ).option(
6904
+ "--mcp-host <host>",
6905
+ "Interface the MCP harness binds to (default 127.0.0.1; 0.0.0.0 for an agent in a container)"
6906
+ ).option(
6340
6907
  "--mutate [ids]",
6341
6908
  "Also run invisible-carrier / obfuscation variants of each single-turn attack (multiplies coverage from the same payloads). Comma-separated mutator ids (e.g. zero_width,tag_chars,homoglyph,base64) or omit the value for all. `--mutate list` prints the available mutators and exits."
6342
6909
  ).option(
@@ -6385,6 +6952,11 @@ program.command("scan").description("Run a security scan against a target chatbo
6385
6952
  ).option(
6386
6953
  "--load-custom-tests",
6387
6954
  "Fetch custom tests from your Shield LLM dashboard"
6955
+ ).option(
6956
+ "--pack <id>",
6957
+ "After the scan, run this test pack (e.g. shield-brand) against the same target. Results are kept apart from the score. Repeatable.",
6958
+ (value, previous) => [...previous, value],
6959
+ []
6388
6960
  ).option(
6389
6961
  "--custom-only",
6390
6962
  "Run ONLY custom tests \u2014 send no preset attack payloads to the target"
@@ -6492,6 +7064,9 @@ program.command("probe-carriers").description(
6492
7064
  "Probe whether invisible-Unicode carriers survive the target's input pipeline (transport diagnostic, no scan/judge/upload)"
6493
7065
  ).option("-c, --config <path>", "Path to config file").option("--ci", "Emit JSON to stdout instead of the human-readable table").action(probeCarriersCommand);
6494
7066
  program.command("report <scanId>").description("Fetch a past scan report from your dashboard").option("-o, --output <format>", "Output format (json, markdown)", "json").option("--output-file <path>", "Write report to file").option("--api-url <url>", "Backend API URL override").action(reportCommand);
7067
+ program.command("import <file>").description(
7068
+ "Import a promptfoo or garak result file into a scan: Shield re-judges each attempt and shows the results apart from the score"
7069
+ ).option("--scan <scan-id>", "Completed scan to attach the results to").option("--format <tool>", "Force the reader: promptfoo or garak (default: detected)").option("--no-progress", "Disable the progress line").option("--ci", "CI mode: JSON summary to stdout").option("--api-url <url>", "Backend API URL override").action(importCommand);
6495
7070
  program.command("retest <scanId>").description(
6496
7071
  "Replay the detected findings of a past scan against the target and record which are fixed (verified) vs still vulnerable"
6497
7072
  ).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").option("--token <value>", "Bearer token or API key value").option("--auth-header <name>", "Custom auth header name (for api-key auth)").option(