Cross-site scripting lets an attacker run JavaScript in another user’s browser, in the context of a trusted site. It can steal session data, perform actions as the victim, or rewrite the page.
Three types
- Reflected — malicious input in a URL is echoed back in the response.
- Stored — the payload is saved (for example in a comment) and served to every visitor.
- DOM-based — client-side JavaScript writes untrusted data into the page, e.g. via
innerHTML.
Prevention
- Encode output for the context it lands in: HTML body, attribute, URL or JavaScript.
- Prefer safe DOM APIs such as
textContentoverinnerHTML. - Sanitise rich HTML with an allow-list library.
- Deploy a strict Content Security Policy.
- Mark session cookies
HttpOnly,SecureandSameSite.
