Ccodemod

codemod/express-xss-prevention-escape-html

Transform Express.js res.send() calls that concatenate user input directly into HTML to use proper HTML escaping to prevent XSS vulnerabilities

securityxsscwe-79expresshtml-escapetransformationvulnerabilityprevention
Public
0 downloads
0 stars
How to Use
Run this codemod on your codebase using one of the following commands

The easiest way to run this codemod without installing anything globally:

Documentation

Express XSS Prevention - HTML Escaping Codemod

Security

This codemod automatically fixes Cross-Site Scripting (XSS) vulnerabilities in Express.js applications by transforming res.send() calls that concatenate user input directly into HTML strings. It adds proper HTML escaping using the escape-html library to prevent XSS attacks.

What it fixes

Direct concatenation of user input in res.send() calls creates XSS vulnerabilities. This codemod identifies these patterns and automatically adds HTML escaping:

String Concatenation

Before:

javascript

After:

javascript

Template Literals

Before:

javascript

After:

javascript

Complex Patterns

Before:

javascript

After:

javascript

Installation & Usage

bash

What gets transformed

Transformed:

  • res.send() calls with HTML content and user variables
  • String concatenation patterns with HTML tags
  • Template literals with HTML and variables
  • Member expressions like req.query.name, req.body.data
  • Multiple variables in the same HTML string

Not transformed:

  • Static HTML strings without variables
  • Already escaped content using escape-html or similar
  • JSON responses (res.json())
  • Plain text without HTML tags
  • Status code responses
  • Test files (.test.js, .spec.js)

Security Impact

This codemod helps prevent CWE-79: Cross-site Scripting (XSS) vulnerabilities by:

  1. Input Sanitization: Wraps user input in escapeHtml() calls
  2. Automatic Import: Adds require('escape-html') when needed
  3. Safe Defaults: Only transforms risky patterns, preserves safe code
  4. No Double-Escaping: Detects already escaped content

Requirements

  • Node.js application using Express.js
  • JavaScript or TypeScript files
  • Will automatically install escape-html dependency

Edge Cases Handled

  • ✅ Already escaped content (prevents double-escaping)
  • ✅ Multiple variables in single expression
  • ✅ Nested member expressions (req.body.user.name)
  • ✅ Mixed string concatenation and template literals
  • ✅ Existing import statements (preserves order)

Development

bash

Security References

License

MIT

Ready to contribute?

Build your own codemod and share it with the community.