|
| 1 | +import { |
| 2 | + HookEventType, |
| 3 | + PluginContext, |
| 4 | + PluginHandler, |
| 5 | + PluginParameters, |
| 6 | +} from '../types'; |
| 7 | +import { getText, post } from '../utils'; |
| 8 | + |
| 9 | +const AIRS_URL = |
| 10 | + 'https://service.api.aisecurity.paloaltonetworks.com/v1/scan/sync/request'; |
| 11 | + |
| 12 | +const fetchAIRS = async (payload: any, apiKey: string, timeout?: number) => { |
| 13 | + const opts = { |
| 14 | + headers: { 'x-pan-token': apiKey }, |
| 15 | + }; |
| 16 | + return post(AIRS_URL, payload, opts, timeout); |
| 17 | +}; |
| 18 | + |
| 19 | +export const handler: PluginHandler = async ( |
| 20 | + ctx: PluginContext, |
| 21 | + params: PluginParameters, |
| 22 | + hook: HookEventType |
| 23 | +) => { |
| 24 | + const apiKey = |
| 25 | + (params.credentials?.AIRS_API_KEY as string | undefined) || |
| 26 | + process.env.AIRS_API_KEY || |
| 27 | + ''; |
| 28 | + |
| 29 | + let verdict = true; |
| 30 | + let data: any = null; |
| 31 | + let error: any = null; |
| 32 | + |
| 33 | + try { |
| 34 | + const text = getText(ctx, hook); // prompt or response |
| 35 | + |
| 36 | + const payload = { |
| 37 | + tr_id: |
| 38 | + typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function' |
| 39 | + ? crypto.randomUUID() |
| 40 | + : Math.random().toString(36).substring(2) + Date.now().toString(36), |
| 41 | + ai_profile: { |
| 42 | + profile_name: params.profile_name ?? 'dev-block-all-profile', |
| 43 | + }, |
| 44 | + metadata: { |
| 45 | + ai_model: params.ai_model ?? 'unknown-model', |
| 46 | + app_user: params.app_user ?? 'portkey-gateway', |
| 47 | + }, |
| 48 | + contents: [ |
| 49 | + { [hook === 'beforeRequestHook' ? 'prompt' : 'response']: text }, |
| 50 | + ], |
| 51 | + }; |
| 52 | + |
| 53 | + const res: any = await fetchAIRS(payload, apiKey, params.timeout); |
| 54 | + |
| 55 | + if (!res || typeof res.action !== 'string') { |
| 56 | + throw new Error('Malformed AIRS response'); |
| 57 | + } |
| 58 | + if (res.action === 'block') { |
| 59 | + verdict = false; |
| 60 | + } |
| 61 | + data = res; |
| 62 | + } catch (e: any) { |
| 63 | + error = e; |
| 64 | + verdict = false; |
| 65 | + } |
| 66 | + |
| 67 | + return { verdict, data, error }; |
| 68 | +}; |
0 commit comments