@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.
Files changed (73) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/LICENSE +21 -0
  3. package/README.md +101 -2
  4. package/dist/cjs/attempt-counter.interface.d.ts +10 -0
  5. package/dist/cjs/attempt-counter.interface.js +2 -0
  6. package/dist/cjs/constants.d.ts +3 -0
  7. package/dist/cjs/constants.js +6 -0
  8. package/dist/cjs/in-memory-attempt-counter.d.ts +9 -0
  9. package/dist/cjs/in-memory-attempt-counter.js +50 -0
  10. package/dist/cjs/index.d.ts +14 -0
  11. package/dist/cjs/index.js +30 -0
  12. package/dist/cjs/package.json +3 -0
  13. package/dist/cjs/rate-limit-logger.d.ts +5 -0
  14. package/dist/cjs/rate-limit-logger.interface.d.ts +3 -0
  15. package/dist/cjs/rate-limit-logger.interface.js +2 -0
  16. package/dist/cjs/rate-limit-logger.js +59 -0
  17. package/dist/cjs/rate-limit.module.d.ts +13 -0
  18. package/dist/cjs/rate-limit.module.js +34 -0
  19. package/dist/cjs/testing/attempt-counter.fake.d.ts +18 -0
  20. package/dist/cjs/testing/attempt-counter.fake.js +34 -0
  21. package/dist/cjs/testing/index.d.ts +1 -0
  22. package/dist/cjs/testing/index.js +17 -0
  23. package/dist/cjs/throttle-axis.d.ts +7 -0
  24. package/dist/cjs/throttle-axis.interface.d.ts +32 -0
  25. package/dist/cjs/throttle-axis.interface.js +2 -0
  26. package/dist/cjs/throttle-axis.js +8 -0
  27. package/dist/cjs/throttle-budget.d.ts +30 -0
  28. package/dist/cjs/throttle-budget.js +47 -0
  29. package/dist/cjs/throttle-gate.d.ts +12 -0
  30. package/dist/cjs/throttle-gate.js +55 -0
  31. package/dist/cjs/throttle-outcome.interceptor.d.ts +12 -0
  32. package/dist/cjs/throttle-outcome.interceptor.js +51 -0
  33. package/dist/cjs/throttle.decorator.d.ts +2 -0
  34. package/dist/cjs/throttle.decorator.js +15 -0
  35. package/dist/cjs/throttle.guard.d.ts +9 -0
  36. package/dist/cjs/throttle.guard.js +33 -0
  37. package/dist/cjs/valkey-attempt-counter.d.ts +16 -0
  38. package/dist/cjs/valkey-attempt-counter.js +50 -0
  39. package/dist/esm/attempt-counter.interface.d.ts +10 -0
  40. package/dist/esm/attempt-counter.interface.js +1 -0
  41. package/dist/esm/constants.d.ts +3 -0
  42. package/dist/esm/constants.js +3 -0
  43. package/dist/esm/in-memory-attempt-counter.d.ts +9 -0
  44. package/dist/esm/in-memory-attempt-counter.js +47 -0
  45. package/dist/esm/index.d.ts +14 -0
  46. package/dist/esm/index.js +14 -0
  47. package/dist/esm/rate-limit-logger.d.ts +5 -0
  48. package/dist/esm/rate-limit-logger.interface.d.ts +3 -0
  49. package/dist/esm/rate-limit-logger.interface.js +1 -0
  50. package/dist/esm/rate-limit-logger.js +23 -0
  51. package/dist/esm/rate-limit.module.d.ts +13 -0
  52. package/dist/esm/rate-limit.module.js +31 -0
  53. package/dist/esm/testing/attempt-counter.fake.d.ts +18 -0
  54. package/dist/esm/testing/attempt-counter.fake.js +30 -0
  55. package/dist/esm/testing/index.d.ts +1 -0
  56. package/dist/esm/testing/index.js +1 -0
  57. package/dist/esm/throttle-axis.d.ts +7 -0
  58. package/dist/esm/throttle-axis.interface.d.ts +32 -0
  59. package/dist/esm/throttle-axis.interface.js +1 -0
  60. package/dist/esm/throttle-axis.js +4 -0
  61. package/dist/esm/throttle-budget.d.ts +30 -0
  62. package/dist/esm/throttle-budget.js +44 -0
  63. package/dist/esm/throttle-gate.d.ts +12 -0
  64. package/dist/esm/throttle-gate.js +52 -0
  65. package/dist/esm/throttle-outcome.interceptor.d.ts +12 -0
  66. package/dist/esm/throttle-outcome.interceptor.js +48 -0
  67. package/dist/esm/throttle.decorator.d.ts +2 -0
  68. package/dist/esm/throttle.decorator.js +11 -0
  69. package/dist/esm/throttle.guard.d.ts +9 -0
  70. package/dist/esm/throttle.guard.js +30 -0
  71. package/dist/esm/valkey-attempt-counter.d.ts +16 -0
  72. package/dist/esm/valkey-attempt-counter.js +46 -0
  73. package/package.json +87 -3
@@ -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
+ }
@@ -0,0 +1,52 @@
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 { ModuleRef } from '@nestjs/core';
15
+ import { RATE_LIMIT_EXECUTE } from './constants.js';
16
+ import { ThrottleBudget } from './throttle-budget.js';
17
+ const RETRY_AFTER_HEADER = 'retry-after';
18
+ const isSpentAxis = (axis) => 'limit' in axis;
19
+ let ThrottleGate = class ThrottleGate {
20
+ execute;
21
+ budget;
22
+ moduleReference;
23
+ constructor(execute, budget, moduleReference) {
24
+ this.execute = execute;
25
+ this.budget = budget;
26
+ this.moduleReference = moduleReference;
27
+ }
28
+ async pass(executionContext, axis) {
29
+ const context = axis.readContext(executionContext);
30
+ const decision = await this.decide(axis, context);
31
+ if (decision.allowed) {
32
+ return true;
33
+ }
34
+ void context.reply.header(RETRY_AFTER_HEADER, String(decision.retryAfterSeconds));
35
+ throw axis.createError();
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
+ }
45
+ };
46
+ ThrottleGate = __decorate([
47
+ Injectable(),
48
+ __param(0, Inject(RATE_LIMIT_EXECUTE)),
49
+ __metadata("design:paramtypes", [Function, ThrottleBudget,
50
+ ModuleRef])
51
+ ], ThrottleGate);
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 };
@@ -0,0 +1,16 @@
1
+ import type { OnApplicationShutdown } from '@nestjs/common';
2
+ import type { Option } from 'oxide.ts';
3
+ import type { AttemptCounterInterface, AttemptWindowInterface } from './attempt-counter.interface.js';
4
+ export interface ValkeyCommandsInterface {
5
+ del(key: string): Promise<number>;
6
+ disconnect(): void;
7
+ eval(script: string, numberOfKeys: number, ...parameters: (number | string)[]): Promise<unknown>;
8
+ }
9
+ export declare class ValkeyAttemptCounter implements AttemptCounterInterface, OnApplicationShutdown {
10
+ private readonly client;
11
+ constructor(client: ValkeyCommandsInterface);
12
+ increment(key: string, windowSeconds: number): Promise<AttemptWindowInterface>;
13
+ onApplicationShutdown(): void;
14
+ read(key: string): Promise<Option<AttemptWindowInterface>>;
15
+ reset(key: string): Promise<void>;
16
+ }
@@ -0,0 +1,46 @@
1
+ import { None, Some } from 'oxide.ts';
2
+ const MILLISECONDS_IN_SECOND = 1000;
3
+ const INCREMENT_SCRIPT = `
4
+ local count = redis.call('INCR', KEYS[1])
5
+ if count == 1 or redis.call('PTTL', KEYS[1]) == -1 then
6
+ redis.call('PEXPIRE', KEYS[1], ARGV[1])
7
+ end
8
+ return {count, redis.call('PTTL', KEYS[1])}
9
+ `;
10
+ const READ_SCRIPT = `
11
+ local count = redis.call('GET', KEYS[1])
12
+ if not count then
13
+ return {0, -2}
14
+ end
15
+ return {tonumber(count), redis.call('PTTL', KEYS[1])}
16
+ `;
17
+ const isWindowReply = (reply) => Array.isArray(reply)
18
+ && reply.length === 2
19
+ && reply.every((item) => typeof item === 'number');
20
+ const toWindow = (reply) => {
21
+ if (!isWindowReply(reply)) {
22
+ throw new TypeError(`Unexpected attempt counter reply: ${JSON.stringify(reply)}`);
23
+ }
24
+ const [count, ttlMs] = reply;
25
+ return { count, retryAfterSeconds: Math.ceil(ttlMs / MILLISECONDS_IN_SECOND) };
26
+ };
27
+ export class ValkeyAttemptCounter {
28
+ client;
29
+ constructor(client) {
30
+ this.client = client;
31
+ }
32
+ async increment(key, windowSeconds) {
33
+ const reply = await this.client.eval(INCREMENT_SCRIPT, 1, key, windowSeconds * MILLISECONDS_IN_SECOND);
34
+ return toWindow(reply);
35
+ }
36
+ onApplicationShutdown() {
37
+ this.client.disconnect();
38
+ }
39
+ async read(key) {
40
+ const window = toWindow(await this.client.eval(READ_SCRIPT, 1, key));
41
+ return window.retryAfterSeconds > 0 ? Some(window) : None;
42
+ }
43
+ async reset(key) {
44
+ await this.client.del(key);
45
+ }
46
+ }
package/package.json CHANGED
@@ -1,6 +1,90 @@
1
1
  {
2
2
  "name": "@application-kit/rate-limit",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.2.0",
4
+ "description": "Частотная защита для NestJS: счётчик попыток с окном (память и Valkey с атомарным Lua), бюджет попыток и gate с Retry-After",
5
+ "keywords": [
6
+ "nestjs",
7
+ "rate-limit",
8
+ "throttle",
9
+ "valkey"
10
+ ],
11
+ "homepage": "https://gitlab.com/application-kit/application-kit/-/tree/main/packages/rate-limit",
12
+ "bugs": "https://gitlab.com/application-kit/application-kit/-/issues",
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "https://gitlab.com/application-kit/application-kit.git",
16
+ "directory": "packages/rate-limit"
17
+ },
18
+ "license": "MIT",
19
+ "author": {
20
+ "name": "application-kit"
21
+ },
22
+ "sideEffects": false,
23
+ "type": "module",
24
+ "exports": {
25
+ ".": {
26
+ "import": {
27
+ "types": "./dist/esm/index.d.ts",
28
+ "default": "./dist/esm/index.js"
29
+ },
30
+ "require": {
31
+ "types": "./dist/cjs/index.d.ts",
32
+ "default": "./dist/cjs/index.js"
33
+ }
34
+ },
35
+ "./package.json": "./package.json",
36
+ "./testing": {
37
+ "import": {
38
+ "types": "./dist/esm/testing/index.d.ts",
39
+ "default": "./dist/esm/testing/index.js"
40
+ },
41
+ "require": {
42
+ "types": "./dist/cjs/testing/index.d.ts",
43
+ "default": "./dist/cjs/testing/index.js"
44
+ }
45
+ }
46
+ },
47
+ "main": "./dist/cjs/index.js",
48
+ "module": "./dist/esm/index.js",
49
+ "types": "./dist/cjs/index.d.ts",
50
+ "files": [
51
+ "dist"
52
+ ],
53
+ "scripts": {
54
+ "build": "rm -rf ./dist && node ../../scripts/barrels.mjs create ./src --entry-only=testing && tsc --project tsconfig.build.json && tsc --project tsconfig.build.cjs.json && node ../../scripts/barrels.mjs clean ./src && node ../../scripts/mark-cjs.mjs ./dist/cjs",
55
+ "lint:tsc": "tsc --noEmit --pretty --project .",
56
+ "test:mutation": "stryker run",
57
+ "test:unit": "vitest run"
58
+ },
59
+ "devDependencies": {
60
+ "@nestjs/common": "^11.2.7",
61
+ "@nestjs/core": "^11.2.7",
62
+ "@nestjs/testing": "^11.2.7",
63
+ "@stryker-mutator/core": "^10.0.0",
64
+ "@stryker-mutator/vitest-runner": "^10.0.0",
65
+ "@types/node": "^26.2.0",
66
+ "iovalkey": "^0.4.0",
67
+ "nestjs-pino": "^4.6.1",
68
+ "oxide.ts": "^1.1.0",
69
+ "pino": "^10.3.1",
70
+ "pino-http": "^11.0.0",
71
+ "reflect-metadata": "^0.2.2",
72
+ "rxjs": "^7.8.2",
73
+ "testcontainers": "12.1.0",
74
+ "typescript": "^6.0.3",
75
+ "vitest": "^4.1.11"
76
+ },
77
+ "peerDependencies": {
78
+ "@nestjs/common": "^11.0.0",
79
+ "@nestjs/core": "^11.0.0",
80
+ "nestjs-pino": "^4.6.1",
81
+ "oxide.ts": "^1.1.0",
82
+ "rxjs": "^7.8.0"
83
+ },
84
+ "engines": {
85
+ "node": ">=24"
86
+ },
87
+ "publishConfig": {
88
+ "access": "public"
89
+ }
6
90
  }