feat: disable some built-in regex

This commit is contained in:
ShareVB 2024-07-12 23:13:20 +02:00
parent 933d824083
commit 80d87cb290
3 changed files with 72 additions and 25 deletions

View file

@ -1,22 +1,34 @@
import { maskString } from 'data-guardian';
import ipRegex from 'ip-regex';
const jwtRegex = /\b([a-zA-Z0-9_=]+)\.([a-zA-Z0-9_=]+)\.([a-zA-Z0-9_\-\+\/=]*)\b/g;
const phoneRegex = /\b(?:(\+\d{1,4})[-.\s]?)?(?:[(](\d{1,3})[)][-.\s]?)?(\d{1,4})[-.\s]?(\d{1,4})[-.\s]?(\d{1,9})\b/g;
const jwtRegex = /\b([a-zA-Z0-9_=]{5,})\.([a-zA-Z0-9_=]{5,})\.([a-zA-Z0-9_\-\+\/=]{5,})\b/g;
const phoneRegex = /(?:(\+\d{1,4})[-.\s]?)(?:[(](\d{1,3})[)][-.\s]?)?(\d{1,4})[-.\s]?(\d{1,4})[-.\s]?(\d{1,9})\b/g;
const macRegex = /\b([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})\b/g;
const ipv6Regex = /\b(?:(::|[0-9a-fA-F]{1,4}:{1,2})([0-9a-fA-F]{1,4}:{1,2}){0,6}([0-9a-fA-F]{1,4}|::)?)\b/g;
const urlWithOrWithoutPrefixRegex = /\b(https?:\/\/)?(www\\.)?[-a-zA-Z0-9@:%.\_\\+~#=]{2,256}\\.[a-z]{2,6}\\b([-a-zA-Z0-9@:%\_\\+.~#?&//=]\*)\b/g;
const urlWithOrWithoutPrefixRegex = /\b(https?:\/\/)?(www\.)?[a-zA-Z0-9@:%._+~#=-]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_+.~#?&\/=]*)\b/g;
export function maskSensitiveData(value: string, customRegex?: string) {
export type MatcherNames = 'uuid' | 'creditCard' | 'ssn' | 'url' | 'ipv4' | 'email' | 'passwordInUri' | 'mac' | 'ipv6' | 'urlWithOrWithoutPrefix' | 'jwt' | 'phone';
export function maskSensitiveData({
value,
customRegex = '',
excludedMatchers = [],
}: {
value: string
customRegex?: string
excludedMatchers?: Array<MatcherNames>
}) {
excludedMatchers = excludedMatchers || [];
const emptyRegex = /(?:)/g;
return maskString(value, null as never, {
customRegex: new RegExp((customRegex || '').split('\n').map(line => `(${line})`).join('|'), 'gi'),
macRegex,
ipv6Regex,
urlWithOrWithoutPrefixRegex,
jwtRegex,
phoneRegex,
macRegex: excludedMatchers.includes('mac') ? emptyRegex : macRegex,
ipv6Regex: excludedMatchers.includes('ipv6') ? emptyRegex : ipRegex.v6({ includeBoundaries: false }),
urlWithOrWithoutPrefixRegex: excludedMatchers.includes('urlWithOrWithoutPrefix') ? emptyRegex : urlWithOrWithoutPrefixRegex,
jwtRegex: excludedMatchers.includes('jwt') ? emptyRegex : jwtRegex,
phoneRegex: excludedMatchers.includes('phone') ? emptyRegex : phoneRegex,
}, {
excludeMatchers: [
excludeMatchers: [...excludedMatchers, ...[
'passwordMention', 'password', 'passwordSubstring',
],
]],
});
}