import type { HookEvent } from '../../src/types.js'; import { scanForInjection } from '../../src/rules/injection-patterns.js'; import { writeAuditLog } from '../../src/utils/logger.js'; import { formatAlert } from '../../src/utils/alert.js'; const handler = async (event: HookEvent): Promise => { try { const { type, action, context, sessionKey, timestamp, messages } = event; if (type !== 'message') return; let content = ''; if (action === 'received') { content = context.content ?? ''; } else if (action === 'preprocessed') { content = context.bodyForAgent ?? ''; } else { return; } if (!content) return; const result = scanForInjection(content); if (!result.matched) return; const alertText = formatAlert(result.findings); messages.push( `🛡️ **Prompt Injection Detector Warning**\n` + `Potential prompt injection or jailbreak attempt detected in ` + `${action === 'preprocessed' ? 'enriched agent content' : 'incoming message'}.\n\n` + alertText, ); writeAuditLog({ timestamp: timestamp.toISOString(), event: `${type}:${action}`, sessionKey, channel: context.channelId, isGroup: context.isGroup, alerts: result.findings, metadata: { messageLength: content.length, source: action }, }); } catch (err) { console.error( '[security-guardrails:prompt-injection-detector] Error:', err instanceof Error ? err.message : String(err), ); writeAuditLog({ timestamp: new Date().toISOString(), event: 'hook_error', sessionKey: event.sessionKey, alerts: [], metadata: { hook: 'prompt-injection-detector', error: err instanceof Error ? err.message : String(err) }, }); } }; export default handler;