shield-llm 0.14.0 → 0.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-EIO2SQEC.js → chunk-M7VCMWRI.js} +345 -37
- package/dist/cli.js +465 -11
- package/dist/index.js +1 -1
- package/package.json +1 -1
|
@@ -1307,9 +1307,9 @@ var RATE_LIMIT_PATTERNS = [
|
|
|
1307
1307
|
}
|
|
1308
1308
|
];
|
|
1309
1309
|
var RATE_LIMIT_SCAN_CHARS = 8192;
|
|
1310
|
-
function detectRateLimit(
|
|
1311
|
-
if (!
|
|
1312
|
-
const head =
|
|
1310
|
+
function detectRateLimit(text2) {
|
|
1311
|
+
if (!text2) return null;
|
|
1312
|
+
const head = text2.length > RATE_LIMIT_SCAN_CHARS ? text2.slice(0, RATE_LIMIT_SCAN_CHARS) : text2;
|
|
1313
1313
|
const run = guardedRun(() => {
|
|
1314
1314
|
for (const { pattern, platform } of RATE_LIMIT_PATTERNS) {
|
|
1315
1315
|
if (pattern.test(head)) return platform;
|
|
@@ -1321,13 +1321,13 @@ function detectRateLimit(text) {
|
|
|
1321
1321
|
|
|
1322
1322
|
// ../../packages/shared/src/unicode.ts
|
|
1323
1323
|
function replaceLoneSurrogates(input) {
|
|
1324
|
-
return input.replace(/[\uD800-\uDFFF]/g, (ch, index,
|
|
1324
|
+
return input.replace(/[\uD800-\uDFFF]/g, (ch, index, str3) => {
|
|
1325
1325
|
const code = ch.charCodeAt(0);
|
|
1326
1326
|
if (code <= 56319) {
|
|
1327
|
-
const next =
|
|
1327
|
+
const next = str3.charCodeAt(index + 1);
|
|
1328
1328
|
if (next >= 56320 && next <= 57343) return ch;
|
|
1329
1329
|
} else {
|
|
1330
|
-
const prev =
|
|
1330
|
+
const prev = str3.charCodeAt(index - 1);
|
|
1331
1331
|
if (prev >= 55296 && prev <= 56319) return ch;
|
|
1332
1332
|
}
|
|
1333
1333
|
return "\uFFFD";
|
|
@@ -8987,8 +8987,300 @@ function evaluateBenign(input) {
|
|
|
8987
8987
|
};
|
|
8988
8988
|
}
|
|
8989
8989
|
|
|
8990
|
+
// ../../packages/shared/src/supplemental/types.ts
|
|
8991
|
+
var IMPORT_SOURCES = ["promptfoo", "garak"];
|
|
8992
|
+
var IMPORT_LIMITS = {
|
|
8993
|
+
/** Attempts read from one file; the rest are reported as skipped. */
|
|
8994
|
+
maxAttemptsPerFile: 500,
|
|
8995
|
+
/** Supplemental rows one scan may hold (imports and packs together). */
|
|
8996
|
+
maxRowsPerScan: 1e3,
|
|
8997
|
+
/** Items per upload request: the server judges them inside the request. */
|
|
8998
|
+
batchSize: 10,
|
|
8999
|
+
maxTurns: 10,
|
|
9000
|
+
maxPromptChars: 1e4,
|
|
9001
|
+
maxResponseChars: 2e4,
|
|
9002
|
+
maxLabelChars: 200,
|
|
9003
|
+
maxObjectiveChars: 1e3,
|
|
9004
|
+
maxExternalIdChars: 200
|
|
9005
|
+
};
|
|
9006
|
+
|
|
9007
|
+
// ../../packages/shared/src/supplemental/import-promptfoo.ts
|
|
9008
|
+
var isObj = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
9009
|
+
var str = (v) => typeof v === "string" ? v : void 0;
|
|
9010
|
+
function text(v) {
|
|
9011
|
+
if (typeof v === "string") return v;
|
|
9012
|
+
if (v === void 0 || v === null) return "";
|
|
9013
|
+
try {
|
|
9014
|
+
return JSON.stringify(v);
|
|
9015
|
+
} catch {
|
|
9016
|
+
return String(v);
|
|
9017
|
+
}
|
|
9018
|
+
}
|
|
9019
|
+
function promptfooResults(doc) {
|
|
9020
|
+
if (!isObj(doc)) return null;
|
|
9021
|
+
const results = doc.results;
|
|
9022
|
+
if (Array.isArray(results)) return results;
|
|
9023
|
+
if (isObj(results) && Array.isArray(results.results)) return results.results;
|
|
9024
|
+
return null;
|
|
9025
|
+
}
|
|
9026
|
+
function turnsFromMessages(messages) {
|
|
9027
|
+
const turns = [];
|
|
9028
|
+
let pending = null;
|
|
9029
|
+
for (const m of messages) {
|
|
9030
|
+
if (!isObj(m)) continue;
|
|
9031
|
+
const role = str(m.role);
|
|
9032
|
+
const content = text(m.content);
|
|
9033
|
+
if (role === "user") {
|
|
9034
|
+
if (pending !== null) turns.push({ prompt: pending, response: "" });
|
|
9035
|
+
pending = content;
|
|
9036
|
+
} else if (role === "assistant" && pending !== null) {
|
|
9037
|
+
turns.push({ prompt: pending, response: content });
|
|
9038
|
+
pending = null;
|
|
9039
|
+
}
|
|
9040
|
+
}
|
|
9041
|
+
if (pending !== null) turns.push({ prompt: pending, response: "" });
|
|
9042
|
+
return turns;
|
|
9043
|
+
}
|
|
9044
|
+
function transcriptOf(r) {
|
|
9045
|
+
const response = isObj(r.response) ? r.response : {};
|
|
9046
|
+
const meta = isObj(response.metadata) ? response.metadata : {};
|
|
9047
|
+
const output = text(response.output);
|
|
9048
|
+
if (Array.isArray(meta.messages) && meta.messages.length > 0) {
|
|
9049
|
+
const turns = turnsFromMessages(meta.messages);
|
|
9050
|
+
const last = turns[turns.length - 1];
|
|
9051
|
+
if (last && !last.response && output) last.response = output;
|
|
9052
|
+
if (turns.length > 0) return turns;
|
|
9053
|
+
}
|
|
9054
|
+
const finalPrompt = str(meta.redteamFinalPrompt) ?? (isObj(r.prompt) ? str(r.prompt.raw) : void 0) ?? "";
|
|
9055
|
+
return [{ prompt: finalPrompt, response: output }];
|
|
9056
|
+
}
|
|
9057
|
+
function toolVerdictOf(r) {
|
|
9058
|
+
const grading = isObj(r.gradingResult) ? r.gradingResult : void 0;
|
|
9059
|
+
const pass = typeof grading?.pass === "boolean" ? grading.pass : typeof r.success === "boolean" ? r.success : void 0;
|
|
9060
|
+
if (pass === void 0) return void 0;
|
|
9061
|
+
return pass ? "safe" : "vulnerable";
|
|
9062
|
+
}
|
|
9063
|
+
function clipTurns(turns) {
|
|
9064
|
+
return turns.slice(-IMPORT_LIMITS.maxTurns).map((t) => ({
|
|
9065
|
+
prompt: t.prompt.slice(0, IMPORT_LIMITS.maxPromptChars),
|
|
9066
|
+
response: t.response.slice(0, IMPORT_LIMITS.maxResponseChars)
|
|
9067
|
+
}));
|
|
9068
|
+
}
|
|
9069
|
+
function bump(skips, r) {
|
|
9070
|
+
skips.set(r, (skips.get(r) ?? 0) + 1);
|
|
9071
|
+
}
|
|
9072
|
+
function attemptOf(r, index, skips) {
|
|
9073
|
+
const testCase = isObj(r.testCase) ? r.testCase : {};
|
|
9074
|
+
const meta = isObj(testCase.metadata) ? testCase.metadata : {};
|
|
9075
|
+
const resultMeta = isObj(r.metadata) ? r.metadata : {};
|
|
9076
|
+
const response = isObj(r.response) ? r.response : void 0;
|
|
9077
|
+
if (!response || response.output === void 0 && !response.metadata) {
|
|
9078
|
+
bump(skips, str(r.error) ? "target_error" : "no_response");
|
|
9079
|
+
return null;
|
|
9080
|
+
}
|
|
9081
|
+
const turns = clipTurns(transcriptOf(r));
|
|
9082
|
+
if (turns.length === 0 || !turns[turns.length - 1].prompt.trim()) {
|
|
9083
|
+
bump(skips, "empty_prompt");
|
|
9084
|
+
return null;
|
|
9085
|
+
}
|
|
9086
|
+
const label = str(meta.pluginId) ?? str(resultMeta.pluginId) ?? "promptfoo-test";
|
|
9087
|
+
const strategy = str(meta.strategyId) ?? str(resultMeta.strategyId);
|
|
9088
|
+
const objective = str(meta.goal) ?? str(resultMeta.goal);
|
|
9089
|
+
const externalId = (str(r.id) ?? `${index}:${label}:${strategy ?? "basic"}`).slice(0, IMPORT_LIMITS.maxExternalIdChars);
|
|
9090
|
+
return {
|
|
9091
|
+
externalId,
|
|
9092
|
+
label: label.slice(0, IMPORT_LIMITS.maxLabelChars),
|
|
9093
|
+
...strategy ? { strategy: strategy.slice(0, IMPORT_LIMITS.maxLabelChars) } : {},
|
|
9094
|
+
...objective ? { objective: objective.slice(0, IMPORT_LIMITS.maxObjectiveChars) } : {},
|
|
9095
|
+
turns,
|
|
9096
|
+
...toolVerdictOf(r) ? { toolVerdict: toolVerdictOf(r) } : {}
|
|
9097
|
+
};
|
|
9098
|
+
}
|
|
9099
|
+
function parsePromptfoo(doc) {
|
|
9100
|
+
const results = promptfooResults(doc);
|
|
9101
|
+
if (!results) return null;
|
|
9102
|
+
const seen = /* @__PURE__ */ new Map();
|
|
9103
|
+
const metadata = isObj(doc) && isObj(doc.metadata) ? doc.metadata : {};
|
|
9104
|
+
const skips = /* @__PURE__ */ new Map();
|
|
9105
|
+
const attempts = [];
|
|
9106
|
+
results.forEach((r, i) => {
|
|
9107
|
+
if (!isObj(r)) return;
|
|
9108
|
+
const a = attemptOf(r, i, skips);
|
|
9109
|
+
if (!a) return;
|
|
9110
|
+
const n = seen.get(a.externalId) ?? 0;
|
|
9111
|
+
seen.set(a.externalId, n + 1);
|
|
9112
|
+
if (n > 0) a.externalId = `${a.externalId}#${n}`.slice(0, IMPORT_LIMITS.maxExternalIdChars);
|
|
9113
|
+
if (attempts.length >= IMPORT_LIMITS.maxAttemptsPerFile) {
|
|
9114
|
+
bump(skips, "too_many_attempts");
|
|
9115
|
+
return;
|
|
9116
|
+
}
|
|
9117
|
+
attempts.push(a);
|
|
9118
|
+
});
|
|
9119
|
+
const version2 = str(metadata.promptfooVersion);
|
|
9120
|
+
return {
|
|
9121
|
+
source: "promptfoo",
|
|
9122
|
+
...version2 ? { sourceVersion: version2 } : {},
|
|
9123
|
+
attempts,
|
|
9124
|
+
skipped: Array.from(skips.entries()).map(([reason, count]) => ({
|
|
9125
|
+
reason,
|
|
9126
|
+
count
|
|
9127
|
+
}))
|
|
9128
|
+
};
|
|
9129
|
+
}
|
|
9130
|
+
|
|
9131
|
+
// ../../packages/shared/src/supplemental/import-garak.ts
|
|
9132
|
+
var isObj2 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
9133
|
+
var str2 = (v) => typeof v === "string" ? v : void 0;
|
|
9134
|
+
var GARAK_HIT_THRESHOLD = 0.5;
|
|
9135
|
+
function garakEntries(textContent) {
|
|
9136
|
+
const entries = [];
|
|
9137
|
+
for (const line of textContent.split(/\r?\n/)) {
|
|
9138
|
+
const trimmed = line.trim();
|
|
9139
|
+
if (!trimmed.startsWith("{")) continue;
|
|
9140
|
+
try {
|
|
9141
|
+
const v = JSON.parse(trimmed);
|
|
9142
|
+
if (isObj2(v) && typeof v.entry_type === "string") entries.push(v);
|
|
9143
|
+
} catch {
|
|
9144
|
+
}
|
|
9145
|
+
}
|
|
9146
|
+
return entries.length > 0 ? entries : null;
|
|
9147
|
+
}
|
|
9148
|
+
function messageText(v) {
|
|
9149
|
+
if (isObj2(v)) return str2(v.text) ?? "";
|
|
9150
|
+
return str2(v) ?? "";
|
|
9151
|
+
}
|
|
9152
|
+
function turnsFromConversation(conv) {
|
|
9153
|
+
if (!isObj2(conv) || !Array.isArray(conv.turns)) return [];
|
|
9154
|
+
const turns = [];
|
|
9155
|
+
let pending = null;
|
|
9156
|
+
for (const t of conv.turns) {
|
|
9157
|
+
if (!isObj2(t)) continue;
|
|
9158
|
+
const content = messageText(t.content);
|
|
9159
|
+
if (t.role === "user") {
|
|
9160
|
+
if (pending !== null) turns.push({ prompt: pending, response: "" });
|
|
9161
|
+
pending = content;
|
|
9162
|
+
} else if (t.role === "assistant" && pending !== null) {
|
|
9163
|
+
turns.push({ prompt: pending, response: content });
|
|
9164
|
+
pending = null;
|
|
9165
|
+
}
|
|
9166
|
+
}
|
|
9167
|
+
if (pending !== null) turns.push({ prompt: pending, response: "" });
|
|
9168
|
+
return turns;
|
|
9169
|
+
}
|
|
9170
|
+
function verdictForGeneration(detectorResults, index) {
|
|
9171
|
+
if (!isObj2(detectorResults)) return void 0;
|
|
9172
|
+
const scores = Object.values(detectorResults).map((list) => Array.isArray(list) ? list[index] : void 0).filter((s) => typeof s === "number");
|
|
9173
|
+
if (scores.length === 0) return void 0;
|
|
9174
|
+
return scores.some((s) => s >= GARAK_HIT_THRESHOLD) ? "vulnerable" : "safe";
|
|
9175
|
+
}
|
|
9176
|
+
function generationsOf(a) {
|
|
9177
|
+
if (Array.isArray(a.conversations) && a.conversations.length > 0) {
|
|
9178
|
+
return a.conversations.map(turnsFromConversation);
|
|
9179
|
+
}
|
|
9180
|
+
const promptTurns = turnsFromConversation(a.prompt);
|
|
9181
|
+
const lastPrompt = promptTurns.length > 0 ? promptTurns[promptTurns.length - 1].prompt : messageText(a.prompt);
|
|
9182
|
+
const outputs = Array.isArray(a.outputs) ? a.outputs : [];
|
|
9183
|
+
return outputs.map((o) => [{ prompt: lastPrompt, response: messageText(o) }]);
|
|
9184
|
+
}
|
|
9185
|
+
function clip(turns) {
|
|
9186
|
+
return turns.slice(-IMPORT_LIMITS.maxTurns).map((t) => ({
|
|
9187
|
+
prompt: t.prompt.slice(0, IMPORT_LIMITS.maxPromptChars),
|
|
9188
|
+
response: t.response.slice(0, IMPORT_LIMITS.maxResponseChars)
|
|
9189
|
+
}));
|
|
9190
|
+
}
|
|
9191
|
+
function latestAttempts(entries) {
|
|
9192
|
+
const byUuid = /* @__PURE__ */ new Map();
|
|
9193
|
+
entries.forEach((e, i) => {
|
|
9194
|
+
if (e.entry_type !== "attempt") return;
|
|
9195
|
+
byUuid.set(str2(e.uuid) ?? `line-${i}`, e);
|
|
9196
|
+
});
|
|
9197
|
+
return Array.from(byUuid.values());
|
|
9198
|
+
}
|
|
9199
|
+
function parseGarak(textContent) {
|
|
9200
|
+
const entries = garakEntries(textContent);
|
|
9201
|
+
if (!entries) return null;
|
|
9202
|
+
const init = entries.find((e) => e.entry_type === "init");
|
|
9203
|
+
const version2 = init ? str2(init.garak_version) : void 0;
|
|
9204
|
+
const skips = /* @__PURE__ */ new Map();
|
|
9205
|
+
const bump2 = (r) => skips.set(r, (skips.get(r) ?? 0) + 1);
|
|
9206
|
+
const attempts = [];
|
|
9207
|
+
for (const a of latestAttempts(entries)) {
|
|
9208
|
+
const probe = (str2(a.probe_classname) ?? "garak-probe").slice(
|
|
9209
|
+
0,
|
|
9210
|
+
IMPORT_LIMITS.maxLabelChars
|
|
9211
|
+
);
|
|
9212
|
+
const goal = str2(a.goal);
|
|
9213
|
+
const uuid = str2(a.uuid) ?? probe;
|
|
9214
|
+
generationsOf(a).forEach((raw, gen) => {
|
|
9215
|
+
const turns = clip(raw);
|
|
9216
|
+
const last = turns[turns.length - 1];
|
|
9217
|
+
if (!last || !last.prompt.trim()) return bump2("empty_prompt");
|
|
9218
|
+
if (!last.response.trim()) return bump2("no_response");
|
|
9219
|
+
if (attempts.length >= IMPORT_LIMITS.maxAttemptsPerFile) {
|
|
9220
|
+
return bump2("too_many_attempts");
|
|
9221
|
+
}
|
|
9222
|
+
const toolVerdict = verdictForGeneration(a.detector_results, gen);
|
|
9223
|
+
attempts.push({
|
|
9224
|
+
externalId: `${uuid}#${gen}`.slice(0, IMPORT_LIMITS.maxExternalIdChars),
|
|
9225
|
+
label: probe,
|
|
9226
|
+
...goal ? { objective: goal.slice(0, IMPORT_LIMITS.maxObjectiveChars) } : {},
|
|
9227
|
+
turns,
|
|
9228
|
+
...toolVerdict ? { toolVerdict } : {}
|
|
9229
|
+
});
|
|
9230
|
+
});
|
|
9231
|
+
}
|
|
9232
|
+
return {
|
|
9233
|
+
source: "garak",
|
|
9234
|
+
...version2 ? { sourceVersion: version2 } : {},
|
|
9235
|
+
attempts,
|
|
9236
|
+
skipped: Array.from(skips.entries()).map(([reason, count]) => ({
|
|
9237
|
+
reason,
|
|
9238
|
+
count
|
|
9239
|
+
}))
|
|
9240
|
+
};
|
|
9241
|
+
}
|
|
9242
|
+
|
|
9243
|
+
// ../../packages/shared/src/supplemental/import-detect.ts
|
|
9244
|
+
function parseJson(textContent) {
|
|
9245
|
+
try {
|
|
9246
|
+
return JSON.parse(textContent);
|
|
9247
|
+
} catch {
|
|
9248
|
+
return void 0;
|
|
9249
|
+
}
|
|
9250
|
+
}
|
|
9251
|
+
function detectImportFormat(textContent) {
|
|
9252
|
+
const doc = parseJson(textContent);
|
|
9253
|
+
if (doc !== void 0) {
|
|
9254
|
+
return parsePromptfoo(doc) ? "promptfoo" : null;
|
|
9255
|
+
}
|
|
9256
|
+
return parseGarak(textContent) ? "garak" : null;
|
|
9257
|
+
}
|
|
9258
|
+
function parseImportFile(textContent, format) {
|
|
9259
|
+
const source = format ?? detectImportFormat(textContent);
|
|
9260
|
+
if (!source) {
|
|
9261
|
+
return {
|
|
9262
|
+
ok: false,
|
|
9263
|
+
error: "Unrecognised file. Supported: a promptfoo result file (promptfoo eval -o results.json) or a garak report (garak.<id>.report.jsonl)."
|
|
9264
|
+
};
|
|
9265
|
+
}
|
|
9266
|
+
const batch = source === "promptfoo" ? (() => {
|
|
9267
|
+
const doc = parseJson(textContent);
|
|
9268
|
+
return doc === void 0 ? null : parsePromptfoo(doc);
|
|
9269
|
+
})() : parseGarak(textContent);
|
|
9270
|
+
if (!batch) {
|
|
9271
|
+
return { ok: false, error: `Not a ${source} result file.` };
|
|
9272
|
+
}
|
|
9273
|
+
if (batch.attempts.length === 0) {
|
|
9274
|
+
return {
|
|
9275
|
+
ok: false,
|
|
9276
|
+
error: `No importable attempt in this ${source} file (every entry lacked a prompt or an answer).`
|
|
9277
|
+
};
|
|
9278
|
+
}
|
|
9279
|
+
return { ok: true, batch };
|
|
9280
|
+
}
|
|
9281
|
+
|
|
8990
9282
|
// package.json
|
|
8991
|
-
var version = "0.
|
|
9283
|
+
var version = "0.15.0";
|
|
8992
9284
|
|
|
8993
9285
|
// src/config/schema.ts
|
|
8994
9286
|
import { z as z3 } from "zod";
|
|
@@ -9490,15 +9782,15 @@ var HttpTargetClient = class {
|
|
|
9490
9782
|
}
|
|
9491
9783
|
async sendMessage(prompt, options) {
|
|
9492
9784
|
const rawResponse = await this.sendRaw(prompt, [], options);
|
|
9493
|
-
const
|
|
9494
|
-
const platform = detectRateLimit(
|
|
9785
|
+
const text2 = this.extractResponse(rawResponse);
|
|
9786
|
+
const platform = detectRateLimit(text2);
|
|
9495
9787
|
if (platform) {
|
|
9496
9788
|
throw new RateLimitError(
|
|
9497
|
-
`Rate limited (soft, body match \u2014 ${platform}): ${
|
|
9789
|
+
`Rate limited (soft, body match \u2014 ${platform}): ${text2.slice(0, 200)}`,
|
|
9498
9790
|
null
|
|
9499
9791
|
);
|
|
9500
9792
|
}
|
|
9501
|
-
return
|
|
9793
|
+
return text2;
|
|
9502
9794
|
}
|
|
9503
9795
|
createSession() {
|
|
9504
9796
|
if (this.config.statefulConversation) {
|
|
@@ -9719,9 +10011,9 @@ var StatefulHttpSession = class extends LazyAllocatedSession {
|
|
|
9719
10011
|
...options,
|
|
9720
10012
|
sessionId
|
|
9721
10013
|
});
|
|
9722
|
-
const
|
|
9723
|
-
this.recordTurn(prompt,
|
|
9724
|
-
return
|
|
10014
|
+
const text2 = this.client.extractResponse(rawResponse);
|
|
10015
|
+
this.recordTurn(prompt, text2);
|
|
10016
|
+
return text2;
|
|
9725
10017
|
}
|
|
9726
10018
|
};
|
|
9727
10019
|
var StatelessHttpSession = class extends LazyAllocatedSession {
|
|
@@ -9735,11 +10027,11 @@ var StatelessHttpSession = class extends LazyAllocatedSession {
|
|
|
9735
10027
|
...options,
|
|
9736
10028
|
sessionId
|
|
9737
10029
|
});
|
|
9738
|
-
const
|
|
10030
|
+
const text2 = this.client.extractResponse(rawResponse);
|
|
9739
10031
|
this.messages.push({ role: "user", content: prompt });
|
|
9740
|
-
this.messages.push({ role: "assistant", content:
|
|
9741
|
-
this.recordTurn(prompt,
|
|
9742
|
-
return
|
|
10032
|
+
this.messages.push({ role: "assistant", content: text2 });
|
|
10033
|
+
this.recordTurn(prompt, text2);
|
|
10034
|
+
return text2;
|
|
9743
10035
|
}
|
|
9744
10036
|
};
|
|
9745
10037
|
function formatHistory(history, format = "openai") {
|
|
@@ -9943,17 +10235,17 @@ async function fetchWithTimeout(url, init, timeoutMs, responseField, allowPrivat
|
|
|
9943
10235
|
}
|
|
9944
10236
|
const contentType = response.headers.get("content-type") ?? "";
|
|
9945
10237
|
if (contentType.includes("text/event-stream")) {
|
|
9946
|
-
const
|
|
9947
|
-
return nestAtPath(responseField ?? "response",
|
|
10238
|
+
const text2 = await collectSSE(response);
|
|
10239
|
+
return nestAtPath(responseField ?? "response", text2);
|
|
9948
10240
|
}
|
|
9949
10241
|
if (contentType.includes("ndjson")) {
|
|
9950
|
-
const
|
|
9951
|
-
return nestAtPath(responseField ?? "response",
|
|
10242
|
+
const text2 = await collectNDJSON(response);
|
|
10243
|
+
return nestAtPath(responseField ?? "response", text2);
|
|
9952
10244
|
}
|
|
9953
10245
|
if (!contentType.includes("json")) {
|
|
9954
|
-
const
|
|
10246
|
+
const text2 = await readBodyWithLimit(response);
|
|
9955
10247
|
throw new HttpTargetError(
|
|
9956
|
-
`Expected JSON response but got ${contentType}. Body: ${
|
|
10248
|
+
`Expected JSON response but got ${contentType}. Body: ${text2.slice(0, 500)}`,
|
|
9957
10249
|
0
|
|
9958
10250
|
);
|
|
9959
10251
|
}
|
|
@@ -9987,8 +10279,8 @@ var ERROR_BODY_HEAD_BYTES = 8192;
|
|
|
9987
10279
|
async function readErrorBodyHead(response) {
|
|
9988
10280
|
try {
|
|
9989
10281
|
if (!response.body) {
|
|
9990
|
-
const
|
|
9991
|
-
return
|
|
10282
|
+
const text2 = typeof response.text === "function" ? await response.text() : "";
|
|
10283
|
+
return text2.slice(0, ERROR_BODY_HEAD_BYTES);
|
|
9992
10284
|
}
|
|
9993
10285
|
const reader = response.body.getReader();
|
|
9994
10286
|
const decoder = new TextDecoder();
|
|
@@ -11304,13 +11596,13 @@ var Scanner = class {
|
|
|
11304
11596
|
const session = this.targetClient.createSession();
|
|
11305
11597
|
try {
|
|
11306
11598
|
const timing = { ms: 0 };
|
|
11307
|
-
const
|
|
11599
|
+
const text2 = await this.sendTurnWithRetry(
|
|
11308
11600
|
session,
|
|
11309
11601
|
CONSUMPTION_BASELINE_PROMPT,
|
|
11310
11602
|
"consumption-baseline",
|
|
11311
11603
|
timing
|
|
11312
11604
|
);
|
|
11313
|
-
return { chars:
|
|
11605
|
+
return { chars: text2.length, ms: timing.ms };
|
|
11314
11606
|
} catch {
|
|
11315
11607
|
return void 0;
|
|
11316
11608
|
} finally {
|
|
@@ -11465,16 +11757,16 @@ function boundedValue(value, cap, canary) {
|
|
|
11465
11757
|
if (typeof value === "number" || typeof value === "boolean" || value === null) {
|
|
11466
11758
|
return value;
|
|
11467
11759
|
}
|
|
11468
|
-
let
|
|
11760
|
+
let text2;
|
|
11469
11761
|
try {
|
|
11470
|
-
|
|
11762
|
+
text2 = typeof value === "string" ? value : JSON.stringify(value) ?? "";
|
|
11471
11763
|
} catch {
|
|
11472
|
-
|
|
11764
|
+
text2 = "[unserialisable]";
|
|
11473
11765
|
}
|
|
11474
|
-
if (
|
|
11475
|
-
const head =
|
|
11476
|
-
if (!
|
|
11477
|
-
return `${
|
|
11766
|
+
if (text2.length <= cap) return text2;
|
|
11767
|
+
const head = text2.slice(0, cap);
|
|
11768
|
+
if (!text2.includes(canary) || head.includes(canary)) return head;
|
|
11769
|
+
return `${text2.slice(0, Math.max(0, cap - canary.length - 1))}\u2026${canary}`;
|
|
11478
11770
|
}
|
|
11479
11771
|
function boundedArguments(args, canary) {
|
|
11480
11772
|
if (!args || typeof args !== "object" || Array.isArray(args)) return {};
|
|
@@ -11930,6 +12222,15 @@ var CodebaseSchema = z3.object({
|
|
|
11930
12222
|
ingestion: AnchorSchema.optional()
|
|
11931
12223
|
}).default({})
|
|
11932
12224
|
});
|
|
12225
|
+
var utf16 = (max) => z3.string().refine((s) => s.length <= max, `at most ${max} characters`);
|
|
12226
|
+
var TargetProfileSchema = z3.object({
|
|
12227
|
+
company: utf16(100).optional(),
|
|
12228
|
+
botName: utf16(100).optional(),
|
|
12229
|
+
competitors: z3.array(utf16(100)).max(5).optional(),
|
|
12230
|
+
allowedScope: utf16(300).optional(),
|
|
12231
|
+
sector: utf16(50).optional(),
|
|
12232
|
+
locale: z3.enum(["en", "fr"]).optional()
|
|
12233
|
+
}).strict();
|
|
11933
12234
|
var ConfigSchema = z3.object({
|
|
11934
12235
|
/** Optional: only needed by `shield-llm fix`. A scan never reads it. */
|
|
11935
12236
|
codebase: CodebaseSchema.optional(),
|
|
@@ -11966,7 +12267,11 @@ var ConfigSchema = z3.object({
|
|
|
11966
12267
|
// timed out, 5xx, no reply) before the scan is incomplete. Default 20.
|
|
11967
12268
|
maxNotExecutedPercent: z3.number().min(0).max(100).optional(),
|
|
11968
12269
|
thresholds: ThresholdSchema.optional(),
|
|
11969
|
-
output: OutputSchema.optional()
|
|
12270
|
+
output: OutputSchema.optional(),
|
|
12271
|
+
/** Target profile for test packs. A scan without --pack never reads it. */
|
|
12272
|
+
profile: TargetProfileSchema.optional(),
|
|
12273
|
+
/** Test packs run after each scan, like --pack. */
|
|
12274
|
+
packs: z3.array(z3.string().regex(/^[a-z0-9-]{3,60}$/)).max(5).optional()
|
|
11970
12275
|
});
|
|
11971
12276
|
|
|
11972
12277
|
// src/config/loader.ts
|
|
@@ -12142,7 +12447,7 @@ function evaluateThresholds(report, thresholds) {
|
|
|
12142
12447
|
|
|
12143
12448
|
// src/display/colors.ts
|
|
12144
12449
|
import { styleText } from "util";
|
|
12145
|
-
var make = (fmt) => (
|
|
12450
|
+
var make = (fmt) => (text2) => styleText(fmt, text2);
|
|
12146
12451
|
var c2 = {
|
|
12147
12452
|
cyan: make("cyan"),
|
|
12148
12453
|
red: make("red"),
|
|
@@ -12702,6 +13007,9 @@ export {
|
|
|
12702
13007
|
redactTargetUrl,
|
|
12703
13008
|
computeScoreDelta,
|
|
12704
13009
|
evaluateBenign,
|
|
13010
|
+
IMPORT_SOURCES,
|
|
13011
|
+
IMPORT_LIMITS,
|
|
13012
|
+
parseImportFile,
|
|
12705
13013
|
version,
|
|
12706
13014
|
RateLimitError,
|
|
12707
13015
|
checkConversationContext,
|
package/dist/cli.js
CHANGED
|
@@ -14,6 +14,8 @@ import {
|
|
|
14
14
|
FRAMEWORK_LABELS,
|
|
15
15
|
FileCheckpointStore,
|
|
16
16
|
GUARDRAIL_PREFIX,
|
|
17
|
+
IMPORT_LIMITS,
|
|
18
|
+
IMPORT_SOURCES,
|
|
17
19
|
JUDGE_OUTAGE_REASON_PREFIX,
|
|
18
20
|
LAYER_META,
|
|
19
21
|
MUTATORS,
|
|
@@ -70,6 +72,7 @@ import {
|
|
|
70
72
|
mayStampFixed,
|
|
71
73
|
missingForContract,
|
|
72
74
|
normalizeTargetUrl,
|
|
75
|
+
parseImportFile,
|
|
73
76
|
parseMaxUnjudgedPercent,
|
|
74
77
|
recordVerification,
|
|
75
78
|
redactTargetUrl,
|
|
@@ -82,7 +85,7 @@ import {
|
|
|
82
85
|
summarizeObfuscationVariants,
|
|
83
86
|
version,
|
|
84
87
|
withoutScoredApartVariants
|
|
85
|
-
} from "./chunk-
|
|
88
|
+
} from "./chunk-M7VCMWRI.js";
|
|
86
89
|
|
|
87
90
|
// src/load-env.ts
|
|
88
91
|
var PROTECTED_ENV_KEYS = [
|
|
@@ -1906,6 +1909,259 @@ function safeHostname(url) {
|
|
|
1906
1909
|
}
|
|
1907
1910
|
}
|
|
1908
1911
|
|
|
1912
|
+
// src/commands/import.ts
|
|
1913
|
+
import { readFileSync as readFileSync3, statSync } from "fs";
|
|
1914
|
+
|
|
1915
|
+
// src/lib/supplements-client.ts
|
|
1916
|
+
import { createHash } from "crypto";
|
|
1917
|
+
var SupplementUploadError = class extends Error {
|
|
1918
|
+
constructor(message, exitCode) {
|
|
1919
|
+
super(message);
|
|
1920
|
+
this.exitCode = exitCode;
|
|
1921
|
+
}
|
|
1922
|
+
};
|
|
1923
|
+
function batchIdFor(content) {
|
|
1924
|
+
return createHash("sha256").update(content).digest("base64url").slice(0, 22);
|
|
1925
|
+
}
|
|
1926
|
+
var MAX_RETRIES_429 = 4;
|
|
1927
|
+
var REQUEST_TIMEOUT_MS = 18e4;
|
|
1928
|
+
function sleep(ms) {
|
|
1929
|
+
return new Promise((r) => setTimeout(r, ms));
|
|
1930
|
+
}
|
|
1931
|
+
async function postSupplementBatch(credentials, scanId, body) {
|
|
1932
|
+
const url = `${credentials.apiUrl}/api/cli/scans/${encodeURIComponent(scanId)}/supplements`;
|
|
1933
|
+
for (let attempt = 0; ; attempt++) {
|
|
1934
|
+
let res;
|
|
1935
|
+
try {
|
|
1936
|
+
res = await fetch(url, {
|
|
1937
|
+
method: "POST",
|
|
1938
|
+
headers: {
|
|
1939
|
+
"Content-Type": "application/json",
|
|
1940
|
+
Authorization: `Bearer ${credentials.apiKey}`
|
|
1941
|
+
},
|
|
1942
|
+
body: JSON.stringify(body),
|
|
1943
|
+
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
|
|
1944
|
+
});
|
|
1945
|
+
} catch (err) {
|
|
1946
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
1947
|
+
throw new SupplementUploadError(`Failed to reach backend: ${msg}`, 3);
|
|
1948
|
+
}
|
|
1949
|
+
if (await reportIfSuspended(res, credentials.apiUrl)) {
|
|
1950
|
+
throw new SupplementUploadError("Account suspended.", 2);
|
|
1951
|
+
}
|
|
1952
|
+
const inFlight = res.status === 409 && res.headers.get("retry-after") !== null && (await res.clone().json().catch(() => ({}))).code === "upload_in_flight";
|
|
1953
|
+
if ((res.status === 429 || inFlight) && attempt < MAX_RETRIES_429) {
|
|
1954
|
+
const retryAfter = Number(res.headers.get("retry-after") ?? "30");
|
|
1955
|
+
await res.text().catch(() => void 0);
|
|
1956
|
+
await sleep(Math.min(Math.max(retryAfter, 1), 120) * 1e3);
|
|
1957
|
+
continue;
|
|
1958
|
+
}
|
|
1959
|
+
if (res.ok) return await res.json();
|
|
1960
|
+
const text = await res.text().catch(() => "");
|
|
1961
|
+
let message = text.slice(0, 300);
|
|
1962
|
+
try {
|
|
1963
|
+
message = JSON.parse(text).error ?? message;
|
|
1964
|
+
} catch {
|
|
1965
|
+
}
|
|
1966
|
+
if (res.status === 401) {
|
|
1967
|
+
message = "API key is invalid or revoked. Run `shield-llm login` to re-authenticate.";
|
|
1968
|
+
} else if (res.status === 404) {
|
|
1969
|
+
message = `Scan "${scanId}" not found, or not completed, in your account.`;
|
|
1970
|
+
}
|
|
1971
|
+
throw new SupplementUploadError(
|
|
1972
|
+
`HTTP ${res.status}: ${message}`,
|
|
1973
|
+
res.status >= 500 || res.status === 429 ? 3 : 2
|
|
1974
|
+
);
|
|
1975
|
+
}
|
|
1976
|
+
}
|
|
1977
|
+
var MAX_BATCH_BYTES = 9e5;
|
|
1978
|
+
function chunkBySize(items, size, maxBytes = MAX_BATCH_BYTES) {
|
|
1979
|
+
const out = [];
|
|
1980
|
+
let current = [];
|
|
1981
|
+
let bytes = 0;
|
|
1982
|
+
for (const item of items) {
|
|
1983
|
+
const b = Buffer.byteLength(JSON.stringify(item));
|
|
1984
|
+
if (current.length > 0 && (current.length >= size || bytes + b > maxBytes)) {
|
|
1985
|
+
out.push(current);
|
|
1986
|
+
current = [];
|
|
1987
|
+
bytes = 0;
|
|
1988
|
+
}
|
|
1989
|
+
current.push(item);
|
|
1990
|
+
bytes += b;
|
|
1991
|
+
}
|
|
1992
|
+
if (current.length > 0) out.push(current);
|
|
1993
|
+
return out;
|
|
1994
|
+
}
|
|
1995
|
+
|
|
1996
|
+
// src/commands/import.ts
|
|
1997
|
+
var MAX_FILE_BYTES = 50 * 1024 * 1024;
|
|
1998
|
+
function summarizeImport(scanId, batch, results, totals) {
|
|
1999
|
+
const tool = new Map(
|
|
2000
|
+
batch.attempts.map((a) => [a.externalId, a.toolVerdict])
|
|
2001
|
+
);
|
|
2002
|
+
const count = (v) => results.filter((r) => r.verdict === v).length;
|
|
2003
|
+
return {
|
|
2004
|
+
scanId,
|
|
2005
|
+
source: batch.source,
|
|
2006
|
+
sourceVersion: batch.sourceVersion ?? null,
|
|
2007
|
+
attempts: batch.attempts.length,
|
|
2008
|
+
stored: totals.stored,
|
|
2009
|
+
duplicates: totals.duplicates,
|
|
2010
|
+
vulnerable: count("vulnerable"),
|
|
2011
|
+
safe: count("safe"),
|
|
2012
|
+
notJudged: count("not_judged"),
|
|
2013
|
+
missedByTool: results.filter(
|
|
2014
|
+
(r) => r.verdict === "vulnerable" && tool.get(r.itemKey) === "safe"
|
|
2015
|
+
).length,
|
|
2016
|
+
refutedByJudge: results.filter(
|
|
2017
|
+
(r) => r.verdict === "safe" && tool.get(r.itemKey) === "vulnerable"
|
|
2018
|
+
).length,
|
|
2019
|
+
skipped: batch.skipped
|
|
2020
|
+
};
|
|
2021
|
+
}
|
|
2022
|
+
function readResultFile(path) {
|
|
2023
|
+
const size = statSync(path).size;
|
|
2024
|
+
if (size > MAX_FILE_BYTES) {
|
|
2025
|
+
throw new Error(
|
|
2026
|
+
`File is ${Math.round(size / 1024 / 1024)} MB; the limit is ${MAX_FILE_BYTES / 1024 / 1024} MB.`
|
|
2027
|
+
);
|
|
2028
|
+
}
|
|
2029
|
+
return readFileSync3(path, "utf8");
|
|
2030
|
+
}
|
|
2031
|
+
function printHuman(o, apiUrl) {
|
|
2032
|
+
const version2 = o.sourceVersion ? ` ${o.sourceVersion.replace(/[\u0000-\u001f\u007f-\u009f]/g, "")}` : "";
|
|
2033
|
+
console.log("");
|
|
2034
|
+
console.log(
|
|
2035
|
+
`Imported ${o.attempts} attempt(s) from ${o.source}${version2} into scan ${o.scanId}.`
|
|
2036
|
+
);
|
|
2037
|
+
if (o.duplicates > 0) {
|
|
2038
|
+
console.log(` ${o.duplicates} were already imported and were skipped.`);
|
|
2039
|
+
}
|
|
2040
|
+
console.log(
|
|
2041
|
+
` Judged by Shield: ${o.vulnerable} vulnerable, ${o.safe} safe, ${o.notJudged} not judged.`
|
|
2042
|
+
);
|
|
2043
|
+
if (o.missedByTool + o.refutedByJudge > 0) {
|
|
2044
|
+
console.log(
|
|
2045
|
+
` Disagreements with ${o.source}: ${o.missedByTool} the tool called safe, ${o.refutedByJudge} the tool called vulnerable.`
|
|
2046
|
+
);
|
|
2047
|
+
}
|
|
2048
|
+
for (const s of o.skipped) {
|
|
2049
|
+
console.log(` Not imported: ${s.count} (${s.reason.replace(/_/g, " ")}).`);
|
|
2050
|
+
}
|
|
2051
|
+
console.log("");
|
|
2052
|
+
console.log(
|
|
2053
|
+
"These results are declared by you and kept apart from the score."
|
|
2054
|
+
);
|
|
2055
|
+
console.log(`Dashboard: ${apiUrl}/scans/${o.scanId}`);
|
|
2056
|
+
}
|
|
2057
|
+
async function uploadBatch(credentials, scanId, batch, batchId, showProgress) {
|
|
2058
|
+
const results = [];
|
|
2059
|
+
const totals = { stored: 0, duplicates: 0 };
|
|
2060
|
+
const chunks = chunkBySize(batch.attempts, IMPORT_LIMITS.batchSize);
|
|
2061
|
+
try {
|
|
2062
|
+
for (const [i, items] of chunks.entries()) {
|
|
2063
|
+
const res = await postSupplementBatch(credentials, scanId, {
|
|
2064
|
+
kind: "import",
|
|
2065
|
+
batchId,
|
|
2066
|
+
source: batch.source,
|
|
2067
|
+
...batch.sourceVersion ? { sourceVersion: batch.sourceVersion.slice(0, 50) } : {},
|
|
2068
|
+
items
|
|
2069
|
+
});
|
|
2070
|
+
results.push(...res.results);
|
|
2071
|
+
totals.stored += res.stored;
|
|
2072
|
+
totals.duplicates += res.duplicates;
|
|
2073
|
+
if (showProgress) {
|
|
2074
|
+
process.stdout.write(`\r ${i + 1}/${chunks.length} batch(es) judged`);
|
|
2075
|
+
}
|
|
2076
|
+
}
|
|
2077
|
+
} catch (err) {
|
|
2078
|
+
if (showProgress) process.stdout.write("\n");
|
|
2079
|
+
console.error(
|
|
2080
|
+
`Import stopped: ${err instanceof Error ? err.message : String(err)}`
|
|
2081
|
+
);
|
|
2082
|
+
if (results.length > 0) {
|
|
2083
|
+
console.error(
|
|
2084
|
+
`${results.length} attempt(s) were stored before it stopped; re-run the same command to finish (stored ones are skipped).`
|
|
2085
|
+
);
|
|
2086
|
+
}
|
|
2087
|
+
setExitCode(err instanceof SupplementUploadError ? err.exitCode : 3);
|
|
2088
|
+
return null;
|
|
2089
|
+
}
|
|
2090
|
+
if (showProgress) process.stdout.write("\n");
|
|
2091
|
+
return { results, ...totals };
|
|
2092
|
+
}
|
|
2093
|
+
async function importCommand(file, opts) {
|
|
2094
|
+
const info = (msg) => {
|
|
2095
|
+
if (opts.ci) console.error(msg);
|
|
2096
|
+
else console.log(msg);
|
|
2097
|
+
};
|
|
2098
|
+
if (!opts.scan) {
|
|
2099
|
+
console.error(
|
|
2100
|
+
"Missing --scan <scanId>: the completed scan to attach the results to."
|
|
2101
|
+
);
|
|
2102
|
+
setExitCode(2);
|
|
2103
|
+
return;
|
|
2104
|
+
}
|
|
2105
|
+
if (opts.format && !IMPORT_SOURCES.includes(opts.format)) {
|
|
2106
|
+
console.error(
|
|
2107
|
+
`Unknown --format "${opts.format}". Supported: ${IMPORT_SOURCES.join(", ")}.`
|
|
2108
|
+
);
|
|
2109
|
+
setExitCode(2);
|
|
2110
|
+
return;
|
|
2111
|
+
}
|
|
2112
|
+
const stored = loadCredentials();
|
|
2113
|
+
if (!stored) {
|
|
2114
|
+
console.error("Not logged in. Run `shield-llm login` to authenticate.");
|
|
2115
|
+
setExitCode(2);
|
|
2116
|
+
return;
|
|
2117
|
+
}
|
|
2118
|
+
const credentials = {
|
|
2119
|
+
...stored,
|
|
2120
|
+
apiUrl: resolveApiUrl(stored.apiUrl, opts.apiUrl)
|
|
2121
|
+
};
|
|
2122
|
+
let content;
|
|
2123
|
+
try {
|
|
2124
|
+
content = readResultFile(file);
|
|
2125
|
+
} catch (err) {
|
|
2126
|
+
console.error(
|
|
2127
|
+
`Cannot read ${file}: ${err instanceof Error ? err.message : String(err)}`
|
|
2128
|
+
);
|
|
2129
|
+
setExitCode(2);
|
|
2130
|
+
return;
|
|
2131
|
+
}
|
|
2132
|
+
const parsed = parseImportFile(
|
|
2133
|
+
content,
|
|
2134
|
+
opts.format
|
|
2135
|
+
);
|
|
2136
|
+
if (!parsed.ok) {
|
|
2137
|
+
console.error(parsed.error);
|
|
2138
|
+
setExitCode(2);
|
|
2139
|
+
return;
|
|
2140
|
+
}
|
|
2141
|
+
const { batch } = parsed;
|
|
2142
|
+
const batchId = batchIdFor(content);
|
|
2143
|
+
info(
|
|
2144
|
+
`Read ${batch.attempts.length} attempt(s) from a ${batch.source} file. Sending them to Shield's judge\u2026`
|
|
2145
|
+
);
|
|
2146
|
+
const uploaded = await uploadBatch(
|
|
2147
|
+
credentials,
|
|
2148
|
+
String(opts.scan),
|
|
2149
|
+
batch,
|
|
2150
|
+
batchId,
|
|
2151
|
+
!opts.ci && opts.progress !== false
|
|
2152
|
+
);
|
|
2153
|
+
if (!uploaded) return;
|
|
2154
|
+
const outcome = summarizeImport(
|
|
2155
|
+
String(opts.scan),
|
|
2156
|
+
batch,
|
|
2157
|
+
uploaded.results,
|
|
2158
|
+
uploaded
|
|
2159
|
+
);
|
|
2160
|
+
if (opts.ci) console.log(JSON.stringify(outcome, null, 2));
|
|
2161
|
+
else printHuman(outcome, credentials.apiUrl);
|
|
2162
|
+
setExitCode(0);
|
|
2163
|
+
}
|
|
2164
|
+
|
|
1909
2165
|
// src/commands/scan.ts
|
|
1910
2166
|
import { resolve as resolve5 } from "path";
|
|
1911
2167
|
|
|
@@ -1962,12 +2218,181 @@ function harnessSkipWarning(results, harness) {
|
|
|
1962
2218
|
return lines.length > 0 ? lines.join("\n") : null;
|
|
1963
2219
|
}
|
|
1964
2220
|
|
|
2221
|
+
// src/lib/pack-run.ts
|
|
2222
|
+
var PackRunError = class extends Error {
|
|
2223
|
+
constructor(message, exitCode) {
|
|
2224
|
+
super(message);
|
|
2225
|
+
this.exitCode = exitCode;
|
|
2226
|
+
}
|
|
2227
|
+
};
|
|
2228
|
+
async function fetchRenderedPacks(input2) {
|
|
2229
|
+
const { credentials } = input2;
|
|
2230
|
+
let res;
|
|
2231
|
+
try {
|
|
2232
|
+
res = await fetch(`${credentials.apiUrl}/api/cli/packs`, {
|
|
2233
|
+
method: "POST",
|
|
2234
|
+
headers: {
|
|
2235
|
+
"Content-Type": "application/json",
|
|
2236
|
+
Authorization: `Bearer ${credentials.apiKey}`
|
|
2237
|
+
},
|
|
2238
|
+
body: JSON.stringify({ packIds: input2.packIds, profile: input2.profile })
|
|
2239
|
+
});
|
|
2240
|
+
} catch (err) {
|
|
2241
|
+
throw new PackRunError(
|
|
2242
|
+
`Failed to reach backend: ${err instanceof Error ? err.message : String(err)}`,
|
|
2243
|
+
3
|
|
2244
|
+
);
|
|
2245
|
+
}
|
|
2246
|
+
if (await reportIfSuspended(res, credentials.apiUrl)) {
|
|
2247
|
+
throw new PackRunError("Account suspended.", 2);
|
|
2248
|
+
}
|
|
2249
|
+
if (!res.ok) {
|
|
2250
|
+
const body = await res.json().catch(() => ({}));
|
|
2251
|
+
const available = body.available?.length ? ` Available: ${body.available.join(", ")}.` : "";
|
|
2252
|
+
throw new PackRunError(
|
|
2253
|
+
`${body.error ?? `HTTP ${res.status}`}.${available}`,
|
|
2254
|
+
res.status >= 500 ? 3 : 2
|
|
2255
|
+
);
|
|
2256
|
+
}
|
|
2257
|
+
return (await res.json()).packs;
|
|
2258
|
+
}
|
|
2259
|
+
async function askTarget(input2, prompt) {
|
|
2260
|
+
const client = createTargetClient(input2.target, input2.systemPrompt, {
|
|
2261
|
+
resolveEnv: true
|
|
2262
|
+
});
|
|
2263
|
+
try {
|
|
2264
|
+
return await client.sendMessage(prompt, {
|
|
2265
|
+
abortSignal: AbortSignal.timeout(input2.timeoutMs ?? 6e4)
|
|
2266
|
+
});
|
|
2267
|
+
} catch {
|
|
2268
|
+
return null;
|
|
2269
|
+
}
|
|
2270
|
+
}
|
|
2271
|
+
async function runOnePack(input2, pack) {
|
|
2272
|
+
const items = [];
|
|
2273
|
+
let notExecuted = 0;
|
|
2274
|
+
for (const c2 of pack.cases) {
|
|
2275
|
+
if (!c2.applicable || !c2.prompt) {
|
|
2276
|
+
items.push({ caseId: c2.caseId, turns: [] });
|
|
2277
|
+
continue;
|
|
2278
|
+
}
|
|
2279
|
+
const answer = await askTarget(input2, c2.prompt);
|
|
2280
|
+
if (answer === null) {
|
|
2281
|
+
notExecuted++;
|
|
2282
|
+
continue;
|
|
2283
|
+
}
|
|
2284
|
+
items.push({
|
|
2285
|
+
caseId: c2.caseId,
|
|
2286
|
+
turns: [
|
|
2287
|
+
{
|
|
2288
|
+
prompt: c2.prompt,
|
|
2289
|
+
response: answer.slice(0, IMPORT_LIMITS.maxResponseChars)
|
|
2290
|
+
}
|
|
2291
|
+
]
|
|
2292
|
+
});
|
|
2293
|
+
}
|
|
2294
|
+
const batchId = batchIdFor(`${input2.scanId}:${pack.packId}:${pack.version}`);
|
|
2295
|
+
const results = [];
|
|
2296
|
+
for (const part of chunkBySize(items, IMPORT_LIMITS.batchSize)) {
|
|
2297
|
+
const res = await postSupplementBatch(input2.credentials, input2.scanId, {
|
|
2298
|
+
kind: "pack",
|
|
2299
|
+
batchId,
|
|
2300
|
+
packId: pack.packId,
|
|
2301
|
+
profile: input2.profile,
|
|
2302
|
+
items: part
|
|
2303
|
+
});
|
|
2304
|
+
results.push(...res.results);
|
|
2305
|
+
}
|
|
2306
|
+
const names = new Map(pack.cases.map((c2) => [c2.caseId, c2.name]));
|
|
2307
|
+
const count = (v) => results.filter((r) => r.verdict === v).length;
|
|
2308
|
+
return {
|
|
2309
|
+
packId: pack.packId,
|
|
2310
|
+
version: pack.version,
|
|
2311
|
+
title: pack.title,
|
|
2312
|
+
passed: count("safe"),
|
|
2313
|
+
failed: count("vulnerable"),
|
|
2314
|
+
notJudged: count("not_judged"),
|
|
2315
|
+
notApplicable: count("not_applicable"),
|
|
2316
|
+
notExecuted,
|
|
2317
|
+
failedCases: results.filter((r) => r.verdict === "vulnerable").map((r) => names.get(r.itemKey) ?? r.itemKey)
|
|
2318
|
+
};
|
|
2319
|
+
}
|
|
2320
|
+
async function runPacks(input2) {
|
|
2321
|
+
const packs = await fetchRenderedPacks(input2);
|
|
2322
|
+
const out = [];
|
|
2323
|
+
for (const pack of packs) out.push(await runOnePack(input2, pack));
|
|
2324
|
+
return out;
|
|
2325
|
+
}
|
|
2326
|
+
function formatPackSummary(s) {
|
|
2327
|
+
const lines = [
|
|
2328
|
+
` Pack ${s.title} (${s.packId} ${s.version}): ${s.passed} passed, ${s.failed} failed` + (s.notJudged ? `, ${s.notJudged} not judged` : "") + (s.notApplicable ? `, ${s.notApplicable} not applicable (profile incomplete)` : "") + (s.notExecuted ? `, ${s.notExecuted} not executed (no answer)` : "") + "."
|
|
2329
|
+
];
|
|
2330
|
+
for (const name of s.failedCases) lines.push(` \u2717 ${name}`);
|
|
2331
|
+
return lines;
|
|
2332
|
+
}
|
|
2333
|
+
async function checkPackIds(credentials, packIds) {
|
|
2334
|
+
let res;
|
|
2335
|
+
try {
|
|
2336
|
+
res = await fetch(`${credentials.apiUrl}/api/cli/packs`, {
|
|
2337
|
+
headers: { Authorization: `Bearer ${credentials.apiKey}` }
|
|
2338
|
+
});
|
|
2339
|
+
} catch (err) {
|
|
2340
|
+
return {
|
|
2341
|
+
ok: false,
|
|
2342
|
+
error: `Failed to reach backend to check --pack: ${err instanceof Error ? err.message : String(err)}`
|
|
2343
|
+
};
|
|
2344
|
+
}
|
|
2345
|
+
if (!res.ok) {
|
|
2346
|
+
await res.text().catch(() => void 0);
|
|
2347
|
+
return { ok: false, error: `Backend returned HTTP ${res.status} listing test packs.` };
|
|
2348
|
+
}
|
|
2349
|
+
const { packs } = await res.json();
|
|
2350
|
+
const published = packs.filter((p) => p.status === "published").map((p) => p.id);
|
|
2351
|
+
const drafts = new Set(packs.filter((p) => p.status !== "published").map((p) => p.id));
|
|
2352
|
+
const bad = packIds.filter((id) => !published.includes(id));
|
|
2353
|
+
if (bad.length === 0) return { ok: true };
|
|
2354
|
+
const why = bad.map((id) => drafts.has(id) ? `${id} (draft, not runnable yet)` : `${id} (unknown)`).join(", ");
|
|
2355
|
+
return {
|
|
2356
|
+
ok: false,
|
|
2357
|
+
error: `Cannot run test pack(s): ${why}. Available: ${published.join(", ") || "none"}.`
|
|
2358
|
+
};
|
|
2359
|
+
}
|
|
2360
|
+
async function runRequestedPacks(args) {
|
|
2361
|
+
if (args.packIds.length === 0) return [];
|
|
2362
|
+
if (!args.uploadedScanId) {
|
|
2363
|
+
const line = " Test packs not run: the scan was not saved to the dashboard.";
|
|
2364
|
+
args.info(line);
|
|
2365
|
+
return [line];
|
|
2366
|
+
}
|
|
2367
|
+
args.info(`Running test pack(s): ${args.packIds.join(", ")}\u2026`);
|
|
2368
|
+
try {
|
|
2369
|
+
const summaries = await runPacks({
|
|
2370
|
+
credentials: args.credentials,
|
|
2371
|
+
scanId: args.uploadedScanId,
|
|
2372
|
+
packIds: args.packIds,
|
|
2373
|
+
profile: args.profile,
|
|
2374
|
+
target: args.target,
|
|
2375
|
+
systemPrompt: args.systemPrompt
|
|
2376
|
+
});
|
|
2377
|
+
const lines = [
|
|
2378
|
+
" Test packs (kept apart from the score):",
|
|
2379
|
+
...summaries.flatMap(formatPackSummary)
|
|
2380
|
+
];
|
|
2381
|
+
if (args.ci) lines.forEach((l) => args.info(l));
|
|
2382
|
+
return lines;
|
|
2383
|
+
} catch (err) {
|
|
2384
|
+
const line = ` Test packs not run: ${err instanceof Error ? err.message : String(err)}`;
|
|
2385
|
+
args.info(line);
|
|
2386
|
+
return [line];
|
|
2387
|
+
}
|
|
2388
|
+
}
|
|
2389
|
+
|
|
1965
2390
|
// src/reporters/evidence.ts
|
|
1966
2391
|
import { writeFileSync as writeFileSync5 } from "fs";
|
|
1967
2392
|
import { resolve as resolve3 } from "path";
|
|
1968
2393
|
|
|
1969
2394
|
// ../../packages/shared/src/compliance/evidence-bundle.ts
|
|
1970
|
-
import { createHash } from "crypto";
|
|
2395
|
+
import { createHash as createHash2 } from "crypto";
|
|
1971
2396
|
|
|
1972
2397
|
// ../../packages/shared/src/compliance/remediation-validation.ts
|
|
1973
2398
|
function claimScopeForScan(scan) {
|
|
@@ -2083,7 +2508,7 @@ function sortDeep(value) {
|
|
|
2083
2508
|
return out;
|
|
2084
2509
|
}
|
|
2085
2510
|
function sha256Hex2(input2) {
|
|
2086
|
-
return
|
|
2511
|
+
return createHash2("sha256").update(input2, "utf8").digest("hex");
|
|
2087
2512
|
}
|
|
2088
2513
|
function truncate2(text, spent) {
|
|
2089
2514
|
if (typeof text !== "string" || text.length === 0) return {};
|
|
@@ -2744,6 +3169,15 @@ async function scanCommand(opts) {
|
|
|
2744
3169
|
configPath: opts.config,
|
|
2745
3170
|
cliOverrides
|
|
2746
3171
|
});
|
|
3172
|
+
const packIds = (opts.pack?.length ? opts.pack : config.packs) ?? [];
|
|
3173
|
+
if (packIds.length > 0) {
|
|
3174
|
+
const check = await checkPackIds(credentials, packIds);
|
|
3175
|
+
if (!check.ok) {
|
|
3176
|
+
console.error(check.error);
|
|
3177
|
+
setExitCode(2);
|
|
3178
|
+
return;
|
|
3179
|
+
}
|
|
3180
|
+
}
|
|
2747
3181
|
if (opts.loadCustomTests) {
|
|
2748
3182
|
try {
|
|
2749
3183
|
const remoteTests = await fetchCustomTests(
|
|
@@ -2990,6 +3424,16 @@ async function scanCommand(opts) {
|
|
|
2990
3424
|
}
|
|
2991
3425
|
}
|
|
2992
3426
|
}
|
|
3427
|
+
const packLines = await runRequestedPacks({
|
|
3428
|
+
packIds,
|
|
3429
|
+
uploadedScanId,
|
|
3430
|
+
credentials,
|
|
3431
|
+
profile: config.profile ?? {},
|
|
3432
|
+
target,
|
|
3433
|
+
systemPrompt,
|
|
3434
|
+
info,
|
|
3435
|
+
ci: Boolean(opts.ci)
|
|
3436
|
+
});
|
|
2993
3437
|
let thresholdResult = evaluateThresholds(report, config.thresholds);
|
|
2994
3438
|
const thresholdsConfigured = config.thresholds !== void 0 || opts.complianceThreshold !== void 0;
|
|
2995
3439
|
let evidenceBundleNote = "";
|
|
@@ -3039,6 +3483,8 @@ async function scanCommand(opts) {
|
|
|
3039
3483
|
console.log(formatComplianceTerminal(complianceResult, report.target));
|
|
3040
3484
|
}
|
|
3041
3485
|
if (evidenceBundleNote) console.log(evidenceBundleNote);
|
|
3486
|
+
if (packLines.length > 0) console.log(`${packLines.join("\n")}
|
|
3487
|
+
`);
|
|
3042
3488
|
if (uploadedScanId) {
|
|
3043
3489
|
console.log(
|
|
3044
3490
|
` Dashboard: ${credentials.apiUrl}/scans/${uploadedScanId}
|
|
@@ -3435,12 +3881,12 @@ function validateCommand(opts) {
|
|
|
3435
3881
|
}
|
|
3436
3882
|
|
|
3437
3883
|
// src/commands/fix.ts
|
|
3438
|
-
import { existsSync as existsSync6, readFileSync as
|
|
3884
|
+
import { existsSync as existsSync6, readFileSync as readFileSync6, readdirSync } from "fs";
|
|
3439
3885
|
import { execFileSync as execFileSync3 } from "child_process";
|
|
3440
3886
|
import { resolve as resolve7 } from "path";
|
|
3441
3887
|
|
|
3442
3888
|
// src/fix/anchor-resolver.ts
|
|
3443
|
-
import { existsSync as existsSync4, readFileSync as
|
|
3889
|
+
import { existsSync as existsSync4, readFileSync as readFileSync4, statSync as statSync2 } from "fs";
|
|
3444
3890
|
import { isAbsolute, relative, resolve as resolve6, sep } from "path";
|
|
3445
3891
|
var AnchorError = class extends Error {
|
|
3446
3892
|
constructor(message, kind, status) {
|
|
@@ -3479,7 +3925,7 @@ function resolveAnchor(root, kind, anchor) {
|
|
|
3479
3925
|
return { kind, status: "anchor_missing", configHint };
|
|
3480
3926
|
}
|
|
3481
3927
|
const abs = safeResolve(root, anchor.file);
|
|
3482
|
-
if (!existsSync4(abs) || !
|
|
3928
|
+
if (!existsSync4(abs) || !statSync2(abs).isFile()) {
|
|
3483
3929
|
throw new AnchorError(
|
|
3484
3930
|
`${configHint}.file points at "${anchor.file}", which does not exist under ${root}. A stale anchor is worse than a missing one \u2014 it fakes coverage.`,
|
|
3485
3931
|
kind,
|
|
@@ -3487,7 +3933,7 @@ function resolveAnchor(root, kind, anchor) {
|
|
|
3487
3933
|
);
|
|
3488
3934
|
}
|
|
3489
3935
|
if (anchor.export) {
|
|
3490
|
-
const source =
|
|
3936
|
+
const source = readFileSync4(abs, "utf8");
|
|
3491
3937
|
if (!declaresExport(source, anchor.export)) {
|
|
3492
3938
|
throw new AnchorError(
|
|
3493
3939
|
`${configHint}.export is "${anchor.export}" but ${anchor.file} does not declare it. (v1 resolves exports textually: a star re-export like \`export * from "./barrel"\` is not seen \u2014 point the anchor at the file that actually declares the symbol.)`,
|
|
@@ -3725,7 +4171,7 @@ function blockedByAnchor(anchors) {
|
|
|
3725
4171
|
import {
|
|
3726
4172
|
existsSync as existsSync5,
|
|
3727
4173
|
mkdirSync as mkdirSync4,
|
|
3728
|
-
readFileSync as
|
|
4174
|
+
readFileSync as readFileSync5,
|
|
3729
4175
|
rmSync,
|
|
3730
4176
|
writeFileSync as writeFileSync7
|
|
3731
4177
|
} from "fs";
|
|
@@ -3896,7 +4342,7 @@ var WorkingSet = class {
|
|
|
3896
4342
|
const cached = this.files.get(relPath);
|
|
3897
4343
|
if (cached) return cached.current;
|
|
3898
4344
|
const abs = safeResolve(this.root, relPath);
|
|
3899
|
-
const before = existsSync5(abs) ?
|
|
4345
|
+
const before = existsSync5(abs) ? readFileSync5(abs, "utf8") : "";
|
|
3900
4346
|
this.files.set(relPath, { before, current: before });
|
|
3901
4347
|
return before;
|
|
3902
4348
|
}
|
|
@@ -5552,7 +5998,7 @@ async function resolveCatalogue(opts) {
|
|
|
5552
5998
|
return pending;
|
|
5553
5999
|
}
|
|
5554
6000
|
function findingsFromLocalReport(path) {
|
|
5555
|
-
const parsed = JSON.parse(
|
|
6001
|
+
const parsed = JSON.parse(readFileSync6(path, "utf8"));
|
|
5556
6002
|
const r = parsed.report;
|
|
5557
6003
|
if (!r?.attacks)
|
|
5558
6004
|
throw new Error(`${path} is not a shield-llm --write-json report`);
|
|
@@ -6185,7 +6631,7 @@ function closurePathConfigured(root) {
|
|
|
6185
6631
|
if (!existsSync6(dir)) return false;
|
|
6186
6632
|
try {
|
|
6187
6633
|
return readdirSync(dir).some(
|
|
6188
|
-
(f) =>
|
|
6634
|
+
(f) => readFileSync6(resolve7(dir, f), "utf8").includes("verify-claims")
|
|
6189
6635
|
);
|
|
6190
6636
|
} catch {
|
|
6191
6637
|
return false;
|
|
@@ -6506,6 +6952,11 @@ program.command("scan").description("Run a security scan against a target chatbo
|
|
|
6506
6952
|
).option(
|
|
6507
6953
|
"--load-custom-tests",
|
|
6508
6954
|
"Fetch custom tests from your Shield LLM dashboard"
|
|
6955
|
+
).option(
|
|
6956
|
+
"--pack <id>",
|
|
6957
|
+
"After the scan, run this test pack (e.g. shield-brand) against the same target. Results are kept apart from the score. Repeatable.",
|
|
6958
|
+
(value, previous) => [...previous, value],
|
|
6959
|
+
[]
|
|
6509
6960
|
).option(
|
|
6510
6961
|
"--custom-only",
|
|
6511
6962
|
"Run ONLY custom tests \u2014 send no preset attack payloads to the target"
|
|
@@ -6613,6 +7064,9 @@ program.command("probe-carriers").description(
|
|
|
6613
7064
|
"Probe whether invisible-Unicode carriers survive the target's input pipeline (transport diagnostic, no scan/judge/upload)"
|
|
6614
7065
|
).option("-c, --config <path>", "Path to config file").option("--ci", "Emit JSON to stdout instead of the human-readable table").action(probeCarriersCommand);
|
|
6615
7066
|
program.command("report <scanId>").description("Fetch a past scan report from your dashboard").option("-o, --output <format>", "Output format (json, markdown)", "json").option("--output-file <path>", "Write report to file").option("--api-url <url>", "Backend API URL override").action(reportCommand);
|
|
7067
|
+
program.command("import <file>").description(
|
|
7068
|
+
"Import a promptfoo or garak result file into a scan: Shield re-judges each attempt and shows the results apart from the score"
|
|
7069
|
+
).option("--scan <scan-id>", "Completed scan to attach the results to").option("--format <tool>", "Force the reader: promptfoo or garak (default: detected)").option("--no-progress", "Disable the progress line").option("--ci", "CI mode: JSON summary to stdout").option("--api-url <url>", "Backend API URL override").action(importCommand);
|
|
6616
7070
|
program.command("retest <scanId>").description(
|
|
6617
7071
|
"Replay the detected findings of a past scan against the target and record which are fixed (verified) vs still vulnerable"
|
|
6618
7072
|
).option("-c, --config <path>", "Path to shield.config.json").option("-e, --endpoint <url>", "Target chatbot HTTP endpoint URL").option("--auth <type>", "Auth type: bearer, api-key").option("--token <value>", "Bearer token or API key value").option("--auth-header <name>", "Custom auth header name (for api-key auth)").option(
|
package/dist/index.js
CHANGED