防止特定post请求的节点xss杀毒器



Context是一个node express api,我在我的主server.js文件上使用xss-clean:

const xss = require('xss-clean');
// Prevent XSS attacks
app.use(xss());

问题:我想保存富文本,但它在卫生时被破坏了。

我想保持这个功能全局,但是它阻止我通过前端的富文本编辑器保存富文本(即tiptap- value)。使用编辑器保存的文本包含html标记,在保存到数据库时对其进行转义,当通过get请求将其推出到前端时,文本将与转义和元素的标记一起读出。

是否有一种方法可以防止这个全局组件在一个特定的请求或请求中的特定数据上工作?

或者是否有一种方法可以取消转义,以便在前端使用?

您可以简单地从您自己的node_modules文件夹中修改中间件,并且在开始解析请求对象的源代码文件中,您可以添加条件逻辑,检查请求对象是否满足您正在检查的条件—它是否是一个特定的请求或在请求中包含特定的数据—然后决定是否在请求对象上使用清理功能。

[的]xss-clean/src/index.js:

import { clean } from './xss'
/**
* export middleware
* @return {function} Middleware function
*/
module.exports = function () {
return (req, res, next) => {
if (req.body) req.body = clean(req.body)
if (req.query) req.query = clean(req.query)
if (req.params) req.params = clean(req.params)
next()
}
}

import { clean } from './xss'
/**
* export middleware
* @return {function} Middleware function
*/
module.exports = function () {
return (req, res, next) => {
if (req.url === "your route path") {
//don't use clean() on request object OR you can store only the data you want 
//in a temp variable to avoid getting sanitized, then sanitize the request 
//object with clean(), and then replace that sanitized data with the data
//in the temp variable OR as a new property in the req object
const dataPoint = req.body.something.dataPoint;
req.body = clean(req.body);
req.body.something.dataPoint = dataPoint;

return next();
}
if (req.body) req.body = clean(req.body)
if (req.query) req.query = clean(req.query)
if (req.params) req.params = clean(req.params)
next()
}
}

这有点俗气,但能完成任务。不消毒是很危险的,除非你确定这不会成为一个问题。你也可以在你的应用中不全局地使用这个中间件,而只在你希望这个中间件消毒的路由上使用它。

最新更新