@application-kit/rate-limit 0.1.0 → 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 +11 -0
- package/README.md +39 -8
- package/dist/cjs/constants.d.ts +1 -1
- package/dist/cjs/constants.js +2 -2
- package/dist/cjs/index.d.ts +5 -0
- package/dist/cjs/index.js +5 -0
- package/dist/cjs/rate-limit.module.d.ts +2 -2
- package/dist/cjs/rate-limit.module.js +2 -2
- 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/constants.d.ts +1 -1
- package/dist/esm/constants.js +1 -1
- package/dist/esm/index.d.ts +5 -0
- package/dist/esm/index.js +5 -0
- package/dist/esm/rate-limit.module.d.ts +2 -2
- package/dist/esm/rate-limit.module.js +3 -3
- 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 +4 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,16 @@
|
|
|
1
1
|
# @application-kit/rate-limit
|
|
2
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
|
+
|
|
3
14
|
## 0.1.0
|
|
4
15
|
|
|
5
16
|
### Minor Changes
|
package/README.md
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
yarn add @application-kit/rate-limit
|
|
10
10
|
```
|
|
11
11
|
|
|
12
|
-
Peer-зависимости: `@nestjs/common`, `nestjs-pino`, `oxide.ts`. Клиент Valkey пакет не импортирует — его собирает
|
|
12
|
+
Peer-зависимости: `@nestjs/common`, `@nestjs/core`, `nestjs-pino`, `oxide.ts`, `rxjs`. Клиент Valkey пакет не импортирует — его собирает
|
|
13
13
|
приложение из своего конфига и отдаёт готовым экземпляром.
|
|
14
14
|
|
|
15
15
|
## Подключение
|
|
@@ -25,8 +25,8 @@ RateLimitModule.forRootAsync({
|
|
|
25
25
|
? new ValkeyAttemptCounter(createValkeyClient(config))
|
|
26
26
|
: new InMemoryAttemptCounter()),
|
|
27
27
|
},
|
|
28
|
-
// Исполнитель
|
|
29
|
-
|
|
28
|
+
// Исполнитель команд оси — решения и исхода: обычно — шина команд приложения.
|
|
29
|
+
execute: {
|
|
30
30
|
inject: [CommandBus],
|
|
31
31
|
useFactory: (commandBus: CommandBus) => async (command: object) => commandBus.execute(command),
|
|
32
32
|
},
|
|
@@ -34,7 +34,8 @@ RateLimitModule.forRootAsync({
|
|
|
34
34
|
})
|
|
35
35
|
```
|
|
36
36
|
|
|
37
|
-
Модуль экспортирует
|
|
37
|
+
Модуль экспортирует токены счётчика и исполнителя (`RATE_LIMIT_COUNTER`, `RATE_LIMIT_EXECUTE`), `ThrottleBudget` и
|
|
38
|
+
`ThrottleGate`: модуль ручки обязан их видеть — guard и интерцептор оси создаются там. Логгер отказов
|
|
38
39
|
(`RATE_LIMIT_LOGGER`, `RateLimitLogger`) модуль связывает сам — нужен глобальный `LoggerModule` из `nestjs-pino`.
|
|
39
40
|
|
|
40
41
|
## Счётчик
|
|
@@ -56,11 +57,41 @@ RateLimitModule.forRootAsync({
|
|
|
56
57
|
Отказ пишется в лог одной записью `{ retryAfterSeconds, securityEvent }` с сообщением `refusal.message` — без ключа
|
|
57
58
|
и идентификаторов.
|
|
58
59
|
|
|
59
|
-
##
|
|
60
|
+
## Ось
|
|
60
61
|
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
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` считает её потраченной попыткой; ошибка ручки уходит дальше без изменений.
|
|
64
95
|
|
|
65
96
|
## Спеки потребителя
|
|
66
97
|
|
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');
|
package/dist/cjs/index.d.ts
CHANGED
|
@@ -4,6 +4,11 @@ export * from './in-memory-attempt-counter.js';
|
|
|
4
4
|
export * from './rate-limit-logger.js';
|
|
5
5
|
export * from './rate-limit-logger.interface.js';
|
|
6
6
|
export * from './rate-limit.module.js';
|
|
7
|
+
export * from './throttle-axis.js';
|
|
8
|
+
export * from './throttle-axis.interface.js';
|
|
7
9
|
export * from './throttle-budget.js';
|
|
8
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';
|
|
9
14
|
export * from './valkey-attempt-counter.js';
|
package/dist/cjs/index.js
CHANGED
|
@@ -20,6 +20,11 @@ __exportStar(require("./in-memory-attempt-counter.js"), exports);
|
|
|
20
20
|
__exportStar(require("./rate-limit-logger.js"), exports);
|
|
21
21
|
__exportStar(require("./rate-limit-logger.interface.js"), exports);
|
|
22
22
|
__exportStar(require("./rate-limit.module.js"), exports);
|
|
23
|
+
__exportStar(require("./throttle-axis.js"), exports);
|
|
24
|
+
__exportStar(require("./throttle-axis.interface.js"), exports);
|
|
23
25
|
__exportStar(require("./throttle-budget.js"), exports);
|
|
24
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);
|
|
25
30
|
__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
5
|
readonly counter: FactoryOptions<AttemptCounterInterface>;
|
|
6
|
-
readonly
|
|
6
|
+
readonly execute: FactoryOptions<ThrottleExecuteFunction>;
|
|
7
7
|
readonly imports?: ModuleMetadata['imports'];
|
|
8
8
|
}
|
|
9
9
|
type FactoryOptions<T> = Omit<FactoryProvider<T>, 'provide'>;
|
|
@@ -15,12 +15,12 @@ const throttle_gate_js_1 = require("./throttle-gate.js");
|
|
|
15
15
|
let RateLimitModule = class RateLimitModule {
|
|
16
16
|
static forRootAsync(options) {
|
|
17
17
|
return {
|
|
18
|
-
exports: [constants_js_1.RATE_LIMIT_COUNTER, throttle_budget_js_1.ThrottleBudget, throttle_gate_js_1.ThrottleGate],
|
|
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
19
|
imports: options.imports ?? [],
|
|
20
20
|
module: this,
|
|
21
21
|
providers: [
|
|
22
22
|
{ ...options.counter, provide: constants_js_1.RATE_LIMIT_COUNTER },
|
|
23
|
-
{ ...options.
|
|
23
|
+
{ ...options.execute, provide: constants_js_1.RATE_LIMIT_EXECUTE },
|
|
24
24
|
{ provide: constants_js_1.RATE_LIMIT_LOGGER, useClass: rate_limit_logger_js_1.RateLimitLogger },
|
|
25
25
|
throttle_budget_js_1.ThrottleBudget,
|
|
26
26
|
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
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
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.ThrottleOutcomeInterceptor = void 0;
|
|
16
|
+
const common_1 = require("@nestjs/common");
|
|
17
|
+
const core_1 = require("@nestjs/core");
|
|
18
|
+
const rxjs_1 = require("rxjs");
|
|
19
|
+
const constants_js_1 = require("./constants.js");
|
|
20
|
+
const throttle_axis_js_1 = require("./throttle-axis.js");
|
|
21
|
+
let ThrottleOutcomeInterceptor = class ThrottleOutcomeInterceptor {
|
|
22
|
+
reflector;
|
|
23
|
+
execute;
|
|
24
|
+
constructor(reflector, execute) {
|
|
25
|
+
this.reflector = reflector;
|
|
26
|
+
this.execute = execute;
|
|
27
|
+
}
|
|
28
|
+
intercept(executionContext, next) {
|
|
29
|
+
const axis = this.reflector.get(throttle_axis_js_1.ThrottleOutcomeMetadata, executionContext.getHandler());
|
|
30
|
+
const context = axis.readContext(executionContext);
|
|
31
|
+
return next.handle().pipe((0, rxjs_1.concatMap)(async (answer) => {
|
|
32
|
+
await this.register(axis, context, true);
|
|
33
|
+
return answer;
|
|
34
|
+
}), (0, rxjs_1.catchError)((error) => (0, rxjs_1.from)(this.registerRejection(axis, context, error))));
|
|
35
|
+
}
|
|
36
|
+
async register(axis, context, didSucceed) {
|
|
37
|
+
await this.execute(axis.outcome.createCommand(context, didSucceed));
|
|
38
|
+
}
|
|
39
|
+
async registerRejection(axis, context, error) {
|
|
40
|
+
if (axis.outcome.isAttemptSpent(error)) {
|
|
41
|
+
await this.register(axis, context, false);
|
|
42
|
+
}
|
|
43
|
+
throw error;
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
exports.ThrottleOutcomeInterceptor = ThrottleOutcomeInterceptor;
|
|
47
|
+
exports.ThrottleOutcomeInterceptor = ThrottleOutcomeInterceptor = __decorate([
|
|
48
|
+
(0, common_1.Injectable)(),
|
|
49
|
+
__param(1, (0, common_1.Inject)(constants_js_1.RATE_LIMIT_EXECUTE)),
|
|
50
|
+
__metadata("design:paramtypes", [core_1.Reflector, Function])
|
|
51
|
+
], ThrottleOutcomeInterceptor);
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import type { ThrottleAxisInterface, ThrottleGateDecisionInterface, ThrottleGuardContextInterface } from './throttle-axis.interface.js';
|
|
2
|
+
export declare const Throttle: <TContext extends ThrottleGuardContextInterface, TDecision extends ThrottleGateDecisionInterface>(axis: ThrottleAxisInterface<TContext, TDecision>) => MethodDecorator;
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.Throttle = void 0;
|
|
4
|
+
const common_1 = require("@nestjs/common");
|
|
5
|
+
const throttle_axis_js_1 = require("./throttle-axis.js");
|
|
6
|
+
const throttle_outcome_interceptor_js_1 = require("./throttle-outcome.interceptor.js");
|
|
7
|
+
const throttle_guard_js_1 = require("./throttle.guard.js");
|
|
8
|
+
const Throttle = (axis) => {
|
|
9
|
+
const decorators = [(0, throttle_axis_js_1.ThrottleAxisMetadata)(axis), (0, common_1.UseGuards)(throttle_guard_js_1.ThrottleGuard)];
|
|
10
|
+
if ('outcome' in axis) {
|
|
11
|
+
decorators.push((0, throttle_axis_js_1.ThrottleOutcomeMetadata)({ outcome: axis.outcome, readContext: (context) => axis.readContext(context) }), (0, common_1.UseInterceptors)(throttle_outcome_interceptor_js_1.ThrottleOutcomeInterceptor));
|
|
12
|
+
}
|
|
13
|
+
return (0, common_1.applyDecorators)(...decorators);
|
|
14
|
+
};
|
|
15
|
+
exports.Throttle = Throttle;
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { CanActivate, ExecutionContext } from '@nestjs/common';
|
|
2
|
+
import { Reflector } from '@nestjs/core';
|
|
3
|
+
import { ThrottleGate } from './throttle-gate.js';
|
|
4
|
+
export declare class ThrottleGuard implements CanActivate {
|
|
5
|
+
private readonly reflector;
|
|
6
|
+
private readonly gate;
|
|
7
|
+
constructor(reflector: Reflector, gate: ThrottleGate);
|
|
8
|
+
canActivate(context: ExecutionContext): Promise<boolean>;
|
|
9
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
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.ThrottleGuard = void 0;
|
|
13
|
+
const common_1 = require("@nestjs/common");
|
|
14
|
+
const core_1 = require("@nestjs/core");
|
|
15
|
+
const throttle_axis_js_1 = require("./throttle-axis.js");
|
|
16
|
+
const throttle_gate_js_1 = require("./throttle-gate.js");
|
|
17
|
+
let ThrottleGuard = class ThrottleGuard {
|
|
18
|
+
reflector;
|
|
19
|
+
gate;
|
|
20
|
+
constructor(reflector, gate) {
|
|
21
|
+
this.reflector = reflector;
|
|
22
|
+
this.gate = gate;
|
|
23
|
+
}
|
|
24
|
+
async canActivate(context) {
|
|
25
|
+
return this.gate.pass(context, this.reflector.get(throttle_axis_js_1.ThrottleAxisMetadata, context.getHandler()));
|
|
26
|
+
}
|
|
27
|
+
};
|
|
28
|
+
exports.ThrottleGuard = ThrottleGuard;
|
|
29
|
+
exports.ThrottleGuard = ThrottleGuard = __decorate([
|
|
30
|
+
(0, common_1.Injectable)(),
|
|
31
|
+
__metadata("design:paramtypes", [core_1.Reflector,
|
|
32
|
+
throttle_gate_js_1.ThrottleGate])
|
|
33
|
+
], ThrottleGuard);
|
package/dist/esm/constants.d.ts
CHANGED
package/dist/esm/constants.js
CHANGED
package/dist/esm/index.d.ts
CHANGED
|
@@ -4,6 +4,11 @@ export * from './in-memory-attempt-counter.js';
|
|
|
4
4
|
export * from './rate-limit-logger.js';
|
|
5
5
|
export * from './rate-limit-logger.interface.js';
|
|
6
6
|
export * from './rate-limit.module.js';
|
|
7
|
+
export * from './throttle-axis.js';
|
|
8
|
+
export * from './throttle-axis.interface.js';
|
|
7
9
|
export * from './throttle-budget.js';
|
|
8
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';
|
|
9
14
|
export * from './valkey-attempt-counter.js';
|
package/dist/esm/index.js
CHANGED
|
@@ -4,6 +4,11 @@ export * from './in-memory-attempt-counter.js';
|
|
|
4
4
|
export * from './rate-limit-logger.js';
|
|
5
5
|
export * from './rate-limit-logger.interface.js';
|
|
6
6
|
export * from './rate-limit.module.js';
|
|
7
|
+
export * from './throttle-axis.js';
|
|
8
|
+
export * from './throttle-axis.interface.js';
|
|
7
9
|
export * from './throttle-budget.js';
|
|
8
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';
|
|
9
14
|
export * from './valkey-attempt-counter.js';
|
|
@@ -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
5
|
readonly counter: FactoryOptions<AttemptCounterInterface>;
|
|
6
|
-
readonly
|
|
6
|
+
readonly execute: FactoryOptions<ThrottleExecuteFunction>;
|
|
7
7
|
readonly imports?: ModuleMetadata['imports'];
|
|
8
8
|
}
|
|
9
9
|
type FactoryOptions<T> = Omit<FactoryProvider<T>, 'provide'>;
|
|
@@ -5,19 +5,19 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
|
|
|
5
5
|
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
6
6
|
};
|
|
7
7
|
import { Module } from '@nestjs/common';
|
|
8
|
-
import { RATE_LIMIT_COUNTER,
|
|
8
|
+
import { RATE_LIMIT_COUNTER, RATE_LIMIT_EXECUTE, RATE_LIMIT_LOGGER } from './constants.js';
|
|
9
9
|
import { RateLimitLogger } from './rate-limit-logger.js';
|
|
10
10
|
import { ThrottleBudget } from './throttle-budget.js';
|
|
11
11
|
import { ThrottleGate } from './throttle-gate.js';
|
|
12
12
|
let RateLimitModule = class RateLimitModule {
|
|
13
13
|
static forRootAsync(options) {
|
|
14
14
|
return {
|
|
15
|
-
exports: [RATE_LIMIT_COUNTER, ThrottleBudget, ThrottleGate],
|
|
15
|
+
exports: [RATE_LIMIT_COUNTER, RATE_LIMIT_EXECUTE, ThrottleBudget, ThrottleGate],
|
|
16
16
|
imports: options.imports ?? [],
|
|
17
17
|
module: this,
|
|
18
18
|
providers: [
|
|
19
19
|
{ ...options.counter, provide: RATE_LIMIT_COUNTER },
|
|
20
|
-
{ ...options.
|
|
20
|
+
{ ...options.execute, provide: RATE_LIMIT_EXECUTE },
|
|
21
21
|
{ provide: RATE_LIMIT_LOGGER, useClass: RateLimitLogger },
|
|
22
22
|
ThrottleBudget,
|
|
23
23
|
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 @@
|
|
|
1
|
+
export {};
|
|
@@ -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
|
}
|
|
@@ -11,26 +11,42 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
|
11
11
|
return function (target, key) { decorator(target, key, paramIndex); }
|
|
12
12
|
};
|
|
13
13
|
import { Inject, Injectable } from '@nestjs/common';
|
|
14
|
-
import {
|
|
14
|
+
import { ModuleRef } from '@nestjs/core';
|
|
15
|
+
import { RATE_LIMIT_EXECUTE } from './constants.js';
|
|
16
|
+
import { ThrottleBudget } from './throttle-budget.js';
|
|
15
17
|
const RETRY_AFTER_HEADER = 'retry-after';
|
|
18
|
+
const isSpentAxis = (axis) => 'limit' in axis;
|
|
16
19
|
let ThrottleGate = class ThrottleGate {
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
+
execute;
|
|
21
|
+
budget;
|
|
22
|
+
moduleReference;
|
|
23
|
+
constructor(execute, budget, moduleReference) {
|
|
24
|
+
this.execute = execute;
|
|
25
|
+
this.budget = budget;
|
|
26
|
+
this.moduleReference = moduleReference;
|
|
20
27
|
}
|
|
21
28
|
async pass(executionContext, axis) {
|
|
22
29
|
const context = axis.readContext(executionContext);
|
|
23
|
-
const decision = await this.decide(axis
|
|
24
|
-
if (
|
|
30
|
+
const decision = await this.decide(axis, context);
|
|
31
|
+
if (decision.allowed) {
|
|
25
32
|
return true;
|
|
26
33
|
}
|
|
27
34
|
void context.reply.header(RETRY_AFTER_HEADER, String(decision.retryAfterSeconds));
|
|
28
35
|
throw axis.createError();
|
|
29
36
|
}
|
|
37
|
+
async decide(axis, context) {
|
|
38
|
+
if (isSpentAxis(axis)) {
|
|
39
|
+
const limit = this.moduleReference.get(axis.limit, { strict: false });
|
|
40
|
+
return this.budget.spend({ key: axis.key(context), limit, refusal: axis.refusal });
|
|
41
|
+
}
|
|
42
|
+
const decision = await this.execute(axis.createCommand(context));
|
|
43
|
+
return { allowed: axis.isAllowed(decision), retryAfterSeconds: decision.retryAfterSeconds };
|
|
44
|
+
}
|
|
30
45
|
};
|
|
31
46
|
ThrottleGate = __decorate([
|
|
32
47
|
Injectable(),
|
|
33
|
-
__param(0, Inject(
|
|
34
|
-
__metadata("design:paramtypes", [Function
|
|
48
|
+
__param(0, Inject(RATE_LIMIT_EXECUTE)),
|
|
49
|
+
__metadata("design:paramtypes", [Function, ThrottleBudget,
|
|
50
|
+
ModuleRef])
|
|
35
51
|
], ThrottleGate);
|
|
36
52
|
export { 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
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
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 { Reflector } from '@nestjs/core';
|
|
15
|
+
import { catchError, concatMap, from } from 'rxjs';
|
|
16
|
+
import { RATE_LIMIT_EXECUTE } from './constants.js';
|
|
17
|
+
import { ThrottleOutcomeMetadata } from './throttle-axis.js';
|
|
18
|
+
let ThrottleOutcomeInterceptor = class ThrottleOutcomeInterceptor {
|
|
19
|
+
reflector;
|
|
20
|
+
execute;
|
|
21
|
+
constructor(reflector, execute) {
|
|
22
|
+
this.reflector = reflector;
|
|
23
|
+
this.execute = execute;
|
|
24
|
+
}
|
|
25
|
+
intercept(executionContext, next) {
|
|
26
|
+
const axis = this.reflector.get(ThrottleOutcomeMetadata, executionContext.getHandler());
|
|
27
|
+
const context = axis.readContext(executionContext);
|
|
28
|
+
return next.handle().pipe(concatMap(async (answer) => {
|
|
29
|
+
await this.register(axis, context, true);
|
|
30
|
+
return answer;
|
|
31
|
+
}), catchError((error) => from(this.registerRejection(axis, context, error))));
|
|
32
|
+
}
|
|
33
|
+
async register(axis, context, didSucceed) {
|
|
34
|
+
await this.execute(axis.outcome.createCommand(context, didSucceed));
|
|
35
|
+
}
|
|
36
|
+
async registerRejection(axis, context, error) {
|
|
37
|
+
if (axis.outcome.isAttemptSpent(error)) {
|
|
38
|
+
await this.register(axis, context, false);
|
|
39
|
+
}
|
|
40
|
+
throw error;
|
|
41
|
+
}
|
|
42
|
+
};
|
|
43
|
+
ThrottleOutcomeInterceptor = __decorate([
|
|
44
|
+
Injectable(),
|
|
45
|
+
__param(1, Inject(RATE_LIMIT_EXECUTE)),
|
|
46
|
+
__metadata("design:paramtypes", [Reflector, Function])
|
|
47
|
+
], ThrottleOutcomeInterceptor);
|
|
48
|
+
export { ThrottleOutcomeInterceptor };
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import type { ThrottleAxisInterface, ThrottleGateDecisionInterface, ThrottleGuardContextInterface } from './throttle-axis.interface.js';
|
|
2
|
+
export declare const Throttle: <TContext extends ThrottleGuardContextInterface, TDecision extends ThrottleGateDecisionInterface>(axis: ThrottleAxisInterface<TContext, TDecision>) => MethodDecorator;
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { applyDecorators, UseGuards, UseInterceptors } from '@nestjs/common';
|
|
2
|
+
import { ThrottleAxisMetadata, ThrottleOutcomeMetadata } from './throttle-axis.js';
|
|
3
|
+
import { ThrottleOutcomeInterceptor } from './throttle-outcome.interceptor.js';
|
|
4
|
+
import { ThrottleGuard } from './throttle.guard.js';
|
|
5
|
+
export const Throttle = (axis) => {
|
|
6
|
+
const decorators = [ThrottleAxisMetadata(axis), UseGuards(ThrottleGuard)];
|
|
7
|
+
if ('outcome' in axis) {
|
|
8
|
+
decorators.push(ThrottleOutcomeMetadata({ outcome: axis.outcome, readContext: (context) => axis.readContext(context) }), UseInterceptors(ThrottleOutcomeInterceptor));
|
|
9
|
+
}
|
|
10
|
+
return applyDecorators(...decorators);
|
|
11
|
+
};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { CanActivate, ExecutionContext } from '@nestjs/common';
|
|
2
|
+
import { Reflector } from '@nestjs/core';
|
|
3
|
+
import { ThrottleGate } from './throttle-gate.js';
|
|
4
|
+
export declare class ThrottleGuard implements CanActivate {
|
|
5
|
+
private readonly reflector;
|
|
6
|
+
private readonly gate;
|
|
7
|
+
constructor(reflector: Reflector, gate: ThrottleGate);
|
|
8
|
+
canActivate(context: ExecutionContext): Promise<boolean>;
|
|
9
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
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
|
+
import { Injectable } from '@nestjs/common';
|
|
11
|
+
import { Reflector } from '@nestjs/core';
|
|
12
|
+
import { ThrottleAxisMetadata } from './throttle-axis.js';
|
|
13
|
+
import { ThrottleGate } from './throttle-gate.js';
|
|
14
|
+
let ThrottleGuard = class ThrottleGuard {
|
|
15
|
+
reflector;
|
|
16
|
+
gate;
|
|
17
|
+
constructor(reflector, gate) {
|
|
18
|
+
this.reflector = reflector;
|
|
19
|
+
this.gate = gate;
|
|
20
|
+
}
|
|
21
|
+
async canActivate(context) {
|
|
22
|
+
return this.gate.pass(context, this.reflector.get(ThrottleAxisMetadata, context.getHandler()));
|
|
23
|
+
}
|
|
24
|
+
};
|
|
25
|
+
ThrottleGuard = __decorate([
|
|
26
|
+
Injectable(),
|
|
27
|
+
__metadata("design:paramtypes", [Reflector,
|
|
28
|
+
ThrottleGate])
|
|
29
|
+
], ThrottleGuard);
|
|
30
|
+
export { ThrottleGuard };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@application-kit/rate-limit",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "Частотная защита для NestJS: счётчик попыток с окном (память и Valkey с атомарным Lua), бюджет попыток и gate с Retry-After",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"nestjs",
|
|
@@ -76,8 +76,10 @@
|
|
|
76
76
|
},
|
|
77
77
|
"peerDependencies": {
|
|
78
78
|
"@nestjs/common": "^11.0.0",
|
|
79
|
+
"@nestjs/core": "^11.0.0",
|
|
79
80
|
"nestjs-pino": "^4.6.1",
|
|
80
|
-
"oxide.ts": "^1.1.0"
|
|
81
|
+
"oxide.ts": "^1.1.0",
|
|
82
|
+
"rxjs": "^7.8.0"
|
|
81
83
|
},
|
|
82
84
|
"engines": {
|
|
83
85
|
"node": ">=24"
|