Advertisement
dev017

XSS, sql injection protection with typescript

Jul 28th, 2023
148
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function validateParameters(param1: string, param2: string): void {
  2.   const parameterRegEx = /^[a-zA-Z0-9_]+$/;
  3.  
  4.   if (!parameterRegEx.test(param1) || !parameterRegEx.test(param2)) {
  5.     throw new Error("Invalid parameters supplied.");
  6.   }
  7. }
  8.  
  9. function checkUrlSecurity(url: string): string {
  10.   const xssPattern = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi;
  11.   const sqlInjectionPattern = /([';])+OR\s*(\d|\=)/gi;
  12.  
  13.   const decodedURL = decodeURIComponent(url);
  14.   const trimmedURL = decodedURL.replace(/\/+$/, '');
  15.   const protocolRegex = /^(http|https):\/\//i;
  16.   const protocolRemovedURL = trimmedURL.replace(protocolRegex, '');
  17.   const noQueryStringURL = protocolRemovedURL.replace(/\?.*$/, '');
  18.   const noFragmentsURL = noQueryStringURL.replace(/#.*/, '');
  19.   const finalURL = noFragmentsURL.trim();
  20.  
  21.   if (xssPattern.test(finalURL)) {
  22.     return "XSS vulnerability detected";
  23.   } else if (sqlInjectionPattern.test(finalURL)) {
  24.     return "SQL injection vulnerability detected";
  25.   } else {
  26.     return "URL is secure";
  27.   }
  28. }
  29.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement