Sanitize/reject 用户输入在 graphql(JS) 中包含不安全 html

Sanitize/reject user inputs containing unsafe html in graphql(JS)

我一直在上下搜索这个,但我找不到任何相关的东西,但是是否有一个很好的解决方案来清理 graphql 突变中用户输入中的 html 个字符?

我知道一个事实,像 name: "<script>{alert('foo')}</script>" 这样的输入被 graphql(在我的例子中是 apollo-server-express)按原样接受,但那不行。当然,像 React 这样的框架不会将该字符串设置为 html,所以它在那里是 "safe",但是如果 graphql 端点被一个将字符串嵌入为 html 的站点使用怎么办?

有人知道解决这个问题的好方法吗?我看过几个包裹,但它们大多很小,上面几乎没有 activity。

另一种解决方案是在数据库级别进行清理,例如 sanitize-html,但我想看看在模式级别是否有合适的解决方案

最后只是在模型级别进行清理,创建了一个通用模型 class,它清理了 args 中的所有内容:

export default class Model {
  constructor(parent, args, context, info) {
    this.db = db;
    this.parent = null;
    this.args = null;
    this.context = null;
    this.info = null;

    this.#init(parent, args, context, info);
  }

  #init = (parent, args, context, info) => {
    this.parent = parent;
    this.args = this.#sanitizeObject(args);
    this.context = context;
    this.info = info;
  };

  #sanitizeObject = (args) => {
    let sanitizedArgs = {};

    Object.entries(args).forEach(([key, value]) => {
      if (Array.isArray(value)) {
        sanitizedArgs[key] = this.#sanitizeArray(value);
      } else if (typeof value === 'object') {
        sanitizedArgs[key] = this.#sanitizeObject(args[key]);
      } else {
        sanitizedArgs[key] = this.#sanitizeInput(value);
      }
    });

    return sanitizedArgs;
  };

  #sanitizeArray = (args) => {
    return args.map((value) => {
      if (Array.isArray(value)) {
        return this.#sanitizeArray(value);
      } else if (typeof value === 'object') {
        return this.#sanitizeObject(value);
      } else {
        return this.#sanitizeInput(value);
      }
    });
  };

  #sanitizeInput = (input) => {
    return DOMPurify.sanitize(input);
  };
}