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