nestjstypeormmiddlewarexsssanitization

ORM OR middleware sanitization level?


I'm currently developing a web application with Nest.JS as backend framework. I would like to sanitize values to avoid potential XSS attacks (package sanitize-html).

Should I put sanitization on a global middleware to clean strings as soon as I can (headers, body and query) OR in association with my ORM (TypeORM) because it is the deepest level. But this could lead to some data incoherency between what I want to save and what there is in database.

Thank you.


Solution

  • The package you use is made to sanitize html (https://www.npmjs.com/package/sanitize-html). So if your API receives HTML content in its request, it's a good idea to sanitize it in a middleware. It's better to only manipulate "clean" data in your API. So do it at the highest level, like this no matter where and how you use the HTML you know it is safe. Maybe one day you will not save it directly in the DB and you will want to do something else with it, like generate a document or anything else. That day you will not need to ask yourself if it's sanitized or not.

    But this package will only be useful for html content. Headers should not contains HTML and you will probably have some query params or body that doesn't include HTML. If you want to validate these other parameters in NestJS I advise you to use DTOs and guards.

    DTOs combined with NestJS ValidationPipe will allow you to validate the body and the query params to ensure there are no forbidden data. There are some basic examples in NestJS docs: https://docs.nestjs.com/techniques/validation#auto-validation

    If you want to validate the headers you can do it in a guard (cf https://docs.nestjs.com/guards) or any kind of middleware.

    About TypeORM, it's not really its jobs to protect you against XSS attack, but it's its job to protect you against SQL Injection. All ORM sanitize SQL requests by default (as long as you use their core API or query builder/runner) so you don't need to do anything about this.