@krizaka/rate-limit 0.0.0-stage → 0.1.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 +201 -0
- package/README.md +34 -2
- package/dist/index.d.ts +67 -0
- package/dist/index.js +194 -0
- package/dist/index.js.map +1 -0
- package/dist/port-DCGtrBSX.d.ts +75 -0
- package/dist/settings.d.ts +24 -0
- package/dist/settings.js +27 -0
- package/dist/settings.js.map +1 -0
- package/dist/testkit.d.ts +6 -0
- package/dist/testkit.js +64 -0
- package/dist/testkit.js.map +1 -0
- package/package.json +80 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,35 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @krizaka/rate-limit
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Limits per action for every Krizaka product: fixed windows per address and per subject, the limits read from the admin's settings, a memory store and a PostgreSQL store shared by every instance. It replaces the `rate-limit.ts` that Yomizaka, Akinaza and Kachizaka carried byte for byte, and the PostgreSQL variants of Orochia and Yasakia.
|
|
4
|
+
|
|
5
|
+
```ts
|
|
6
|
+
import { emitMigration } from "@krizaka/db";
|
|
7
|
+
import { createLimiter, dbLimitStore, rateLimitSchema, RateLimited } from "@krizaka/rate-limit";
|
|
8
|
+
import { limitsFromSettings, rateLimitSettings } from "@krizaka/rate-limit/settings";
|
|
9
|
+
import { clientIp } from "@krizaka/auth";
|
|
10
|
+
|
|
11
|
+
emitMigration(rateLimitSchema, 1, { tables: {} }); // commit the SQL once, in your migrations: table rate_limit.bucket
|
|
12
|
+
|
|
13
|
+
// the registry fragment: limits.signIn.perIp, limits.signIn.perSubject, limits.signIn.windowSeconds… the admin changes them without a redeploy
|
|
14
|
+
export const limitSettings = rateLimitSettings({ signIn: { perIp: 30, perSubject: 10, windowSeconds: 900 }, me: { perIp: 600, windowSeconds: 3600 } });
|
|
15
|
+
|
|
16
|
+
const limiter = createLimiter({
|
|
17
|
+
store: dbLimitStore(query), // or memoryLimitStore() in one process and in tests
|
|
18
|
+
clock: { now: () => new Date() },
|
|
19
|
+
limits: limitsFromSettings((key) => settings.get(key)), // or a plain table: { signIn: { perIp: 30, perSubject: 10, windowSeconds: 900 } }
|
|
20
|
+
onStoreError: (error, action) => log.error({ error, action }),
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
// in a route
|
|
24
|
+
await limiter.enforce("signIn", { ip: clientIp(req.headers, rules), subject: email }); // throws RateLimited: status 429, headers { "Retry-After" }
|
|
25
|
+
const verdict = await limiter.check("signIn", keys); // { ok: true } | { ok: false, retryAfterSeconds, scope: "ip" | "subject" }
|
|
26
|
+
await limiter.forget("signIn", keys); // a successful sign-in clears its failures
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
- **The semantics of the copies**, so their tests pass unchanged: a window starts at its first hit and lasts `windowSeconds`; a refused hit is counted too; the address is counted first and a refusal stops there; the subject is compared in lower case and counted only when the action has a `perSubject` limit and one is given; an unknown address is counted under `unknown`. The old call `limit("sign-in", req, email, [30, 900], [10, 900])` is `enforce("signIn", { ip, subject: email })` with `{ perIp: 30, perSubject: 10, windowSeconds: 900 }` in the settings.
|
|
30
|
+
- **The limiter takes keys, never a request.** The client's address is extracted by `clientIp` of `@krizaka/auth`; the package reads no header.
|
|
31
|
+
- **Limits are settings.** `rateLimitSettings` (`@krizaka/rate-limit/settings`, needs `@krizaka/settings` and `zod`) declares `limits.<action>.perIp`, `.perSubject` and `.windowSeconds` as integers with the product's defaults; `limitsFromSettings` reads them back at each check. An action id is letters and digits (`signIn`), because it sits in a settings key.
|
|
32
|
+
- **Stores:** `memoryLimitStore({ maxKeys })` keeps the copies' bound (10 000 windows; ended ones dropped first, then one shared overflow window, so a flood of keys limits itself and never clears a blocked caller's count). `dbLimitStore(query, { schema })` counts in **one atomic statement** (`INSERT … ON CONFLICT DO UPDATE … RETURNING`), so 100 parallel checks count exactly and every instance sees the same counters; times come from the injected clock, not the database's. The table is `rate_limit.bucket (key, count, window_start, reset_at)`, one row per key (a deviation from `(key, window_start)` as primary key: with the first hit starting the window, two concurrent first hits would otherwise open two rows). `purge(now)` deletes the ended windows: call it from the product's job.
|
|
33
|
+
- **A store that fails lets the request through** (the limiter must not take the site down) and tells `onStoreError`; `failOpen: false` rethrows instead.
|
|
34
|
+
- **Orochia's extras** are in the port: `peek` (read without counting), `set` (a lock-out) and `reset`.
|
|
35
|
+
- `limitStoreContract` (from `@krizaka/rate-limit/testkit`) is the contract every store runs.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import * as _krizaka_db from '@krizaka/db';
|
|
2
|
+
import { Clock, Query } from '@krizaka/db';
|
|
3
|
+
import { L as LimitKeys, C as CheckResult, a as LimitStore, b as LimitsSource } from './port-DCGtrBSX.js';
|
|
4
|
+
export { A as ActionLimit, B as BucketHit, R as RATE_LIMIT_CODE, c as RateLimitCode, d as RateLimited } from './port-DCGtrBSX.js';
|
|
5
|
+
|
|
6
|
+
interface LimiterDeps {
|
|
7
|
+
store: LimitStore;
|
|
8
|
+
clock: Clock;
|
|
9
|
+
/** The limits by action: a table, or a function reading the admin's settings at each check (see `@krizaka/rate-limit/settings`). */
|
|
10
|
+
limits: LimitsSource;
|
|
11
|
+
/**
|
|
12
|
+
* What a store that fails does: `true` (the default) lets the request through, so a limiter outage never takes the site down;
|
|
13
|
+
* `false` refuses it by rethrowing. Either way `onStoreError` hears of it.
|
|
14
|
+
*/
|
|
15
|
+
failOpen?: boolean;
|
|
16
|
+
/** Told of every store failure (log it). */
|
|
17
|
+
onStoreError?: (error: unknown, action: string) => void;
|
|
18
|
+
}
|
|
19
|
+
interface Limiter {
|
|
20
|
+
/** Counts one hit for the action on the address and the subject, address first; the first limit exceeded refuses. */
|
|
21
|
+
check(action: string, keys: LimitKeys): Promise<CheckResult>;
|
|
22
|
+
/** `check`, throwing `RateLimited` (429 with `Retry-After`) on a refusal: the shape of the copies' `limit(…)`. */
|
|
23
|
+
enforce(action: string, keys: LimitKeys): Promise<void>;
|
|
24
|
+
/** Forgets the action's counters of these keys: a successful sign-in clears its failures. */
|
|
25
|
+
forget(action: string, keys: LimitKeys): Promise<void>;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* The limiter of a product: fixed windows per address and per subject for each action, the limits from a table or from settings.
|
|
29
|
+
* The semantics are the copies' (`limit(action, req, subject, perIp, perSubject)`): a window starts at its first hit; a refused hit is
|
|
30
|
+
* counted too; the subject is only counted when a subject is given and the action limits it.
|
|
31
|
+
* @throws RangeError when an action has no limits, or limits that are not whole numbers from 1
|
|
32
|
+
*/
|
|
33
|
+
declare function createLimiter(deps: LimiterDeps): Limiter;
|
|
34
|
+
|
|
35
|
+
/** The memory bound of the in-process store, not a business parameter. */
|
|
36
|
+
declare const DEFAULT_MAX_KEYS = 10000;
|
|
37
|
+
/**
|
|
38
|
+
* Counters kept in this process: fine for one instance, and for tests; a second instance needs `dbLimitStore`. Behaves like the copies
|
|
39
|
+
* Yomizaka, Akinaza and Kachizaka carried: when `maxKeys` live windows are held, the ended ones are dropped first, and if it is still
|
|
40
|
+
* full a new key shares ONE overflow window instead, so a flood of keys limits itself and never hands a blocked caller a fresh count.
|
|
41
|
+
* @param options `maxKeys`: the most windows held
|
|
42
|
+
*/
|
|
43
|
+
declare function memoryLimitStore(options?: {
|
|
44
|
+
maxKeys?: number;
|
|
45
|
+
}): LimitStore;
|
|
46
|
+
/** How long until a window ends, in whole seconds, at least one: the `Retry-After` of a refusal. */
|
|
47
|
+
declare function retryAfterSeconds(resetAt: Date, now: Date): number;
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* The counters shared by every instance, in `rate_limit.bucket` (see `rateLimitSchema`; the schema may be renamed by the product).
|
|
51
|
+
* `hit` is ONE atomic statement — `INSERT … ON CONFLICT DO UPDATE … RETURNING` — so the row lock serialises concurrent hits and
|
|
52
|
+
* they are counted exactly; an ended window restarts at 1 in the same statement. Times come from the caller (the injected clock),
|
|
53
|
+
* never from the database's `now()`.
|
|
54
|
+
* @param query the product's query (its pool, or a transaction's client)
|
|
55
|
+
* @param options `schema`: the Postgres schema of the module, default `rate_limit`
|
|
56
|
+
*/
|
|
57
|
+
declare function dbLimitStore(query: Query, options?: {
|
|
58
|
+
schema?: string;
|
|
59
|
+
}): LimitStore;
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* The table of counters of « rate-limit », in its own Postgres schema (ADR-001 §3). One row per key holds the open window: its count,
|
|
63
|
+
* when it started and when it ends. It references no product table. Version 1 is frozen once released: a change is version 2.
|
|
64
|
+
*/
|
|
65
|
+
declare const rateLimitSchema: _krizaka_db.ModuleSchema;
|
|
66
|
+
|
|
67
|
+
export { CheckResult, DEFAULT_MAX_KEYS, LimitKeys, LimitStore, type Limiter, type LimiterDeps, LimitsSource, createLimiter, dbLimitStore, memoryLimitStore, rateLimitSchema, retryAfterSeconds };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
// src/memory.ts
|
|
2
|
+
import { addSeconds, differenceInMilliseconds, isAfter } from "@krizaka/time";
|
|
3
|
+
var DEFAULT_MAX_KEYS = 1e4;
|
|
4
|
+
var OVERFLOW = "overflow";
|
|
5
|
+
function memoryLimitStore(options = {}) {
|
|
6
|
+
const maxKeys = options.maxKeys ?? DEFAULT_MAX_KEYS;
|
|
7
|
+
const windows = /* @__PURE__ */ new Map();
|
|
8
|
+
const live = (entry, now) => !!entry && isAfter(entry.resetAt, now);
|
|
9
|
+
function prune(now) {
|
|
10
|
+
let dropped = 0;
|
|
11
|
+
for (const [key, entry] of windows) {
|
|
12
|
+
if (!live(entry, now)) {
|
|
13
|
+
windows.delete(key);
|
|
14
|
+
dropped += 1;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
return dropped;
|
|
18
|
+
}
|
|
19
|
+
return {
|
|
20
|
+
async hit(key, windowSeconds, now) {
|
|
21
|
+
let slot = key;
|
|
22
|
+
let entry = windows.get(slot);
|
|
23
|
+
if (!live(entry, now)) {
|
|
24
|
+
if (windows.size >= maxKeys) prune(now);
|
|
25
|
+
slot = windows.size >= maxKeys ? OVERFLOW : key;
|
|
26
|
+
entry = windows.get(slot);
|
|
27
|
+
if (!live(entry, now)) {
|
|
28
|
+
entry = { count: 0, resetAt: addSeconds(now, windowSeconds) };
|
|
29
|
+
windows.set(slot, entry);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
entry.count += 1;
|
|
33
|
+
return { count: entry.count, resetAt: entry.resetAt };
|
|
34
|
+
},
|
|
35
|
+
async peek(key, now) {
|
|
36
|
+
const entry = windows.get(key);
|
|
37
|
+
return live(entry, now) ? { ...entry } : null;
|
|
38
|
+
},
|
|
39
|
+
async set(key, count, seconds, now) {
|
|
40
|
+
if (!windows.has(key) && windows.size >= maxKeys) prune(now);
|
|
41
|
+
windows.set(key, { count, resetAt: addSeconds(now, seconds) });
|
|
42
|
+
},
|
|
43
|
+
async reset(key) {
|
|
44
|
+
windows.delete(key);
|
|
45
|
+
},
|
|
46
|
+
async purge(now) {
|
|
47
|
+
return prune(now);
|
|
48
|
+
}
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
function retryAfterSeconds(resetAt, now) {
|
|
52
|
+
return Math.max(1, Math.ceil(differenceInMilliseconds(resetAt, now) / 1e3));
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// src/port.ts
|
|
56
|
+
var RATE_LIMIT_CODE = {
|
|
57
|
+
limited: "RATE_LIMITED",
|
|
58
|
+
noLimits: "RATE_LIMIT_NO_LIMITS",
|
|
59
|
+
badLimit: "RATE_LIMIT_BAD_LIMIT"
|
|
60
|
+
};
|
|
61
|
+
var RateLimited = class extends Error {
|
|
62
|
+
constructor(retryAfterSeconds2, scope) {
|
|
63
|
+
super("Too many requests");
|
|
64
|
+
this.retryAfterSeconds = retryAfterSeconds2;
|
|
65
|
+
this.scope = scope;
|
|
66
|
+
this.name = "RateLimited";
|
|
67
|
+
}
|
|
68
|
+
retryAfterSeconds;
|
|
69
|
+
scope;
|
|
70
|
+
status = 429;
|
|
71
|
+
code = RATE_LIMIT_CODE.limited;
|
|
72
|
+
/** The header to send with the 429. */
|
|
73
|
+
get headers() {
|
|
74
|
+
return { "Retry-After": String(this.retryAfterSeconds) };
|
|
75
|
+
}
|
|
76
|
+
};
|
|
77
|
+
|
|
78
|
+
// src/limiter.ts
|
|
79
|
+
var ipKey = (action, ip) => `${action}:ip:${ip ?? "unknown"}`;
|
|
80
|
+
var subjectKey = (action, subject) => `${action}:s:${subject.toLowerCase()}`;
|
|
81
|
+
function checked(action, limit) {
|
|
82
|
+
if (!limit) throw new RangeError(`${RATE_LIMIT_CODE.noLimits}: no limits declared for the action \xAB ${action} \xBB`);
|
|
83
|
+
const whole = (value) => value === void 0 || Number.isInteger(value) && value >= 1;
|
|
84
|
+
if (!Number.isInteger(limit.windowSeconds) || limit.windowSeconds < 1 || !whole(limit.perIp) || !whole(limit.perSubject)) {
|
|
85
|
+
throw new RangeError(`${RATE_LIMIT_CODE.badLimit}: \xAB ${action} \xBB needs whole numbers from 1 (windowSeconds ${limit.windowSeconds}, perIp ${limit.perIp}, perSubject ${limit.perSubject})`);
|
|
86
|
+
}
|
|
87
|
+
return limit;
|
|
88
|
+
}
|
|
89
|
+
function createLimiter(deps) {
|
|
90
|
+
const limitsOf = async (action) => checked(action, typeof deps.limits === "function" ? await deps.limits(action) : deps.limits[action]);
|
|
91
|
+
async function guarded(action, work, whenFailed) {
|
|
92
|
+
try {
|
|
93
|
+
return await work();
|
|
94
|
+
} catch (error) {
|
|
95
|
+
deps.onStoreError?.(error, action);
|
|
96
|
+
if (deps.failOpen === false) throw error;
|
|
97
|
+
return whenFailed;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
async function check(action, keys) {
|
|
101
|
+
const limit = await limitsOf(action);
|
|
102
|
+
const now = deps.clock.now();
|
|
103
|
+
const counters = [];
|
|
104
|
+
if (limit.perIp !== void 0) counters.push({ scope: "ip", key: ipKey(action, keys.ip), max: limit.perIp });
|
|
105
|
+
if (limit.perSubject !== void 0 && keys.subject) counters.push({ scope: "subject", key: subjectKey(action, keys.subject), max: limit.perSubject });
|
|
106
|
+
for (const { scope, key, max } of counters) {
|
|
107
|
+
const hit = await guarded(action, () => deps.store.hit(key, limit.windowSeconds, now), null);
|
|
108
|
+
if (hit && hit.count > max) return { ok: false, retryAfterSeconds: retryAfterSeconds(hit.resetAt, now), scope };
|
|
109
|
+
}
|
|
110
|
+
return { ok: true };
|
|
111
|
+
}
|
|
112
|
+
return {
|
|
113
|
+
check,
|
|
114
|
+
async enforce(action, keys) {
|
|
115
|
+
const result = await check(action, keys);
|
|
116
|
+
if (!result.ok) throw new RateLimited(result.retryAfterSeconds, result.scope);
|
|
117
|
+
},
|
|
118
|
+
async forget(action, keys) {
|
|
119
|
+
const keysToForget = [ipKey(action, keys.ip), ...keys.subject ? [subjectKey(action, keys.subject)] : []];
|
|
120
|
+
for (const key of keysToForget) await guarded(action, () => deps.store.reset(key), void 0);
|
|
121
|
+
}
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
// src/persistence.ts
|
|
126
|
+
import { ident } from "@krizaka/db";
|
|
127
|
+
import { addSeconds as addSeconds2 } from "@krizaka/time";
|
|
128
|
+
var toHit = (row) => ({ count: Number(row.count), resetAt: new Date(row.reset_at) });
|
|
129
|
+
function dbLimitStore(query, options = {}) {
|
|
130
|
+
const bucket = `${ident(options.schema ?? "rate_limit")}.bucket`;
|
|
131
|
+
return {
|
|
132
|
+
async hit(key, windowSeconds, now) {
|
|
133
|
+
const [row] = await query(
|
|
134
|
+
`INSERT INTO ${bucket} AS b (key, count, window_start, reset_at) VALUES ($1, 1, $2, $3)
|
|
135
|
+
ON CONFLICT (key) DO UPDATE SET
|
|
136
|
+
count = CASE WHEN b.reset_at <= $2 THEN 1 ELSE b.count + 1 END,
|
|
137
|
+
window_start = CASE WHEN b.reset_at <= $2 THEN $2 ELSE b.window_start END,
|
|
138
|
+
reset_at = CASE WHEN b.reset_at <= $2 THEN $3 ELSE b.reset_at END
|
|
139
|
+
RETURNING count, reset_at`,
|
|
140
|
+
[key, now, addSeconds2(now, windowSeconds)]
|
|
141
|
+
);
|
|
142
|
+
return toHit(row);
|
|
143
|
+
},
|
|
144
|
+
async peek(key, now) {
|
|
145
|
+
const [row] = await query(`SELECT count, reset_at FROM ${bucket} WHERE key = $1 AND reset_at > $2`, [key, now]);
|
|
146
|
+
return row ? toHit(row) : null;
|
|
147
|
+
},
|
|
148
|
+
async set(key, count, seconds, now) {
|
|
149
|
+
await query(
|
|
150
|
+
`INSERT INTO ${bucket} (key, count, window_start, reset_at) VALUES ($1, $2, $3, $4)
|
|
151
|
+
ON CONFLICT (key) DO UPDATE SET count = excluded.count, window_start = excluded.window_start, reset_at = excluded.reset_at`,
|
|
152
|
+
[key, count, now, addSeconds2(now, seconds)]
|
|
153
|
+
);
|
|
154
|
+
},
|
|
155
|
+
async reset(key) {
|
|
156
|
+
await query(`DELETE FROM ${bucket} WHERE key = $1`, [key]);
|
|
157
|
+
},
|
|
158
|
+
async purge(now) {
|
|
159
|
+
const rows = await query(`DELETE FROM ${bucket} WHERE reset_at <= $1 RETURNING 1`, [now]);
|
|
160
|
+
return rows.length;
|
|
161
|
+
}
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
// src/schema.ts
|
|
166
|
+
import { defineModule } from "@krizaka/db";
|
|
167
|
+
var rateLimitSchema = defineModule({
|
|
168
|
+
module: "rate_limit",
|
|
169
|
+
migrations: [
|
|
170
|
+
{
|
|
171
|
+
version: 1,
|
|
172
|
+
name: "buckets",
|
|
173
|
+
sql: (c) => `
|
|
174
|
+
CREATE TABLE ${c.schema}.bucket (
|
|
175
|
+
key text PRIMARY KEY CHECK (char_length(key) BETWEEN 1 AND 300),
|
|
176
|
+
count integer NOT NULL CHECK (count >= 0),
|
|
177
|
+
window_start timestamptz NOT NULL,
|
|
178
|
+
reset_at timestamptz NOT NULL
|
|
179
|
+
);
|
|
180
|
+
CREATE INDEX bucket_reset_at ON ${c.schema}.bucket (reset_at);`
|
|
181
|
+
}
|
|
182
|
+
]
|
|
183
|
+
});
|
|
184
|
+
export {
|
|
185
|
+
DEFAULT_MAX_KEYS,
|
|
186
|
+
RATE_LIMIT_CODE,
|
|
187
|
+
RateLimited,
|
|
188
|
+
createLimiter,
|
|
189
|
+
dbLimitStore,
|
|
190
|
+
memoryLimitStore,
|
|
191
|
+
rateLimitSchema,
|
|
192
|
+
retryAfterSeconds
|
|
193
|
+
};
|
|
194
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/memory.ts","../src/port.ts","../src/limiter.ts","../src/persistence.ts","../src/schema.ts"],"sourcesContent":["import { addSeconds, differenceInMilliseconds, isAfter } from \"@krizaka/time\";\n\nimport type { BucketHit, LimitStore } from \"./port\";\n\n/** The memory bound of the in-process store, not a business parameter. */\n// @fixed: bounds the memory a flood of distinct keys can take\nexport const DEFAULT_MAX_KEYS = 10_000;\nconst OVERFLOW = \"overflow\";\n\n/**\n * Counters kept in this process: fine for one instance, and for tests; a second instance needs `dbLimitStore`. Behaves like the copies\n * Yomizaka, Akinaza and Kachizaka carried: when `maxKeys` live windows are held, the ended ones are dropped first, and if it is still\n * full a new key shares ONE overflow window instead, so a flood of keys limits itself and never hands a blocked caller a fresh count.\n * @param options `maxKeys`: the most windows held\n */\nexport function memoryLimitStore(options: { maxKeys?: number } = {}): LimitStore {\n const maxKeys = options.maxKeys ?? DEFAULT_MAX_KEYS;\n const windows = new Map<string, BucketHit>();\n const live = (entry: BucketHit | undefined, now: Date): entry is BucketHit => !!entry && isAfter(entry.resetAt, now);\n\n function prune(now: Date): number {\n let dropped = 0;\n for (const [key, entry] of windows) {\n if (!live(entry, now)) {\n windows.delete(key);\n dropped += 1;\n }\n }\n return dropped;\n }\n\n return {\n async hit(key, windowSeconds, now) {\n let slot = key;\n let entry = windows.get(slot);\n if (!live(entry, now)) {\n if (windows.size >= maxKeys) prune(now);\n slot = windows.size >= maxKeys ? OVERFLOW : key;\n entry = windows.get(slot);\n if (!live(entry, now)) {\n entry = { count: 0, resetAt: addSeconds(now, windowSeconds) };\n windows.set(slot, entry);\n }\n }\n entry.count += 1;\n return { count: entry.count, resetAt: entry.resetAt };\n },\n async peek(key, now) {\n const entry = windows.get(key);\n return live(entry, now) ? { ...entry } : null;\n },\n async set(key, count, seconds, now) {\n if (!windows.has(key) && windows.size >= maxKeys) prune(now);\n windows.set(key, { count, resetAt: addSeconds(now, seconds) });\n },\n async reset(key) {\n windows.delete(key);\n },\n async purge(now) {\n return prune(now);\n },\n };\n}\n\n/** How long until a window ends, in whole seconds, at least one: the `Retry-After` of a refusal. */\nexport function retryAfterSeconds(resetAt: Date, now: Date): number {\n return Math.max(1, Math.ceil(differenceInMilliseconds(resetAt, now) / 1000));\n}\n","/**\n * The ports of « rate-limit »: nothing here knows a request, a database client, an environment variable or the wall clock. The\n * product extracts the keys (an address, a subject) and the limiter counts them.\n */\n\n/** The state of a counter's window after a hit: how many hits it holds, and when it ends. */\nexport interface BucketHit {\n count: number;\n resetAt: Date;\n}\n\n/**\n * Where counters live: a fixed window per key, started by its first hit and lasting `windowSeconds`. A hit after the window ended\n * starts a new one. Adapters: `memoryLimitStore` (one process) and `dbLimitStore` (shared by every instance).\n */\nexport interface LimitStore {\n /** Counts one hit on `key` and returns the window it fell in. Atomic: concurrent hits are counted exactly. */\n hit(key: string, windowSeconds: number, now: Date): Promise<BucketHit>;\n /** The open window of `key`, without counting; null when none is open. */\n peek(key: string, now: Date): Promise<BucketHit | null>;\n /** Opens (or replaces) a window holding `count` that ends `seconds` from now: a lock-out. */\n set(key: string, count: number, seconds: number, now: Date): Promise<void>;\n /** Forgets `key` (a successful sign-in clears its failures). */\n reset(key: string): Promise<void>;\n /** Drops the windows that ended; returns how many. The product's job calls it. */\n purge(now: Date): Promise<number>;\n}\n\n/** What one action allows in one window. Each of `perIp` and `perSubject` is optional: absent means that key is not limited. */\nexport interface ActionLimit {\n /** Hits an address may make in the window. */\n perIp?: number;\n /** Hits a subject (an e-mail address, an account id) may make in the window. */\n perSubject?: number;\n /** The window's length in seconds. */\n windowSeconds: number;\n}\n\n/**\n * The limits, by action: a table, or a function that answers for an action (so the product can read them from its settings at each\n * check). `undefined` for an action nobody declared is a programming error and throws.\n */\nexport type LimitsSource = Readonly<Record<string, ActionLimit>> | ((action: string) => ActionLimit | undefined | Promise<ActionLimit | undefined>);\n\n/** The keys one check counts. The limiter receives keys, never a request: extract the address with `clientIp` of `@krizaka/auth`. */\nexport interface LimitKeys {\n /** The client's address; null (unknown) is counted under `unknown`, like the copies did. */\n ip?: string | null | undefined;\n /** The subject: an address, an account. Compared in lower case. Counted only when the action has a `perSubject` limit. */\n subject?: string | null | undefined;\n}\n\n/** A hit allowed, or refused with when to come back. */\nexport type CheckResult = { ok: true } | { ok: false; retryAfterSeconds: number; scope: \"ip\" | \"subject\" };\n\n/** Stable codes of this package's errors. */\nexport const RATE_LIMIT_CODE = {\n limited: \"RATE_LIMITED\",\n noLimits: \"RATE_LIMIT_NO_LIMITS\",\n badLimit: \"RATE_LIMIT_BAD_LIMIT\",\n} as const;\nexport type RateLimitCode = (typeof RATE_LIMIT_CODE)[keyof typeof RATE_LIMIT_CODE];\n\n/** A refusal: HTTP 429, with the seconds to wait (the `Retry-After` header). */\nexport class RateLimited extends Error {\n readonly status = 429;\n readonly code = RATE_LIMIT_CODE.limited;\n constructor(\n readonly retryAfterSeconds: number,\n readonly scope: \"ip\" | \"subject\",\n ) {\n super(\"Too many requests\");\n this.name = \"RateLimited\";\n }\n\n /** The header to send with the 429. */\n get headers(): { \"Retry-After\": string } {\n return { \"Retry-After\": String(this.retryAfterSeconds) };\n }\n}\n","import type { Clock } from \"@krizaka/db\";\n\nimport { retryAfterSeconds } from \"./memory\";\nimport { type ActionLimit, type CheckResult, type LimitKeys, type LimitsSource, type LimitStore, RATE_LIMIT_CODE, RateLimited } from \"./port\";\n\nexport interface LimiterDeps {\n store: LimitStore;\n clock: Clock;\n /** The limits by action: a table, or a function reading the admin's settings at each check (see `@krizaka/rate-limit/settings`). */\n limits: LimitsSource;\n /**\n * What a store that fails does: `true` (the default) lets the request through, so a limiter outage never takes the site down;\n * `false` refuses it by rethrowing. Either way `onStoreError` hears of it.\n */\n failOpen?: boolean;\n /** Told of every store failure (log it). */\n onStoreError?: (error: unknown, action: string) => void;\n}\n\nexport interface Limiter {\n /** Counts one hit for the action on the address and the subject, address first; the first limit exceeded refuses. */\n check(action: string, keys: LimitKeys): Promise<CheckResult>;\n /** `check`, throwing `RateLimited` (429 with `Retry-After`) on a refusal: the shape of the copies' `limit(…)`. */\n enforce(action: string, keys: LimitKeys): Promise<void>;\n /** Forgets the action's counters of these keys: a successful sign-in clears its failures. */\n forget(action: string, keys: LimitKeys): Promise<void>;\n}\n\nconst ipKey = (action: string, ip: string | null | undefined) => `${action}:ip:${ip ?? \"unknown\"}`;\nconst subjectKey = (action: string, subject: string) => `${action}:s:${subject.toLowerCase()}`;\n\nfunction checked(action: string, limit: ActionLimit | undefined): ActionLimit {\n if (!limit) throw new RangeError(`${RATE_LIMIT_CODE.noLimits}: no limits declared for the action « ${action} »`);\n const whole = (value: number | undefined) => value === undefined || (Number.isInteger(value) && value >= 1);\n if (!Number.isInteger(limit.windowSeconds) || limit.windowSeconds < 1 || !whole(limit.perIp) || !whole(limit.perSubject)) {\n throw new RangeError(`${RATE_LIMIT_CODE.badLimit}: « ${action} » needs whole numbers from 1 (windowSeconds ${limit.windowSeconds}, perIp ${limit.perIp}, perSubject ${limit.perSubject})`);\n }\n return limit;\n}\n\n/**\n * The limiter of a product: fixed windows per address and per subject for each action, the limits from a table or from settings.\n * The semantics are the copies' (`limit(action, req, subject, perIp, perSubject)`): a window starts at its first hit; a refused hit is\n * counted too; the subject is only counted when a subject is given and the action limits it.\n * @throws RangeError when an action has no limits, or limits that are not whole numbers from 1\n */\nexport function createLimiter(deps: LimiterDeps): Limiter {\n const limitsOf = async (action: string): Promise<ActionLimit> => checked(action, typeof deps.limits === \"function\" ? await deps.limits(action) : deps.limits[action]);\n\n async function guarded<T>(action: string, work: () => Promise<T>, whenFailed: T): Promise<T> {\n try {\n return await work();\n } catch (error) {\n deps.onStoreError?.(error, action);\n if (deps.failOpen === false) throw error;\n return whenFailed;\n }\n }\n\n async function check(action: string, keys: LimitKeys): Promise<CheckResult> {\n const limit = await limitsOf(action);\n const now = deps.clock.now();\n const counters: { scope: \"ip\" | \"subject\"; key: string; max: number }[] = [];\n if (limit.perIp !== undefined) counters.push({ scope: \"ip\", key: ipKey(action, keys.ip), max: limit.perIp });\n if (limit.perSubject !== undefined && keys.subject) counters.push({ scope: \"subject\", key: subjectKey(action, keys.subject), max: limit.perSubject });\n for (const { scope, key, max } of counters) {\n const hit = await guarded(action, () => deps.store.hit(key, limit.windowSeconds, now), null);\n if (hit && hit.count > max) return { ok: false, retryAfterSeconds: retryAfterSeconds(hit.resetAt, now), scope };\n }\n return { ok: true };\n }\n\n return {\n check,\n async enforce(action, keys) {\n const result = await check(action, keys);\n if (!result.ok) throw new RateLimited(result.retryAfterSeconds, result.scope);\n },\n async forget(action, keys) {\n const keysToForget = [ipKey(action, keys.ip), ...(keys.subject ? [subjectKey(action, keys.subject)] : [])];\n for (const key of keysToForget) await guarded(action, () => deps.store.reset(key), undefined);\n },\n };\n}\n","import { ident, type Query } from \"@krizaka/db\";\nimport { addSeconds } from \"@krizaka/time\";\n\nimport type { BucketHit, LimitStore } from \"./port\";\n\ninterface Row {\n count: number;\n reset_at: Date | string;\n}\nconst toHit = (row: Row): BucketHit => ({ count: Number(row.count), resetAt: new Date(row.reset_at) });\n\n/**\n * The counters shared by every instance, in `rate_limit.bucket` (see `rateLimitSchema`; the schema may be renamed by the product).\n * `hit` is ONE atomic statement — `INSERT … ON CONFLICT DO UPDATE … RETURNING` — so the row lock serialises concurrent hits and\n * they are counted exactly; an ended window restarts at 1 in the same statement. Times come from the caller (the injected clock),\n * never from the database's `now()`.\n * @param query the product's query (its pool, or a transaction's client)\n * @param options `schema`: the Postgres schema of the module, default `rate_limit`\n */\nexport function dbLimitStore(query: Query, options: { schema?: string } = {}): LimitStore {\n const bucket = `${ident(options.schema ?? \"rate_limit\")}.bucket`;\n return {\n async hit(key, windowSeconds, now) {\n const [row] = await query<Row>(\n `INSERT INTO ${bucket} AS b (key, count, window_start, reset_at) VALUES ($1, 1, $2, $3)\n ON CONFLICT (key) DO UPDATE SET\n count = CASE WHEN b.reset_at <= $2 THEN 1 ELSE b.count + 1 END,\n window_start = CASE WHEN b.reset_at <= $2 THEN $2 ELSE b.window_start END,\n reset_at = CASE WHEN b.reset_at <= $2 THEN $3 ELSE b.reset_at END\n RETURNING count, reset_at`,\n [key, now, addSeconds(now, windowSeconds)],\n );\n return toHit(row!);\n },\n async peek(key, now) {\n const [row] = await query<Row>(`SELECT count, reset_at FROM ${bucket} WHERE key = $1 AND reset_at > $2`, [key, now]);\n return row ? toHit(row) : null;\n },\n async set(key, count, seconds, now) {\n await query(\n `INSERT INTO ${bucket} (key, count, window_start, reset_at) VALUES ($1, $2, $3, $4)\n ON CONFLICT (key) DO UPDATE SET count = excluded.count, window_start = excluded.window_start, reset_at = excluded.reset_at`,\n [key, count, now, addSeconds(now, seconds)],\n );\n },\n async reset(key) {\n await query(`DELETE FROM ${bucket} WHERE key = $1`, [key]);\n },\n async purge(now) {\n const rows = await query(`DELETE FROM ${bucket} WHERE reset_at <= $1 RETURNING 1`, [now]);\n return rows.length;\n },\n };\n}\n","import { defineModule } from \"@krizaka/db\";\n\n/**\n * The table of counters of « rate-limit », in its own Postgres schema (ADR-001 §3). One row per key holds the open window: its count,\n * when it started and when it ends. It references no product table. Version 1 is frozen once released: a change is version 2.\n */\nexport const rateLimitSchema = defineModule({\n module: \"rate_limit\",\n migrations: [\n {\n version: 1,\n name: \"buckets\",\n sql: (c) => `\nCREATE TABLE ${c.schema}.bucket (\n key text PRIMARY KEY CHECK (char_length(key) BETWEEN 1 AND 300),\n count integer NOT NULL CHECK (count >= 0),\n window_start timestamptz NOT NULL,\n reset_at timestamptz NOT NULL\n);\nCREATE INDEX bucket_reset_at ON ${c.schema}.bucket (reset_at);`,\n },\n ],\n});\n"],"mappings":";AAAA,SAAS,YAAY,0BAA0B,eAAe;AAMvD,IAAM,mBAAmB;AAChC,IAAM,WAAW;AAQV,SAAS,iBAAiB,UAAgC,CAAC,GAAe;AAC/E,QAAM,UAAU,QAAQ,WAAW;AACnC,QAAM,UAAU,oBAAI,IAAuB;AAC3C,QAAM,OAAO,CAAC,OAA8B,QAAkC,CAAC,CAAC,SAAS,QAAQ,MAAM,SAAS,GAAG;AAEnH,WAAS,MAAM,KAAmB;AAChC,QAAI,UAAU;AACd,eAAW,CAAC,KAAK,KAAK,KAAK,SAAS;AAClC,UAAI,CAAC,KAAK,OAAO,GAAG,GAAG;AACrB,gBAAQ,OAAO,GAAG;AAClB,mBAAW;AAAA,MACb;AAAA,IACF;AACA,WAAO;AAAA,EACT;AAEA,SAAO;AAAA,IACL,MAAM,IAAI,KAAK,eAAe,KAAK;AACjC,UAAI,OAAO;AACX,UAAI,QAAQ,QAAQ,IAAI,IAAI;AAC5B,UAAI,CAAC,KAAK,OAAO,GAAG,GAAG;AACrB,YAAI,QAAQ,QAAQ,QAAS,OAAM,GAAG;AACtC,eAAO,QAAQ,QAAQ,UAAU,WAAW;AAC5C,gBAAQ,QAAQ,IAAI,IAAI;AACxB,YAAI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AK;AACjC,YAAM,CAAC,GAAG,IAAI,MAAM;AAAA,QAClB,eAAe,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,QAMrB,CAAC,KAAK,KAAKA,YAAW,KAAK,aAAa,CAAC;AAAA,MAC3C;AACA,aAAO,MAAM,GAAI;AAAA,IACnB;AAAA,IACA,MAAM,KAAK,KAAK,KAAK;AACnB,YAAM,CAAC,GAAG,IAAI,MAAM,MAAW,+BAA+B,MAAM,qCAAqC,CAAC,KAAK,GAAG,CAAC;AACnH,aAAO,MAAM,MAAM,GAAG,IAAI;AAAA,IAC5B;AAAA,IACA,MAAM,IAAI,KAAK,OAAO,SAAS,KAAK;AAClC,YAAM;AAAA,QACJ,eAAe,MAAM;AAAA;AAAA,QAErB,CAAC,KAAK,OAAO,KAAKA,YAAW,KAAK,OAAO,CAAC;AAAA,MAC5C;AAAA,IACF;AAAA,IACA,MAAM,MAAM,KAAK;AACf,YAAM,MAAM,eAAe,MAAM,mBAAmB,CAAC,GAAG,CAAC;AAAA,IAC3D;AAAA,IACA,MAAM,MAAM,KAAK;AACf,YAAM,OAAO,MAAM,MAAM,eAAe,MAAM,qCAAqC,CAAC,GAAG,CAAC;AACxF,aAAO,KAAK;AAAA,IACd;AAAA,EACF;AACF;;;ACrDA,SAAS,oBAAoB;AAMtB,IAAM,kBAAkB,aAAa;AAAA,EAC1C,QAAQ;AAAA,EACR,YAAY;AAAA,IACV;AAAA,MACE,SAAS;AAAA,MACT,MAAM;AAAA,MACN,KAAK,CAAC,MAAM;AAAA,eACH,EAAE,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,kCAMW,EAAE,MAAM;AAAA,IACtC;AAAA,EACF;AACF,CAAC;","names":["retryAfterSeconds","addSeconds"]}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The ports of « rate-limit »: nothing here knows a request, a database client, an environment variable or the wall clock. The
|
|
3
|
+
* product extracts the keys (an address, a subject) and the limiter counts them.
|
|
4
|
+
*/
|
|
5
|
+
/** The state of a counter's window after a hit: how many hits it holds, and when it ends. */
|
|
6
|
+
interface BucketHit {
|
|
7
|
+
count: number;
|
|
8
|
+
resetAt: Date;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Where counters live: a fixed window per key, started by its first hit and lasting `windowSeconds`. A hit after the window ended
|
|
12
|
+
* starts a new one. Adapters: `memoryLimitStore` (one process) and `dbLimitStore` (shared by every instance).
|
|
13
|
+
*/
|
|
14
|
+
interface LimitStore {
|
|
15
|
+
/** Counts one hit on `key` and returns the window it fell in. Atomic: concurrent hits are counted exactly. */
|
|
16
|
+
hit(key: string, windowSeconds: number, now: Date): Promise<BucketHit>;
|
|
17
|
+
/** The open window of `key`, without counting; null when none is open. */
|
|
18
|
+
peek(key: string, now: Date): Promise<BucketHit | null>;
|
|
19
|
+
/** Opens (or replaces) a window holding `count` that ends `seconds` from now: a lock-out. */
|
|
20
|
+
set(key: string, count: number, seconds: number, now: Date): Promise<void>;
|
|
21
|
+
/** Forgets `key` (a successful sign-in clears its failures). */
|
|
22
|
+
reset(key: string): Promise<void>;
|
|
23
|
+
/** Drops the windows that ended; returns how many. The product's job calls it. */
|
|
24
|
+
purge(now: Date): Promise<number>;
|
|
25
|
+
}
|
|
26
|
+
/** What one action allows in one window. Each of `perIp` and `perSubject` is optional: absent means that key is not limited. */
|
|
27
|
+
interface ActionLimit {
|
|
28
|
+
/** Hits an address may make in the window. */
|
|
29
|
+
perIp?: number;
|
|
30
|
+
/** Hits a subject (an e-mail address, an account id) may make in the window. */
|
|
31
|
+
perSubject?: number;
|
|
32
|
+
/** The window's length in seconds. */
|
|
33
|
+
windowSeconds: number;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* The limits, by action: a table, or a function that answers for an action (so the product can read them from its settings at each
|
|
37
|
+
* check). `undefined` for an action nobody declared is a programming error and throws.
|
|
38
|
+
*/
|
|
39
|
+
type LimitsSource = Readonly<Record<string, ActionLimit>> | ((action: string) => ActionLimit | undefined | Promise<ActionLimit | undefined>);
|
|
40
|
+
/** The keys one check counts. The limiter receives keys, never a request: extract the address with `clientIp` of `@krizaka/auth`. */
|
|
41
|
+
interface LimitKeys {
|
|
42
|
+
/** The client's address; null (unknown) is counted under `unknown`, like the copies did. */
|
|
43
|
+
ip?: string | null | undefined;
|
|
44
|
+
/** The subject: an address, an account. Compared in lower case. Counted only when the action has a `perSubject` limit. */
|
|
45
|
+
subject?: string | null | undefined;
|
|
46
|
+
}
|
|
47
|
+
/** A hit allowed, or refused with when to come back. */
|
|
48
|
+
type CheckResult = {
|
|
49
|
+
ok: true;
|
|
50
|
+
} | {
|
|
51
|
+
ok: false;
|
|
52
|
+
retryAfterSeconds: number;
|
|
53
|
+
scope: "ip" | "subject";
|
|
54
|
+
};
|
|
55
|
+
/** Stable codes of this package's errors. */
|
|
56
|
+
declare const RATE_LIMIT_CODE: {
|
|
57
|
+
readonly limited: "RATE_LIMITED";
|
|
58
|
+
readonly noLimits: "RATE_LIMIT_NO_LIMITS";
|
|
59
|
+
readonly badLimit: "RATE_LIMIT_BAD_LIMIT";
|
|
60
|
+
};
|
|
61
|
+
type RateLimitCode = (typeof RATE_LIMIT_CODE)[keyof typeof RATE_LIMIT_CODE];
|
|
62
|
+
/** A refusal: HTTP 429, with the seconds to wait (the `Retry-After` header). */
|
|
63
|
+
declare class RateLimited extends Error {
|
|
64
|
+
readonly retryAfterSeconds: number;
|
|
65
|
+
readonly scope: "ip" | "subject";
|
|
66
|
+
readonly status = 429;
|
|
67
|
+
readonly code: "RATE_LIMITED";
|
|
68
|
+
constructor(retryAfterSeconds: number, scope: "ip" | "subject");
|
|
69
|
+
/** The header to send with the 429. */
|
|
70
|
+
get headers(): {
|
|
71
|
+
"Retry-After": string;
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export { type ActionLimit as A, type BucketHit as B, type CheckResult as C, type LimitKeys as L, RATE_LIMIT_CODE as R, type LimitStore as a, type LimitsSource as b, type RateLimitCode as c, RateLimited as d };
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { Registry } from '@krizaka/settings';
|
|
2
|
+
import { A as ActionLimit } from './port-DCGtrBSX.js';
|
|
3
|
+
|
|
4
|
+
/** What a product declares for an action: the defaults the admin can then change. */
|
|
5
|
+
interface ActionDefaults {
|
|
6
|
+
perIp?: number;
|
|
7
|
+
perSubject?: number;
|
|
8
|
+
windowSeconds: number;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* The registry fragment of the limits: `limits.<action>.perIp`, `limits.<action>.perSubject` (when the action has one) and
|
|
12
|
+
* `limits.<action>.windowSeconds`, each an integer with the product's default and bounds. Global scope. The admin changes a limit
|
|
13
|
+
* without a redeploy; `limitsFromSettings` reads them back for the limiter.
|
|
14
|
+
* @param actions the product's actions, by id (camelCase: `signIn`, `passwordForgot`), with their defaults
|
|
15
|
+
* @throws RangeError for an action id that cannot be part of a settings key
|
|
16
|
+
*/
|
|
17
|
+
declare function rateLimitSettings(actions: Readonly<Record<string, ActionDefaults>>): Registry;
|
|
18
|
+
/**
|
|
19
|
+
* The limiter's `limits` function over the settings: it reads the keys of an action. `read` is the product's accessor
|
|
20
|
+
* (`(key) => service.get(key, ctx)`); a key the action does not declare answers `undefined` and is left out.
|
|
21
|
+
*/
|
|
22
|
+
declare function limitsFromSettings(read: (key: string) => number | undefined | Promise<number | undefined>): (action: string) => Promise<ActionLimit | undefined>;
|
|
23
|
+
|
|
24
|
+
export { type ActionDefaults, limitsFromSettings, rateLimitSettings };
|
package/dist/settings.js
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
// src/settings.ts
|
|
2
|
+
import { integer } from "@krizaka/settings";
|
|
3
|
+
var ACTION_ID = /^[a-z][A-Za-z0-9]{0,39}$/;
|
|
4
|
+
function rateLimitSettings(actions) {
|
|
5
|
+
const fragment = {};
|
|
6
|
+
for (const [action, defaults] of Object.entries(actions)) {
|
|
7
|
+
if (!ACTION_ID.test(action)) throw new RangeError(`rate-limit action \xAB ${action} \xBB: use letters and digits, starting with a lower-case letter (it is part of a settings key)`);
|
|
8
|
+
if (defaults.perIp !== void 0) fragment[`limits.${action}.perIp`] = integer("limits", defaults.perIp, { min: 1, max: 1e6, unit: "hits" });
|
|
9
|
+
if (defaults.perSubject !== void 0) fragment[`limits.${action}.perSubject`] = integer("limits", defaults.perSubject, { min: 1, max: 1e6, unit: "hits" });
|
|
10
|
+
fragment[`limits.${action}.windowSeconds`] = integer("limits", defaults.windowSeconds, { min: 1, max: 86400, unit: "seconds" });
|
|
11
|
+
}
|
|
12
|
+
return fragment;
|
|
13
|
+
}
|
|
14
|
+
function limitsFromSettings(read) {
|
|
15
|
+
return async (action) => {
|
|
16
|
+
const windowSeconds = await read(`limits.${action}.windowSeconds`);
|
|
17
|
+
if (windowSeconds === void 0) return void 0;
|
|
18
|
+
const perIp = await read(`limits.${action}.perIp`);
|
|
19
|
+
const perSubject = await read(`limits.${action}.perSubject`);
|
|
20
|
+
return { windowSeconds, ...perIp === void 0 ? {} : { perIp }, ...perSubject === void 0 ? {} : { perSubject } };
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
export {
|
|
24
|
+
limitsFromSettings,
|
|
25
|
+
rateLimitSettings
|
|
26
|
+
};
|
|
27
|
+
//# sourceMappingURL=settings.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/settings.ts"],"sourcesContent":["import { integer, type Registry } from \"@krizaka/settings\";\n\nimport type { ActionLimit } from \"./port\";\n\n/** What a product declares for an action: the defaults the admin can then change. */\nexport interface ActionDefaults {\n perIp?: number;\n perSubject?: number;\n windowSeconds: number;\n}\n\n/** An action id that can sit in a settings key (`limits.signIn.perIp`): letters and digits, starting with a lower-case letter. */\nconst ACTION_ID = /^[a-z][A-Za-z0-9]{0,39}$/;\n\n/**\n * The registry fragment of the limits: `limits.<action>.perIp`, `limits.<action>.perSubject` (when the action has one) and\n * `limits.<action>.windowSeconds`, each an integer with the product's default and bounds. Global scope. The admin changes a limit\n * without a redeploy; `limitsFromSettings` reads them back for the limiter.\n * @param actions the product's actions, by id (camelCase: `signIn`, `passwordForgot`), with their defaults\n * @throws RangeError for an action id that cannot be part of a settings key\n */\nexport function rateLimitSettings(actions: Readonly<Record<string, ActionDefaults>>): Registry {\n const fragment: Registry = {};\n for (const [action, defaults] of Object.entries(actions)) {\n if (!ACTION_ID.test(action)) throw new RangeError(`rate-limit action « ${action} »: use letters and digits, starting with a lower-case letter (it is part of a settings key)`);\n // @fixed: an admin may set 1 to a million hits and a window of a second to a day; the defaults are the product's\n if (defaults.perIp !== undefined) fragment[`limits.${action}.perIp`] = integer(\"limits\", defaults.perIp, { min: 1, max: 1_000_000, unit: \"hits\" });\n if (defaults.perSubject !== undefined) fragment[`limits.${action}.perSubject`] = integer(\"limits\", defaults.perSubject, { min: 1, max: 1_000_000, unit: \"hits\" });\n fragment[`limits.${action}.windowSeconds`] = integer(\"limits\", defaults.windowSeconds, { min: 1, max: 86_400, unit: \"seconds\" });\n }\n return fragment;\n}\n\n/**\n * The limiter's `limits` function over the settings: it reads the keys of an action. `read` is the product's accessor\n * (`(key) => service.get(key, ctx)`); a key the action does not declare answers `undefined` and is left out.\n */\nexport function limitsFromSettings(read: (key: string) => number | undefined | Promise<number | undefined>): (action: string) => Promise<ActionLimit | undefined> {\n return async (action) => {\n const windowSeconds = await read(`limits.${action}.windowSeconds`);\n if (windowSeconds === undefined) return undefined;\n const perIp = await read(`limits.${action}.perIp`);\n const perSubject = await read(`limits.${action}.perSubject`);\n return { windowSeconds, ...(perIp === undefined ? {} : { perIp }), ...(perSubject === undefined ? {} : { perSubject }) };\n };\n}\n"],"mappings":";AAAA,SAAS,eAA8B;AAYvC,IAAM,YAAY;AASX,SAAS,kBAAkB,SAA6D;AAC7F,QAAM,WAAqB,CAAC;AAC5B,aAAW,CAAC,QAAQ,QAAQ,KAAK,OAAO,QAAQ,OAAO,GAAG;AACxD,QAAI,CAAC,UAAU,KAAK,MAAM,EAAG,OAAM,IAAI,WAAW,0BAAuB,MAAM,iGAA8F;AAE7K,QAAI,SAAS,UAAU,OAAW,UAAS,UAAU,MAAM,QAAQ,IAAI,QAAQ,UAAU,SAAS,OAAO,EAAE,KAAK,GAAG,KAAK,KAAW,MAAM,OAAO,CAAC;AACjJ,QAAI,SAAS,eAAe,OAAW,UAAS,UAAU,MAAM,aAAa,IAAI,QAAQ,UAAU,SAAS,YAAY,EAAE,KAAK,GAAG,KAAK,KAAW,MAAM,OAAO,CAAC;AAChK,aAAS,UAAU,MAAM,gBAAgB,IAAI,QAAQ,UAAU,SAAS,eAAe,EAAE,KAAK,GAAG,KAAK,OAAQ,MAAM,UAAU,CAAC;AAAA,EACjI;AACA,SAAO;AACT;AAMO,SAAS,mBAAmB,MAA+H;AAChK,SAAO,OAAO,WAAW;AACvB,UAAM,gBAAgB,MAAM,KAAK,UAAU,MAAM,gBAAgB;AACjE,QAAI,kBAAkB,OAAW,QAAO;AACxC,UAAM,QAAQ,MAAM,KAAK,UAAU,MAAM,QAAQ;AACjD,UAAM,aAAa,MAAM,KAAK,UAAU,MAAM,aAAa;AAC3D,WAAO,EAAE,eAAe,GAAI,UAAU,SAAY,CAAC,IAAI,EAAE,MAAM,GAAI,GAAI,eAAe,SAAY,CAAC,IAAI,EAAE,WAAW,EAAG;AAAA,EACzH;AACF;","names":[]}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { a as LimitStore } from './port-DCGtrBSX.js';
|
|
2
|
+
|
|
3
|
+
/** What every `LimitStore` adapter must do: the same behaviour behind the same port. `make` gives a store with no counters. */
|
|
4
|
+
declare function limitStoreContract(name: string, make: () => LimitStore | Promise<LimitStore>): void;
|
|
5
|
+
|
|
6
|
+
export { limitStoreContract };
|
package/dist/testkit.js
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
// src/testkit.ts
|
|
2
|
+
import { expect, it } from "vitest";
|
|
3
|
+
var T0 = /* @__PURE__ */ new Date("2026-10-26T12:00:00.000Z");
|
|
4
|
+
var at = (seconds) => new Date(T0.valueOf() + seconds * 1e3);
|
|
5
|
+
function limitStoreContract(name, make) {
|
|
6
|
+
it(`${name}: counts hits in a window that the first hit starts`, async () => {
|
|
7
|
+
const store = await make();
|
|
8
|
+
const first = await store.hit("k", 60, T0);
|
|
9
|
+
expect(first.count).toBe(1);
|
|
10
|
+
expect(first.resetAt.toISOString()).toBe(at(60).toISOString());
|
|
11
|
+
const later = await store.hit("k", 60, at(30));
|
|
12
|
+
expect(later.count).toBe(2);
|
|
13
|
+
expect(later.resetAt.toISOString()).toBe(at(60).toISOString());
|
|
14
|
+
});
|
|
15
|
+
it(`${name}: starts a new window when the last one has ended`, async () => {
|
|
16
|
+
const store = await make();
|
|
17
|
+
await store.hit("k", 60, T0);
|
|
18
|
+
await store.hit("k", 60, at(10));
|
|
19
|
+
const next = await store.hit("k", 60, at(60));
|
|
20
|
+
expect(next.count).toBe(1);
|
|
21
|
+
expect(next.resetAt.toISOString()).toBe(at(120).toISOString());
|
|
22
|
+
});
|
|
23
|
+
it(`${name}: keeps keys apart`, async () => {
|
|
24
|
+
const store = await make();
|
|
25
|
+
await store.hit("a", 60, T0);
|
|
26
|
+
await store.hit("a", 60, T0);
|
|
27
|
+
expect((await store.hit("b", 60, T0)).count).toBe(1);
|
|
28
|
+
});
|
|
29
|
+
it(`${name}: peeks without counting, and only while the window is open`, async () => {
|
|
30
|
+
const store = await make();
|
|
31
|
+
expect(await store.peek("k", T0)).toBeNull();
|
|
32
|
+
await store.hit("k", 60, T0);
|
|
33
|
+
expect((await store.peek("k", at(1)))?.count).toBe(1);
|
|
34
|
+
expect((await store.peek("k", at(1)))?.count).toBe(1);
|
|
35
|
+
expect(await store.peek("k", at(60))).toBeNull();
|
|
36
|
+
});
|
|
37
|
+
it(`${name}: opens a lock-out with set, and forgets with reset`, async () => {
|
|
38
|
+
const store = await make();
|
|
39
|
+
await store.set("k", 99, 300, T0);
|
|
40
|
+
expect(await store.peek("k", at(299))).toMatchObject({ count: 99 });
|
|
41
|
+
expect((await store.hit("k", 60, at(10))).count).toBe(100);
|
|
42
|
+
await store.reset("k");
|
|
43
|
+
expect(await store.peek("k", at(11))).toBeNull();
|
|
44
|
+
await store.reset("k");
|
|
45
|
+
});
|
|
46
|
+
it(`${name}: purges the ended windows and only those`, async () => {
|
|
47
|
+
const store = await make();
|
|
48
|
+
await store.hit("short", 10, T0);
|
|
49
|
+
await store.hit("long", 600, T0);
|
|
50
|
+
expect(await store.purge(at(30))).toBe(1);
|
|
51
|
+
expect(await store.peek("short", at(30))).toBeNull();
|
|
52
|
+
expect((await store.peek("long", at(30)))?.count).toBe(1);
|
|
53
|
+
});
|
|
54
|
+
it(`${name}: counts parallel hits exactly`, async () => {
|
|
55
|
+
const store = await make();
|
|
56
|
+
const hits = await Promise.all(Array.from({ length: 100 }, () => store.hit("burst", 60, T0)));
|
|
57
|
+
expect(hits.map((h) => h.count).sort((a, b) => a - b)).toEqual(Array.from({ length: 100 }, (_, i) => i + 1));
|
|
58
|
+
expect((await store.peek("burst", at(1)))?.count).toBe(100);
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
export {
|
|
62
|
+
limitStoreContract
|
|
63
|
+
};
|
|
64
|
+
//# sourceMappingURL=testkit.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/testkit.ts"],"sourcesContent":["import { expect, it } from \"vitest\";\n\nimport type { LimitStore } from \"./port\";\n\nconst T0 = new Date(\"2026-10-26T12:00:00.000Z\");\nconst at = (seconds: number) => new Date(T0.valueOf() + seconds * 1000);\n\n/** What every `LimitStore` adapter must do: the same behaviour behind the same port. `make` gives a store with no counters. */\nexport function limitStoreContract(name: string, make: () => LimitStore | Promise<LimitStore>) {\n it(`${name}: counts hits in a window that the first hit starts`, async () => {\n const store = await make();\n const first = await store.hit(\"k\", 60, T0);\n expect(first.count).toBe(1);\n expect(first.resetAt.toISOString()).toBe(at(60).toISOString());\n const later = await store.hit(\"k\", 60, at(30));\n expect(later.count).toBe(2);\n expect(later.resetAt.toISOString()).toBe(at(60).toISOString()); // a later hit does not extend the window\n });\n\n it(`${name}: starts a new window when the last one has ended`, async () => {\n const store = await make();\n await store.hit(\"k\", 60, T0);\n await store.hit(\"k\", 60, at(10));\n const next = await store.hit(\"k\", 60, at(60));\n expect(next.count).toBe(1);\n expect(next.resetAt.toISOString()).toBe(at(120).toISOString());\n });\n\n it(`${name}: keeps keys apart`, async () => {\n const store = await make();\n await store.hit(\"a\", 60, T0);\n await store.hit(\"a\", 60, T0);\n expect((await store.hit(\"b\", 60, T0)).count).toBe(1);\n });\n\n it(`${name}: peeks without counting, and only while the window is open`, async () => {\n const store = await make();\n expect(await store.peek(\"k\", T0)).toBeNull();\n await store.hit(\"k\", 60, T0);\n expect((await store.peek(\"k\", at(1)))?.count).toBe(1);\n expect((await store.peek(\"k\", at(1)))?.count).toBe(1);\n expect(await store.peek(\"k\", at(60))).toBeNull();\n });\n\n it(`${name}: opens a lock-out with set, and forgets with reset`, async () => {\n const store = await make();\n await store.set(\"k\", 99, 300, T0);\n expect(await store.peek(\"k\", at(299))).toMatchObject({ count: 99 });\n expect((await store.hit(\"k\", 60, at(10))).count).toBe(100);\n await store.reset(\"k\");\n expect(await store.peek(\"k\", at(11))).toBeNull();\n await store.reset(\"k\"); // twice: safe\n });\n\n it(`${name}: purges the ended windows and only those`, async () => {\n const store = await make();\n await store.hit(\"short\", 10, T0);\n await store.hit(\"long\", 600, T0);\n expect(await store.purge(at(30))).toBe(1);\n expect(await store.peek(\"short\", at(30))).toBeNull();\n expect((await store.peek(\"long\", at(30)))?.count).toBe(1);\n });\n\n it(`${name}: counts parallel hits exactly`, async () => {\n const store = await make();\n const hits = await Promise.all(Array.from({ length: 100 }, () => store.hit(\"burst\", 60, T0)));\n expect(hits.map((h) => h.count).sort((a, b) => a - b)).toEqual(Array.from({ length: 100 }, (_, i) => i + 1));\n expect((await store.peek(\"bur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,GAAG,EAAE,CAAC,CAAC,EAAE,SAAS;AACnD,YAAQ,MAAM,MAAM,KAAK,QAAQ,GAAG,EAAE,CAAC,IAAI,KAAK,EAAE,KAAK,CAAC;AAAA,EAC1D,CAAC;AAED,KAAG,GAAG,IAAI,kCAAkC,YAAY;AACtD,UAAM,QAAQ,MAAM,KAAK;AACzB,UAAM,OAAO,MAAM,QAAQ,IAAI,MAAM,KAAK,EAAE,QAAQ,IAAI,GAAG,MAAM,MAAM,IAAI,SAAS,IAAI,EAAE,CAAC,CAAC;AAC5F,WAAO,KAAK,IAAI,CAAC,MAAM,EAAE,KAAK,EAAE,KAAK,CAAC,GAAG,MAAM,IAAI,CAAC,CAAC,EAAE,QAAQ,MAAM,KAAK,EAAE,QAAQ,IAAI,GAAG,CAAC,GAAG,MAAM,IAAI,CAAC,CAAC;AAC3G,YAAQ,MAAM,MAAM,KAAK,SAAS,GAAG,CAAC,CAAC,IAAI,KAAK,EAAE,KAAK,GAAG;AAAA,EAC5D,CAAC;AACH;","names":[]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,83 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@krizaka/rate-limit",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "Limits per action for every Krizaka product: fixed windows per address and per subject, the limits read from the admin's settings, a memory store and a PostgreSQL store whose atomic upsert counts exactly under concurrency, a stable 429 with Retry-After. No database client, no wall clock, no request object.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"krizaka",
|
|
7
|
+
"rate-limit",
|
|
8
|
+
"abuse",
|
|
9
|
+
"postgresql"
|
|
10
|
+
],
|
|
11
|
+
"homepage": "https://github.com/krizaka/krizaka-ts/tree/main/packages/rate-limit",
|
|
12
|
+
"bugs": "https://github.com/krizaka/krizaka-ts/issues",
|
|
13
|
+
"repository": {
|
|
14
|
+
"type": "git",
|
|
15
|
+
"url": "git+https://github.com/krizaka/krizaka-ts.git",
|
|
16
|
+
"directory": "packages/rate-limit"
|
|
17
|
+
},
|
|
18
|
+
"license": "Apache-2.0",
|
|
19
|
+
"author": "Krizaka (https://www.krizaka.com)",
|
|
20
|
+
"type": "module",
|
|
21
|
+
"main": "./dist/index.js",
|
|
22
|
+
"module": "./dist/index.js",
|
|
23
|
+
"types": "./dist/index.d.ts",
|
|
24
|
+
"exports": {
|
|
25
|
+
".": {
|
|
26
|
+
"types": "./dist/index.d.ts",
|
|
27
|
+
"import": "./dist/index.js"
|
|
28
|
+
},
|
|
29
|
+
"./settings": {
|
|
30
|
+
"types": "./dist/settings.d.ts",
|
|
31
|
+
"import": "./dist/settings.js"
|
|
32
|
+
},
|
|
33
|
+
"./testkit": {
|
|
34
|
+
"types": "./dist/testkit.d.ts",
|
|
35
|
+
"import": "./dist/testkit.js"
|
|
36
|
+
},
|
|
37
|
+
"./package.json": "./package.json"
|
|
38
|
+
},
|
|
39
|
+
"files": [
|
|
40
|
+
"dist",
|
|
41
|
+
"README.md",
|
|
42
|
+
"LICENSE"
|
|
43
|
+
],
|
|
44
|
+
"sideEffects": false,
|
|
45
|
+
"engines": {
|
|
46
|
+
"node": ">=22"
|
|
47
|
+
},
|
|
48
|
+
"devDependencies": {
|
|
49
|
+
"@types/node": "^22.10.0",
|
|
50
|
+
"@types/pg": "^8.23.1",
|
|
51
|
+
"eslint": "^9.39.0",
|
|
52
|
+
"pg": "^8.23.1",
|
|
53
|
+
"tsup": "^8.5.0",
|
|
54
|
+
"typescript": "^5.9.3",
|
|
55
|
+
"vitest": "^4.1.11",
|
|
56
|
+
"zod": "^4.6.7",
|
|
57
|
+
"@krizaka/config": "^0.8.1"
|
|
58
|
+
},
|
|
59
|
+
"dependencies": {
|
|
60
|
+
"@krizaka/db": "^0.2.0",
|
|
61
|
+
"@krizaka/settings": "^0.5.0",
|
|
62
|
+
"@krizaka/time": "^0.1.0"
|
|
63
|
+
},
|
|
64
|
+
"peerDependencies": {
|
|
65
|
+
"vitest": ">=4",
|
|
66
|
+
"zod": ">=3.23"
|
|
67
|
+
},
|
|
68
|
+
"peerDependenciesMeta": {
|
|
69
|
+
"vitest": {
|
|
70
|
+
"optional": true
|
|
71
|
+
},
|
|
72
|
+
"zod": {
|
|
73
|
+
"optional": true
|
|
74
|
+
}
|
|
75
|
+
},
|
|
76
|
+
"scripts": {
|
|
77
|
+
"build": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\" && tsup",
|
|
78
|
+
"lint": "eslint . --max-warnings 0 && tsc --noEmit",
|
|
79
|
+
"typecheck": "tsc --noEmit",
|
|
80
|
+
"test": "vitest run",
|
|
81
|
+
"check": "pnpm run lint && pnpm run test && pnpm run build"
|
|
82
|
+
}
|
|
6
83
|
}
|