html
<!-- Insert the vulnerable code into a short web application --><!DOCTYPE html><html><head><title>Input Validation Example</title><script src="vulnerable.js"></script></head><body><inputid="userNameInput"type="text"placeholder="Enter your name"/><buttononclick="greetUser(userNameInput.value)">Greet</button></body></html>
javascript // vulnerable code function greetUser(userName) { alert('Hello, ' + userName + '!'); } const userInputElement = document.getElementById('userNameInput'); const userName = userInputElement.value; greetUser(userName); The vulnerability in the initial code is due to not validating or sanitizing the user input, which allows for potentially malicious content to be executed. The solution is to use a proper input validation and sanitization method, such as the `escapeHTML` function in the provided solution. This function creates a temporary DOM element and sets its textContent to the user input, which automatically escapes any potentially dangerous HTML entities. As a result, when the modified `greetUser` function uses `safeUserName`, it's guaranteed to be free from any potential threats.
javascript// solution how to fix the vulnerable codefunctionescapeHTML(unsafeText){constdiv=document.createElement('div');div.textContent=unsafeText;returndiv.innerHTML;}functiongreetUser(userName){constsafeUserName=escapeHTML(userName);alert('Hello, '+safeUserName+'!');}constuserInputElement=document.getElementById('userNameInput');constuserName=userInputElement.value;greetUser(userName);