UNPKG

1.67 kBJavaScriptView Raw
1"use strict";
2
3/**
4 * Implementation of failure aware rate restriction.
5 *
6 * Will intercept monitor requests. After a certain number of failures, it will block for a duration.
7 *
8 * Requires ```block-failed``` package.
9 *
10 * @param {object} [settings] settings for rate restriction, or null to disable
11 * @param {number} settings.blockAttemptMs duration to monitor failure for
12 * @param {number} settings.blockAttemptCount number of failures allowed in this duration
13 * @param {number} settings.blockDurationMs duration to block for
14 * @return {ExpressMiddlewareFunction}
15 */
16function failure(settings = null)
17{
18 if (settings)
19 {
20 let blocker = require('block-failed');
21
22 // decypher config and defaults
23 const blockAttemptMs = settings.blockAttemptMs || 60 * 1000;
24 const blockAttemptCount = settings.blockAttemptCount || 5;
25 const blockDurationMs = settings.blockDurationMs || 5 * 60 * 1000;
26
27 // construct block object
28 const block = blocker(blockDurationMs, blockAttemptMs, blockAttemptCount - 1);
29
30 return function (req, res, next)
31 {
32 let attempted = false;
33
34 block(req.clientIp, (on_failure) =>
35 {
36 attempted = true;
37 res.on('finish', function ()
38 {
39 if (res.statusCode !== 200)
40 {
41 on_failure();
42 }
43 });
44 next();
45 }, (blockedMs) =>
46 {
47 if (!attempted)
48 {
49 res.error(`Operation is disabled due to too many failed attempts. Please try again in ${Math.round(blockedMs / 1000)} seconds`);
50 }
51 });
52 };
53 }
54
55 return function (req, res, next)
56 {
57 next();
58 };
59
60}
61
62module.exports = failure;