feat: enhance HTML encoding/decoding with input validation

- Improved `toHtmlEncode` to validate string input and added sanitization in `toHtmlDecode`
This commit is contained in:
Sergey Kurdin 2025-06-23 15:00:53 -04:00
parent 717a7c0729
commit 34d304d1b8
3 changed files with 35 additions and 12 deletions

View File

@ -3,6 +3,8 @@
* Organized by categories with enable/disable controls
*/
import DOMPurify from 'dompurify'
export interface TextTransform {
id: string
label: string
@ -123,15 +125,35 @@ const toUrlDecode = (text: string): string => {
return text
}
}
const toHtmlEncode = (text: string): string => {
const div = document.createElement('div')
div.textContent = text
return div.innerHTML
function toHtmlEncode(str: string): string {
// Ensure the input is a string
if (typeof str !== 'string') {
console.warn('Input to encodeHtmlSpecialChars was not a string:', str)
return '' // Or throw an error, depending on desired behavior
}
return str.replace(/[&<>"']/g, function (char) {
switch (char) {
case '&':
return '&amp;' // Ampersand
case '<':
return '&lt;' // Less than
case '>':
return '&gt;' // Greater than
case '"':
return '&quot;' // Double quote
case "'":
return '&#039;' // Single quote (apostrophe)
default:
return char // Should not happen with the given regex, but good practice
}
})
}
const toHtmlDecode = (text: string): string => {
const div = document.createElement('div')
div.innerHTML = text
return div.textContent || ''
const sanitized = DOMPurify.sanitize(text, { RETURN_DOM: true })
return sanitized.textContent || ''
}
// Transform functions for Text Tools

View File

@ -0,0 +1 @@
Special Settings: Special Settings

View File

@ -347,11 +347,11 @@ pub async fn format_convert(text: String, conversion_type: String) -> Result<Str
}
// Log the conversion attempt for debugging
eprintln!(
"Converting {} with type: {}",
text.chars().take(50).collect::<String>(),
conversion_type
);
// eprintln!(
// "Converting {} with type: {}",
// text.chars().take(50).collect::<String>(),
// conversion_type
// );
match conversion_type.as_str() {
"csv_to_json" => csv_to_json(&text).map_err(|e| format!("CSV to JSON conversion failed: {}", e)),