@application-kit/rate-limit 0.0.0-stage → 0.1.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.
Files changed (53) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/LICENSE +21 -0
  3. package/README.md +70 -2
  4. package/dist/cjs/attempt-counter.interface.d.ts +10 -0
  5. package/dist/cjs/attempt-counter.interface.js +2 -0
  6. package/dist/cjs/constants.d.ts +3 -0
  7. package/dist/cjs/constants.js +6 -0
  8. package/dist/cjs/in-memory-attempt-counter.d.ts +9 -0
  9. package/dist/cjs/in-memory-attempt-counter.js +50 -0
  10. package/dist/cjs/index.d.ts +9 -0
  11. package/dist/cjs/index.js +25 -0
  12. package/dist/cjs/package.json +3 -0
  13. package/dist/cjs/rate-limit-logger.d.ts +5 -0
  14. package/dist/cjs/rate-limit-logger.interface.d.ts +3 -0
  15. package/dist/cjs/rate-limit-logger.interface.js +2 -0
  16. package/dist/cjs/rate-limit-logger.js +59 -0
  17. package/dist/cjs/rate-limit.module.d.ts +13 -0
  18. package/dist/cjs/rate-limit.module.js +34 -0
  19. package/dist/cjs/testing/attempt-counter.fake.d.ts +18 -0
  20. package/dist/cjs/testing/attempt-counter.fake.js +34 -0
  21. package/dist/cjs/testing/index.d.ts +1 -0
  22. package/dist/cjs/testing/index.js +17 -0
  23. package/dist/cjs/throttle-budget.d.ts +30 -0
  24. package/dist/cjs/throttle-budget.js +47 -0
  25. package/dist/cjs/throttle-gate.d.ts +22 -0
  26. package/dist/cjs/throttle-gate.js +39 -0
  27. package/dist/cjs/valkey-attempt-counter.d.ts +16 -0
  28. package/dist/cjs/valkey-attempt-counter.js +50 -0
  29. package/dist/esm/attempt-counter.interface.d.ts +10 -0
  30. package/dist/esm/attempt-counter.interface.js +1 -0
  31. package/dist/esm/constants.d.ts +3 -0
  32. package/dist/esm/constants.js +3 -0
  33. package/dist/esm/in-memory-attempt-counter.d.ts +9 -0
  34. package/dist/esm/in-memory-attempt-counter.js +47 -0
  35. package/dist/esm/index.d.ts +9 -0
  36. package/dist/esm/index.js +9 -0
  37. package/dist/esm/rate-limit-logger.d.ts +5 -0
  38. package/dist/esm/rate-limit-logger.interface.d.ts +3 -0
  39. package/dist/esm/rate-limit-logger.interface.js +1 -0
  40. package/dist/esm/rate-limit-logger.js +23 -0
  41. package/dist/esm/rate-limit.module.d.ts +13 -0
  42. package/dist/esm/rate-limit.module.js +31 -0
  43. package/dist/esm/testing/attempt-counter.fake.d.ts +18 -0
  44. package/dist/esm/testing/attempt-counter.fake.js +30 -0
  45. package/dist/esm/testing/index.d.ts +1 -0
  46. package/dist/esm/testing/index.js +1 -0
  47. package/dist/esm/throttle-budget.d.ts +30 -0
  48. package/dist/esm/throttle-budget.js +44 -0
  49. package/dist/esm/throttle-gate.d.ts +22 -0
  50. package/dist/esm/throttle-gate.js +36 -0
  51. package/dist/esm/valkey-attempt-counter.d.ts +16 -0
  52. package/dist/esm/valkey-attempt-counter.js +46 -0
  53. package/package.json +85 -3
package/CHANGELOG.md ADDED
@@ -0,0 +1,11 @@
1
+ # @application-kit/rate-limit
2
+
3
+ ## 0.1.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 2a0e18c: Первый выпуск: порт счётчика попыток с окном `AttemptCounterInterface`, адаптеры `InMemoryAttemptCounter` и
8
+ `ValkeyAttemptCounter` (атомарный Lua `INCR + PEXPIRE`, клиент узкой формы `ValkeyCommandsInterface` приносит
9
+ приложение), бюджет `ThrottleBudget` (`spend` — трата проверкой, `readFailures` — чтение без траты), `ThrottleGate`
10
+ с заголовком `Retry-After` и исполнителем решения оси, `RateLimitModule.forRootAsync`; фейк порта `FakeAttemptCounter`
11
+ (вход `/testing`).
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 application-kit
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,71 @@
1
- # Temporary Holding Version
1
+ # @application-kit/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
+ Частотная защита для NestJS: счётчик попыток с окном, бюджет попыток и gate маршрута с заголовком `Retry-After`.
4
+ Доменных понятий в пакете нет: ключи, пороги, оси и ошибки отказа объявляет приложение.
5
+
6
+ ## Установка
7
+
8
+ ```sh
9
+ yarn add @application-kit/rate-limit
10
+ ```
11
+
12
+ Peer-зависимости: `@nestjs/common`, `nestjs-pino`, `oxide.ts`. Клиент Valkey пакет не импортирует — его собирает
13
+ приложение из своего конфига и отдаёт готовым экземпляром.
14
+
15
+ ## Подключение
16
+
17
+ ```ts
18
+ import { InMemoryAttemptCounter, RateLimitModule, ValkeyAttemptCounter } from '@application-kit/rate-limit'
19
+
20
+ RateLimitModule.forRootAsync({
21
+ // Память или Valkey выбирает приложение: адрес хранилища знает его конфиг.
22
+ counter: {
23
+ inject: [ValkeyConfig],
24
+ useFactory: (config: ValkeyConfig) => (config.isEnabled
25
+ ? new ValkeyAttemptCounter(createValkeyClient(config))
26
+ : new InMemoryAttemptCounter()),
27
+ },
28
+ // Исполнитель решения оси для `ThrottleGate`: обычно — шина команд приложения.
29
+ decide: {
30
+ inject: [CommandBus],
31
+ useFactory: (commandBus: CommandBus) => async (command: object) => commandBus.execute(command),
32
+ },
33
+ imports: [ValkeyConfigModule],
34
+ })
35
+ ```
36
+
37
+ Модуль экспортирует токен счётчика `RATE_LIMIT_COUNTER`, `ThrottleBudget` и `ThrottleGate`. Логгер отказов
38
+ (`RATE_LIMIT_LOGGER`, `RateLimitLogger`) модуль связывает сам — нужен глобальный `LoggerModule` из `nestjs-pino`.
39
+
40
+ ## Счётчик
41
+
42
+ - `increment(key, windowSeconds)` — фиксирует попытку. Окно открывает первая попытка, попытки внутри окна его не
43
+ продлевают: иначе блокировку нельзя переждать.
44
+ - `read(key)` — состояние окна или `None`.
45
+ - `reset(key)` — сброс окна, например после успешного входа.
46
+
47
+ `ValkeyAttemptCounter` меняет счёт и срок одним Lua-скриптом: попытки разных реплик складываются, а рестарт процесса
48
+ блокировку не снимает. `InMemoryAttemptCounter` — для спек и запуска без хранилища: порог в нём действует на процесс.
49
+
50
+ ## Бюджет
51
+
52
+ - `spend({ key, limit, refusal })` — попытка стоит окна независимо от исхода (ручки с одинаковым ответом всегда).
53
+ - `readFailures({ key, maxFailures, refusal })` — бюджет только читается; тратит его зарегистрированный исход попытки,
54
+ то есть `increment` у потребителя.
55
+
56
+ Отказ пишется в лог одной записью `{ retryAfterSeconds, securityEvent }` с сообщением `refusal.message` — без ключа
57
+ и идентификаторов.
58
+
59
+ ## Gate
60
+
61
+ `ThrottleGate.pass(executionContext, axis)` читает контекст оси, спрашивает решение у исполнителя `decide`, пропускает
62
+ запрос или пишет `retry-after` в ответ и бросает ошибку оси. Ось (`ThrottleAxisInterface`) — данные приложения:
63
+ `readContext`, `createCommand`, `isAllowed`, `createError`.
64
+
65
+ ## Спеки потребителя
66
+
67
+ ```ts
68
+ import { FakeAttemptCounter } from '@application-kit/rate-limit/testing'
69
+ ```
70
+
71
+ Фейк копит счёт и вызовы (`increments`, `resets`, `seed`, `countOf`) и отдаёт фиксированный остаток окна.
@@ -0,0 +1,10 @@
1
+ import type { Option } from 'oxide.ts';
2
+ export interface AttemptCounterInterface {
3
+ increment(key: string, windowSeconds: number): Promise<AttemptWindowInterface>;
4
+ read(key: string): Promise<Option<AttemptWindowInterface>>;
5
+ reset(key: string): Promise<void>;
6
+ }
7
+ export interface AttemptWindowInterface {
8
+ count: number;
9
+ retryAfterSeconds: number;
10
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,3 @@
1
+ export declare const RATE_LIMIT_COUNTER: unique symbol;
2
+ export declare const RATE_LIMIT_LOGGER: unique symbol;
3
+ export declare const RATE_LIMIT_DECIDE: unique symbol;
@@ -0,0 +1,6 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RATE_LIMIT_DECIDE = exports.RATE_LIMIT_LOGGER = exports.RATE_LIMIT_COUNTER = void 0;
4
+ exports.RATE_LIMIT_COUNTER = Symbol('RATE_LIMIT_COUNTER');
5
+ exports.RATE_LIMIT_LOGGER = Symbol('RATE_LIMIT_LOGGER');
6
+ exports.RATE_LIMIT_DECIDE = Symbol('RATE_LIMIT_DECIDE');
@@ -0,0 +1,9 @@
1
+ import { Option } from 'oxide.ts';
2
+ import type { AttemptCounterInterface, AttemptWindowInterface } from './attempt-counter.interface.js';
3
+ export declare class InMemoryAttemptCounter implements AttemptCounterInterface {
4
+ private readonly windows;
5
+ increment(key: string, windowSeconds: number): Promise<AttemptWindowInterface>;
6
+ read(key: string): Promise<Option<AttemptWindowInterface>>;
7
+ reset(key: string): Promise<void>;
8
+ private prune;
9
+ }
@@ -0,0 +1,50 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.InMemoryAttemptCounter = void 0;
10
+ const common_1 = require("@nestjs/common");
11
+ const oxide_ts_1 = require("oxide.ts");
12
+ const MILLISECONDS_IN_SECOND = 1000;
13
+ const toWindow = (record, nowMs) => ({
14
+ count: record.count,
15
+ retryAfterSeconds: Math.ceil((record.expiresAtMs - nowMs) / MILLISECONDS_IN_SECOND),
16
+ });
17
+ let InMemoryAttemptCounter = class InMemoryAttemptCounter {
18
+ windows = new Map();
19
+ async increment(key, windowSeconds) {
20
+ await Promise.resolve();
21
+ const nowMs = Date.now();
22
+ this.prune(nowMs);
23
+ const current = this.windows.get(key);
24
+ const record = current ?? { count: 0, expiresAtMs: nowMs + (windowSeconds * MILLISECONDS_IN_SECOND) };
25
+ record.count += 1;
26
+ this.windows.set(key, record);
27
+ return toWindow(record, nowMs);
28
+ }
29
+ async read(key) {
30
+ await Promise.resolve();
31
+ const nowMs = Date.now();
32
+ const record = this.windows.get(key);
33
+ return record === undefined || record.expiresAtMs <= nowMs ? oxide_ts_1.None : (0, oxide_ts_1.Some)(toWindow(record, nowMs));
34
+ }
35
+ async reset(key) {
36
+ await Promise.resolve();
37
+ this.windows.delete(key);
38
+ }
39
+ prune(nowMs) {
40
+ for (const [key, record] of this.windows) {
41
+ if (record.expiresAtMs <= nowMs) {
42
+ this.windows.delete(key);
43
+ }
44
+ }
45
+ }
46
+ };
47
+ exports.InMemoryAttemptCounter = InMemoryAttemptCounter;
48
+ exports.InMemoryAttemptCounter = InMemoryAttemptCounter = __decorate([
49
+ (0, common_1.Injectable)()
50
+ ], InMemoryAttemptCounter);
@@ -0,0 +1,9 @@
1
+ export * from './attempt-counter.interface.js';
2
+ export * from './constants.js';
3
+ export * from './in-memory-attempt-counter.js';
4
+ export * from './rate-limit-logger.js';
5
+ export * from './rate-limit-logger.interface.js';
6
+ export * from './rate-limit.module.js';
7
+ export * from './throttle-budget.js';
8
+ export * from './throttle-gate.js';
9
+ export * from './valkey-attempt-counter.js';
@@ -0,0 +1,25 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./attempt-counter.interface.js"), exports);
18
+ __exportStar(require("./constants.js"), exports);
19
+ __exportStar(require("./in-memory-attempt-counter.js"), exports);
20
+ __exportStar(require("./rate-limit-logger.js"), exports);
21
+ __exportStar(require("./rate-limit-logger.interface.js"), exports);
22
+ __exportStar(require("./rate-limit.module.js"), exports);
23
+ __exportStar(require("./throttle-budget.js"), exports);
24
+ __exportStar(require("./throttle-gate.js"), exports);
25
+ __exportStar(require("./valkey-attempt-counter.js"), exports);
@@ -0,0 +1,3 @@
1
+ {
2
+ "type": "commonjs"
3
+ }
@@ -0,0 +1,5 @@
1
+ import * as nestjsPino from 'nestjs-pino';
2
+ import type { RateLimitLoggerInterface } from './rate-limit-logger.interface.js';
3
+ export declare class RateLimitLogger extends nestjsPino.PinoLogger implements RateLimitLoggerInterface {
4
+ constructor(options: nestjsPino.Params);
5
+ }
@@ -0,0 +1,3 @@
1
+ export interface RateLimitLoggerInterface {
2
+ warn(context: unknown, message: string): void;
3
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,59 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
19
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
20
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
21
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
22
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
23
+ };
24
+ var __importStar = (this && this.__importStar) || (function () {
25
+ var ownKeys = function(o) {
26
+ ownKeys = Object.getOwnPropertyNames || function (o) {
27
+ var ar = [];
28
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
29
+ return ar;
30
+ };
31
+ return ownKeys(o);
32
+ };
33
+ return function (mod) {
34
+ if (mod && mod.__esModule) return mod;
35
+ var result = {};
36
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
37
+ __setModuleDefault(result, mod);
38
+ return result;
39
+ };
40
+ })();
41
+ var __metadata = (this && this.__metadata) || function (k, v) {
42
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
43
+ };
44
+ var RateLimitLogger_1;
45
+ Object.defineProperty(exports, "__esModule", { value: true });
46
+ exports.RateLimitLogger = void 0;
47
+ const common_1 = require("@nestjs/common");
48
+ const nestjsPino = __importStar(require("nestjs-pino"));
49
+ let RateLimitLogger = RateLimitLogger_1 = class RateLimitLogger extends nestjsPino.PinoLogger {
50
+ constructor(options) {
51
+ super(options);
52
+ this.setContext(RateLimitLogger_1.name);
53
+ }
54
+ };
55
+ exports.RateLimitLogger = RateLimitLogger;
56
+ exports.RateLimitLogger = RateLimitLogger = RateLimitLogger_1 = __decorate([
57
+ (0, common_1.Injectable)(),
58
+ __metadata("design:paramtypes", [Object])
59
+ ], RateLimitLogger);
@@ -0,0 +1,13 @@
1
+ import type { DynamicModule, FactoryProvider, ModuleMetadata } from '@nestjs/common';
2
+ import type { AttemptCounterInterface } from './attempt-counter.interface.js';
3
+ import type { ThrottleDecideFunction } from './throttle-gate.js';
4
+ export interface RateLimitModuleOptionsInterface {
5
+ readonly counter: FactoryOptions<AttemptCounterInterface>;
6
+ readonly decide: FactoryOptions<ThrottleDecideFunction>;
7
+ readonly imports?: ModuleMetadata['imports'];
8
+ }
9
+ type FactoryOptions<T> = Omit<FactoryProvider<T>, 'provide'>;
10
+ export declare class RateLimitModule {
11
+ static forRootAsync(options: RateLimitModuleOptionsInterface): DynamicModule;
12
+ }
13
+ export {};
@@ -0,0 +1,34 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.RateLimitModule = void 0;
10
+ const common_1 = require("@nestjs/common");
11
+ const constants_js_1 = require("./constants.js");
12
+ const rate_limit_logger_js_1 = require("./rate-limit-logger.js");
13
+ const throttle_budget_js_1 = require("./throttle-budget.js");
14
+ const throttle_gate_js_1 = require("./throttle-gate.js");
15
+ let RateLimitModule = class RateLimitModule {
16
+ static forRootAsync(options) {
17
+ return {
18
+ exports: [constants_js_1.RATE_LIMIT_COUNTER, throttle_budget_js_1.ThrottleBudget, throttle_gate_js_1.ThrottleGate],
19
+ imports: options.imports ?? [],
20
+ module: this,
21
+ providers: [
22
+ { ...options.counter, provide: constants_js_1.RATE_LIMIT_COUNTER },
23
+ { ...options.decide, provide: constants_js_1.RATE_LIMIT_DECIDE },
24
+ { provide: constants_js_1.RATE_LIMIT_LOGGER, useClass: rate_limit_logger_js_1.RateLimitLogger },
25
+ throttle_budget_js_1.ThrottleBudget,
26
+ throttle_gate_js_1.ThrottleGate,
27
+ ],
28
+ };
29
+ }
30
+ };
31
+ exports.RateLimitModule = RateLimitModule;
32
+ exports.RateLimitModule = RateLimitModule = __decorate([
33
+ (0, common_1.Module)({})
34
+ ], RateLimitModule);
@@ -0,0 +1,18 @@
1
+ import type { Option } from 'oxide.ts';
2
+ import type { AttemptCounterInterface, AttemptWindowInterface } from '../attempt-counter.interface.js';
3
+ interface IncrementCallInterface {
4
+ key: string;
5
+ windowSeconds: number;
6
+ }
7
+ export declare class FakeAttemptCounter implements AttemptCounterInterface {
8
+ readonly increments: IncrementCallInterface[];
9
+ readonly resets: string[];
10
+ retryAfterSeconds: number;
11
+ private readonly counts;
12
+ countOf(key: string): number;
13
+ increment(key: string, windowSeconds: number): Promise<AttemptWindowInterface>;
14
+ read(key: string): Promise<Option<AttemptWindowInterface>>;
15
+ reset(key: string): Promise<void>;
16
+ seed(key: string, count: number): void;
17
+ }
18
+ export {};
@@ -0,0 +1,34 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.FakeAttemptCounter = void 0;
4
+ const oxide_ts_1 = require("oxide.ts");
5
+ class FakeAttemptCounter {
6
+ increments = [];
7
+ resets = [];
8
+ retryAfterSeconds = 42;
9
+ counts = new Map();
10
+ countOf(key) {
11
+ return this.counts.get(key) ?? 0;
12
+ }
13
+ async increment(key, windowSeconds) {
14
+ await Promise.resolve();
15
+ this.increments.push({ key, windowSeconds });
16
+ const count = (this.counts.get(key) ?? 0) + 1;
17
+ this.counts.set(key, count);
18
+ return { count, retryAfterSeconds: this.retryAfterSeconds };
19
+ }
20
+ async read(key) {
21
+ await Promise.resolve();
22
+ const count = this.counts.get(key);
23
+ return count === undefined ? oxide_ts_1.None : (0, oxide_ts_1.Some)({ count, retryAfterSeconds: this.retryAfterSeconds });
24
+ }
25
+ async reset(key) {
26
+ await Promise.resolve();
27
+ this.counts.delete(key);
28
+ this.resets.push(key);
29
+ }
30
+ seed(key, count) {
31
+ this.counts.set(key, count);
32
+ }
33
+ }
34
+ exports.FakeAttemptCounter = FakeAttemptCounter;
@@ -0,0 +1 @@
1
+ export * from './attempt-counter.fake.js';
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./attempt-counter.fake.js"), exports);
@@ -0,0 +1,30 @@
1
+ import type { AttemptCounterInterface } from './attempt-counter.interface.js';
2
+ import type { RateLimitLoggerInterface } from './rate-limit-logger.interface.js';
3
+ export interface ThrottleDecisionInterface {
4
+ allowed: boolean;
5
+ retryAfterSeconds: number;
6
+ }
7
+ export interface ThrottleRateLimitInterface {
8
+ rateLimitMaxRequests: number;
9
+ rateLimitWindowSeconds: number;
10
+ }
11
+ export interface ThrottleRefusalInterface {
12
+ message: string;
13
+ securityEvent: string;
14
+ }
15
+ export declare class ThrottleBudget {
16
+ private readonly attempts;
17
+ private readonly logger;
18
+ constructor(attempts: AttemptCounterInterface, logger: RateLimitLoggerInterface);
19
+ readFailures(options: {
20
+ key: string;
21
+ maxFailures: number;
22
+ refusal: ThrottleRefusalInterface;
23
+ }): Promise<ThrottleDecisionInterface>;
24
+ spend(options: {
25
+ key: string;
26
+ limit: ThrottleRateLimitInterface;
27
+ refusal: ThrottleRefusalInterface;
28
+ }): Promise<ThrottleDecisionInterface>;
29
+ private refuse;
30
+ }
@@ -0,0 +1,47 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
12
+ return function (target, key) { decorator(target, key, paramIndex); }
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.ThrottleBudget = void 0;
16
+ const common_1 = require("@nestjs/common");
17
+ const constants_js_1 = require("./constants.js");
18
+ const allow = () => ({ allowed: true, retryAfterSeconds: 0 });
19
+ let ThrottleBudget = class ThrottleBudget {
20
+ attempts;
21
+ logger;
22
+ constructor(attempts, logger) {
23
+ this.attempts = attempts;
24
+ this.logger = logger;
25
+ }
26
+ async readFailures(options) {
27
+ const window = await this.attempts.read(options.key);
28
+ const isBelowThreshold = window.isNone() || window.unwrap().count < options.maxFailures;
29
+ return isBelowThreshold ? allow() : this.refuse(window.unwrap().retryAfterSeconds, options.refusal);
30
+ }
31
+ async spend(options) {
32
+ const window = await this.attempts.increment(options.key, options.limit.rateLimitWindowSeconds);
33
+ const isWithinLimit = window.count <= options.limit.rateLimitMaxRequests;
34
+ return isWithinLimit ? allow() : this.refuse(window.retryAfterSeconds, options.refusal);
35
+ }
36
+ refuse(retryAfterSeconds, refusal) {
37
+ this.logger.warn({ retryAfterSeconds, securityEvent: refusal.securityEvent }, refusal.message);
38
+ return { allowed: false, retryAfterSeconds };
39
+ }
40
+ };
41
+ exports.ThrottleBudget = ThrottleBudget;
42
+ exports.ThrottleBudget = ThrottleBudget = __decorate([
43
+ (0, common_1.Injectable)(),
44
+ __param(0, (0, common_1.Inject)(constants_js_1.RATE_LIMIT_COUNTER)),
45
+ __param(1, (0, common_1.Inject)(constants_js_1.RATE_LIMIT_LOGGER)),
46
+ __metadata("design:paramtypes", [Object, Object])
47
+ ], ThrottleBudget);
@@ -0,0 +1,22 @@
1
+ import type { ExecutionContext } from '@nestjs/common';
2
+ export interface ThrottleAxisInterface<TContext extends ThrottleGuardContextInterface, TDecision extends ThrottleGateDecisionInterface> {
3
+ createCommand(context: TContext): object;
4
+ createError(): Error;
5
+ isAllowed(decision: TDecision): boolean;
6
+ readContext(context: ExecutionContext): TContext;
7
+ }
8
+ export type ThrottleDecideFunction = <TDecision>(command: object) => Promise<TDecision>;
9
+ export interface ThrottleGateDecisionInterface {
10
+ retryAfterSeconds: number;
11
+ }
12
+ export interface ThrottleGuardContextInterface {
13
+ reply: ThrottleReplyInterface;
14
+ }
15
+ export interface ThrottleReplyInterface {
16
+ header(name: string, value: string): unknown;
17
+ }
18
+ export declare class ThrottleGate {
19
+ private readonly decide;
20
+ constructor(decide: ThrottleDecideFunction);
21
+ pass<TContext extends ThrottleGuardContextInterface, TDecision extends ThrottleGateDecisionInterface>(executionContext: ExecutionContext, axis: ThrottleAxisInterface<TContext, TDecision>): Promise<boolean>;
22
+ }
@@ -0,0 +1,39 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
12
+ return function (target, key) { decorator(target, key, paramIndex); }
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.ThrottleGate = void 0;
16
+ const common_1 = require("@nestjs/common");
17
+ const constants_js_1 = require("./constants.js");
18
+ const RETRY_AFTER_HEADER = 'retry-after';
19
+ let ThrottleGate = class ThrottleGate {
20
+ decide;
21
+ constructor(decide) {
22
+ this.decide = decide;
23
+ }
24
+ async pass(executionContext, axis) {
25
+ const context = axis.readContext(executionContext);
26
+ const decision = await this.decide(axis.createCommand(context));
27
+ if (axis.isAllowed(decision)) {
28
+ return true;
29
+ }
30
+ void context.reply.header(RETRY_AFTER_HEADER, String(decision.retryAfterSeconds));
31
+ throw axis.createError();
32
+ }
33
+ };
34
+ exports.ThrottleGate = ThrottleGate;
35
+ exports.ThrottleGate = ThrottleGate = __decorate([
36
+ (0, common_1.Injectable)(),
37
+ __param(0, (0, common_1.Inject)(constants_js_1.RATE_LIMIT_DECIDE)),
38
+ __metadata("design:paramtypes", [Function])
39
+ ], ThrottleGate);
@@ -0,0 +1,16 @@
1
+ import type { OnApplicationShutdown } from '@nestjs/common';
2
+ import type { Option } from 'oxide.ts';
3
+ import type { AttemptCounterInterface, AttemptWindowInterface } from './attempt-counter.interface.js';
4
+ export interface ValkeyCommandsInterface {
5
+ del(key: string): Promise<number>;
6
+ disconnect(): void;
7
+ eval(script: string, numberOfKeys: number, ...parameters: (number | string)[]): Promise<unknown>;
8
+ }
9
+ export declare class ValkeyAttemptCounter implements AttemptCounterInterface, OnApplicationShutdown {
10
+ private readonly client;
11
+ constructor(client: ValkeyCommandsInterface);
12
+ increment(key: string, windowSeconds: number): Promise<AttemptWindowInterface>;
13
+ onApplicationShutdown(): void;
14
+ read(key: string): Promise<Option<AttemptWindowInterface>>;
15
+ reset(key: string): Promise<void>;
16
+ }
@@ -0,0 +1,50 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ValkeyAttemptCounter = void 0;
4
+ const oxide_ts_1 = require("oxide.ts");
5
+ const MILLISECONDS_IN_SECOND = 1000;
6
+ const INCREMENT_SCRIPT = `
7
+ local count = redis.call('INCR', KEYS[1])
8
+ if count == 1 or redis.call('PTTL', KEYS[1]) == -1 then
9
+ redis.call('PEXPIRE', KEYS[1], ARGV[1])
10
+ end
11
+ return {count, redis.call('PTTL', KEYS[1])}
12
+ `;
13
+ const READ_SCRIPT = `
14
+ local count = redis.call('GET', KEYS[1])
15
+ if not count then
16
+ return {0, -2}
17
+ end
18
+ return {tonumber(count), redis.call('PTTL', KEYS[1])}
19
+ `;
20
+ const isWindowReply = (reply) => Array.isArray(reply)
21
+ && reply.length === 2
22
+ && reply.every((item) => typeof item === 'number');
23
+ const toWindow = (reply) => {
24
+ if (!isWindowReply(reply)) {
25
+ throw new TypeError(`Unexpected attempt counter reply: ${JSON.stringify(reply)}`);
26
+ }
27
+ const [count, ttlMs] = reply;
28
+ return { count, retryAfterSeconds: Math.ceil(ttlMs / MILLISECONDS_IN_SECOND) };
29
+ };
30
+ class ValkeyAttemptCounter {
31
+ client;
32
+ constructor(client) {
33
+ this.client = client;
34
+ }
35
+ async increment(key, windowSeconds) {
36
+ const reply = await this.client.eval(INCREMENT_SCRIPT, 1, key, windowSeconds * MILLISECONDS_IN_SECOND);
37
+ return toWindow(reply);
38
+ }
39
+ onApplicationShutdown() {
40
+ this.client.disconnect();
41
+ }
42
+ async read(key) {
43
+ const window = toWindow(await this.client.eval(READ_SCRIPT, 1, key));
44
+ return window.retryAfterSeconds > 0 ? (0, oxide_ts_1.Some)(window) : oxide_ts_1.None;
45
+ }
46
+ async reset(key) {
47
+ await this.client.del(key);
48
+ }
49
+ }
50
+ exports.ValkeyAttemptCounter = ValkeyAttemptCounter;
@@ -0,0 +1,10 @@
1
+ import type { Option } from 'oxide.ts';
2
+ export interface AttemptCounterInterface {
3
+ increment(key: string, windowSeconds: number): Promise<AttemptWindowInterface>;
4
+ read(key: string): Promise<Option<AttemptWindowInterface>>;
5
+ reset(key: string): Promise<void>;
6
+ }
7
+ export interface AttemptWindowInterface {
8
+ count: number;
9
+ retryAfterSeconds: number;
10
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,3 @@
1
+ export declare const RATE_LIMIT_COUNTER: unique symbol;
2
+ export declare const RATE_LIMIT_LOGGER: unique symbol;
3
+ export declare const RATE_LIMIT_DECIDE: unique symbol;
@@ -0,0 +1,3 @@
1
+ export const RATE_LIMIT_COUNTER = Symbol('RATE_LIMIT_COUNTER');
2
+ export const RATE_LIMIT_LOGGER = Symbol('RATE_LIMIT_LOGGER');
3
+ export const RATE_LIMIT_DECIDE = Symbol('RATE_LIMIT_DECIDE');
@@ -0,0 +1,9 @@
1
+ import { Option } from 'oxide.ts';
2
+ import type { AttemptCounterInterface, AttemptWindowInterface } from './attempt-counter.interface.js';
3
+ export declare class InMemoryAttemptCounter implements AttemptCounterInterface {
4
+ private readonly windows;
5
+ increment(key: string, windowSeconds: number): Promise<AttemptWindowInterface>;
6
+ read(key: string): Promise<Option<AttemptWindowInterface>>;
7
+ reset(key: string): Promise<void>;
8
+ private prune;
9
+ }
@@ -0,0 +1,47 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ import { Injectable } from '@nestjs/common';
8
+ import { None, Some } from 'oxide.ts';
9
+ const MILLISECONDS_IN_SECOND = 1000;
10
+ const toWindow = (record, nowMs) => ({
11
+ count: record.count,
12
+ retryAfterSeconds: Math.ceil((record.expiresAtMs - nowMs) / MILLISECONDS_IN_SECOND),
13
+ });
14
+ let InMemoryAttemptCounter = class InMemoryAttemptCounter {
15
+ windows = new Map();
16
+ async increment(key, windowSeconds) {
17
+ await Promise.resolve();
18
+ const nowMs = Date.now();
19
+ this.prune(nowMs);
20
+ const current = this.windows.get(key);
21
+ const record = current ?? { count: 0, expiresAtMs: nowMs + (windowSeconds * MILLISECONDS_IN_SECOND) };
22
+ record.count += 1;
23
+ this.windows.set(key, record);
24
+ return toWindow(record, nowMs);
25
+ }
26
+ async read(key) {
27
+ await Promise.resolve();
28
+ const nowMs = Date.now();
29
+ const record = this.windows.get(key);
30
+ return record === undefined || record.expiresAtMs <= nowMs ? None : Some(toWindow(record, nowMs));
31
+ }
32
+ async reset(key) {
33
+ await Promise.resolve();
34
+ this.windows.delete(key);
35
+ }
36
+ prune(nowMs) {
37
+ for (const [key, record] of this.windows) {
38
+ if (record.expiresAtMs <= nowMs) {
39
+ this.windows.delete(key);
40
+ }
41
+ }
42
+ }
43
+ };
44
+ InMemoryAttemptCounter = __decorate([
45
+ Injectable()
46
+ ], InMemoryAttemptCounter);
47
+ export { InMemoryAttemptCounter };
@@ -0,0 +1,9 @@
1
+ export * from './attempt-counter.interface.js';
2
+ export * from './constants.js';
3
+ export * from './in-memory-attempt-counter.js';
4
+ export * from './rate-limit-logger.js';
5
+ export * from './rate-limit-logger.interface.js';
6
+ export * from './rate-limit.module.js';
7
+ export * from './throttle-budget.js';
8
+ export * from './throttle-gate.js';
9
+ export * from './valkey-attempt-counter.js';
@@ -0,0 +1,9 @@
1
+ export * from './attempt-counter.interface.js';
2
+ export * from './constants.js';
3
+ export * from './in-memory-attempt-counter.js';
4
+ export * from './rate-limit-logger.js';
5
+ export * from './rate-limit-logger.interface.js';
6
+ export * from './rate-limit.module.js';
7
+ export * from './throttle-budget.js';
8
+ export * from './throttle-gate.js';
9
+ export * from './valkey-attempt-counter.js';
@@ -0,0 +1,5 @@
1
+ import * as nestjsPino from 'nestjs-pino';
2
+ import type { RateLimitLoggerInterface } from './rate-limit-logger.interface.js';
3
+ export declare class RateLimitLogger extends nestjsPino.PinoLogger implements RateLimitLoggerInterface {
4
+ constructor(options: nestjsPino.Params);
5
+ }
@@ -0,0 +1,3 @@
1
+ export interface RateLimitLoggerInterface {
2
+ warn(context: unknown, message: string): void;
3
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,23 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __metadata = (this && this.__metadata) || function (k, v) {
8
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
9
+ };
10
+ var RateLimitLogger_1;
11
+ import { Injectable } from '@nestjs/common';
12
+ import * as nestjsPino from 'nestjs-pino';
13
+ let RateLimitLogger = RateLimitLogger_1 = class RateLimitLogger extends nestjsPino.PinoLogger {
14
+ constructor(options) {
15
+ super(options);
16
+ this.setContext(RateLimitLogger_1.name);
17
+ }
18
+ };
19
+ RateLimitLogger = RateLimitLogger_1 = __decorate([
20
+ Injectable(),
21
+ __metadata("design:paramtypes", [Object])
22
+ ], RateLimitLogger);
23
+ export { RateLimitLogger };
@@ -0,0 +1,13 @@
1
+ import type { DynamicModule, FactoryProvider, ModuleMetadata } from '@nestjs/common';
2
+ import type { AttemptCounterInterface } from './attempt-counter.interface.js';
3
+ import type { ThrottleDecideFunction } from './throttle-gate.js';
4
+ export interface RateLimitModuleOptionsInterface {
5
+ readonly counter: FactoryOptions<AttemptCounterInterface>;
6
+ readonly decide: FactoryOptions<ThrottleDecideFunction>;
7
+ readonly imports?: ModuleMetadata['imports'];
8
+ }
9
+ type FactoryOptions<T> = Omit<FactoryProvider<T>, 'provide'>;
10
+ export declare class RateLimitModule {
11
+ static forRootAsync(options: RateLimitModuleOptionsInterface): DynamicModule;
12
+ }
13
+ export {};
@@ -0,0 +1,31 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ import { Module } from '@nestjs/common';
8
+ import { RATE_LIMIT_COUNTER, RATE_LIMIT_DECIDE, RATE_LIMIT_LOGGER } from './constants.js';
9
+ import { RateLimitLogger } from './rate-limit-logger.js';
10
+ import { ThrottleBudget } from './throttle-budget.js';
11
+ import { ThrottleGate } from './throttle-gate.js';
12
+ let RateLimitModule = class RateLimitModule {
13
+ static forRootAsync(options) {
14
+ return {
15
+ exports: [RATE_LIMIT_COUNTER, ThrottleBudget, ThrottleGate],
16
+ imports: options.imports ?? [],
17
+ module: this,
18
+ providers: [
19
+ { ...options.counter, provide: RATE_LIMIT_COUNTER },
20
+ { ...options.decide, provide: RATE_LIMIT_DECIDE },
21
+ { provide: RATE_LIMIT_LOGGER, useClass: RateLimitLogger },
22
+ ThrottleBudget,
23
+ ThrottleGate,
24
+ ],
25
+ };
26
+ }
27
+ };
28
+ RateLimitModule = __decorate([
29
+ Module({})
30
+ ], RateLimitModule);
31
+ export { RateLimitModule };
@@ -0,0 +1,18 @@
1
+ import type { Option } from 'oxide.ts';
2
+ import type { AttemptCounterInterface, AttemptWindowInterface } from '../attempt-counter.interface.js';
3
+ interface IncrementCallInterface {
4
+ key: string;
5
+ windowSeconds: number;
6
+ }
7
+ export declare class FakeAttemptCounter implements AttemptCounterInterface {
8
+ readonly increments: IncrementCallInterface[];
9
+ readonly resets: string[];
10
+ retryAfterSeconds: number;
11
+ private readonly counts;
12
+ countOf(key: string): number;
13
+ increment(key: string, windowSeconds: number): Promise<AttemptWindowInterface>;
14
+ read(key: string): Promise<Option<AttemptWindowInterface>>;
15
+ reset(key: string): Promise<void>;
16
+ seed(key: string, count: number): void;
17
+ }
18
+ export {};
@@ -0,0 +1,30 @@
1
+ import { None, Some } from 'oxide.ts';
2
+ export class FakeAttemptCounter {
3
+ increments = [];
4
+ resets = [];
5
+ retryAfterSeconds = 42;
6
+ counts = new Map();
7
+ countOf(key) {
8
+ return this.counts.get(key) ?? 0;
9
+ }
10
+ async increment(key, windowSeconds) {
11
+ await Promise.resolve();
12
+ this.increments.push({ key, windowSeconds });
13
+ const count = (this.counts.get(key) ?? 0) + 1;
14
+ this.counts.set(key, count);
15
+ return { count, retryAfterSeconds: this.retryAfterSeconds };
16
+ }
17
+ async read(key) {
18
+ await Promise.resolve();
19
+ const count = this.counts.get(key);
20
+ return count === undefined ? None : Some({ count, retryAfterSeconds: this.retryAfterSeconds });
21
+ }
22
+ async reset(key) {
23
+ await Promise.resolve();
24
+ this.counts.delete(key);
25
+ this.resets.push(key);
26
+ }
27
+ seed(key, count) {
28
+ this.counts.set(key, count);
29
+ }
30
+ }
@@ -0,0 +1 @@
1
+ export * from './attempt-counter.fake.js';
@@ -0,0 +1 @@
1
+ export * from './attempt-counter.fake.js';
@@ -0,0 +1,30 @@
1
+ import type { AttemptCounterInterface } from './attempt-counter.interface.js';
2
+ import type { RateLimitLoggerInterface } from './rate-limit-logger.interface.js';
3
+ export interface ThrottleDecisionInterface {
4
+ allowed: boolean;
5
+ retryAfterSeconds: number;
6
+ }
7
+ export interface ThrottleRateLimitInterface {
8
+ rateLimitMaxRequests: number;
9
+ rateLimitWindowSeconds: number;
10
+ }
11
+ export interface ThrottleRefusalInterface {
12
+ message: string;
13
+ securityEvent: string;
14
+ }
15
+ export declare class ThrottleBudget {
16
+ private readonly attempts;
17
+ private readonly logger;
18
+ constructor(attempts: AttemptCounterInterface, logger: RateLimitLoggerInterface);
19
+ readFailures(options: {
20
+ key: string;
21
+ maxFailures: number;
22
+ refusal: ThrottleRefusalInterface;
23
+ }): Promise<ThrottleDecisionInterface>;
24
+ spend(options: {
25
+ key: string;
26
+ limit: ThrottleRateLimitInterface;
27
+ refusal: ThrottleRefusalInterface;
28
+ }): Promise<ThrottleDecisionInterface>;
29
+ private refuse;
30
+ }
@@ -0,0 +1,44 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __metadata = (this && this.__metadata) || function (k, v) {
8
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
9
+ };
10
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
11
+ return function (target, key) { decorator(target, key, paramIndex); }
12
+ };
13
+ import { Inject, Injectable } from '@nestjs/common';
14
+ import { RATE_LIMIT_COUNTER, RATE_LIMIT_LOGGER } from './constants.js';
15
+ const allow = () => ({ allowed: true, retryAfterSeconds: 0 });
16
+ let ThrottleBudget = class ThrottleBudget {
17
+ attempts;
18
+ logger;
19
+ constructor(attempts, logger) {
20
+ this.attempts = attempts;
21
+ this.logger = logger;
22
+ }
23
+ async readFailures(options) {
24
+ const window = await this.attempts.read(options.key);
25
+ const isBelowThreshold = window.isNone() || window.unwrap().count < options.maxFailures;
26
+ return isBelowThreshold ? allow() : this.refuse(window.unwrap().retryAfterSeconds, options.refusal);
27
+ }
28
+ async spend(options) {
29
+ const window = await this.attempts.increment(options.key, options.limit.rateLimitWindowSeconds);
30
+ const isWithinLimit = window.count <= options.limit.rateLimitMaxRequests;
31
+ return isWithinLimit ? allow() : this.refuse(window.retryAfterSeconds, options.refusal);
32
+ }
33
+ refuse(retryAfterSeconds, refusal) {
34
+ this.logger.warn({ retryAfterSeconds, securityEvent: refusal.securityEvent }, refusal.message);
35
+ return { allowed: false, retryAfterSeconds };
36
+ }
37
+ };
38
+ ThrottleBudget = __decorate([
39
+ Injectable(),
40
+ __param(0, Inject(RATE_LIMIT_COUNTER)),
41
+ __param(1, Inject(RATE_LIMIT_LOGGER)),
42
+ __metadata("design:paramtypes", [Object, Object])
43
+ ], ThrottleBudget);
44
+ export { ThrottleBudget };
@@ -0,0 +1,22 @@
1
+ import type { ExecutionContext } from '@nestjs/common';
2
+ export interface ThrottleAxisInterface<TContext extends ThrottleGuardContextInterface, TDecision extends ThrottleGateDecisionInterface> {
3
+ createCommand(context: TContext): object;
4
+ createError(): Error;
5
+ isAllowed(decision: TDecision): boolean;
6
+ readContext(context: ExecutionContext): TContext;
7
+ }
8
+ export type ThrottleDecideFunction = <TDecision>(command: object) => Promise<TDecision>;
9
+ export interface ThrottleGateDecisionInterface {
10
+ retryAfterSeconds: number;
11
+ }
12
+ export interface ThrottleGuardContextInterface {
13
+ reply: ThrottleReplyInterface;
14
+ }
15
+ export interface ThrottleReplyInterface {
16
+ header(name: string, value: string): unknown;
17
+ }
18
+ export declare class ThrottleGate {
19
+ private readonly decide;
20
+ constructor(decide: ThrottleDecideFunction);
21
+ pass<TContext extends ThrottleGuardContextInterface, TDecision extends ThrottleGateDecisionInterface>(executionContext: ExecutionContext, axis: ThrottleAxisInterface<TContext, TDecision>): Promise<boolean>;
22
+ }
@@ -0,0 +1,36 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __metadata = (this && this.__metadata) || function (k, v) {
8
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
9
+ };
10
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
11
+ return function (target, key) { decorator(target, key, paramIndex); }
12
+ };
13
+ import { Inject, Injectable } from '@nestjs/common';
14
+ import { RATE_LIMIT_DECIDE } from './constants.js';
15
+ const RETRY_AFTER_HEADER = 'retry-after';
16
+ let ThrottleGate = class ThrottleGate {
17
+ decide;
18
+ constructor(decide) {
19
+ this.decide = decide;
20
+ }
21
+ async pass(executionContext, axis) {
22
+ const context = axis.readContext(executionContext);
23
+ const decision = await this.decide(axis.createCommand(context));
24
+ if (axis.isAllowed(decision)) {
25
+ return true;
26
+ }
27
+ void context.reply.header(RETRY_AFTER_HEADER, String(decision.retryAfterSeconds));
28
+ throw axis.createError();
29
+ }
30
+ };
31
+ ThrottleGate = __decorate([
32
+ Injectable(),
33
+ __param(0, Inject(RATE_LIMIT_DECIDE)),
34
+ __metadata("design:paramtypes", [Function])
35
+ ], ThrottleGate);
36
+ export { ThrottleGate };
@@ -0,0 +1,16 @@
1
+ import type { OnApplicationShutdown } from '@nestjs/common';
2
+ import type { Option } from 'oxide.ts';
3
+ import type { AttemptCounterInterface, AttemptWindowInterface } from './attempt-counter.interface.js';
4
+ export interface ValkeyCommandsInterface {
5
+ del(key: string): Promise<number>;
6
+ disconnect(): void;
7
+ eval(script: string, numberOfKeys: number, ...parameters: (number | string)[]): Promise<unknown>;
8
+ }
9
+ export declare class ValkeyAttemptCounter implements AttemptCounterInterface, OnApplicationShutdown {
10
+ private readonly client;
11
+ constructor(client: ValkeyCommandsInterface);
12
+ increment(key: string, windowSeconds: number): Promise<AttemptWindowInterface>;
13
+ onApplicationShutdown(): void;
14
+ read(key: string): Promise<Option<AttemptWindowInterface>>;
15
+ reset(key: string): Promise<void>;
16
+ }
@@ -0,0 +1,46 @@
1
+ import { None, Some } from 'oxide.ts';
2
+ const MILLISECONDS_IN_SECOND = 1000;
3
+ const INCREMENT_SCRIPT = `
4
+ local count = redis.call('INCR', KEYS[1])
5
+ if count == 1 or redis.call('PTTL', KEYS[1]) == -1 then
6
+ redis.call('PEXPIRE', KEYS[1], ARGV[1])
7
+ end
8
+ return {count, redis.call('PTTL', KEYS[1])}
9
+ `;
10
+ const READ_SCRIPT = `
11
+ local count = redis.call('GET', KEYS[1])
12
+ if not count then
13
+ return {0, -2}
14
+ end
15
+ return {tonumber(count), redis.call('PTTL', KEYS[1])}
16
+ `;
17
+ const isWindowReply = (reply) => Array.isArray(reply)
18
+ && reply.length === 2
19
+ && reply.every((item) => typeof item === 'number');
20
+ const toWindow = (reply) => {
21
+ if (!isWindowReply(reply)) {
22
+ throw new TypeError(`Unexpected attempt counter reply: ${JSON.stringify(reply)}`);
23
+ }
24
+ const [count, ttlMs] = reply;
25
+ return { count, retryAfterSeconds: Math.ceil(ttlMs / MILLISECONDS_IN_SECOND) };
26
+ };
27
+ export class ValkeyAttemptCounter {
28
+ client;
29
+ constructor(client) {
30
+ this.client = client;
31
+ }
32
+ async increment(key, windowSeconds) {
33
+ const reply = await this.client.eval(INCREMENT_SCRIPT, 1, key, windowSeconds * MILLISECONDS_IN_SECOND);
34
+ return toWindow(reply);
35
+ }
36
+ onApplicationShutdown() {
37
+ this.client.disconnect();
38
+ }
39
+ async read(key) {
40
+ const window = toWindow(await this.client.eval(READ_SCRIPT, 1, key));
41
+ return window.retryAfterSeconds > 0 ? Some(window) : None;
42
+ }
43
+ async reset(key) {
44
+ await this.client.del(key);
45
+ }
46
+ }
package/package.json CHANGED
@@ -1,6 +1,88 @@
1
1
  {
2
2
  "name": "@application-kit/rate-limit",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "Частотная защита для NestJS: счётчик попыток с окном (память и Valkey с атомарным Lua), бюджет попыток и gate с Retry-After",
5
+ "keywords": [
6
+ "nestjs",
7
+ "rate-limit",
8
+ "throttle",
9
+ "valkey"
10
+ ],
11
+ "homepage": "https://gitlab.com/application-kit/application-kit/-/tree/main/packages/rate-limit",
12
+ "bugs": "https://gitlab.com/application-kit/application-kit/-/issues",
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "https://gitlab.com/application-kit/application-kit.git",
16
+ "directory": "packages/rate-limit"
17
+ },
18
+ "license": "MIT",
19
+ "author": {
20
+ "name": "application-kit"
21
+ },
22
+ "sideEffects": false,
23
+ "type": "module",
24
+ "exports": {
25
+ ".": {
26
+ "import": {
27
+ "types": "./dist/esm/index.d.ts",
28
+ "default": "./dist/esm/index.js"
29
+ },
30
+ "require": {
31
+ "types": "./dist/cjs/index.d.ts",
32
+ "default": "./dist/cjs/index.js"
33
+ }
34
+ },
35
+ "./package.json": "./package.json",
36
+ "./testing": {
37
+ "import": {
38
+ "types": "./dist/esm/testing/index.d.ts",
39
+ "default": "./dist/esm/testing/index.js"
40
+ },
41
+ "require": {
42
+ "types": "./dist/cjs/testing/index.d.ts",
43
+ "default": "./dist/cjs/testing/index.js"
44
+ }
45
+ }
46
+ },
47
+ "main": "./dist/cjs/index.js",
48
+ "module": "./dist/esm/index.js",
49
+ "types": "./dist/cjs/index.d.ts",
50
+ "files": [
51
+ "dist"
52
+ ],
53
+ "scripts": {
54
+ "build": "rm -rf ./dist && node ../../scripts/barrels.mjs create ./src --entry-only=testing && tsc --project tsconfig.build.json && tsc --project tsconfig.build.cjs.json && node ../../scripts/barrels.mjs clean ./src && node ../../scripts/mark-cjs.mjs ./dist/cjs",
55
+ "lint:tsc": "tsc --noEmit --pretty --project .",
56
+ "test:mutation": "stryker run",
57
+ "test:unit": "vitest run"
58
+ },
59
+ "devDependencies": {
60
+ "@nestjs/common": "^11.2.7",
61
+ "@nestjs/core": "^11.2.7",
62
+ "@nestjs/testing": "^11.2.7",
63
+ "@stryker-mutator/core": "^10.0.0",
64
+ "@stryker-mutator/vitest-runner": "^10.0.0",
65
+ "@types/node": "^26.2.0",
66
+ "iovalkey": "^0.4.0",
67
+ "nestjs-pino": "^4.6.1",
68
+ "oxide.ts": "^1.1.0",
69
+ "pino": "^10.3.1",
70
+ "pino-http": "^11.0.0",
71
+ "reflect-metadata": "^0.2.2",
72
+ "rxjs": "^7.8.2",
73
+ "testcontainers": "12.1.0",
74
+ "typescript": "^6.0.3",
75
+ "vitest": "^4.1.11"
76
+ },
77
+ "peerDependencies": {
78
+ "@nestjs/common": "^11.0.0",
79
+ "nestjs-pino": "^4.6.1",
80
+ "oxide.ts": "^1.1.0"
81
+ },
82
+ "engines": {
83
+ "node": ">=24"
84
+ },
85
+ "publishConfig": {
86
+ "access": "public"
87
+ }
6
88
  }