Skip to content

Instantly share code, notes, and snippets.

@space11
Created September 4, 2023 21:47
Show Gist options
  • Save space11/19b05367d2401cb456372b440cb8e66a to your computer and use it in GitHub Desktop.
Save space11/19b05367d2401cb456372b440cb8e66a to your computer and use it in GitHub Desktop.
Sanitizes input data to mitigate potential security risks by removing or escaping special characters, HTML entities, Unicode characters, and null bytes.
/**
* Sanitizes input data to mitigate potential security risks by removing or escaping
* special characters, HTML entities, Unicode characters, and null bytes.
*
* @param input The input data to be sanitized.
* @returns A sanitized version of the input data.
*/
function sanitizeData(input: string): string {
/**
* Removes carriage return characters (\r).
*/
let result = input.replace(/\r/g, '');
/**
* Escapes single quotes ('') to prevent SQL injection.
*/
result = result.replace(/'/g, "''");
/**
* Escapes double quotes (\"\") to prevent issues in certain contexts.
*/
result = result.replace(/"/g, '\\"');
// Remove or escape special SQL characters (hyphens and semicolons)
const specialCharacters = /[-;]/g;
/**
* Removes or escapes special SQL characters (hyphens and semicolons)
* to prevent SQL injection and other security risks.
*/
result = result.replace(specialCharacters, '');
// Escape HTML and JavaScript injection characters (<, >, &)
const htmlEntities = {
'<': '&lt;',
'>': '&gt;',
'&': '&amp;'
// Add more as needed
};
/**
* Escapes HTML and JavaScript injection characters (<, >, &)
* to prevent cross-site scripting (XSS) attacks.
*/
result = result.replace(/[<>&]/g, (match) => htmlEntities[match]);
/**
* Removes or escapes Unicode characters outside the ASCII range
* to enhance security.
*/
result = result.replace(/[^\x00-\x7F]+/g, '');
/**
* Removes null bytes (\0) to prevent unexpected behavior.
*/
result = result.replace(/\0/g, '');
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment