-
Notifications
You must be signed in to change notification settings - Fork 0
/
replaydetector.js
104 lines (79 loc) · 2.17 KB
/
replaydetector.js
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
'use strict'
var ReplayDetector = function (timeout) {
this.first = {};
this.last = {};
this.first.next = this.last;
this.last.previous = this.first;
this.length = 0;
this.timeout = (timeout || 0)*1000;
this.items = {};
};
ReplayDetector.prototype.register = function (nonce) {
var node;
if (this.items[nonce.toString()] === undefined) {
node = {
nonce: nonce,
updated: Date.now(),
counter: 0,
previous: this.last.previous,
next: this.last
};
// Insert the new node at the end of the list.
this.last.previous.next = node;
this.last.previous = node;
this.items[nonce.toString()] = node;
this.length += 1;
this.invalidate();
}
};
ReplayDetector.prototype.check = function (nonce, count) {
var node, previous;
var result = false;
var now = Date.now();
if (node = this.items[nonce.toString()]) {
if (count > node.counter) {
if (this.timeout === 0 || now < node.updated + this.timeout) {
node.counter = count;
node.updated = now;
// Unlink from the list.
previous = node.previous;
node.previous.next = node.next;
node.next.previous = previous;
// Insert at the end of the list.
node.previous = this.last.previous;
node.next = this.last;
this.last.previous.next = node;
this.last.previous = node;
result = true;
}
}
}
return result;
};
ReplayDetector.prototype.remove = function (nonce) {
var node, previous;
var result;
if (node = this.items[nonce.toString()]) {
// Unlink from the list.
previous = node.previous;
node.previous.next = node.next;
node.next.previous = previous;
// Remove links to other nodes.
delete node.previous;
delete node.next;
delete this.items[nonce.toString()];
this.length -= 1;
result = true;
} else {
result = false;
}
};
ReplayDetector.prototype.invalidate = function () {
var current = this.first.next;
var now = Date.now();
while (current !== this.last && now > current.updated + this.timeout) {
current = current.next;
this.remove(current.previous.nonce);
}
};
module.exports = ReplayDetector;