From 6efd35a75ed41da97563937c9e4833ce9b6bfd39 Mon Sep 17 00:00:00 2001 From: Lovell Fuller Date: Tue, 9 Sep 2025 15:25:54 +0100 Subject: [PATCH] Help reduce the likelihood/effects of attempted ReDoS - Limits maximum string length to 200 characters - Normalizes whitespace runs to a single space character --- index.js | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/index.js b/index.js index ade033b..54afb49 100644 --- a/index.js +++ b/index.js @@ -46,7 +46,7 @@ cs.get = function (string) { }; cs.get.rgb = function (string) { - if (!string) { + if (!isValidString(string)) { return null; } @@ -61,6 +61,7 @@ cs.get.rgb = function (string) { let i; let hexAlpha; + string = normalizeSpace(string); if (match = string.match(hex)) { hexAlpha = match[2]; match = match[1]; @@ -128,12 +129,12 @@ cs.get.rgb = function (string) { }; cs.get.hsl = function (string) { - if (!string) { + if (!isValidString(string)) { return null; } const hsl = /^hsla?\(\s*([+-]?(?:\d{0,3}\.)?\d+)(?:deg)?\s*,?\s*([+-]?[\d.]+)%\s*,?\s*([+-]?[\d.]+)%\s*(?:[,|/]\s*([+-]?(?=\.\d|\d)(?:0|[1-9]\d*)?(?:\.\d*)?(?:[eE][+-]?\d+)?)\s*)?\)$/; - const match = string.match(hsl); + const match = normalizeSpace(string).match(hsl); if (match) { const alpha = Number.parseFloat(match[4]); @@ -149,12 +150,12 @@ cs.get.hsl = function (string) { }; cs.get.hwb = function (string) { - if (!string) { + if (!isValidString(string)) { return null; } const hwb = /^hwb\(\s*([+-]?\d{0,3}(?:\.\d+)?)(?:deg)?\s*[\s,]\s*([+-]?[\d.]+)%\s*[\s,]\s*([+-]?[\d.]+)%\s*(?:[\s,]\s*([+-]?(?=\.\d|\d)(?:0|[1-9]\d*)?(?:\.\d*)?(?:[eE][+-]?\d+)?)\s*)?\)$/; - const match = string.match(hwb); + const match = normalizeSpace(string).match(hwb); if (match) { const alpha = Number.parseFloat(match[4]); @@ -227,4 +228,12 @@ function hexDouble(number_) { return (string_.length < 2) ? '0' + string_ : string_; } +function isValidString(string) { + return typeof string === 'string' && string.length >= 4 && string.length <= 200; +} + +function normalizeSpace(string) { + return string.split(/\s+/).join(' ').trim(); +} + export default cs;