@softistx/alxia-rate-limit 0.0.0-stage → 0.7.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +126 -2
- package/dist/index.d.ts +4 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +221 -0
- package/dist/index.js.map +13 -0
- package/dist/ipv6-network.d.ts +8 -0
- package/dist/ipv6-network.d.ts.map +1 -0
- package/dist/policy.d.ts +16 -0
- package/dist/policy.d.ts.map +1 -0
- package/dist/rate-limit.d.ts +81 -0
- package/dist/rate-limit.d.ts.map +1 -0
- package/dist/store.d.ts +46 -0
- package/dist/store.d.ts.map +1 -0
- package/docs/README.md +17 -0
- package/docs/guide.md +511 -0
- package/docs/roadmap.md +84 -0
- package/docs/troubleshooting.md +322 -0
- package/package.json +51 -5
package/docs/guide.md
ADDED
|
@@ -0,0 +1,511 @@
|
|
|
1
|
+
# Guide
|
|
2
|
+
|
|
3
|
+
This page covers everything `rateLimit` does: which requests it counts, what
|
|
4
|
+
it answers past the limit, the headers it sets, what a route and a client
|
|
5
|
+
read, and where the counts are kept. It is a middleware: `app.use(rateLimit(…))`.
|
|
6
|
+
|
|
7
|
+
```ts
|
|
8
|
+
import { alxia } from '@softistx/alxia';
|
|
9
|
+
import { rateLimit } from '@softistx/alxia-rate-limit';
|
|
10
|
+
|
|
11
|
+
const app = alxia()
|
|
12
|
+
.get('/health', ({ reply }) => reply(200, 'ok')) // not limited
|
|
13
|
+
.use(rateLimit({ limit: 100, windowMs: 60_000 }))
|
|
14
|
+
.get('/search', ({ rateLimit, reply }) => // limited
|
|
15
|
+
reply(200, { remaining: rateLimit?.remaining }),
|
|
16
|
+
);
|
|
17
|
+
|
|
18
|
+
app.listen({ port: 3000 });
|
|
19
|
+
// the 101st GET /search from one address within a minute
|
|
20
|
+
// → 429 {"error":"rate_limited","retryAfter":…}
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
## The signature
|
|
24
|
+
|
|
25
|
+
```ts
|
|
26
|
+
function rateLimit<Requires extends object = Empty>(
|
|
27
|
+
options: RateLimitOptions<Requires>,
|
|
28
|
+
): RateLimit<Requires>; // a middleware, given to `app.use`, which checks `Requires`
|
|
29
|
+
|
|
30
|
+
type RateLimitOptions<Requires extends object = Empty> = {
|
|
31
|
+
readonly key?: (ctx: BaseContext & Requires) => string | undefined | Promise<string | undefined>;
|
|
32
|
+
readonly skip?: (ctx: BaseContext & Requires) => boolean;
|
|
33
|
+
readonly headers?: 'draft' | 'legacy' | false;
|
|
34
|
+
} & (
|
|
35
|
+
| { readonly limit: number; readonly windowMs: number; readonly store?: RateLimitStore }
|
|
36
|
+
| { readonly limit?: number; readonly windowMs?: number; readonly store: PolicyStore } // a store with a policy
|
|
37
|
+
);
|
|
38
|
+
|
|
39
|
+
type PolicyStore = RateLimitStore & { readonly policy: { limit: number; windowMs: number } };
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
`rateLimit` returns a middleware that counts the request. Given to `app.use`,
|
|
43
|
+
it adds `rateLimit` to the context of every route declared after it, and each
|
|
44
|
+
of those routes may answer its 429; it also counts a request no route
|
|
45
|
+
matches, and answers its 429 before the 404 (see [Which requests are
|
|
46
|
+
counted](#which-requests-are-counted)). `Requires` is what `key` and `skip`
|
|
47
|
+
read beyond `BaseContext`; see [Reading the app's context](#reading-the-apps-context).
|
|
48
|
+
|
|
49
|
+
```ts
|
|
50
|
+
type RateLimit<Requires extends object = Empty> = Middleware<
|
|
51
|
+
Requires,
|
|
52
|
+
Promise<Reply<429, RateLimitedBody> | Next<{ rateLimit: RateLimitInfo | undefined }>>
|
|
53
|
+
>;
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
## Options
|
|
57
|
+
|
|
58
|
+
| Option | Type | Default | Effect |
|
|
59
|
+
| --- | --- | --- | --- |
|
|
60
|
+
| `limit` | `number` | required, unless the store has a `policy` | requests one key may make in a window: a whole number, 1 or more |
|
|
61
|
+
| `windowMs` | `number` | required, unless the store has a `policy` | the window, in milliseconds: a whole number, 1 or more |
|
|
62
|
+
| `key` | `(ctx: BaseContext & Requires) => string \| undefined \| Promise<…>` | `ctx.ip` | what is counted; `undefined` is not counted |
|
|
63
|
+
| `store` | `RateLimitStore` | a new `MemoryStore` | where the counts are kept; with a `policy`, it gives `limit` and `windowMs` |
|
|
64
|
+
| `ipv6Prefix` | `number` | none: each address is counted | the default key becomes the IPv6 network of `ctx.ip`, its first `ipv6Prefix` bits, a whole number from 0 to 128; throws with a `key` |
|
|
65
|
+
| `skip` | `(ctx: BaseContext & Requires) => boolean` | none | requests not counted at all |
|
|
66
|
+
| `headers` | `'draft' \| 'legacy' \| false` | `'draft'` | which rate-limit headers each counted response carries |
|
|
67
|
+
|
|
68
|
+
A `limit` or a `windowMs` that is not a whole number of 1 or more makes
|
|
69
|
+
`rateLimit()` throw a `TypeError` when it is called, so the app fails at
|
|
70
|
+
startup ([troubleshooting](troubleshooting.md#typeerror-ratelimit--must-be-a-whole-number-of-1-or-more-not-)).
|
|
71
|
+
|
|
72
|
+
### A store with a policy
|
|
73
|
+
|
|
74
|
+
A store that counts by a rate of its own — a rate limit defined elsewhere —
|
|
75
|
+
declares it as `policy?: { limit: number; windowMs: number }`. With one,
|
|
76
|
+
`limit` and `windowMs` are optional in the type and read from the store, the
|
|
77
|
+
`RateLimit-*` headers and `ctx.rateLimit.limit` included, so the rate is
|
|
78
|
+
written once. Without one they are required, and a type error says so.
|
|
79
|
+
|
|
80
|
+
```ts
|
|
81
|
+
import { redisStore } from '@softistx/alxia-redis';
|
|
82
|
+
|
|
83
|
+
// `api` is the defineRateLimit definition the handle wired.
|
|
84
|
+
app.use(rateLimit({ store: redisStore(handle.limits.api) })); // 100 per 60 s, from `api`
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
A `limit` or a `windowMs` given beside a policy must equal it, or
|
|
88
|
+
`rateLimit()` throws at declaration
|
|
89
|
+
([troubleshooting](troubleshooting.md#typeerror-ratelimit-limit--differs-from-the-stores-policy-of-)).
|
|
90
|
+
|
|
91
|
+
A store may refuse larger values than `rateLimit` does: `redisStore`
|
|
92
|
+
refuses a `limit × windowMs` above 9,007,199,254,740 and a `windowMs`
|
|
93
|
+
above ten 365-day years (315,360,000,000), on the first request it counts rather than at startup
|
|
94
|
+
([`@softistx/alxia-redis`: Policies Redis refuses](https://github.com/softistx/alxia/blob/develop/packages/redis/docs/guide/rate-limits.md#policies-redis-refuses)).
|
|
95
|
+
|
|
96
|
+
### `key`
|
|
97
|
+
|
|
98
|
+
By default a limit counts per client address, `ctx.ip`, which is what the
|
|
99
|
+
app's [`ip` option](https://github.com/softistx/alxia/blob/develop/packages/core/docs/guide/serving.md#the-clients-address-ip)
|
|
100
|
+
reads. Behind a proxy, that is the proxy's address unless you set `ip`, and
|
|
101
|
+
the header to read it from is the client's to write: the first entry of
|
|
102
|
+
`X-Forwarded-For` is whatever the client sent, so a limit keyed by it is
|
|
103
|
+
bypassed with a new value in each request. Use core's `forwardedIp`, which
|
|
104
|
+
reads the entry your own proxies appended, from the right:
|
|
105
|
+
|
|
106
|
+
```ts
|
|
107
|
+
import { alxia, forwardedIp } from '@softistx/alxia';
|
|
108
|
+
|
|
109
|
+
const app = alxia({
|
|
110
|
+
ip: forwardedIp({ trusted: 1 }), // or ['10.0.0.0/8'], the proxies' own ranges
|
|
111
|
+
}).use(rateLimit({ limit: 100, windowMs: 60_000 }));
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
`trusted` is the number of proxies in front of the app (`2` for a CDN and a
|
|
115
|
+
load balancer), or their CIDR ranges, in which case a client that reaches the
|
|
116
|
+
app directly is counted by its own address, whatever header it sends
|
|
117
|
+
([Serving](https://github.com/softistx/alxia/blob/develop/packages/core/docs/guide/serving.md#the-clients-address-ip)).
|
|
118
|
+
|
|
119
|
+
One client is one key however its address is written: core gives `ctx.ip`
|
|
120
|
+
in one canonical text, from the socket or the header alike — an
|
|
121
|
+
IPv4-mapped `::ffff:203.0.113.9` as `203.0.113.9`, IPv6 as RFC 5952 writes
|
|
122
|
+
it (`2001:DB8:0:0:0:0:0:1` as `2001:db8::1`) — so a client cannot buy a
|
|
123
|
+
new allowance by writing its address another way, nor reach the app by
|
|
124
|
+
socket and by proxy under two keys
|
|
125
|
+
([One text per address](https://github.com/softistx/alxia/blob/develop/packages/core/docs/guide/serving.md#one-text-per-address)).
|
|
126
|
+
A `key` of your own that reads an address elsewhere gets the same form
|
|
127
|
+
from core's `canonicalIp`.
|
|
128
|
+
|
|
129
|
+
Count by something else — an API key, a token — by returning it from `key`.
|
|
130
|
+
It may be async. A request whose key is `undefined` is not counted: it passes,
|
|
131
|
+
gets no rate-limit header, and its route reads `rateLimit` as `undefined`.
|
|
132
|
+
|
|
133
|
+
```ts
|
|
134
|
+
app.use(
|
|
135
|
+
rateLimit({
|
|
136
|
+
limit: 1_000,
|
|
137
|
+
windowMs: 60 * 60_000,
|
|
138
|
+
key: ({ request }) => request.headers.get('x-api-key') ?? undefined, // no key: not counted
|
|
139
|
+
}),
|
|
140
|
+
);
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
`key` is typed with `BaseContext`, what every middleware reads: the request,
|
|
144
|
+
`url`, `ip`, `server`, `route` (`undefined` on a request no route matches) and `pathParams`, and with `Requires`, empty
|
|
145
|
+
by default. To read what an earlier middleware added, see [Reading the app's
|
|
146
|
+
context](#reading-the-apps-context).
|
|
147
|
+
|
|
148
|
+
### `ipv6Prefix`
|
|
149
|
+
|
|
150
|
+
One IPv6 subscriber usually holds a whole /64, so a client that counts per
|
|
151
|
+
address can take a new one for each request. `ipv6Prefix` makes the default
|
|
152
|
+
key the network of `ctx.ip` instead: its first `ipv6Prefix` bits, in
|
|
153
|
+
canonical form (RFC 5952), followed by `/` and the prefix. The function that
|
|
154
|
+
writes it is exported as `ipv6Network(address, prefix)`, for a `key` of your
|
|
155
|
+
own that groups the same way.
|
|
156
|
+
|
|
157
|
+
```ts
|
|
158
|
+
app.use(rateLimit({ limit: 100, windowMs: 60_000, ipv6Prefix: 64 }));
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
| `ctx.ip` | key with `ipv6Prefix: 64` | key with `ipv6Prefix: 48` |
|
|
162
|
+
| --- | --- | --- |
|
|
163
|
+
| `2001:db8:1:2::1` | `2001:db8:1:2::/64` | `2001:db8:1::/48` |
|
|
164
|
+
| `2001:db8:1:2:aaaa:bbbb:cccc:dddd` | `2001:db8:1:2::/64` | `2001:db8:1::/48` |
|
|
165
|
+
| `2001:db8:1:3::1` | `2001:db8:1:3::/64` | `2001:db8:1::/48` |
|
|
166
|
+
| `203.0.113.9`, or `::ffff:203.0.113.9` | `203.0.113.9` | `203.0.113.9` |
|
|
167
|
+
|
|
168
|
+
- **Set `64` on the open Internet.** It is the size of a subscriber's
|
|
169
|
+
network. `128` counts each address, as the default does; `0` puts every
|
|
170
|
+
IPv6 client in one key (`::/0`).
|
|
171
|
+
- **The default stays per address.** Without the option, every key is
|
|
172
|
+
`ctx.ip`, as before.
|
|
173
|
+
- **IPv4 is untouched.** An IPv4 address, and an IPv4-mapped IPv6 one (core
|
|
174
|
+
already gives it as IPv4), keep their key.
|
|
175
|
+
- **A zone id** (`%eth0`) is dropped, and a text that is not an IPv6 address
|
|
176
|
+
is used as it is.
|
|
177
|
+
- **Default key only.** With a `key` of your own, `ipv6Prefix` would do
|
|
178
|
+
nothing, so `rateLimit()` throws, as it does for a `limit` that differs
|
|
179
|
+
from the store's policy. Group the address yourself in that case.
|
|
180
|
+
- A prefix that is not a whole number from 0 to 128 throws at declaration.
|
|
181
|
+
|
|
182
|
+
### `skip`
|
|
183
|
+
|
|
184
|
+
A request `skip` returns `true` for is not counted, exactly like one whose
|
|
185
|
+
key is `undefined`. It is synchronous.
|
|
186
|
+
|
|
187
|
+
```ts
|
|
188
|
+
app.use(
|
|
189
|
+
rateLimit({
|
|
190
|
+
limit: 100,
|
|
191
|
+
windowMs: 60_000,
|
|
192
|
+
skip: ({ ip }) => ip === '127.0.0.1', // the local health checker, IPv4-mapped or not
|
|
193
|
+
}),
|
|
194
|
+
);
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
### Reading the app's context
|
|
198
|
+
|
|
199
|
+
To count by what an earlier middleware added, such as a signed-in `user`,
|
|
200
|
+
name it as `rateLimit`'s type argument. `key` and `skip` then read it, and
|
|
201
|
+
the app that uses the limit must give it first: an app that does not give
|
|
202
|
+
`user` before it cannot use it.
|
|
203
|
+
|
|
204
|
+
```ts
|
|
205
|
+
const perUser = rateLimit<{ user: { id: string; role: string } }>({
|
|
206
|
+
limit: 100,
|
|
207
|
+
windowMs: 60_000,
|
|
208
|
+
key: ({ user }) => user.id,
|
|
209
|
+
skip: ({ user }) => user.role === 'admin',
|
|
210
|
+
});
|
|
211
|
+
|
|
212
|
+
const app = alxia()
|
|
213
|
+
.plugin(auth) // derives user, or answers 401
|
|
214
|
+
.use(perUser)
|
|
215
|
+
.get('/search', handler);
|
|
216
|
+
|
|
217
|
+
alxia().use(perUser);
|
|
218
|
+
// error: Property 'user' is missing in type 'BaseContext & Empty' but required in type '{ user: { id: string; role: string; }; }'
|
|
219
|
+
```
|
|
220
|
+
|
|
221
|
+
### `headers`
|
|
222
|
+
|
|
223
|
+
Every counted response — the route's own and the 429 alike — carries the
|
|
224
|
+
headers of the style you choose:
|
|
225
|
+
|
|
226
|
+
| `headers` | Sent | Values |
|
|
227
|
+
| --- | --- | --- |
|
|
228
|
+
| `'draft'` (default) | `RateLimit-Limit`, `RateLimit-Remaining`, `RateLimit-Reset`, `RateLimit-Policy` | the limit; what is left; seconds until the allowance is whole again; `<limit>;w=<window in seconds>` |
|
|
229
|
+
| `'legacy'` | `X-RateLimit-Limit`, `X-RateLimit-Remaining`, `X-RateLimit-Reset` | the limit; what is left; the Unix time, in seconds, at which the allowance is whole again |
|
|
230
|
+
| `false` | none | — |
|
|
231
|
+
|
|
232
|
+
With `limit: 1, windowMs: 60_000`, the first request answers:
|
|
233
|
+
|
|
234
|
+
```text
|
|
235
|
+
ratelimit-limit: 1
|
|
236
|
+
ratelimit-remaining: 0
|
|
237
|
+
ratelimit-reset: 60
|
|
238
|
+
ratelimit-policy: 1;w=60
|
|
239
|
+
```
|
|
240
|
+
|
|
241
|
+
The 429 carries `Retry-After` whatever `headers` says.
|
|
242
|
+
|
|
243
|
+
### `store`
|
|
244
|
+
|
|
245
|
+
Each `rateLimit` call without a `store` creates its own `MemoryStore`: the
|
|
246
|
+
counts live in that process and are lost when it stops. See
|
|
247
|
+
[Stores](#stores) for sharing them across processes, and for resetting a key.
|
|
248
|
+
|
|
249
|
+
## Which requests are counted
|
|
250
|
+
|
|
251
|
+
The limit is a middleware, so order decides, at runtime and in the types:
|
|
252
|
+
|
|
253
|
+
- a route declared **before** `use(rateLimit(…))` is not counted, and
|
|
254
|
+
never answers the 429;
|
|
255
|
+
- a route declared **after** it is counted, and may answer the 429;
|
|
256
|
+
- a request **no route matches** (a 404, a 405) is counted too, when the limit
|
|
257
|
+
is on the app: every top-level `use()` runs on it, wherever declared, and
|
|
258
|
+
past the limit the 429 comes before the 404. Spamming missing paths spends
|
|
259
|
+
the allowance;
|
|
260
|
+
- inside a [group](https://github.com/softistx/alxia/blob/develop/packages/core/docs/guide/groups-and-plugins.md#groups),
|
|
261
|
+
the limit stays inside it: its routes, and an unmatched request under the
|
|
262
|
+
group's prefix, never a route declared after the group nor a path outside
|
|
263
|
+
the prefix;
|
|
264
|
+
- a path-scoped `use('/api', rateLimit(…))` does not compile: a middleware
|
|
265
|
+
given a path may add nothing to the context, and the limit adds
|
|
266
|
+
`rateLimit`. A group is the scope.
|
|
267
|
+
|
|
268
|
+
A guard on the app answers an anonymous caller of a missing path with its
|
|
269
|
+
refusal, not the 404: that is the same rule for a rate limit.
|
|
270
|
+
|
|
271
|
+
```ts
|
|
272
|
+
const app = alxia()
|
|
273
|
+
.get('/health', ({ reply }) => reply(200, 'ok')) // never counted
|
|
274
|
+
.group('/auth', (auth) =>
|
|
275
|
+
auth
|
|
276
|
+
.use(rateLimit({ limit: 5, windowMs: 15 * 60_000 })) // 5 per 15 minutes
|
|
277
|
+
.post('/login', ({ reply }) => reply(200, 'ok')),
|
|
278
|
+
)
|
|
279
|
+
.use(rateLimit({ limit: 100, windowMs: 60_000 })) // 100 per minute
|
|
280
|
+
.get('/search', ({ reply }) => reply(200, [])); // the group's limit does not reach it
|
|
281
|
+
```
|
|
282
|
+
|
|
283
|
+
The limit runs before the request is validated: a request the route
|
|
284
|
+
refuses with a 400 has already been counted.
|
|
285
|
+
|
|
286
|
+
Two limits on the same routes both count, and either may answer the 429 —
|
|
287
|
+
a burst limit and an hourly one, say. Each sets its own headers on the
|
|
288
|
+
response, so with two `'draft'` limits the later one's values win; give the
|
|
289
|
+
other `headers: false`. A route reads the `rateLimit` of the later one.
|
|
290
|
+
|
|
291
|
+
```ts
|
|
292
|
+
app
|
|
293
|
+
.use(rateLimit({ limit: 10, windowMs: 1_000 })) // a burst
|
|
294
|
+
.use(rateLimit({ limit: 1_000, windowMs: 60 * 60_000, headers: false })) // an hour
|
|
295
|
+
.get('/search', ({ rateLimit, reply }) => reply(200, rateLimit ?? null)); // the hourly limit's info
|
|
296
|
+
```
|
|
297
|
+
|
|
298
|
+
## What a route reads
|
|
299
|
+
|
|
300
|
+
Every route after the limit reads `ctx.rateLimit`:
|
|
301
|
+
|
|
302
|
+
```ts
|
|
303
|
+
interface RateLimitInfo {
|
|
304
|
+
readonly limit: number;
|
|
305
|
+
readonly remaining: number; // after this request
|
|
306
|
+
readonly resetAfter: number; // milliseconds until the allowance is whole again
|
|
307
|
+
}
|
|
308
|
+
```
|
|
309
|
+
|
|
310
|
+
It is `RateLimitInfo | undefined`: `undefined` when the request was not
|
|
311
|
+
counted, by `skip` or an `undefined` key.
|
|
312
|
+
|
|
313
|
+
```ts
|
|
314
|
+
app
|
|
315
|
+
.use(rateLimit({ limit: 100, windowMs: 60_000 }))
|
|
316
|
+
.get('/quota', ({ rateLimit, reply }) =>
|
|
317
|
+
rateLimit === undefined
|
|
318
|
+
? reply(200, { limited: false as const })
|
|
319
|
+
: reply(200, { limited: true as const, remaining: rateLimit.remaining }),
|
|
320
|
+
);
|
|
321
|
+
```
|
|
322
|
+
|
|
323
|
+
## The 429
|
|
324
|
+
|
|
325
|
+
Past the limit the middleware ends the request before the route runs:
|
|
326
|
+
|
|
327
|
+
```text
|
|
328
|
+
HTTP/1.1 429 Too Many Requests
|
|
329
|
+
retry-after: 60
|
|
330
|
+
ratelimit-limit: 100
|
|
331
|
+
ratelimit-remaining: 0
|
|
332
|
+
ratelimit-reset: 60
|
|
333
|
+
ratelimit-policy: 100;w=60
|
|
334
|
+
|
|
335
|
+
{"error":"rate_limited","retryAfter":60}
|
|
336
|
+
```
|
|
337
|
+
|
|
338
|
+
```ts
|
|
339
|
+
interface RateLimitedBody {
|
|
340
|
+
readonly error: 'rate_limited';
|
|
341
|
+
readonly retryAfter: number; // seconds until a request would be allowed, at least 1
|
|
342
|
+
}
|
|
343
|
+
```
|
|
344
|
+
|
|
345
|
+
`retryAfter` and `Retry-After` are the same number. A refused request
|
|
346
|
+
counts nothing: retrying after `retryAfter` seconds succeeds.
|
|
347
|
+
|
|
348
|
+
## On the wire
|
|
349
|
+
|
|
350
|
+
Every route after the limit may answer `429 { error: 'rate_limited',
|
|
351
|
+
retryAfter }`; a route declared before it never does. Declare the 429 in
|
|
352
|
+
your OpenAPI document, and the client you generate from it (with
|
|
353
|
+
`@nxgt/openapi-codegen`, say) reads it typed. A caller waits, then tries
|
|
354
|
+
again:
|
|
355
|
+
|
|
356
|
+
```ts
|
|
357
|
+
async function search() {
|
|
358
|
+
for (;;) {
|
|
359
|
+
const response = await fetch('http://localhost:3000/search');
|
|
360
|
+
if (response.status !== 429) return response;
|
|
361
|
+
const { retryAfter } = await response.json();
|
|
362
|
+
await Bun.sleep(retryAfter * 1000); // wait, then try again
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
```
|
|
366
|
+
|
|
367
|
+
## Stores
|
|
368
|
+
|
|
369
|
+
A store counts and decides. `rateLimit` asks it once per counted request,
|
|
370
|
+
and never knows which store it was given.
|
|
371
|
+
|
|
372
|
+
```ts
|
|
373
|
+
interface RateLimitStore {
|
|
374
|
+
/** Counts one request for `key` under `policy`; a refused one counts nothing. */
|
|
375
|
+
consume(key: string, policy: Policy): Decision | Promise<Decision>;
|
|
376
|
+
/** Forgets `key`. */
|
|
377
|
+
reset(key: string): void | Promise<void>;
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
interface Policy {
|
|
381
|
+
readonly limit: number;
|
|
382
|
+
readonly windowMs: number;
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
interface Decision {
|
|
386
|
+
readonly allowed: boolean;
|
|
387
|
+
readonly remaining: number; // requests still allowed now, after this one
|
|
388
|
+
readonly resetAfter: number; // ms until the allowance is whole again
|
|
389
|
+
readonly retryAfter: number; // ms until a refused request would be allowed; 0 when allowed
|
|
390
|
+
}
|
|
391
|
+
```
|
|
392
|
+
|
|
393
|
+
### `MemoryStore`
|
|
394
|
+
|
|
395
|
+
A fixed window per key, in one process's memory. The first request of a key
|
|
396
|
+
opens a window of `windowMs`; the key may make `limit` requests in it; the
|
|
397
|
+
next request after it ends opens a new one. Ended windows are swept on a
|
|
398
|
+
timer that does not keep the process alive.
|
|
399
|
+
|
|
400
|
+
```ts
|
|
401
|
+
import { MemoryStore } from '@softistx/alxia-rate-limit';
|
|
402
|
+
|
|
403
|
+
const store = new MemoryStore();
|
|
404
|
+
const policy = { limit: 2, windowMs: 60_000 };
|
|
405
|
+
|
|
406
|
+
store.consume('a', policy); // { allowed: true, remaining: 1, resetAfter: 60000, retryAfter: 0 }
|
|
407
|
+
store.consume('a', policy); // { allowed: true, remaining: 0, … }
|
|
408
|
+
store.consume('a', policy); // { allowed: false, remaining: 0, retryAfter: 60000, … }
|
|
409
|
+
store.reset('a');
|
|
410
|
+
store.consume('a', policy); // { allowed: true, remaining: 1, … }
|
|
411
|
+
store.size; // 1: the keys it counts
|
|
412
|
+
```
|
|
413
|
+
|
|
414
|
+
A `MemoryStore` keys its counts by `key` alone, not by policy: give each
|
|
415
|
+
limit its own store, as `rateLimit` does when you pass none.
|
|
416
|
+
|
|
417
|
+
### Across processes
|
|
418
|
+
|
|
419
|
+
Behind a load balancer each process would count on its own, and a client
|
|
420
|
+
would get `limit` requests per process. Give every process the same store:
|
|
421
|
+
[`@softistx/alxia-redis`](https://www.npmjs.com/package/@softistx/alxia-redis)'s `redisStore`
|
|
422
|
+
counts in Redis, with GCRA timed by the Redis server's clock.
|
|
423
|
+
|
|
424
|
+
```ts
|
|
425
|
+
import { redisStore } from '@softistx/alxia-redis';
|
|
426
|
+
|
|
427
|
+
app.use(
|
|
428
|
+
rateLimit({
|
|
429
|
+
limit: 100,
|
|
430
|
+
windowMs: 60_000,
|
|
431
|
+
store: redisStore(redis, { name: 'api' }), // redis: a Bun RedisClient
|
|
432
|
+
}),
|
|
433
|
+
);
|
|
434
|
+
```
|
|
435
|
+
|
|
436
|
+
### Resetting a key
|
|
437
|
+
|
|
438
|
+
Keep a reference to the store to forget a key — the failed logins of an
|
|
439
|
+
address that has just logged in:
|
|
440
|
+
|
|
441
|
+
```ts
|
|
442
|
+
import { alxia, validate } from '@softistx/alxia';
|
|
443
|
+
import { MemoryStore, rateLimit } from '@softistx/alxia-rate-limit';
|
|
444
|
+
import { z } from 'zod';
|
|
445
|
+
|
|
446
|
+
const attempts = new MemoryStore();
|
|
447
|
+
const passwords = new Map([['ada', 'lovelace']]);
|
|
448
|
+
|
|
449
|
+
export const app = alxia()
|
|
450
|
+
.group('/auth', (auth) =>
|
|
451
|
+
auth
|
|
452
|
+
.use(rateLimit({ limit: 5, windowMs: 15 * 60_000, store: attempts }))
|
|
453
|
+
.post(
|
|
454
|
+
'/login',
|
|
455
|
+
validate({ body: z.object({ name: z.string(), password: z.string() }) }),
|
|
456
|
+
async ({ body, ip, reply }) => {
|
|
457
|
+
if (passwords.get(body.name) !== body.password) {
|
|
458
|
+
return reply(401, { error: 'invalid_credentials' as const });
|
|
459
|
+
}
|
|
460
|
+
if (ip !== undefined) await attempts.reset(ip); // the key is ctx.ip by default
|
|
461
|
+
return reply(200, { name: body.name });
|
|
462
|
+
},
|
|
463
|
+
),
|
|
464
|
+
);
|
|
465
|
+
```
|
|
466
|
+
|
|
467
|
+
The key to reset is the one `key` returned: `ctx.ip` by default.
|
|
468
|
+
|
|
469
|
+
### A store of your own
|
|
470
|
+
|
|
471
|
+
Implement `RateLimitStore`. `consume` decides — `allowed`, `remaining`,
|
|
472
|
+
`resetAfter` and `retryAfter`, each delay in milliseconds — and must count
|
|
473
|
+
nothing for a refused request, or a client that retries on time is refused
|
|
474
|
+
again. `rateLimit` rounds the delays up to seconds for the headers and the
|
|
475
|
+
429 body.
|
|
476
|
+
|
|
477
|
+
## Testing
|
|
478
|
+
|
|
479
|
+
Without a server, `ctx.ip` is `undefined`, so the default key counts
|
|
480
|
+
nothing. Give the app an `ip` that reads a header, and send it:
|
|
481
|
+
|
|
482
|
+
```ts
|
|
483
|
+
import { expect, test } from 'bun:test';
|
|
484
|
+
import { alxia } from '@softistx/alxia';
|
|
485
|
+
import { rateLimit } from '@softistx/alxia-rate-limit';
|
|
486
|
+
|
|
487
|
+
const app = alxia({ ip: (request) => request.headers.get('x-ip') ?? undefined })
|
|
488
|
+
.use(rateLimit({ limit: 2, windowMs: 60_000 }))
|
|
489
|
+
.get('/limited', ({ rateLimit, reply }) => reply(200, rateLimit?.remaining ?? -1));
|
|
490
|
+
|
|
491
|
+
test('answers 429 past the limit, per address', async () => {
|
|
492
|
+
const from = (ip: string) => app.request('/limited', { headers: { 'x-ip': ip } });
|
|
493
|
+
expect(await (await from('1.1.1.1')).json()).toBe(1);
|
|
494
|
+
await from('1.1.1.1');
|
|
495
|
+
const third = await from('1.1.1.1');
|
|
496
|
+
expect(third.status).toBe(429);
|
|
497
|
+
expect(third.headers.get('retry-after')).toBe('60');
|
|
498
|
+
expect((await from('2.2.2.2')).status).toBe(200);
|
|
499
|
+
});
|
|
500
|
+
```
|
|
501
|
+
|
|
502
|
+
The counts live as long as the app: build a new app per test, or use a
|
|
503
|
+
distinct `x-ip` in each, so one test does not spend another's allowance.
|
|
504
|
+
|
|
505
|
+
## See also
|
|
506
|
+
|
|
507
|
+
- [`fieldRateLimit` and `limitFromStore`](https://github.com/softistx/alxia/blob/develop/packages/graphql/docs/guide/production.md#count-a-field-not-a-request)
|
|
508
|
+
in `@softistx/alxia-graphql`: count the selections of a GraphQL field, aliases included, on one of these stores.
|
|
509
|
+
- [Troubleshooting](troubleshooting.md): a message, and what to do about it.
|
|
510
|
+
- [`@softistx/alxia`'s middleware guide](https://github.com/softistx/alxia/blob/develop/packages/core/docs/guide/middleware.md):
|
|
511
|
+
how `use`, groups and their order work, and which requests a middleware runs on.
|
package/docs/roadmap.md
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
# Roadmap
|
|
2
|
+
|
|
3
|
+
What `@softistx/alxia-rate-limit` gives an app, and what is coming. This page is a
|
|
4
|
+
direction, not a commitment: the version something shipped in is the only
|
|
5
|
+
number on it. Every release, with each change it made, is in
|
|
6
|
+
[`CHANGELOG.md`](https://github.com/softistx/alxia/blob/develop/packages/rate-limit/CHANGELOG.md).
|
|
7
|
+
|
|
8
|
+
## Now
|
|
9
|
+
|
|
10
|
+
- **Moving to the `@softistx` scope.** The package is now `@softistx/alxia-rate-limit` (it was `@alxia/rate-limit`). Same code and API; replace the dependency and the imports ([migration guide](https://github.com/softistx/alxia/blob/develop/packages/core/docs/guide/migrating-from-alxia-scope.md)). The old name is deprecated.
|
|
11
|
+
|
|
12
|
+
## Next
|
|
13
|
+
|
|
14
|
+
Nothing scheduled yet.
|
|
15
|
+
|
|
16
|
+
## Later
|
|
17
|
+
|
|
18
|
+
Nothing scheduled yet.
|
|
19
|
+
|
|
20
|
+
## Not planned
|
|
21
|
+
|
|
22
|
+
- **A runtime dependency.** `@softistx/alxia-rate-limit` installs nothing beside
|
|
23
|
+
itself; `@softistx/alxia` is its only peer.
|
|
24
|
+
- **A Redis store in this package.** This package defines the store's
|
|
25
|
+
contract and ships the memory store; counting across processes is
|
|
26
|
+
`@softistx/alxia-redis`'s `redisStore`, which answers the same contract, so an app
|
|
27
|
+
that never runs more than one process installs no Redis client.
|
|
28
|
+
|
|
29
|
+
## Shipped
|
|
30
|
+
|
|
31
|
+
### Unreleased
|
|
32
|
+
|
|
33
|
+
- **`ipv6Network(address, prefix)` exported.** The network `ipv6Prefix` groups a client by, for a key of your own or another package that groups clients the same way (`@alxia/graphql`'s `fieldRateLimit`).
|
|
34
|
+
|
|
35
|
+
### 0.5.0
|
|
36
|
+
|
|
37
|
+
- **An IPv6 client counted by its network.** `ipv6Prefix: 64` makes the
|
|
38
|
+
default key the /64 of `ctx.ip` (`2001:db8:1:2::/64`), so a subscriber
|
|
39
|
+
cannot dodge the limit with a new address. Off by default; IPv4 is
|
|
40
|
+
unchanged.
|
|
41
|
+
|
|
42
|
+
### 0.4.0: a store with a policy
|
|
43
|
+
|
|
44
|
+
- **The rate, written once.** A store may declare `policy?: { limit,
|
|
45
|
+
windowMs }` (`PolicyStore` is one that does). `rateLimit({ store })` then
|
|
46
|
+
reads `limit` and `windowMs` from it, both optional in the type, headers
|
|
47
|
+
included; without a policy they stay required. A `limit` or `windowMs` that
|
|
48
|
+
differs from the policy throws at declaration. `@alxia/redis`'s
|
|
49
|
+
`redisStore(handle.limits.api)` is such a store. Every existing form
|
|
50
|
+
works as before.
|
|
51
|
+
|
|
52
|
+
### 0.3.0
|
|
53
|
+
|
|
54
|
+
- **A middleware, not a plugin.** `app.use(rateLimit({ limit, windowMs }))` is
|
|
55
|
+
the form; `app.plugin(rateLimit(…))`, deprecated in 0.4, was removed in 0.5.
|
|
56
|
+
Given to the
|
|
57
|
+
app, the limit also counts a request no route matches, and `RateLimit<Requires>`
|
|
58
|
+
names what `rateLimit()` returns.
|
|
59
|
+
|
|
60
|
+
### 0.1.0
|
|
61
|
+
|
|
62
|
+
- **A rate limit as a plugin**, the 0.1 form. `rateLimit({ limit, windowMs })` counts
|
|
63
|
+
the requests of every route declared after it, per client address by
|
|
64
|
+
default, and answers a 429 with `Retry-After` and
|
|
65
|
+
`{ error: 'rate_limited', retryAfter }` past the limit.
|
|
66
|
+
- **Options that can work, or a startup error.** A `limit` or `windowMs`
|
|
67
|
+
that is not a whole number of 1 or more throws when `rateLimit()` is
|
|
68
|
+
called.
|
|
69
|
+
- **A 429 only behind the limit.** A route declared before the limit is
|
|
70
|
+
never counted and never answers a 429. (Its place in a typed client left
|
|
71
|
+
with the client: alxia is OpenAPI spec first, so the 429 is declared in
|
|
72
|
+
the document a client is generated from.)
|
|
73
|
+
- **What the route reads.** `ctx.rateLimit` gives the limit, what is left,
|
|
74
|
+
and when the allowance is whole again.
|
|
75
|
+
- **Standard headers.** The IETF draft's `RateLimit-Limit`, `-Remaining`,
|
|
76
|
+
`-Reset` and `-Policy` on every counted response, `X-RateLimit-*` with
|
|
77
|
+
`headers: 'legacy'`, or none.
|
|
78
|
+
- **What is counted, your way.** `key` counts by an address, a token or an
|
|
79
|
+
API key, sync or async; `skip` and an `undefined` key leave a request
|
|
80
|
+
uncounted. `rateLimit<{ user: User }>(…)` types them with what an earlier
|
|
81
|
+
plugin adds, and an app that does not give it cannot use the limit.
|
|
82
|
+
- **A store contract.** `RateLimitStore` decides each request; `MemoryStore`
|
|
83
|
+
counts a fixed window in one process, and `@alxia/redis`'s `redisStore`
|
|
84
|
+
counts across processes. `reset(key)` forgets a key.
|