-
-
Notifications
You must be signed in to change notification settings - Fork 235
/
Copy pathapi_keys.js
88 lines (75 loc) · 1.71 KB
/
api_keys.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
const crypto = require('crypto');
const { logger } = require('./logging');
const keys = new Set();
const accountIdToKey = {};
function addKeyLine(line) {
const splits = line.split(':');
keys.add(splits[0]);
if (splits[1]) {
accountIdToKey[splits[1]] = splits[0];
}
}
try {
const raw = require('./api_key_list.js').forEach(addKeyLine);
logger.info(`Loaded ${keys.size} keys from API keyfile`);
} catch (err) {
// No keyfile. That's ok.
}
// Map from key to number of recent requests - this is not persisted through
// restarts.
const recentRequestCount = {};
function isValidKey(key) {
return keys.has(key);
}
function getKeyFromRequest(req) {
if (req.query.key) {
return req.query.key;
}
if (req.body.key) {
return req.body.key;
}
return null;
}
function requestHasValidKey(req) {
const key = getKeyFromRequest(req);
if (key) {
return isValidKey(key);
}
return false;
}
function countRequest(req) {
const key = getKeyFromRequest(req);
if (!key) {
return;
}
if (!recentRequestCount[key]) {
recentRequestCount[key] = 0;
}
recentRequestCount[key] += 1;
}
function getNumRecentRequests(key) {
return recentRequestCount[key] || 0;
}
function verifySignature(content, sig, accountId) {
const expectedSig = crypto
.createHmac('sha256', accountIdToKey[accountId] || '')
.update(content, 'utf8')
.digest('hex');
if (expectedSig.length !== sig.length) {
return false;
}
const verified = crypto.timingSafeEqual(
Buffer.from(expectedSig, 'utf8'),
Buffer.from(sig, 'utf8'),
);
return verified;
}
module.exports = {
isValidKey,
getKeyFromRequest,
requestHasValidKey,
countRequest,
getNumRecentRequests,
verifySignature,
addKeyLine,
};