0

Do you think that this functions are enough to prevent XSS if used to filter user input? And should I really make my own or use XSS libraries available? Give me constructive criticism please. Thank you everyone.

/**
 * Escape HTML string to prevent XSS.
 */
export const escapeHtml = (string: string): string => {
    if (isString(string)) {
        const entityMap = {
            "&": "&",
            "<": "&lt;",
            ">": "&gt;",
            '"': "&quot;"
        };
        return string.slice(0, string.length).replace(/[&<>"]/g, (s: string): string => entityMap[s]);
    }
    return string;
};

/**
 * Loop over Object to escape each of its value to prevent XSS.
 */
export const escapeHtmlQueryObject = (obj: { [string]: string }): { [string]: string } => {
    let result = obj;
    if (obj && isObject(obj)) {
        result = Object.keys(obj).reduce((res: { [string]: string }, key: string): {
            [string]: string
        } => {
            res[key] = escapeHtml(obj[key]);
            return res;
        }, {});
    } else if (process.env.NODE_ENV !== "production" && process.env.NODE_ENV !== "test") {
        console.error(`FilterXSSQueryObject can't process ${obj.toString()}`);
    }
    return result;
};
  • Friends don't let friends write their own XSS filters. Not in XXI century. Please look into https://www.youtube.com/watch?v=SXbrgvAK_5U and never do it again. – Marek Puchalski Aug 03 '20 at 06:31

1 Answers1

0

Compared to this answer, you may want to escape single quotes also.

That said, if you want to make sure your code is secure, it may be better to rely on a library that has been battle tested by security experts.

People don't like loading libraries for small things, but this is an important small thing, so I wouldn't mind it.

Unrelated: it seems that you're iterating over an object's keys to access its values in a roundabout way using Object.keys, but you can also just use Object.values.

Dennis Hackethal
  • 13,662
  • 12
  • 66
  • 115
  • Hi, Thank you for the response. Can you give me a reason why single quotes needs to be escaped also if I am already escaping most of the 'dangerous' chars? Thank you. – Emanuel Beni Aug 04 '20 at 08:57
  • Dunno for sure, presumably due to string injection into strings declared using single quotes. – Dennis Hackethal Aug 04 '20 at 17:13