速率限制以防止ExpressJS中的恶意行为

Rate limiting to prevent malicious behavior in ExpressJS

本文关键字:恶意 ExpressJS 速率      更新时间:2023-09-26

有人让我意识到我正在开发的应用程序中存在一些缺陷(主要是在前端的JavaScript中),这让我有可能一次点击大量按钮并发送大量事务性电子邮件。这显然不好。

我认为在ExpressJS中处理这一问题的一种方法是使用app.all()来计算在特定时间段内发生的请求数量。我会将其存储在带有时间戳的会话元数据中,如果在Y时间内发生了X个以上的请求,我会将它们中断一段时间,直到限制到期。

以前有人做过这件事吗?或者有什么建议/提示可以帮助我吗?更可取的是,我的应用程序中可以轻松进出的东西。谢谢

您可以在网页中使用Collate对象。

function Collate(timeout) {
  this.timeout = timeout || 1000;
}
Collate.prototype = {
  time: 0,
  idle: function() {
    var t = new Date().getTime();
    return (t - this.time > this.timeout && (this.time = t));
  },
  prefer: function(func) {
    this.func = func;
    clearTimeout(this.timer);
    this.timer = setTimeout(func, this.timeout);
  }
};

如果您希望函数运行一次,而在接下来的1秒内不再运行。就像如果你想阻止用户多次提交表格,你可以这样做:

var timer = new Collate(3000);  //3 seconds
button1.onclick = function() {
    if(timer.idle()) {
        button1.form.submit();
    } else alert("Don't click too quickly!");
}
//or on the form tag
<script>var submitTimer = new Collate(3000);</script>
<form action="post" onsubmit="return submitTimer.idle();">

如果您希望一个事件触发多次,但只想对上次触发作出反应。就像如果你想在用户完成输入后进行搜索,你可以这样做:

var timer = new Collate(700); //0.7 seconds
textfield1.onkeyup = function() {
    timer.prefer(function() {
        autocomplete.search(textfield1.value);
    });
};