UNPKG

payu-websdk

Version:
56 lines (48 loc) 1.4 kB
/** * HTML Encoder utility to prevent XSS attacks * Encodes special HTML characters to their entity equivalents */ /** * Encodes HTML special characters * @param {string} str - String to encode * @returns {string} - HTML encoded string */ function encodeHTML(str) { if (str === null || str === undefined) return ''; return String(str) .replace(/&/g, '&amp;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;') .replace(/"/g, '&quot;') .replace(/'/g, '&#39;') .replace(/\//g, '&#x2F;'); } /** * Encodes HTML attributes * @param {string} str - String to encode for attribute * @returns {string} - HTML attribute encoded string */ function encodeHTMLAttribute(str) { if (str === null || str === undefined) return ''; return String(str) .replace(/&/g, '&amp;') .replace(/"/g, '&quot;') .replace(/'/g, '&#39;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;'); } /** * Safely encodes JSON for HTML context * @param {object} obj - Object to encode as JSON * @returns {string} - Safely encoded JSON string */ function encodeJSONForHTML(obj) { if (obj === null || obj === undefined) return ''; const jsonString = JSON.stringify(obj); return encodeHTMLAttribute(jsonString); } module.exports = { encodeHTML, encodeHTMLAttribute, encodeJSONForHTML };