llm-security/hooks/scripts/pre-prompt-inject-scan.mjs
Kjell Tore Guttormsen b6af9b46df feat(llm-security)!: v8 Phase 3 step 1 - remove the deprecated mode env-vars
BREAKING CHANGE: the four LLM_SECURITY_* configuration env-vars deprecated in
v7.3.0 are removed. .llm-security/policy.json is now the only source:

  LLM_SECURITY_INJECTION_MODE     -> injection.mode
  LLM_SECURITY_TRIFECTA_MODE      -> trifecta.mode
  LLM_SECURITY_ESCALATION_WINDOW  -> trifecta.escalation_window
  LLM_SECURITY_AUDIT_LOG          -> audit.log_path
  LLM_SECURITY_DEPRECATION_QUIET  -> dies with the mechanism it silenced

Setting a removed var is now inert - it does not warn, and it does not
configure. Env-vars with no policy equivalent (PRECOMPACT_MODE,
PRECOMPACT_MAX_BYTES, UPDATE_CHECK, MCP_CACHE_FILE, IDE_ROOTS) are unaffected.

getPolicyValueWithEnvWarn and its one-shot stderr warning are deleted from
policy-loader.mjs, along with the module-scoped warned-var Set. The four call
sites collapse to getPolicyValue. getPolicyValue's JSDoc claimed "environment
variables ALWAYS take precedence" - it never read env itself, so that line
described the shim, and it is corrected rather than deleted.

User-facing hook strings that advertised a removed var as the escape hatch now
name the policy key instead: the inject-scan block reason, its warn-mode note,
both escalation-window advisories, and the trifecta block message. A blocked
user following the old text would have set a var that does nothing.

Tests. tests/lib/v8-env-removal.test.mjs is the regression gate and was written
failing first (8 of 12 red before the change). It pins the NEGATIVE - setting a
removed var does not alter the outcome - because that is the half that rots
silently: a re-introduced process.env read would leave every migrated positive
test green, since those configure through policy.json and never set the var at
all. One assertion walks hooks/scripts and scanners for `process.env.<removed>`
so the re-introduction is caught structurally, not only behaviourally.

The 44 env-driven test occurrences (18 inject-scan, 13+4 session-guard, 9
audit-trail) migrate to a throwaway .llm-security/policy.json via a new
runHookWithPolicy helper in hook-helper.mjs; audit-trail runs in-process, so it
supplies the same policy through CLAUDE_PROJECT_ROOT. The D3 mechanism tests in
policy-loader.test.mjs are deleted with the mechanism.

Suite 2039 tests, 2037 pass (+12 gate, -7 D3 mechanism). The 2 failures are the
known parallel-load timing flakes (pre-compact-scan size-cap,
pre-install-supply-chain F-3); both green when run isolated.

Remaining in Phase 3: posture-scanner TRIFECTA_MODE heuristic, riskScoreV1
removal, ghost-var cleanup, docs + migration note.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BB4vXvwvtW4dxbPRd6vsez
2026-08-09 10:17:47 +02:00

138 lines
5.3 KiB
JavaScript

#!/usr/bin/env node
// Hook: pre-prompt-inject-scan.mjs
// Event: UserPromptSubmit
// Purpose: Scan user prompts for injection patterns before sending to model.
//
// Catches injection hidden in pasted content, piped input, or headless mode.
// Critical patterns (direct override, spoofed headers, identity redefinition) -> block.
// High patterns (subtle manipulation, context normalization) -> warn.
// Medium patterns (leetspeak, homoglyphs, zero-width, multi-language) -> advisory.
//
// v2.3.0: mode configurable (block/warn/off). Default: block.
// v8.0.0: mode moved from the LLM_SECURITY_INJECTION_MODE env var to the
// `injection.mode` key in .llm-security/policy.json.
// v5.0.0: MEDIUM patterns emit advisory (never block). Appended to existing advisory
// when critical/high patterns are also present.
//
// Protocol:
// - Read JSON from stdin: { session_id, message: { role, content } }
// - content may be a string or array of content blocks
// - Block: exit 2, stdout JSON { decision: "block", reason: "..." }
// - Allow: exit 0
// - Warn: exit 0, stdout JSON { systemMessage: "..." }
import { readFileSync } from 'node:fs';
import { scanForInjection } from '../../scanners/lib/injection-patterns.mjs';
import { getPolicyValue } from '../../scanners/lib/policy-loader.mjs';
// ---------------------------------------------------------------------------
// Mode configuration. v8.0.0: `injection.mode` in .llm-security/policy.json is
// the only source; the LLM_SECURITY_INJECTION_MODE env-var was removed after
// its v7.3.0 deprecation runway.
// ---------------------------------------------------------------------------
const VALID_MODES = new Set(['block', 'warn', 'off']);
const resolved = getPolicyValue('injection', 'mode', 'block');
const mode = VALID_MODES.has(resolved) ? resolved : 'block';
// Off mode: skip scanning entirely
if (mode === 'off') {
process.exit(0);
}
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
/**
* Extract plaintext from the UserPromptSubmit input payload.
* Handles multiple input shapes for robustness.
*/
function extractText(input) {
// Shape 1: { message: { content: "string" } }
// Shape 2: { message: { content: [{ type: "text", text: "..." }] } }
// Shape 3: { prompt: "string" } (fallback)
const message = input?.message;
if (!message) return input?.prompt ?? '';
const content = message.content;
if (typeof content === 'string') return content;
if (Array.isArray(content)) {
return content
.filter((block) => block.type === 'text')
.map((block) => block.text)
.join('\n');
}
return '';
}
// ---------------------------------------------------------------------------
// Main
// ---------------------------------------------------------------------------
let input;
try {
const raw = readFileSync(0, 'utf-8');
input = JSON.parse(raw);
} catch {
// Cannot parse stdin — allow (don't block on parse errors)
process.exit(0);
}
const text = extractText(input);
if (!text.trim()) {
process.exit(0);
}
const { critical, high, medium } = scanForInjection(text);
if (critical.length > 0 && mode === 'block') {
const reason =
`Blocked: prompt injection pattern detected (OWASP LLM01).\n` +
critical.map((c) => ` - ${c}`).join('\n') +
'\n' +
` This prompt contains patterns associated with prompt injection attacks.\n` +
` If intentional (testing, security research), set "injection": {"mode": "warn"} in .llm-security/policy.json to allow with advisory.`;
process.stdout.write(JSON.stringify({ decision: 'block', reason }));
process.exit(2);
}
if (critical.length > 0 || high.length > 0) {
// In warn mode, critical patterns are downgraded to advisory.
// In block mode, we only reach here if critical is empty (only high patterns).
const allFindings = [...critical, ...high];
const severity = critical.length > 0 ? 'CRITICAL' : 'HIGH';
let message =
`SECURITY ADVISORY (prompt-inject-scan): ${severity} manipulation signals detected.\n\n` +
allFindings.map((f, i) => `[${i + 1}] ${f}`).join('\n') +
'\n\n' +
` These patterns may indicate prompt manipulation in pasted content.\n` +
` Review the source before proceeding.` +
(mode === 'warn' && critical.length > 0
? `\n Note: blocking is disabled (policy.json injection.mode=warn).`
: '');
// Append MEDIUM count if present (never list individual medium findings with critical/high)
if (medium.length > 0) {
message += `\n Additionally, ${medium.length} lower-confidence signal(s) detected (MEDIUM).`;
}
process.stdout.write(JSON.stringify({ decision: 'allow', systemMessage: message }));
process.exit(0);
}
// MEDIUM-only: advisory (never block)
if (medium.length > 0) {
const message =
`SECURITY ADVISORY (prompt-inject-scan): MEDIUM obfuscation/manipulation signals detected.\n\n` +
medium.map((f, i) => `[${i + 1}] ${f}`).join('\n') +
'\n\n' +
` These patterns may indicate obfuscated prompt manipulation (leetspeak, homoglyphs, multi-language).\n` +
` Review the source before proceeding. MEDIUM signals are advisory-only and never block.`;
process.stdout.write(JSON.stringify({ decision: 'allow', systemMessage: message }));
process.exit(0);
}
// Clean — allow silently
process.exit(0);