shrike-guard 1.3.3 → 4.0.2

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.
@@ -72,9 +72,11 @@ var THREAT_TYPE_MAP = {
72
72
  completion_baiting: "jailbreak",
73
73
  override: "jailbreak",
74
74
  manipulate: "jailbreak",
75
- tonality_drift_profanity: "jailbreak",
75
+ // L8 tonality drift — backend normalizes profanity + hostile as toxic_content;
76
+ // casual stays as jailbreak (matches platform/common/models/response.go:309-313).
77
+ tonality_drift_profanity: "toxic_content",
78
+ tonality_drift_hostile: "toxic_content",
76
79
  tonality_drift_casual: "jailbreak",
77
- tonality_drift_hostile: "jailbreak",
78
80
  // System prompt leak
79
81
  system_prompt_leak: "system_prompt_leak",
80
82
  system_prompt_extraction: "system_prompt_leak",
@@ -130,9 +132,11 @@ var THREAT_TYPE_MAP = {
130
132
  suspicious_tld: "blocked_domain",
131
133
  suspicious_domain: "blocked_domain",
132
134
  malicious_url: "blocked_domain",
133
- // Toxicity
134
- toxicity: "toxicity",
135
- harmful_content: "toxicity",
135
+ // Toxic content (canonical name as of the L7 rewrite). `toxicity` kept as a
136
+ // legacy alias so older backend builds + customer code don't break.
137
+ toxic_content: "toxic_content",
138
+ toxicity: "toxic_content",
139
+ harmful_content: "toxic_content",
136
140
  // Malicious code
137
141
  malicious_content: "malicious_code",
138
142
  malicious_code: "malicious_code",
@@ -153,6 +157,12 @@ var THREAT_TYPE_MAP = {
153
157
  privilege_escalation: "privilege_escalation",
154
158
  // Destructive operation
155
159
  destructive_operation: "destructive_operation",
160
+ // L9 multi-turn correlation — the pseudo-category emitted when any
161
+ // multi_turn_* pattern fires (crescendo, blocked_retry, trust-building,
162
+ // memory_poisoning, etc.). The normalizeThreatType prefix check below
163
+ // handles the specific pattern names; this entry catches the pseudo
164
+ // value if the backend pre-normalizes.
165
+ multi_turn_attack: "multi_turn_attack",
156
166
  // Errors
157
167
  scan_error: "scan_error",
158
168
  size_limit_exceeded: "size_limit_exceeded",
@@ -169,7 +179,9 @@ var THREAT_GUIDANCE = {
169
179
  secrets_exposure: "This content contains patterns matching API keys, tokens, or credentials.",
170
180
  pii_exposure: "This content contains personally identifiable information.",
171
181
  blocked_domain: "This web search targets a restricted domain.",
182
+ toxic_content: "This content contains potentially harmful or inappropriate language.",
172
183
  toxicity: "This content contains potentially harmful or inappropriate language.",
184
+ multi_turn_attack: "A pattern was detected across multiple turns of this session that suggests a coordinated attempt to bypass safety controls.",
173
185
  malicious_code: "This content contains patterns associated with malicious code.",
174
186
  harmful_intent: "This request contains content associated with harmful intent.",
175
187
  social_engineering: "This prompt contains social engineering patterns.",
@@ -189,7 +201,9 @@ var THREAT_SEVERITY = {
189
201
  secrets_exposure: "critical",
190
202
  pii_exposure: "high",
191
203
  blocked_domain: "medium",
204
+ toxic_content: "medium",
192
205
  toxicity: "medium",
206
+ multi_turn_attack: "high",
193
207
  malicious_code: "critical",
194
208
  harmful_intent: "high",
195
209
  social_engineering: "medium",
@@ -199,12 +213,31 @@ var THREAT_SEVERITY = {
199
213
  size_limit_exceeded: "low",
200
214
  unknown: "medium"
201
215
  };
216
+ var INTERNAL_FIELDS = /* @__PURE__ */ new Set([
217
+ "detected_by",
218
+ "policy_id",
219
+ "policy_name",
220
+ "matched_pattern",
221
+ "matched_text",
222
+ "pattern",
223
+ "scan_stage",
224
+ "ai_reasoning",
225
+ "llm_analysis",
226
+ "performance_metrics",
227
+ "performance"
228
+ ]);
202
229
  function normalizeThreatType(rawType) {
203
230
  if (!rawType) {
204
231
  return "unknown";
205
232
  }
206
233
  const normalized = rawType.toLowerCase().replace(/-/g, "_");
207
- return THREAT_TYPE_MAP[normalized] || "unknown";
234
+ if (THREAT_TYPE_MAP[normalized]) {
235
+ return THREAT_TYPE_MAP[normalized];
236
+ }
237
+ if (normalized.startsWith("multi_turn_")) {
238
+ return "multi_turn_attack";
239
+ }
240
+ return "unknown";
208
241
  }
209
242
  function deriveSeverity(threatType, rawSeverity) {
210
243
  const validSeverities = /* @__PURE__ */ new Set(["critical", "high", "medium", "low"]);
@@ -225,20 +258,59 @@ function bucketConfidence(score) {
225
258
  }
226
259
  return "low";
227
260
  }
261
+ var PRESERVED_GOVERNANCE_FIELDS = [
262
+ "action",
263
+ "refuse_tier",
264
+ "recovery",
265
+ "session_state",
266
+ "content_type",
267
+ "approval_info",
268
+ "client_session_rotation"
269
+ ];
270
+ function sanitizeViolation(raw) {
271
+ if (!raw || typeof raw !== "object") {
272
+ return null;
273
+ }
274
+ const source = raw;
275
+ const out = {};
276
+ for (const [k, v] of Object.entries(source)) {
277
+ if (!INTERNAL_FIELDS.has(k)) {
278
+ out[k] = v;
279
+ }
280
+ }
281
+ return out;
282
+ }
228
283
  function sanitizeScanResponse(raw) {
229
284
  const safe = raw.safe !== false;
230
- const approvalInfo = raw.approval_info;
285
+ const result = { safe };
286
+ for (const field of PRESERVED_GOVERNANCE_FIELDS) {
287
+ const value = raw[field];
288
+ if (value !== void 0 && value !== null) {
289
+ result[field] = value;
290
+ }
291
+ }
292
+ const rawViolations = raw.violations;
293
+ if (Array.isArray(rawViolations) && rawViolations.length > 0) {
294
+ const cleaned = rawViolations.map((v) => sanitizeViolation(v)).filter((v) => v !== null);
295
+ if (cleaned.length > 0) {
296
+ result.violations = cleaned;
297
+ }
298
+ }
231
299
  if (safe) {
232
- const result2 = {
233
- safe: true,
234
- reason: raw.reason || ""
235
- };
236
- if (approvalInfo) {
237
- result2.approval_info = approvalInfo;
300
+ result.reason = raw.reason || "";
301
+ return result;
302
+ }
303
+ let rawThreatType = raw.threat_type;
304
+ if (!rawThreatType && Array.isArray(rawViolations) && rawViolations.length > 0) {
305
+ const first = rawViolations[0];
306
+ if (first && typeof first === "object" && !Array.isArray(first)) {
307
+ const firstThreat = first.threat_type;
308
+ if (typeof firstThreat === "string") {
309
+ rawThreatType = firstThreat;
310
+ }
238
311
  }
239
- return result2;
240
312
  }
241
- const threatType = normalizeThreatType(raw.threat_type);
313
+ const threatType = normalizeThreatType(rawThreatType);
242
314
  const confidence = bucketConfidence(
243
315
  typeof raw.confidence === "number" ? raw.confidence : void 0
244
316
  );
@@ -247,22 +319,19 @@ function sanitizeScanResponse(raw) {
247
319
  typeof raw.severity === "string" ? raw.severity : void 0
248
320
  );
249
321
  const guidance = THREAT_GUIDANCE[threatType] || THREAT_GUIDANCE["unknown"];
250
- const result = {
251
- safe: false,
252
- threat_type: threatType,
253
- severity,
254
- confidence,
255
- reason: raw.reason || guidance,
256
- guidance
257
- };
258
- if (approvalInfo) {
259
- result.approval_info = approvalInfo;
260
- }
322
+ result.threat_type = threatType;
323
+ result.severity = severity;
324
+ result.confidence = confidence;
325
+ result.reason = raw.reason || guidance;
326
+ result.guidance = guidance;
261
327
  return result;
262
328
  }
263
329
 
264
330
  // src/version.ts
265
- var VERSION = "1.3.1";
331
+ var VERSION = "1.5.0";
332
+ function failOpenResult(reason) {
333
+ return { safe: true, reason, degraded: true };
334
+ }
266
335
  function generateUUID() {
267
336
  return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
268
337
  const r = Math.random() * 16 | 0;
@@ -279,6 +348,18 @@ function getScanHeaders(shrikeApiKey, requestId) {
279
348
  "X-Shrike-Request-ID": generateUUID()
280
349
  };
281
350
  }
351
+ function isBlocked(verdict) {
352
+ const action = verdict.action;
353
+ if (typeof action === "string" && action.length > 0) {
354
+ if (action === "allow" || action === "warn") return false;
355
+ if (action === "block" || action === "require_approval") return true;
356
+ }
357
+ const safe = verdict.safe;
358
+ if (typeof safe === "boolean") {
359
+ return !safe;
360
+ }
361
+ return false;
362
+ }
282
363
  function maybeAddSignupHint(result, apiKey) {
283
364
  if (apiKey) return result;
284
365
  if (result.upgrade_hint) return result;
@@ -304,11 +385,11 @@ var ShrikeGemini = class {
304
385
  console.warn("[shrike-guard] For full scanning (LLM analysis, session correlation): npx shrike-mcp --signup");
305
386
  }
306
387
  try {
307
- const { GoogleGenerativeAI } = __require("@google/genai");
308
- this._genAI = new GoogleGenerativeAI(this._apiKey);
309
- } catch {
388
+ const { GoogleGenAI } = __require("@google/genai");
389
+ this._genAI = new GoogleGenAI({ apiKey: this._apiKey });
390
+ } catch (err) {
310
391
  throw new Error(
311
- "@google/genai package is not installed. Install it with: npm install @google/genai"
392
+ `@google/genai is not installed or failed to initialize. Install it with: npm install @google/genai${err instanceof Error ? ` (${err.message})` : ""}`
312
393
  );
313
394
  }
314
395
  }
@@ -374,7 +455,7 @@ var ShrikeGemini = class {
374
455
  const controller = new AbortController();
375
456
  const timeoutId = setTimeout(() => controller.abort(), this._scanTimeout);
376
457
  try {
377
- const response = await fetch(`${this._shrikeEndpoint}/scan`, {
458
+ const response = await fetch(`${this._shrikeEndpoint}/api/scan/enforce`, {
378
459
  method: "POST",
379
460
  headers: getScanHeaders(this._shrikeApiKey),
380
461
  body: JSON.stringify({
@@ -389,7 +470,7 @@ var ShrikeGemini = class {
389
470
  });
390
471
  if (!response.ok) {
391
472
  if (this._failMode === "open" /* OPEN */) {
392
- return { safe: true, reason: `Scan API error: ${response.status}` };
473
+ return failOpenResult(`Scan API error: ${response.status}`);
393
474
  }
394
475
  throw new ShrikeScanError(`Scan API returned error: ${response.status}`);
395
476
  }
@@ -402,12 +483,12 @@ var ShrikeGemini = class {
402
483
  if (errorMessage.includes("abort")) {
403
484
  if (this._failMode === "open" /* OPEN */) {
404
485
  logWarning("Scan request timed out, failing open (allowing request)");
405
- return { safe: true, reason: "Scan timeout, failing open" };
486
+ return failOpenResult("Scan timeout, failing open");
406
487
  }
407
488
  throw new ShrikeScanError("Scan request timed out and fail_mode is 'closed'");
408
489
  }
409
490
  if (this._failMode === "open" /* OPEN */) {
410
- return { safe: true, reason: `Scan error: ${errorMessage}` };
491
+ return failOpenResult(`Scan error: ${errorMessage}`);
411
492
  }
412
493
  throw new ShrikeScanError(`Scan failed: ${errorMessage}`);
413
494
  } finally {
@@ -423,14 +504,14 @@ var ShrikeGenerativeModel = class {
423
504
  constructor(params, shrikeClient) {
424
505
  this._modelParams = params;
425
506
  this._shrikeClient = shrikeClient;
426
- this._model = this._shrikeClient.genAI.getGenerativeModel(params);
507
+ this._models = this._shrikeClient.genAI.models;
427
508
  }
428
509
  /**
429
510
  * Generate content with Shrike protection.
430
511
  */
431
512
  async generateContent(contents) {
432
513
  const scanResult = await this._shrikeClient._scanContent(contents);
433
- if (!scanResult.safe) {
514
+ if (isBlocked(scanResult)) {
434
515
  throw new ShrikeBlockedError(
435
516
  scanResult.reason || "Request blocked by Shrike",
436
517
  scanResult.threat_type,
@@ -438,14 +519,14 @@ var ShrikeGenerativeModel = class {
438
519
  scanResult.violations || []
439
520
  );
440
521
  }
441
- return this._model.generateContent(contents);
522
+ return this._models.generateContent({ model: this._modelParams.model, contents });
442
523
  }
443
524
  /**
444
525
  * Stream content generation with Shrike protection.
445
526
  */
446
527
  async generateContentStream(contents) {
447
528
  const scanResult = await this._shrikeClient._scanContent(contents);
448
- if (!scanResult.safe) {
529
+ if (isBlocked(scanResult)) {
449
530
  throw new ShrikeBlockedError(
450
531
  scanResult.reason || "Request blocked by Shrike",
451
532
  scanResult.threat_type,
@@ -453,13 +534,16 @@ var ShrikeGenerativeModel = class {
453
534
  scanResult.violations || []
454
535
  );
455
536
  }
456
- return this._model.generateContentStream(contents);
537
+ return this._models.generateContentStream({ model: this._modelParams.model, contents });
457
538
  }
458
539
  /**
459
540
  * Start a chat session with Shrike protection.
460
541
  */
461
542
  startChat(options) {
462
- const chat = this._model.startChat(options);
543
+ const chat = this._shrikeClient.genAI.chats.create({
544
+ model: this._modelParams.model,
545
+ ...options || {}
546
+ });
463
547
  return new ShrikeChatSession(chat, this._shrikeClient);
464
548
  }
465
549
  get modelName() {
@@ -476,7 +560,7 @@ var ShrikeChatSession = class {
476
560
  */
477
561
  async sendMessage(content) {
478
562
  const scanResult = await this._shrikeClient._scanContent(content);
479
- if (!scanResult.safe) {
563
+ if (isBlocked(scanResult)) {
480
564
  throw new ShrikeBlockedError(
481
565
  scanResult.reason || "Request blocked by Shrike",
482
566
  scanResult.threat_type,
@@ -484,14 +568,14 @@ var ShrikeChatSession = class {
484
568
  scanResult.violations || []
485
569
  );
486
570
  }
487
- return this._chat.sendMessage(content);
571
+ return this._chat.sendMessage({ message: content });
488
572
  }
489
573
  /**
490
574
  * Send a message with streaming and Shrike protection.
491
575
  */
492
576
  async sendMessageStream(content) {
493
577
  const scanResult = await this._shrikeClient._scanContent(content);
494
- if (!scanResult.safe) {
578
+ if (isBlocked(scanResult)) {
495
579
  throw new ShrikeBlockedError(
496
580
  scanResult.reason || "Request blocked by Shrike",
497
581
  scanResult.threat_type,
@@ -499,10 +583,10 @@ var ShrikeChatSession = class {
499
583
  scanResult.violations || []
500
584
  );
501
585
  }
502
- return this._chat.sendMessageStream(content);
586
+ return this._chat.sendMessageStream({ message: content });
503
587
  }
504
588
  get history() {
505
- return this._chat.history || [];
589
+ return typeof this._chat.getHistory === "function" ? this._chat.getHistory() : [];
506
590
  }
507
591
  };
508
592