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 * Organized by categories with enable/disable controls
*/ */
import DOMPurify from 'dompurify'
export interface TextTransform { export interface TextTransform {
id: string id: string
label: string label: string
@ -123,15 +125,35 @@ const toUrlDecode = (text: string): string => {
return text return text
} }
} }
const toHtmlEncode = (text: string): string => {
const div = document.createElement('div') function toHtmlEncode(str: string): string {
div.textContent = text // Ensure the input is a string
return div.innerHTML 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 toHtmlDecode = (text: string): string => {
const div = document.createElement('div') const sanitized = DOMPurify.sanitize(text, { RETURN_DOM: true })
div.innerHTML = text return sanitized.textContent || ''
return div.textContent || ''
} }
// Transform functions for Text Tools // 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 // Log the conversion attempt for debugging
eprintln!( // eprintln!(
"Converting {} with type: {}", // "Converting {} with type: {}",
text.chars().take(50).collect::<String>(), // text.chars().take(50).collect::<String>(),
conversion_type // conversion_type
); // );
match conversion_type.as_str() { match conversion_type.as_str() {
"csv_to_json" => csv_to_json(&text).map_err(|e| format!("CSV to JSON conversion failed: {}", e)), "csv_to_json" => csv_to_json(&text).map_err(|e| format!("CSV to JSON conversion failed: {}", e)),