-
-
Notifications
You must be signed in to change notification settings - Fork 73
/
Copy pathindex.js
288 lines (242 loc) · 9.72 KB
/
index.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
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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
'use strict'
const fp = require('fastify-plugin')
const ms = require('ms')
const LocalStore = require('./store/LocalStore')
const RedisStore = require('./store/RedisStore')
const defaultHook = 'onRequest'
async function fastifyRateLimit (fastify, settings) {
let labels = {
rateLimit: 'x-ratelimit-limit',
rateRemaining: 'x-ratelimit-remaining',
rateReset: 'x-ratelimit-reset',
retryAfter: 'retry-after'
}
const draftSpecHeaders = {
rateLimit: 'ratelimit-limit',
rateRemaining: 'ratelimit-remaining',
rateReset: 'ratelimit-reset',
retryAfter: 'retry-after'
}
// create the object that will hold the "main" settings that can be shared during the build
// 'global' will define, if the rate limit should be apply by default on all route. default : true
const globalParams = {
global: (typeof settings.global === 'boolean') ? settings.global : true
}
if (typeof settings.enableDraftSpec === 'boolean' && settings.enableDraftSpec) {
globalParams.enableDraftSpec = true
labels = draftSpecHeaders
}
globalParams.addHeaders = Object.assign({
[labels.rateLimit]: true,
[labels.rateRemaining]: true,
[labels.rateReset]: true,
[labels.retryAfter]: true
}, settings.addHeaders)
globalParams.addHeadersOnExceeding = Object.assign({
[labels.rateLimit]: true,
[labels.rateRemaining]: true,
[labels.rateReset]: true
}, settings.addHeadersOnExceeding)
globalParams.labels = labels
// define the global maximum of request allowed
globalParams.max = ((typeof settings.max === 'number' && !isNaN(settings.max)) || typeof settings.max === 'function')
? settings.max
: 1000
// define the global Time Window
globalParams.timeWindow = typeof settings.timeWindow === 'string'
? ms(settings.timeWindow)
: typeof settings.timeWindow === 'number' && !isNaN(settings.timeWindow)
? settings.timeWindow
: 1000 * 60
globalParams.timeWindowInSeconds = (globalParams.timeWindow / 1000) | 0
globalParams.hook = settings.hook || defaultHook
globalParams.allowList = settings.allowList || settings.whitelist || null
globalParams.ban = settings.ban || null
globalParams.onBanReach = defaultOnBanReach
if (typeof settings.onBanReach === 'function') {
globalParams.onBanReach = settings.onBanReach
}
globalParams.continueExceeding = settings.continueExceeding || false
// define the name of the app component. Related to redis, it will be use as a part of the keyname define in redis.
const pluginComponent = {
allowList: globalParams.allowList
}
if (settings.store) {
const Store = settings.store
pluginComponent.store = new Store(globalParams)
} else {
if (settings.redis) {
pluginComponent.store = new RedisStore(settings.redis, settings.nameSpace || 'fastify-rate-limit-', globalParams.timeWindow, settings.continueExceeding)
} else {
pluginComponent.store = new LocalStore(globalParams.timeWindow, settings.cache, fastify, settings.continueExceeding)
}
}
globalParams.keyGenerator = typeof settings.keyGenerator === 'function'
? settings.keyGenerator
: (req) => req.ip
globalParams.errorResponseBuilder = defaultErrorResponse
globalParams.isCustomErrorMessage = false
globalParams.onExceeded = settings.onExceeded
globalParams.onExceeding = settings.onExceeding
// define if error message was overwritten with a custom error response callback
if (typeof settings.errorResponseBuilder === 'function') {
globalParams.errorResponseBuilder = settings.errorResponseBuilder
globalParams.isCustomErrorMessage = true
}
globalParams.skipOnError = settings.skipOnError || false
const run = Symbol('rate-limit-did-run')
pluginComponent.run = run
fastify.decorateRequest(run, false)
if (!fastify.hasDecorator('rateLimit')) {
// The rate limit plugin can be registered multiple times but decorate throws if called multiple times for the same field
fastify.decorate('rateLimit', function rateLimit (options) {
let params = globalParams
if (options) {
params = makeParams(options)
}
if (params.timeWindow && params.timeWindow !== globalParams.timeWindow) {
const newPluginComponent = Object.create(pluginComponent)
const newStore = newPluginComponent.store.child(Object.assign({}, { routeInfo: {} }, params))
newPluginComponent.store = newStore
return rateLimitRequestHandler(params, newPluginComponent)
}
return rateLimitRequestHandler(params, pluginComponent)
})
}
// onRoute add the hook rate-limit function if needed
fastify.addHook('onRoute', (routeOptions) => {
if (routeOptions.config && typeof routeOptions.config.rateLimit !== 'undefined') {
if (typeof routeOptions.config.rateLimit === 'object') {
const current = Object.create(pluginComponent)
const mergedRateLimitParams = makeParams(routeOptions.config.rateLimit)
mergedRateLimitParams.routeInfo = routeOptions
current.store = pluginComponent.store.child(mergedRateLimitParams)
// if the current endpoint have a custom rateLimit configuration ...
addRouteRateHook(current, mergedRateLimitParams, routeOptions)
} else if (routeOptions.config.rateLimit === false) {
// don't apply any rate-limit
} else {
throw new Error('Unknown value for route rate-limit configuration')
}
} else if (globalParams.global) {
// if the plugin is set globally ( meaning that all the route will be 'rate limited' )
// As the endpoint, does not have a custom rateLimit configuration, use the global one.
addRouteRateHook(pluginComponent, globalParams, routeOptions)
}
})
// Merge the parameters of a route with the global ones
function makeParams (routeParams) {
const result = Object.assign({}, globalParams, routeParams)
if (typeof result.timeWindow === 'string') {
result.timeWindow = ms(result.timeWindow)
}
if (typeof result.timeWindow === 'number') {
result.timeWindowInSeconds = (result.timeWindow / 1000) | 0
}
return result
}
}
async function addRouteRateHook (pluginComponent, params, routeOptions) {
const hook = params.hook || defaultHook
const hookHandler = rateLimitRequestHandler(params, pluginComponent)
if (Array.isArray(routeOptions[hook])) {
routeOptions[hook].push(hookHandler)
} else if (typeof routeOptions[hook] === 'function') {
routeOptions[hook] = [routeOptions[hook], hookHandler]
} else {
routeOptions[hook] = [hookHandler]
}
}
function rateLimitRequestHandler (params, pluginComponent) {
const theStore = pluginComponent.store
return async function onRequestRateLimiter (req, res) {
const run = pluginComponent.run
const after = ms(params.timeWindow, { long: true })
if (req[run]) {
return
}
req[run] = true
// We retrieve the key from the generator. (can be the global one, or the one define in the endpoint)
const key = await params.keyGenerator(req)
// allowList doesn't apply any rate limit
if (params.allowList) {
if (typeof pluginComponent.allowList === 'function') {
if (await params.allowList(req, key)) {
return
}
} else if (params.allowList.indexOf(key) > -1) {
return
}
}
let current = 0
let ttl = 0
let maximum
if (typeof params.max === 'number' && !isNaN(params.max)) {
maximum = params.max
} else {
maximum = await params.max(req, key)
}
// As the key is not allowList in redis/lru, then we increment the rate-limit of the current request
try {
const res = await new Promise(function (resolve, reject) {
theStore.incr(key, function (err, res) {
if (err) {
reject(err)
return
}
resolve(res)
}, maximum)
})
current = res.current
ttl = res.ttl
} catch (err) {
if (!params.skipOnError) {
throw err
}
}
const timeLeft = Math.floor(ttl / 1000)
if (current <= maximum) {
if (params.addHeadersOnExceeding[params.labels.rateLimit]) { res.header(params.labels.rateLimit, maximum) }
if (params.addHeadersOnExceeding[params.labels.rateRemaining]) { res.header(params.labels.rateRemaining, maximum - current) }
if (params.addHeadersOnExceeding[params.labels.rateReset]) { res.header(params.labels.rateReset, timeLeft) }
if (typeof params.onExceeding === 'function') {
params.onExceeding(req, key)
}
return
}
if (typeof params.onExceeded === 'function') {
params.onExceeded(req, key)
}
if (params.addHeaders[params.labels.rateLimit]) { res.header(params.labels.rateLimit, maximum) }
if (params.addHeaders[params.labels.rateRemaining]) { res.header(params.labels.rateRemaining, 0) }
if (params.addHeaders[params.labels.rateReset]) { res.header(params.labels.rateReset, timeLeft) }
if (params.addHeaders[params.labels.retryAfter]) {
const resetAfterTime = (params.enableDraftSpec ? timeLeft : params.timeWindowInSeconds)
res.header(params.labels.retryAfter, resetAfterTime)
}
const code = params.ban && current - maximum > params.ban ? 403 : 429
const respCtx = {
statusCode: code,
after,
max: maximum,
ttl
}
if (code === 403) {
respCtx.ban = true
params.onBanReach(req, key)
}
throw params.errorResponseBuilder(req, respCtx)
}
}
function defaultErrorResponse (req, context) {
const err = new Error(`Rate limit exceeded, retry in ${context.after}`)
err.statusCode = context.statusCode
return err
}
function defaultOnBanReach (req, key) {}
module.exports = fp(fastifyRateLimit, {
fastify: '4.x',
name: '@fastify/rate-limit'
})
module.exports.default = fastifyRateLimit
module.exports.fastifyRateLimit = fastifyRateLimit