@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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Steve Tsala
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,127 @@
1
- # Temporary Holding Version
1
+ # @softistx/alxia-rate-limit
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ > Moved from `@alxia/rate-limit`: see the [migration guide](https://github.com/softistx/alxia/blob/develop/packages/core/docs/guide/migrating-from-alxia-scope.md).
4
+
5
+ Rate limiting for [alxia](https://www.npmjs.com/package/@softistx/alxia), as a
6
+ middleware: every request it runs on answers a 429 with `Retry-After` once a key has
7
+ spent its allowance, and reads what is left as a typed `ctx.rateLimit`. No
8
+ dependency.
9
+
10
+ ```sh
11
+ bun add @softistx/alxia-rate-limit @softistx/alxia
12
+ bun add -d typescript
13
+ ```
14
+
15
+ ## Usage
16
+
17
+ ```ts
18
+ import { rateLimit } from '@softistx/alxia-rate-limit';
19
+
20
+ const app = alxia()
21
+ .get('/health', ...) // not limited
22
+ .use(rateLimit({ limit: 100, windowMs: 60_000 }))
23
+ .get('/search', ({ rateLimit, reply }) => ...); // limited; rateLimit.remaining
24
+
25
+ const response = await app.request('/search');
26
+ if (response.status === 429) (await response.json()).retryAfter; // seconds
27
+ ```
28
+
29
+ Past the limit, a 429 with `Retry-After` and
30
+ `{ error: 'rate_limited', retryAfter }`. Every counted response carries the
31
+ IETF draft's `RateLimit-Limit`, `-Remaining`, `-Reset` and `-Policy`.
32
+
33
+ ## Options
34
+
35
+ | option | default | |
36
+ | --- | --- | --- |
37
+ | `limit` | required, unless the store has a `policy` | requests per window: a whole number, 1 or more |
38
+ | `windowMs` | required, unless the store has a `policy` | the window, in milliseconds: a whole number, 1 or more |
39
+ | `key` | the client's address | what is counted: `(ctx) => string \| undefined`; `undefined` is not counted. `rateLimit<{ user: User }>(…)` lets it read a `user` an earlier middleware adds |
40
+ | `store` | `MemoryStore` | where: `redisStore` from `@softistx/alxia-redis`, or your own `RateLimitStore`. A store with a `policy` gives `limit` and `windowMs` |
41
+ | `ipv6Prefix` | none: each address is counted | count an IPv6 client by its network, the first `ipv6Prefix` bits (0 to 128) of its address; `64` on the open Internet. Default key only: throws with a `key` |
42
+ | `skip` | none | requests not counted |
43
+ | `headers` | `'draft'` | `'legacy'` for `X-RateLimit-*`, or `false` |
44
+
45
+ ### One IPv6 client, one key
46
+
47
+ A home or mobile subscriber usually holds a whole /64, billions of
48
+ addresses, so counting each address apart lets it dodge the limit. On the
49
+ open Internet, count the network:
50
+
51
+ ```ts
52
+ app.use(rateLimit({ limit: 100, windowMs: 60_000, ipv6Prefix: 64 }));
53
+ // 2001:db8:1:2::1 and 2001:db8:1:2:aaaa::9 are one key: 2001:db8:1:2::/64
54
+ ```
55
+
56
+ IPv4 and IPv4-mapped addresses keep their key. Without the option, each
57
+ address is its own key.
58
+
59
+ ## Order
60
+
61
+ `rateLimit` counts every request it runs on. Given to `app.use`, that is the
62
+ routes declared after it, and also a request no route matches: it is counted,
63
+ and past the limit answers the 429 before the 404. Put it in a `group` to
64
+ count only some routes: a path-scoped `use('/api', …)` cannot give `rateLimit` to the context.
65
+
66
+ Behind a proxy, the connection is the proxy: give the app an `ip` option that
67
+ reads the client from the header the proxy appends to, with core's `forwardedIp`:
68
+
69
+ ```ts
70
+ import { alxia, forwardedIp } from '@softistx/alxia';
71
+
72
+ const app = alxia({ ip: forwardedIp({ trusted: 1 }) }) // one proxy in front
73
+ .use(rateLimit({ limit: 100, windowMs: 60_000 }));
74
+ ```
75
+
76
+ With `@softistx/alxia` 0.10 or later, one client is counted once however its
77
+ address is written (IPv4-mapped, IPv6 in any case or zero run, with a port or
78
+ brackets), since `ctx.ip` is its canonical text.
79
+
80
+ Never key by the first entry of `X-Forwarded-For` (`split(',')[0]`): the client
81
+ writes it, so a new value in each request is a new allowance. `forwardedIp`
82
+ reads the entry your proxy appended
83
+ ([Serving](https://github.com/softistx/alxia/blob/develop/packages/core/docs/guide/serving.md#the-clients-address-ip)).
84
+
85
+ ## Across processes
86
+
87
+ `MemoryStore` counts in one process. Behind a load balancer, give every
88
+ process the same store: [`@softistx/alxia-redis`](https://www.npmjs.com/package/@softistx/alxia-redis)'s
89
+ `redisStore` counts in Redis, with GCRA timed by the Redis server's clock.
90
+
91
+ ```ts
92
+ import { redisStore } from '@softistx/alxia-redis';
93
+
94
+ app.use(rateLimit({ limit: 100, windowMs: 60_000, store: redisStore(redis, { name: 'api' }) }));
95
+ ```
96
+
97
+ A store that counts by a rate of its own declares it as `policy: { limit,
98
+ windowMs }`, and `rateLimit({ store })` reads both from it, headers included:
99
+ the numbers are written once. `redisStore(handle.limits.api)` does, from
100
+ the bound limit's definition. A `limit` or `windowMs` given beside it that differs
101
+ throws at declaration.
102
+
103
+ ```ts
104
+ app.use(rateLimit({ store: redisStore(handle.limits.api) }));
105
+ ```
106
+
107
+ A store of your own implements `RateLimitStore` (and, to count by a rate of
108
+ its own, the optional `policy`): `consume(key, { limit, windowMs })` decides — `allowed`, `remaining`, `resetAfter` and
109
+ `retryAfter`, delays in milliseconds — and a refused request counts
110
+ nothing.
111
+
112
+ ## API
113
+
114
+ | export | |
115
+ | --- | --- |
116
+ | `rateLimit(options)` | the middleware: gives `rateLimit` to what runs after it, or answers the 429 |
117
+ | `MemoryStore` | a fixed window in one process's memory |
118
+ | `RateLimitStore`, `Decision`, `Policy`, `PolicyStore` | a store's contract; `PolicyStore` is a store with its own `policy`, which `rateLimit` reads `limit` and `windowMs` from |
119
+ | `ipv6Network(address, prefix)` | the IPv6 network `ipv6Prefix` groups a client by, as `2001:db8:1:2::/64`; an IPv4 or unparsable text is returned as it is |
120
+ | `RateLimit`, `RateLimitedBody`, `RateLimitInfo`, `RateLimitOptions` | its types: `RateLimit<Requires>` is the middleware `rateLimit()` returns |
121
+
122
+ ## Documentation
123
+
124
+ - [Guide](https://github.com/softistx/alxia/tree/develop/packages/rate-limit/docs): the options and their defaults, which requests are counted, the headers, the 429 on the wire, stores, and testing.
125
+ - [Troubleshooting](https://github.com/softistx/alxia/blob/develop/packages/rate-limit/docs/troubleshooting.md): an error message, and what to do about it.
126
+ - [Roadmap](https://github.com/softistx/alxia/blob/develop/packages/rate-limit/docs/roadmap.md): what is coming, and what is not planned.
127
+ - [Recipes](https://github.com/softistx/alxia/blob/develop/docs/recipes/README.md): [Caching and rate limiting with Redis](https://github.com/softistx/alxia/blob/develop/docs/recipes/caching-and-rate-limiting.md).
@@ -0,0 +1,4 @@
1
+ export { ipv6Network } from './ipv6-network';
2
+ export { type RateLimit, type RateLimitedBody, type RateLimitInfo, type RateLimitOptions, rateLimit, } from './rate-limit';
3
+ export { type Decision, MemoryStore, type Policy, type PolicyStore, type RateLimitStore, } from './store';
4
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAC7C,OAAO,EACN,KAAK,SAAS,EACd,KAAK,eAAe,EACpB,KAAK,aAAa,EAClB,KAAK,gBAAgB,EACrB,SAAS,GACT,MAAM,cAAc,CAAC;AACtB,OAAO,EACN,KAAK,QAAQ,EACb,WAAW,EACX,KAAK,MAAM,EACX,KAAK,WAAW,EAChB,KAAK,cAAc,GACnB,MAAM,SAAS,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,221 @@
1
+ // src/ipv6-network.ts
2
+ function groupsOf(text) {
3
+ const zone = text.indexOf("%");
4
+ const address = zone === -1 ? text : text.slice(0, zone);
5
+ const halves = address.split("::");
6
+ if (halves.length > 2 || !address.includes(":"))
7
+ return;
8
+ const read = (half) => half === undefined || half === "" ? [] : half.split(":");
9
+ const head = read(halves[0]) ?? [];
10
+ const tail = read(halves[1]) ?? [];
11
+ const written = [...head, ...tail];
12
+ const last = written[written.length - 1];
13
+ if (last?.includes(".")) {
14
+ if (!address.endsWith(last))
15
+ return;
16
+ const octets = last.split(".");
17
+ const bytes = octets.map((octet) => /^\d{1,3}$/.test(octet) ? Number(octet) : Number.NaN);
18
+ if (bytes.length !== 4 || bytes.some((byte) => !(byte <= 255)))
19
+ return;
20
+ const [a = 0, b = 0, c = 0, d = 0] = bytes;
21
+ written.splice(-1, 1, (a << 8 | b).toString(16), (c << 8 | d).toString(16));
22
+ if (tail.length > 0)
23
+ tail.splice(-1, 1, "x", "x");
24
+ else
25
+ head.splice(-1, 1, "x", "x");
26
+ }
27
+ const compressed = halves.length === 2;
28
+ const missing = 8 - written.length;
29
+ if (compressed ? missing < 1 : missing !== 0)
30
+ return;
31
+ const all = compressed ? [
32
+ ...written.slice(0, head.length),
33
+ ...new Array(missing).fill("0"),
34
+ ...written.slice(head.length)
35
+ ] : written;
36
+ const groups = all.map((group) => /^[0-9a-f]{1,4}$/i.test(group) ? Number.parseInt(group, 16) : Number.NaN);
37
+ return groups.some(Number.isNaN) ? undefined : groups;
38
+ }
39
+ function written(groups) {
40
+ let start = -1;
41
+ let length = 0;
42
+ for (let i = 0;i < 8; ) {
43
+ if (groups[i] !== 0) {
44
+ i++;
45
+ continue;
46
+ }
47
+ let end = i;
48
+ while (end < 8 && groups[end] === 0)
49
+ end++;
50
+ if (end - i > length) {
51
+ start = i;
52
+ length = end - i;
53
+ }
54
+ i = end;
55
+ }
56
+ const hex = (list) => list.map((group) => group.toString(16)).join(":");
57
+ if (length < 2)
58
+ return hex(groups);
59
+ return `${hex(groups.slice(0, start))}::${hex(groups.slice(start + length))}`;
60
+ }
61
+ function ipv6Network(address, prefix) {
62
+ const groups = groupsOf(address);
63
+ if (groups === undefined)
64
+ return address;
65
+ if (groups.slice(0, 5).every((group) => group === 0) && groups[5] === 65535) {
66
+ const [a = 0, b = 0] = groups.slice(6);
67
+ return `${a >> 8}.${a & 255}.${b >> 8}.${b & 255}`;
68
+ }
69
+ const masked = groups.map((group, index) => {
70
+ const kept = Math.min(16, Math.max(0, prefix - index * 16));
71
+ return group >> 16 - kept << 16 - kept;
72
+ });
73
+ return `${written(masked.map((group) => group & 65535))}/${prefix}`;
74
+ }
75
+ // src/rate-limit.ts
76
+ import {
77
+ defineMiddleware,
78
+ markFactory
79
+ } from "@softistx/alxia";
80
+
81
+ // src/policy.ts
82
+ function resolvePolicy(given) {
83
+ const own = given.store?.policy;
84
+ const policy = {
85
+ limit: given.limit ?? own?.limit ?? Number.NaN,
86
+ windowMs: given.windowMs ?? own?.windowMs ?? Number.NaN
87
+ };
88
+ for (const name of ["limit", "windowMs"]) {
89
+ const value = policy[name];
90
+ if (!Number.isSafeInteger(value) || value < 1) {
91
+ throw new TypeError(`rateLimit: ${name} must be a whole number of 1 or more, not ${String(given[name] ?? own?.[name])}`);
92
+ }
93
+ }
94
+ if (own !== undefined) {
95
+ for (const name of ["limit", "windowMs"]) {
96
+ if (policy[name] !== own[name]) {
97
+ throw new TypeError(`rateLimit: ${name} ${policy[name]} differs from the store's policy of ${own.limit} per ${own.windowMs}ms. Leave limit and windowMs out to use the store's, or give the same numbers.`);
98
+ }
99
+ }
100
+ }
101
+ return policy;
102
+ }
103
+
104
+ // src/store.ts
105
+ class MemoryStore {
106
+ #hits = new Map;
107
+ #sweeper;
108
+ consume(key, policy) {
109
+ const now = Date.now();
110
+ let entry = this.#hits.get(key);
111
+ if (entry === undefined || entry.resetAt <= now) {
112
+ entry = { count: 0, resetAt: now + policy.windowMs };
113
+ this.#hits.set(key, entry);
114
+ }
115
+ this.#sweep(policy.windowMs);
116
+ const resetAfter = entry.resetAt - now;
117
+ if (entry.count >= policy.limit) {
118
+ return {
119
+ allowed: false,
120
+ remaining: 0,
121
+ resetAfter,
122
+ retryAfter: resetAfter
123
+ };
124
+ }
125
+ entry.count++;
126
+ return {
127
+ allowed: true,
128
+ remaining: policy.limit - entry.count,
129
+ resetAfter,
130
+ retryAfter: 0
131
+ };
132
+ }
133
+ reset(key) {
134
+ this.#hits.delete(key);
135
+ }
136
+ get size() {
137
+ return this.#hits.size;
138
+ }
139
+ #sweep(windowMs) {
140
+ if (this.#sweeper !== undefined)
141
+ return;
142
+ this.#sweeper = setInterval(() => {
143
+ const now = Date.now();
144
+ for (const [key, entry] of this.#hits) {
145
+ if (entry.resetAt <= now)
146
+ this.#hits.delete(key);
147
+ }
148
+ if (this.#hits.size === 0) {
149
+ clearInterval(this.#sweeper);
150
+ this.#sweeper = undefined;
151
+ }
152
+ }, windowMs);
153
+ this.#sweeper.unref?.();
154
+ }
155
+ }
156
+
157
+ // src/rate-limit.ts
158
+ function rateLimit(options) {
159
+ checkPrefix(options);
160
+ const store = options.store ?? new MemoryStore;
161
+ const policy = resolvePolicy(options);
162
+ const key = options.key ?? defaultKey(options.ipv6Prefix);
163
+ const style = options.headers ?? "draft";
164
+ return defineMiddleware()(async function rateLimit(ctx, next) {
165
+ const counted = options.skip?.(ctx) ? undefined : await key(ctx);
166
+ if (counted === undefined) {
167
+ const rateLimit = undefined;
168
+ return next({ rateLimit });
169
+ }
170
+ const decision = await store.consume(counted, policy);
171
+ said(ctx.set.headers, style, policy, decision);
172
+ if (!decision.allowed) {
173
+ const retryAfter = Math.max(1, Math.ceil(decision.retryAfter / 1000));
174
+ const body = { error: "rate_limited", retryAfter };
175
+ return ctx.reply(429, body, {
176
+ headers: { "retry-after": String(retryAfter) }
177
+ });
178
+ }
179
+ const rateLimit = {
180
+ limit: policy.limit,
181
+ remaining: decision.remaining,
182
+ resetAfter: decision.resetAfter
183
+ };
184
+ return next({ rateLimit });
185
+ });
186
+ }
187
+ function defaultKey(prefix) {
188
+ return (ctx) => prefix === undefined || ctx.ip === undefined ? ctx.ip : ipv6Network(ctx.ip, prefix);
189
+ }
190
+ function checkPrefix(options) {
191
+ const { ipv6Prefix } = options;
192
+ if (ipv6Prefix === undefined)
193
+ return;
194
+ if (!Number.isInteger(ipv6Prefix) || ipv6Prefix < 0 || ipv6Prefix > 128) {
195
+ throw new TypeError(`rateLimit: ipv6Prefix must be a whole number from 0 to 128, not ${String(ipv6Prefix)}`);
196
+ }
197
+ if (options.key !== undefined) {
198
+ throw new TypeError("rateLimit: ipv6Prefix applies to the default key, and a key of your own was given. Drop one, or group the address in your key.");
199
+ }
200
+ }
201
+ function said(headers, style, options, decision) {
202
+ if (style === "draft") {
203
+ headers.set("ratelimit-limit", String(options.limit));
204
+ headers.set("ratelimit-remaining", String(decision.remaining));
205
+ headers.set("ratelimit-reset", String(Math.ceil(decision.resetAfter / 1000)));
206
+ headers.set("ratelimit-policy", `${options.limit};w=${Math.ceil(options.windowMs / 1000)}`);
207
+ } else if (style === "legacy") {
208
+ headers.set("x-ratelimit-limit", String(options.limit));
209
+ headers.set("x-ratelimit-remaining", String(decision.remaining));
210
+ headers.set("x-ratelimit-reset", String(Math.ceil((Date.now() + decision.resetAfter) / 1000)));
211
+ }
212
+ }
213
+ markFactory(rateLimit);
214
+ export {
215
+ MemoryStore,
216
+ ipv6Network,
217
+ rateLimit
218
+ };
219
+
220
+ //# debugId=623097C58F28DD0764756E2164756E21
221
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,13 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/ipv6-network.ts", "../src/rate-limit.ts", "../src/policy.ts", "../src/store.ts"],
4
+ "sourcesContent": [
5
+ "/** The eight 16-bit groups of an IPv6 address, or `undefined` when `text` is not one. */\nfunction groupsOf(text: string): number[] | undefined {\n\tconst zone = text.indexOf('%');\n\tconst address = zone === -1 ? text : text.slice(0, zone);\n\tconst halves = address.split('::');\n\tif (halves.length > 2 || !address.includes(':')) return undefined;\n\tconst read = (half: string | undefined): string[] | undefined =>\n\t\thalf === undefined || half === '' ? [] : half.split(':');\n\tconst head = read(halves[0]) ?? [];\n\tconst tail = read(halves[1]) ?? [];\n\tconst written = [...head, ...tail];\n\tconst last = written[written.length - 1];\n\tif (last?.includes('.')) {\n\t\t// The dotted form ends the address: `1.2.3.4::` is not one.\n\t\tif (!address.endsWith(last)) return undefined;\n\t\tconst octets = last.split('.');\n\t\tconst bytes = octets.map((octet) =>\n\t\t\t/^\\d{1,3}$/.test(octet) ? Number(octet) : Number.NaN,\n\t\t);\n\t\tif (bytes.length !== 4 || bytes.some((byte) => !(byte <= 255)))\n\t\t\treturn undefined;\n\t\tconst [a = 0, b = 0, c = 0, d = 0] = bytes;\n\t\twritten.splice(\n\t\t\t-1,\n\t\t\t1,\n\t\t\t((a << 8) | b).toString(16),\n\t\t\t((c << 8) | d).toString(16),\n\t\t);\n\t\tif (tail.length > 0) tail.splice(-1, 1, 'x', 'x');\n\t\telse head.splice(-1, 1, 'x', 'x');\n\t}\n\tconst compressed = halves.length === 2;\n\tconst missing = 8 - written.length;\n\tif (compressed ? missing < 1 : missing !== 0) return undefined;\n\tconst all = compressed\n\t\t? [\n\t\t\t\t...written.slice(0, head.length),\n\t\t\t\t...new Array<string>(missing).fill('0'),\n\t\t\t\t...written.slice(head.length),\n\t\t\t]\n\t\t: written;\n\tconst groups = all.map((group) =>\n\t\t/^[0-9a-f]{1,4}$/i.test(group) ? Number.parseInt(group, 16) : Number.NaN,\n\t);\n\treturn groups.some(Number.isNaN) ? undefined : groups;\n}\n\n/** RFC 5952: the longest run of two or more zero groups (the first on a tie) as `::`. */\nfunction written(groups: readonly number[]): string {\n\tlet start = -1;\n\tlet length = 0;\n\tfor (let i = 0; i < 8; ) {\n\t\tif (groups[i] !== 0) {\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\t\tlet end = i;\n\t\twhile (end < 8 && groups[end] === 0) end++;\n\t\tif (end - i > length) {\n\t\t\tstart = i;\n\t\t\tlength = end - i;\n\t\t}\n\t\ti = end;\n\t}\n\tconst hex = (list: readonly number[]) =>\n\t\tlist.map((group) => group.toString(16)).join(':');\n\tif (length < 2) return hex(groups);\n\treturn `${hex(groups.slice(0, start))}::${hex(groups.slice(start + length))}`;\n}\n\n/**\n * The network of an IPv6 `address` under `prefix` bits, as `2001:db8:1:2::/64`\n * writes it. An IPv4-mapped address (`::ffff:203.0.113.9`) is its IPv4 address,\n * a zone id (`%eth0`) is dropped, and a text that is not an IPv6 address\n * (an IPv4 one included) is returned as it is.\n */\nexport function ipv6Network(address: string, prefix: number): string {\n\tconst groups = groupsOf(address);\n\tif (groups === undefined) return address;\n\tif (\n\t\tgroups.slice(0, 5).every((group) => group === 0) &&\n\t\tgroups[5] === 0xffff\n\t) {\n\t\tconst [a = 0, b = 0] = groups.slice(6);\n\t\treturn `${a >> 8}.${a & 255}.${b >> 8}.${b & 255}`;\n\t}\n\tconst masked = groups.map((group, index) => {\n\t\tconst kept = Math.min(16, Math.max(0, prefix - index * 16));\n\t\treturn (group >> (16 - kept)) << (16 - kept);\n\t});\n\treturn `${written(masked.map((group) => group & 0xffff))}/${prefix}`;\n}\n",
6
+ "import {\n\ttype BaseContext,\n\tdefineMiddleware,\n\ttype Empty,\n\ttype Middleware,\n\tmarkFactory,\n\ttype Next,\n\ttype Reply,\n} from '@softistx/alxia';\nimport { ipv6Network } from './ipv6-network';\nimport { resolvePolicy } from './policy';\nimport {\n\ttype Decision,\n\tMemoryStore,\n\ttype Policy,\n\ttype PolicyStore,\n\ttype RateLimitStore,\n} from './store';\n\n/** What `RateLimitOptions` holds whatever the store: how a request is counted and answered. */\ninterface CountingOptions<Requires extends object> {\n\t/** What is counted: the client's address by default. `undefined` is not counted. */\n\treadonly key?: (\n\t\tctx: BaseContext & Requires,\n\t) => string | undefined | Promise<string | undefined>;\n\t/** Requests not counted at all. */\n\treadonly skip?: (ctx: BaseContext & Requires) => boolean;\n\t/**\n\t * Count an IPv6 client by its network: the first `ipv6Prefix` bits of\n\t * `ctx.ip`, keyed as `2001:db8:1:2::/64`. One subscriber usually holds a\n\t * whole /64, so per address it can dodge the limit; `64` is the value for\n\t * the open Internet. A whole number from 0 to 128. IPv4 and IPv4-mapped\n\t * addresses keep their own key. Off by default: each address is counted.\n\t * It applies to the default key alone: given with a `key`, `rateLimit()`\n\t * throws, since the option would silently do nothing.\n\t */\n\treadonly ipv6Prefix?: number;\n\t/**\n\t * The `RateLimit` headers of the IETF draft on every counted response,\n\t * `X-RateLimit-*` with `legacy`, or none. `draft` by default.\n\t */\n\treadonly headers?: 'draft' | 'legacy' | false;\n}\n\n/**\n * `Requires` is what `key` and `skip` read from the context beyond\n * `BaseContext` — a `user` an earlier middleware adds — and what the app that\n * uses the limit must then give.\n *\n * `limit` and `windowMs` are required, unless the `store` declares its own\n * `policy` (`@softistx/alxia-redis`'s `redisStore` of a wired limit): they are then\n * read from it, and one that is given must equal it.\n */\nexport type RateLimitOptions<Requires extends object = Empty> =\n\tCountingOptions<Requires> &\n\t\t(\n\t\t\t| {\n\t\t\t\t\t/** How many requests a key may make in a window: a whole number, 1 or more. */\n\t\t\t\t\treadonly limit: number;\n\t\t\t\t\t/** The window, in milliseconds: a whole number, 1 or more. */\n\t\t\t\t\treadonly windowMs: number;\n\t\t\t\t\t/** Where it is counted: one process's memory by default. */\n\t\t\t\t\treadonly store?: RateLimitStore;\n\t\t\t }\n\t\t\t| {\n\t\t\t\t\treadonly limit?: number;\n\t\t\t\t\treadonly windowMs?: number;\n\t\t\t\t\t/** A store with a policy of its own gives `limit` and `windowMs`. */\n\t\t\t\t\treadonly store: PolicyStore;\n\t\t\t }\n\t\t);\n\n/** The body of the 429. */\nexport interface RateLimitedBody {\n\treadonly error: 'rate_limited';\n\t/** Seconds until the window ends. */\n\treadonly retryAfter: number;\n}\n\n/** What the routes behind the limit read: where the key stands. */\nexport interface RateLimitInfo {\n\treadonly limit: number;\n\treadonly remaining: number;\n\t/** Milliseconds until the allowance is whole again. */\n\treadonly resetAfter: number;\n}\n\n/**\n * What `rateLimit()` makes: a middleware that requires `Requires` of the\n * app, and gives `rateLimit` or answers the 429.\n */\nexport type RateLimit<Requires extends object = Empty> = Middleware<\n\tRequires,\n\tPromise<\n\t\tReply<429, RateLimitedBody> | Next<{ rateLimit: RateLimitInfo | undefined }>\n\t>\n>;\n\n/**\n * A rate limit, as a middleware: every request it runs on is counted —\n * the routes declared after it, and, given to `app.use`, a request no\n * route matches too — and answered a 429 past the limit.\n *\n * ```ts\n * app.use(rateLimit({ limit: 100, windowMs: 60_000 })).get(...);\n * ```\n *\n * A `key` that reads what an earlier middleware added names it, and the\n * app must then give it: `rateLimit<{ user: User }>({ key: ({ user }) => user.id, … })`.\n */\nexport function rateLimit<Requires extends object = Empty>(\n\toptions: RateLimitOptions<Requires>,\n): NoInfer<RateLimit<Requires>> {\n\tcheckPrefix(options);\n\tconst store = options.store ?? new MemoryStore();\n\tconst policy = resolvePolicy(options);\n\tconst key = options.key ?? defaultKey<Requires>(options.ipv6Prefix);\n\tconst style = options.headers ?? 'draft';\n\treturn defineMiddleware<Requires>()(async function rateLimit(ctx, next) {\n\t\tconst counted = options.skip?.(ctx) ? undefined : await key(ctx);\n\t\tif (counted === undefined) {\n\t\t\tconst rateLimit: RateLimitInfo | undefined = undefined;\n\t\t\treturn next({ rateLimit });\n\t\t}\n\t\tconst decision = await store.consume(counted, policy);\n\t\tsaid(ctx.set.headers, style, policy, decision);\n\t\tif (!decision.allowed) {\n\t\t\tconst retryAfter = Math.max(1, Math.ceil(decision.retryAfter / 1000));\n\t\t\tconst body: RateLimitedBody = { error: 'rate_limited', retryAfter };\n\t\t\treturn ctx.reply(429, body, {\n\t\t\t\theaders: { 'retry-after': String(retryAfter) },\n\t\t\t});\n\t\t}\n\t\tconst rateLimit: RateLimitInfo | undefined = {\n\t\t\tlimit: policy.limit,\n\t\t\tremaining: decision.remaining,\n\t\t\tresetAfter: decision.resetAfter,\n\t\t};\n\t\treturn next({ rateLimit });\n\t});\n}\n\n/** The default key: `ctx.ip`, or its IPv6 network under `prefix` bits. */\nfunction defaultKey<Requires extends object>(prefix: number | undefined) {\n\treturn (ctx: BaseContext & Requires): string | undefined =>\n\t\tprefix === undefined || ctx.ip === undefined\n\t\t\t? ctx.ip\n\t\t\t: ipv6Network(ctx.ip, prefix);\n}\n\n/** `ipv6Prefix` is a whole number from 0 to 128, and goes with the default key. */\nfunction checkPrefix(options: {\n\treadonly ipv6Prefix?: number | undefined;\n\treadonly key?: unknown;\n}): void {\n\tconst { ipv6Prefix } = options;\n\tif (ipv6Prefix === undefined) return;\n\tif (!Number.isInteger(ipv6Prefix) || ipv6Prefix < 0 || ipv6Prefix > 128) {\n\t\tthrow new TypeError(\n\t\t\t`rateLimit: ipv6Prefix must be a whole number from 0 to 128, not ${String(ipv6Prefix)}`,\n\t\t);\n\t}\n\tif (options.key !== undefined) {\n\t\tthrow new TypeError(\n\t\t\t'rateLimit: ipv6Prefix applies to the default key, and a key of your own was given. Drop one, or group the address in your key.',\n\t\t);\n\t}\n}\n\n/** The headers that say where the key stands, in the `style` asked for. */\nfunction said(\n\theaders: Headers,\n\tstyle: 'draft' | 'legacy' | false,\n\toptions: Policy,\n\tdecision: Decision,\n): void {\n\tif (style === 'draft') {\n\t\theaders.set('ratelimit-limit', String(options.limit));\n\t\theaders.set('ratelimit-remaining', String(decision.remaining));\n\t\theaders.set(\n\t\t\t'ratelimit-reset',\n\t\t\tString(Math.ceil(decision.resetAfter / 1000)),\n\t\t);\n\t\theaders.set(\n\t\t\t'ratelimit-policy',\n\t\t\t`${options.limit};w=${Math.ceil(options.windowMs / 1000)}`,\n\t\t);\n\t} else if (style === 'legacy') {\n\t\theaders.set('x-ratelimit-limit', String(options.limit));\n\t\theaders.set('x-ratelimit-remaining', String(decision.remaining));\n\t\theaders.set(\n\t\t\t'x-ratelimit-reset',\n\t\t\tString(Math.ceil((Date.now() + decision.resetAfter) / 1000)),\n\t\t);\n\t}\n}\n\nmarkFactory(rateLimit);\n",
7
+ "import type { Policy, RateLimitStore } from './store';\n\n/** What `resolvePolicy` reads: the numbers an app gave, and the store they count in. */\ninterface Given {\n\treadonly limit?: number | undefined;\n\treadonly windowMs?: number | undefined;\n\treadonly store?: RateLimitStore | undefined;\n}\n\n/**\n * The policy a limit counts and writes its headers by: the app's `limit`\n * and `windowMs`, or the store's own `policy` where it has one. A number\n * that differs from the store's is an error at declaration, since the\n * headers would say what the store does not do.\n */\nexport function resolvePolicy(given: Given): Policy {\n\tconst own = given.store?.policy;\n\tconst policy: Policy = {\n\t\tlimit: given.limit ?? own?.limit ?? Number.NaN,\n\t\twindowMs: given.windowMs ?? own?.windowMs ?? Number.NaN,\n\t};\n\tfor (const name of ['limit', 'windowMs'] as const) {\n\t\tconst value = policy[name];\n\t\tif (!Number.isSafeInteger(value) || value < 1) {\n\t\t\t// 0 refuses every request; a window of 0 or less never ends one.\n\t\t\tthrow new TypeError(\n\t\t\t\t`rateLimit: ${name} must be a whole number of 1 or more, not ${String(given[name] ?? own?.[name])}`,\n\t\t\t);\n\t\t}\n\t}\n\tif (own !== undefined) {\n\t\tfor (const name of ['limit', 'windowMs'] as const) {\n\t\t\tif (policy[name] !== own[name]) {\n\t\t\t\tthrow new TypeError(\n\t\t\t\t\t`rateLimit: ${name} ${policy[name]} differs from the store's policy of ${own.limit} per ${own.windowMs}ms. Leave limit and windowMs out to use the store's, or give the same numbers.`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\treturn policy;\n}\n",
8
+ "/** What a store decides for one request. Every duration is a delay, in milliseconds. */\nexport interface Decision {\n\treadonly allowed: boolean;\n\t/** Requests the key may still make now, after this one. */\n\treadonly remaining: number;\n\t/** Until the key's allowance is whole again. */\n\treadonly resetAfter: number;\n\t/** Until a refused request would be allowed; 0 when this one is. */\n\treadonly retryAfter: number;\n}\n\n/** The policy a store applies: `limit` requests per `windowMs`. */\nexport interface Policy {\n\treadonly limit: number;\n\treadonly windowMs: number;\n}\n\n/**\n * Where requests are counted, and what decides. The memory store counts in\n * one process with a fixed window; `@softistx/alxia-redis`'s counts across every\n * process sharing a Redis, with GCRA.\n */\nexport interface RateLimitStore {\n\t/** Counts one request for `key` under `policy`; a refused one counts nothing. */\n\tconsume(key: string, policy: Policy): Decision | Promise<Decision>;\n\t/** Forgets `key`: a user who just logged in. */\n\treset(key: string): void | Promise<void>;\n\t/**\n\t * The policy the store counts by itself, when it has one of its own — a\n\t * rate limit defined elsewhere, as `@softistx/alxia-redis`'s `redisStore` of a wired\n\t * limit. `rateLimit({ store })` then reads `limit` and `windowMs` from it,\n\t * and refuses numbers that differ.\n\t */\n\treadonly policy?: Policy;\n}\n\n/** A store that declares its own policy: `rateLimit` needs no `limit` nor `windowMs` with it. */\nexport type PolicyStore = RateLimitStore & { readonly policy: Policy };\n\n/** A fixed-window counter in memory, swept as windows end. */\nexport class MemoryStore implements RateLimitStore {\n\treadonly #hits = new Map<string, { count: number; resetAt: number }>();\n\t#sweeper: ReturnType<typeof setInterval> | undefined;\n\n\tconsume(key: string, policy: Policy): Decision {\n\t\tconst now = Date.now();\n\t\tlet entry = this.#hits.get(key);\n\t\tif (entry === undefined || entry.resetAt <= now) {\n\t\t\tentry = { count: 0, resetAt: now + policy.windowMs };\n\t\t\tthis.#hits.set(key, entry);\n\t\t}\n\t\tthis.#sweep(policy.windowMs);\n\t\tconst resetAfter = entry.resetAt - now;\n\t\tif (entry.count >= policy.limit) {\n\t\t\treturn {\n\t\t\t\tallowed: false,\n\t\t\t\tremaining: 0,\n\t\t\t\tresetAfter,\n\t\t\t\tretryAfter: resetAfter,\n\t\t\t};\n\t\t}\n\t\tentry.count++;\n\t\treturn {\n\t\t\tallowed: true,\n\t\t\tremaining: policy.limit - entry.count,\n\t\t\tresetAfter,\n\t\t\tretryAfter: 0,\n\t\t};\n\t}\n\n\treset(key: string): void {\n\t\tthis.#hits.delete(key);\n\t}\n\n\t/** How many keys are counted. */\n\tget size(): number {\n\t\treturn this.#hits.size;\n\t}\n\n\t#sweep(windowMs: number): void {\n\t\tif (this.#sweeper !== undefined) return;\n\t\tthis.#sweeper = setInterval(() => {\n\t\t\tconst now = Date.now();\n\t\t\tfor (const [key, entry] of this.#hits) {\n\t\t\t\tif (entry.resetAt <= now) this.#hits.delete(key);\n\t\t\t}\n\t\t\tif (this.#hits.size === 0) {\n\t\t\t\tclearInterval(this.#sweeper);\n\t\t\t\tthis.#sweeper = undefined;\n\t\t\t}\n\t\t}, windowMs);\n\t\tthis.#sweeper.unref?.();\n\t}\n}\n"
9
+ ],
10
+ "mappings": ";AACA,SAAS,QAAQ,CAAC,MAAoC;AAAA,EACrD,MAAM,OAAO,KAAK,QAAQ,GAAG;AAAA,EAC7B,MAAM,UAAU,SAAS,KAAK,OAAO,KAAK,MAAM,GAAG,IAAI;AAAA,EACvD,MAAM,SAAS,QAAQ,MAAM,IAAI;AAAA,EACjC,IAAI,OAAO,SAAS,KAAK,CAAC,QAAQ,SAAS,GAAG;AAAA,IAAG;AAAA,EACjD,MAAM,OAAO,CAAC,SACb,SAAS,aAAa,SAAS,KAAK,CAAC,IAAI,KAAK,MAAM,GAAG;AAAA,EACxD,MAAM,OAAO,KAAK,OAAO,EAAE,KAAK,CAAC;AAAA,EACj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,IAAI,UAAU,SAAS;AAAA,IACtB,QAAQ,IAAI,mBAAmB,OAAO,QAAQ,KAAK,CAAC;AAAA,IACpD,QAAQ,IAAI,uBAAuB,OAAO,SAAS,SAAS,CAAC;AAAA,IAC7D,QAAQ,IACP,mBACA,OAAO,KAAK,KAAK,SAAS,aAAa,IAAI,CAAC,CAC7C;AAAA,IACA,QAAQ,IACP,oBACA,GAAG,QAAQ,WAAW,KAAK,KAAK,QAAQ,WAAW,IAAI,GACxD;AAAA,EACD,EAAE,KAAK,IAAI,UAAU,UAAU;AAAA,IAC9B,QAAQ,IAAI,qBAAqB,OAAO,QAAQ,KAAK,CAAC;AAAA,IACtD,QAAQ,IAAI,yBAAyB,OAAO,SAAS,SAAS,CAAC;AAAA,IAC/D,QAAQ,IACP,qBACA,OAAO,KAAK,MAAM,KAAK,IAAI,IAAI,SAAS,cAAc,IAAI,CAAC,CAC5D;AAAA,EACD;AAAA;AAGD,YAAY,SAAS;",
11
+ "debugId": "623097C58F28DD0764756E2164756E21",
12
+ "names": []
13
+ }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * The network of an IPv6 `address` under `prefix` bits, as `2001:db8:1:2::/64`
3
+ * writes it. An IPv4-mapped address (`::ffff:203.0.113.9`) is its IPv4 address,
4
+ * a zone id (`%eth0`) is dropped, and a text that is not an IPv6 address
5
+ * (an IPv4 one included) is returned as it is.
6
+ */
7
+ export declare function ipv6Network(address: string, prefix: number): string;
8
+ //# sourceMappingURL=ipv6-network.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ipv6-network.d.ts","sourceRoot":"","sources":["../src/ipv6-network.ts"],"names":[],"mappings":"AAsEA;;;;;GAKG;AACH,wBAAgB,WAAW,CAAC,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,MAAM,CAenE"}
@@ -0,0 +1,16 @@
1
+ import type { Policy, RateLimitStore } from './store';
2
+ /** What `resolvePolicy` reads: the numbers an app gave, and the store they count in. */
3
+ interface Given {
4
+ readonly limit?: number | undefined;
5
+ readonly windowMs?: number | undefined;
6
+ readonly store?: RateLimitStore | undefined;
7
+ }
8
+ /**
9
+ * The policy a limit counts and writes its headers by: the app's `limit`
10
+ * and `windowMs`, or the store's own `policy` where it has one. A number
11
+ * that differs from the store's is an error at declaration, since the
12
+ * headers would say what the store does not do.
13
+ */
14
+ export declare function resolvePolicy(given: Given): Policy;
15
+ export {};
16
+ //# sourceMappingURL=policy.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"policy.d.ts","sourceRoot":"","sources":["../src/policy.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAEtD,wFAAwF;AACxF,UAAU,KAAK;IACd,QAAQ,CAAC,KAAK,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IACpC,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IACvC,QAAQ,CAAC,KAAK,CAAC,EAAE,cAAc,GAAG,SAAS,CAAC;CAC5C;AAED;;;;;GAKG;AACH,wBAAgB,aAAa,CAAC,KAAK,EAAE,KAAK,GAAG,MAAM,CAyBlD"}
@@ -0,0 +1,81 @@
1
+ import { type BaseContext, type Empty, type Middleware, type Next, type Reply } from '@softistx/alxia';
2
+ import { type PolicyStore, type RateLimitStore } from './store';
3
+ /** What `RateLimitOptions` holds whatever the store: how a request is counted and answered. */
4
+ interface CountingOptions<Requires extends object> {
5
+ /** What is counted: the client's address by default. `undefined` is not counted. */
6
+ readonly key?: (ctx: BaseContext & Requires) => string | undefined | Promise<string | undefined>;
7
+ /** Requests not counted at all. */
8
+ readonly skip?: (ctx: BaseContext & Requires) => boolean;
9
+ /**
10
+ * Count an IPv6 client by its network: the first `ipv6Prefix` bits of
11
+ * `ctx.ip`, keyed as `2001:db8:1:2::/64`. One subscriber usually holds a
12
+ * whole /64, so per address it can dodge the limit; `64` is the value for
13
+ * the open Internet. A whole number from 0 to 128. IPv4 and IPv4-mapped
14
+ * addresses keep their own key. Off by default: each address is counted.
15
+ * It applies to the default key alone: given with a `key`, `rateLimit()`
16
+ * throws, since the option would silently do nothing.
17
+ */
18
+ readonly ipv6Prefix?: number;
19
+ /**
20
+ * The `RateLimit` headers of the IETF draft on every counted response,
21
+ * `X-RateLimit-*` with `legacy`, or none. `draft` by default.
22
+ */
23
+ readonly headers?: 'draft' | 'legacy' | false;
24
+ }
25
+ /**
26
+ * `Requires` is what `key` and `skip` read from the context beyond
27
+ * `BaseContext` — a `user` an earlier middleware adds — and what the app that
28
+ * uses the limit must then give.
29
+ *
30
+ * `limit` and `windowMs` are required, unless the `store` declares its own
31
+ * `policy` (`@softistx/alxia-redis`'s `redisStore` of a wired limit): they are then
32
+ * read from it, and one that is given must equal it.
33
+ */
34
+ export type RateLimitOptions<Requires extends object = Empty> = CountingOptions<Requires> & ({
35
+ /** How many requests a key may make in a window: a whole number, 1 or more. */
36
+ readonly limit: number;
37
+ /** The window, in milliseconds: a whole number, 1 or more. */
38
+ readonly windowMs: number;
39
+ /** Where it is counted: one process's memory by default. */
40
+ readonly store?: RateLimitStore;
41
+ } | {
42
+ readonly limit?: number;
43
+ readonly windowMs?: number;
44
+ /** A store with a policy of its own gives `limit` and `windowMs`. */
45
+ readonly store: PolicyStore;
46
+ });
47
+ /** The body of the 429. */
48
+ export interface RateLimitedBody {
49
+ readonly error: 'rate_limited';
50
+ /** Seconds until the window ends. */
51
+ readonly retryAfter: number;
52
+ }
53
+ /** What the routes behind the limit read: where the key stands. */
54
+ export interface RateLimitInfo {
55
+ readonly limit: number;
56
+ readonly remaining: number;
57
+ /** Milliseconds until the allowance is whole again. */
58
+ readonly resetAfter: number;
59
+ }
60
+ /**
61
+ * What `rateLimit()` makes: a middleware that requires `Requires` of the
62
+ * app, and gives `rateLimit` or answers the 429.
63
+ */
64
+ export type RateLimit<Requires extends object = Empty> = Middleware<Requires, Promise<Reply<429, RateLimitedBody> | Next<{
65
+ rateLimit: RateLimitInfo | undefined;
66
+ }>>>;
67
+ /**
68
+ * A rate limit, as a middleware: every request it runs on is counted —
69
+ * the routes declared after it, and, given to `app.use`, a request no
70
+ * route matches too — and answered a 429 past the limit.
71
+ *
72
+ * ```ts
73
+ * app.use(rateLimit({ limit: 100, windowMs: 60_000 })).get(...);
74
+ * ```
75
+ *
76
+ * A `key` that reads what an earlier middleware added names it, and the
77
+ * app must then give it: `rateLimit<{ user: User }>({ key: ({ user }) => user.id, … })`.
78
+ */
79
+ export declare function rateLimit<Requires extends object = Empty>(options: RateLimitOptions<Requires>): NoInfer<RateLimit<Requires>>;
80
+ export {};
81
+ //# sourceMappingURL=rate-limit.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rate-limit.d.ts","sourceRoot":"","sources":["../src/rate-limit.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,KAAK,WAAW,EAEhB,KAAK,KAAK,EACV,KAAK,UAAU,EAEf,KAAK,IAAI,EACT,KAAK,KAAK,EACV,MAAM,iBAAiB,CAAC;AAGzB,OAAO,EAIN,KAAK,WAAW,EAChB,KAAK,cAAc,EACnB,MAAM,SAAS,CAAC;AAEjB,+FAA+F;AAC/F,UAAU,eAAe,CAAC,QAAQ,SAAS,MAAM;IAChD,oFAAoF;IACpF,QAAQ,CAAC,GAAG,CAAC,EAAE,CACd,GAAG,EAAE,WAAW,GAAG,QAAQ,KACvB,MAAM,GAAG,SAAS,GAAG,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAAC;IACtD,mCAAmC;IACnC,QAAQ,CAAC,IAAI,CAAC,EAAE,CAAC,GAAG,EAAE,WAAW,GAAG,QAAQ,KAAK,OAAO,CAAC;IACzD;;;;;;;;OAQG;IACH,QAAQ,CAAC,UAAU,CAAC,EAAE,MAAM,CAAC;IAC7B;;;OAGG;IACH,QAAQ,CAAC,OAAO,CAAC,EAAE,OAAO,GAAG,QAAQ,GAAG,KAAK,CAAC;CAC9C;AAED;;;;;;;;GAQG;AACH,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CA4B9B"}
@@ -0,0 +1,46 @@
1
+ /** What a store decides for one request. Every duration is a delay, in milliseconds. */
2
+ export interface Decision {
3
+ readonly allowed: boolean;
4
+ /** Requests the key may still make now, after this one. */
5
+ readonly remaining: number;
6
+ /** Until the key's allowance is whole again. */
7
+ readonly resetAfter: number;
8
+ /** Until a refused request would be allowed; 0 when this one is. */
9
+ readonly retryAfter: number;
10
+ }
11
+ /** The policy a store applies: `limit` requests per `windowMs`. */
12
+ export interface Policy {
13
+ readonly limit: number;
14
+ readonly windowMs: number;
15
+ }
16
+ /**
17
+ * Where requests are counted, and what decides. The memory store counts in
18
+ * one process with a fixed window; `@softistx/alxia-redis`'s counts across every
19
+ * process sharing a Redis, with GCRA.
20
+ */
21
+ export interface RateLimitStore {
22
+ /** Counts one request for `key` under `policy`; a refused one counts nothing. */
23
+ consume(key: string, policy: Policy): Decision | Promise<Decision>;
24
+ /** Forgets `key`: a user who just logged in. */
25
+ reset(key: string): void | Promise<void>;
26
+ /**
27
+ * The policy the store counts by itself, when it has one of its own — a
28
+ * rate limit defined elsewhere, as `@softistx/alxia-redis`'s `redisStore` of a wired
29
+ * limit. `rateLimit({ store })` then reads `limit` and `windowMs` from it,
30
+ * and refuses numbers that differ.
31
+ */
32
+ readonly policy?: Policy;
33
+ }
34
+ /** A store that declares its own policy: `rateLimit` needs no `limit` nor `windowMs` with it. */
35
+ export type PolicyStore = RateLimitStore & {
36
+ readonly policy: Policy;
37
+ };
38
+ /** A fixed-window counter in memory, swept as windows end. */
39
+ export declare class MemoryStore implements RateLimitStore {
40
+ #private;
41
+ consume(key: string, policy: Policy): Decision;
42
+ reset(key: string): void;
43
+ /** How many keys are counted. */
44
+ get size(): number;
45
+ }
46
+ //# sourceMappingURL=store.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"store.d.ts","sourceRoot":"","sources":["../src/store.ts"],"names":[],"mappings":"AAAA,wFAAwF;AACxF,MAAM,WAAW,QAAQ;IACxB,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAC;IAC1B,2DAA2D;IAC3D,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,gDAAgD;IAChD,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,oEAAoE;IACpE,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;CAC5B;AAED,mEAAmE;AACnE,MAAM,WAAW,MAAM;IACtB,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;CAC1B;AAED;;;;GAIG;AACH,MAAM,WAAW,cAAc;IAC9B,iFAAiF;IACjF,OAAO,CAAC,GAAG,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,QAAQ,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC;IACnE,gDAAgD;IAChD,KAAK,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IACzC;;;;;OAKG;IACH,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC;CACzB;AAED,iGAAiG;AACjG,MAAM,MAAM,WAAW,GAAG,cAAc,GAAG;IAAE,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAAC;AAEvE,8DAA8D;AAC9D,qBAAa,WAAY,YAAW,cAAc;;IAIjD,OAAO,CAAC,GAAG,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,QAAQ;IA0B9C,KAAK,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI;IAIxB,iCAAiC;IACjC,IAAI,IAAI,IAAI,MAAM,CAEjB;CAgBD"}
package/docs/README.md ADDED
@@ -0,0 +1,17 @@
1
+ # @softistx/alxia-rate-limit documentation
2
+
3
+ The [package README](../README.md) is the short version. This folder is
4
+ the long one: the options, defaults and behaviours with an example each,
5
+ the errors you may meet, and what is coming.
6
+
7
+ | Page | Read it when |
8
+ | --- | --- |
9
+ | [Guide](guide.md) | choosing what to count and where, reading the 429 on the wire, keeping counts across processes, or testing a limit |
10
+ | [Troubleshooting](troubleshooting.md) | something went wrong and you have the message, or a limit does not count as you expected |
11
+ | [Roadmap](roadmap.md) | wondering what is coming, and what is not planned |
12
+
13
+ ## Recipes
14
+
15
+ A task that crosses packages, in [the repository's recipes](https://github.com/softistx/alxia/blob/develop/docs/recipes/README.md), each with a complete example:
16
+
17
+ - [Caching and rate limiting with Redis](https://github.com/softistx/alxia/blob/develop/docs/recipes/caching-and-rate-limiting.md): a limit and a response cache shared by every process