shield-llm 0.3.1 → 0.5.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/README.md +49 -20
- package/dist/{chunk-UXBLUD2Y.js → chunk-AH5UVQFM.js} +1 -1
- package/dist/{chunk-WM5Z3SXV.js → chunk-I7M3BZK7.js} +5 -1
- package/dist/{chunk-NCPHRVFO.js → chunk-IB7T5OJ2.js} +2951 -271
- package/dist/cli.js +1209 -140
- package/dist/index.js +2 -2
- package/dist/logo.png +0 -0
- package/dist/{token-BYYUIFPC.js → token-4MGV4LR3.js} +2 -2
- package/dist/{token-util-S2RPFVDM.js → token-util-U5SGZSEU.js} +2 -2
- package/package.json +10 -5
- package/dist/report-template.hbs +0 -1726
package/dist/cli.js
CHANGED
|
@@ -1,11 +1,16 @@
|
|
|
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
|
+
CONSENT_SCOPES,
|
|
3
4
|
ConfigError,
|
|
4
5
|
ConfigSchema,
|
|
6
|
+
FileCheckpointStore,
|
|
5
7
|
Scanner,
|
|
6
8
|
analyzeJudgeHealth,
|
|
9
|
+
buildAuthFromFlags,
|
|
7
10
|
buildTargetConfig,
|
|
8
11
|
calculateComplianceScore,
|
|
12
|
+
computeCatalogHash,
|
|
13
|
+
computeScanKey,
|
|
9
14
|
createTargetClient,
|
|
10
15
|
deserializeAttack,
|
|
11
16
|
deserializeMultiTurnAttack,
|
|
@@ -16,14 +21,21 @@ import {
|
|
|
16
21
|
formatSarif,
|
|
17
22
|
generatePdf,
|
|
18
23
|
loadConfig,
|
|
19
|
-
loadSystemPrompt
|
|
20
|
-
|
|
21
|
-
|
|
24
|
+
loadSystemPrompt,
|
|
25
|
+
parseSegmentKey,
|
|
26
|
+
parseSnapshot,
|
|
27
|
+
resolveOfflinePosition,
|
|
28
|
+
summarizeAttackErrors
|
|
29
|
+
} from "./chunk-IB7T5OJ2.js";
|
|
30
|
+
import "./chunk-I7M3BZK7.js";
|
|
22
31
|
|
|
23
32
|
// src/cli.ts
|
|
24
33
|
import "dotenv/config";
|
|
25
34
|
import { Command, CommanderError } from "commander";
|
|
26
35
|
|
|
36
|
+
// package.json
|
|
37
|
+
var version = "0.5.0";
|
|
38
|
+
|
|
27
39
|
// src/credentials.ts
|
|
28
40
|
import {
|
|
29
41
|
readFileSync,
|
|
@@ -34,7 +46,6 @@ import {
|
|
|
34
46
|
} from "fs";
|
|
35
47
|
import { join } from "path";
|
|
36
48
|
import { homedir } from "os";
|
|
37
|
-
var DEFAULT_API_URL = "https://shield-llm.com";
|
|
38
49
|
function getConfigDir() {
|
|
39
50
|
const home = process.env.SHIELD_LLM_HOME ?? homedir();
|
|
40
51
|
return join(home, ".shield-llm");
|
|
@@ -51,15 +62,22 @@ function loadCredentials() {
|
|
|
51
62
|
if (!parsed.apiKey || typeof parsed.apiKey !== "string") return null;
|
|
52
63
|
return {
|
|
53
64
|
apiKey: parsed.apiKey,
|
|
54
|
-
|
|
65
|
+
// No public-SaaS default: Shield LLM is self-hosted, so a missing URL
|
|
66
|
+
// stays empty and resolveApiUrl() throws rather than guessing a host.
|
|
67
|
+
apiUrl: typeof parsed.apiUrl === "string" ? parsed.apiUrl : ""
|
|
55
68
|
};
|
|
56
69
|
} catch {
|
|
57
70
|
return null;
|
|
58
71
|
}
|
|
59
72
|
}
|
|
60
73
|
function resolveApiUrl(stored, override) {
|
|
61
|
-
const
|
|
62
|
-
|
|
74
|
+
const explicit = override ?? process.env.SHIELD_API_URL ?? stored;
|
|
75
|
+
if (explicit && explicit.trim()) {
|
|
76
|
+
return explicit.trim().replace(/\/+$/, "");
|
|
77
|
+
}
|
|
78
|
+
throw new ConfigError(
|
|
79
|
+
"No Shield LLM backend URL is configured. Point the CLI at your self-hosted instance via `--api-url`, the SHIELD_API_URL env var, or `shield-llm login --api-url <url> --key <key>`."
|
|
80
|
+
);
|
|
63
81
|
}
|
|
64
82
|
function saveCredentials(creds) {
|
|
65
83
|
const dir = getConfigDir();
|
|
@@ -107,15 +125,10 @@ async function fetchAttacks(args) {
|
|
|
107
125
|
"API key is invalid or revoked. Run `shield-llm login` to re-authenticate."
|
|
108
126
|
);
|
|
109
127
|
}
|
|
110
|
-
if (res.status === 403) {
|
|
111
|
-
const body = await res.json().catch(() => ({}));
|
|
112
|
-
throw new Error(
|
|
113
|
-
body.error ?? "Plan does not allow this preset. Upgrade required."
|
|
114
|
-
);
|
|
115
|
-
}
|
|
116
128
|
if (!res.ok) {
|
|
129
|
+
const body = await res.json().catch(() => ({}));
|
|
117
130
|
throw new Error(
|
|
118
|
-
`Backend returned HTTP ${res.status} fetching the attack catalogue.`
|
|
131
|
+
body.error ?? `Backend returned HTTP ${res.status} fetching the attack catalogue.`
|
|
119
132
|
);
|
|
120
133
|
}
|
|
121
134
|
try {
|
|
@@ -126,7 +139,10 @@ async function fetchAttacks(args) {
|
|
|
126
139
|
deserializeMultiTurnAttack
|
|
127
140
|
),
|
|
128
141
|
source: "backend",
|
|
129
|
-
catalogVersion: body.catalogVersion
|
|
142
|
+
catalogVersion: body.catalogVersion,
|
|
143
|
+
...body.attackPackVersion && {
|
|
144
|
+
attackPackVersion: body.attackPackVersion
|
|
145
|
+
}
|
|
130
146
|
};
|
|
131
147
|
} catch (err) {
|
|
132
148
|
const reason = err instanceof Error ? err.message : "Unknown error";
|
|
@@ -212,10 +228,472 @@ Attack catalogue \u2014 ${total} attack(s)${wanted ? ` (severity: ${wanted})` :
|
|
|
212
228
|
);
|
|
213
229
|
}
|
|
214
230
|
|
|
231
|
+
// src/commands/benchmark.ts
|
|
232
|
+
import { writeFileSync as writeFileSync2 } from "fs";
|
|
233
|
+
import { confirm, select } from "@inquirer/prompts";
|
|
234
|
+
|
|
235
|
+
// src/benchmark/api.ts
|
|
236
|
+
var BenchmarkApiError = class extends Error {
|
|
237
|
+
constructor(status, body) {
|
|
238
|
+
const detail = typeof body.message === "string" ? body.message : typeof body.error === "string" ? body.error : `HTTP ${status}`;
|
|
239
|
+
super(detail);
|
|
240
|
+
this.name = "BenchmarkApiError";
|
|
241
|
+
this.status = status;
|
|
242
|
+
this.body = body;
|
|
243
|
+
}
|
|
244
|
+
};
|
|
245
|
+
async function request(creds, method, path, body) {
|
|
246
|
+
let res;
|
|
247
|
+
try {
|
|
248
|
+
res = await fetch(`${creds.apiUrl}${path}`, {
|
|
249
|
+
method,
|
|
250
|
+
headers: {
|
|
251
|
+
Authorization: `Bearer ${creds.apiKey}`,
|
|
252
|
+
...body !== void 0 && { "Content-Type": "application/json" }
|
|
253
|
+
},
|
|
254
|
+
...body !== void 0 && { body: JSON.stringify(body) }
|
|
255
|
+
});
|
|
256
|
+
} catch (err) {
|
|
257
|
+
const reason = err instanceof Error ? err.message : "Unknown error";
|
|
258
|
+
throw new Error(
|
|
259
|
+
`Could not reach the Shield LLM backend at ${creds.apiUrl} (${reason}).`
|
|
260
|
+
);
|
|
261
|
+
}
|
|
262
|
+
const json = await res.json().catch(() => ({}));
|
|
263
|
+
if (!res.ok) {
|
|
264
|
+
if (res.status === 401) {
|
|
265
|
+
throw new BenchmarkApiError(401, {
|
|
266
|
+
error: "API key is invalid or revoked. Run `shield-llm login` to re-authenticate."
|
|
267
|
+
});
|
|
268
|
+
}
|
|
269
|
+
if (res.status === 404 && json.error === "Not found") {
|
|
270
|
+
throw new BenchmarkApiError(404, {
|
|
271
|
+
error: "Benchmark module is not enabled on this backend (NEXT_PUBLIC_MODULE_BENCHMARK)."
|
|
272
|
+
});
|
|
273
|
+
}
|
|
274
|
+
throw new BenchmarkApiError(res.status, json);
|
|
275
|
+
}
|
|
276
|
+
return json;
|
|
277
|
+
}
|
|
278
|
+
function listCohorts(creds) {
|
|
279
|
+
return request(
|
|
280
|
+
creds,
|
|
281
|
+
"GET",
|
|
282
|
+
"/api/benchmark/cohorts"
|
|
283
|
+
);
|
|
284
|
+
}
|
|
285
|
+
function createCohort(creds, args) {
|
|
286
|
+
return request(
|
|
287
|
+
creds,
|
|
288
|
+
"POST",
|
|
289
|
+
"/api/benchmark/cohorts",
|
|
290
|
+
args
|
|
291
|
+
);
|
|
292
|
+
}
|
|
293
|
+
function getCohort(creds, cohortId) {
|
|
294
|
+
return request(
|
|
295
|
+
creds,
|
|
296
|
+
"GET",
|
|
297
|
+
`/api/benchmark/cohorts/${encodeURIComponent(cohortId)}`
|
|
298
|
+
);
|
|
299
|
+
}
|
|
300
|
+
function grantConsent(creds, args) {
|
|
301
|
+
return request(
|
|
302
|
+
creds,
|
|
303
|
+
"POST",
|
|
304
|
+
`/api/benchmark/cohorts/${encodeURIComponent(args.cohortId)}/targets/${encodeURIComponent(args.targetId)}/consent`,
|
|
305
|
+
{ scopes: args.scopes, grantedBy: args.grantedBy }
|
|
306
|
+
);
|
|
307
|
+
}
|
|
308
|
+
function revokeConsent(creds, args) {
|
|
309
|
+
return request(
|
|
310
|
+
creds,
|
|
311
|
+
"DELETE",
|
|
312
|
+
`/api/benchmark/cohorts/${encodeURIComponent(args.cohortId)}/targets/${encodeURIComponent(args.targetId)}/consent`
|
|
313
|
+
);
|
|
314
|
+
}
|
|
315
|
+
function previewSubmission(creds, args) {
|
|
316
|
+
return request(
|
|
317
|
+
creds,
|
|
318
|
+
"POST",
|
|
319
|
+
`/api/benchmark/cohorts/${encodeURIComponent(args.cohortId)}/submissions/preview`,
|
|
320
|
+
{ scanId: args.scanId, targetId: args.targetId }
|
|
321
|
+
);
|
|
322
|
+
}
|
|
323
|
+
function submitAggregate(creds, args) {
|
|
324
|
+
return request(
|
|
325
|
+
creds,
|
|
326
|
+
"POST",
|
|
327
|
+
`/api/benchmark/cohorts/${encodeURIComponent(args.cohortId)}/submissions`,
|
|
328
|
+
{ scanId: args.scanId, targetId: args.targetId }
|
|
329
|
+
);
|
|
330
|
+
}
|
|
331
|
+
function exportSnapshot(creds, cohortId) {
|
|
332
|
+
return request(
|
|
333
|
+
creds,
|
|
334
|
+
"POST",
|
|
335
|
+
`/api/benchmark/cohorts/${encodeURIComponent(cohortId)}/snapshot`
|
|
336
|
+
);
|
|
337
|
+
}
|
|
338
|
+
function getPosition(creds, cohortId, query) {
|
|
339
|
+
const params = new URLSearchParams();
|
|
340
|
+
if ("scanId" in query) {
|
|
341
|
+
params.set("scanId", query.scanId);
|
|
342
|
+
params.set("targetId", query.targetId);
|
|
343
|
+
} else {
|
|
344
|
+
params.set("score", String(query.score));
|
|
345
|
+
params.set("segmentKey", query.segmentKey);
|
|
346
|
+
}
|
|
347
|
+
return request(
|
|
348
|
+
creds,
|
|
349
|
+
"GET",
|
|
350
|
+
`/api/benchmark/cohorts/${encodeURIComponent(cohortId)}/position?${params.toString()}`
|
|
351
|
+
);
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
// src/benchmark/format.ts
|
|
355
|
+
var LABELS = {
|
|
356
|
+
above_p75: "Reinforced posture (above the 3rd quartile)",
|
|
357
|
+
p25_p75: "Within cohort average",
|
|
358
|
+
below_p25: "Above-median exposure"
|
|
359
|
+
};
|
|
360
|
+
function ordinal(n) {
|
|
361
|
+
const rounded = Math.round(n);
|
|
362
|
+
const mod100 = rounded % 100;
|
|
363
|
+
if (mod100 >= 11 && mod100 <= 13) return `${rounded}th`;
|
|
364
|
+
switch (rounded % 10) {
|
|
365
|
+
case 1:
|
|
366
|
+
return `${rounded}st`;
|
|
367
|
+
case 2:
|
|
368
|
+
return `${rounded}nd`;
|
|
369
|
+
case 3:
|
|
370
|
+
return `${rounded}rd`;
|
|
371
|
+
default:
|
|
372
|
+
return `${rounded}th`;
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
function formatPosition(position, attackPackVersion) {
|
|
376
|
+
if (position.status === "insufficient_cohort") {
|
|
377
|
+
return `Benchmark building (N=${position.n}/${position.kMin}) \u2014 position unavailable below the k-anonymity threshold.`;
|
|
378
|
+
}
|
|
379
|
+
const percentile = position.clamped === "low" ? `\u2264 ${ordinal(position.percentile)} percentile` : position.clamped === "high" ? `\u2265 ${ordinal(position.percentile)} percentile` : `${ordinal(position.percentile)} percentile`;
|
|
380
|
+
const scope = position.generalizationLevel === 0 ? "exact segment" : position.segmentKey === "s1|*|*|*|*|*" ? "whole cohort" : `generalized segment ${position.segmentKey}`;
|
|
381
|
+
return [
|
|
382
|
+
`${percentile} \u2014 ${LABELS[position.labelKey] ?? position.labelKey}`,
|
|
383
|
+
`vs ${position.n} comparable organizations \xB7 ${scope} \xB7 attack pack v${attackPackVersion}`
|
|
384
|
+
].join("\n");
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
// src/benchmark/snapshot.ts
|
|
388
|
+
import { readFileSync as readFileSync2 } from "fs";
|
|
389
|
+
import { createPublicKey, verify } from "crypto";
|
|
390
|
+
function verifyAndLoadSnapshot(args) {
|
|
391
|
+
const bytes = readFileSync2(args.snapshotPath);
|
|
392
|
+
const signature = Buffer.from(
|
|
393
|
+
readFileSync2(args.signaturePath, "utf8").trim(),
|
|
394
|
+
"base64"
|
|
395
|
+
);
|
|
396
|
+
let publicKey;
|
|
397
|
+
try {
|
|
398
|
+
publicKey = createPublicKey(readFileSync2(args.publicKeyPath, "utf8"));
|
|
399
|
+
} catch (err) {
|
|
400
|
+
throw new Error(
|
|
401
|
+
`Could not load the public key at ${args.publicKeyPath}: ${err instanceof Error ? err.message : String(err)}`
|
|
402
|
+
);
|
|
403
|
+
}
|
|
404
|
+
if (publicKey.asymmetricKeyType !== "ed25519") {
|
|
405
|
+
throw new Error(
|
|
406
|
+
`Public key must be Ed25519 (got ${publicKey.asymmetricKeyType ?? "unknown"})`
|
|
407
|
+
);
|
|
408
|
+
}
|
|
409
|
+
const valid = verify(null, bytes, publicKey, signature);
|
|
410
|
+
if (!valid) {
|
|
411
|
+
throw new Error(
|
|
412
|
+
"Snapshot signature verification FAILED \u2014 refusing to compute a position. The snapshot or its signature was modified, or the public key does not match the issuing instance."
|
|
413
|
+
);
|
|
414
|
+
}
|
|
415
|
+
return parseSnapshot(JSON.parse(bytes.toString("utf8")));
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
// src/commands/benchmark.ts
|
|
419
|
+
function requireCreds(opts) {
|
|
420
|
+
const stored = loadCredentials();
|
|
421
|
+
if (!stored) {
|
|
422
|
+
console.error(
|
|
423
|
+
"Not authenticated. Run `shield-llm login --key <api-key>` first."
|
|
424
|
+
);
|
|
425
|
+
setExitCode(2);
|
|
426
|
+
return null;
|
|
427
|
+
}
|
|
428
|
+
return {
|
|
429
|
+
apiUrl: resolveApiUrl(stored.apiUrl, opts.apiUrl),
|
|
430
|
+
apiKey: stored.apiKey
|
|
431
|
+
};
|
|
432
|
+
}
|
|
433
|
+
function reportError(err) {
|
|
434
|
+
if (err instanceof BenchmarkApiError) {
|
|
435
|
+
console.error(`Error: ${err.message}`);
|
|
436
|
+
if (Array.isArray(err.body.reasons)) {
|
|
437
|
+
console.error(`Reasons: ${err.body.reasons.join(", ")}`);
|
|
438
|
+
}
|
|
439
|
+
if (Array.isArray(err.body.violations)) {
|
|
440
|
+
console.error(
|
|
441
|
+
`Violations: ${err.body.violations.join("; ")}`
|
|
442
|
+
);
|
|
443
|
+
}
|
|
444
|
+
setExitCode(2);
|
|
445
|
+
} else {
|
|
446
|
+
console.error(err instanceof Error ? err.message : String(err));
|
|
447
|
+
setExitCode(3);
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
function parseScopes(raw) {
|
|
451
|
+
const scopes = [];
|
|
452
|
+
for (const part of raw.split(",").map((s) => s.trim()).filter(Boolean)) {
|
|
453
|
+
const full = part.startsWith("contribute:") ? part : `contribute:${part}`;
|
|
454
|
+
if (!CONSENT_SCOPES.includes(full)) {
|
|
455
|
+
throw new Error(
|
|
456
|
+
`Unknown consent scope "${part}". Valid scopes: ` + CONSENT_SCOPES.map((s) => s.replace("contribute:", "")).join(", ")
|
|
457
|
+
);
|
|
458
|
+
}
|
|
459
|
+
scopes.push(full);
|
|
460
|
+
}
|
|
461
|
+
return scopes;
|
|
462
|
+
}
|
|
463
|
+
async function cohortsCommand(opts) {
|
|
464
|
+
const creds = requireCreds(opts);
|
|
465
|
+
if (!creds) return;
|
|
466
|
+
try {
|
|
467
|
+
if (opts.create) {
|
|
468
|
+
const created = await createCohort(creds, {
|
|
469
|
+
displayName: String(opts.create),
|
|
470
|
+
...opts.kMin !== void 0 && { kMin: Number(opts.kMin) }
|
|
471
|
+
});
|
|
472
|
+
console.log(
|
|
473
|
+
`Created cohort ${created.id} (attack pack v${created.activePackVersion}, k_min=${created.kMin})`
|
|
474
|
+
);
|
|
475
|
+
return;
|
|
476
|
+
}
|
|
477
|
+
const { cohorts } = await listCohorts(creds);
|
|
478
|
+
if (cohorts.length === 0) {
|
|
479
|
+
console.log(
|
|
480
|
+
"No cohorts yet. Create one with `shield-llm benchmark cohorts --create <name>`."
|
|
481
|
+
);
|
|
482
|
+
return;
|
|
483
|
+
}
|
|
484
|
+
for (const c of cohorts) {
|
|
485
|
+
console.log(
|
|
486
|
+
`${c.id} ${c.displayName} pack v${c.activePackVersion} k_min=${c.kMin} targets=${c.targetCount} submissions=${c.submissionCount}`
|
|
487
|
+
);
|
|
488
|
+
}
|
|
489
|
+
} catch (err) {
|
|
490
|
+
reportError(err);
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
async function consentShowCommand(opts) {
|
|
494
|
+
const creds = requireCreds(opts);
|
|
495
|
+
if (!creds) return;
|
|
496
|
+
try {
|
|
497
|
+
const preview = await previewSubmission(creds, {
|
|
498
|
+
cohortId: opts.cohort,
|
|
499
|
+
scanId: opts.scan,
|
|
500
|
+
targetId: opts.target
|
|
501
|
+
});
|
|
502
|
+
console.log("Exact payload that WOULD be submitted (nothing sent):");
|
|
503
|
+
console.log(JSON.stringify(preview.payload, null, 2));
|
|
504
|
+
if (preview.wouldReplace) {
|
|
505
|
+
console.log(
|
|
506
|
+
"Note: this would REPLACE the previous contribution of this organization for this attack pack version."
|
|
507
|
+
);
|
|
508
|
+
}
|
|
509
|
+
} catch (err) {
|
|
510
|
+
reportError(err);
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
async function consentGrantCommand(opts) {
|
|
514
|
+
const creds = requireCreds(opts);
|
|
515
|
+
if (!creds) return;
|
|
516
|
+
try {
|
|
517
|
+
const scopes = parseScopes(String(opts.scope ?? ""));
|
|
518
|
+
const granted = await grantConsent(creds, {
|
|
519
|
+
cohortId: opts.cohort,
|
|
520
|
+
targetId: opts.target,
|
|
521
|
+
scopes,
|
|
522
|
+
grantedBy: String(opts.by)
|
|
523
|
+
});
|
|
524
|
+
console.log(
|
|
525
|
+
`Consent recorded (${granted.id}) \u2014 scopes: ${granted.scopes.join(", ")}`
|
|
526
|
+
);
|
|
527
|
+
} catch (err) {
|
|
528
|
+
reportError(err);
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
async function consentRevokeCommand(opts) {
|
|
532
|
+
const creds = requireCreds(opts);
|
|
533
|
+
if (!creds) return;
|
|
534
|
+
try {
|
|
535
|
+
const result = await revokeConsent(creds, {
|
|
536
|
+
cohortId: opts.cohort,
|
|
537
|
+
targetId: opts.target
|
|
538
|
+
});
|
|
539
|
+
console.log(
|
|
540
|
+
result.revoked ? "Consent revoked. Future contributions are blocked until a new grant." : "No active consent to revoke."
|
|
541
|
+
);
|
|
542
|
+
} catch (err) {
|
|
543
|
+
reportError(err);
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
async function confirmAndSubmit(creds, args, opts = {}) {
|
|
547
|
+
const log = opts.log ?? console.log;
|
|
548
|
+
const preview = await previewSubmission(creds, args);
|
|
549
|
+
log("The following anonymous aggregate will be submitted to the cohort:");
|
|
550
|
+
log(JSON.stringify(preview.payload, null, 2));
|
|
551
|
+
if (preview.wouldReplace) {
|
|
552
|
+
log("This will REPLACE the organization's previous contribution.");
|
|
553
|
+
}
|
|
554
|
+
const approved = opts.yes === true ? true : await confirm({ message: "Submit this aggregate?", default: false });
|
|
555
|
+
if (!approved) {
|
|
556
|
+
log("Aborted \u2014 nothing was submitted. Your scan stays 100% local.");
|
|
557
|
+
return false;
|
|
558
|
+
}
|
|
559
|
+
const result = await submitAggregate(creds, args);
|
|
560
|
+
log(
|
|
561
|
+
result.replaced ? "Aggregate submitted (replaced the previous contribution)." : "Aggregate submitted."
|
|
562
|
+
);
|
|
563
|
+
return true;
|
|
564
|
+
}
|
|
565
|
+
async function submitCommand(opts) {
|
|
566
|
+
const creds = requireCreds(opts);
|
|
567
|
+
if (!creds) return;
|
|
568
|
+
try {
|
|
569
|
+
await confirmAndSubmit(
|
|
570
|
+
creds,
|
|
571
|
+
{ cohortId: opts.cohort, scanId: opts.scan, targetId: opts.target },
|
|
572
|
+
{ yes: Boolean(opts.yes) }
|
|
573
|
+
);
|
|
574
|
+
} catch (err) {
|
|
575
|
+
reportError(err);
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
async function positionCommand(opts) {
|
|
579
|
+
if (opts.offline || opts.snapshot) {
|
|
580
|
+
return offlinePositionCommand(opts);
|
|
581
|
+
}
|
|
582
|
+
const creds = requireCreds(opts);
|
|
583
|
+
if (!creds) return;
|
|
584
|
+
try {
|
|
585
|
+
const query = opts.scan && opts.target ? { scanId: String(opts.scan), targetId: String(opts.target) } : opts.score !== void 0 && opts.segmentKey ? { score: Number(opts.score), segmentKey: String(opts.segmentKey) } : null;
|
|
586
|
+
if (!query) {
|
|
587
|
+
console.error(
|
|
588
|
+
"Provide either --scan <id> --target <id>, or --score <n> --segment-key <key>."
|
|
589
|
+
);
|
|
590
|
+
setExitCode(2);
|
|
591
|
+
return;
|
|
592
|
+
}
|
|
593
|
+
const response = await getPosition(creds, opts.cohort, query);
|
|
594
|
+
if (response.scanEligibility && !response.scanEligibility.eligible) {
|
|
595
|
+
console.log(
|
|
596
|
+
`Warning: this scan is not benchmark-grade (${response.scanEligibility.reasons.join(", ")}) \u2014 position is indicative only.`
|
|
597
|
+
);
|
|
598
|
+
}
|
|
599
|
+
console.log(formatPosition(response.position, response.attackPackVersion));
|
|
600
|
+
} catch (err) {
|
|
601
|
+
reportError(err);
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
async function offlinePositionCommand(opts) {
|
|
605
|
+
try {
|
|
606
|
+
if (!opts.snapshot || !opts.publicKey) {
|
|
607
|
+
console.error(
|
|
608
|
+
"Offline mode requires --snapshot <file> and --public-key <pem> (pinned out-of-band)."
|
|
609
|
+
);
|
|
610
|
+
setExitCode(2);
|
|
611
|
+
return;
|
|
612
|
+
}
|
|
613
|
+
if (opts.score === void 0 || !opts.segmentKey) {
|
|
614
|
+
console.error(
|
|
615
|
+
"Offline mode requires --score <n> and --segment-key <key>."
|
|
616
|
+
);
|
|
617
|
+
setExitCode(2);
|
|
618
|
+
return;
|
|
619
|
+
}
|
|
620
|
+
const snapshot2 = verifyAndLoadSnapshot({
|
|
621
|
+
snapshotPath: String(opts.snapshot),
|
|
622
|
+
signaturePath: String(opts.sig ?? `${opts.snapshot}.sig`),
|
|
623
|
+
publicKeyPath: String(opts.publicKey)
|
|
624
|
+
});
|
|
625
|
+
console.log(
|
|
626
|
+
`Signature verified (Ed25519) \u2014 snapshot of ${snapshot2.computedAt}, attack pack v${snapshot2.attackPackVersion}.`
|
|
627
|
+
);
|
|
628
|
+
const position = resolveOfflinePosition(snapshot2, {
|
|
629
|
+
segment: parseSegmentKey(String(opts.segmentKey)),
|
|
630
|
+
score: Number(opts.score)
|
|
631
|
+
});
|
|
632
|
+
console.log(formatPosition(position, snapshot2.attackPackVersion));
|
|
633
|
+
} catch (err) {
|
|
634
|
+
console.error(err instanceof Error ? err.message : String(err));
|
|
635
|
+
setExitCode(2);
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
async function snapshotExportCommand(opts) {
|
|
639
|
+
const creds = requireCreds(opts);
|
|
640
|
+
if (!creds) return;
|
|
641
|
+
try {
|
|
642
|
+
const out = String(opts.out ?? "./snapshot.json");
|
|
643
|
+
const result = await exportSnapshot(creds, opts.cohort);
|
|
644
|
+
writeFileSync2(out, result.snapshotJson);
|
|
645
|
+
writeFileSync2(`${out}.sig`, result.signature + "\n");
|
|
646
|
+
writeFileSync2(`${out}.pub.pem`, result.publicKeyPem);
|
|
647
|
+
console.log(`Snapshot written: ${out} (+ .sig, + .pub.pem)`);
|
|
648
|
+
console.log(
|
|
649
|
+
"Distribute the public key through a separate, trusted channel and pin it on the verifying side."
|
|
650
|
+
);
|
|
651
|
+
} catch (err) {
|
|
652
|
+
reportError(err);
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
async function interactiveSubmitFlow(creds, scanId, log) {
|
|
656
|
+
try {
|
|
657
|
+
const { cohorts } = await listCohorts(creds);
|
|
658
|
+
if (cohorts.length === 0) {
|
|
659
|
+
log(
|
|
660
|
+
"Benchmark: no cohort on this backend \u2014 create one with `shield-llm benchmark cohorts --create <name>`."
|
|
661
|
+
);
|
|
662
|
+
return;
|
|
663
|
+
}
|
|
664
|
+
const cohortId = cohorts.length === 1 ? cohorts[0].id : await select({
|
|
665
|
+
message: "Cohort to contribute to:",
|
|
666
|
+
choices: cohorts.map((c) => ({
|
|
667
|
+
name: `${c.displayName} (pack v${c.activePackVersion})`,
|
|
668
|
+
value: c.id
|
|
669
|
+
}))
|
|
670
|
+
});
|
|
671
|
+
const detail = await getCohort(creds, cohortId);
|
|
672
|
+
if (detail.targets.length === 0) {
|
|
673
|
+
log(
|
|
674
|
+
"Benchmark: this cohort has no declared organizations yet \u2014 add targets in the dashboard or API first."
|
|
675
|
+
);
|
|
676
|
+
return;
|
|
677
|
+
}
|
|
678
|
+
const targetId = await select({
|
|
679
|
+
message: "Organization this scan belongs to:",
|
|
680
|
+
choices: detail.targets.map((t) => ({
|
|
681
|
+
name: `${t.displayName}${t.consent ? "" : " (no consent on record)"}`,
|
|
682
|
+
value: t.id
|
|
683
|
+
}))
|
|
684
|
+
});
|
|
685
|
+
await confirmAndSubmit(creds, { cohortId, scanId, targetId }, { log });
|
|
686
|
+
} catch (err) {
|
|
687
|
+
log(
|
|
688
|
+
`Benchmark submission skipped: ${err instanceof Error ? err.message : String(err)}`
|
|
689
|
+
);
|
|
690
|
+
}
|
|
691
|
+
}
|
|
692
|
+
|
|
215
693
|
// src/commands/init.ts
|
|
216
|
-
import { existsSync as existsSync2, writeFileSync as
|
|
694
|
+
import { existsSync as existsSync2, writeFileSync as writeFileSync3 } from "fs";
|
|
217
695
|
import { resolve } from "path";
|
|
218
|
-
import { select, input, confirm } from "@inquirer/prompts";
|
|
696
|
+
import { select as select2, input, confirm as confirm2 } from "@inquirer/prompts";
|
|
219
697
|
var CONFIG_FILENAME = "shield.config.json";
|
|
220
698
|
async function initCommand() {
|
|
221
699
|
console.log("\nShield LLM \u2014 Configuration wizard\n");
|
|
@@ -228,7 +706,7 @@ async function initCommand() {
|
|
|
228
706
|
}
|
|
229
707
|
const configPath = resolve(CONFIG_FILENAME);
|
|
230
708
|
if (existsSync2(configPath)) {
|
|
231
|
-
const overwrite = await
|
|
709
|
+
const overwrite = await confirm2({
|
|
232
710
|
message: `${CONFIG_FILENAME} already exists. Overwrite?`,
|
|
233
711
|
default: false
|
|
234
712
|
});
|
|
@@ -248,7 +726,7 @@ async function initCommand() {
|
|
|
248
726
|
}
|
|
249
727
|
}
|
|
250
728
|
});
|
|
251
|
-
const method = await
|
|
729
|
+
const method = await select2({
|
|
252
730
|
message: "HTTP method:",
|
|
253
731
|
choices: [
|
|
254
732
|
{ value: "POST", name: "POST (most chatbots)" },
|
|
@@ -260,7 +738,7 @@ async function initCommand() {
|
|
|
260
738
|
const auth = await collectAuth();
|
|
261
739
|
const { body, responseField } = await collectBodyShape();
|
|
262
740
|
const customHeaders = await collectCustomHeaders();
|
|
263
|
-
const preset = await
|
|
741
|
+
const preset = await select2({
|
|
264
742
|
message: "Default scan preset:",
|
|
265
743
|
choices: [
|
|
266
744
|
{ value: "owasp", name: "owasp \u2014 OWASP LLM Top 10 (10 tests)" },
|
|
@@ -295,12 +773,12 @@ async function initCommand() {
|
|
|
295
773
|
Generated config is invalid:
|
|
296
774
|
${issues}`);
|
|
297
775
|
console.error(
|
|
298
|
-
"This is a bug \u2014 please report it at https://
|
|
776
|
+
"This is a bug \u2014 please report it at https://shield-llm.com/contact"
|
|
299
777
|
);
|
|
300
778
|
setExitCode(3);
|
|
301
779
|
return;
|
|
302
780
|
}
|
|
303
|
-
|
|
781
|
+
writeFileSync3(configPath, JSON.stringify(result.data, null, 2) + "\n");
|
|
304
782
|
console.log(`
|
|
305
783
|
\u2713 Config written to ${CONFIG_FILENAME}
|
|
306
784
|
`);
|
|
@@ -313,7 +791,7 @@ ${issues}`);
|
|
|
313
791
|
console.log("");
|
|
314
792
|
}
|
|
315
793
|
async function collectAuth() {
|
|
316
|
-
const authType = await
|
|
794
|
+
const authType = await select2({
|
|
317
795
|
message: "How does your endpoint authenticate?",
|
|
318
796
|
choices: [
|
|
319
797
|
{ value: "none", name: "No authentication" },
|
|
@@ -364,7 +842,7 @@ async function collectAuth() {
|
|
|
364
842
|
return { type: "oauth2", clientId, clientSecret, tokenUrl };
|
|
365
843
|
}
|
|
366
844
|
async function collectBodyShape() {
|
|
367
|
-
const shape = await
|
|
845
|
+
const shape = await select2({
|
|
368
846
|
message: "Request body shape:",
|
|
369
847
|
choices: [
|
|
370
848
|
{
|
|
@@ -390,7 +868,7 @@ async function collectBodyShape() {
|
|
|
390
868
|
default: "message"
|
|
391
869
|
});
|
|
392
870
|
const body = { [promptField]: "{{prompt}}" };
|
|
393
|
-
const addExtra = await
|
|
871
|
+
const addExtra = await confirm2({
|
|
394
872
|
message: "Add extra fixed fields to the request body (assistant_id, thread_id, ...) ?",
|
|
395
873
|
default: false
|
|
396
874
|
});
|
|
@@ -405,7 +883,7 @@ async function collectBodyShape() {
|
|
|
405
883
|
message: `Value for "${key}":`
|
|
406
884
|
});
|
|
407
885
|
body[key] = value;
|
|
408
|
-
more = await
|
|
886
|
+
more = await confirm2({ message: "Another field?", default: false });
|
|
409
887
|
}
|
|
410
888
|
}
|
|
411
889
|
const responseField = await input({
|
|
@@ -415,7 +893,7 @@ async function collectBodyShape() {
|
|
|
415
893
|
return { body, responseField };
|
|
416
894
|
}
|
|
417
895
|
async function collectCustomHeaders() {
|
|
418
|
-
const add = await
|
|
896
|
+
const add = await confirm2({
|
|
419
897
|
message: "Add custom request headers?",
|
|
420
898
|
default: false
|
|
421
899
|
});
|
|
@@ -432,7 +910,7 @@ async function collectCustomHeaders() {
|
|
|
432
910
|
});
|
|
433
911
|
warnIfHardcodedSecret(value);
|
|
434
912
|
headers[name] = value;
|
|
435
|
-
more = await
|
|
913
|
+
more = await confirm2({ message: "Another header?", default: false });
|
|
436
914
|
}
|
|
437
915
|
return headers;
|
|
438
916
|
}
|
|
@@ -457,9 +935,8 @@ async function loginCommand(opts) {
|
|
|
457
935
|
console.log(`Credentials saved to ${getCredentialsPath()}`);
|
|
458
936
|
try {
|
|
459
937
|
const res = await fetch(`${apiUrl}/api/cli/scans`, {
|
|
460
|
-
method: "
|
|
938
|
+
method: "GET",
|
|
461
939
|
headers: {
|
|
462
|
-
"Content-Type": "application/json",
|
|
463
940
|
Authorization: `Bearer ${key}`
|
|
464
941
|
}
|
|
465
942
|
});
|
|
@@ -468,10 +945,7 @@ async function loginCommand(opts) {
|
|
|
468
945
|
"Warning: API key appears to be invalid. Check your key and try again."
|
|
469
946
|
);
|
|
470
947
|
} else if (res.ok) {
|
|
471
|
-
|
|
472
|
-
console.log(
|
|
473
|
-
`Authenticated to ${apiUrl}! Plan: ${data.plan} (${data.remaining}/${data.limit} scans remaining)`
|
|
474
|
-
);
|
|
948
|
+
console.log(`Authenticated to ${apiUrl}!`);
|
|
475
949
|
}
|
|
476
950
|
} catch {
|
|
477
951
|
console.log(
|
|
@@ -524,20 +998,31 @@ async function presetsCommand(opts) {
|
|
|
524
998
|
}
|
|
525
999
|
console.log("\nAvailable presets:\n");
|
|
526
1000
|
for (const preset of presets) {
|
|
527
|
-
const lock = preset.allowed ? "" : " (upgrade required)";
|
|
528
1001
|
console.log(
|
|
529
|
-
` ${preset.id.padEnd(12)} ${preset.name.padEnd(20)} ${preset.description}
|
|
1002
|
+
` ${preset.id.padEnd(12)} ${preset.name.padEnd(20)} ${preset.description}`
|
|
530
1003
|
);
|
|
531
1004
|
}
|
|
532
1005
|
console.log("");
|
|
533
1006
|
}
|
|
534
1007
|
|
|
535
1008
|
// src/commands/report.ts
|
|
536
|
-
import { writeFileSync as
|
|
1009
|
+
import { writeFileSync as writeFileSync4 } from "fs";
|
|
537
1010
|
import { resolve as resolve2 } from "path";
|
|
1011
|
+
function verificationLabel(v) {
|
|
1012
|
+
if (v.verificationStatus === "fixed") {
|
|
1013
|
+
return `\u2713 Fixed & verified${v.verifiedAt ? ` (${v.verifiedAt.slice(0, 10)})` : ""}`;
|
|
1014
|
+
}
|
|
1015
|
+
if (v.verificationStatus === "still_vulnerable") {
|
|
1016
|
+
return `\u2717 Still vulnerable${v.verifiedAt ? ` (${v.verifiedAt.slice(0, 10)})` : ""}`;
|
|
1017
|
+
}
|
|
1018
|
+
return "\u2014";
|
|
1019
|
+
}
|
|
538
1020
|
function renderScanMarkdown(scan) {
|
|
539
1021
|
const detected = scan.vulns.filter((v) => v.status === "DETECTED");
|
|
540
1022
|
const passed = scan.vulns.length - detected.length;
|
|
1023
|
+
const verifiedFixed = detected.filter(
|
|
1024
|
+
(v) => v.verificationStatus === "fixed"
|
|
1025
|
+
).length;
|
|
541
1026
|
const lines = [
|
|
542
1027
|
`# Shield LLM scan ${scan.id}`,
|
|
543
1028
|
"",
|
|
@@ -545,6 +1030,9 @@ function renderScanMarkdown(scan) {
|
|
|
545
1030
|
`- Score: **${scan.score}** (${scan.grade})`,
|
|
546
1031
|
`- Date: ${scan.createdAt}`,
|
|
547
1032
|
`- Tests: ${scan.testsRun}/${scan.testsTotal} run, ${detected.length} vulnerable, ${passed} secure`,
|
|
1033
|
+
...verifiedFixed > 0 ? [
|
|
1034
|
+
`- Verified fixes: ${verifiedFixed}/${detected.length} (shield-llm retest)`
|
|
1035
|
+
] : [],
|
|
548
1036
|
"",
|
|
549
1037
|
"## Vulnerabilities detected",
|
|
550
1038
|
""
|
|
@@ -552,11 +1040,11 @@ function renderScanMarkdown(scan) {
|
|
|
552
1040
|
if (detected.length === 0) {
|
|
553
1041
|
lines.push("_None_");
|
|
554
1042
|
} else {
|
|
555
|
-
lines.push("| Severity | Name | Notes |");
|
|
556
|
-
lines.push("
|
|
1043
|
+
lines.push("| Severity | Name | Verification | Notes |");
|
|
1044
|
+
lines.push("|---|---|---|---|");
|
|
557
1045
|
for (const v of detected) {
|
|
558
1046
|
lines.push(
|
|
559
|
-
`| ${v.severity} | ${v.name} | ${(v.description ?? "").slice(0, 80)} |`
|
|
1047
|
+
`| ${v.severity} | ${v.name} | ${verificationLabel(v)} | ${(v.description ?? "").slice(0, 80)} |`
|
|
560
1048
|
);
|
|
561
1049
|
}
|
|
562
1050
|
}
|
|
@@ -612,17 +1100,13 @@ async function reportCommand(scanId, opts) {
|
|
|
612
1100
|
content = JSON.stringify(scan, null, 2);
|
|
613
1101
|
}
|
|
614
1102
|
if (opts.outputFile) {
|
|
615
|
-
|
|
1103
|
+
writeFileSync4(resolve2(opts.outputFile), content, "utf-8");
|
|
616
1104
|
console.error(`Report written to ${opts.outputFile}`);
|
|
617
1105
|
} else {
|
|
618
1106
|
console.log(content);
|
|
619
1107
|
}
|
|
620
1108
|
}
|
|
621
1109
|
|
|
622
|
-
// src/commands/scan.ts
|
|
623
|
-
import { writeFileSync as writeFileSync4 } from "fs";
|
|
624
|
-
import { resolve as resolve3 } from "path";
|
|
625
|
-
|
|
626
1110
|
// src/custom-tests-loader.ts
|
|
627
1111
|
async function fetchCustomTests(apiUrl, apiKey) {
|
|
628
1112
|
const res = await fetch(`${apiUrl}/api/cli/tests`, {
|
|
@@ -671,52 +1155,75 @@ function truncateInput(input2) {
|
|
|
671
1155
|
}))
|
|
672
1156
|
};
|
|
673
1157
|
}
|
|
1158
|
+
var TRANSIENT_STATUSES = /* @__PURE__ */ new Set([429, 502, 503, 504]);
|
|
674
1159
|
var BackendEvaluator = class {
|
|
675
|
-
constructor(apiUrl, apiKey) {
|
|
1160
|
+
constructor(apiUrl, apiKey, opts) {
|
|
676
1161
|
this.apiUrl = apiUrl;
|
|
677
1162
|
this.apiKey = apiKey;
|
|
1163
|
+
this.maxRetries = opts?.maxRetries ?? 3;
|
|
1164
|
+
this.backoffMs = opts?.backoffMs ?? 1e3;
|
|
1165
|
+
this.maxBackoffMs = opts?.maxBackoffMs ?? 3e4;
|
|
1166
|
+
this.sleep = opts?.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
|
|
678
1167
|
}
|
|
679
1168
|
async evaluate(input2) {
|
|
680
|
-
const
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
)
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
)
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
}
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
1169
|
+
const body = JSON.stringify(truncateInput(input2));
|
|
1170
|
+
let attempt = 0;
|
|
1171
|
+
for (; ; ) {
|
|
1172
|
+
const response = await fetch(`${this.apiUrl}/api/cli/evaluate`, {
|
|
1173
|
+
method: "POST",
|
|
1174
|
+
headers: {
|
|
1175
|
+
"Content-Type": "application/json",
|
|
1176
|
+
Authorization: `Bearer ${this.apiKey}`
|
|
1177
|
+
},
|
|
1178
|
+
body
|
|
1179
|
+
});
|
|
1180
|
+
if (TRANSIENT_STATUSES.has(response.status) && attempt < this.maxRetries) {
|
|
1181
|
+
const waitMs = this.backoffFor(response, attempt);
|
|
1182
|
+
attempt++;
|
|
1183
|
+
await this.sleep(waitMs);
|
|
1184
|
+
continue;
|
|
1185
|
+
}
|
|
1186
|
+
if (response.status === 401) {
|
|
1187
|
+
throw new Error(
|
|
1188
|
+
"Invalid API key. Run `shield-llm login` to re-authenticate."
|
|
1189
|
+
);
|
|
1190
|
+
}
|
|
1191
|
+
if (response.status === 403) {
|
|
1192
|
+
const errBody = await response.json().catch(() => ({}));
|
|
1193
|
+
throw new Error(errBody.error ?? "Access denied by the backend (403).");
|
|
1194
|
+
}
|
|
1195
|
+
if (response.status === 429) {
|
|
1196
|
+
throw new Error(
|
|
1197
|
+
"Rate limit exceeded after retries. Please wait and try again."
|
|
1198
|
+
);
|
|
1199
|
+
}
|
|
1200
|
+
if (!response.ok) {
|
|
1201
|
+
const errText = await response.text().catch(() => "");
|
|
1202
|
+
let userMessage = `Backend evaluation failed (HTTP ${response.status}). Please try again.`;
|
|
1203
|
+
try {
|
|
1204
|
+
const parsed = JSON.parse(errText);
|
|
1205
|
+
if (typeof parsed.error === "string" && parsed.error.length > 0) {
|
|
1206
|
+
userMessage = `Backend evaluation failed (${response.status}): ${parsed.error}`;
|
|
1207
|
+
}
|
|
1208
|
+
} catch {
|
|
1209
|
+
if (errText) {
|
|
1210
|
+
console.error(
|
|
1211
|
+
`[BackendEvaluator] Non-JSON ${response.status} response body (first 500 chars): ${errText.slice(0, 500)}`
|
|
1212
|
+
);
|
|
1213
|
+
}
|
|
715
1214
|
}
|
|
1215
|
+
throw new Error(userMessage);
|
|
716
1216
|
}
|
|
717
|
-
|
|
1217
|
+
return response.json();
|
|
718
1218
|
}
|
|
719
|
-
|
|
1219
|
+
}
|
|
1220
|
+
/** Backoff for one retry: a 429 Retry-After (seconds) when present, else
|
|
1221
|
+
* exponential (backoffMs · 2^attempt). Both clamped to maxBackoffMs. */
|
|
1222
|
+
backoffFor(response, attempt) {
|
|
1223
|
+
const header = response.headers.get("retry-after");
|
|
1224
|
+
const retryAfterSec = header ? parseInt(header, 10) : NaN;
|
|
1225
|
+
const base = response.status === 429 && Number.isFinite(retryAfterSec) && retryAfterSec > 0 ? retryAfterSec * 1e3 : this.backoffMs * 2 ** attempt;
|
|
1226
|
+
return Math.min(base, this.maxBackoffMs);
|
|
720
1227
|
}
|
|
721
1228
|
};
|
|
722
1229
|
|
|
@@ -732,6 +1239,14 @@ function handleEvent(event) {
|
|
|
732
1239
|
chalk.cyan(`Starting scan (${event.totalAttacks} attacks)...`)
|
|
733
1240
|
);
|
|
734
1241
|
break;
|
|
1242
|
+
case "scan:resume":
|
|
1243
|
+
spinner.info(
|
|
1244
|
+
chalk.cyan(
|
|
1245
|
+
`Resuming \u2014 ${event.completed}/${event.total} attacks already done, running the rest`
|
|
1246
|
+
)
|
|
1247
|
+
);
|
|
1248
|
+
spinner.start();
|
|
1249
|
+
break;
|
|
735
1250
|
case "attack:start":
|
|
736
1251
|
currentAttackName = event.attack.name;
|
|
737
1252
|
spinner.text = chalk.cyan(
|
|
@@ -762,6 +1277,11 @@ function handleEvent(event) {
|
|
|
762
1277
|
`${currentAttackName} \u2014 turn ${event.turn}/${event.totalTurns}`
|
|
763
1278
|
);
|
|
764
1279
|
break;
|
|
1280
|
+
case "attack:retry":
|
|
1281
|
+
spinner.text = chalk.yellow(
|
|
1282
|
+
`${currentAttackName} \u2014 ${event.reason === "rate_limited" ? "rate limited" : "server error"}, backing off ${(event.waitMs / 1e3).toFixed(1)}s (retry ${event.attempt}/${event.maxRetries})`
|
|
1283
|
+
);
|
|
1284
|
+
break;
|
|
765
1285
|
case "scan:rate_limited":
|
|
766
1286
|
spinner.fail(
|
|
767
1287
|
chalk.red(
|
|
@@ -861,6 +1381,403 @@ function gradeColor(grade) {
|
|
|
861
1381
|
}
|
|
862
1382
|
}
|
|
863
1383
|
|
|
1384
|
+
// src/lib/format.ts
|
|
1385
|
+
function truncate(str, max) {
|
|
1386
|
+
const oneLine = str.replace(/\n/g, " ").trim();
|
|
1387
|
+
return oneLine.length <= max ? oneLine : oneLine.slice(0, max - 3) + "...";
|
|
1388
|
+
}
|
|
1389
|
+
|
|
1390
|
+
// src/retest-core.ts
|
|
1391
|
+
function selectRetestableFindings(vulns, filter) {
|
|
1392
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1393
|
+
const findings = [];
|
|
1394
|
+
for (const v of vulns) {
|
|
1395
|
+
if (v.status !== "DETECTED") continue;
|
|
1396
|
+
if (v.captureStatus === "pending" || v.captureStatus === "rate_limited") {
|
|
1397
|
+
continue;
|
|
1398
|
+
}
|
|
1399
|
+
const key = v.vulnerabilityType ?? v.name;
|
|
1400
|
+
if (seen.has(key)) continue;
|
|
1401
|
+
seen.add(key);
|
|
1402
|
+
findings.push({
|
|
1403
|
+
attackId: v.vulnerabilityType ?? null,
|
|
1404
|
+
name: v.name,
|
|
1405
|
+
severity: v.severity
|
|
1406
|
+
});
|
|
1407
|
+
}
|
|
1408
|
+
if (!filter || filter.length === 0) return findings;
|
|
1409
|
+
const wanted = new Set(filter);
|
|
1410
|
+
return findings.filter(
|
|
1411
|
+
(f) => f.attackId && wanted.has(f.attackId) || wanted.has(f.name)
|
|
1412
|
+
);
|
|
1413
|
+
}
|
|
1414
|
+
var CUSTOM_PREFIX = "custom_";
|
|
1415
|
+
function buildRetestPlan(findings, catalogue) {
|
|
1416
|
+
const plan = {
|
|
1417
|
+
singles: [],
|
|
1418
|
+
multiTurn: [],
|
|
1419
|
+
customs: [],
|
|
1420
|
+
unavailable: [],
|
|
1421
|
+
findingByResultId: /* @__PURE__ */ new Map()
|
|
1422
|
+
};
|
|
1423
|
+
for (const finding of findings) {
|
|
1424
|
+
if (finding.attackId?.startsWith(CUSTOM_PREFIX)) {
|
|
1425
|
+
const customName = finding.attackId.slice(CUSTOM_PREFIX.length);
|
|
1426
|
+
const test = catalogue.customTests.find((t) => t.name === customName);
|
|
1427
|
+
if (test) {
|
|
1428
|
+
plan.customs.push({ finding, test });
|
|
1429
|
+
plan.findingByResultId.set(`${CUSTOM_PREFIX}${test.name}`, finding);
|
|
1430
|
+
} else {
|
|
1431
|
+
plan.unavailable.push(finding);
|
|
1432
|
+
}
|
|
1433
|
+
continue;
|
|
1434
|
+
}
|
|
1435
|
+
const single = catalogue.attacks.find((a) => a.id === finding.attackId) ?? (finding.attackId ? void 0 : catalogue.attacks.find((a) => a.name === finding.name));
|
|
1436
|
+
if (single) {
|
|
1437
|
+
plan.singles.push({ finding, attack: single });
|
|
1438
|
+
plan.findingByResultId.set(single.id, finding);
|
|
1439
|
+
continue;
|
|
1440
|
+
}
|
|
1441
|
+
const multi = catalogue.multiTurnAttacks.find((a) => a.id === finding.attackId) ?? (finding.attackId ? void 0 : catalogue.multiTurnAttacks.find((a) => a.name === finding.name));
|
|
1442
|
+
if (multi) {
|
|
1443
|
+
plan.multiTurn.push({ finding, attack: multi });
|
|
1444
|
+
plan.findingByResultId.set(multi.id, finding);
|
|
1445
|
+
continue;
|
|
1446
|
+
}
|
|
1447
|
+
plan.unavailable.push(finding);
|
|
1448
|
+
}
|
|
1449
|
+
return plan;
|
|
1450
|
+
}
|
|
1451
|
+
var EVIDENCE_PROMPT_CAP = 6e3;
|
|
1452
|
+
var EVIDENCE_RESPONSE_CAP = 2500;
|
|
1453
|
+
var REASONING_CAP = 4500;
|
|
1454
|
+
function buildRetestOutcome(results, findingByResultId) {
|
|
1455
|
+
const outcome = { verifications: [], failed: [] };
|
|
1456
|
+
for (const result of results) {
|
|
1457
|
+
const finding = findingByResultId.get(result.id);
|
|
1458
|
+
if (!finding) continue;
|
|
1459
|
+
if (result.error || result.rateLimited) {
|
|
1460
|
+
outcome.failed.push({
|
|
1461
|
+
finding,
|
|
1462
|
+
error: result.error ?? "rate limited"
|
|
1463
|
+
});
|
|
1464
|
+
continue;
|
|
1465
|
+
}
|
|
1466
|
+
outcome.verifications.push({
|
|
1467
|
+
// For legacy findings attackId is the catalogue id we matched by name;
|
|
1468
|
+
// the server falls back to name-matching rows with null vulnerabilityType.
|
|
1469
|
+
attackId: finding.attackId ?? result.id,
|
|
1470
|
+
name: finding.name,
|
|
1471
|
+
vulnerable: result.vulnerable,
|
|
1472
|
+
evidence: JSON.stringify({
|
|
1473
|
+
prompt: truncate(result.prompt, EVIDENCE_PROMPT_CAP),
|
|
1474
|
+
response: truncate(result.response, EVIDENCE_RESPONSE_CAP)
|
|
1475
|
+
}),
|
|
1476
|
+
evaluationMethod: result.llmEvaluation?.evaluationMethod,
|
|
1477
|
+
confidence: result.llmEvaluation?.confidence,
|
|
1478
|
+
reasoning: result.llmEvaluation?.reasoning ? truncate(result.llmEvaluation.reasoning, REASONING_CAP) : void 0
|
|
1479
|
+
});
|
|
1480
|
+
}
|
|
1481
|
+
return outcome;
|
|
1482
|
+
}
|
|
1483
|
+
function decideExitCode(summary) {
|
|
1484
|
+
if (summary.stillVulnerable > 0) return 1;
|
|
1485
|
+
if (summary.fixed > 0) return 0;
|
|
1486
|
+
return 3;
|
|
1487
|
+
}
|
|
1488
|
+
|
|
1489
|
+
// src/commands/retest.ts
|
|
1490
|
+
function findingLabel(finding) {
|
|
1491
|
+
return `${finding.name} (${finding.severity})`;
|
|
1492
|
+
}
|
|
1493
|
+
async function retestCommand(scanId, opts) {
|
|
1494
|
+
try {
|
|
1495
|
+
if (opts.ci) opts.progress = false;
|
|
1496
|
+
const info = (msg) => {
|
|
1497
|
+
if (opts.ci) console.error(msg);
|
|
1498
|
+
else console.log(msg);
|
|
1499
|
+
};
|
|
1500
|
+
const stored = loadCredentials();
|
|
1501
|
+
const credentials = stored ? { ...stored, apiUrl: resolveApiUrl(stored.apiUrl, opts.apiUrl) } : null;
|
|
1502
|
+
if (!credentials) {
|
|
1503
|
+
console.error("Not logged in. Run `shield-llm login` to authenticate.");
|
|
1504
|
+
setExitCode(2);
|
|
1505
|
+
return;
|
|
1506
|
+
}
|
|
1507
|
+
let scan;
|
|
1508
|
+
try {
|
|
1509
|
+
const res = await fetch(
|
|
1510
|
+
`${credentials.apiUrl}/api/cli/reports/${encodeURIComponent(scanId)}`,
|
|
1511
|
+
{ headers: { Authorization: `Bearer ${credentials.apiKey}` } }
|
|
1512
|
+
);
|
|
1513
|
+
if (res.status === 401) {
|
|
1514
|
+
await res.text().catch(() => void 0);
|
|
1515
|
+
console.error(
|
|
1516
|
+
"API key is invalid or revoked. Run `shield-llm login` to re-authenticate."
|
|
1517
|
+
);
|
|
1518
|
+
setExitCode(2);
|
|
1519
|
+
return;
|
|
1520
|
+
}
|
|
1521
|
+
if (res.status === 403) {
|
|
1522
|
+
const body = await res.json().catch(() => ({}));
|
|
1523
|
+
console.error(body.error ?? "Plan does not allow CLI access.");
|
|
1524
|
+
setExitCode(2);
|
|
1525
|
+
return;
|
|
1526
|
+
}
|
|
1527
|
+
if (res.status === 404) {
|
|
1528
|
+
await res.text().catch(() => void 0);
|
|
1529
|
+
console.error(`Scan "${scanId}" not found.`);
|
|
1530
|
+
setExitCode(2);
|
|
1531
|
+
return;
|
|
1532
|
+
}
|
|
1533
|
+
if (!res.ok) {
|
|
1534
|
+
await res.text().catch(() => void 0);
|
|
1535
|
+
console.error(`Backend returned HTTP ${res.status} fetching the scan.`);
|
|
1536
|
+
setExitCode(3);
|
|
1537
|
+
return;
|
|
1538
|
+
}
|
|
1539
|
+
scan = await res.json();
|
|
1540
|
+
} catch (err) {
|
|
1541
|
+
const msg = err instanceof Error ? err.message : "Unknown error";
|
|
1542
|
+
console.error(`Failed to reach backend: ${msg}`);
|
|
1543
|
+
setExitCode(3);
|
|
1544
|
+
return;
|
|
1545
|
+
}
|
|
1546
|
+
if (scan.status && scan.status !== "completed") {
|
|
1547
|
+
console.error(
|
|
1548
|
+
`Scan "${scanId}" is ${scan.status} \u2014 only completed scans can be retested.`
|
|
1549
|
+
);
|
|
1550
|
+
setExitCode(2);
|
|
1551
|
+
return;
|
|
1552
|
+
}
|
|
1553
|
+
const filter = opts.finding && opts.finding.length > 0 ? opts.finding : void 0;
|
|
1554
|
+
const findings = selectRetestableFindings(scan.vulns ?? [], filter);
|
|
1555
|
+
if (findings.length === 0) {
|
|
1556
|
+
if (filter) {
|
|
1557
|
+
console.error(
|
|
1558
|
+
`No detected finding matches ${filter.map((f) => `"${f}"`).join(", ")} in scan ${scanId}.`
|
|
1559
|
+
);
|
|
1560
|
+
setExitCode(2);
|
|
1561
|
+
return;
|
|
1562
|
+
}
|
|
1563
|
+
info(`Scan ${scanId} has no detected findings \u2014 nothing to retest.`);
|
|
1564
|
+
setExitCode(0);
|
|
1565
|
+
return;
|
|
1566
|
+
}
|
|
1567
|
+
const cliOverrides = {};
|
|
1568
|
+
if (opts.endpoint) {
|
|
1569
|
+
cliOverrides.endpoint = {
|
|
1570
|
+
url: opts.endpoint,
|
|
1571
|
+
auth: buildAuthFromFlags(opts),
|
|
1572
|
+
request: {
|
|
1573
|
+
method: "POST",
|
|
1574
|
+
body: opts.requestBody ? JSON.parse(opts.requestBody) : { message: "{{prompt}}" }
|
|
1575
|
+
},
|
|
1576
|
+
response: { field: opts.responseField ?? "response" }
|
|
1577
|
+
};
|
|
1578
|
+
}
|
|
1579
|
+
const config = loadConfig({ configPath: opts.config, cliOverrides });
|
|
1580
|
+
const systemPrompt = loadSystemPrompt(config);
|
|
1581
|
+
const endpointHost = safeHostname(config.endpoint?.url);
|
|
1582
|
+
if (scan.targetDomain && endpointHost && endpointHost !== scan.targetDomain) {
|
|
1583
|
+
console.error(
|
|
1584
|
+
`Warning: retesting against "${endpointHost}" but scan ${scanId} targeted "${scan.targetDomain}". Verification badges will reflect this endpoint.`
|
|
1585
|
+
);
|
|
1586
|
+
}
|
|
1587
|
+
const needsCustom = findings.some(
|
|
1588
|
+
(f) => f.attackId?.startsWith(CUSTOM_PREFIX)
|
|
1589
|
+
);
|
|
1590
|
+
let catalogue;
|
|
1591
|
+
try {
|
|
1592
|
+
const fetched = await fetchAttacks({
|
|
1593
|
+
apiUrl: credentials.apiUrl,
|
|
1594
|
+
apiKey: credentials.apiKey,
|
|
1595
|
+
preset: "full",
|
|
1596
|
+
includeMultiTurn: true
|
|
1597
|
+
});
|
|
1598
|
+
catalogue = {
|
|
1599
|
+
attacks: fetched.attacks,
|
|
1600
|
+
multiTurnAttacks: fetched.multiTurnAttacks,
|
|
1601
|
+
customTests: needsCustom ? await fetchCustomTests(credentials.apiUrl, credentials.apiKey) : []
|
|
1602
|
+
};
|
|
1603
|
+
} catch (err) {
|
|
1604
|
+
const msg = err instanceof Error ? err.message : "Unknown error";
|
|
1605
|
+
console.error(`Failed to fetch the attack catalogue: ${msg}`);
|
|
1606
|
+
setExitCode(3);
|
|
1607
|
+
return;
|
|
1608
|
+
}
|
|
1609
|
+
const plan = buildRetestPlan(findings, catalogue);
|
|
1610
|
+
const runnable = plan.singles.length + plan.multiTurn.length + plan.customs.length;
|
|
1611
|
+
for (const finding of plan.unavailable) {
|
|
1612
|
+
info(
|
|
1613
|
+
`Skipping ${findingLabel(finding)} \u2014 not replayable from the CLI (attack unavailable in the catalogue or custom test deleted).`
|
|
1614
|
+
);
|
|
1615
|
+
}
|
|
1616
|
+
if (runnable === 0) {
|
|
1617
|
+
console.error("None of the selected findings can be replayed.");
|
|
1618
|
+
setExitCode(3);
|
|
1619
|
+
return;
|
|
1620
|
+
}
|
|
1621
|
+
info(
|
|
1622
|
+
`Retesting ${runnable} finding(s) from scan ${scanId} against ${config.endpoint?.url ?? "target"}\u2026`
|
|
1623
|
+
);
|
|
1624
|
+
const evaluator = new BackendEvaluator(
|
|
1625
|
+
credentials.apiUrl,
|
|
1626
|
+
credentials.apiKey
|
|
1627
|
+
);
|
|
1628
|
+
const scanOptions = {
|
|
1629
|
+
target: buildTargetConfig(config),
|
|
1630
|
+
systemPrompt,
|
|
1631
|
+
preset: config.preset ?? "standard",
|
|
1632
|
+
attacks: plan.singles.map((s) => s.attack),
|
|
1633
|
+
multiTurnAttacks: plan.multiTurn.map((m) => m.attack),
|
|
1634
|
+
includeCrescendo: plan.multiTurn.length > 0,
|
|
1635
|
+
customTests: plan.customs.map((c) => c.test),
|
|
1636
|
+
concurrency: config.concurrency,
|
|
1637
|
+
delayMs: config.delayMs,
|
|
1638
|
+
attackTimeoutMs: config.attackTimeoutMs,
|
|
1639
|
+
maxConsecutiveFailures: config.maxConsecutiveFailures,
|
|
1640
|
+
maxRateLimitRetries: config.maxRateLimitRetries,
|
|
1641
|
+
rateLimitBackoffMs: config.rateLimitBackoffMs,
|
|
1642
|
+
rateLimitMaxBackoffMs: config.rateLimitMaxBackoffMs,
|
|
1643
|
+
evaluator
|
|
1644
|
+
};
|
|
1645
|
+
const onEvent = opts.progress !== false ? handleEvent : void 0;
|
|
1646
|
+
const scanner = new Scanner(scanOptions, onEvent);
|
|
1647
|
+
const report = await scanner.run();
|
|
1648
|
+
const outcome = buildRetestOutcome(report.attacks, plan.findingByResultId);
|
|
1649
|
+
let verify2 = null;
|
|
1650
|
+
let verifyError = null;
|
|
1651
|
+
if (outcome.verifications.length > 0) {
|
|
1652
|
+
try {
|
|
1653
|
+
const res = await fetch(
|
|
1654
|
+
`${credentials.apiUrl}/api/cli/reports/${encodeURIComponent(scanId)}/verify`,
|
|
1655
|
+
{
|
|
1656
|
+
method: "POST",
|
|
1657
|
+
headers: {
|
|
1658
|
+
"Content-Type": "application/json",
|
|
1659
|
+
Authorization: `Bearer ${credentials.apiKey}`
|
|
1660
|
+
},
|
|
1661
|
+
body: JSON.stringify({
|
|
1662
|
+
targetUrl: config.endpoint?.url,
|
|
1663
|
+
results: outcome.verifications
|
|
1664
|
+
})
|
|
1665
|
+
}
|
|
1666
|
+
);
|
|
1667
|
+
if (!res.ok) {
|
|
1668
|
+
const body = await res.text().catch(() => "");
|
|
1669
|
+
verifyError = `HTTP ${res.status}: ${body.slice(0, 200)}`;
|
|
1670
|
+
} else {
|
|
1671
|
+
verify2 = await res.json();
|
|
1672
|
+
}
|
|
1673
|
+
} catch (err) {
|
|
1674
|
+
verifyError = err instanceof Error ? err.message : "Unknown error";
|
|
1675
|
+
}
|
|
1676
|
+
}
|
|
1677
|
+
const fixed = outcome.verifications.filter((v) => !v.vulnerable);
|
|
1678
|
+
const stillVulnerable = outcome.verifications.filter((v) => v.vulnerable);
|
|
1679
|
+
if (opts.ci) {
|
|
1680
|
+
console.log(
|
|
1681
|
+
JSON.stringify(
|
|
1682
|
+
{
|
|
1683
|
+
scanId,
|
|
1684
|
+
targetUrl: config.endpoint?.url,
|
|
1685
|
+
retested: outcome.verifications.length,
|
|
1686
|
+
fixed: fixed.length,
|
|
1687
|
+
stillVulnerable: stillVulnerable.length,
|
|
1688
|
+
results: outcome.verifications.map((v) => ({
|
|
1689
|
+
attackId: v.attackId,
|
|
1690
|
+
name: v.name,
|
|
1691
|
+
outcome: v.vulnerable ? "still_vulnerable" : "fixed"
|
|
1692
|
+
})),
|
|
1693
|
+
failed: outcome.failed.map((f) => ({
|
|
1694
|
+
attackId: f.finding.attackId,
|
|
1695
|
+
name: f.finding.name,
|
|
1696
|
+
error: f.error
|
|
1697
|
+
})),
|
|
1698
|
+
unavailable: plan.unavailable.map((f) => ({
|
|
1699
|
+
attackId: f.attackId,
|
|
1700
|
+
name: f.name
|
|
1701
|
+
})),
|
|
1702
|
+
verify: verify2 ?? void 0,
|
|
1703
|
+
verifyError: verifyError ?? void 0
|
|
1704
|
+
},
|
|
1705
|
+
null,
|
|
1706
|
+
2
|
|
1707
|
+
)
|
|
1708
|
+
);
|
|
1709
|
+
} else {
|
|
1710
|
+
console.log("");
|
|
1711
|
+
for (const v of fixed) {
|
|
1712
|
+
console.log(` \u2713 FIXED & VERIFIED ${v.name}`);
|
|
1713
|
+
}
|
|
1714
|
+
for (const v of stillVulnerable) {
|
|
1715
|
+
console.log(` \u2717 STILL VULNERABLE ${v.name}`);
|
|
1716
|
+
}
|
|
1717
|
+
for (const f of outcome.failed) {
|
|
1718
|
+
console.log(
|
|
1719
|
+
` \u26A0 NOT RETESTED ${findingLabel(f.finding)} \u2014 ${f.error}`
|
|
1720
|
+
);
|
|
1721
|
+
}
|
|
1722
|
+
for (const f of plan.unavailable) {
|
|
1723
|
+
console.log(` \u26A0 NOT RETESTED ${findingLabel(f)} \u2014 unavailable`);
|
|
1724
|
+
}
|
|
1725
|
+
console.log("");
|
|
1726
|
+
console.log(
|
|
1727
|
+
`Retest complete: ${fixed.length} fixed & verified, ${stillVulnerable.length} still vulnerable` + (outcome.failed.length + plan.unavailable.length > 0 ? `, ${outcome.failed.length + plan.unavailable.length} not retested` : "") + "."
|
|
1728
|
+
);
|
|
1729
|
+
if (verify2) {
|
|
1730
|
+
console.log(
|
|
1731
|
+
`Dashboard updated (${verify2.updated} finding(s) stamped).`
|
|
1732
|
+
);
|
|
1733
|
+
if (verify2.notFound.length > 0) {
|
|
1734
|
+
console.warn(
|
|
1735
|
+
`Warning: no matching dashboard row for: ${verify2.notFound.join(", ")}`
|
|
1736
|
+
);
|
|
1737
|
+
}
|
|
1738
|
+
}
|
|
1739
|
+
}
|
|
1740
|
+
if (verifyError) {
|
|
1741
|
+
console.error(
|
|
1742
|
+
`Warning: verdicts computed but NOT recorded on the dashboard: ${verifyError}`
|
|
1743
|
+
);
|
|
1744
|
+
setExitCode(3);
|
|
1745
|
+
return;
|
|
1746
|
+
}
|
|
1747
|
+
setExitCode(
|
|
1748
|
+
decideExitCode({
|
|
1749
|
+
fixed: fixed.length,
|
|
1750
|
+
stillVulnerable: stillVulnerable.length,
|
|
1751
|
+
failed: outcome.failed.length,
|
|
1752
|
+
unavailable: plan.unavailable.length
|
|
1753
|
+
})
|
|
1754
|
+
);
|
|
1755
|
+
return;
|
|
1756
|
+
} catch (error) {
|
|
1757
|
+
if (error instanceof ConfigError) {
|
|
1758
|
+
console.error(`Configuration error: ${error.message}`);
|
|
1759
|
+
setExitCode(2);
|
|
1760
|
+
return;
|
|
1761
|
+
}
|
|
1762
|
+
const msg = error instanceof Error ? error.message : "Unknown error";
|
|
1763
|
+
console.error(`Runtime error: ${msg}`);
|
|
1764
|
+
setExitCode(3);
|
|
1765
|
+
return;
|
|
1766
|
+
}
|
|
1767
|
+
}
|
|
1768
|
+
function safeHostname(url) {
|
|
1769
|
+
if (!url) return null;
|
|
1770
|
+
try {
|
|
1771
|
+
return new URL(url).hostname.replace(/^www\./, "");
|
|
1772
|
+
} catch {
|
|
1773
|
+
return null;
|
|
1774
|
+
}
|
|
1775
|
+
}
|
|
1776
|
+
|
|
1777
|
+
// src/commands/scan.ts
|
|
1778
|
+
import { writeFileSync as writeFileSync5 } from "fs";
|
|
1779
|
+
import { resolve as resolve3 } from "path";
|
|
1780
|
+
|
|
864
1781
|
// src/lib/sanitize.ts
|
|
865
1782
|
var DEFAULTS = {
|
|
866
1783
|
responseMaxChars: 500,
|
|
@@ -901,36 +1818,8 @@ function sanitizeReportForDisk(report, opts = {}) {
|
|
|
901
1818
|
};
|
|
902
1819
|
}
|
|
903
1820
|
|
|
904
|
-
// src/lib/format.ts
|
|
905
|
-
function truncate(str, max) {
|
|
906
|
-
const oneLine = str.replace(/\n/g, " ").trim();
|
|
907
|
-
return oneLine.length <= max ? oneLine : oneLine.slice(0, max - 3) + "...";
|
|
908
|
-
}
|
|
909
|
-
|
|
910
1821
|
// src/commands/scan.ts
|
|
911
|
-
function
|
|
912
|
-
if (!opts.auth) return void 0;
|
|
913
|
-
switch (opts.auth) {
|
|
914
|
-
case "bearer":
|
|
915
|
-
if (!opts.token)
|
|
916
|
-
throw new ConfigError("--token is required with --auth bearer");
|
|
917
|
-
return { type: "bearer", token: opts.token };
|
|
918
|
-
case "api-key":
|
|
919
|
-
if (!opts.token)
|
|
920
|
-
throw new ConfigError("--token is required with --auth api-key");
|
|
921
|
-
return {
|
|
922
|
-
type: "api-key",
|
|
923
|
-
header: opts.authHeader ?? "X-API-Key",
|
|
924
|
-
value: opts.token
|
|
925
|
-
};
|
|
926
|
-
// oauth2 requires too many params for CLI flags — use config file instead
|
|
927
|
-
default:
|
|
928
|
-
throw new ConfigError(
|
|
929
|
-
`Unknown or unsupported auth type for CLI flags: "${opts.auth}". OAuth2 must be configured via shield.config.json.`
|
|
930
|
-
);
|
|
931
|
-
}
|
|
932
|
-
}
|
|
933
|
-
async function uploadReportToBackend(report, credentials, scanId) {
|
|
1822
|
+
async function uploadReportToBackend(report, credentials, scanId, attackPackVersion) {
|
|
934
1823
|
const vulnerabilities = report.attacks.filter((a) => !a.error && !a.rateLimited).map((a) => ({
|
|
935
1824
|
// attackId lets the backend validate against its known catalogue + the
|
|
936
1825
|
// user's custom tests, rejecting fabricated vulnerability rows.
|
|
@@ -956,6 +1845,7 @@ async function uploadReportToBackend(report, credentials, scanId) {
|
|
|
956
1845
|
const testsRun = report.attacks.filter(
|
|
957
1846
|
(a) => !a.error && !a.rateLimited
|
|
958
1847
|
).length;
|
|
1848
|
+
const attackErrorSummary = summarizeAttackErrors(report.attacks);
|
|
959
1849
|
const payload = {
|
|
960
1850
|
scanId,
|
|
961
1851
|
targetUrl: report.target,
|
|
@@ -964,6 +1854,11 @@ async function uploadReportToBackend(report, credentials, scanId) {
|
|
|
964
1854
|
testsRun,
|
|
965
1855
|
testsTotal: report.config.totalAttacks,
|
|
966
1856
|
durationMs: report.durationMs,
|
|
1857
|
+
preset: report.config.preset,
|
|
1858
|
+
...attackPackVersion && { attackPackVersion },
|
|
1859
|
+
...attackErrorSummary && {
|
|
1860
|
+
attackErrors: { items: attackErrorSummary.items }
|
|
1861
|
+
},
|
|
967
1862
|
vulnerabilities
|
|
968
1863
|
};
|
|
969
1864
|
const res = await fetch(`${credentials.apiUrl}/api/cli/reports`, {
|
|
@@ -978,8 +1873,30 @@ async function uploadReportToBackend(report, credentials, scanId) {
|
|
|
978
1873
|
const body = await res.text().catch(() => "");
|
|
979
1874
|
throw new Error(`HTTP ${res.status}: ${body.slice(0, 200)}`);
|
|
980
1875
|
}
|
|
1876
|
+
const data = await res.json().catch(() => ({}));
|
|
1877
|
+
return {
|
|
1878
|
+
score: typeof data.score === "number" ? data.score : report.score,
|
|
1879
|
+
grade: data.grade ?? report.grade,
|
|
1880
|
+
droppedAttackIds: data.droppedAttackIds ?? 0
|
|
1881
|
+
};
|
|
1882
|
+
}
|
|
1883
|
+
async function reportScanFailure(credentials, scanId, reason) {
|
|
1884
|
+
try {
|
|
1885
|
+
await fetch(`${credentials.apiUrl}/api/cli/scans/${scanId}/fail`, {
|
|
1886
|
+
method: "POST",
|
|
1887
|
+
headers: {
|
|
1888
|
+
"Content-Type": "application/json",
|
|
1889
|
+
Authorization: `Bearer ${credentials.apiKey}`
|
|
1890
|
+
},
|
|
1891
|
+
body: JSON.stringify({ error: reason.slice(0, 2e3) })
|
|
1892
|
+
});
|
|
1893
|
+
} catch {
|
|
1894
|
+
}
|
|
981
1895
|
}
|
|
982
1896
|
async function scanCommand(opts) {
|
|
1897
|
+
let reservedScanId = null;
|
|
1898
|
+
let scanFinalized = false;
|
|
1899
|
+
let failTarget = null;
|
|
983
1900
|
try {
|
|
984
1901
|
if (opts.ci) {
|
|
985
1902
|
opts.output = opts.output ?? "json";
|
|
@@ -1001,7 +1918,7 @@ async function scanCommand(opts) {
|
|
|
1001
1918
|
setExitCode(2);
|
|
1002
1919
|
return;
|
|
1003
1920
|
}
|
|
1004
|
-
|
|
1921
|
+
failTarget = { apiUrl: credentials.apiUrl, apiKey: credentials.apiKey };
|
|
1005
1922
|
try {
|
|
1006
1923
|
const res = await fetch(`${credentials.apiUrl}/api/cli/scans`, {
|
|
1007
1924
|
method: "POST",
|
|
@@ -1017,14 +1934,6 @@ async function scanCommand(opts) {
|
|
|
1017
1934
|
setExitCode(2);
|
|
1018
1935
|
return;
|
|
1019
1936
|
}
|
|
1020
|
-
if (res.status === 403) {
|
|
1021
|
-
const body = await res.json().catch(() => ({}));
|
|
1022
|
-
console.error(
|
|
1023
|
-
body.error ?? `Monthly scan limit reached. Upgrade at ${DEFAULT_API_URL}/settings`
|
|
1024
|
-
);
|
|
1025
|
-
setExitCode(2);
|
|
1026
|
-
return;
|
|
1027
|
-
}
|
|
1028
1937
|
if (!res.ok) {
|
|
1029
1938
|
console.error(`Failed to start scan: HTTP ${res.status}`);
|
|
1030
1939
|
setExitCode(3);
|
|
@@ -1032,9 +1941,7 @@ async function scanCommand(opts) {
|
|
|
1032
1941
|
}
|
|
1033
1942
|
const scanSlot = await res.json();
|
|
1034
1943
|
reservedScanId = scanSlot.scanId;
|
|
1035
|
-
info(
|
|
1036
|
-
`Scan reserved (${scanSlot.remaining}/${scanSlot.limit} remaining this month)`
|
|
1037
|
-
);
|
|
1944
|
+
info("Scan started");
|
|
1038
1945
|
} catch (err) {
|
|
1039
1946
|
const msg = err instanceof Error ? err.message : "Unknown error";
|
|
1040
1947
|
console.error(`Failed to connect to backend: ${msg}`);
|
|
@@ -1086,11 +1993,26 @@ async function scanCommand(opts) {
|
|
|
1086
1993
|
);
|
|
1087
1994
|
if (remoteTests.length === 0) {
|
|
1088
1995
|
info(
|
|
1089
|
-
`No custom tests found in your dashboard. Create them at ${
|
|
1996
|
+
`No custom tests found in your dashboard. Create them at ${credentials.apiUrl}/tests`
|
|
1090
1997
|
);
|
|
1091
1998
|
} else {
|
|
1092
1999
|
info(`Loaded ${remoteTests.length} custom test(s) from dashboard`);
|
|
1093
2000
|
config.customTests = [...config.customTests ?? [], ...remoteTests];
|
|
2001
|
+
const seen = /* @__PURE__ */ new Set();
|
|
2002
|
+
const dupNames = [
|
|
2003
|
+
...new Set(
|
|
2004
|
+
config.customTests.map((t) => t.name).filter((n) => seen.has(n) ? true : (seen.add(n), false))
|
|
2005
|
+
)
|
|
2006
|
+
];
|
|
2007
|
+
if (dupNames.length > 0) {
|
|
2008
|
+
console.error(
|
|
2009
|
+
`Duplicate custom test name(s) after merging local + dashboard tests: ${dupNames.join(
|
|
2010
|
+
", "
|
|
2011
|
+
)}. Rename so every custom test name is unique.`
|
|
2012
|
+
);
|
|
2013
|
+
setExitCode(2);
|
|
2014
|
+
return;
|
|
2015
|
+
}
|
|
1094
2016
|
}
|
|
1095
2017
|
} catch (err) {
|
|
1096
2018
|
const msg = err instanceof Error ? err.message : "Unknown error";
|
|
@@ -1108,6 +2030,7 @@ async function scanCommand(opts) {
|
|
|
1108
2030
|
const includeCrescendo = customOnly ? false : config.includeCrescendo ?? config.preset === "full";
|
|
1109
2031
|
let attacks = [];
|
|
1110
2032
|
let multiTurnAttacks = [];
|
|
2033
|
+
let attackPackVersion;
|
|
1111
2034
|
if (customOnly) {
|
|
1112
2035
|
if (!config.customTests || config.customTests.length === 0) {
|
|
1113
2036
|
console.error(
|
|
@@ -1128,38 +2051,114 @@ async function scanCommand(opts) {
|
|
|
1128
2051
|
});
|
|
1129
2052
|
attacks = fetched.attacks;
|
|
1130
2053
|
multiTurnAttacks = fetched.multiTurnAttacks;
|
|
2054
|
+
attackPackVersion = fetched.attackPackVersion;
|
|
1131
2055
|
const multiTurnNote = fetched.multiTurnAttacks.length > 0 ? ` + ${fetched.multiTurnAttacks.length} multi-turn` : "";
|
|
1132
2056
|
info(
|
|
1133
2057
|
`Loaded ${fetched.attacks.length} attacks${multiTurnNote} from ${fetched.source} (catalog ${fetched.catalogVersion})`
|
|
1134
2058
|
);
|
|
1135
2059
|
}
|
|
2060
|
+
const target = buildTargetConfig(config);
|
|
2061
|
+
const catalogHash = computeCatalogHash([
|
|
2062
|
+
...(attacks ?? []).map((a) => a.id),
|
|
2063
|
+
...(multiTurnAttacks ?? []).map((a) => a.id),
|
|
2064
|
+
...(config.customTests ?? []).map((t) => `custom_${t.name}`)
|
|
2065
|
+
]);
|
|
2066
|
+
const scanKey = computeScanKey({
|
|
2067
|
+
target: target.url,
|
|
2068
|
+
preset: presetForScan,
|
|
2069
|
+
systemPromptHash: systemPrompt,
|
|
2070
|
+
catalogHash
|
|
2071
|
+
});
|
|
2072
|
+
const checkpointDir = opts.checkpointDir ?? resolve3(process.cwd(), ".shield-llm", "checkpoints");
|
|
2073
|
+
const checkpointStore = new FileCheckpointStore(
|
|
2074
|
+
resolve3(checkpointDir, `scan-${scanKey}.jsonl`)
|
|
2075
|
+
);
|
|
2076
|
+
if (opts.resume === false) {
|
|
2077
|
+
await checkpointStore.finalize();
|
|
2078
|
+
}
|
|
1136
2079
|
const scanOptions = {
|
|
1137
|
-
target
|
|
2080
|
+
target,
|
|
1138
2081
|
systemPrompt,
|
|
1139
2082
|
preset: presetForScan,
|
|
1140
2083
|
attacks,
|
|
1141
2084
|
multiTurnAttacks,
|
|
1142
2085
|
includeCrescendo,
|
|
1143
2086
|
customTests: config.customTests,
|
|
1144
|
-
concurrency:
|
|
2087
|
+
// Adaptive concurrency: 4-way by default (AIMD backs off on 429s),
|
|
2088
|
+
// overridable via config.concurrency. Set 1 for strictly sequential.
|
|
2089
|
+
concurrency: config.concurrency ?? 4,
|
|
1145
2090
|
delayMs: config.delayMs,
|
|
1146
2091
|
attackTimeoutMs: config.attackTimeoutMs,
|
|
1147
2092
|
maxConsecutiveFailures: config.maxConsecutiveFailures,
|
|
2093
|
+
maxRateLimitRetries: config.maxRateLimitRetries,
|
|
2094
|
+
rateLimitBackoffMs: config.rateLimitBackoffMs,
|
|
2095
|
+
rateLimitMaxBackoffMs: config.rateLimitMaxBackoffMs,
|
|
2096
|
+
checkpoint: checkpointStore,
|
|
1148
2097
|
evaluator
|
|
1149
2098
|
};
|
|
1150
2099
|
const onEvent = opts.progress !== false ? handleEvent : void 0;
|
|
1151
2100
|
const scanner = new Scanner(scanOptions, onEvent);
|
|
1152
2101
|
const report = await scanner.run();
|
|
2102
|
+
const attempted = report.attacks.length;
|
|
2103
|
+
const evaluated = report.attacks.filter(
|
|
2104
|
+
(a) => !a.error && !a.rateLimited
|
|
2105
|
+
).length;
|
|
2106
|
+
if (reservedScanId && attempted > 0 && evaluated === 0) {
|
|
2107
|
+
const errored = report.attacks.filter(
|
|
2108
|
+
(a) => a.error && !a.rateLimited
|
|
2109
|
+
).length;
|
|
2110
|
+
const rateLimited = report.attacks.filter((a) => a.rateLimited).length;
|
|
2111
|
+
const reason = `Target unreachable: 0/${attempted} attacks evaluated (${errored} errored, ${rateLimited} rate-limited)`;
|
|
2112
|
+
await reportScanFailure(credentials, reservedScanId, reason);
|
|
2113
|
+
scanFinalized = true;
|
|
2114
|
+
console.error(`Scan failed: ${reason}`);
|
|
2115
|
+
setExitCode(3);
|
|
2116
|
+
return;
|
|
2117
|
+
}
|
|
2118
|
+
let uploadedScanId = null;
|
|
1153
2119
|
try {
|
|
1154
2120
|
if (!reservedScanId) {
|
|
1155
2121
|
throw new Error(
|
|
1156
2122
|
"Missing scan reservation id (server returned no scanId)."
|
|
1157
2123
|
);
|
|
1158
2124
|
}
|
|
1159
|
-
await uploadReportToBackend(
|
|
2125
|
+
const authoritative = await uploadReportToBackend(
|
|
2126
|
+
report,
|
|
2127
|
+
credentials,
|
|
2128
|
+
reservedScanId,
|
|
2129
|
+
attackPackVersion
|
|
2130
|
+
);
|
|
2131
|
+
uploadedScanId = reservedScanId;
|
|
2132
|
+
scanFinalized = true;
|
|
2133
|
+
await checkpointStore.finalize();
|
|
2134
|
+
report.score = authoritative.score;
|
|
2135
|
+
report.grade = authoritative.grade;
|
|
2136
|
+
if (authoritative.droppedAttackIds > 0) {
|
|
2137
|
+
info(
|
|
2138
|
+
`Note: ${authoritative.droppedAttackIds} result(s) weren't in the backend catalogue (e.g. local custom tests) and were excluded from the saved score.`
|
|
2139
|
+
);
|
|
2140
|
+
}
|
|
1160
2141
|
} catch (err) {
|
|
1161
2142
|
const msg = err instanceof Error ? err.message : String(err);
|
|
1162
2143
|
console.warn(`Warning: Could not save scan to dashboard: ${msg}`);
|
|
2144
|
+
console.warn(
|
|
2145
|
+
"Showing the locally-computed score \u2014 it may differ from the dashboard."
|
|
2146
|
+
);
|
|
2147
|
+
}
|
|
2148
|
+
const benchmarkEligible = presetForScan === "full" && !customOnly && (config.customTests?.length ?? 0) === 0 && attackPackVersion !== void 0;
|
|
2149
|
+
if (opts.consent || benchmarkEligible) {
|
|
2150
|
+
info(
|
|
2151
|
+
benchmarkEligible ? `Benchmark: scan is eligible (full preset, attack pack v${attackPackVersion})` : `Benchmark: scan is NOT eligible (requires the full preset with no custom tests)`
|
|
2152
|
+
);
|
|
2153
|
+
}
|
|
2154
|
+
if (opts.consent && uploadedScanId) {
|
|
2155
|
+
if (opts.ci) {
|
|
2156
|
+
info(
|
|
2157
|
+
"Benchmark: --consent is interactive and is skipped in --ci mode. Use `shield-llm benchmark submit --yes` instead."
|
|
2158
|
+
);
|
|
2159
|
+
} else {
|
|
2160
|
+
await interactiveSubmitFlow(credentials, uploadedScanId, info);
|
|
2161
|
+
}
|
|
1163
2162
|
}
|
|
1164
2163
|
let thresholdResult = evaluateThresholds(report, config.thresholds);
|
|
1165
2164
|
if (!opts.ci) {
|
|
@@ -1193,7 +2192,7 @@ async function scanCommand(opts) {
|
|
|
1193
2192
|
if (format === "pdf") {
|
|
1194
2193
|
const pdfPath = outputFile ?? `shield-report-${report.id.slice(0, 8)}.pdf`;
|
|
1195
2194
|
const pdfBuffer = await generatePdf(report);
|
|
1196
|
-
|
|
2195
|
+
writeFileSync5(resolve3(pdfPath), pdfBuffer);
|
|
1197
2196
|
info(`PDF report written to ${pdfPath}`);
|
|
1198
2197
|
} else {
|
|
1199
2198
|
let content;
|
|
@@ -1214,7 +2213,7 @@ async function scanCommand(opts) {
|
|
|
1214
2213
|
break;
|
|
1215
2214
|
}
|
|
1216
2215
|
if (outputFile) {
|
|
1217
|
-
|
|
2216
|
+
writeFileSync5(resolve3(outputFile), content, "utf-8");
|
|
1218
2217
|
info(`Report written to ${outputFile}`);
|
|
1219
2218
|
} else {
|
|
1220
2219
|
console.log(content);
|
|
@@ -1229,7 +2228,7 @@ async function scanCommand(opts) {
|
|
|
1229
2228
|
thresholds: thresholdResult,
|
|
1230
2229
|
compliance: complianceResult
|
|
1231
2230
|
});
|
|
1232
|
-
|
|
2231
|
+
writeFileSync5(jsonPath, jsonContent, "utf-8");
|
|
1233
2232
|
info(
|
|
1234
2233
|
`JSON copy written to ${jsonPath}${opts.includeFullPayloads ? " (full payloads)" : " (sanitized)"}`
|
|
1235
2234
|
);
|
|
@@ -1237,6 +2236,10 @@ async function scanCommand(opts) {
|
|
|
1237
2236
|
setExitCode(thresholdResult.passed ? 0 : 1);
|
|
1238
2237
|
return;
|
|
1239
2238
|
} catch (error) {
|
|
2239
|
+
if (failTarget && reservedScanId && !scanFinalized) {
|
|
2240
|
+
const reason = error instanceof ConfigError ? `Configuration error: ${error.message}` : `Scan run failed: ${error instanceof Error ? error.message : "Unknown error"}`;
|
|
2241
|
+
await reportScanFailure(failTarget, reservedScanId, reason);
|
|
2242
|
+
}
|
|
1240
2243
|
if (error instanceof ConfigError) {
|
|
1241
2244
|
console.error(`Configuration error: ${error.message}`);
|
|
1242
2245
|
setExitCode(2);
|
|
@@ -1265,9 +2268,8 @@ async function testConnectionCommand(opts) {
|
|
|
1265
2268
|
const target = buildTargetConfig(config);
|
|
1266
2269
|
const systemPrompt = loadSystemPrompt(config);
|
|
1267
2270
|
const message = opts.message ?? DEFAULT_MESSAGE;
|
|
1268
|
-
|
|
1269
|
-
|
|
1270
|
-
if (target.mode === "endpoint" && target.request.encoding) {
|
|
2271
|
+
console.log(`Target: ${target.url}`);
|
|
2272
|
+
if (target.request.encoding) {
|
|
1271
2273
|
console.log(`Encoding: ${target.request.encoding}`);
|
|
1272
2274
|
}
|
|
1273
2275
|
console.log(`Sending benign test message: "${message}"
|
|
@@ -1333,8 +2335,7 @@ async function testsCommand(opts) {
|
|
|
1333
2335
|
" shield-llm init Add tests to shield.config.json"
|
|
1334
2336
|
);
|
|
1335
2337
|
console.log(
|
|
1336
|
-
|
|
1337
|
-
`
|
|
2338
|
+
" Tests page on your dashboard Create tests in the web app\n"
|
|
1338
2339
|
);
|
|
1339
2340
|
return;
|
|
1340
2341
|
}
|
|
@@ -1383,7 +2384,7 @@ function validateCommand(opts) {
|
|
|
1383
2384
|
return;
|
|
1384
2385
|
} catch (error) {
|
|
1385
2386
|
if (error instanceof ConfigError) {
|
|
1386
|
-
console.error(
|
|
2387
|
+
console.error(error.message);
|
|
1387
2388
|
setExitCode(2);
|
|
1388
2389
|
return;
|
|
1389
2390
|
}
|
|
@@ -1405,22 +2406,31 @@ ${label}:`);
|
|
|
1405
2406
|
);
|
|
1406
2407
|
process.exit(3);
|
|
1407
2408
|
}
|
|
2409
|
+
function exitWithConfigError(err) {
|
|
2410
|
+
console.error(`Configuration error: ${err.message}`);
|
|
2411
|
+
process.exit(2);
|
|
2412
|
+
}
|
|
1408
2413
|
process.on("unhandledRejection", (reason) => {
|
|
2414
|
+
if (reason instanceof ConfigError) exitWithConfigError(reason);
|
|
1409
2415
|
reportFatal("Unhandled promise rejection", reason);
|
|
1410
2416
|
});
|
|
1411
2417
|
process.on("uncaughtException", (err) => {
|
|
2418
|
+
if (err instanceof ConfigError) exitWithConfigError(err);
|
|
1412
2419
|
reportFatal("Uncaught exception", err);
|
|
1413
2420
|
});
|
|
1414
2421
|
var program = new Command();
|
|
1415
2422
|
program.exitOverride();
|
|
1416
|
-
program.name("shield-llm").description("AI chatbot security scanner \u2014 automated red teaming for LLMs").version(
|
|
2423
|
+
program.name("shield-llm").description("AI chatbot security scanner \u2014 automated red teaming for LLMs").version(version);
|
|
1417
2424
|
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(
|
|
1418
2425
|
"--response-field <path>",
|
|
1419
2426
|
"Dot-notation path to response text in JSON (default: response)"
|
|
1420
2427
|
).option(
|
|
1421
2428
|
"--request-body <json>",
|
|
1422
2429
|
"JSON request body template (use {{prompt}} placeholder)"
|
|
1423
|
-
).option(
|
|
2430
|
+
).option(
|
|
2431
|
+
"--preset <name>",
|
|
2432
|
+
"Scan preset (dev, quick, owasp, frontier, standard, full)"
|
|
2433
|
+
).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("--min-score <n>", "Minimum score threshold", parseFloat).option("--fail-on-critical", "Fail if any CRITICAL vulnerability found").option("-o, --output <format>", "Output format (json, markdown, sarif, pdf)").option("--output-file <path>", "Write report to file").option(
|
|
1424
2434
|
"--write-json <path>",
|
|
1425
2435
|
"Always write a parseable JSON copy here, regardless of --output (useful for CI to extract score/grade alongside SARIF)"
|
|
1426
2436
|
).option(
|
|
@@ -1442,7 +2452,46 @@ program.command("scan").description("Run a security scan against a target chatbo
|
|
|
1442
2452
|
).option(
|
|
1443
2453
|
"--api-url <url>",
|
|
1444
2454
|
"Backend API URL (overrides SHIELD_API_URL env var and stored credentials)"
|
|
2455
|
+
).option(
|
|
2456
|
+
"--consent",
|
|
2457
|
+
"After the scan, offer to contribute an anonymous aggregate to a benchmark cohort (interactive preview + explicit confirmation)"
|
|
2458
|
+
).option(
|
|
2459
|
+
"--no-resume",
|
|
2460
|
+
"Ignore any saved checkpoint and start fresh (the scan still checkpoints so it can resume if THIS run is interrupted)"
|
|
2461
|
+
).option(
|
|
2462
|
+
"--checkpoint-dir <path>",
|
|
2463
|
+
"Directory for resumable scan checkpoints (default: .shield-llm/checkpoints)"
|
|
1445
2464
|
).action(scanCommand);
|
|
2465
|
+
var benchmark = program.command("benchmark").description("Cohort benchmarking \u2014 consent, submission, relative position");
|
|
2466
|
+
benchmark.command("cohorts").description("List your cohorts, or create one with --create").option(
|
|
2467
|
+
"--create <name>",
|
|
2468
|
+
"Create a cohort pinned to the current attack pack version"
|
|
2469
|
+
).option("--k-min <n>", "K-anonymity threshold for --create (default 5)").option("--api-url <url>", "Backend API URL override").action(cohortsCommand);
|
|
2470
|
+
var consent = benchmark.command("consent").description("Manage an organization's contribution consent");
|
|
2471
|
+
consent.command("show").description(
|
|
2472
|
+
"Preview the EXACT payload a submission would send (nothing is sent)"
|
|
2473
|
+
).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);
|
|
2474
|
+
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(
|
|
2475
|
+
"--scope <scopes>",
|
|
2476
|
+
"Comma-separated: global_score,category_scores,segment_metadata"
|
|
2477
|
+
).requiredOption(
|
|
2478
|
+
"--by <identity>",
|
|
2479
|
+
"Identity/role with authority granting the consent"
|
|
2480
|
+
).option("--api-url <url>", "Backend API URL override").action(consentGrantCommand);
|
|
2481
|
+
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);
|
|
2482
|
+
benchmark.command("submit").description(
|
|
2483
|
+
"Contribute a scan's anonymous aggregate (preview + confirmation)"
|
|
2484
|
+
).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);
|
|
2485
|
+
benchmark.command("position").description(
|
|
2486
|
+
"Relative position of a score within the cohort (read-only; --offline for air-gapped)"
|
|
2487
|
+
).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(
|
|
2488
|
+
"--public-key <pem>",
|
|
2489
|
+
"Issuer public key PEM, pinned out-of-band (offline mode, REQUIRED)"
|
|
2490
|
+
).option("--api-url <url>", "Backend API URL override").action(positionCommand);
|
|
2491
|
+
var snapshot = benchmark.command("snapshot").description("Signed distribution snapshots for air-gapped positioning");
|
|
2492
|
+
snapshot.command("export").description(
|
|
2493
|
+
"Export the cohort's signed snapshot (segments under k_min are excluded)"
|
|
2494
|
+
).requiredOption("--cohort <id>", "Cohort id").option("--out <file>", "Output path (default ./snapshot.json)").option("--api-url <url>", "Backend API URL override").action(snapshotExportCommand);
|
|
1446
2495
|
program.command("init").description("Generate a shield.config.json interactively").action(initCommand);
|
|
1447
2496
|
program.command("attacks").description("List all available attacks (fetched from your backend)").option("--severity <level>", "Filter by severity").option("--api-url <url>", "Backend API URL override").action(attacksCommand);
|
|
1448
2497
|
program.command("presets").description("List available scan presets (fetched from your backend)").option("--api-url <url>", "Backend API URL override").action(presetsCommand);
|
|
@@ -1458,9 +2507,26 @@ program.command("test-connection").description(
|
|
|
1458
2507
|
"Benign message to send (default: a greeting)"
|
|
1459
2508
|
).action(testConnectionCommand);
|
|
1460
2509
|
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);
|
|
2510
|
+
program.command("retest <scanId>").description(
|
|
2511
|
+
"Replay the detected findings of a past scan against the target and record which are fixed (verified) vs still vulnerable"
|
|
2512
|
+
).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(
|
|
2513
|
+
"--response-field <path>",
|
|
2514
|
+
"Dot-notation path to response text in JSON (default: response)"
|
|
2515
|
+
).option(
|
|
2516
|
+
"--request-body <json>",
|
|
2517
|
+
"JSON request body template (use {{prompt}} placeholder)"
|
|
2518
|
+
).option(
|
|
2519
|
+
"--finding <attackId>",
|
|
2520
|
+
"Retest only this finding (attack id or name). Repeatable.",
|
|
2521
|
+
(value, previous) => [...previous, value],
|
|
2522
|
+
[]
|
|
2523
|
+
).option("--no-progress", "Disable progress spinner").option(
|
|
2524
|
+
"--ci",
|
|
2525
|
+
"CI mode: JSON to stdout, no spinner. Exit 0=all fixed, 1=still vulnerable, 2=config/auth, 3=infra"
|
|
2526
|
+
).option("--api-url <url>", "Backend API URL override").action(retestCommand);
|
|
1461
2527
|
program.command("login").description("Authenticate with your Shield LLM API key").requiredOption("--key <api-key>", "Your API key (sk_shield_...)").option(
|
|
1462
2528
|
"--api-url <url>",
|
|
1463
|
-
"
|
|
2529
|
+
"Your Shield LLM backend URL (or set the SHIELD_API_URL env var)"
|
|
1464
2530
|
).action(loginCommand);
|
|
1465
2531
|
program.command("logout").description("Remove stored API key credentials").action(logoutCommand);
|
|
1466
2532
|
try {
|
|
@@ -1470,5 +2536,8 @@ try {
|
|
|
1470
2536
|
const code = err.code === "commander.helpDisplayed" || err.code === "commander.version" ? 0 : 2;
|
|
1471
2537
|
process.exit(code);
|
|
1472
2538
|
}
|
|
2539
|
+
if (err instanceof ConfigError) {
|
|
2540
|
+
exitWithConfigError(err);
|
|
2541
|
+
}
|
|
1473
2542
|
reportFatal("Error", err);
|
|
1474
2543
|
}
|