Hi I am writing a small chat here on node.js + socket.io, and the question arose: -how to validate messages correctly (for example, with a regular schedule) to prevent the user from sending messages theoretically containing javascript code? Do not throw an example of such a regular season?

  • one
    The best protection is the screening of the message, so that even if there is a JS in it, it will be displayed as text. Everything else is a potential security hole. - ReinRaus

1 answer 1

Well, it is not necessary to validate it, it is enough or not to set the value that came from the backend through .innerHTML or filter it, for example, when sending:

 var unsaveBtn = document.getElementById('unsaveBtn'); var saveBtn = document.getElementById('saveBtn'); var message = document.getElementById('message'); var result = document.getElementById('result'); function esc(html) { var el = document.createElement('div'); el.textContent = html; return el.innerHTML; } unsaveBtn.addEventListener('click', function() { result.innerHTML = message.value; }); saveBtn.addEventListener('click', function() { result.innerHTML = esc(message.value); }); 
 <textarea id="message"> <b>Hello!</b> <script> alert(); </script> </textarea> <br/> <input type="button" id="unsaveBtn" value="Опасно отправить" /> <input type="button" id="saveBtn" value="Отправить безопасно" /> <div id="result"></div>