aboutsummaryrefslogtreecommitdiffstats
path: root/server/src/serverLib/RateLimiter.js
blob: a4a0cd80eb83cb21575ca291a3fb16f64ad2e9ce (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
import { RateLimits } from '../utility/Constants';

/**
  * Tracks frequency of occurances based on `id` (remote address), then allows or
  * denies command execution based on comparison with `threshold`
  * @property {Object} data - The current stats data
  * @author Marzavec ( https://github.com/marzavec )
  * @author Andrew Belt ( https://github.com/AndrewBelt )
  * @version v2.0.0
  * @license WTFPL ( http://www.wtfpl.net/txt/copying/ )
  */
class RateLimiter {
  /**
    * Create a ratelimiter instance
    */
  constructor() {
    /**
      * Data holder rate limit records
      * @type {Object}
      */
    this.records = {};

    /**
      * Time in milliseconds to decrement ratelimit weight
      * @type {Number}
      */
    this.halflife = RateLimits.halflife;

    /**
      * Weight until ratelimited
      * @type {Number}
      */
    this.threshold = RateLimits.threshold;

    /**
      * Stores the associated connection fingerprint with record id
      * @type {Array}
      */
    this.hashes = [];
  }

  /**
    * Finds current score by `id`
    * @param {String} id target id / address
    * @private
    * @return {Object} Object containing the record meta
    */
  search(id) {
    let record = this.records[id];

    if (!record) {
      this.records[id] = {
        time: Date.now(),
        score: 0,
      };

      record = this.records[id];
    }

    return record;
  }

  /**
    * Adjusts the current ratelimit score by `deltaScore`
    * @param {String} id target id / address
    * @param {Number} deltaScore amount to adjust current score by
    * @example
    * // Penalize by 1 and store if connection is ratelimited or not
    * let isLimited = police.frisk(socket.address, 1);
    * @public
    * @return {Boolean} True if record threshold has been exceeded
    */
  frisk(id, deltaScore) {
    const record = this.search(id);

    if (record.arrested) {
      return true;
    }

    record.score *= Math.pow(2, -(Date.now() - record.time ) / this.halflife);
    record.score += deltaScore;
    record.time = Date.now();

    if (record.score >= this.threshold) {
      return true;
    }

    return false;
  }

  /**
    * Statically set server to no longer accept traffic from `id`
    * @param {String} id target id / address
    * @example
    * // Usage within a command module:
    * let badClient = server.findSockets({ channel: socket.channel, nick: targetNick });
    * server.police.arrest(badClient[0].address, badClient[0].hash);
    * @public
    * @return {void}
    */
  arrest(id, hash) {
    const record = this.search(id);

    record.arrested = true;
    this.hashes[hash] = id;
  }

  /**
    * Remove statically assigned limit from `id`
    * @param {String} id target id / address
    * @example
    * // Usage within a command module:
    * server.police.pardon('targetHashOrIP');
    * @public
    * @return {void}
    */
  pardon(id) {
    let targetId = id;
    if (typeof this.hashes[targetId] !== 'undefined') {
      targetId = this.hashes[targetId];
    }

    const record = this.search(targetId);
    record.arrested = false;
  }

  /**
    * Clear all records
    * @public
    * @return {void}
    */
  clear() {
    this.records = {};
    this.hashes = [];
  }
}

export default RateLimiter;