html
<!-- Insert the vulnerable code into a short web application --><!DOCTYPE html><html><head><script src="vulnerable.js"></script></head><body><buttononclick="greetUser('<script>alert("Hacked!")</script>')">Say hello</button></body></html>
javascript // Vulnerable code function greetUser(username) { const welcomeMsg = "Welcome, " + username + "!"; console.log(welcomeMsg); } greetUser(''); n greetUser(username) { const welcomeMsg = "Welcome, " + username + "!"; console.log(welcomeMsg); } greetUser(''); ``` ```html ``` ```javascript // Solution to fix the vulnerable code function greetUser(username) { const safeUsername = username.replace(//g, '>'); const welcomeMsg = "Welcome, " + safeUsername + "!"; console.log(welcomeMsg); } greetUser(''); ``` To fix the vulnerability, we need to sanitize the input by escaping any dangerous characters (like `<` and `>`) before creating the welcome message. This will prevent any potentially harmful code from being executed.
javascript// Solution to fix the vulnerable codefunctiongreetUser(username){constsafeUsername=username.replace(/</g,'<').replace(/>/g,'>');constwelcomeMsg="Welcome, "+safeUsername+"!";console.log(welcomeMsg);}greetUser('<script>alert("Hacked!")</script>');