|
| 1 | +import { |
| 2 | + HookEventType, |
| 3 | + PluginContext, |
| 4 | + PluginHandler, |
| 5 | + PluginParameters, |
| 6 | +} from '../types'; |
| 7 | +import { getCurrentContentPart, setCurrentContentPart } from '../utils'; |
| 8 | + |
| 9 | +export const handler: PluginHandler = async ( |
| 10 | + context: PluginContext, |
| 11 | + parameters: PluginParameters, |
| 12 | + eventType: HookEventType |
| 13 | +) => { |
| 14 | + let error = null; |
| 15 | + let verdict = true; |
| 16 | + let data: any = null; |
| 17 | + const transformedData: Record<string, any> = { |
| 18 | + request: { |
| 19 | + json: null, |
| 20 | + }, |
| 21 | + response: { |
| 22 | + json: null, |
| 23 | + }, |
| 24 | + }; |
| 25 | + let transformed = false; |
| 26 | + |
| 27 | + try { |
| 28 | + const regexPattern = parameters.rule; |
| 29 | + const redactText = parameters.redactText || '[REDACTED]'; |
| 30 | + const failOnDetection = parameters.failOnDetection || false; |
| 31 | + |
| 32 | + const { content, textArray } = getCurrentContentPart(context, eventType); |
| 33 | + |
| 34 | + if (!regexPattern) { |
| 35 | + throw new Error('Missing regex pattern'); |
| 36 | + } |
| 37 | + if (!content) { |
| 38 | + throw new Error('Missing text to match'); |
| 39 | + } |
| 40 | + |
| 41 | + const regex = new RegExp(regexPattern, 'g'); |
| 42 | + |
| 43 | + // Process all text items in the array |
| 44 | + let hasMatches = false; |
| 45 | + const mappedTextArray: Array<string | null> = []; |
| 46 | + textArray.forEach((text) => { |
| 47 | + if (!text) { |
| 48 | + mappedTextArray.push(null); |
| 49 | + return; |
| 50 | + } |
| 51 | + |
| 52 | + // Reset regex for each text when using global flag |
| 53 | + regex.lastIndex = 0; |
| 54 | + |
| 55 | + const matches = text.match(regex); |
| 56 | + if (matches && matches.length > 0) { |
| 57 | + hasMatches = true; |
| 58 | + } |
| 59 | + const replacedText = text.replace(regex, redactText); |
| 60 | + mappedTextArray.push(replacedText); |
| 61 | + }); |
| 62 | + |
| 63 | + // Handle transformation |
| 64 | + if (hasMatches) { |
| 65 | + setCurrentContentPart( |
| 66 | + context, |
| 67 | + eventType, |
| 68 | + transformedData, |
| 69 | + mappedTextArray |
| 70 | + ); |
| 71 | + transformed = true; |
| 72 | + } |
| 73 | + if (failOnDetection && hasMatches) { |
| 74 | + verdict = false; |
| 75 | + } |
| 76 | + data = { |
| 77 | + regexPattern, |
| 78 | + verdict, |
| 79 | + explanation: transformed |
| 80 | + ? `Pattern '${regexPattern}' matched and was replaced with '${redactText}'` |
| 81 | + : `The regex pattern '${regexPattern}' did not match any text.`, |
| 82 | + }; |
| 83 | + } catch (e: any) { |
| 84 | + error = e; |
| 85 | + data = { |
| 86 | + explanation: `An error occurred while processing the regex: ${e.message}`, |
| 87 | + regexPattern: parameters.rule, |
| 88 | + }; |
| 89 | + } |
| 90 | + |
| 91 | + return { error, verdict, data, transformedData, transformed }; |
| 92 | +}; |
0 commit comments