From 1c79adb9068ec9e1f531e3710c5f86af097e365c Mon Sep 17 00:00:00 2001 From: Greg Date: Thu, 29 May 2025 17:14:44 +0200 Subject: [PATCH] feat: implement core UI and utility modules with form handling and data validation and add data security against XSS. --- js/ui.js | 10 +++++----- js/utils.js | 22 +++++++++++++++++++++- 2 files changed, 26 insertions(+), 6 deletions(-) diff --git a/js/ui.js b/js/ui.js index 91612ed..11edcc0 100644 --- a/js/ui.js +++ b/js/ui.js @@ -303,7 +303,7 @@ const UI = (() => { row.innerHTML = ` ${Utils.formatDate(entry.date)} ${entry.weight} kg - ${entry.notes} + ${Utils.sanitizeHTML(entry.notes)} @@ -350,10 +350,10 @@ const UI = (() => { const row = document.createElement('tr'); row.innerHTML = ` ${Utils.formatDate(entry.date)} - ${Utils.truncateText(entry.breakfast, 30)} - ${Utils.truncateText(entry.lunch, 30)} - ${Utils.truncateText(entry.dinner, 30)} - ${Utils.truncateText(entry.otherMeals, 30)} + ${Utils.sanitizeHTML(Utils.truncateText(entry.breakfast, 30))} + ${Utils.sanitizeHTML(Utils.truncateText(entry.lunch, 30))} + ${Utils.sanitizeHTML(Utils.truncateText(entry.dinner, 30))} + ${Utils.sanitizeHTML(Utils.truncateText(entry.otherMeals, 30))} diff --git a/js/utils.js b/js/utils.js index 1659d5b..c1425ce 100644 --- a/js/utils.js +++ b/js/utils.js @@ -155,6 +155,25 @@ const Utils = (() => { } }; + /** + * Sanitize HTML to prevent XSS attacks. + * Replaces special characters with their HTML entities. + * @param {string} text - The text to sanitize. + * @returns {string} - The sanitized text. + */ + const sanitizeHTML = (text) => { + if (typeof text !== 'string') return ''; + return text.replace(/[&<>"']/g, function (match) { + return { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + "'": ''' + }[match]; + }); + }; + // Return public API return { formatDate, @@ -163,6 +182,7 @@ const Utils = (() => { showNotification, validateWeightEntry, calculateWeightStats, - copyToClipboard + copyToClipboard, + sanitizeHTML }; })();