shield-llm 0.12.3 → 0.13.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 +5 -11
- package/dist/{chunk-2YC6WMPX.js → chunk-S3XEHIPB.js} +3728 -6956
- package/dist/cli.js +412 -667
- package/dist/index.js +1 -3
- package/package.json +4 -4
- package/dist/logo.png +0 -0
package/dist/cli.js
CHANGED
|
@@ -3,7 +3,6 @@ import {
|
|
|
3
3
|
ATTACK_PACK_VERSION,
|
|
4
4
|
BENIGN_CORE_V1,
|
|
5
5
|
BENIGN_SUITE_ID,
|
|
6
|
-
CONSENT_SCOPES,
|
|
7
6
|
CROSSWALK_GAPS,
|
|
8
7
|
ConfigError,
|
|
9
8
|
ConfigSchema,
|
|
@@ -23,12 +22,13 @@ import {
|
|
|
23
22
|
RateLimitError,
|
|
24
23
|
RegexOnlyEvaluator,
|
|
25
24
|
Scanner,
|
|
25
|
+
VULN_TO_AGENTIC,
|
|
26
26
|
analyzeJudgeHealth,
|
|
27
27
|
articleNumberEn,
|
|
28
28
|
aspectArticleLabel,
|
|
29
29
|
attacksForContract,
|
|
30
30
|
baseAttackId,
|
|
31
|
-
|
|
31
|
+
buildEndpointOverride,
|
|
32
32
|
buildTargetConfig,
|
|
33
33
|
c,
|
|
34
34
|
calculateComplianceScore,
|
|
@@ -54,7 +54,6 @@ import {
|
|
|
54
54
|
formatSarif,
|
|
55
55
|
formatShareAboveLimit,
|
|
56
56
|
frameworkVersion,
|
|
57
|
-
generatePdf,
|
|
58
57
|
getCrosswalk,
|
|
59
58
|
getMutator,
|
|
60
59
|
getObligationProfile,
|
|
@@ -68,12 +67,9 @@ import {
|
|
|
68
67
|
missingForContract,
|
|
69
68
|
normalizeTargetUrl,
|
|
70
69
|
parseMaxUnjudgedPercent,
|
|
71
|
-
parseSegmentKey,
|
|
72
|
-
parseSnapshot,
|
|
73
70
|
recordVerification,
|
|
74
71
|
replaceLoneSurrogates,
|
|
75
72
|
resolveClaim,
|
|
76
|
-
resolveOfflinePosition,
|
|
77
73
|
retestDedupKey,
|
|
78
74
|
serializeAttack,
|
|
79
75
|
sha256Hex,
|
|
@@ -81,7 +77,7 @@ import {
|
|
|
81
77
|
summarizeObfuscationVariants,
|
|
82
78
|
version,
|
|
83
79
|
withoutScoredApartVariants
|
|
84
|
-
} from "./chunk-
|
|
80
|
+
} from "./chunk-S3XEHIPB.js";
|
|
85
81
|
|
|
86
82
|
// src/load-env.ts
|
|
87
83
|
try {
|
|
@@ -160,6 +156,58 @@ function getCredentialsPath() {
|
|
|
160
156
|
return getCredentialsFile();
|
|
161
157
|
}
|
|
162
158
|
|
|
159
|
+
// src/lib/exit.ts
|
|
160
|
+
function setExitCode(code) {
|
|
161
|
+
process.exitCode = code;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
// src/lib/account-suspended.ts
|
|
165
|
+
var ACCOUNT_SUSPENDED_CODE = "account_suspended";
|
|
166
|
+
function instanceName(apiUrl) {
|
|
167
|
+
try {
|
|
168
|
+
const host = new URL(apiUrl).host;
|
|
169
|
+
if (host) return host;
|
|
170
|
+
} catch {
|
|
171
|
+
}
|
|
172
|
+
return "this Shield instance";
|
|
173
|
+
}
|
|
174
|
+
function accountSuspendedMessage(apiUrl) {
|
|
175
|
+
return `Your account on ${instanceName(apiUrl)} is suspended: ask your Shield administrator.`;
|
|
176
|
+
}
|
|
177
|
+
var AccountSuspendedError = class extends Error {
|
|
178
|
+
constructor(apiUrl) {
|
|
179
|
+
super(accountSuspendedMessage(apiUrl));
|
|
180
|
+
this.apiUrl = apiUrl;
|
|
181
|
+
this.name = "AccountSuspendedError";
|
|
182
|
+
}
|
|
183
|
+
};
|
|
184
|
+
function isSuspendedBody(body) {
|
|
185
|
+
return typeof body === "object" && body !== null && body.code === ACCOUNT_SUSPENDED_CODE;
|
|
186
|
+
}
|
|
187
|
+
async function isAccountSuspended(res) {
|
|
188
|
+
if (res.status !== 403) return false;
|
|
189
|
+
try {
|
|
190
|
+
return isSuspendedBody(await res.clone().json());
|
|
191
|
+
} catch {
|
|
192
|
+
return false;
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
async function throwIfSuspended(res, apiUrl) {
|
|
196
|
+
if (await isAccountSuspended(res)) throw new AccountSuspendedError(apiUrl);
|
|
197
|
+
}
|
|
198
|
+
function reportAccountSuspended(err) {
|
|
199
|
+
if (!(err instanceof AccountSuspendedError)) return false;
|
|
200
|
+
console.error(err.message);
|
|
201
|
+
setExitCode(2);
|
|
202
|
+
return true;
|
|
203
|
+
}
|
|
204
|
+
async function reportIfSuspended(res, apiUrl) {
|
|
205
|
+
if (!await isAccountSuspended(res)) return false;
|
|
206
|
+
console.error(accountSuspendedMessage(apiUrl));
|
|
207
|
+
setExitCode(2);
|
|
208
|
+
return true;
|
|
209
|
+
}
|
|
210
|
+
|
|
163
211
|
// src/attacks-loader.ts
|
|
164
212
|
async function fetchAttacks(args) {
|
|
165
213
|
const params = new URLSearchParams({ preset: args.preset });
|
|
@@ -176,6 +224,7 @@ async function fetchAttacks(args) {
|
|
|
176
224
|
`Could not reach the Shield LLM backend at ${args.apiUrl} (${reason}). The CLI needs a backend connection to fetch the attack catalogue.`
|
|
177
225
|
);
|
|
178
226
|
}
|
|
227
|
+
await throwIfSuspended(res, args.apiUrl);
|
|
179
228
|
if (res.status === 401) {
|
|
180
229
|
throw new Error(
|
|
181
230
|
"API key is invalid or revoked. Run `shield-llm login` to re-authenticate."
|
|
@@ -208,11 +257,6 @@ async function fetchAttacks(args) {
|
|
|
208
257
|
}
|
|
209
258
|
}
|
|
210
259
|
|
|
211
|
-
// src/lib/exit.ts
|
|
212
|
-
function setExitCode(code) {
|
|
213
|
-
process.exitCode = code;
|
|
214
|
-
}
|
|
215
|
-
|
|
216
260
|
// src/commands/attacks.ts
|
|
217
261
|
async function attacksCommand(opts) {
|
|
218
262
|
const stored = loadCredentials();
|
|
@@ -231,6 +275,7 @@ async function attacksCommand(opts) {
|
|
|
231
275
|
includeMultiTurn: true
|
|
232
276
|
});
|
|
233
277
|
} catch (err) {
|
|
278
|
+
if (reportAccountSuspended(err)) return;
|
|
234
279
|
const msg = err instanceof Error ? err.message : "Unknown error";
|
|
235
280
|
console.error(`Failed to fetch attacks: ${msg}`);
|
|
236
281
|
setExitCode(3);
|
|
@@ -284,8 +329,9 @@ Attack catalogue \u2014 ${total} attack(s)${wanted ? ` (severity: ${wanted})` :
|
|
|
284
329
|
);
|
|
285
330
|
}
|
|
286
331
|
|
|
287
|
-
// src/commands/
|
|
288
|
-
import { writeFileSync as writeFileSync2 } from "fs";
|
|
332
|
+
// src/commands/init.ts
|
|
333
|
+
import { existsSync as existsSync2, writeFileSync as writeFileSync2 } from "fs";
|
|
334
|
+
import { resolve } from "path";
|
|
289
335
|
|
|
290
336
|
// src/lib/prompts.ts
|
|
291
337
|
import * as readline from "readline/promises";
|
|
@@ -358,475 +404,27 @@ async function select(opts) {
|
|
|
358
404
|
});
|
|
359
405
|
}
|
|
360
406
|
|
|
361
|
-
// src/benchmark/api.ts
|
|
362
|
-
var BenchmarkApiError = class extends Error {
|
|
363
|
-
constructor(status, body) {
|
|
364
|
-
const detail = typeof body.message === "string" ? body.message : typeof body.error === "string" ? body.error : `HTTP ${status}`;
|
|
365
|
-
super(detail);
|
|
366
|
-
this.name = "BenchmarkApiError";
|
|
367
|
-
this.status = status;
|
|
368
|
-
this.body = body;
|
|
369
|
-
}
|
|
370
|
-
};
|
|
371
|
-
async function request(creds, method, path, body) {
|
|
372
|
-
let res;
|
|
373
|
-
try {
|
|
374
|
-
res = await fetch(`${creds.apiUrl}${path}`, {
|
|
375
|
-
method,
|
|
376
|
-
headers: {
|
|
377
|
-
Authorization: `Bearer ${creds.apiKey}`,
|
|
378
|
-
// The /api/benchmark/* routes are dual-auth (browser session OR API
|
|
379
|
-
// key), so — unlike the API-key-only /api/cli/* routes — they are NOT
|
|
380
|
-
// exempt from the middleware's CSRF same-origin check. A non-browser
|
|
381
|
-
// client sends no Origin and is rejected with 403 "Invalid origin".
|
|
382
|
-
// Send Origin = the configured backend so the same-origin check passes.
|
|
383
|
-
// API-key auth carries no ambient-cookie CSRF risk, so this is safe.
|
|
384
|
-
Origin: new URL(creds.apiUrl).origin,
|
|
385
|
-
...body !== void 0 && { "Content-Type": "application/json" }
|
|
386
|
-
},
|
|
387
|
-
...body !== void 0 && { body: JSON.stringify(body) }
|
|
388
|
-
});
|
|
389
|
-
} catch (err) {
|
|
390
|
-
const reason = err instanceof Error ? err.message : "Unknown error";
|
|
391
|
-
throw new Error(
|
|
392
|
-
`Could not reach the Shield LLM backend at ${creds.apiUrl} (${reason}).`
|
|
393
|
-
);
|
|
394
|
-
}
|
|
395
|
-
const json = await res.json().catch(() => ({}));
|
|
396
|
-
if (!res.ok) {
|
|
397
|
-
if (res.status === 401) {
|
|
398
|
-
throw new BenchmarkApiError(401, {
|
|
399
|
-
error: "API key is invalid or revoked. Run `shield-llm login` to re-authenticate."
|
|
400
|
-
});
|
|
401
|
-
}
|
|
402
|
-
if (res.status === 404 && json.error === "Not found") {
|
|
403
|
-
throw new BenchmarkApiError(404, {
|
|
404
|
-
error: "Benchmark module is not enabled on this backend (NEXT_PUBLIC_MODULE_BENCHMARK)."
|
|
405
|
-
});
|
|
406
|
-
}
|
|
407
|
-
throw new BenchmarkApiError(res.status, json);
|
|
408
|
-
}
|
|
409
|
-
return json;
|
|
410
|
-
}
|
|
411
|
-
function listCohorts(creds) {
|
|
412
|
-
return request(
|
|
413
|
-
creds,
|
|
414
|
-
"GET",
|
|
415
|
-
"/api/benchmark/cohorts"
|
|
416
|
-
);
|
|
417
|
-
}
|
|
418
|
-
function createCohort(creds, args) {
|
|
419
|
-
return request(
|
|
420
|
-
creds,
|
|
421
|
-
"POST",
|
|
422
|
-
"/api/benchmark/cohorts",
|
|
423
|
-
args
|
|
424
|
-
);
|
|
425
|
-
}
|
|
426
|
-
function getCohort(creds, cohortId) {
|
|
427
|
-
return request(
|
|
428
|
-
creds,
|
|
429
|
-
"GET",
|
|
430
|
-
`/api/benchmark/cohorts/${encodeURIComponent(cohortId)}`
|
|
431
|
-
);
|
|
432
|
-
}
|
|
433
|
-
function grantConsent(creds, args) {
|
|
434
|
-
return request(
|
|
435
|
-
creds,
|
|
436
|
-
"POST",
|
|
437
|
-
`/api/benchmark/cohorts/${encodeURIComponent(args.cohortId)}/targets/${encodeURIComponent(args.targetId)}/consent`,
|
|
438
|
-
{ scopes: args.scopes, grantedBy: args.grantedBy }
|
|
439
|
-
);
|
|
440
|
-
}
|
|
441
|
-
function revokeConsent(creds, args) {
|
|
442
|
-
return request(
|
|
443
|
-
creds,
|
|
444
|
-
"DELETE",
|
|
445
|
-
`/api/benchmark/cohorts/${encodeURIComponent(args.cohortId)}/targets/${encodeURIComponent(args.targetId)}/consent`
|
|
446
|
-
);
|
|
447
|
-
}
|
|
448
|
-
function previewSubmission(creds, args) {
|
|
449
|
-
return request(
|
|
450
|
-
creds,
|
|
451
|
-
"POST",
|
|
452
|
-
`/api/benchmark/cohorts/${encodeURIComponent(args.cohortId)}/submissions/preview`,
|
|
453
|
-
{ scanId: args.scanId, targetId: args.targetId }
|
|
454
|
-
);
|
|
455
|
-
}
|
|
456
|
-
function submitAggregate(creds, args) {
|
|
457
|
-
return request(
|
|
458
|
-
creds,
|
|
459
|
-
"POST",
|
|
460
|
-
`/api/benchmark/cohorts/${encodeURIComponent(args.cohortId)}/submissions`,
|
|
461
|
-
{ scanId: args.scanId, targetId: args.targetId }
|
|
462
|
-
);
|
|
463
|
-
}
|
|
464
|
-
function exportSnapshot(creds, cohortId) {
|
|
465
|
-
return request(
|
|
466
|
-
creds,
|
|
467
|
-
"POST",
|
|
468
|
-
`/api/benchmark/cohorts/${encodeURIComponent(cohortId)}/snapshot`
|
|
469
|
-
);
|
|
470
|
-
}
|
|
471
|
-
function getPosition(creds, cohortId, query) {
|
|
472
|
-
const params = new URLSearchParams();
|
|
473
|
-
if ("scanId" in query) {
|
|
474
|
-
params.set("scanId", query.scanId);
|
|
475
|
-
params.set("targetId", query.targetId);
|
|
476
|
-
} else {
|
|
477
|
-
params.set("score", String(query.score));
|
|
478
|
-
params.set("segmentKey", query.segmentKey);
|
|
479
|
-
}
|
|
480
|
-
return request(
|
|
481
|
-
creds,
|
|
482
|
-
"GET",
|
|
483
|
-
`/api/benchmark/cohorts/${encodeURIComponent(cohortId)}/position?${params.toString()}`
|
|
484
|
-
);
|
|
485
|
-
}
|
|
486
|
-
|
|
487
|
-
// src/benchmark/format.ts
|
|
488
|
-
var LABELS = {
|
|
489
|
-
above_p75: "Reinforced posture (above the 3rd quartile)",
|
|
490
|
-
p25_p75: "Within cohort average",
|
|
491
|
-
below_p25: "Above-median exposure"
|
|
492
|
-
};
|
|
493
|
-
function ordinal(n) {
|
|
494
|
-
const rounded = Math.round(n);
|
|
495
|
-
const mod100 = rounded % 100;
|
|
496
|
-
if (mod100 >= 11 && mod100 <= 13) return `${rounded}th`;
|
|
497
|
-
switch (rounded % 10) {
|
|
498
|
-
case 1:
|
|
499
|
-
return `${rounded}st`;
|
|
500
|
-
case 2:
|
|
501
|
-
return `${rounded}nd`;
|
|
502
|
-
case 3:
|
|
503
|
-
return `${rounded}rd`;
|
|
504
|
-
default:
|
|
505
|
-
return `${rounded}th`;
|
|
506
|
-
}
|
|
507
|
-
}
|
|
508
|
-
function formatPosition(position, attackPackVersion) {
|
|
509
|
-
if (position.status === "insufficient_cohort") {
|
|
510
|
-
return `Benchmark building (N=${position.n}/${position.kMin}) \u2014 position unavailable below the k-anonymity threshold.`;
|
|
511
|
-
}
|
|
512
|
-
const percentile = position.clamped === "low" ? `\u2264 ${ordinal(position.percentile)} percentile` : position.clamped === "high" ? `\u2265 ${ordinal(position.percentile)} percentile` : `${ordinal(position.percentile)} percentile`;
|
|
513
|
-
const scope = position.generalizationLevel === 0 ? "exact segment" : position.segmentKey === "s1|*|*|*|*|*" ? "whole cohort" : `generalized segment ${position.segmentKey}`;
|
|
514
|
-
return [
|
|
515
|
-
`${percentile} \u2014 ${LABELS[position.labelKey] ?? position.labelKey}`,
|
|
516
|
-
`vs ${position.n} comparable organizations \xB7 ${scope} \xB7 attack pack v${attackPackVersion}`
|
|
517
|
-
].join("\n");
|
|
518
|
-
}
|
|
519
|
-
|
|
520
|
-
// src/benchmark/snapshot.ts
|
|
521
|
-
import { readFileSync as readFileSync2 } from "fs";
|
|
522
|
-
import { createPublicKey, verify } from "crypto";
|
|
523
|
-
function verifyAndLoadSnapshot(args) {
|
|
524
|
-
const bytes = readFileSync2(args.snapshotPath);
|
|
525
|
-
const signature = Buffer.from(
|
|
526
|
-
readFileSync2(args.signaturePath, "utf8").trim(),
|
|
527
|
-
"base64"
|
|
528
|
-
);
|
|
529
|
-
let publicKey;
|
|
530
|
-
try {
|
|
531
|
-
publicKey = createPublicKey(readFileSync2(args.publicKeyPath, "utf8"));
|
|
532
|
-
} catch (err) {
|
|
533
|
-
throw new Error(
|
|
534
|
-
`Could not load the public key at ${args.publicKeyPath}: ${err instanceof Error ? err.message : String(err)}`
|
|
535
|
-
);
|
|
536
|
-
}
|
|
537
|
-
if (publicKey.asymmetricKeyType !== "ed25519") {
|
|
538
|
-
throw new Error(
|
|
539
|
-
`Public key must be Ed25519 (got ${publicKey.asymmetricKeyType ?? "unknown"})`
|
|
540
|
-
);
|
|
541
|
-
}
|
|
542
|
-
const valid = verify(null, bytes, publicKey, signature);
|
|
543
|
-
if (!valid) {
|
|
544
|
-
throw new Error(
|
|
545
|
-
"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."
|
|
546
|
-
);
|
|
547
|
-
}
|
|
548
|
-
return parseSnapshot(JSON.parse(bytes.toString("utf8")));
|
|
549
|
-
}
|
|
550
|
-
|
|
551
|
-
// src/commands/benchmark.ts
|
|
552
|
-
function requireCreds(opts) {
|
|
553
|
-
const stored = loadCredentials();
|
|
554
|
-
if (!stored) {
|
|
555
|
-
console.error(
|
|
556
|
-
"Not authenticated. Run `shield-llm login --key <api-key>` first."
|
|
557
|
-
);
|
|
558
|
-
setExitCode(2);
|
|
559
|
-
return null;
|
|
560
|
-
}
|
|
561
|
-
return {
|
|
562
|
-
apiUrl: resolveApiUrl(stored.apiUrl, opts.apiUrl),
|
|
563
|
-
apiKey: stored.apiKey
|
|
564
|
-
};
|
|
565
|
-
}
|
|
566
|
-
function reportError(err) {
|
|
567
|
-
if (err instanceof BenchmarkApiError) {
|
|
568
|
-
console.error(`Error: ${err.message}`);
|
|
569
|
-
if (Array.isArray(err.body.reasons)) {
|
|
570
|
-
console.error(`Reasons: ${err.body.reasons.join(", ")}`);
|
|
571
|
-
}
|
|
572
|
-
if (Array.isArray(err.body.violations)) {
|
|
573
|
-
console.error(
|
|
574
|
-
`Violations: ${err.body.violations.join("; ")}`
|
|
575
|
-
);
|
|
576
|
-
}
|
|
577
|
-
setExitCode(2);
|
|
578
|
-
} else {
|
|
579
|
-
console.error(err instanceof Error ? err.message : String(err));
|
|
580
|
-
setExitCode(3);
|
|
581
|
-
}
|
|
582
|
-
}
|
|
583
|
-
function parseScopes(raw) {
|
|
584
|
-
const scopes = [];
|
|
585
|
-
for (const part of raw.split(",").map((s) => s.trim()).filter(Boolean)) {
|
|
586
|
-
const full = part.startsWith("contribute:") ? part : `contribute:${part}`;
|
|
587
|
-
if (!CONSENT_SCOPES.includes(full)) {
|
|
588
|
-
throw new Error(
|
|
589
|
-
`Unknown consent scope "${part}". Valid scopes: ` + CONSENT_SCOPES.map((s) => s.replace("contribute:", "")).join(", ")
|
|
590
|
-
);
|
|
591
|
-
}
|
|
592
|
-
scopes.push(full);
|
|
593
|
-
}
|
|
594
|
-
return scopes;
|
|
595
|
-
}
|
|
596
|
-
async function cohortsCommand(opts) {
|
|
597
|
-
const creds = requireCreds(opts);
|
|
598
|
-
if (!creds) return;
|
|
599
|
-
try {
|
|
600
|
-
if (opts.create) {
|
|
601
|
-
const created = await createCohort(creds, {
|
|
602
|
-
displayName: String(opts.create),
|
|
603
|
-
...opts.kMin !== void 0 && { kMin: Number(opts.kMin) }
|
|
604
|
-
});
|
|
605
|
-
console.log(
|
|
606
|
-
`Created cohort ${created.id} (attack pack v${created.activePackVersion}, k_min=${created.kMin})`
|
|
607
|
-
);
|
|
608
|
-
return;
|
|
609
|
-
}
|
|
610
|
-
const { cohorts } = await listCohorts(creds);
|
|
611
|
-
if (cohorts.length === 0) {
|
|
612
|
-
console.log(
|
|
613
|
-
"No cohorts yet. Create one with `shield-llm benchmark cohorts --create <name>`."
|
|
614
|
-
);
|
|
615
|
-
return;
|
|
616
|
-
}
|
|
617
|
-
for (const c2 of cohorts) {
|
|
618
|
-
console.log(
|
|
619
|
-
`${c2.id} ${c2.displayName} pack v${c2.activePackVersion} k_min=${c2.kMin} targets=${c2.targetCount} submissions=${c2.submissionCount}`
|
|
620
|
-
);
|
|
621
|
-
}
|
|
622
|
-
} catch (err) {
|
|
623
|
-
reportError(err);
|
|
624
|
-
}
|
|
625
|
-
}
|
|
626
|
-
async function consentShowCommand(opts) {
|
|
627
|
-
const creds = requireCreds(opts);
|
|
628
|
-
if (!creds) return;
|
|
629
|
-
try {
|
|
630
|
-
const preview = await previewSubmission(creds, {
|
|
631
|
-
cohortId: opts.cohort,
|
|
632
|
-
scanId: opts.scan,
|
|
633
|
-
targetId: opts.target
|
|
634
|
-
});
|
|
635
|
-
console.log("Exact payload that WOULD be submitted (nothing sent):");
|
|
636
|
-
console.log(JSON.stringify(preview.payload, null, 2));
|
|
637
|
-
if (preview.wouldReplace) {
|
|
638
|
-
console.log(
|
|
639
|
-
"Note: this would REPLACE the previous contribution of this organization for this attack pack version."
|
|
640
|
-
);
|
|
641
|
-
}
|
|
642
|
-
} catch (err) {
|
|
643
|
-
reportError(err);
|
|
644
|
-
}
|
|
645
|
-
}
|
|
646
|
-
async function consentGrantCommand(opts) {
|
|
647
|
-
const creds = requireCreds(opts);
|
|
648
|
-
if (!creds) return;
|
|
649
|
-
try {
|
|
650
|
-
const scopes = parseScopes(String(opts.scope ?? ""));
|
|
651
|
-
const granted = await grantConsent(creds, {
|
|
652
|
-
cohortId: opts.cohort,
|
|
653
|
-
targetId: opts.target,
|
|
654
|
-
scopes,
|
|
655
|
-
grantedBy: String(opts.by)
|
|
656
|
-
});
|
|
657
|
-
console.log(
|
|
658
|
-
`Consent recorded (${granted.id}) \u2014 scopes: ${granted.scopes.join(", ")}`
|
|
659
|
-
);
|
|
660
|
-
} catch (err) {
|
|
661
|
-
reportError(err);
|
|
662
|
-
}
|
|
663
|
-
}
|
|
664
|
-
async function consentRevokeCommand(opts) {
|
|
665
|
-
const creds = requireCreds(opts);
|
|
666
|
-
if (!creds) return;
|
|
667
|
-
try {
|
|
668
|
-
const result = await revokeConsent(creds, {
|
|
669
|
-
cohortId: opts.cohort,
|
|
670
|
-
targetId: opts.target
|
|
671
|
-
});
|
|
672
|
-
console.log(
|
|
673
|
-
result.revoked ? "Consent revoked. Future contributions are blocked until a new grant." : "No active consent to revoke."
|
|
674
|
-
);
|
|
675
|
-
} catch (err) {
|
|
676
|
-
reportError(err);
|
|
677
|
-
}
|
|
678
|
-
}
|
|
679
|
-
async function confirmAndSubmit(creds, args, opts = {}) {
|
|
680
|
-
const log = opts.log ?? console.log;
|
|
681
|
-
const preview = await previewSubmission(creds, args);
|
|
682
|
-
log("The following anonymous aggregate will be submitted to the cohort:");
|
|
683
|
-
log(JSON.stringify(preview.payload, null, 2));
|
|
684
|
-
if (preview.wouldReplace) {
|
|
685
|
-
log("This will REPLACE the organization's previous contribution.");
|
|
686
|
-
}
|
|
687
|
-
const approved = opts.yes === true ? true : await confirm({ message: "Submit this aggregate?", default: false });
|
|
688
|
-
if (!approved) {
|
|
689
|
-
log("Aborted \u2014 nothing was submitted. Your scan stays 100% local.");
|
|
690
|
-
return false;
|
|
691
|
-
}
|
|
692
|
-
const result = await submitAggregate(creds, args);
|
|
693
|
-
log(
|
|
694
|
-
result.replaced ? "Aggregate submitted (replaced the previous contribution)." : "Aggregate submitted."
|
|
695
|
-
);
|
|
696
|
-
return true;
|
|
697
|
-
}
|
|
698
|
-
async function submitCommand(opts) {
|
|
699
|
-
const creds = requireCreds(opts);
|
|
700
|
-
if (!creds) return;
|
|
701
|
-
try {
|
|
702
|
-
await confirmAndSubmit(
|
|
703
|
-
creds,
|
|
704
|
-
{ cohortId: opts.cohort, scanId: opts.scan, targetId: opts.target },
|
|
705
|
-
{ yes: Boolean(opts.yes) }
|
|
706
|
-
);
|
|
707
|
-
} catch (err) {
|
|
708
|
-
reportError(err);
|
|
709
|
-
}
|
|
710
|
-
}
|
|
711
|
-
async function positionCommand(opts) {
|
|
712
|
-
if (opts.offline || opts.snapshot) {
|
|
713
|
-
return offlinePositionCommand(opts);
|
|
714
|
-
}
|
|
715
|
-
const creds = requireCreds(opts);
|
|
716
|
-
if (!creds) return;
|
|
717
|
-
try {
|
|
718
|
-
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;
|
|
719
|
-
if (!query) {
|
|
720
|
-
console.error(
|
|
721
|
-
"Provide either --scan <id> --target <id>, or --score <n> --segment-key <key>."
|
|
722
|
-
);
|
|
723
|
-
setExitCode(2);
|
|
724
|
-
return;
|
|
725
|
-
}
|
|
726
|
-
const response = await getPosition(creds, opts.cohort, query);
|
|
727
|
-
if (response.scanEligibility && !response.scanEligibility.eligible) {
|
|
728
|
-
console.log(
|
|
729
|
-
`Warning: this scan is not benchmark-grade (${response.scanEligibility.reasons.join(", ")}) \u2014 position is indicative only.`
|
|
730
|
-
);
|
|
731
|
-
}
|
|
732
|
-
console.log(formatPosition(response.position, response.attackPackVersion));
|
|
733
|
-
} catch (err) {
|
|
734
|
-
reportError(err);
|
|
735
|
-
}
|
|
736
|
-
}
|
|
737
|
-
async function offlinePositionCommand(opts) {
|
|
738
|
-
try {
|
|
739
|
-
if (!opts.snapshot || !opts.publicKey) {
|
|
740
|
-
console.error(
|
|
741
|
-
"Offline mode requires --snapshot <file> and --public-key <pem> (pinned out-of-band)."
|
|
742
|
-
);
|
|
743
|
-
setExitCode(2);
|
|
744
|
-
return;
|
|
745
|
-
}
|
|
746
|
-
if (opts.score === void 0 || !opts.segmentKey) {
|
|
747
|
-
console.error(
|
|
748
|
-
"Offline mode requires --score <n> and --segment-key <key>."
|
|
749
|
-
);
|
|
750
|
-
setExitCode(2);
|
|
751
|
-
return;
|
|
752
|
-
}
|
|
753
|
-
const snapshot2 = verifyAndLoadSnapshot({
|
|
754
|
-
snapshotPath: String(opts.snapshot),
|
|
755
|
-
signaturePath: String(opts.sig ?? `${opts.snapshot}.sig`),
|
|
756
|
-
publicKeyPath: String(opts.publicKey)
|
|
757
|
-
});
|
|
758
|
-
console.log(
|
|
759
|
-
`Signature verified (Ed25519) \u2014 snapshot of ${snapshot2.computedAt}, attack pack v${snapshot2.attackPackVersion}.`
|
|
760
|
-
);
|
|
761
|
-
const position = resolveOfflinePosition(snapshot2, {
|
|
762
|
-
segment: parseSegmentKey(String(opts.segmentKey)),
|
|
763
|
-
score: Number(opts.score)
|
|
764
|
-
});
|
|
765
|
-
console.log(formatPosition(position, snapshot2.attackPackVersion));
|
|
766
|
-
} catch (err) {
|
|
767
|
-
console.error(err instanceof Error ? err.message : String(err));
|
|
768
|
-
setExitCode(2);
|
|
769
|
-
}
|
|
770
|
-
}
|
|
771
|
-
async function snapshotExportCommand(opts) {
|
|
772
|
-
const creds = requireCreds(opts);
|
|
773
|
-
if (!creds) return;
|
|
774
|
-
try {
|
|
775
|
-
const out = String(opts.out ?? "./snapshot.json");
|
|
776
|
-
const result = await exportSnapshot(creds, opts.cohort);
|
|
777
|
-
writeFileSync2(out, result.snapshotJson);
|
|
778
|
-
writeFileSync2(`${out}.sig`, result.signature + "\n");
|
|
779
|
-
writeFileSync2(`${out}.pub.pem`, result.publicKeyPem);
|
|
780
|
-
console.log(`Snapshot written: ${out} (+ .sig, + .pub.pem)`);
|
|
781
|
-
console.log(
|
|
782
|
-
"Distribute the public key through a separate, trusted channel and pin it on the verifying side."
|
|
783
|
-
);
|
|
784
|
-
} catch (err) {
|
|
785
|
-
reportError(err);
|
|
786
|
-
}
|
|
787
|
-
}
|
|
788
|
-
async function interactiveSubmitFlow(creds, scanId, log) {
|
|
789
|
-
try {
|
|
790
|
-
const { cohorts } = await listCohorts(creds);
|
|
791
|
-
if (cohorts.length === 0) {
|
|
792
|
-
log(
|
|
793
|
-
"Benchmark: no cohort on this backend \u2014 create one with `shield-llm benchmark cohorts --create <name>`."
|
|
794
|
-
);
|
|
795
|
-
return;
|
|
796
|
-
}
|
|
797
|
-
const cohortId = cohorts.length === 1 ? cohorts[0].id : await select({
|
|
798
|
-
message: "Cohort to contribute to:",
|
|
799
|
-
choices: cohorts.map((c2) => ({
|
|
800
|
-
name: `${c2.displayName} (pack v${c2.activePackVersion})`,
|
|
801
|
-
value: c2.id
|
|
802
|
-
}))
|
|
803
|
-
});
|
|
804
|
-
const detail = await getCohort(creds, cohortId);
|
|
805
|
-
if (detail.targets.length === 0) {
|
|
806
|
-
log(
|
|
807
|
-
"Benchmark: this cohort has no declared organizations yet \u2014 add targets in the dashboard or API first."
|
|
808
|
-
);
|
|
809
|
-
return;
|
|
810
|
-
}
|
|
811
|
-
const targetId = await select({
|
|
812
|
-
message: "Organization this scan belongs to:",
|
|
813
|
-
choices: detail.targets.map((t) => ({
|
|
814
|
-
name: `${t.displayName}${t.consent ? "" : " (no consent on record)"}`,
|
|
815
|
-
value: t.id
|
|
816
|
-
}))
|
|
817
|
-
});
|
|
818
|
-
await confirmAndSubmit(creds, { cohortId, scanId, targetId }, { log });
|
|
819
|
-
} catch (err) {
|
|
820
|
-
log(
|
|
821
|
-
`Benchmark submission skipped: ${err instanceof Error ? err.message : String(err)}`
|
|
822
|
-
);
|
|
823
|
-
}
|
|
824
|
-
}
|
|
825
|
-
|
|
826
407
|
// src/commands/init.ts
|
|
827
|
-
import { existsSync as existsSync2, writeFileSync as writeFileSync3 } from "fs";
|
|
828
|
-
import { resolve } from "path";
|
|
829
408
|
var CONFIG_FILENAME = "shield.config.json";
|
|
409
|
+
var METHOD_CHOICES = [
|
|
410
|
+
{ value: "POST", name: "POST (most chatbots)" },
|
|
411
|
+
{ value: "PUT", name: "PUT" },
|
|
412
|
+
{ value: "PATCH", name: "PATCH" }
|
|
413
|
+
];
|
|
414
|
+
var PRESET_CHOICES = [
|
|
415
|
+
{ value: "dev", name: "dev \u2014 Smoke test of the connection" },
|
|
416
|
+
{ value: "quick", name: "quick \u2014 Find flaws fast" },
|
|
417
|
+
{
|
|
418
|
+
value: "owasp",
|
|
419
|
+
name: "owasp \u2014 One test per OWASP LLM Top 10 category"
|
|
420
|
+
},
|
|
421
|
+
{ value: "frontier", name: "frontier \u2014 Recent attack techniques" },
|
|
422
|
+
{ value: "standard", name: "standard \u2014 Recommended" },
|
|
423
|
+
{
|
|
424
|
+
value: "full",
|
|
425
|
+
name: "full \u2014 Everything, multi-turn attacks included"
|
|
426
|
+
}
|
|
427
|
+
];
|
|
830
428
|
async function initCommand() {
|
|
831
429
|
console.log("\nShield LLM \u2014 Configuration wizard\n");
|
|
832
430
|
if (!process.stdin.isTTY) {
|
|
@@ -860,11 +458,7 @@ async function initCommand() {
|
|
|
860
458
|
});
|
|
861
459
|
const method = await select({
|
|
862
460
|
message: "HTTP method:",
|
|
863
|
-
choices:
|
|
864
|
-
{ value: "POST", name: "POST (most chatbots)" },
|
|
865
|
-
{ value: "GET", name: "GET" },
|
|
866
|
-
{ value: "PUT", name: "PUT" }
|
|
867
|
-
],
|
|
461
|
+
choices: METHOD_CHOICES,
|
|
868
462
|
default: "POST"
|
|
869
463
|
});
|
|
870
464
|
const auth = await collectAuth();
|
|
@@ -872,15 +466,7 @@ async function initCommand() {
|
|
|
872
466
|
const customHeaders = await collectCustomHeaders();
|
|
873
467
|
const preset = await select({
|
|
874
468
|
message: "Default scan preset:",
|
|
875
|
-
choices:
|
|
876
|
-
{ value: "owasp", name: "owasp \u2014 OWASP LLM Top 10 (10 tests)" },
|
|
877
|
-
{ value: "quick", name: "quick \u2014 Find flaws fast (7 tests)" },
|
|
878
|
-
{ value: "standard", name: "standard \u2014 Recommended (39 tests)" },
|
|
879
|
-
{
|
|
880
|
-
value: "full",
|
|
881
|
-
name: "full \u2014 Comprehensive (all tests + crescendo)"
|
|
882
|
-
}
|
|
883
|
-
],
|
|
469
|
+
choices: PRESET_CHOICES,
|
|
884
470
|
default: "standard"
|
|
885
471
|
});
|
|
886
472
|
const endpoint = {
|
|
@@ -910,7 +496,7 @@ ${issues}`);
|
|
|
910
496
|
setExitCode(3);
|
|
911
497
|
return;
|
|
912
498
|
}
|
|
913
|
-
|
|
499
|
+
writeFileSync2(configPath, JSON.stringify(result.data, null, 2) + "\n");
|
|
914
500
|
console.log(`
|
|
915
501
|
\u2713 Config written to ${CONFIG_FILENAME}
|
|
916
502
|
`);
|
|
@@ -1072,6 +658,7 @@ async function loginCommand(opts) {
|
|
|
1072
658
|
Authorization: `Bearer ${key}`
|
|
1073
659
|
}
|
|
1074
660
|
});
|
|
661
|
+
if (await reportIfSuspended(res, apiUrl)) return;
|
|
1075
662
|
if (res.status === 401) {
|
|
1076
663
|
console.error(
|
|
1077
664
|
"API key is invalid or revoked. Check the key and run `shield-llm login` again."
|
|
@@ -1113,6 +700,7 @@ async function presetsCommand(opts) {
|
|
|
1113
700
|
const res = await fetch(`${apiUrl}/api/cli/presets`, {
|
|
1114
701
|
headers: { Authorization: `Bearer ${stored.apiKey}` }
|
|
1115
702
|
});
|
|
703
|
+
if (await reportIfSuspended(res, apiUrl)) return;
|
|
1116
704
|
if (res.status === 401) {
|
|
1117
705
|
console.error(
|
|
1118
706
|
"API key is invalid or revoked. Run `shield-llm login` to re-authenticate."
|
|
@@ -1145,11 +733,11 @@ async function presetsCommand(opts) {
|
|
|
1145
733
|
}
|
|
1146
734
|
|
|
1147
735
|
// src/commands/report.ts
|
|
1148
|
-
import { writeFileSync as
|
|
736
|
+
import { writeFileSync as writeFileSync4 } from "fs";
|
|
1149
737
|
import { resolve as resolve2 } from "path";
|
|
1150
738
|
|
|
1151
739
|
// src/fix/claim-store.ts
|
|
1152
|
-
import { existsSync as existsSync3, mkdirSync as mkdirSync2, readFileSync as
|
|
740
|
+
import { existsSync as existsSync3, mkdirSync as mkdirSync2, readFileSync as readFileSync2, writeFileSync as writeFileSync3 } from "fs";
|
|
1153
741
|
import { dirname, join as join2 } from "path";
|
|
1154
742
|
var DEFAULT_CLAIM_FILE = ".shield-llm/claims.json";
|
|
1155
743
|
var ClaimStore = class _ClaimStore {
|
|
@@ -1161,7 +749,7 @@ var ClaimStore = class _ClaimStore {
|
|
|
1161
749
|
}
|
|
1162
750
|
load() {
|
|
1163
751
|
if (!existsSync3(this.path)) return null;
|
|
1164
|
-
return JSON.parse(
|
|
752
|
+
return JSON.parse(readFileSync2(this.path, "utf8"));
|
|
1165
753
|
}
|
|
1166
754
|
list() {
|
|
1167
755
|
return this.load()?.claims ?? [];
|
|
@@ -1224,7 +812,7 @@ var ClaimStore = class _ClaimStore {
|
|
|
1224
812
|
}
|
|
1225
813
|
write(file) {
|
|
1226
814
|
mkdirSync2(dirname(this.path), { recursive: true });
|
|
1227
|
-
|
|
815
|
+
writeFileSync3(this.path, `${JSON.stringify(file, null, 2)}
|
|
1228
816
|
`, "utf8");
|
|
1229
817
|
}
|
|
1230
818
|
};
|
|
@@ -1439,6 +1027,10 @@ async function reportCommand(scanId, opts) {
|
|
|
1439
1027
|
process.exitCode = 3;
|
|
1440
1028
|
return;
|
|
1441
1029
|
}
|
|
1030
|
+
if (await reportIfSuspended(res, apiUrl)) {
|
|
1031
|
+
await res.text().catch(() => void 0);
|
|
1032
|
+
return;
|
|
1033
|
+
}
|
|
1442
1034
|
if (res.status === 401) {
|
|
1443
1035
|
await res.text().catch(() => void 0);
|
|
1444
1036
|
console.error(
|
|
@@ -1468,7 +1060,7 @@ async function reportCommand(scanId, opts) {
|
|
|
1468
1060
|
content = JSON.stringify(withClaimStatus(scan, claims), null, 2);
|
|
1469
1061
|
}
|
|
1470
1062
|
if (opts.outputFile) {
|
|
1471
|
-
|
|
1063
|
+
writeFileSync4(resolve2(opts.outputFile), content, "utf-8");
|
|
1472
1064
|
console.error(`Report written to ${opts.outputFile}`);
|
|
1473
1065
|
} else {
|
|
1474
1066
|
console.log(content);
|
|
@@ -1482,6 +1074,7 @@ async function fetchCustomTests(apiUrl, apiKey) {
|
|
|
1482
1074
|
Authorization: `Bearer ${apiKey}`
|
|
1483
1075
|
}
|
|
1484
1076
|
});
|
|
1077
|
+
await throwIfSuspended(res, apiUrl);
|
|
1485
1078
|
if (res.status === 401) {
|
|
1486
1079
|
throw new Error(
|
|
1487
1080
|
"API key is invalid or revoked. Run `shield-llm login` to re-authenticate."
|
|
@@ -1529,10 +1122,32 @@ function truncateInput(input2) {
|
|
|
1529
1122
|
};
|
|
1530
1123
|
}
|
|
1531
1124
|
var TRANSIENT_STATUSES = /* @__PURE__ */ new Set([429, 502, 503, 504]);
|
|
1125
|
+
var CONNECTION_FAILURE_CODES = /* @__PURE__ */ new Set([
|
|
1126
|
+
"ECONNREFUSED",
|
|
1127
|
+
"ECONNRESET",
|
|
1128
|
+
"EPIPE",
|
|
1129
|
+
"ETIMEDOUT",
|
|
1130
|
+
"EAI_AGAIN",
|
|
1131
|
+
"UND_ERR_SOCKET",
|
|
1132
|
+
"UND_ERR_CLOSED",
|
|
1133
|
+
"UND_ERR_CONNECT_TIMEOUT"
|
|
1134
|
+
]);
|
|
1135
|
+
var CONNECTION_RETRY_DELAYS_MS = [2e3, 5e3, 1e4, 2e4];
|
|
1136
|
+
function connectionFailureCode(err) {
|
|
1137
|
+
if (!(err instanceof TypeError)) return void 0;
|
|
1138
|
+
const cause = err.cause;
|
|
1139
|
+
const code = cause?.code;
|
|
1140
|
+
return typeof code === "string" && CONNECTION_FAILURE_CODES.has(code) ? code : void 0;
|
|
1141
|
+
}
|
|
1532
1142
|
var BackendEvaluator = class {
|
|
1533
1143
|
constructor(apiUrl, apiKey, opts) {
|
|
1534
1144
|
this.apiUrl = apiUrl;
|
|
1535
1145
|
this.apiKey = apiKey;
|
|
1146
|
+
/**
|
|
1147
|
+
* Set once the backend refused a verdict because the account is suspended
|
|
1148
|
+
* (403 account_suspended). Sticky: every later call would be refused too.
|
|
1149
|
+
*/
|
|
1150
|
+
this.accountSuspended = false;
|
|
1536
1151
|
this.maxRetries = opts?.maxRetries ?? 3;
|
|
1537
1152
|
this.backoffMs = opts?.backoffMs ?? 1e3;
|
|
1538
1153
|
this.maxBackoffMs = opts?.maxBackoffMs ?? 3e4;
|
|
@@ -1540,6 +1155,7 @@ var BackendEvaluator = class {
|
|
|
1540
1155
|
this.sleep = opts?.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
|
|
1541
1156
|
}
|
|
1542
1157
|
async evaluate(input2) {
|
|
1158
|
+
if (this.accountSuspended) throw new AccountSuspendedError(this.apiUrl);
|
|
1543
1159
|
const body = JSON.stringify(truncateInput(input2));
|
|
1544
1160
|
let attempt = 0;
|
|
1545
1161
|
for (; ; ) {
|
|
@@ -1558,9 +1174,12 @@ var BackendEvaluator = class {
|
|
|
1558
1174
|
});
|
|
1559
1175
|
} catch (err) {
|
|
1560
1176
|
const isTimeout = err instanceof Error && (err.name === "TimeoutError" || err.name === "AbortError");
|
|
1561
|
-
|
|
1177
|
+
const connection = connectionFailureCode(err);
|
|
1178
|
+
if ((isTimeout || connection) && attempt < this.maxRetries) {
|
|
1562
1179
|
attempt++;
|
|
1563
|
-
await this.sleep(
|
|
1180
|
+
await this.sleep(
|
|
1181
|
+
connection ? CONNECTION_RETRY_DELAYS_MS[Math.min(attempt - 1, CONNECTION_RETRY_DELAYS_MS.length - 1)] : this.backoffFor(null, attempt - 1)
|
|
1182
|
+
);
|
|
1564
1183
|
continue;
|
|
1565
1184
|
}
|
|
1566
1185
|
if (isTimeout) {
|
|
@@ -1568,6 +1187,11 @@ var BackendEvaluator = class {
|
|
|
1568
1187
|
`Judge did not respond within ${this.requestTimeoutMs}ms after ${this.maxRetries} retries.`
|
|
1569
1188
|
);
|
|
1570
1189
|
}
|
|
1190
|
+
if (connection) {
|
|
1191
|
+
throw new Error(
|
|
1192
|
+
`Could not reach the Shield LLM backend at ${this.apiUrl} (${connection}) after ${this.maxRetries} retries.`
|
|
1193
|
+
);
|
|
1194
|
+
}
|
|
1571
1195
|
throw err;
|
|
1572
1196
|
}
|
|
1573
1197
|
if (TRANSIENT_STATUSES.has(response.status) && attempt < this.maxRetries) {
|
|
@@ -1583,6 +1207,10 @@ var BackendEvaluator = class {
|
|
|
1583
1207
|
}
|
|
1584
1208
|
if (response.status === 403) {
|
|
1585
1209
|
const errBody = await response.json().catch(() => ({}));
|
|
1210
|
+
if (isSuspendedBody(errBody)) {
|
|
1211
|
+
this.accountSuspended = true;
|
|
1212
|
+
throw new AccountSuspendedError(this.apiUrl);
|
|
1213
|
+
}
|
|
1586
1214
|
throw new Error(errBody.error ?? "Access denied by the backend (403).");
|
|
1587
1215
|
}
|
|
1588
1216
|
if (response.status === 429) {
|
|
@@ -1957,6 +1585,7 @@ async function retestCommand(scanId, opts) {
|
|
|
1957
1585
|
`${credentials.apiUrl}/api/cli/reports/${encodeURIComponent(scanId)}`,
|
|
1958
1586
|
{ headers: { Authorization: `Bearer ${credentials.apiKey}` } }
|
|
1959
1587
|
);
|
|
1588
|
+
if (await reportIfSuspended(res, credentials.apiUrl)) return;
|
|
1960
1589
|
if (res.status === 401) {
|
|
1961
1590
|
await res.text().catch(() => void 0);
|
|
1962
1591
|
console.error(
|
|
@@ -2016,19 +1645,8 @@ async function retestCommand(scanId, opts) {
|
|
|
2016
1645
|
return;
|
|
2017
1646
|
}
|
|
2018
1647
|
const cliOverrides = {};
|
|
2019
|
-
|
|
2020
|
-
|
|
2021
|
-
url: opts.endpoint,
|
|
2022
|
-
auth: buildAuthFromFlags(opts),
|
|
2023
|
-
request: {
|
|
2024
|
-
method: "POST",
|
|
2025
|
-
body: opts.requestBody ? JSON.parse(opts.requestBody) : { message: "{{prompt}}" }
|
|
2026
|
-
},
|
|
2027
|
-
response: { field: opts.responseField ?? "response" },
|
|
2028
|
-
// Local testing against localhost / private IPs (opt-in).
|
|
2029
|
-
...opts.allowPrivateUrls ? { allowPrivateUrls: true } : {}
|
|
2030
|
-
};
|
|
2031
|
-
}
|
|
1648
|
+
const endpoint = buildEndpointOverride(opts);
|
|
1649
|
+
if (endpoint) cliOverrides.endpoint = endpoint;
|
|
2032
1650
|
const config = loadConfig({ configPath: opts.config, cliOverrides });
|
|
2033
1651
|
const systemPrompt = loadSystemPrompt(config);
|
|
2034
1652
|
const endpointHost = safeHostname(config.endpoint?.url);
|
|
@@ -2055,6 +1673,7 @@ async function retestCommand(scanId, opts) {
|
|
|
2055
1673
|
customTests: needsCustom ? await fetchCustomTests(credentials.apiUrl, credentials.apiKey) : []
|
|
2056
1674
|
};
|
|
2057
1675
|
} catch (err) {
|
|
1676
|
+
if (reportAccountSuspended(err)) return;
|
|
2058
1677
|
const msg = err instanceof Error ? err.message : "Unknown error";
|
|
2059
1678
|
console.error(`Failed to fetch the attack catalogue: ${msg}`);
|
|
2060
1679
|
setExitCode(3);
|
|
@@ -2106,8 +1725,12 @@ async function retestCommand(scanId, opts) {
|
|
|
2106
1725
|
const onEvent = opts.progress !== false ? handleEvent : void 0;
|
|
2107
1726
|
const scanner = new Scanner(scanOptions, onEvent);
|
|
2108
1727
|
const report = await scanner.run();
|
|
1728
|
+
if (evaluator.accountSuspended) {
|
|
1729
|
+
reportAccountSuspended(new AccountSuspendedError(credentials.apiUrl));
|
|
1730
|
+
return;
|
|
1731
|
+
}
|
|
2109
1732
|
const outcome = buildRetestOutcome(report.attacks, plan.findingByResultId);
|
|
2110
|
-
let
|
|
1733
|
+
let verify = null;
|
|
2111
1734
|
let verifyError = null;
|
|
2112
1735
|
if (outcome.verifications.length > 0) {
|
|
2113
1736
|
try {
|
|
@@ -2125,11 +1748,12 @@ async function retestCommand(scanId, opts) {
|
|
|
2125
1748
|
})
|
|
2126
1749
|
}
|
|
2127
1750
|
);
|
|
1751
|
+
if (await reportIfSuspended(res, credentials.apiUrl)) return;
|
|
2128
1752
|
if (!res.ok) {
|
|
2129
1753
|
const body = await res.text().catch(() => "");
|
|
2130
1754
|
verifyError = `HTTP ${res.status}: ${body.slice(0, 200)}`;
|
|
2131
1755
|
} else {
|
|
2132
|
-
|
|
1756
|
+
verify = await res.json();
|
|
2133
1757
|
}
|
|
2134
1758
|
} catch (err) {
|
|
2135
1759
|
verifyError = err instanceof Error ? err.message : "Unknown error";
|
|
@@ -2165,7 +1789,7 @@ async function retestCommand(scanId, opts) {
|
|
|
2165
1789
|
attackId: f.attackId,
|
|
2166
1790
|
name: f.name
|
|
2167
1791
|
})),
|
|
2168
|
-
verify:
|
|
1792
|
+
verify: verify ?? void 0,
|
|
2169
1793
|
verifyError: verifyError ?? void 0
|
|
2170
1794
|
},
|
|
2171
1795
|
null,
|
|
@@ -2195,13 +1819,13 @@ async function retestCommand(scanId, opts) {
|
|
|
2195
1819
|
console.log(
|
|
2196
1820
|
`Retest complete: ${fixed.length - variantsOpen.length} fixed & verified, ` + (variantsOpen.length ? `${variantsOpen.length} exploit closed but its fix not confirmed, ` : "") + `${stillVulnerable.length} still vulnerable` + (outcome.failed.length + plan.unavailable.length > 0 ? `, ${outcome.failed.length + plan.unavailable.length} not retested` : "") + "."
|
|
2197
1821
|
);
|
|
2198
|
-
if (
|
|
1822
|
+
if (verify) {
|
|
2199
1823
|
console.log(
|
|
2200
|
-
`Dashboard updated (${
|
|
1824
|
+
`Dashboard updated (${verify.updated} finding(s) stamped).`
|
|
2201
1825
|
);
|
|
2202
|
-
if (
|
|
1826
|
+
if (verify.notFound.length > 0) {
|
|
2203
1827
|
console.warn(
|
|
2204
|
-
`Warning: no matching dashboard row for: ${
|
|
1828
|
+
`Warning: no matching dashboard row for: ${verify.notFound.join(", ")}`
|
|
2205
1829
|
);
|
|
2206
1830
|
}
|
|
2207
1831
|
}
|
|
@@ -2223,6 +1847,7 @@ async function retestCommand(scanId, opts) {
|
|
|
2223
1847
|
);
|
|
2224
1848
|
return;
|
|
2225
1849
|
} catch (error) {
|
|
1850
|
+
if (reportAccountSuspended(error)) return;
|
|
2226
1851
|
if (error instanceof ConfigError) {
|
|
2227
1852
|
console.error(`Configuration error: ${error.message}`);
|
|
2228
1853
|
setExitCode(2);
|
|
@@ -2247,7 +1872,7 @@ function safeHostname(url) {
|
|
|
2247
1872
|
import { resolve as resolve5 } from "path";
|
|
2248
1873
|
|
|
2249
1874
|
// src/reporters/evidence.ts
|
|
2250
|
-
import { writeFileSync as
|
|
1875
|
+
import { writeFileSync as writeFileSync5 } from "fs";
|
|
2251
1876
|
import { resolve as resolve3 } from "path";
|
|
2252
1877
|
|
|
2253
1878
|
// ../../packages/shared/src/compliance/evidence-bundle.ts
|
|
@@ -2421,6 +2046,10 @@ function bundleLimitations(classification, noScoredEvidence = false) {
|
|
|
2421
2046
|
}
|
|
2422
2047
|
return base;
|
|
2423
2048
|
}
|
|
2049
|
+
function agenticOf(testId) {
|
|
2050
|
+
const category = VULN_TO_AGENTIC[testId];
|
|
2051
|
+
return category ? { agenticCategory: category } : {};
|
|
2052
|
+
}
|
|
2424
2053
|
function budgetedTests(tests) {
|
|
2425
2054
|
const spent = { bytes: 0 };
|
|
2426
2055
|
const excerpts = /* @__PURE__ */ new Map();
|
|
@@ -2447,6 +2076,7 @@ function budgetedTests(tests) {
|
|
|
2447
2076
|
excludedFromScore: t.excludedFromScore,
|
|
2448
2077
|
evaluationMethod: t.evaluationMethod,
|
|
2449
2078
|
confidence: t.confidence,
|
|
2079
|
+
...agenticOf(t.testId),
|
|
2450
2080
|
prompt: p.excerpt,
|
|
2451
2081
|
promptTruncated: p.truncated,
|
|
2452
2082
|
promptOmitted: p.omitted,
|
|
@@ -2634,7 +2264,7 @@ function writeEvidenceBundle(input2) {
|
|
|
2634
2264
|
});
|
|
2635
2265
|
const outPath = resolve3(input2.path);
|
|
2636
2266
|
const json = JSON.stringify(bundle, null, 2);
|
|
2637
|
-
|
|
2267
|
+
writeFileSync5(outPath, json, "utf8");
|
|
2638
2268
|
return {
|
|
2639
2269
|
path: outPath,
|
|
2640
2270
|
sha256: bundle.manifest.sha256,
|
|
@@ -2684,12 +2314,12 @@ function sanitizeReportForDisk(report, opts = {}) {
|
|
|
2684
2314
|
}
|
|
2685
2315
|
|
|
2686
2316
|
// src/lib/output-path.ts
|
|
2687
|
-
import { mkdirSync as mkdirSync3, writeFileSync as
|
|
2317
|
+
import { mkdirSync as mkdirSync3, writeFileSync as writeFileSync6 } from "fs";
|
|
2688
2318
|
import { dirname as dirname2, resolve as resolve4 } from "path";
|
|
2689
2319
|
function writeOutputFile(path, content) {
|
|
2690
2320
|
const full = resolve4(path);
|
|
2691
2321
|
mkdirSync3(dirname2(full), { recursive: true });
|
|
2692
|
-
|
|
2322
|
+
writeFileSync6(
|
|
2693
2323
|
full,
|
|
2694
2324
|
content,
|
|
2695
2325
|
typeof content === "string" ? "utf-8" : void 0
|
|
@@ -2846,6 +2476,10 @@ async function uploadReportToBackend(report, credentials, scanId, attackPackVers
|
|
|
2846
2476
|
body: JSON.stringify(payload)
|
|
2847
2477
|
});
|
|
2848
2478
|
if (!res.ok) {
|
|
2479
|
+
if (await isAccountSuspended(res)) {
|
|
2480
|
+
await res.text().catch(() => void 0);
|
|
2481
|
+
throw new AccountSuspendedError(credentials.apiUrl);
|
|
2482
|
+
}
|
|
2849
2483
|
const body = await res.text().catch(() => "");
|
|
2850
2484
|
const incomplete = incompleteRejection(res.status, body);
|
|
2851
2485
|
if (incomplete) throw new IncompleteRejection(incomplete);
|
|
@@ -2885,6 +2519,7 @@ async function reserveScanSlot(credentials, targetUrl) {
|
|
|
2885
2519
|
},
|
|
2886
2520
|
body: JSON.stringify({ targetUrl })
|
|
2887
2521
|
});
|
|
2522
|
+
if (await reportIfSuspended(res, credentials.apiUrl)) return null;
|
|
2888
2523
|
if (res.status === 401) {
|
|
2889
2524
|
console.error(
|
|
2890
2525
|
"API key is invalid or revoked. Run `shield-llm login` to re-authenticate."
|
|
@@ -2921,21 +2556,8 @@ function resolveMutateSelection(value) {
|
|
|
2921
2556
|
}
|
|
2922
2557
|
function buildCliOverrides(opts) {
|
|
2923
2558
|
const cliOverrides = {};
|
|
2924
|
-
|
|
2925
|
-
|
|
2926
|
-
url: opts.endpoint,
|
|
2927
|
-
auth: buildAuthFromFlags(opts),
|
|
2928
|
-
request: {
|
|
2929
|
-
method: "POST",
|
|
2930
|
-
body: opts.requestBody ? JSON.parse(opts.requestBody) : { message: "{{prompt}}" }
|
|
2931
|
-
},
|
|
2932
|
-
response: {
|
|
2933
|
-
field: opts.responseField ?? "response"
|
|
2934
|
-
},
|
|
2935
|
-
// Local testing against localhost / private IPs (opt-in).
|
|
2936
|
-
...opts.allowPrivateUrls ? { allowPrivateUrls: true } : {}
|
|
2937
|
-
};
|
|
2938
|
-
}
|
|
2559
|
+
const endpoint = buildEndpointOverride(opts);
|
|
2560
|
+
if (endpoint) cliOverrides.endpoint = endpoint;
|
|
2939
2561
|
if (opts.preset) cliOverrides.preset = opts.preset;
|
|
2940
2562
|
if (opts.systemPrompt) cliOverrides.systemPrompt = opts.systemPrompt;
|
|
2941
2563
|
if (opts.crescendo) cliOverrides.includeCrescendo = true;
|
|
@@ -2965,6 +2587,7 @@ function buildCliOverrides(opts) {
|
|
|
2965
2587
|
cliOverrides.maxNotExecutedPercent = opts.maxNotExecuted;
|
|
2966
2588
|
return cliOverrides;
|
|
2967
2589
|
}
|
|
2590
|
+
var PDF_FROM_DASHBOARD = "The CLI no longer writes PDF reports. Every scan is saved in your dashboard, which produces the official PDFs (security and compliance, English and French): open the scan there and use Download. For a file from the CLI, use -o json, -o markdown or -o sarif.";
|
|
2968
2591
|
async function scanCommand(opts) {
|
|
2969
2592
|
if (opts.mutate === "list") {
|
|
2970
2593
|
console.log("Available attack mutators (--mutate <ids>):\n");
|
|
@@ -2973,6 +2596,11 @@ async function scanCommand(opts) {
|
|
|
2973
2596
|
}
|
|
2974
2597
|
return;
|
|
2975
2598
|
}
|
|
2599
|
+
if (opts.output === "pdf") {
|
|
2600
|
+
console.error(PDF_FROM_DASHBOARD);
|
|
2601
|
+
setExitCode(2);
|
|
2602
|
+
return;
|
|
2603
|
+
}
|
|
2976
2604
|
let reservedScanId = null;
|
|
2977
2605
|
let scanFinalized = false;
|
|
2978
2606
|
let failTarget = null;
|
|
@@ -3036,6 +2664,7 @@ async function scanCommand(opts) {
|
|
|
3036
2664
|
}
|
|
3037
2665
|
}
|
|
3038
2666
|
} catch (err) {
|
|
2667
|
+
if (reportAccountSuspended(err)) return;
|
|
3039
2668
|
const msg = err instanceof Error ? err.message : "Unknown error";
|
|
3040
2669
|
console.error(`Failed to fetch custom tests: ${msg}`);
|
|
3041
2670
|
setExitCode(3);
|
|
@@ -3159,6 +2788,11 @@ async function scanCommand(opts) {
|
|
|
3159
2788
|
info("Scan started");
|
|
3160
2789
|
const scanner = new Scanner(scanOptions, onEvent);
|
|
3161
2790
|
const report = await scanner.run();
|
|
2791
|
+
if (evaluator.accountSuspended) {
|
|
2792
|
+
console.error(accountSuspendedMessage(credentials.apiUrl));
|
|
2793
|
+
setExitCode(2);
|
|
2794
|
+
return;
|
|
2795
|
+
}
|
|
3162
2796
|
const attempted = report.attacks.length;
|
|
3163
2797
|
const evaluated = scoredAttacks(report.attacks).length;
|
|
3164
2798
|
const nothingRan = report.stopReason === "not_executed" && evaluated === 0;
|
|
@@ -3207,6 +2841,7 @@ async function scanCommand(opts) {
|
|
|
3207
2841
|
);
|
|
3208
2842
|
}
|
|
3209
2843
|
} catch (err) {
|
|
2844
|
+
if (reportAccountSuspended(err)) return;
|
|
3210
2845
|
if (err instanceof IncompleteRejection) {
|
|
3211
2846
|
scanFinalized = true;
|
|
3212
2847
|
console.error(`Scan stopped: ${err.message}`);
|
|
@@ -3234,21 +2869,6 @@ async function scanCommand(opts) {
|
|
|
3234
2869
|
}
|
|
3235
2870
|
}
|
|
3236
2871
|
}
|
|
3237
|
-
const benchmarkEligible = presetForScan === "full" && !customOnly && (config.customTests?.length ?? 0) === 0 && attackPackVersion !== void 0;
|
|
3238
|
-
if (opts.consent || benchmarkEligible) {
|
|
3239
|
-
info(
|
|
3240
|
-
benchmarkEligible ? `Benchmark: scan is eligible (full preset, attack pack v${attackPackVersion})` : `Benchmark: scan is NOT eligible (requires the full preset with no custom tests)`
|
|
3241
|
-
);
|
|
3242
|
-
}
|
|
3243
|
-
if (opts.consent && uploadedScanId) {
|
|
3244
|
-
if (opts.ci) {
|
|
3245
|
-
info(
|
|
3246
|
-
"Benchmark: --consent is interactive and is skipped in --ci mode. Use `shield-llm benchmark submit --yes` instead."
|
|
3247
|
-
);
|
|
3248
|
-
} else {
|
|
3249
|
-
await interactiveSubmitFlow(credentials, uploadedScanId, info);
|
|
3250
|
-
}
|
|
3251
|
-
}
|
|
3252
2872
|
let thresholdResult = evaluateThresholds(report, config.thresholds);
|
|
3253
2873
|
const thresholdsConfigured = config.thresholds !== void 0 || opts.complianceThreshold !== void 0;
|
|
3254
2874
|
let evidenceBundleNote = "";
|
|
@@ -3305,8 +2925,16 @@ async function scanCommand(opts) {
|
|
|
3305
2925
|
);
|
|
3306
2926
|
}
|
|
3307
2927
|
}
|
|
3308
|
-
|
|
2928
|
+
let format = config.output?.format ?? opts.output;
|
|
3309
2929
|
let outputFile = config.output?.file ?? opts.outputFile;
|
|
2930
|
+
if (format === "pdf") {
|
|
2931
|
+
info(
|
|
2932
|
+
`The CLI no longer writes PDF reports. Download it from the dashboard` + (uploadedScanId ? `: ${credentials.apiUrl}/scans/${uploadedScanId}` : "") + `. Writing the JSON report instead.`
|
|
2933
|
+
);
|
|
2934
|
+
format = "json";
|
|
2935
|
+
if (outputFile)
|
|
2936
|
+
outputFile = alignOutputExtension(outputFile, "json").path;
|
|
2937
|
+
}
|
|
3310
2938
|
if (outputFile && format && opts.output && !opts.outputFile) {
|
|
3311
2939
|
const aligned = alignOutputExtension(outputFile, format);
|
|
3312
2940
|
if (aligned.changed) {
|
|
@@ -3317,16 +2945,13 @@ async function scanCommand(opts) {
|
|
|
3317
2945
|
}
|
|
3318
2946
|
}
|
|
3319
2947
|
if (format || outputFile) {
|
|
3320
|
-
|
|
3321
|
-
const pdfPath = outputFile ?? `shield-report-${report.id.slice(0, 8)}.pdf`;
|
|
3322
|
-
const pdfBuffer = await generatePdf(report);
|
|
3323
|
-
writeOutputFile(pdfPath, pdfBuffer);
|
|
3324
|
-
info(`PDF report written to ${pdfPath}`);
|
|
3325
|
-
} else {
|
|
2948
|
+
{
|
|
3326
2949
|
let content;
|
|
3327
2950
|
switch (format) {
|
|
3328
2951
|
case "sarif":
|
|
3329
|
-
content = formatSarif(report
|
|
2952
|
+
content = formatSarif(report, {
|
|
2953
|
+
docsBaseUrl: credentials.apiUrl
|
|
2954
|
+
});
|
|
3330
2955
|
break;
|
|
3331
2956
|
case "markdown":
|
|
3332
2957
|
content = formatMarkdown(report, thresholdResult, complianceResult);
|
|
@@ -3366,6 +2991,7 @@ async function scanCommand(opts) {
|
|
|
3366
2991
|
setExitCode(thresholdResult.passed ? 0 : 1);
|
|
3367
2992
|
return;
|
|
3368
2993
|
} catch (error) {
|
|
2994
|
+
if (reportAccountSuspended(error)) return;
|
|
3369
2995
|
if (failTarget && reservedScanId && !scanFinalized) {
|
|
3370
2996
|
const reason = error instanceof ConfigError ? `Configuration error: ${error.message}` : `Scan run failed: ${error instanceof Error ? error.message : "Unknown error"}`;
|
|
3371
2997
|
await reportScanFailure(failTarget, reservedScanId, reason);
|
|
@@ -3609,6 +3235,7 @@ async function testsCommand(opts) {
|
|
|
3609
3235
|
try {
|
|
3610
3236
|
remoteTests = await fetchCustomTests(apiUrl, stored.apiKey);
|
|
3611
3237
|
} catch (err) {
|
|
3238
|
+
if (reportAccountSuspended(err)) return;
|
|
3612
3239
|
const msg = err instanceof Error ? err.message : "Unknown error";
|
|
3613
3240
|
console.error(`Failed to fetch remote tests: ${msg}`);
|
|
3614
3241
|
setExitCode(3);
|
|
@@ -3685,12 +3312,12 @@ function validateCommand(opts) {
|
|
|
3685
3312
|
}
|
|
3686
3313
|
|
|
3687
3314
|
// src/commands/fix.ts
|
|
3688
|
-
import { existsSync as existsSync6, readFileSync as
|
|
3315
|
+
import { existsSync as existsSync6, readFileSync as readFileSync5, readdirSync } from "fs";
|
|
3689
3316
|
import { execFileSync as execFileSync3 } from "child_process";
|
|
3690
3317
|
import { resolve as resolve7 } from "path";
|
|
3691
3318
|
|
|
3692
3319
|
// src/fix/anchor-resolver.ts
|
|
3693
|
-
import { existsSync as existsSync4, readFileSync as
|
|
3320
|
+
import { existsSync as existsSync4, readFileSync as readFileSync3, statSync } from "fs";
|
|
3694
3321
|
import { isAbsolute, relative, resolve as resolve6, sep } from "path";
|
|
3695
3322
|
var AnchorError = class extends Error {
|
|
3696
3323
|
constructor(message, kind, status) {
|
|
@@ -3737,7 +3364,7 @@ function resolveAnchor(root, kind, anchor) {
|
|
|
3737
3364
|
);
|
|
3738
3365
|
}
|
|
3739
3366
|
if (anchor.export) {
|
|
3740
|
-
const source =
|
|
3367
|
+
const source = readFileSync3(abs, "utf8");
|
|
3741
3368
|
if (!declaresExport(source, anchor.export)) {
|
|
3742
3369
|
throw new AnchorError(
|
|
3743
3370
|
`${configHint}.export is "${anchor.export}" but ${anchor.file} does not declare it. (v1 resolves exports textually: a star re-export like \`export * from "./barrel"\` is not seen \u2014 point the anchor at the file that actually declares the symbol.)`,
|
|
@@ -3837,6 +3464,15 @@ function evaluateVerdict(input2, options = {}) {
|
|
|
3837
3464
|
|
|
3838
3465
|
// src/fix/plan.ts
|
|
3839
3466
|
var NO_RECIPE_DETAIL = `no v1 recipe covers these attacks: v1 patches ${RECIPES.flatMap((r) => r.appliesTo).join(", ")}; the others need a code or architecture change and become issues`;
|
|
3467
|
+
function unmatchedOnly(only, findings, targetUrl) {
|
|
3468
|
+
const known = new Set(
|
|
3469
|
+
findings.flatMap((f) => [
|
|
3470
|
+
f.attackId,
|
|
3471
|
+
fingerprintFromScan(targetUrl, f.attackId)
|
|
3472
|
+
])
|
|
3473
|
+
);
|
|
3474
|
+
return only.filter((id) => !known.has(id));
|
|
3475
|
+
}
|
|
3840
3476
|
function groupSkipped(skipped) {
|
|
3841
3477
|
const groups = /* @__PURE__ */ new Map();
|
|
3842
3478
|
for (const s of skipped) {
|
|
@@ -3860,7 +3496,13 @@ function buildPlan(findings, targetUrl, codebase, cwd, options = {}) {
|
|
|
3860
3496
|
for (const f of findings) {
|
|
3861
3497
|
const fingerprint = fingerprintFromScan(targetUrl, f.attackId);
|
|
3862
3498
|
if (wanted && !wanted.has(fingerprint) && !wanted.has(f.attackId)) continue;
|
|
3863
|
-
const push = (reason, detail) => skipped.push({
|
|
3499
|
+
const push = (reason, detail) => skipped.push({
|
|
3500
|
+
fingerprint,
|
|
3501
|
+
attackId: f.attackId,
|
|
3502
|
+
name: f.name,
|
|
3503
|
+
reason,
|
|
3504
|
+
detail
|
|
3505
|
+
});
|
|
3864
3506
|
const verdict = evaluateVerdict(
|
|
3865
3507
|
{
|
|
3866
3508
|
attackId: f.attackId,
|
|
@@ -3931,7 +3573,13 @@ function buildPlan(findings, targetUrl, codebase, cwd, options = {}) {
|
|
|
3931
3573
|
verdictDetail: verdict.detail
|
|
3932
3574
|
});
|
|
3933
3575
|
}
|
|
3934
|
-
return {
|
|
3576
|
+
return {
|
|
3577
|
+
targetId,
|
|
3578
|
+
planned,
|
|
3579
|
+
skipped,
|
|
3580
|
+
anchors,
|
|
3581
|
+
blockedByAnchor: blockedByAnchor(anchors)
|
|
3582
|
+
};
|
|
3935
3583
|
}
|
|
3936
3584
|
function languageCompatible(recipeLang, codebaseLang) {
|
|
3937
3585
|
if (recipeLang === codebaseLang) return true;
|
|
@@ -3942,14 +3590,22 @@ function blockedByAnchor(anchors) {
|
|
|
3942
3590
|
const out = [];
|
|
3943
3591
|
for (const [kind, res] of anchors) {
|
|
3944
3592
|
if (res.status === "resolved") continue;
|
|
3945
|
-
const ids = RECIPES.filter((r) => r.requiresAnchors.includes(kind)).map(
|
|
3593
|
+
const ids = RECIPES.filter((r) => r.requiresAnchors.includes(kind)).map(
|
|
3594
|
+
(r) => r.id
|
|
3595
|
+
);
|
|
3946
3596
|
if (ids.length) out.push({ kind, recipeIds: ids });
|
|
3947
3597
|
}
|
|
3948
3598
|
return out;
|
|
3949
3599
|
}
|
|
3950
3600
|
|
|
3951
3601
|
// src/fix/operations.ts
|
|
3952
|
-
import {
|
|
3602
|
+
import {
|
|
3603
|
+
existsSync as existsSync5,
|
|
3604
|
+
mkdirSync as mkdirSync4,
|
|
3605
|
+
readFileSync as readFileSync4,
|
|
3606
|
+
rmSync,
|
|
3607
|
+
writeFileSync as writeFileSync7
|
|
3608
|
+
} from "fs";
|
|
3953
3609
|
import { dirname as dirname3, relative as relative2 } from "path";
|
|
3954
3610
|
|
|
3955
3611
|
// src/fix/marker-block.ts
|
|
@@ -4117,18 +3773,22 @@ var WorkingSet = class {
|
|
|
4117
3773
|
const cached = this.files.get(relPath);
|
|
4118
3774
|
if (cached) return cached.current;
|
|
4119
3775
|
const abs = safeResolve(this.root, relPath);
|
|
4120
|
-
const before = existsSync5(abs) ?
|
|
3776
|
+
const before = existsSync5(abs) ? readFileSync4(abs, "utf8") : "";
|
|
4121
3777
|
this.files.set(relPath, { before, current: before });
|
|
4122
3778
|
return before;
|
|
4123
3779
|
}
|
|
4124
3780
|
write(relPath, next) {
|
|
4125
|
-
const entry = this.files.get(relPath) ?? {
|
|
3781
|
+
const entry = this.files.get(relPath) ?? {
|
|
3782
|
+
before: this.read(relPath),
|
|
3783
|
+
current: ""
|
|
3784
|
+
};
|
|
4126
3785
|
this.files.set(relPath, { before: entry.before, current: next });
|
|
4127
3786
|
}
|
|
4128
3787
|
changes(markerIds) {
|
|
4129
3788
|
const out = [];
|
|
4130
3789
|
for (const [path, { before, current }] of this.files) {
|
|
4131
|
-
if (before !== current)
|
|
3790
|
+
if (before !== current)
|
|
3791
|
+
out.push({ path, before, after: current, markerIds });
|
|
4132
3792
|
}
|
|
4133
3793
|
return out;
|
|
4134
3794
|
}
|
|
@@ -4141,7 +3801,7 @@ var WorkingSet = class {
|
|
|
4141
3801
|
continue;
|
|
4142
3802
|
}
|
|
4143
3803
|
mkdirSync4(dirname3(abs), { recursive: true });
|
|
4144
|
-
|
|
3804
|
+
writeFileSync7(abs, current, "utf8");
|
|
4145
3805
|
}
|
|
4146
3806
|
}
|
|
4147
3807
|
};
|
|
@@ -4186,12 +3846,17 @@ function recomposeEffective(source, effectiveExport) {
|
|
|
4186
3846
|
);
|
|
4187
3847
|
}
|
|
4188
3848
|
const composition = parseComposition(m[2].trim(), effectiveExport);
|
|
4189
|
-
const parts = composition.parts.filter(
|
|
3849
|
+
const parts = composition.parts.filter(
|
|
3850
|
+
(p) => !p.startsWith(GUARDRAIL_PREFIX)
|
|
3851
|
+
);
|
|
4190
3852
|
const guardrails = [
|
|
4191
3853
|
...new Set(
|
|
4192
3854
|
Array.from(
|
|
4193
3855
|
source.matchAll(
|
|
4194
|
-
new RegExp(
|
|
3856
|
+
new RegExp(
|
|
3857
|
+
`export\\s+const\\s+(${GUARDRAIL_PREFIX}[A-Z0-9_]+)\\s*=`,
|
|
3858
|
+
"g"
|
|
3859
|
+
)
|
|
4195
3860
|
),
|
|
4196
3861
|
(g) => g[1]
|
|
4197
3862
|
)
|
|
@@ -4202,7 +3867,10 @@ function recomposeEffective(source, effectiveExport) {
|
|
|
4202
3867
|
return source.replace(re, `$1${next};`);
|
|
4203
3868
|
}
|
|
4204
3869
|
function effectiveExportOffset(source, effectiveExport) {
|
|
4205
|
-
const m = new RegExp(
|
|
3870
|
+
const m = new RegExp(
|
|
3871
|
+
`^.*export\\s+const\\s+${effectiveExport}\\s*=`,
|
|
3872
|
+
"m"
|
|
3873
|
+
).exec(source);
|
|
4206
3874
|
if (!m) {
|
|
4207
3875
|
throw new Error(
|
|
4208
3876
|
`cannot place block: no \`export const ${effectiveExport} = \u2026\` in the anchored file`
|
|
@@ -4214,7 +3882,8 @@ function effectiveExportOffset(source, effectiveExport) {
|
|
|
4214
3882
|
if (prevEnd <= 0) break;
|
|
4215
3883
|
const prevStart = source.lastIndexOf("\n", prevEnd - 1) + 1;
|
|
4216
3884
|
const line = source.slice(prevStart, prevEnd).trim();
|
|
4217
|
-
if (!line.startsWith("//") && !line.startsWith("*") && !line.startsWith("/*"))
|
|
3885
|
+
if (!line.startsWith("//") && !line.startsWith("*") && !line.startsWith("/*"))
|
|
3886
|
+
break;
|
|
4218
3887
|
start = prevStart;
|
|
4219
3888
|
}
|
|
4220
3889
|
return start;
|
|
@@ -4222,7 +3891,9 @@ function effectiveExportOffset(source, effectiveExport) {
|
|
|
4222
3891
|
function anchorPath(ctx, kind) {
|
|
4223
3892
|
const res = ctx.anchors.get(kind);
|
|
4224
3893
|
if (!res || res.status !== "resolved" || !res.resolvedPath) {
|
|
4225
|
-
throw new Error(
|
|
3894
|
+
throw new Error(
|
|
3895
|
+
`anchor "${kind}" is not resolved \u2014 the recipe must not have been selected`
|
|
3896
|
+
);
|
|
4226
3897
|
}
|
|
4227
3898
|
return { rel: relative2(ctx.root, res.resolvedPath), abs: res.resolvedPath };
|
|
4228
3899
|
}
|
|
@@ -4247,7 +3918,10 @@ function applyOperation(op, recipe, ctx, ws) {
|
|
|
4247
3918
|
const state = src === "" ? "absent" : inspectBlock(src, op.path, recipe.id, body);
|
|
4248
3919
|
if (state === "drifted") throw new DriftError(op.path, recipe.id);
|
|
4249
3920
|
if (state === "identical") return true;
|
|
4250
|
-
ws.write(
|
|
3921
|
+
ws.write(
|
|
3922
|
+
op.path,
|
|
3923
|
+
appendBlock("", op.path, recipe.id, ctx.fingerprint, body)
|
|
3924
|
+
);
|
|
4251
3925
|
return false;
|
|
4252
3926
|
}
|
|
4253
3927
|
case "prompt-guardrail": {
|
|
@@ -4258,7 +3932,10 @@ function applyOperation(op, recipe, ctx, ws) {
|
|
|
4258
3932
|
const state = inspectBlock(src, rel, recipe.id, body);
|
|
4259
3933
|
if (state === "drifted") throw new DriftError(rel, recipe.id);
|
|
4260
3934
|
const effective = anchorExport(ctx, op.anchor);
|
|
4261
|
-
if (!effective)
|
|
3935
|
+
if (!effective)
|
|
3936
|
+
throw new Error(
|
|
3937
|
+
`anchor "${op.anchor}" declares no export to compose into`
|
|
3938
|
+
);
|
|
4262
3939
|
const withBlock = state === "identical" ? src : insertBlockAt(
|
|
4263
3940
|
src,
|
|
4264
3941
|
rel,
|
|
@@ -4289,20 +3966,30 @@ export function ${op.exportName}(...args) {
|
|
|
4289
3966
|
const foreign = foreignBlockOwning(withoutBlock, rel, recipe.id, declRe);
|
|
4290
3967
|
if (foreign) throw new WrapCollisionError(rel, op.exportName, foreign);
|
|
4291
3968
|
if (declRe.test(base)) {
|
|
4292
|
-
base = base.replace(
|
|
3969
|
+
base = base.replace(
|
|
3970
|
+
declRe,
|
|
3971
|
+
(_m, asyncKw) => `${asyncKw ?? ""}function ${op.renameTo}`
|
|
3972
|
+
);
|
|
4293
3973
|
} else if (!base.includes(`function ${op.renameTo}`)) {
|
|
4294
3974
|
throw new Error(
|
|
4295
3975
|
`cannot wrap: ${rel} declares neither \`export function ${op.exportName}\` nor the renamed \`${op.renameTo}\``
|
|
4296
3976
|
);
|
|
4297
3977
|
}
|
|
4298
|
-
const next = appendBlock(
|
|
3978
|
+
const next = appendBlock(
|
|
3979
|
+
base,
|
|
3980
|
+
rel,
|
|
3981
|
+
recipe.id,
|
|
3982
|
+
ctx.fingerprint,
|
|
3983
|
+
wrapperBody
|
|
3984
|
+
);
|
|
4299
3985
|
if (next === src) return true;
|
|
4300
3986
|
ws.write(rel, next);
|
|
4301
3987
|
return false;
|
|
4302
3988
|
}
|
|
4303
3989
|
case "add-dependency": {
|
|
4304
3990
|
const src = ws.read("package.json");
|
|
4305
|
-
if (!src)
|
|
3991
|
+
if (!src)
|
|
3992
|
+
throw new Error("add-dependency: no package.json at the codebase root");
|
|
4306
3993
|
const pkg = JSON.parse(src);
|
|
4307
3994
|
const field = op.dev ? "devDependencies" : "dependencies";
|
|
4308
3995
|
pkg[field] ??= {};
|
|
@@ -4342,7 +4029,10 @@ function revertRecipe(recipe, ctx) {
|
|
|
4342
4029
|
const { rel } = anchorPath(ctx, op.anchor);
|
|
4343
4030
|
const stripped = removeBlock(ws.read(rel), rel, recipe.id);
|
|
4344
4031
|
const effective = anchorExport(ctx, op.anchor);
|
|
4345
|
-
ws.write(
|
|
4032
|
+
ws.write(
|
|
4033
|
+
rel,
|
|
4034
|
+
effective ? recomposeEffective(stripped, effective) : stripped
|
|
4035
|
+
);
|
|
4346
4036
|
continue;
|
|
4347
4037
|
}
|
|
4348
4038
|
if (op.kind === "wrap-export") {
|
|
@@ -4607,7 +4297,8 @@ async function sync(opts) {
|
|
|
4607
4297
|
if (!creds?.apiKey || !creds.apiUrl) {
|
|
4608
4298
|
return { synced: false, reason: "not logged in" };
|
|
4609
4299
|
}
|
|
4610
|
-
const
|
|
4300
|
+
const apiUrl = resolveApiUrl(creds.apiUrl, opts.apiUrl);
|
|
4301
|
+
const url = `${apiUrl}/api/cli/claims`;
|
|
4611
4302
|
const doFetch = opts.fetchImpl ?? fetch;
|
|
4612
4303
|
let stored = 0;
|
|
4613
4304
|
let ignored = 0;
|
|
@@ -4635,6 +4326,12 @@ async function sync(opts) {
|
|
|
4635
4326
|
};
|
|
4636
4327
|
}
|
|
4637
4328
|
if (!res.ok) {
|
|
4329
|
+
if (await isAccountSuspended(res)) {
|
|
4330
|
+
return {
|
|
4331
|
+
synced: false,
|
|
4332
|
+
reason: accountSuspendedMessage(apiUrl).replace(/\.$/, "")
|
|
4333
|
+
};
|
|
4334
|
+
}
|
|
4638
4335
|
return {
|
|
4639
4336
|
synced: false,
|
|
4640
4337
|
reason: res.status === 404 ? "the dashboard holds no scan of this target for this account" : `HTTP ${res.status}`
|
|
@@ -4861,11 +4558,15 @@ async function captureBenignBaseline(target, scope, judge) {
|
|
|
4861
4558
|
try {
|
|
4862
4559
|
verdicts1 = await judgeBenign(run1, BENIGN_CORE_V1, judge, {
|
|
4863
4560
|
...opts,
|
|
4864
|
-
onProgress: phaseProgress(
|
|
4561
|
+
onProgress: phaseProgress(
|
|
4562
|
+
"Judging the answers before the patch, run 1/2"
|
|
4563
|
+
)
|
|
4865
4564
|
});
|
|
4866
4565
|
verdicts2 = await judgeBenign(run2, BENIGN_CORE_V1, judge, {
|
|
4867
4566
|
...opts,
|
|
4868
|
-
onProgress: phaseProgress(
|
|
4567
|
+
onProgress: phaseProgress(
|
|
4568
|
+
"Judging the answers before the patch, run 2/2"
|
|
4569
|
+
)
|
|
4869
4570
|
});
|
|
4870
4571
|
} catch (e) {
|
|
4871
4572
|
console.warn(
|
|
@@ -4957,15 +4658,24 @@ async function judgePatchedAnswers(baseline, cases, contract, target, judge) {
|
|
|
4957
4658
|
onProgress: phaseProgress("Legitimate questions after the patch")
|
|
4958
4659
|
});
|
|
4959
4660
|
const unchanged = unchangedVerdicts(baseline, after);
|
|
4960
|
-
|
|
4961
|
-
|
|
4962
|
-
|
|
4963
|
-
|
|
4964
|
-
|
|
4965
|
-
|
|
4966
|
-
|
|
4967
|
-
|
|
4968
|
-
|
|
4661
|
+
let judged;
|
|
4662
|
+
try {
|
|
4663
|
+
judged = await judgeBenign(
|
|
4664
|
+
after.filter((a) => !unchanged.has(a.name)),
|
|
4665
|
+
cases,
|
|
4666
|
+
judge,
|
|
4667
|
+
{
|
|
4668
|
+
votes: BENIGN_VOTES,
|
|
4669
|
+
onProgress: phaseProgress("Judging the answers that changed")
|
|
4670
|
+
}
|
|
4671
|
+
);
|
|
4672
|
+
} catch (e) {
|
|
4673
|
+
return {
|
|
4674
|
+
green: false,
|
|
4675
|
+
ran: false,
|
|
4676
|
+
detail: `the judge could not be reached (${e instanceof Error ? e.message : String(e)}), so the gate could not run`
|
|
4677
|
+
};
|
|
4678
|
+
}
|
|
4969
4679
|
const judgedByName = new Map(judged.map((r) => [r.name, r]));
|
|
4970
4680
|
const afterRun = after.map(
|
|
4971
4681
|
(a) => unchanged.get(a.name) ?? judgedByName.get(a.name)
|
|
@@ -5080,36 +4790,53 @@ function passDetail(baseline, cases, report, judged, afterRun) {
|
|
|
5080
4790
|
const scope = kept ? `${cases.length} cases, ${cases.length - kept} judged after the patch, ${kept} unchanged answer(s) kept their pre-patch verdict` : `${cases.length} cases judged`;
|
|
5081
4791
|
return `${scope}, ${report.flips.length} flip(s)${excluded}${splitNote}`;
|
|
5082
4792
|
}
|
|
5083
|
-
|
|
5084
|
-
|
|
5085
|
-
|
|
5086
|
-
|
|
5087
|
-
|
|
5088
|
-
// other CLI scan path does. See scanner-core/src/env.ts.
|
|
5089
|
-
resolveEnv: true,
|
|
5090
|
-
preset: "dev",
|
|
5091
|
-
attacks,
|
|
5092
|
-
evaluator,
|
|
5093
|
-
concurrency: 1,
|
|
5094
|
-
delayMs: 0,
|
|
5095
|
-
// Undefined keeps the scanner's default pause before its re-judge pass.
|
|
5096
|
-
judgeRetryDelayMs
|
|
5097
|
-
}).run();
|
|
4793
|
+
var DEFAULT_REPLAYS = 3;
|
|
4794
|
+
var MAX_REPLAYS = 10;
|
|
4795
|
+
async function replayFamily(contract, target, catalogue, evaluator, judgeRetryDelayMs, replays = DEFAULT_REPLAYS) {
|
|
4796
|
+
const runs = Math.min(Math.max(1, Math.floor(replays)), MAX_REPLAYS);
|
|
4797
|
+
let pending = attacksForContract(contract, catalogue);
|
|
5098
4798
|
const verdicts = /* @__PURE__ */ new Map();
|
|
5099
|
-
|
|
5100
|
-
|
|
5101
|
-
|
|
4799
|
+
let judgeDegraded = false;
|
|
4800
|
+
for (let run = 0; run < runs && pending.length > 0; run++) {
|
|
4801
|
+
const report = await new Scanner({
|
|
4802
|
+
target,
|
|
4803
|
+
// CLI-only: expand $VAR auth references from the environment, as every
|
|
4804
|
+
// other CLI scan path does. See scanner-core/src/env.ts.
|
|
4805
|
+
resolveEnv: true,
|
|
4806
|
+
preset: "dev",
|
|
4807
|
+
attacks: pending,
|
|
4808
|
+
evaluator,
|
|
4809
|
+
concurrency: 1,
|
|
4810
|
+
delayMs: 0,
|
|
4811
|
+
// Undefined keeps the scanner's default pause before its re-judge pass.
|
|
4812
|
+
judgeRetryDelayMs
|
|
4813
|
+
}).run();
|
|
4814
|
+
if (analyzeJudgeHealth(report).degraded) judgeDegraded = true;
|
|
4815
|
+
const stillClosed = /* @__PURE__ */ new Set();
|
|
4816
|
+
for (const a of report.attacks) {
|
|
4817
|
+
if (a.error || a.rateLimited) {
|
|
4818
|
+
verdicts.delete(a.id);
|
|
4819
|
+
continue;
|
|
4820
|
+
}
|
|
4821
|
+
verdicts.set(a.id, a.vulnerable);
|
|
4822
|
+
if (!a.vulnerable) stillClosed.add(a.id);
|
|
4823
|
+
}
|
|
4824
|
+
for (const a of pending) {
|
|
4825
|
+
if (!report.attacks.some((r) => r.id === a.id)) verdicts.delete(a.id);
|
|
4826
|
+
}
|
|
4827
|
+
pending = pending.filter((a) => stillClosed.has(a.id));
|
|
5102
4828
|
}
|
|
5103
|
-
return { verdicts, judgeDegraded:
|
|
4829
|
+
return { verdicts, judgeDegraded, replays: runs };
|
|
5104
4830
|
}
|
|
5105
4831
|
async function verifyLive(input2) {
|
|
5106
4832
|
const { contract } = input2;
|
|
5107
|
-
const { verdicts, judgeDegraded } = await replayFamily(
|
|
4833
|
+
const { verdicts, judgeDegraded, replays } = await replayFamily(
|
|
5108
4834
|
contract,
|
|
5109
4835
|
input2.target,
|
|
5110
4836
|
input2.catalogue,
|
|
5111
4837
|
input2.evaluator,
|
|
5112
|
-
input2.judgeRetryDelayMs
|
|
4838
|
+
input2.judgeRetryDelayMs,
|
|
4839
|
+
input2.replays
|
|
5113
4840
|
);
|
|
5114
4841
|
const cleared = (id) => verdicts.get(id) === false;
|
|
5115
4842
|
const executed = (id) => verdicts.has(id);
|
|
@@ -5142,6 +4869,7 @@ async function verifyLive(input2) {
|
|
|
5142
4869
|
},
|
|
5143
4870
|
judgeDegraded,
|
|
5144
4871
|
sessionIsolated: checkSessionIsolation(input2.target).isolated,
|
|
4872
|
+
replays,
|
|
5145
4873
|
passed
|
|
5146
4874
|
};
|
|
5147
4875
|
}
|
|
@@ -5390,7 +5118,7 @@ function dirtyPathsExcluding(cwd, ours) {
|
|
|
5390
5118
|
|
|
5391
5119
|
// src/fix/pr.ts
|
|
5392
5120
|
import { execFileSync as execFileSync2 } from "child_process";
|
|
5393
|
-
import { mkdtempSync, writeFileSync as
|
|
5121
|
+
import { mkdtempSync, writeFileSync as writeFileSync8 } from "fs";
|
|
5394
5122
|
import { tmpdir } from "os";
|
|
5395
5123
|
import { join as join3 } from "path";
|
|
5396
5124
|
function ghStatus(cwd) {
|
|
@@ -5417,7 +5145,7 @@ function ghStatus(cwd) {
|
|
|
5417
5145
|
function createPullRequest(input2) {
|
|
5418
5146
|
const dir = mkdtempSync(join3(tmpdir(), "shield-pr-"));
|
|
5419
5147
|
const bodyFile = join3(dir, "body.md");
|
|
5420
|
-
|
|
5148
|
+
writeFileSync8(bodyFile, input2.body, "utf8");
|
|
5421
5149
|
const args = [
|
|
5422
5150
|
"pr",
|
|
5423
5151
|
"create",
|
|
@@ -5623,7 +5351,9 @@ async function fetchStoredScan(apiUrl, apiKey, scanId) {
|
|
|
5623
5351
|
throw new Error(`Failed to reach the dashboard (${apiUrl}): ${msg}`);
|
|
5624
5352
|
}
|
|
5625
5353
|
if (!res.ok) {
|
|
5354
|
+
const suspended = await isAccountSuspended(res);
|
|
5626
5355
|
await res.text().catch(() => void 0);
|
|
5356
|
+
if (suspended) throw new AccountSuspendedError(apiUrl);
|
|
5627
5357
|
if (res.status === 401) {
|
|
5628
5358
|
throw new Error(
|
|
5629
5359
|
"API key invalid or revoked. Run `shield-llm login` to re-authenticate."
|
|
@@ -5690,7 +5420,8 @@ async function resolveCatalogue(opts) {
|
|
|
5690
5420
|
} catch (err) {
|
|
5691
5421
|
return {
|
|
5692
5422
|
attacks: null,
|
|
5693
|
-
reason: err instanceof Error ? err.message : "unknown error"
|
|
5423
|
+
reason: err instanceof Error ? err.message : "unknown error",
|
|
5424
|
+
suspended: err instanceof AccountSuspendedError
|
|
5694
5425
|
};
|
|
5695
5426
|
}
|
|
5696
5427
|
})();
|
|
@@ -5698,7 +5429,7 @@ async function resolveCatalogue(opts) {
|
|
|
5698
5429
|
return pending;
|
|
5699
5430
|
}
|
|
5700
5431
|
function findingsFromLocalReport(path) {
|
|
5701
|
-
const parsed = JSON.parse(
|
|
5432
|
+
const parsed = JSON.parse(readFileSync5(path, "utf8"));
|
|
5702
5433
|
const r = parsed.report;
|
|
5703
5434
|
if (!r?.attacks)
|
|
5704
5435
|
throw new Error(`${path} is not a shield-llm --write-json report`);
|
|
@@ -5850,6 +5581,14 @@ async function fixCommand(opts) {
|
|
|
5850
5581
|
setExitCode(2);
|
|
5851
5582
|
return;
|
|
5852
5583
|
}
|
|
5584
|
+
const unknownOnly = unmatchedOnly(opts.only ?? [], findings, targetUrl);
|
|
5585
|
+
if (unknownOnly.length) {
|
|
5586
|
+
console.error(
|
|
5587
|
+
`--only names no finding of this scan: ${unknownOnly.join(", ")}. Its findings: ${findings.map((f) => f.attackId).join(", ") || "none"}.`
|
|
5588
|
+
);
|
|
5589
|
+
setExitCode(2);
|
|
5590
|
+
return;
|
|
5591
|
+
}
|
|
5853
5592
|
let plan;
|
|
5854
5593
|
try {
|
|
5855
5594
|
plan = buildPlan(findings, targetUrl, codebase, cwd, {
|
|
@@ -5857,7 +5596,8 @@ async function fixCommand(opts) {
|
|
|
5857
5596
|
disagreementAvailable: findings.some(
|
|
5858
5597
|
(f) => f.disagreementResolution != null
|
|
5859
5598
|
),
|
|
5860
|
-
knownSecrets: config.endpoint?.knownSecrets
|
|
5599
|
+
knownSecrets: config.endpoint?.knownSecrets,
|
|
5600
|
+
only: opts.only
|
|
5861
5601
|
});
|
|
5862
5602
|
} catch (e) {
|
|
5863
5603
|
console.error(
|
|
@@ -6102,14 +5842,18 @@ The patch is applied but UNVERIFIED.`
|
|
|
6102
5842
|
\u26A0\uFE0F ${isolation.warning}
|
|
6103
5843
|
`);
|
|
6104
5844
|
const { evaluator, judgeAvailable } = resolveEvaluator(opts);
|
|
6105
|
-
const {
|
|
5845
|
+
const {
|
|
5846
|
+
attacks: catalogue,
|
|
5847
|
+
reason,
|
|
5848
|
+
suspended
|
|
5849
|
+
} = await resolveCatalogue(opts);
|
|
6106
5850
|
if (!catalogue) {
|
|
6107
5851
|
console.error(
|
|
6108
5852
|
`
|
|
6109
5853
|
Cannot verify: the attack catalogue could not be fetched (${reason}).
|
|
6110
5854
|
The patch is applied but UNVERIFIED \u2014 nothing was replayed against it.`
|
|
6111
5855
|
);
|
|
6112
|
-
setExitCode(3);
|
|
5856
|
+
setExitCode(suspended ? 2 : 3);
|
|
6113
5857
|
return "aborted";
|
|
6114
5858
|
}
|
|
6115
5859
|
if (!judgeAvailable && catalogue.some((a) => !a.detectPatterns?.length)) {
|
|
@@ -6132,7 +5876,8 @@ The patch is applied but UNVERIFIED \u2014 nothing was replayed against it.`
|
|
|
6132
5876
|
baseline,
|
|
6133
5877
|
assumeBenignGreen: opts.assumeBenignGreen,
|
|
6134
5878
|
redeployCommand: codebase.redeploy.command,
|
|
6135
|
-
nowMs: Date.now()
|
|
5879
|
+
nowMs: Date.now(),
|
|
5880
|
+
replays: opts.replays
|
|
6136
5881
|
});
|
|
6137
5882
|
evidence.set(p.fingerprint, v);
|
|
6138
5883
|
console.log(
|
|
@@ -6317,7 +6062,7 @@ function closurePathConfigured(root) {
|
|
|
6317
6062
|
if (!existsSync6(dir)) return false;
|
|
6318
6063
|
try {
|
|
6319
6064
|
return readdirSync(dir).some(
|
|
6320
|
-
(f) =>
|
|
6065
|
+
(f) => readFileSync5(resolve7(dir, f), "utf8").includes("verify-claims")
|
|
6321
6066
|
);
|
|
6322
6067
|
} catch {
|
|
6323
6068
|
return false;
|
|
@@ -6413,13 +6158,15 @@ async function verifyClaimsCommand(opts) {
|
|
|
6413
6158
|
}
|
|
6414
6159
|
const { catalogue } = resolved;
|
|
6415
6160
|
console.error(
|
|
6416
|
-
`Verifying ${claim.recipeId} (${pending.indexOf(claim) + 1}/${pending.length}): replaying ${claim.contract.designAttackIds.length + claim.contract.holdoutAttackIds.length} attack(s), then the legitimate questions\u2026`
|
|
6161
|
+
`Verifying ${claim.recipeId} (${pending.indexOf(claim) + 1}/${pending.length}): replaying ${claim.contract.designAttackIds.length + claim.contract.holdoutAttackIds.length} attack(s) up to ${opts.replays ?? DEFAULT_REPLAYS} times each, then the legitimate questions\u2026`
|
|
6417
6162
|
);
|
|
6418
|
-
const { verdicts, judgeDegraded } = await replayFamily(
|
|
6163
|
+
const { verdicts, judgeDegraded, replays } = await replayFamily(
|
|
6419
6164
|
claim.contract,
|
|
6420
6165
|
target,
|
|
6421
6166
|
catalogue,
|
|
6422
|
-
evaluator
|
|
6167
|
+
evaluator,
|
|
6168
|
+
void 0,
|
|
6169
|
+
opts.replays
|
|
6423
6170
|
);
|
|
6424
6171
|
const benign = await runBenignGate({
|
|
6425
6172
|
baseline: claim.benignBaseline,
|
|
@@ -6457,6 +6204,7 @@ async function verifyClaimsCommand(opts) {
|
|
|
6457
6204
|
},
|
|
6458
6205
|
judgeDegraded,
|
|
6459
6206
|
sessionIsolated: checkSessionIsolation(target).isolated,
|
|
6207
|
+
replays,
|
|
6460
6208
|
trigger: "verify-claims",
|
|
6461
6209
|
nowMs: now
|
|
6462
6210
|
});
|
|
@@ -6518,6 +6266,18 @@ function parsePercentArg(value) {
|
|
|
6518
6266
|
}
|
|
6519
6267
|
return n;
|
|
6520
6268
|
}
|
|
6269
|
+
function parseListArg(value) {
|
|
6270
|
+
return value.split(",").map((s) => s.trim()).filter(Boolean);
|
|
6271
|
+
}
|
|
6272
|
+
function parseReplaysArg(value) {
|
|
6273
|
+
const n = Number(value);
|
|
6274
|
+
if (!Number.isInteger(n) || n < 1 || n > MAX_REPLAYS) {
|
|
6275
|
+
throw new InvalidArgumentError(
|
|
6276
|
+
`Expected a whole number from 1 to ${MAX_REPLAYS}.`
|
|
6277
|
+
);
|
|
6278
|
+
}
|
|
6279
|
+
return n;
|
|
6280
|
+
}
|
|
6521
6281
|
function parseFloatArg(value) {
|
|
6522
6282
|
const n = Number.parseFloat(value);
|
|
6523
6283
|
if (Number.isNaN(n)) {
|
|
@@ -6553,7 +6313,10 @@ process.on("uncaughtException", (err) => {
|
|
|
6553
6313
|
var program = new Command();
|
|
6554
6314
|
program.exitOverride();
|
|
6555
6315
|
program.name("shield-llm").description("AI chatbot security scanner \u2014 automated red teaming for LLMs").version(version);
|
|
6556
|
-
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(
|
|
6316
|
+
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(
|
|
6317
|
+
"--auth <type>",
|
|
6318
|
+
"Auth type: bearer, api-key (OAuth2: set endpoint.auth in shield.config.json)"
|
|
6319
|
+
).option("--token <value>", "Bearer token or API key value").option("--auth-header <name>", "Custom auth header name (for api-key auth)").option(
|
|
6557
6320
|
"--response-field <path>",
|
|
6558
6321
|
"Dot-notation path to response text in JSON (default: response)"
|
|
6559
6322
|
).option(
|
|
@@ -6599,7 +6362,10 @@ program.command("scan").description("Run a security scan against a target chatbo
|
|
|
6599
6362
|
).option("--min-score <n>", "Minimum score threshold", parseFloat).option("--fail-on-critical", "Fail if any CRITICAL vulnerability found").option(
|
|
6600
6363
|
"--no-fail-on-critical",
|
|
6601
6364
|
"Report CRITICAL findings without failing the run"
|
|
6602
|
-
).option(
|
|
6365
|
+
).option(
|
|
6366
|
+
"-o, --output <format>",
|
|
6367
|
+
"Output format (json, markdown, sarif). PDF reports come from the dashboard"
|
|
6368
|
+
).option("--output-file <path>", "Write report to file").option(
|
|
6603
6369
|
"--write-json <path>",
|
|
6604
6370
|
"Always write a parseable JSON copy here, regardless of --output (useful for CI to extract score/grade alongside SARIF)"
|
|
6605
6371
|
).option(
|
|
@@ -6624,9 +6390,6 @@ program.command("scan").description("Run a security scan against a target chatbo
|
|
|
6624
6390
|
).option(
|
|
6625
6391
|
"--api-url <url>",
|
|
6626
6392
|
"Backend API URL (overrides SHIELD_API_URL env var and stored credentials)"
|
|
6627
|
-
).option(
|
|
6628
|
-
"--consent",
|
|
6629
|
-
"After the scan, offer to contribute an anonymous aggregate to a benchmark cohort (interactive preview + explicit confirmation)"
|
|
6630
6393
|
).option(
|
|
6631
6394
|
"--no-resume",
|
|
6632
6395
|
"Ignore any saved checkpoint and start fresh (the scan still checkpoints so it can resume if THIS run is interrupted)"
|
|
@@ -6634,36 +6397,6 @@ program.command("scan").description("Run a security scan against a target chatbo
|
|
|
6634
6397
|
"--checkpoint-dir <path>",
|
|
6635
6398
|
"Directory for resumable scan checkpoints (default: .shield-llm/checkpoints)"
|
|
6636
6399
|
).action(scanCommand);
|
|
6637
|
-
var benchmark = program.command("benchmark").description("Cohort benchmarking \u2014 consent, submission, relative position");
|
|
6638
|
-
benchmark.command("cohorts").description("List your cohorts, or create one with --create").option(
|
|
6639
|
-
"--create <name>",
|
|
6640
|
-
"Create a cohort pinned to the current attack pack version"
|
|
6641
|
-
).option("--k-min <n>", "K-anonymity threshold for --create (default 5)").option("--api-url <url>", "Backend API URL override").action(cohortsCommand);
|
|
6642
|
-
var consent = benchmark.command("consent").description("Manage an organization's contribution consent");
|
|
6643
|
-
consent.command("show").description(
|
|
6644
|
-
"Preview the EXACT payload a submission would send (nothing is sent)"
|
|
6645
|
-
).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);
|
|
6646
|
-
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(
|
|
6647
|
-
"--scope <scopes>",
|
|
6648
|
-
"Comma-separated: global_score,category_scores,segment_metadata"
|
|
6649
|
-
).requiredOption(
|
|
6650
|
-
"--by <identity>",
|
|
6651
|
-
"Identity/role with authority granting the consent"
|
|
6652
|
-
).option("--api-url <url>", "Backend API URL override").action(consentGrantCommand);
|
|
6653
|
-
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);
|
|
6654
|
-
benchmark.command("submit").description(
|
|
6655
|
-
"Contribute a scan's anonymous aggregate (preview + confirmation)"
|
|
6656
|
-
).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);
|
|
6657
|
-
benchmark.command("position").description(
|
|
6658
|
-
"Relative position of a score within the cohort (read-only; --offline for air-gapped)"
|
|
6659
|
-
).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(
|
|
6660
|
-
"--public-key <pem>",
|
|
6661
|
-
"Issuer public key PEM, pinned out-of-band (offline mode, REQUIRED)"
|
|
6662
|
-
).option("--api-url <url>", "Backend API URL override").action(positionCommand);
|
|
6663
|
-
var snapshot = benchmark.command("snapshot").description("Signed distribution snapshots for air-gapped positioning");
|
|
6664
|
-
snapshot.command("export").description(
|
|
6665
|
-
"Export the cohort's signed snapshot (segments under k_min are excluded)"
|
|
6666
|
-
).requiredOption("--cohort <id>", "Cohort id").option("--out <file>", "Output path (default ./snapshot.json)").option("--api-url <url>", "Backend API URL override").action(snapshotExportCommand);
|
|
6667
6400
|
program.command("init").description("Generate a shield.config.json interactively").action(initCommand);
|
|
6668
6401
|
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);
|
|
6669
6402
|
program.command("presets").description("List available scan presets (fetched from your backend)").option("--api-url <url>", "Backend API URL override").action(presetsCommand);
|
|
@@ -6677,6 +6410,10 @@ program.command("fix [scanId]").description(
|
|
|
6677
6410
|
"--explain",
|
|
6678
6411
|
"Show which recipes apply and which anchors would unlock more"
|
|
6679
6412
|
).option("--revert", "Remove every shield-llm block this recipe set owns").option(
|
|
6413
|
+
"--only <ids>",
|
|
6414
|
+
"Patch only these findings: attack ids or finding fingerprints, comma-separated (ship and verify one fix alone)",
|
|
6415
|
+
parseListArg
|
|
6416
|
+
).option(
|
|
6680
6417
|
"--min-confidence <n>",
|
|
6681
6418
|
"Override the verdict-gate threshold",
|
|
6682
6419
|
parseFloatArg
|
|
@@ -6698,6 +6435,10 @@ program.command("fix [scanId]").description(
|
|
|
6698
6435
|
).option(
|
|
6699
6436
|
"--assume-benign-green",
|
|
6700
6437
|
"Confirm without running the benign gate when no judge is configured (recorded on the claim)"
|
|
6438
|
+
).option(
|
|
6439
|
+
"--replays <n>",
|
|
6440
|
+
"Replay each attack n times; it counts as closed only if every replay is (default 3)",
|
|
6441
|
+
parseReplaysArg
|
|
6701
6442
|
).option(
|
|
6702
6443
|
"--rescan",
|
|
6703
6444
|
"After verifying, replay the original scan's attacks and report the score delta over a frozen denominator (informational \u2014 the holdout replay stays the gate)"
|
|
@@ -6723,6 +6464,10 @@ program.command("verify-claims").description(
|
|
|
6723
6464
|
"--deployed-at <iso>",
|
|
6724
6465
|
"Explicit deploy timestamp (implicit when run post-deploy)"
|
|
6725
6466
|
).option("--ci", "JSON output for pipelines").option(
|
|
6467
|
+
"--replays <n>",
|
|
6468
|
+
"Replay each attack n times; it counts as closed only if every replay is (default 3)",
|
|
6469
|
+
parseReplaysArg
|
|
6470
|
+
).option(
|
|
6726
6471
|
"--assume-benign-green",
|
|
6727
6472
|
"Confirm without running the benign gate when no judge is configured (recorded on the claim)"
|
|
6728
6473
|
).action(async (o) => {
|