@yaebal/ratelimiter 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +13 -0
- package/lib/index.d.ts +28 -0
- package/lib/index.d.ts.map +1 -0
- package/lib/index.js +33 -0
- package/lib/index.js.map +1 -0
- package/lib/index.test.d.ts +2 -0
- package/lib/index.test.d.ts.map +1 -0
- package/lib/index.test.js +52 -0
- package/lib/index.test.js.map +1 -0
- package/package.json +48 -0
- package/src/index.test.ts +67 -0
- package/src/index.ts +65 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 neverlane
|
|
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
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
# @yaebal/ratelimiter
|
|
2
|
+
|
|
3
|
+
max updates allowed per window. defaults to 5.
|
|
4
|
+
|
|
5
|
+
## install
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
pnpm add @yaebal/ratelimiter
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
---
|
|
12
|
+
|
|
13
|
+
part of [**yaebal**](https://github.com/neverlane/yaebal) — a type-safe, runtime-agnostic Telegram Bot API framework. MIT.
|
package/lib/index.d.ts
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import type { Context, Plugin } from "@yaebal/core";
|
|
2
|
+
interface Window {
|
|
3
|
+
count: number;
|
|
4
|
+
resetAt: number;
|
|
5
|
+
}
|
|
6
|
+
export interface RateLimiterOptions {
|
|
7
|
+
/** max updates allowed per window. defaults to 5. */
|
|
8
|
+
limit?: number;
|
|
9
|
+
/** window length in ms. defaults to 1000. */
|
|
10
|
+
windowMs?: number;
|
|
11
|
+
/** called when an update is dropped for exceeding the limit. */
|
|
12
|
+
onLimit?: (ctx: Context) => unknown;
|
|
13
|
+
/** limit key for an update. defaults to per-user (`ctx.from.id`). */
|
|
14
|
+
getKey?: (ctx: Context) => string | undefined;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* decide whether an update is within the limit, returning the updated window.
|
|
18
|
+
* mutates `rec` in place when reusing the window, or allocates a fresh one on
|
|
19
|
+
* reset. exported for testing.
|
|
20
|
+
*/
|
|
21
|
+
export declare function decide(rec: Window | undefined, now: number, limit: number, windowMs: number): {
|
|
22
|
+
allowed: boolean;
|
|
23
|
+
window: Window;
|
|
24
|
+
};
|
|
25
|
+
/** drop updates from a key (defaults to per-user) that exceed `limit` per `windowMs`. */
|
|
26
|
+
export declare function ratelimiter(options?: RateLimiterOptions): Plugin<Context, Record<never, never>>;
|
|
27
|
+
export {};
|
|
28
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AAEpD,UAAU,MAAM;IACf,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,kBAAkB;IAClC,qDAAqD;IACrD,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,6CAA6C;IAC7C,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,gEAAgE;IAChE,OAAO,CAAC,EAAE,CAAC,GAAG,EAAE,OAAO,KAAK,OAAO,CAAC;IACpC,qEAAqE;IACrE,MAAM,CAAC,EAAE,CAAC,GAAG,EAAE,OAAO,KAAK,MAAM,GAAG,SAAS,CAAC;CAC9C;AAED;;;;GAIG;AACH,wBAAgB,MAAM,CACrB,GAAG,EAAE,MAAM,GAAG,SAAS,EACvB,GAAG,EAAE,MAAM,EACX,KAAK,EAAE,MAAM,EACb,QAAQ,EAAE,MAAM,GACd;IAAE,OAAO,EAAE,OAAO,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAKtC;AAED,yFAAyF;AACzF,wBAAgB,WAAW,CAC1B,OAAO,GAAE,kBAAuB,GAC9B,MAAM,CAAC,OAAO,EAAE,MAAM,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC,CA0BvC"}
|
package/lib/index.js
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* decide whether an update is within the limit, returning the updated window.
|
|
3
|
+
* mutates `rec` in place when reusing the window, or allocates a fresh one on
|
|
4
|
+
* reset. exported for testing.
|
|
5
|
+
*/
|
|
6
|
+
export function decide(rec, now, limit, windowMs) {
|
|
7
|
+
const window = !rec || now >= rec.resetAt ? { count: 0, resetAt: now + windowMs } : rec;
|
|
8
|
+
window.count += 1;
|
|
9
|
+
return { allowed: window.count <= limit, window };
|
|
10
|
+
}
|
|
11
|
+
/** drop updates from a key (defaults to per-user) that exceed `limit` per `windowMs`. */
|
|
12
|
+
export function ratelimiter(options = {}) {
|
|
13
|
+
const limit = options.limit ?? 5;
|
|
14
|
+
const windowMs = options.windowMs ?? 1000;
|
|
15
|
+
const getKey = options.getKey ?? ((ctx) => ctx.from?.id?.toString());
|
|
16
|
+
// ponytail: one entry per distinct key, never evicted — bounded by the number
|
|
17
|
+
// of users the bot ever sees. fine for anti-spam scale; add a sweep if it grows.
|
|
18
|
+
const windows = new Map();
|
|
19
|
+
const plugin = (composer) => composer.use(async (ctx, next) => {
|
|
20
|
+
const key = getKey(ctx);
|
|
21
|
+
if (key === undefined)
|
|
22
|
+
return next();
|
|
23
|
+
const { allowed, window } = decide(windows.get(key), Date.now(), limit, windowMs);
|
|
24
|
+
windows.set(key, window);
|
|
25
|
+
if (!allowed) {
|
|
26
|
+
await options.onLimit?.(ctx);
|
|
27
|
+
return; // dropped
|
|
28
|
+
}
|
|
29
|
+
await next();
|
|
30
|
+
});
|
|
31
|
+
return plugin;
|
|
32
|
+
}
|
|
33
|
+
//# sourceMappingURL=index.js.map
|
package/lib/index.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAkBA;;;;GAIG;AACH,MAAM,UAAU,MAAM,CACrB,GAAuB,EACvB,GAAW,EACX,KAAa,EACb,QAAgB;IAEhB,MAAM,MAAM,GAAG,CAAC,GAAG,IAAI,GAAG,IAAI,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,EAAE,OAAO,EAAE,GAAG,GAAG,QAAQ,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC;IACxF,MAAM,CAAC,KAAK,IAAI,CAAC,CAAC;IAElB,OAAO,EAAE,OAAO,EAAE,MAA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["../src/index.test.ts"],"names":[],"mappings":""}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import test from "node:test";
|
|
3
|
+
import { Composer, Context } from "@yaebal/core";
|
|
4
|
+
import { decide, ratelimiter } from "./index.js";
|
|
5
|
+
const noop = async () => { };
|
|
6
|
+
const entry = (c) => c.toMiddleware();
|
|
7
|
+
const api = {};
|
|
8
|
+
const ctxFrom = (userId) => new Context({
|
|
9
|
+
api,
|
|
10
|
+
update: {
|
|
11
|
+
update_id: 1,
|
|
12
|
+
message: {
|
|
13
|
+
message_id: 1,
|
|
14
|
+
date: 0,
|
|
15
|
+
chat: { id: userId, type: "private" },
|
|
16
|
+
from: { id: userId, is_bot: false, first_name: "u" },
|
|
17
|
+
text: "spam",
|
|
18
|
+
},
|
|
19
|
+
},
|
|
20
|
+
updateType: "message",
|
|
21
|
+
});
|
|
22
|
+
test("decide allows up to the limit, then blocks within the window", () => {
|
|
23
|
+
const a = decide(undefined, 1000, 2, 1000);
|
|
24
|
+
assert.deepEqual(a, { allowed: true, window: { count: 1, resetAt: 2000 } });
|
|
25
|
+
const b = decide(a.window, 1000, 2, 1000);
|
|
26
|
+
assert.equal(b.allowed, true); // count 2
|
|
27
|
+
const c = decide(b.window, 1000, 2, 1000);
|
|
28
|
+
assert.equal(c.allowed, false); // count 3 > 2
|
|
29
|
+
});
|
|
30
|
+
test("decide resets after the window elapses", () => {
|
|
31
|
+
const over = { count: 9, resetAt: 1500 };
|
|
32
|
+
const r = decide(over, 2000, 2, 1000); // now >= resetAt
|
|
33
|
+
assert.deepEqual(r, { allowed: true, window: { count: 1, resetAt: 3000 } });
|
|
34
|
+
});
|
|
35
|
+
test("ratelimiter drops updates over the limit and fires onLimit", async () => {
|
|
36
|
+
let handled = 0;
|
|
37
|
+
let limited = 0;
|
|
38
|
+
const mw = entry(new Composer()
|
|
39
|
+
.install(ratelimiter({ limit: 2, windowMs: 10_000, onLimit: () => limited++ }))
|
|
40
|
+
.use((_ctx, next) => {
|
|
41
|
+
handled++;
|
|
42
|
+
return next();
|
|
43
|
+
}));
|
|
44
|
+
await mw(ctxFrom(1), noop);
|
|
45
|
+
await mw(ctxFrom(1), noop);
|
|
46
|
+
await mw(ctxFrom(1), noop); // third → dropped
|
|
47
|
+
assert.equal(handled, 2);
|
|
48
|
+
assert.equal(limited, 1);
|
|
49
|
+
await mw(ctxFrom(2), noop); // different user → allowed
|
|
50
|
+
assert.equal(handled, 3);
|
|
51
|
+
});
|
|
52
|
+
//# sourceMappingURL=index.test.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.test.js","sourceRoot":"","sources":["../src/index.test.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,oBAAoB,CAAC;AACxC,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAmB,MAAM,cAAc,CAAC;AAClE,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAEjD,MAAM,IAAI,GAAG,KAAK,IAAI,EAAE,GAAE,CAAC,CAAC;AAC5B,MAAM,KAAK,GAAG,CAAoB,CAAc,EAAE,EAAE,CACnD,CAAC,CAAC,YAAY,EAAoC,CAAC;AAEpD,MAAM,GAAG,GAAG,EAAW,CAAC;AACxB,MAAM,OAAO,GAAG,CAAC,MAAc,EAAE,EAAE,CAClC,IAAI,OAAO,CAAC;IACX,GAAG;IACH,MAAM,EAAE;QACP,SAAS,EAAE,CAAC;QACZ,OAAO,EAAE;YACR,UAAU,EAAE,CAAC;YACb,IAAI,EAAE,CAAC;YACP,IAAI,EAAE,EAAE,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,SAAS,EAAE;YACrC,IAAI,EAAE,EAAE,EAAE,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,UAAU,EAAE,GAAG,EAAE;YACpD,IAAI,EAAE,MAAM;SACZ;KACQ;IACV,U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C;IAChB,IAAI,OAAO,GAAG,CAAC,CAAC;IAEhB,MAAM,EAAE,GAAG,KAAK,CACf,IAAI,QAAQ,EAAW;SACrB,OAAO,CAAC,WAAW,CAAC,EAAE,KAAK,EAAE,CAAC,EAAE,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,GAAG,EAAE,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC;SAC9E,GAAG,CAAC,CAAC,IAAI,EAAE,IAAI,EAAE,EAAE;QACnB,OAAO,EAAE,CAAC;QACV,OAAO,IAAI,EAAE,CAAC;IACf,CAAC,CAAC,CACH,CAAC;IAEF,MAAM,EAAE,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC;IAC3B,MAAM,EAAE,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC;IAC3B,MAAM,EAAE,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC,CAAC,kBAAkB;IAE9C,MAAM,CAAC,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC;IACzB,MAAM,CAAC,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC;IAEzB,MAAM,EAAE,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC,CAAC,2BAA2B;IACvD,MAAM,CAAC,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC;AAC1B,CAAC,CAAC,CAAC"}
|
package/package.json
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@yaebal/ratelimiter",
|
|
3
|
+
"version": "0.0.1",
|
|
4
|
+
"description": "yaebal ratelimiter plugin — drop updates from users who spam the bot.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./lib/index.js",
|
|
7
|
+
"types": "./lib/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./lib/index.d.ts",
|
|
11
|
+
"import": "./lib/index.js"
|
|
12
|
+
}
|
|
13
|
+
},
|
|
14
|
+
"files": [
|
|
15
|
+
"lib",
|
|
16
|
+
"src"
|
|
17
|
+
],
|
|
18
|
+
"dependencies": {
|
|
19
|
+
"@yaebal/core": "0.0.1"
|
|
20
|
+
},
|
|
21
|
+
"devDependencies": {
|
|
22
|
+
"@types/node": "latest"
|
|
23
|
+
},
|
|
24
|
+
"engines": {
|
|
25
|
+
"node": ">=20"
|
|
26
|
+
},
|
|
27
|
+
"keywords": [
|
|
28
|
+
"telegram",
|
|
29
|
+
"telegram-bot",
|
|
30
|
+
"yaebal",
|
|
31
|
+
"rate-limit",
|
|
32
|
+
"anti-spam"
|
|
33
|
+
],
|
|
34
|
+
"license": "MIT",
|
|
35
|
+
"repository": {
|
|
36
|
+
"type": "git",
|
|
37
|
+
"url": "https://github.com/neverlane/yaebal",
|
|
38
|
+
"directory": "packages/ratelimiter"
|
|
39
|
+
},
|
|
40
|
+
"publishConfig": {
|
|
41
|
+
"access": "public"
|
|
42
|
+
},
|
|
43
|
+
"scripts": {
|
|
44
|
+
"build": "tsc -p tsconfig.json",
|
|
45
|
+
"typecheck": "tsc -p tsconfig.json --noEmit",
|
|
46
|
+
"test": "node --test lib"
|
|
47
|
+
}
|
|
48
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import test from "node:test";
|
|
3
|
+
import { Composer, Context, type Middleware } from "@yaebal/core";
|
|
4
|
+
import { decide, ratelimiter } from "./index.js";
|
|
5
|
+
|
|
6
|
+
const noop = async () => {};
|
|
7
|
+
const entry = <C extends Context>(c: Composer<C>) =>
|
|
8
|
+
c.toMiddleware() as unknown as Middleware<Context>;
|
|
9
|
+
|
|
10
|
+
const api = {} as never;
|
|
11
|
+
const ctxFrom = (userId: number) =>
|
|
12
|
+
new Context({
|
|
13
|
+
api,
|
|
14
|
+
update: {
|
|
15
|
+
update_id: 1,
|
|
16
|
+
message: {
|
|
17
|
+
message_id: 1,
|
|
18
|
+
date: 0,
|
|
19
|
+
chat: { id: userId, type: "private" },
|
|
20
|
+
from: { id: userId, is_bot: false, first_name: "u" },
|
|
21
|
+
text: "spam",
|
|
22
|
+
},
|
|
23
|
+
} as never,
|
|
24
|
+
updateType: "message",
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
test("decide allows up to the limit, then blocks within the window", () => {
|
|
28
|
+
const a = decide(undefined, 1000, 2, 1000);
|
|
29
|
+
assert.deepEqual(a, { allowed: true, window: { count: 1, resetAt: 2000 } });
|
|
30
|
+
|
|
31
|
+
const b = decide(a.window, 1000, 2, 1000);
|
|
32
|
+
assert.equal(b.allowed, true); // count 2
|
|
33
|
+
|
|
34
|
+
const c = decide(b.window, 1000, 2, 1000);
|
|
35
|
+
assert.equal(c.allowed, false); // count 3 > 2
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
test("decide resets after the window elapses", () => {
|
|
39
|
+
const over = { count: 9, resetAt: 1500 };
|
|
40
|
+
const r = decide(over, 2000, 2, 1000); // now >= resetAt
|
|
41
|
+
|
|
42
|
+
assert.deepEqual(r, { allowed: true, window: { count: 1, resetAt: 3000 } });
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
test("ratelimiter drops updates over the limit and fires onLimit", async () => {
|
|
46
|
+
let handled = 0;
|
|
47
|
+
let limited = 0;
|
|
48
|
+
|
|
49
|
+
const mw = entry(
|
|
50
|
+
new Composer<Context>()
|
|
51
|
+
.install(ratelimiter({ limit: 2, windowMs: 10_000, onLimit: () => limited++ }))
|
|
52
|
+
.use((_ctx, next) => {
|
|
53
|
+
handled++;
|
|
54
|
+
return next();
|
|
55
|
+
}),
|
|
56
|
+
);
|
|
57
|
+
|
|
58
|
+
await mw(ctxFrom(1), noop);
|
|
59
|
+
await mw(ctxFrom(1), noop);
|
|
60
|
+
await mw(ctxFrom(1), noop); // third → dropped
|
|
61
|
+
|
|
62
|
+
assert.equal(handled, 2);
|
|
63
|
+
assert.equal(limited, 1);
|
|
64
|
+
|
|
65
|
+
await mw(ctxFrom(2), noop); // different user → allowed
|
|
66
|
+
assert.equal(handled, 3);
|
|
67
|
+
});
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import type { Context, Plugin } from "@yaebal/core";
|
|
2
|
+
|
|
3
|
+
interface Window {
|
|
4
|
+
count: number;
|
|
5
|
+
resetAt: number;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export interface RateLimiterOptions {
|
|
9
|
+
/** max updates allowed per window. defaults to 5. */
|
|
10
|
+
limit?: number;
|
|
11
|
+
/** window length in ms. defaults to 1000. */
|
|
12
|
+
windowMs?: number;
|
|
13
|
+
/** called when an update is dropped for exceeding the limit. */
|
|
14
|
+
onLimit?: (ctx: Context) => unknown;
|
|
15
|
+
/** limit key for an update. defaults to per-user (`ctx.from.id`). */
|
|
16
|
+
getKey?: (ctx: Context) => string | undefined;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* decide whether an update is within the limit, returning the updated window.
|
|
21
|
+
* mutates `rec` in place when reusing the window, or allocates a fresh one on
|
|
22
|
+
* reset. exported for testing.
|
|
23
|
+
*/
|
|
24
|
+
export function decide(
|
|
25
|
+
rec: Window | undefined,
|
|
26
|
+
now: number,
|
|
27
|
+
limit: number,
|
|
28
|
+
windowMs: number,
|
|
29
|
+
): { allowed: boolean; window: Window } {
|
|
30
|
+
const window = !rec || now >= rec.resetAt ? { count: 0, resetAt: now + windowMs } : rec;
|
|
31
|
+
window.count += 1;
|
|
32
|
+
|
|
33
|
+
return { allowed: window.count <= limit, window };
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** drop updates from a key (defaults to per-user) that exceed `limit` per `windowMs`. */
|
|
37
|
+
export function ratelimiter(
|
|
38
|
+
options: RateLimiterOptions = {},
|
|
39
|
+
): Plugin<Context, Record<never, never>> {
|
|
40
|
+
const limit = options.limit ?? 5;
|
|
41
|
+
const windowMs = options.windowMs ?? 1000;
|
|
42
|
+
const getKey = options.getKey ?? ((ctx: Context) => ctx.from?.id?.toString());
|
|
43
|
+
|
|
44
|
+
// ponytail: one entry per distinct key, never evicted — bounded by the number
|
|
45
|
+
// of users the bot ever sees. fine for anti-spam scale; add a sweep if it grows.
|
|
46
|
+
const windows = new Map<string, Window>();
|
|
47
|
+
|
|
48
|
+
const plugin: Plugin<Context, Record<never, never>> = (composer) =>
|
|
49
|
+
composer.use(async (ctx, next) => {
|
|
50
|
+
const key = getKey(ctx);
|
|
51
|
+
if (key === undefined) return next();
|
|
52
|
+
|
|
53
|
+
const { allowed, window } = decide(windows.get(key), Date.now(), limit, windowMs);
|
|
54
|
+
windows.set(key, window);
|
|
55
|
+
|
|
56
|
+
if (!allowed) {
|
|
57
|
+
await options.onLimit?.(ctx);
|
|
58
|
+
return; // dropped
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
await next();
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
return plugin;
|
|
65
|
+
}
|