@softistx/alxia-rate-limit 0.0.0-stage → 0.7.0

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.
@@ -0,0 +1,322 @@
1
+ # Troubleshooting
2
+
3
+ Each entry is headed by what you see: a TypeScript error, a response, or a
4
+ limit that does not count the way you expected. `@softistx/alxia-rate-limit` throws
5
+ nothing of its own; past the limit it answers a 429.
6
+
7
+ **Types**
8
+
9
+ - [`Property 'user' does not exist on type 'BaseContext & Empty'`](#property-user-does-not-exist-on-type-basecontext--empty)
10
+ - [`Type '() => Promise<boolean>' is not assignable to type '(ctx: BaseContext & Empty) => boolean'`](#type---promiseboolean-is-not-assignable-to-type-ctx-basecontext--empty--boolean)
11
+ - [`'rateLimit' is possibly 'undefined'`](#ratelimit-is-possibly-undefined)
12
+
13
+ **Startup**
14
+
15
+ - [`TypeError: rateLimit: … must be a whole number of 1 or more, not …`](#typeerror-ratelimit--must-be-a-whole-number-of-1-or-more-not-)
16
+ - [`TypeError: rateLimit: limit … differs from the store's policy of …`](#typeerror-ratelimit-limit--differs-from-the-stores-policy-of-)
17
+
18
+ **Responses**
19
+
20
+ - [`429 {"error":"rate_limited","retryAfter":…}`](#429-errorrate_limitedretryafter)
21
+
22
+ **Counting**
23
+
24
+ - [Every client is refused at once](#every-client-is-refused-at-once)
25
+ - [One client is never refused, whatever it sends](#one-client-is-never-refused-whatever-it-sends)
26
+ - [Nothing is limited, and no `RateLimit-*` header is sent](#nothing-is-limited-and-no-ratelimit--header-is-sent)
27
+ - [A client makes more than `limit` requests](#a-client-makes-more-than-limit-requests)
28
+ - [A client is refused before `limit` requests](#a-client-is-refused-before-limit-requests)
29
+ - [A missing path answers 429](#a-missing-path-answers-429)
30
+
31
+ ## Types
32
+
33
+ ### `Property 'user' does not exist on type 'BaseContext & Empty'`
34
+
35
+ **When:** a `key` (or `skip`) reads something an earlier `derive` or middleware
36
+ added to the context, and `rateLimit` is not told about it.
37
+
38
+ ```text
39
+ error TS2339: Property 'user' does not exist on type 'BaseContext & Empty'.
40
+ ```
41
+
42
+ **Why:** `key` and `skip` are typed with `BaseContext`, what every middleware
43
+ reads — `request`, `url`, `ip`, `server`, `route`, `pathParams` — plus what
44
+ you name as `rateLimit`'s type argument, and nothing else. `rateLimit` is
45
+ built before it is used, so it cannot see the app it will be used on.
46
+
47
+ **Fix:** name what `key` reads. The app that uses the limit must then give
48
+ it, before the limit:
49
+
50
+ ```ts
51
+ const perUser = rateLimit<{ user: { id: string } }>({
52
+ limit: 100,
53
+ windowMs: 60_000,
54
+ key: ({ user }) => user.id,
55
+ });
56
+
57
+ alxia().plugin(auth).use(perUser); // auth derives user
58
+ ```
59
+
60
+ On an app that does not give `user`, `use(perUser)` is a compile error:
61
+ `Property 'user' is missing in type 'BaseContext & Empty' but required in type '{ user: { id: string; }; }'`.
62
+
63
+ ### `Type '() => Promise<boolean>' is not assignable to type '(ctx: BaseContext & Empty) => boolean'`
64
+
65
+ **When:** `skip` is an `async` function.
66
+
67
+ ```text
68
+ error TS2322: Type '() => Promise<boolean>' is not assignable to type '(ctx: BaseContext & Empty) => boolean'.
69
+ Type 'Promise<boolean>' is not assignable to type 'boolean'.
70
+ ```
71
+
72
+ **Why:** `skip` is synchronous: a promise is always truthy, so an async
73
+ `skip` would skip every request. `key` may be async; `skip` may not.
74
+
75
+ **Fix:** decide synchronously, or move the async part into `key` and return
76
+ `undefined` for a request that should not be counted:
77
+
78
+ ```ts
79
+ app.use(
80
+ rateLimit({
81
+ limit: 100,
82
+ windowMs: 60_000,
83
+ key: async ({ ip }) => ((await isTrusted(ip)) ? undefined : ip), // undefined: not counted
84
+ }),
85
+ );
86
+ ```
87
+
88
+ ### `'rateLimit' is possibly 'undefined'`
89
+
90
+ **When:** a route reads `ctx.rateLimit.remaining` directly.
91
+
92
+ ```text
93
+ error TS18048: 'rateLimit' is possibly 'undefined'.
94
+ ```
95
+
96
+ **Why:** `ctx.rateLimit` is `RateLimitInfo | undefined`. It is `undefined`
97
+ for a request that was not counted: `skip` returned `true`, or `key`
98
+ returned `undefined` — which the default key does when `ctx.ip` is
99
+ `undefined`.
100
+
101
+ **Fix:**
102
+
103
+ ```ts
104
+ app
105
+ .use(rateLimit({ limit: 100, windowMs: 60_000 }))
106
+ .get('/quota', ({ rateLimit, reply }) => reply(200, { remaining: rateLimit?.remaining ?? null }));
107
+ ```
108
+
109
+ ## Startup
110
+
111
+ ### `TypeError: rateLimit: … must be a whole number of 1 or more, not …`
112
+
113
+ **When:** `rateLimit()` is called with a `limit` or a `windowMs` of 0, a
114
+ negative or fractional number, or `NaN`, often from an environment variable
115
+ that is unset. It throws at once, so the app fails at startup:
116
+
117
+ ```text
118
+ TypeError: rateLimit: limit must be a whole number of 1 or more, not 0
119
+ TypeError: rateLimit: windowMs must be a whole number of 1 or more, not NaN
120
+ ```
121
+
122
+ **Why:** a `limit` of 0 would refuse every request, and a window of 0 or
123
+ less would never end one.
124
+
125
+ **Fix:** pass whole numbers. A value read from the environment is a
126
+ string, or `undefined` when the variable is unset: give it a default, and
127
+ let an empty or non-numeric value still fail at startup, as it should:
128
+
129
+ ```ts
130
+ app.use(rateLimit({ limit: Number(Bun.env.RATE_LIMIT ?? 100), windowMs: 60_000 }));
131
+ ```
132
+
133
+ ### `TypeError: rateLimit: ipv6Prefix must be a whole number from 0 to 128, not …`
134
+
135
+ **When:** `rateLimit()` is given an `ipv6Prefix` of -1, 129, a fraction or
136
+ `NaN`, often from an environment variable.
137
+
138
+ **Fix:** pass a whole number from 0 to 128; `64` on the open Internet.
139
+
140
+ ### `TypeError: rateLimit: ipv6Prefix applies to the default key, and a key of your own was given`
141
+
142
+ **When:** `rateLimit()` is given both `ipv6Prefix` and `key`.
143
+
144
+ **Why:** the prefix groups `ctx.ip`, the default key. A `key` of your own
145
+ decides what is counted, so the option would silently do nothing.
146
+
147
+ **Fix:** drop one. To group addresses in your own key, build it from `ctx.ip`
148
+ yourself.
149
+
150
+ ### `TypeError: rateLimit: limit … differs from the store's policy of …`
151
+
152
+ **When:** `rateLimit()` is given a `store` that declares its own `policy`
153
+ (`redisStore(handle.limits.api)`) and a `limit` or a `windowMs` that is
154
+ not the store's. It throws at declaration, so the app fails at startup:
155
+
156
+ ```text
157
+ TypeError: rateLimit: limit 50 differs from the store's policy of 100 per 60000ms. Leave limit and windowMs out to use the store's, or give the same numbers.
158
+ ```
159
+
160
+ **Why:** the store counts by its policy, and the `RateLimit-*` headers are
161
+ written from the numbers `rateLimit` holds: two values would make the headers
162
+ say what the store does not enforce. (`windowMs` reads the same way.)
163
+
164
+ **Fix:** leave `limit` and `windowMs` out; they come from the store. To change
165
+ the rate, change the definition the store reads it from:
166
+
167
+ ```ts
168
+ app.use(rateLimit({ store: redisStore(handle.limits.api) }));
169
+ ```
170
+
171
+ ## Responses
172
+
173
+ ### `429 {"error":"rate_limited","retryAfter":…}`
174
+
175
+ **When:** a key has made `limit` counted requests within the window.
176
+
177
+ **Why:** that is the limit working. `retryAfter` and the `Retry-After`
178
+ header are the seconds until a request would be allowed, at least 1. The
179
+ refused request counted nothing.
180
+
181
+ **Fix:** on the client, wait that long, then try again:
182
+
183
+ ```ts
184
+ const response = await fetch('http://localhost:3000/search');
185
+ if (response.status === 429) {
186
+ await Bun.sleep((await response.json()).retryAfter * 1000);
187
+ }
188
+ ```
189
+
190
+ If it arrives sooner than you expect, see the entries below.
191
+
192
+ ## Counting
193
+
194
+ ### Every client is refused at once
195
+
196
+ **When:** in production, behind a reverse proxy or a load balancer: one
197
+ busy client, or a handful of ordinary ones, and everyone gets the 429.
198
+
199
+ **Why:** the default key is `ctx.ip`, the connection's address — the
200
+ proxy's, the same for every request. All clients share one allowance.
201
+
202
+ **Fix:** give the app an `ip` option that reads the client from the header
203
+ your proxy appends to, with core's `forwardedIp`:
204
+
205
+ ```ts
206
+ import { alxia, forwardedIp } from '@softistx/alxia';
207
+
208
+ const app = alxia({ ip: forwardedIp({ trusted: 1 }) }).use(
209
+ rateLimit({ limit: 100, windowMs: 60_000 }),
210
+ );
211
+ ```
212
+
213
+ ### One IPv6 client is never refused
214
+
215
+ **When:** a client on IPv6 keeps getting 200s, each request from a different
216
+ address of the same network.
217
+
218
+ **Why:** the default key is one address, and a subscriber holds a whole /64.
219
+
220
+ **Fix:** `rateLimit({ …, ipv6Prefix: 64 })` counts the network.
221
+
222
+ ### One client is never refused, whatever it sends
223
+
224
+ **When:** behind a proxy, a client changes its `X-Forwarded-For` in each
225
+ request and is never answered a 429, or one address is refused for a
226
+ header another client wrote.
227
+
228
+ **Why:** the `ip` option reads the header's first entry
229
+ (`split(',')[0]`). That entry is what the client wrote, so each value is a
230
+ new key. Each proxy appends the address it saw to the right.
231
+
232
+ **Fix:** read from the right, as `forwardedIp` does: `trusted: 1` is the
233
+ last entry, `2` the one before it behind two proxies, and a list of CIDR
234
+ ranges the first entry from the right that is not a proxy of yours.
235
+
236
+ ### Nothing is limited, and no `RateLimit-*` header is sent
237
+
238
+ **When:** requests past `limit` still answer 200, without a rate-limit
239
+ header, and `ctx.rateLimit` is `undefined` — typically in a test calling
240
+ the app through `app.fetch` or `app.request`.
241
+
242
+ **Why:** a request whose key is `undefined` is not counted. Without a server
243
+ there is no connection, so the default `ip` is `undefined`, and so is the
244
+ default key. A custom `key` returning `undefined`, or a `skip` returning
245
+ `true`, does the same. (A route declared before the limit is not counted
246
+ either, and never answers a 429; nor is a request a group's limit does not
247
+ run on.)
248
+
249
+ **Fix:** in tests, read the address from a header you send:
250
+
251
+ ```ts
252
+ const app = alxia({ ip: (request) => request.headers.get('x-ip') ?? undefined })
253
+ .use(rateLimit({ limit: 2, windowMs: 60_000 }))
254
+ .get('/limited', ({ reply }) => reply(200, 'ok'));
255
+
256
+ await app.request('/limited', { headers: { 'x-ip': '1.1.1.1' } });
257
+ ```
258
+
259
+ ### A client makes more than `limit` requests
260
+
261
+ **When:** the app runs as several processes or instances, or restarts.
262
+
263
+ **Why:** the default store is a `MemoryStore`, which counts in one process's
264
+ memory. Each process grants `limit` on its own, and a restart forgets
265
+ every count.
266
+
267
+ **Fix:** give every process the same store, such as `@softistx/alxia-redis`'s:
268
+
269
+ ```ts
270
+ import { redisStore } from '@softistx/alxia-redis';
271
+
272
+ app.use(rateLimit({ limit: 100, windowMs: 60_000, store: redisStore(redis, { name: 'api' }) }));
273
+ ```
274
+
275
+ ### A client is refused before `limit` requests
276
+
277
+ **When:** a 429 comes earlier than `limit` suggests.
278
+
279
+ **Why:** one of these:
280
+
281
+ - **Two limits share one `MemoryStore`.** It keys its counts by key alone,
282
+ not by policy, so both limits spend the same count, and the smaller
283
+ `limit` refuses first.
284
+ - **Two limits apply to the route.** A group's limit and an app-wide one
285
+ both count; either may refuse. With two `'draft'` limits, the headers
286
+ show the later one's numbers.
287
+ - **Refused requests are counted.** The limit runs before the route
288
+ validates the request, so a request answered 400 has spent one.
289
+ - **Unmatched requests are counted.** On the app, the limit runs on a
290
+ request no route matches too, so a client probing missing paths spends
291
+ its allowance: see [A missing path answers 429](#a-missing-path-answers-429).
292
+
293
+ **Fix:** give each limit its own `MemoryStore` — or none, and `rateLimit`
294
+ creates one — and give all but one limit `headers: false`:
295
+
296
+ ```ts
297
+ app
298
+ .use(rateLimit({ limit: 10, windowMs: 1_000 }))
299
+ .use(rateLimit({ limit: 1_000, windowMs: 60 * 60_000, headers: false }));
300
+ ```
301
+
302
+ ### A missing path answers 429
303
+
304
+ **When:** a request to a path no route serves answers `429`, not `404`, once
305
+ the client is past the limit.
306
+
307
+ **Why:** a limit given to `app.use` runs on every request, a request no
308
+ route matches included, and answers before the 404. Declared after a route,
309
+ it still runs for unmatched requests: only the routes before it are spared.
310
+ A limit inside a `group` does not.
311
+
312
+ **Fix:** that is the limit working. To count only some routes, scope it:
313
+
314
+ ```ts
315
+ const app = alxia()
316
+ .get('/health', ({ reply }) => reply(200, 'ok'))
317
+ .group('/api', (api) =>
318
+ api
319
+ .use(rateLimit({ limit: 100, windowMs: 60_000 })) // /api routes only
320
+ .get('/search', ({ reply }) => reply(200, [])),
321
+ );
322
+ ```
package/package.json CHANGED
@@ -1,6 +1,52 @@
1
1
  {
2
- "name": "@softistx/alxia-rate-limit",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
2
+ "name": "@softistx/alxia-rate-limit",
3
+ "version": "0.7.0",
4
+ "description": "Rate limiting for alxia: a 429 with Retry-After past the limit, the remaining allowance typed in the context, pluggable stores",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "main": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "files": [
10
+ "dist",
11
+ "docs",
12
+ "README.md",
13
+ "package.json",
14
+ "LICENSE"
15
+ ],
16
+ "exports": {
17
+ ".": {
18
+ "types": "./dist/index.d.ts",
19
+ "import": "./dist/index.js",
20
+ "default": "./dist/index.js"
21
+ },
22
+ "./package.json": "./package.json"
23
+ },
24
+ "repository": {
25
+ "type": "git",
26
+ "url": "git+https://github.com/softistx/alxia.git",
27
+ "directory": "packages/rate-limit"
28
+ },
29
+ "publishConfig": {
30
+ "registry": "https://registry.npmjs.org",
31
+ "access": "public"
32
+ },
33
+ "scripts": {
34
+ "build": "bun run ../../build.ts",
35
+ "test": "bun test src",
36
+ "typecheck": "tsc --noEmit"
37
+ },
38
+ "alxia": {
39
+ "entrypoints": [
40
+ "src/index.ts"
41
+ ]
42
+ },
43
+ "devDependencies": {
44
+ "@softistx/alxia": "^0.28.0",
45
+ "@types/bun": "^1.4.4",
46
+ "zod": "^4.2.0"
47
+ },
48
+ "peerDependencies": {
49
+ "@softistx/alxia": "^0.28.0",
50
+ "typescript": "^6.0.3 || ^7.0.0"
51
+ }
52
+ }