简体   繁体   English

如何正确清理 NestJS 输入?

[英]How to Properly Sanitize NestJS Input?

I'm asking this as I can't seem to get a straight answer.我问这个是因为我似乎无法得到一个直接的答案。

So, NestJS has a very elegant way of handling validation by using decorators.因此,NestJS 有一种非常优雅的方式来使用装饰器来处理验证。 That is, you define DTO classes with properties you expect, and annotate them with class-validator decorators.也就是说,您可以使用您期望的属性定义 DTO 类,并使用类验证器装饰器对它们进行注释。 For example, assume we have a route that accepts input from a contact form.例如,假设我们有一个接受来自联系表单的输入的路由。

class ContactInfoDTO {
     @IsString()
     @IsNotEmpty()
     name: string
     
     @IsEmail()
     email: string
     
     @IsString()
     @IsNotEmpty
     subject: string

     @IsString()
     @IsNotEmpty()
     body: string

}

This works great for validation.这非常适合验证。 If I enter an invalid email, it will reject it as expected.如果我输入无效的电子邮件,它会按预期拒绝。 But, here's my question.但是,这是我的问题。 What about input Sanitization?输入消毒怎么样? Say, for example, I enter a some JavaScript in the body parameter?比如说,我在 body 参数中输入了一些 JavaScript? Like, say, my body looks like this:比如说,我的身体看起来像这样:

body: “Hello <script>//some malicious code here</script>”

Now, this is still accepted.现在,这仍然被接受。 Even though the script tags are not converted to HTML entities, which does pose a bit of a security risk.即使脚本标签没有转换为 HTML 实体,这确实会带来一些安全风险。

So, my question is does NestJS have any kind of built-in Sanitization mechanisms?所以,我的问题是 NestJS 是否有任何内置的消毒机制? Is there proper documentation on this?是否有关于此的适当文件? Because I can't really find any, despite this kind of thing being very important in the context of web development.因为我真的找不到任何东西,尽管这种东西在 Web 开发的上下文中非常重要。

What's the best practice for doing input Sanitization in NestJS?在 NestJS 中进行输入清理的最佳实践是什么?

You could use the class-sanitizer library and apply its decorators to your model's properties:您可以使用 class-sanitizer并将其装饰器应用于模型的属性:

class ContactInfoDTO {
     @IsString()
     @IsNotEmpty()
     name: string
     
     @IsEmail()
     email: string
     
     @IsString()
     @IsNotEmpty
     subject: string

     @IsString()
     @IsNotEmpty()
     @Escape()
     body: string

}

Use sanitize-html with Transform like this:像这样将sanitize-htmlTransform一起使用:

import { ApiProperty } from '@nestjs/swagger';
import { Transform } from 'class-transformer';
import { IsString } from 'class-validator';
import * as sanitizeHtml from 'sanitize-html';

export class DocumentDto {
  @ApiProperty()
  @IsString()
  @Transform((value: string) => sanitizeHtml(value))
  public content: string;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM