@application-kit/rate-limit 0.1.0 → 0.3.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 +23 -0
- package/README.md +57 -18
- package/dist/cjs/configs/envs/index.d.ts +1 -0
- package/dist/cjs/configs/envs/index.js +17 -0
- package/dist/cjs/configs/envs/valkey.environment.d.ts +7 -0
- package/dist/cjs/configs/envs/valkey.environment.js +50 -0
- package/dist/cjs/configs/index.d.ts +2 -0
- package/dist/cjs/configs/index.js +18 -0
- package/dist/cjs/configs/valkey.config.d.ts +11 -0
- package/dist/cjs/configs/valkey.config.js +43 -0
- package/dist/cjs/constants.d.ts +1 -1
- package/dist/cjs/constants.js +2 -2
- package/dist/cjs/create-attempt-counter.d.ts +6 -0
- package/dist/cjs/create-attempt-counter.js +23 -0
- package/dist/cjs/index.d.ts +7 -0
- package/dist/cjs/index.js +7 -0
- package/dist/cjs/rate-limit.module.d.ts +3 -3
- package/dist/cjs/rate-limit.module.js +18 -4
- 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-gate.d.ts +8 -18
- package/dist/cjs/throttle-gate.js +23 -7
- 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/esm/configs/envs/index.d.ts +1 -0
- package/dist/esm/configs/envs/index.js +1 -0
- package/dist/esm/configs/envs/valkey.environment.d.ts +7 -0
- package/dist/esm/configs/envs/valkey.environment.js +46 -0
- package/dist/esm/configs/index.d.ts +2 -0
- package/dist/esm/configs/index.js +2 -0
- package/dist/esm/configs/valkey.config.d.ts +11 -0
- package/dist/esm/configs/valkey.config.js +40 -0
- package/dist/esm/constants.d.ts +1 -1
- package/dist/esm/constants.js +1 -1
- package/dist/esm/create-attempt-counter.d.ts +6 -0
- package/dist/esm/create-attempt-counter.js +18 -0
- package/dist/esm/index.d.ts +7 -0
- package/dist/esm/index.js +7 -0
- package/dist/esm/rate-limit.module.d.ts +3 -3
- package/dist/esm/rate-limit.module.js +19 -5
- 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-gate.d.ts +8 -18
- package/dist/esm/throttle-gate.js +24 -8
- 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/package.json +13 -3
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,28 @@
|
|
|
1
1
|
# @application-kit/rate-limit
|
|
2
2
|
|
|
3
|
+
## 0.3.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- d8557a5: `RateLimitModule.forRootAsync` без опции `counter` выбирает хранилище счётчика сам по окружению `VALKEY_*`
|
|
8
|
+
(`VALKEY_HOST`, `VALKEY_PORT`, `VALKEY_CLUSTER`, `VALKEY_USERNAME`, `VALKEY_PASSWORD`): адрес задан — `ValkeyAttemptCounter`
|
|
9
|
+
над ленивым клиентом кластера или одиночного сервера, пуст — `InMemoryAttemptCounter` и одно предупреждение в лог.
|
|
10
|
+
Окружение валидируется в `forRootAsync`, не на импорте пакета. Переданный `counter` работает как раньше, и тогда
|
|
11
|
+
`VALKEY_*` не читается. Новые экспорты: `ValkeyEnvironment`, `ValkeyConfig`, `createValkeyClient`, `createAttemptCounter`;
|
|
12
|
+
`iovalkey` — зависимость пакета, `@libs-for-dev/nestjs-config-module`, `class-transformer`, `class-validator` — новые
|
|
13
|
+
peer: потребителю — поставить их, а свою сборку клиента и фабрику счётчика заменить умолчанием модуля.
|
|
14
|
+
|
|
15
|
+
## 0.2.0
|
|
16
|
+
|
|
17
|
+
### Minor Changes
|
|
18
|
+
|
|
19
|
+
- 8011515: Ось частотной защиты — данными: `defineThrottleAxis` описывает ось с решением командой приложения (и, по желанию,
|
|
20
|
+
регистрацией исхода) либо с бюджетом, который тратит каждая попытка (`key`, `limit` токеном порогов, `refusal`);
|
|
21
|
+
`@Throttle(axis)` ставит на ручку `ThrottleGuard` и — только у оси с исходом — `ThrottleOutcomeInterceptor`.
|
|
22
|
+
Ломающее: опция `RateLimitModule.forRootAsync` `decide` переименована в `execute` (`ThrottleExecuteFunction`,
|
|
23
|
+
`RATE_LIMIT_EXECUTE` — теперь в экспорте модуля), типы оси переехали из `throttle-gate` в описание оси; новые
|
|
24
|
+
peer-зависимости — `@nestjs/core` и `rxjs`.
|
|
25
|
+
|
|
3
26
|
## 0.1.0
|
|
4
27
|
|
|
5
28
|
### Minor Changes
|
package/README.md
CHANGED
|
@@ -9,32 +9,41 @@
|
|
|
9
9
|
yarn add @application-kit/rate-limit
|
|
10
10
|
```
|
|
11
11
|
|
|
12
|
-
Peer-зависимости: `@nestjs/common`,
|
|
13
|
-
|
|
12
|
+
Peer-зависимости: `@libs-for-dev/nestjs-config-module`, `@nestjs/common`, `@nestjs/core`, `class-transformer`,
|
|
13
|
+
`class-validator`, `nestjs-pino`, `oxide.ts`, `rxjs`. Клиент Valkey (`iovalkey`) — зависимость пакета.
|
|
14
14
|
|
|
15
15
|
## Подключение
|
|
16
16
|
|
|
17
17
|
```ts
|
|
18
|
-
import {
|
|
18
|
+
import { RateLimitModule } from '@application-kit/rate-limit'
|
|
19
19
|
|
|
20
20
|
RateLimitModule.forRootAsync({
|
|
21
|
-
//
|
|
22
|
-
|
|
23
|
-
inject: [ValkeyConfig],
|
|
24
|
-
useFactory: (config: ValkeyConfig) => (config.isEnabled
|
|
25
|
-
? new ValkeyAttemptCounter(createValkeyClient(config))
|
|
26
|
-
: new InMemoryAttemptCounter()),
|
|
27
|
-
},
|
|
28
|
-
// Исполнитель решения оси для `ThrottleGate`: обычно — шина команд приложения.
|
|
29
|
-
decide: {
|
|
21
|
+
// Исполнитель команд оси — решения и исхода: обычно — шина команд приложения.
|
|
22
|
+
execute: {
|
|
30
23
|
inject: [CommandBus],
|
|
31
24
|
useFactory: (commandBus: CommandBus) => async (command: object) => commandBus.execute(command),
|
|
32
25
|
},
|
|
33
|
-
imports: [
|
|
26
|
+
imports: [CqrsModule],
|
|
34
27
|
})
|
|
35
28
|
```
|
|
36
29
|
|
|
37
|
-
|
|
30
|
+
Счётчик без опции `counter` выбирает окружение:
|
|
31
|
+
|
|
32
|
+
| Переменная | Умолчание | Смысл |
|
|
33
|
+
|---|---|---|
|
|
34
|
+
| `VALKEY_HOST` | `''` | адрес хранилища; пусто — счётчик в памяти процесса и одно предупреждение в лог |
|
|
35
|
+
| `VALKEY_PORT` | `6379` | порт |
|
|
36
|
+
| `VALKEY_CLUSTER` | `true` | кластерный протокол (адрес — стартовый узел); `false` — одиночный сервер |
|
|
37
|
+
| `VALKEY_USERNAME` | `default` | пользователь ACL |
|
|
38
|
+
| `VALKEY_PASSWORD` | `''` | пароль |
|
|
39
|
+
|
|
40
|
+
Клиент ленивый (`lazyConnect`): соединение открывает первая попытка, а не сборка графа. Окружение читается и
|
|
41
|
+
валидируется в `forRootAsync`, а не на импорте пакета; неверное значение роняет старт с именем переменной.
|
|
42
|
+
Свой счётчик — фабрикой в опции `counter` (`{ useFactory: () => new FakeAttemptCounter() }` из
|
|
43
|
+
`@application-kit/rate-limit/testing` в спеках): тогда `VALKEY_*` не читается.
|
|
44
|
+
|
|
45
|
+
Модуль экспортирует токены счётчика и исполнителя (`RATE_LIMIT_COUNTER`, `RATE_LIMIT_EXECUTE`), `ThrottleBudget` и
|
|
46
|
+
`ThrottleGate`: модуль ручки обязан их видеть — guard и интерцептор оси создаются там. Логгер отказов
|
|
38
47
|
(`RATE_LIMIT_LOGGER`, `RateLimitLogger`) модуль связывает сам — нужен глобальный `LoggerModule` из `nestjs-pino`.
|
|
39
48
|
|
|
40
49
|
## Счётчик
|
|
@@ -56,11 +65,41 @@ RateLimitModule.forRootAsync({
|
|
|
56
65
|
Отказ пишется в лог одной записью `{ retryAfterSeconds, securityEvent }` с сообщением `refusal.message` — без ключа
|
|
57
66
|
и идентификаторов.
|
|
58
67
|
|
|
59
|
-
##
|
|
68
|
+
## Ось
|
|
69
|
+
|
|
70
|
+
Ось — данные приложения, объявленные `defineThrottleAxis` и поставленные на ручку декоратором `@Throttle(axis)`:
|
|
71
|
+
|
|
72
|
+
```ts
|
|
73
|
+
// Бюджет тратит каждая попытка: ответ ручки одинаков при любом исходе.
|
|
74
|
+
const PASSWORD_RESET = defineThrottleAxis<ClientContext>({
|
|
75
|
+
createError: () => new TooManyPasswordResetRequestsError(),
|
|
76
|
+
key: ({ clientId }) => `passwordReset:rate:${clientId}`,
|
|
77
|
+
limit: PasswordResetProtectionConfig,
|
|
78
|
+
readContext: readClientContext,
|
|
79
|
+
refusal: { message: 'password reset request refused', securityEvent: 'passwordReset.refused' },
|
|
80
|
+
})
|
|
81
|
+
|
|
82
|
+
// Решение — команда приложения, исход попытки — вторая команда после ответа ручки.
|
|
83
|
+
const SIGN_IN = defineThrottleAxis<SignInContext, CheckSignInThrottleResult>({
|
|
84
|
+
createCommand: ({ clientId, subject }) => new CheckSignInThrottleCommand({ clientId, subject }),
|
|
85
|
+
createError: () => new TooManySignInAttemptsError(),
|
|
86
|
+
isAllowed: (decision) => decision.reason === null,
|
|
87
|
+
outcome: {
|
|
88
|
+
createCommand: ({ subject }, succeeded) => new RegisterSignInOutcomeCommand({ subject, succeeded }),
|
|
89
|
+
isAttemptSpent: isSignInAttemptSpent,
|
|
90
|
+
},
|
|
91
|
+
readContext: readSignInContext,
|
|
92
|
+
})
|
|
93
|
+
|
|
94
|
+
@Throttle(SIGN_IN)
|
|
95
|
+
public async signIn(...) {}
|
|
96
|
+
```
|
|
60
97
|
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
98
|
+
- `ThrottleGuard` до тела ручки спрашивает `ThrottleGate`: у оси с `limit` решение — `ThrottleBudget.spend` по
|
|
99
|
+
порогам из провайдера приложения, у оси с `createCommand` — команда через `execute`. Отказ пишет `retry-after`
|
|
100
|
+
в ответ и бросает ошибку оси.
|
|
101
|
+
- `ThrottleOutcomeInterceptor` стоит только у оси с `outcome`: успех регистрируется всегда, ошибка — когда
|
|
102
|
+
`isAttemptSpent` считает её потраченной попыткой; ошибка ручки уходит дальше без изменений.
|
|
64
103
|
|
|
65
104
|
## Спеки потребителя
|
|
66
105
|
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from './valkey.environment.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("./valkey.environment.js"), exports);
|
|
@@ -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
|
+
var __metadata = (this && this.__metadata) || function (k, v) {
|
|
9
|
+
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
10
|
+
};
|
|
11
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
12
|
+
exports.ValkeyEnvironment = void 0;
|
|
13
|
+
const nestjs_config_module_1 = require("@libs-for-dev/nestjs-config-module");
|
|
14
|
+
const class_transformer_1 = require("class-transformer");
|
|
15
|
+
const class_validator_1 = require("class-validator");
|
|
16
|
+
class ValkeyEnvironment {
|
|
17
|
+
VALKEY_CLUSTER = true;
|
|
18
|
+
VALKEY_HOST = '';
|
|
19
|
+
VALKEY_PASSWORD = '';
|
|
20
|
+
VALKEY_PORT = 6379;
|
|
21
|
+
VALKEY_USERNAME = 'default';
|
|
22
|
+
}
|
|
23
|
+
exports.ValkeyEnvironment = ValkeyEnvironment;
|
|
24
|
+
__decorate([
|
|
25
|
+
(0, class_transformer_1.Expose)(),
|
|
26
|
+
(0, class_validator_1.IsBoolean)(),
|
|
27
|
+
(0, nestjs_config_module_1.ParseBoolean)(),
|
|
28
|
+
__metadata("design:type", Object)
|
|
29
|
+
], ValkeyEnvironment.prototype, "VALKEY_CLUSTER", void 0);
|
|
30
|
+
__decorate([
|
|
31
|
+
(0, class_transformer_1.Expose)(),
|
|
32
|
+
(0, class_validator_1.IsString)(),
|
|
33
|
+
__metadata("design:type", Object)
|
|
34
|
+
], ValkeyEnvironment.prototype, "VALKEY_HOST", void 0);
|
|
35
|
+
__decorate([
|
|
36
|
+
(0, class_transformer_1.Expose)(),
|
|
37
|
+
(0, class_validator_1.IsString)(),
|
|
38
|
+
__metadata("design:type", Object)
|
|
39
|
+
], ValkeyEnvironment.prototype, "VALKEY_PASSWORD", void 0);
|
|
40
|
+
__decorate([
|
|
41
|
+
(0, class_transformer_1.Expose)(),
|
|
42
|
+
(0, class_validator_1.IsNumber)(),
|
|
43
|
+
(0, class_transformer_1.Type)(() => Number),
|
|
44
|
+
__metadata("design:type", Object)
|
|
45
|
+
], ValkeyEnvironment.prototype, "VALKEY_PORT", void 0);
|
|
46
|
+
__decorate([
|
|
47
|
+
(0, class_transformer_1.Expose)(),
|
|
48
|
+
(0, class_validator_1.IsString)(),
|
|
49
|
+
__metadata("design:type", Object)
|
|
50
|
+
], ValkeyEnvironment.prototype, "VALKEY_USERNAME", void 0);
|
|
@@ -0,0 +1,18 @@
|
|
|
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("./envs/index.js"), exports);
|
|
18
|
+
__exportStar(require("./valkey.config.js"), exports);
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { ValkeyEnvironment } from './envs/valkey.environment.js';
|
|
2
|
+
export declare class ValkeyConfig {
|
|
3
|
+
private readonly environment;
|
|
4
|
+
get host(): string;
|
|
5
|
+
get isCluster(): boolean;
|
|
6
|
+
get isEnabled(): boolean;
|
|
7
|
+
get password(): string;
|
|
8
|
+
get port(): number;
|
|
9
|
+
get username(): string;
|
|
10
|
+
constructor(environment: ValkeyEnvironment);
|
|
11
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
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
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
12
|
+
exports.ValkeyConfig = void 0;
|
|
13
|
+
const common_1 = require("@nestjs/common");
|
|
14
|
+
const valkey_environment_js_1 = require("./envs/valkey.environment.js");
|
|
15
|
+
let ValkeyConfig = class ValkeyConfig {
|
|
16
|
+
environment;
|
|
17
|
+
get host() {
|
|
18
|
+
return this.environment.VALKEY_HOST;
|
|
19
|
+
}
|
|
20
|
+
get isCluster() {
|
|
21
|
+
return this.environment.VALKEY_CLUSTER;
|
|
22
|
+
}
|
|
23
|
+
get isEnabled() {
|
|
24
|
+
return this.environment.VALKEY_HOST !== '';
|
|
25
|
+
}
|
|
26
|
+
get password() {
|
|
27
|
+
return this.environment.VALKEY_PASSWORD;
|
|
28
|
+
}
|
|
29
|
+
get port() {
|
|
30
|
+
return this.environment.VALKEY_PORT;
|
|
31
|
+
}
|
|
32
|
+
get username() {
|
|
33
|
+
return this.environment.VALKEY_USERNAME;
|
|
34
|
+
}
|
|
35
|
+
constructor(environment) {
|
|
36
|
+
this.environment = environment;
|
|
37
|
+
}
|
|
38
|
+
};
|
|
39
|
+
exports.ValkeyConfig = ValkeyConfig;
|
|
40
|
+
exports.ValkeyConfig = ValkeyConfig = __decorate([
|
|
41
|
+
(0, common_1.Injectable)(),
|
|
42
|
+
__metadata("design:paramtypes", [valkey_environment_js_1.ValkeyEnvironment])
|
|
43
|
+
], ValkeyConfig);
|
package/dist/cjs/constants.d.ts
CHANGED
package/dist/cjs/constants.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.
|
|
3
|
+
exports.RATE_LIMIT_EXECUTE = exports.RATE_LIMIT_LOGGER = exports.RATE_LIMIT_COUNTER = void 0;
|
|
4
4
|
exports.RATE_LIMIT_COUNTER = Symbol('RATE_LIMIT_COUNTER');
|
|
5
5
|
exports.RATE_LIMIT_LOGGER = Symbol('RATE_LIMIT_LOGGER');
|
|
6
|
-
exports.
|
|
6
|
+
exports.RATE_LIMIT_EXECUTE = Symbol('RATE_LIMIT_EXECUTE');
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { Cluster, Redis } from 'iovalkey';
|
|
2
|
+
import type { AttemptCounterInterface } from './attempt-counter.interface.js';
|
|
3
|
+
import type { ValkeyConfig } from './configs/valkey.config.js';
|
|
4
|
+
import type { RateLimitLoggerInterface } from './rate-limit-logger.interface.js';
|
|
5
|
+
export declare const createValkeyClient: (config: ValkeyConfig) => Cluster | Redis;
|
|
6
|
+
export declare const createAttemptCounter: (config: ValkeyConfig, logger: RateLimitLoggerInterface) => AttemptCounterInterface;
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.createAttemptCounter = exports.createValkeyClient = void 0;
|
|
4
|
+
const iovalkey_1 = require("iovalkey");
|
|
5
|
+
const in_memory_attempt_counter_js_1 = require("./in-memory-attempt-counter.js");
|
|
6
|
+
const valkey_attempt_counter_js_1 = require("./valkey-attempt-counter.js");
|
|
7
|
+
const IN_MEMORY_FALLBACK_WARNING = 'VALKEY_HOST is empty: attempt counters are kept in process memory,'
|
|
8
|
+
+ ' so the lockout threshold applies per replica and resets on restart';
|
|
9
|
+
const createValkeyClient = (config) => {
|
|
10
|
+
const options = { lazyConnect: true, password: config.password, username: config.username };
|
|
11
|
+
return config.isCluster
|
|
12
|
+
? new iovalkey_1.Cluster([{ host: config.host, port: config.port }], { lazyConnect: true, redisOptions: options })
|
|
13
|
+
: new iovalkey_1.Redis({ ...options, host: config.host, port: config.port });
|
|
14
|
+
};
|
|
15
|
+
exports.createValkeyClient = createValkeyClient;
|
|
16
|
+
const createAttemptCounter = (config, logger) => {
|
|
17
|
+
if (config.isEnabled) {
|
|
18
|
+
return new valkey_attempt_counter_js_1.ValkeyAttemptCounter((0, exports.createValkeyClient)(config));
|
|
19
|
+
}
|
|
20
|
+
logger.warn({}, IN_MEMORY_FALLBACK_WARNING);
|
|
21
|
+
return new in_memory_attempt_counter_js_1.InMemoryAttemptCounter();
|
|
22
|
+
};
|
|
23
|
+
exports.createAttemptCounter = createAttemptCounter;
|
package/dist/cjs/index.d.ts
CHANGED
|
@@ -1,9 +1,16 @@
|
|
|
1
|
+
export * from './configs/index.js';
|
|
1
2
|
export * from './attempt-counter.interface.js';
|
|
2
3
|
export * from './constants.js';
|
|
4
|
+
export * from './create-attempt-counter.js';
|
|
3
5
|
export * from './in-memory-attempt-counter.js';
|
|
4
6
|
export * from './rate-limit-logger.js';
|
|
5
7
|
export * from './rate-limit-logger.interface.js';
|
|
6
8
|
export * from './rate-limit.module.js';
|
|
9
|
+
export * from './throttle-axis.js';
|
|
10
|
+
export * from './throttle-axis.interface.js';
|
|
7
11
|
export * from './throttle-budget.js';
|
|
8
12
|
export * from './throttle-gate.js';
|
|
13
|
+
export * from './throttle-outcome.interceptor.js';
|
|
14
|
+
export * from './throttle.decorator.js';
|
|
15
|
+
export * from './throttle.guard.js';
|
|
9
16
|
export * from './valkey-attempt-counter.js';
|
package/dist/cjs/index.js
CHANGED
|
@@ -14,12 +14,19 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
|
14
14
|
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
15
|
};
|
|
16
16
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
+
__exportStar(require("./configs/index.js"), exports);
|
|
17
18
|
__exportStar(require("./attempt-counter.interface.js"), exports);
|
|
18
19
|
__exportStar(require("./constants.js"), exports);
|
|
20
|
+
__exportStar(require("./create-attempt-counter.js"), exports);
|
|
19
21
|
__exportStar(require("./in-memory-attempt-counter.js"), exports);
|
|
20
22
|
__exportStar(require("./rate-limit-logger.js"), exports);
|
|
21
23
|
__exportStar(require("./rate-limit-logger.interface.js"), exports);
|
|
22
24
|
__exportStar(require("./rate-limit.module.js"), exports);
|
|
25
|
+
__exportStar(require("./throttle-axis.js"), exports);
|
|
26
|
+
__exportStar(require("./throttle-axis.interface.js"), exports);
|
|
23
27
|
__exportStar(require("./throttle-budget.js"), exports);
|
|
24
28
|
__exportStar(require("./throttle-gate.js"), exports);
|
|
29
|
+
__exportStar(require("./throttle-outcome.interceptor.js"), exports);
|
|
30
|
+
__exportStar(require("./throttle.decorator.js"), exports);
|
|
31
|
+
__exportStar(require("./throttle.guard.js"), exports);
|
|
25
32
|
__exportStar(require("./valkey-attempt-counter.js"), exports);
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import type { DynamicModule, FactoryProvider, ModuleMetadata } from '@nestjs/common';
|
|
2
2
|
import type { AttemptCounterInterface } from './attempt-counter.interface.js';
|
|
3
|
-
import type {
|
|
3
|
+
import type { ThrottleExecuteFunction } from './throttle-axis.interface.js';
|
|
4
4
|
export interface RateLimitModuleOptionsInterface {
|
|
5
|
-
readonly counter
|
|
6
|
-
readonly
|
|
5
|
+
readonly counter?: FactoryOptions<AttemptCounterInterface>;
|
|
6
|
+
readonly execute: FactoryOptions<ThrottleExecuteFunction>;
|
|
7
7
|
readonly imports?: ModuleMetadata['imports'];
|
|
8
8
|
}
|
|
9
9
|
type FactoryOptions<T> = Omit<FactoryProvider<T>, 'provide'>;
|
|
@@ -7,20 +7,34 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
|
|
|
7
7
|
};
|
|
8
8
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
9
9
|
exports.RateLimitModule = void 0;
|
|
10
|
+
const nestjs_config_module_1 = require("@libs-for-dev/nestjs-config-module");
|
|
10
11
|
const common_1 = require("@nestjs/common");
|
|
12
|
+
const valkey_environment_js_1 = require("./configs/envs/valkey.environment.js");
|
|
13
|
+
const valkey_config_js_1 = require("./configs/valkey.config.js");
|
|
11
14
|
const constants_js_1 = require("./constants.js");
|
|
15
|
+
const create_attempt_counter_js_1 = require("./create-attempt-counter.js");
|
|
12
16
|
const rate_limit_logger_js_1 = require("./rate-limit-logger.js");
|
|
13
17
|
const throttle_budget_js_1 = require("./throttle-budget.js");
|
|
14
18
|
const throttle_gate_js_1 = require("./throttle-gate.js");
|
|
19
|
+
const bindCounter = (counter) => {
|
|
20
|
+
if (counter !== undefined) {
|
|
21
|
+
return { imports: [], provider: counter };
|
|
22
|
+
}
|
|
23
|
+
return {
|
|
24
|
+
imports: [nestjs_config_module_1.ConfigsModule.forFeature([valkey_config_js_1.ValkeyConfig], [valkey_environment_js_1.ValkeyEnvironment])],
|
|
25
|
+
provider: { inject: [valkey_config_js_1.ValkeyConfig, constants_js_1.RATE_LIMIT_LOGGER], useFactory: create_attempt_counter_js_1.createAttemptCounter },
|
|
26
|
+
};
|
|
27
|
+
};
|
|
15
28
|
let RateLimitModule = class RateLimitModule {
|
|
16
29
|
static forRootAsync(options) {
|
|
30
|
+
const counter = bindCounter(options.counter);
|
|
17
31
|
return {
|
|
18
|
-
exports: [constants_js_1.RATE_LIMIT_COUNTER, throttle_budget_js_1.ThrottleBudget, throttle_gate_js_1.ThrottleGate],
|
|
19
|
-
imports: options.imports ?? [],
|
|
32
|
+
exports: [constants_js_1.RATE_LIMIT_COUNTER, constants_js_1.RATE_LIMIT_EXECUTE, throttle_budget_js_1.ThrottleBudget, throttle_gate_js_1.ThrottleGate],
|
|
33
|
+
imports: [...(options.imports ?? []), ...counter.imports],
|
|
20
34
|
module: this,
|
|
21
35
|
providers: [
|
|
22
|
-
{ ...
|
|
23
|
-
{ ...options.
|
|
36
|
+
{ ...counter.provider, provide: constants_js_1.RATE_LIMIT_COUNTER },
|
|
37
|
+
{ ...options.execute, provide: constants_js_1.RATE_LIMIT_EXECUTE },
|
|
24
38
|
{ provide: constants_js_1.RATE_LIMIT_LOGGER, useClass: rate_limit_logger_js_1.RateLimitLogger },
|
|
25
39
|
throttle_budget_js_1.ThrottleBudget,
|
|
26
40
|
throttle_gate_js_1.ThrottleGate,
|
|
@@ -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();
|
|
@@ -1,22 +1,12 @@
|
|
|
1
1
|
import type { ExecutionContext } from '@nestjs/common';
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
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
|
-
}
|
|
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';
|
|
18
5
|
export declare class ThrottleGate {
|
|
19
|
-
private readonly
|
|
20
|
-
|
|
6
|
+
private readonly execute;
|
|
7
|
+
private readonly budget;
|
|
8
|
+
private readonly moduleReference;
|
|
9
|
+
constructor(execute: ThrottleExecuteFunction, budget: ThrottleBudget, moduleReference: ModuleRef);
|
|
21
10
|
pass<TContext extends ThrottleGuardContextInterface, TDecision extends ThrottleGateDecisionInterface>(executionContext: ExecutionContext, axis: ThrottleAxisInterface<TContext, TDecision>): Promise<boolean>;
|
|
11
|
+
private decide;
|
|
22
12
|
}
|
|
@@ -14,26 +14,42 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
|
14
14
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
15
15
|
exports.ThrottleGate = void 0;
|
|
16
16
|
const common_1 = require("@nestjs/common");
|
|
17
|
+
const core_1 = require("@nestjs/core");
|
|
17
18
|
const constants_js_1 = require("./constants.js");
|
|
19
|
+
const throttle_budget_js_1 = require("./throttle-budget.js");
|
|
18
20
|
const RETRY_AFTER_HEADER = 'retry-after';
|
|
21
|
+
const isSpentAxis = (axis) => 'limit' in axis;
|
|
19
22
|
let ThrottleGate = class ThrottleGate {
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
+
execute;
|
|
24
|
+
budget;
|
|
25
|
+
moduleReference;
|
|
26
|
+
constructor(execute, budget, moduleReference) {
|
|
27
|
+
this.execute = execute;
|
|
28
|
+
this.budget = budget;
|
|
29
|
+
this.moduleReference = moduleReference;
|
|
23
30
|
}
|
|
24
31
|
async pass(executionContext, axis) {
|
|
25
32
|
const context = axis.readContext(executionContext);
|
|
26
|
-
const decision = await this.decide(axis
|
|
27
|
-
if (
|
|
33
|
+
const decision = await this.decide(axis, context);
|
|
34
|
+
if (decision.allowed) {
|
|
28
35
|
return true;
|
|
29
36
|
}
|
|
30
37
|
void context.reply.header(RETRY_AFTER_HEADER, String(decision.retryAfterSeconds));
|
|
31
38
|
throw axis.createError();
|
|
32
39
|
}
|
|
40
|
+
async decide(axis, context) {
|
|
41
|
+
if (isSpentAxis(axis)) {
|
|
42
|
+
const limit = this.moduleReference.get(axis.limit, { strict: false });
|
|
43
|
+
return this.budget.spend({ key: axis.key(context), limit, refusal: axis.refusal });
|
|
44
|
+
}
|
|
45
|
+
const decision = await this.execute(axis.createCommand(context));
|
|
46
|
+
return { allowed: axis.isAllowed(decision), retryAfterSeconds: decision.retryAfterSeconds };
|
|
47
|
+
}
|
|
33
48
|
};
|
|
34
49
|
exports.ThrottleGate = ThrottleGate;
|
|
35
50
|
exports.ThrottleGate = ThrottleGate = __decorate([
|
|
36
51
|
(0, common_1.Injectable)(),
|
|
37
|
-
__param(0, (0, common_1.Inject)(constants_js_1.
|
|
38
|
-
__metadata("design:paramtypes", [Function
|
|
52
|
+
__param(0, (0, common_1.Inject)(constants_js_1.RATE_LIMIT_EXECUTE)),
|
|
53
|
+
__metadata("design:paramtypes", [Function, throttle_budget_js_1.ThrottleBudget,
|
|
54
|
+
core_1.ModuleRef])
|
|
39
55
|
], ThrottleGate);
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { CallHandler, ExecutionContext, NestInterceptor } from '@nestjs/common';
|
|
2
|
+
import type { Observable } from 'rxjs';
|
|
3
|
+
import { Reflector } from '@nestjs/core';
|
|
4
|
+
import type { ThrottleExecuteFunction } from './throttle-axis.interface.js';
|
|
5
|
+
export declare class ThrottleOutcomeInterceptor implements NestInterceptor {
|
|
6
|
+
private readonly reflector;
|
|
7
|
+
private readonly execute;
|
|
8
|
+
constructor(reflector: Reflector, execute: ThrottleExecuteFunction);
|
|
9
|
+
intercept(executionContext: ExecutionContext, next: CallHandler): Observable<unknown>;
|
|
10
|
+
private register;
|
|
11
|
+
private registerRejection;
|
|
12
|
+
}
|