@application-kit/rate-limit 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +22 -0
- package/LICENSE +21 -0
- package/README.md +101 -2
- package/dist/cjs/attempt-counter.interface.d.ts +10 -0
- package/dist/cjs/attempt-counter.interface.js +2 -0
- package/dist/cjs/constants.d.ts +3 -0
- package/dist/cjs/constants.js +6 -0
- package/dist/cjs/in-memory-attempt-counter.d.ts +9 -0
- package/dist/cjs/in-memory-attempt-counter.js +50 -0
- package/dist/cjs/index.d.ts +14 -0
- package/dist/cjs/index.js +30 -0
- package/dist/cjs/package.json +3 -0
- package/dist/cjs/rate-limit-logger.d.ts +5 -0
- package/dist/cjs/rate-limit-logger.interface.d.ts +3 -0
- package/dist/cjs/rate-limit-logger.interface.js +2 -0
- package/dist/cjs/rate-limit-logger.js +59 -0
- package/dist/cjs/rate-limit.module.d.ts +13 -0
- package/dist/cjs/rate-limit.module.js +34 -0
- package/dist/cjs/testing/attempt-counter.fake.d.ts +18 -0
- package/dist/cjs/testing/attempt-counter.fake.js +34 -0
- package/dist/cjs/testing/index.d.ts +1 -0
- package/dist/cjs/testing/index.js +17 -0
- package/dist/cjs/throttle-axis.d.ts +7 -0
- package/dist/cjs/throttle-axis.interface.d.ts +32 -0
- package/dist/cjs/throttle-axis.interface.js +2 -0
- package/dist/cjs/throttle-axis.js +8 -0
- package/dist/cjs/throttle-budget.d.ts +30 -0
- package/dist/cjs/throttle-budget.js +47 -0
- package/dist/cjs/throttle-gate.d.ts +12 -0
- package/dist/cjs/throttle-gate.js +55 -0
- package/dist/cjs/throttle-outcome.interceptor.d.ts +12 -0
- package/dist/cjs/throttle-outcome.interceptor.js +51 -0
- package/dist/cjs/throttle.decorator.d.ts +2 -0
- package/dist/cjs/throttle.decorator.js +15 -0
- package/dist/cjs/throttle.guard.d.ts +9 -0
- package/dist/cjs/throttle.guard.js +33 -0
- package/dist/cjs/valkey-attempt-counter.d.ts +16 -0
- package/dist/cjs/valkey-attempt-counter.js +50 -0
- package/dist/esm/attempt-counter.interface.d.ts +10 -0
- package/dist/esm/attempt-counter.interface.js +1 -0
- package/dist/esm/constants.d.ts +3 -0
- package/dist/esm/constants.js +3 -0
- package/dist/esm/in-memory-attempt-counter.d.ts +9 -0
- package/dist/esm/in-memory-attempt-counter.js +47 -0
- package/dist/esm/index.d.ts +14 -0
- package/dist/esm/index.js +14 -0
- package/dist/esm/rate-limit-logger.d.ts +5 -0
- package/dist/esm/rate-limit-logger.interface.d.ts +3 -0
- package/dist/esm/rate-limit-logger.interface.js +1 -0
- package/dist/esm/rate-limit-logger.js +23 -0
- package/dist/esm/rate-limit.module.d.ts +13 -0
- package/dist/esm/rate-limit.module.js +31 -0
- package/dist/esm/testing/attempt-counter.fake.d.ts +18 -0
- package/dist/esm/testing/attempt-counter.fake.js +30 -0
- package/dist/esm/testing/index.d.ts +1 -0
- package/dist/esm/testing/index.js +1 -0
- package/dist/esm/throttle-axis.d.ts +7 -0
- package/dist/esm/throttle-axis.interface.d.ts +32 -0
- package/dist/esm/throttle-axis.interface.js +1 -0
- package/dist/esm/throttle-axis.js +4 -0
- package/dist/esm/throttle-budget.d.ts +30 -0
- package/dist/esm/throttle-budget.js +44 -0
- package/dist/esm/throttle-gate.d.ts +12 -0
- package/dist/esm/throttle-gate.js +52 -0
- package/dist/esm/throttle-outcome.interceptor.d.ts +12 -0
- package/dist/esm/throttle-outcome.interceptor.js +48 -0
- package/dist/esm/throttle.decorator.d.ts +2 -0
- package/dist/esm/throttle.decorator.js +11 -0
- package/dist/esm/throttle.guard.d.ts +9 -0
- package/dist/esm/throttle.guard.js +30 -0
- package/dist/esm/valkey-attempt-counter.d.ts +16 -0
- package/dist/esm/valkey-attempt-counter.js +46 -0
- package/package.json +87 -3
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
# @application-kit/rate-limit
|
|
2
|
+
|
|
3
|
+
## 0.2.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 8011515: Ось частотной защиты — данными: `defineThrottleAxis` описывает ось с решением командой приложения (и, по желанию,
|
|
8
|
+
регистрацией исхода) либо с бюджетом, который тратит каждая попытка (`key`, `limit` токеном порогов, `refusal`);
|
|
9
|
+
`@Throttle(axis)` ставит на ручку `ThrottleGuard` и — только у оси с исходом — `ThrottleOutcomeInterceptor`.
|
|
10
|
+
Ломающее: опция `RateLimitModule.forRootAsync` `decide` переименована в `execute` (`ThrottleExecuteFunction`,
|
|
11
|
+
`RATE_LIMIT_EXECUTE` — теперь в экспорте модуля), типы оси переехали из `throttle-gate` в описание оси; новые
|
|
12
|
+
peer-зависимости — `@nestjs/core` и `rxjs`.
|
|
13
|
+
|
|
14
|
+
## 0.1.0
|
|
15
|
+
|
|
16
|
+
### Minor Changes
|
|
17
|
+
|
|
18
|
+
- 2a0e18c: Первый выпуск: порт счётчика попыток с окном `AttemptCounterInterface`, адаптеры `InMemoryAttemptCounter` и
|
|
19
|
+
`ValkeyAttemptCounter` (атомарный Lua `INCR + PEXPIRE`, клиент узкой формы `ValkeyCommandsInterface` приносит
|
|
20
|
+
приложение), бюджет `ThrottleBudget` (`spend` — трата проверкой, `readFailures` — чтение без траты), `ThrottleGate`
|
|
21
|
+
с заголовком `Retry-After` и исполнителем решения оси, `RateLimitModule.forRootAsync`; фейк порта `FakeAttemptCounter`
|
|
22
|
+
(вход `/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,102 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @application-kit/rate-limit
|
|
2
2
|
|
|
3
|
-
|
|
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/core`, `nestjs-pino`, `oxide.ts`, `rxjs`. Клиент 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
|
+
// Исполнитель команд оси — решения и исхода: обычно — шина команд приложения.
|
|
29
|
+
execute: {
|
|
30
|
+
inject: [CommandBus],
|
|
31
|
+
useFactory: (commandBus: CommandBus) => async (command: object) => commandBus.execute(command),
|
|
32
|
+
},
|
|
33
|
+
imports: [ValkeyConfigModule],
|
|
34
|
+
})
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
Модуль экспортирует токены счётчика и исполнителя (`RATE_LIMIT_COUNTER`, `RATE_LIMIT_EXECUTE`), `ThrottleBudget` и
|
|
38
|
+
`ThrottleGate`: модуль ручки обязан их видеть — guard и интерцептор оси создаются там. Логгер отказов
|
|
39
|
+
(`RATE_LIMIT_LOGGER`, `RateLimitLogger`) модуль связывает сам — нужен глобальный `LoggerModule` из `nestjs-pino`.
|
|
40
|
+
|
|
41
|
+
## Счётчик
|
|
42
|
+
|
|
43
|
+
- `increment(key, windowSeconds)` — фиксирует попытку. Окно открывает первая попытка, попытки внутри окна его не
|
|
44
|
+
продлевают: иначе блокировку нельзя переждать.
|
|
45
|
+
- `read(key)` — состояние окна или `None`.
|
|
46
|
+
- `reset(key)` — сброс окна, например после успешного входа.
|
|
47
|
+
|
|
48
|
+
`ValkeyAttemptCounter` меняет счёт и срок одним Lua-скриптом: попытки разных реплик складываются, а рестарт процесса
|
|
49
|
+
блокировку не снимает. `InMemoryAttemptCounter` — для спек и запуска без хранилища: порог в нём действует на процесс.
|
|
50
|
+
|
|
51
|
+
## Бюджет
|
|
52
|
+
|
|
53
|
+
- `spend({ key, limit, refusal })` — попытка стоит окна независимо от исхода (ручки с одинаковым ответом всегда).
|
|
54
|
+
- `readFailures({ key, maxFailures, refusal })` — бюджет только читается; тратит его зарегистрированный исход попытки,
|
|
55
|
+
то есть `increment` у потребителя.
|
|
56
|
+
|
|
57
|
+
Отказ пишется в лог одной записью `{ retryAfterSeconds, securityEvent }` с сообщением `refusal.message` — без ключа
|
|
58
|
+
и идентификаторов.
|
|
59
|
+
|
|
60
|
+
## Ось
|
|
61
|
+
|
|
62
|
+
Ось — данные приложения, объявленные `defineThrottleAxis` и поставленные на ручку декоратором `@Throttle(axis)`:
|
|
63
|
+
|
|
64
|
+
```ts
|
|
65
|
+
// Бюджет тратит каждая попытка: ответ ручки одинаков при любом исходе.
|
|
66
|
+
const PASSWORD_RESET = defineThrottleAxis<ClientContext>({
|
|
67
|
+
createError: () => new TooManyPasswordResetRequestsError(),
|
|
68
|
+
key: ({ clientId }) => `passwordReset:rate:${clientId}`,
|
|
69
|
+
limit: PasswordResetProtectionConfig,
|
|
70
|
+
readContext: readClientContext,
|
|
71
|
+
refusal: { message: 'password reset request refused', securityEvent: 'passwordReset.refused' },
|
|
72
|
+
})
|
|
73
|
+
|
|
74
|
+
// Решение — команда приложения, исход попытки — вторая команда после ответа ручки.
|
|
75
|
+
const SIGN_IN = defineThrottleAxis<SignInContext, CheckSignInThrottleResult>({
|
|
76
|
+
createCommand: ({ clientId, subject }) => new CheckSignInThrottleCommand({ clientId, subject }),
|
|
77
|
+
createError: () => new TooManySignInAttemptsError(),
|
|
78
|
+
isAllowed: (decision) => decision.reason === null,
|
|
79
|
+
outcome: {
|
|
80
|
+
createCommand: ({ subject }, succeeded) => new RegisterSignInOutcomeCommand({ subject, succeeded }),
|
|
81
|
+
isAttemptSpent: isSignInAttemptSpent,
|
|
82
|
+
},
|
|
83
|
+
readContext: readSignInContext,
|
|
84
|
+
})
|
|
85
|
+
|
|
86
|
+
@Throttle(SIGN_IN)
|
|
87
|
+
public async signIn(...) {}
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
- `ThrottleGuard` до тела ручки спрашивает `ThrottleGate`: у оси с `limit` решение — `ThrottleBudget.spend` по
|
|
91
|
+
порогам из провайдера приложения, у оси с `createCommand` — команда через `execute`. Отказ пишет `retry-after`
|
|
92
|
+
в ответ и бросает ошибку оси.
|
|
93
|
+
- `ThrottleOutcomeInterceptor` стоит только у оси с `outcome`: успех регистрируется всегда, ошибка — когда
|
|
94
|
+
`isAttemptSpent` считает её потраченной попыткой; ошибка ручки уходит дальше без изменений.
|
|
95
|
+
|
|
96
|
+
## Спеки потребителя
|
|
97
|
+
|
|
98
|
+
```ts
|
|
99
|
+
import { FakeAttemptCounter } from '@application-kit/rate-limit/testing'
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
Фейк копит счёт и вызовы (`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,6 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.RATE_LIMIT_EXECUTE = 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_EXECUTE = Symbol('RATE_LIMIT_EXECUTE');
|
|
@@ -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,14 @@
|
|
|
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-axis.js';
|
|
8
|
+
export * from './throttle-axis.interface.js';
|
|
9
|
+
export * from './throttle-budget.js';
|
|
10
|
+
export * from './throttle-gate.js';
|
|
11
|
+
export * from './throttle-outcome.interceptor.js';
|
|
12
|
+
export * from './throttle.decorator.js';
|
|
13
|
+
export * from './throttle.guard.js';
|
|
14
|
+
export * from './valkey-attempt-counter.js';
|
|
@@ -0,0 +1,30 @@
|
|
|
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-axis.js"), exports);
|
|
24
|
+
__exportStar(require("./throttle-axis.interface.js"), exports);
|
|
25
|
+
__exportStar(require("./throttle-budget.js"), exports);
|
|
26
|
+
__exportStar(require("./throttle-gate.js"), exports);
|
|
27
|
+
__exportStar(require("./throttle-outcome.interceptor.js"), exports);
|
|
28
|
+
__exportStar(require("./throttle.decorator.js"), exports);
|
|
29
|
+
__exportStar(require("./throttle.guard.js"), exports);
|
|
30
|
+
__exportStar(require("./valkey-attempt-counter.js"), exports);
|
|
@@ -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,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 { ThrottleExecuteFunction } from './throttle-axis.interface.js';
|
|
4
|
+
export interface RateLimitModuleOptionsInterface {
|
|
5
|
+
readonly counter: FactoryOptions<AttemptCounterInterface>;
|
|
6
|
+
readonly execute: FactoryOptions<ThrottleExecuteFunction>;
|
|
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, constants_js_1.RATE_LIMIT_EXECUTE, 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.execute, provide: constants_js_1.RATE_LIMIT_EXECUTE },
|
|
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,7 @@
|
|
|
1
|
+
import type { ThrottleAxisInterface, ThrottleAxisOutcomeInterface, ThrottleDecidedAxisInterface, ThrottleGateDecisionInterface, ThrottleGuardContextInterface } from './throttle-axis.interface.js';
|
|
2
|
+
export interface ThrottleOutcomeAxisInterface<TContext extends ThrottleGuardContextInterface> extends Pick<ThrottleDecidedAxisInterface<TContext, ThrottleGateDecisionInterface>, 'readContext'> {
|
|
3
|
+
readonly outcome: ThrottleAxisOutcomeInterface<TContext>;
|
|
4
|
+
}
|
|
5
|
+
export declare const defineThrottleAxis: <TContext extends ThrottleGuardContextInterface, TDecision extends ThrottleGateDecisionInterface = ThrottleGateDecisionInterface>(axis: ThrottleAxisInterface<TContext, TDecision>) => ThrottleAxisInterface<TContext, TDecision>;
|
|
6
|
+
export declare const ThrottleAxisMetadata: import("@nestjs/core").ReflectableDecorator<ThrottleAxisInterface<ThrottleGuardContextInterface>, ThrottleAxisInterface<ThrottleGuardContextInterface>>;
|
|
7
|
+
export declare const ThrottleOutcomeMetadata: import("@nestjs/core").ReflectableDecorator<ThrottleOutcomeAxisInterface<ThrottleGuardContextInterface>, ThrottleOutcomeAxisInterface<ThrottleGuardContextInterface>>;
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import type { ExecutionContext, InjectionToken } from '@nestjs/common';
|
|
2
|
+
import type { ThrottleRateLimitInterface, ThrottleRefusalInterface } from './throttle-budget.js';
|
|
3
|
+
export type ThrottleAxisInterface<TContext extends ThrottleGuardContextInterface, TDecision extends ThrottleGateDecisionInterface = ThrottleGateDecisionInterface> = ThrottleDecidedAxisInterface<TContext, TDecision> | ThrottleSpentAxisInterface<TContext>;
|
|
4
|
+
export interface ThrottleAxisOutcomeInterface<TContext extends ThrottleGuardContextInterface> {
|
|
5
|
+
createCommand(context: TContext, didSucceed: boolean): object;
|
|
6
|
+
isAttemptSpent(error: unknown): boolean;
|
|
7
|
+
}
|
|
8
|
+
export interface ThrottleDecidedAxisInterface<TContext extends ThrottleGuardContextInterface, TDecision extends ThrottleGateDecisionInterface> extends ThrottleAxisBaseInterface<TContext> {
|
|
9
|
+
createCommand(context: TContext): object;
|
|
10
|
+
isAllowed(decision: TDecision): boolean;
|
|
11
|
+
readonly outcome?: ThrottleAxisOutcomeInterface<TContext>;
|
|
12
|
+
}
|
|
13
|
+
export type ThrottleExecuteFunction = <TResult>(command: object) => Promise<TResult>;
|
|
14
|
+
export interface ThrottleGateDecisionInterface {
|
|
15
|
+
retryAfterSeconds: number;
|
|
16
|
+
}
|
|
17
|
+
export interface ThrottleGuardContextInterface {
|
|
18
|
+
reply: ThrottleReplyInterface;
|
|
19
|
+
}
|
|
20
|
+
export interface ThrottleReplyInterface {
|
|
21
|
+
header(name: string, value: string): unknown;
|
|
22
|
+
}
|
|
23
|
+
export interface ThrottleSpentAxisInterface<TContext extends ThrottleGuardContextInterface> extends ThrottleAxisBaseInterface<TContext> {
|
|
24
|
+
key(context: TContext): string;
|
|
25
|
+
readonly limit: InjectionToken<ThrottleRateLimitInterface>;
|
|
26
|
+
readonly refusal: ThrottleRefusalInterface;
|
|
27
|
+
}
|
|
28
|
+
interface ThrottleAxisBaseInterface<TContext extends ThrottleGuardContextInterface> {
|
|
29
|
+
createError(): Error;
|
|
30
|
+
readContext(context: ExecutionContext): TContext;
|
|
31
|
+
}
|
|
32
|
+
export {};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.ThrottleOutcomeMetadata = exports.ThrottleAxisMetadata = exports.defineThrottleAxis = void 0;
|
|
4
|
+
const core_1 = require("@nestjs/core");
|
|
5
|
+
const defineThrottleAxis = (axis) => Object.freeze(axis);
|
|
6
|
+
exports.defineThrottleAxis = defineThrottleAxis;
|
|
7
|
+
exports.ThrottleAxisMetadata = core_1.Reflector.createDecorator();
|
|
8
|
+
exports.ThrottleOutcomeMetadata = core_1.Reflector.createDecorator();
|
|
@@ -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,12 @@
|
|
|
1
|
+
import type { ExecutionContext } from '@nestjs/common';
|
|
2
|
+
import { ModuleRef } from '@nestjs/core';
|
|
3
|
+
import type { ThrottleAxisInterface, ThrottleExecuteFunction, ThrottleGateDecisionInterface, ThrottleGuardContextInterface } from './throttle-axis.interface.js';
|
|
4
|
+
import { ThrottleBudget } from './throttle-budget.js';
|
|
5
|
+
export declare class ThrottleGate {
|
|
6
|
+
private readonly execute;
|
|
7
|
+
private readonly budget;
|
|
8
|
+
private readonly moduleReference;
|
|
9
|
+
constructor(execute: ThrottleExecuteFunction, budget: ThrottleBudget, moduleReference: ModuleRef);
|
|
10
|
+
pass<TContext extends ThrottleGuardContextInterface, TDecision extends ThrottleGateDecisionInterface>(executionContext: ExecutionContext, axis: ThrottleAxisInterface<TContext, TDecision>): Promise<boolean>;
|
|
11
|
+
private decide;
|
|
12
|
+
}
|