@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,55 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
12
+ return function (target, key) { decorator(target, key, paramIndex); }
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.ThrottleGate = void 0;
16
+ const common_1 = require("@nestjs/common");
17
+ const core_1 = require("@nestjs/core");
18
+ const constants_js_1 = require("./constants.js");
19
+ const throttle_budget_js_1 = require("./throttle-budget.js");
20
+ const RETRY_AFTER_HEADER = 'retry-after';
21
+ const isSpentAxis = (axis) => 'limit' in axis;
22
+ let ThrottleGate = class ThrottleGate {
23
+ execute;
24
+ budget;
25
+ moduleReference;
26
+ constructor(execute, budget, moduleReference) {
27
+ this.execute = execute;
28
+ this.budget = budget;
29
+ this.moduleReference = moduleReference;
30
+ }
31
+ async pass(executionContext, axis) {
32
+ const context = axis.readContext(executionContext);
33
+ const decision = await this.decide(axis, context);
34
+ if (decision.allowed) {
35
+ return true;
36
+ }
37
+ void context.reply.header(RETRY_AFTER_HEADER, String(decision.retryAfterSeconds));
38
+ throw axis.createError();
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
+ }
48
+ };
49
+ exports.ThrottleGate = ThrottleGate;
50
+ exports.ThrottleGate = ThrottleGate = __decorate([
51
+ (0, common_1.Injectable)(),
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])
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);
@@ -0,0 +1,16 @@
1
+ import type { OnApplicationShutdown } from '@nestjs/common';
2
+ import type { Option } from 'oxide.ts';
3
+ import type { AttemptCounterInterface, AttemptWindowInterface } from './attempt-counter.interface.js';
4
+ export interface ValkeyCommandsInterface {
5
+ del(key: string): Promise<number>;
6
+ disconnect(): void;
7
+ eval(script: string, numberOfKeys: number, ...parameters: (number | string)[]): Promise<unknown>;
8
+ }
9
+ export declare class ValkeyAttemptCounter implements AttemptCounterInterface, OnApplicationShutdown {
10
+ private readonly client;
11
+ constructor(client: ValkeyCommandsInterface);
12
+ increment(key: string, windowSeconds: number): Promise<AttemptWindowInterface>;
13
+ onApplicationShutdown(): void;
14
+ read(key: string): Promise<Option<AttemptWindowInterface>>;
15
+ reset(key: string): Promise<void>;
16
+ }
@@ -0,0 +1,50 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ValkeyAttemptCounter = void 0;
4
+ const oxide_ts_1 = require("oxide.ts");
5
+ const MILLISECONDS_IN_SECOND = 1000;
6
+ const INCREMENT_SCRIPT = `
7
+ local count = redis.call('INCR', KEYS[1])
8
+ if count == 1 or redis.call('PTTL', KEYS[1]) == -1 then
9
+ redis.call('PEXPIRE', KEYS[1], ARGV[1])
10
+ end
11
+ return {count, redis.call('PTTL', KEYS[1])}
12
+ `;
13
+ const READ_SCRIPT = `
14
+ local count = redis.call('GET', KEYS[1])
15
+ if not count then
16
+ return {0, -2}
17
+ end
18
+ return {tonumber(count), redis.call('PTTL', KEYS[1])}
19
+ `;
20
+ const isWindowReply = (reply) => Array.isArray(reply)
21
+ && reply.length === 2
22
+ && reply.every((item) => typeof item === 'number');
23
+ const toWindow = (reply) => {
24
+ if (!isWindowReply(reply)) {
25
+ throw new TypeError(`Unexpected attempt counter reply: ${JSON.stringify(reply)}`);
26
+ }
27
+ const [count, ttlMs] = reply;
28
+ return { count, retryAfterSeconds: Math.ceil(ttlMs / MILLISECONDS_IN_SECOND) };
29
+ };
30
+ class ValkeyAttemptCounter {
31
+ client;
32
+ constructor(client) {
33
+ this.client = client;
34
+ }
35
+ async increment(key, windowSeconds) {
36
+ const reply = await this.client.eval(INCREMENT_SCRIPT, 1, key, windowSeconds * MILLISECONDS_IN_SECOND);
37
+ return toWindow(reply);
38
+ }
39
+ onApplicationShutdown() {
40
+ this.client.disconnect();
41
+ }
42
+ async read(key) {
43
+ const window = toWindow(await this.client.eval(READ_SCRIPT, 1, key));
44
+ return window.retryAfterSeconds > 0 ? (0, oxide_ts_1.Some)(window) : oxide_ts_1.None;
45
+ }
46
+ async reset(key) {
47
+ await this.client.del(key);
48
+ }
49
+ }
50
+ exports.ValkeyAttemptCounter = ValkeyAttemptCounter;
@@ -0,0 +1,10 @@
1
+ import type { Option } from 'oxide.ts';
2
+ export interface AttemptCounterInterface {
3
+ increment(key: string, windowSeconds: number): Promise<AttemptWindowInterface>;
4
+ read(key: string): Promise<Option<AttemptWindowInterface>>;
5
+ reset(key: string): Promise<void>;
6
+ }
7
+ export interface AttemptWindowInterface {
8
+ count: number;
9
+ retryAfterSeconds: number;
10
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,3 @@
1
+ export declare const RATE_LIMIT_COUNTER: unique symbol;
2
+ export declare const RATE_LIMIT_LOGGER: unique symbol;
3
+ export declare const RATE_LIMIT_EXECUTE: unique symbol;
@@ -0,0 +1,3 @@
1
+ export const RATE_LIMIT_COUNTER = Symbol('RATE_LIMIT_COUNTER');
2
+ export const RATE_LIMIT_LOGGER = Symbol('RATE_LIMIT_LOGGER');
3
+ export const RATE_LIMIT_EXECUTE = Symbol('RATE_LIMIT_EXECUTE');
@@ -0,0 +1,9 @@
1
+ import { Option } from 'oxide.ts';
2
+ import type { AttemptCounterInterface, AttemptWindowInterface } from './attempt-counter.interface.js';
3
+ export declare class InMemoryAttemptCounter implements AttemptCounterInterface {
4
+ private readonly windows;
5
+ increment(key: string, windowSeconds: number): Promise<AttemptWindowInterface>;
6
+ read(key: string): Promise<Option<AttemptWindowInterface>>;
7
+ reset(key: string): Promise<void>;
8
+ private prune;
9
+ }
@@ -0,0 +1,47 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ import { Injectable } from '@nestjs/common';
8
+ import { None, Some } from 'oxide.ts';
9
+ const MILLISECONDS_IN_SECOND = 1000;
10
+ const toWindow = (record, nowMs) => ({
11
+ count: record.count,
12
+ retryAfterSeconds: Math.ceil((record.expiresAtMs - nowMs) / MILLISECONDS_IN_SECOND),
13
+ });
14
+ let InMemoryAttemptCounter = class InMemoryAttemptCounter {
15
+ windows = new Map();
16
+ async increment(key, windowSeconds) {
17
+ await Promise.resolve();
18
+ const nowMs = Date.now();
19
+ this.prune(nowMs);
20
+ const current = this.windows.get(key);
21
+ const record = current ?? { count: 0, expiresAtMs: nowMs + (windowSeconds * MILLISECONDS_IN_SECOND) };
22
+ record.count += 1;
23
+ this.windows.set(key, record);
24
+ return toWindow(record, nowMs);
25
+ }
26
+ async read(key) {
27
+ await Promise.resolve();
28
+ const nowMs = Date.now();
29
+ const record = this.windows.get(key);
30
+ return record === undefined || record.expiresAtMs <= nowMs ? None : Some(toWindow(record, nowMs));
31
+ }
32
+ async reset(key) {
33
+ await Promise.resolve();
34
+ this.windows.delete(key);
35
+ }
36
+ prune(nowMs) {
37
+ for (const [key, record] of this.windows) {
38
+ if (record.expiresAtMs <= nowMs) {
39
+ this.windows.delete(key);
40
+ }
41
+ }
42
+ }
43
+ };
44
+ InMemoryAttemptCounter = __decorate([
45
+ Injectable()
46
+ ], InMemoryAttemptCounter);
47
+ export { InMemoryAttemptCounter };
@@ -0,0 +1,14 @@
1
+ export * from './attempt-counter.interface.js';
2
+ export * from './constants.js';
3
+ export * from './in-memory-attempt-counter.js';
4
+ export * from './rate-limit-logger.js';
5
+ export * from './rate-limit-logger.interface.js';
6
+ export * from './rate-limit.module.js';
7
+ export * from './throttle-axis.js';
8
+ export * from './throttle-axis.interface.js';
9
+ export * from './throttle-budget.js';
10
+ export * from './throttle-gate.js';
11
+ export * from './throttle-outcome.interceptor.js';
12
+ export * from './throttle.decorator.js';
13
+ export * from './throttle.guard.js';
14
+ export * from './valkey-attempt-counter.js';
@@ -0,0 +1,14 @@
1
+ export * from './attempt-counter.interface.js';
2
+ export * from './constants.js';
3
+ export * from './in-memory-attempt-counter.js';
4
+ export * from './rate-limit-logger.js';
5
+ export * from './rate-limit-logger.interface.js';
6
+ export * from './rate-limit.module.js';
7
+ export * from './throttle-axis.js';
8
+ export * from './throttle-axis.interface.js';
9
+ export * from './throttle-budget.js';
10
+ export * from './throttle-gate.js';
11
+ export * from './throttle-outcome.interceptor.js';
12
+ export * from './throttle.decorator.js';
13
+ export * from './throttle.guard.js';
14
+ export * from './valkey-attempt-counter.js';
@@ -0,0 +1,5 @@
1
+ import * as nestjsPino from 'nestjs-pino';
2
+ import type { RateLimitLoggerInterface } from './rate-limit-logger.interface.js';
3
+ export declare class RateLimitLogger extends nestjsPino.PinoLogger implements RateLimitLoggerInterface {
4
+ constructor(options: nestjsPino.Params);
5
+ }
@@ -0,0 +1,3 @@
1
+ export interface RateLimitLoggerInterface {
2
+ warn(context: unknown, message: string): void;
3
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,23 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __metadata = (this && this.__metadata) || function (k, v) {
8
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
9
+ };
10
+ var RateLimitLogger_1;
11
+ import { Injectable } from '@nestjs/common';
12
+ import * as nestjsPino from 'nestjs-pino';
13
+ let RateLimitLogger = RateLimitLogger_1 = class RateLimitLogger extends nestjsPino.PinoLogger {
14
+ constructor(options) {
15
+ super(options);
16
+ this.setContext(RateLimitLogger_1.name);
17
+ }
18
+ };
19
+ RateLimitLogger = RateLimitLogger_1 = __decorate([
20
+ Injectable(),
21
+ __metadata("design:paramtypes", [Object])
22
+ ], RateLimitLogger);
23
+ export { RateLimitLogger };
@@ -0,0 +1,13 @@
1
+ import type { DynamicModule, FactoryProvider, ModuleMetadata } from '@nestjs/common';
2
+ import type { AttemptCounterInterface } from './attempt-counter.interface.js';
3
+ import type { ThrottleExecuteFunction } from './throttle-axis.interface.js';
4
+ export interface RateLimitModuleOptionsInterface {
5
+ readonly counter: FactoryOptions<AttemptCounterInterface>;
6
+ readonly execute: FactoryOptions<ThrottleExecuteFunction>;
7
+ readonly imports?: ModuleMetadata['imports'];
8
+ }
9
+ type FactoryOptions<T> = Omit<FactoryProvider<T>, 'provide'>;
10
+ export declare class RateLimitModule {
11
+ static forRootAsync(options: RateLimitModuleOptionsInterface): DynamicModule;
12
+ }
13
+ export {};
@@ -0,0 +1,31 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ import { Module } from '@nestjs/common';
8
+ import { RATE_LIMIT_COUNTER, RATE_LIMIT_EXECUTE, RATE_LIMIT_LOGGER } from './constants.js';
9
+ import { RateLimitLogger } from './rate-limit-logger.js';
10
+ import { ThrottleBudget } from './throttle-budget.js';
11
+ import { ThrottleGate } from './throttle-gate.js';
12
+ let RateLimitModule = class RateLimitModule {
13
+ static forRootAsync(options) {
14
+ return {
15
+ exports: [RATE_LIMIT_COUNTER, RATE_LIMIT_EXECUTE, ThrottleBudget, ThrottleGate],
16
+ imports: options.imports ?? [],
17
+ module: this,
18
+ providers: [
19
+ { ...options.counter, provide: RATE_LIMIT_COUNTER },
20
+ { ...options.execute, provide: RATE_LIMIT_EXECUTE },
21
+ { provide: RATE_LIMIT_LOGGER, useClass: RateLimitLogger },
22
+ ThrottleBudget,
23
+ ThrottleGate,
24
+ ],
25
+ };
26
+ }
27
+ };
28
+ RateLimitModule = __decorate([
29
+ Module({})
30
+ ], RateLimitModule);
31
+ export { RateLimitModule };
@@ -0,0 +1,18 @@
1
+ import type { Option } from 'oxide.ts';
2
+ import type { AttemptCounterInterface, AttemptWindowInterface } from '../attempt-counter.interface.js';
3
+ interface IncrementCallInterface {
4
+ key: string;
5
+ windowSeconds: number;
6
+ }
7
+ export declare class FakeAttemptCounter implements AttemptCounterInterface {
8
+ readonly increments: IncrementCallInterface[];
9
+ readonly resets: string[];
10
+ retryAfterSeconds: number;
11
+ private readonly counts;
12
+ countOf(key: string): number;
13
+ increment(key: string, windowSeconds: number): Promise<AttemptWindowInterface>;
14
+ read(key: string): Promise<Option<AttemptWindowInterface>>;
15
+ reset(key: string): Promise<void>;
16
+ seed(key: string, count: number): void;
17
+ }
18
+ export {};
@@ -0,0 +1,30 @@
1
+ import { None, Some } from 'oxide.ts';
2
+ export class FakeAttemptCounter {
3
+ increments = [];
4
+ resets = [];
5
+ retryAfterSeconds = 42;
6
+ counts = new Map();
7
+ countOf(key) {
8
+ return this.counts.get(key) ?? 0;
9
+ }
10
+ async increment(key, windowSeconds) {
11
+ await Promise.resolve();
12
+ this.increments.push({ key, windowSeconds });
13
+ const count = (this.counts.get(key) ?? 0) + 1;
14
+ this.counts.set(key, count);
15
+ return { count, retryAfterSeconds: this.retryAfterSeconds };
16
+ }
17
+ async read(key) {
18
+ await Promise.resolve();
19
+ const count = this.counts.get(key);
20
+ return count === undefined ? None : Some({ count, retryAfterSeconds: this.retryAfterSeconds });
21
+ }
22
+ async reset(key) {
23
+ await Promise.resolve();
24
+ this.counts.delete(key);
25
+ this.resets.push(key);
26
+ }
27
+ seed(key, count) {
28
+ this.counts.set(key, count);
29
+ }
30
+ }
@@ -0,0 +1 @@
1
+ export * from './attempt-counter.fake.js';
@@ -0,0 +1 @@
1
+ export * from './attempt-counter.fake.js';
@@ -0,0 +1,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 {};
@@ -0,0 +1,4 @@
1
+ import { Reflector } from '@nestjs/core';
2
+ export const defineThrottleAxis = (axis) => Object.freeze(axis);
3
+ export const ThrottleAxisMetadata = Reflector.createDecorator();
4
+ export const ThrottleOutcomeMetadata = Reflector.createDecorator();
@@ -0,0 +1,30 @@
1
+ import type { AttemptCounterInterface } from './attempt-counter.interface.js';
2
+ import type { RateLimitLoggerInterface } from './rate-limit-logger.interface.js';
3
+ export interface ThrottleDecisionInterface {
4
+ allowed: boolean;
5
+ retryAfterSeconds: number;
6
+ }
7
+ export interface ThrottleRateLimitInterface {
8
+ rateLimitMaxRequests: number;
9
+ rateLimitWindowSeconds: number;
10
+ }
11
+ export interface ThrottleRefusalInterface {
12
+ message: string;
13
+ securityEvent: string;
14
+ }
15
+ export declare class ThrottleBudget {
16
+ private readonly attempts;
17
+ private readonly logger;
18
+ constructor(attempts: AttemptCounterInterface, logger: RateLimitLoggerInterface);
19
+ readFailures(options: {
20
+ key: string;
21
+ maxFailures: number;
22
+ refusal: ThrottleRefusalInterface;
23
+ }): Promise<ThrottleDecisionInterface>;
24
+ spend(options: {
25
+ key: string;
26
+ limit: ThrottleRateLimitInterface;
27
+ refusal: ThrottleRefusalInterface;
28
+ }): Promise<ThrottleDecisionInterface>;
29
+ private refuse;
30
+ }
@@ -0,0 +1,44 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __metadata = (this && this.__metadata) || function (k, v) {
8
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
9
+ };
10
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
11
+ return function (target, key) { decorator(target, key, paramIndex); }
12
+ };
13
+ import { Inject, Injectable } from '@nestjs/common';
14
+ import { RATE_LIMIT_COUNTER, RATE_LIMIT_LOGGER } from './constants.js';
15
+ const allow = () => ({ allowed: true, retryAfterSeconds: 0 });
16
+ let ThrottleBudget = class ThrottleBudget {
17
+ attempts;
18
+ logger;
19
+ constructor(attempts, logger) {
20
+ this.attempts = attempts;
21
+ this.logger = logger;
22
+ }
23
+ async readFailures(options) {
24
+ const window = await this.attempts.read(options.key);
25
+ const isBelowThreshold = window.isNone() || window.unwrap().count < options.maxFailures;
26
+ return isBelowThreshold ? allow() : this.refuse(window.unwrap().retryAfterSeconds, options.refusal);
27
+ }
28
+ async spend(options) {
29
+ const window = await this.attempts.increment(options.key, options.limit.rateLimitWindowSeconds);
30
+ const isWithinLimit = window.count <= options.limit.rateLimitMaxRequests;
31
+ return isWithinLimit ? allow() : this.refuse(window.retryAfterSeconds, options.refusal);
32
+ }
33
+ refuse(retryAfterSeconds, refusal) {
34
+ this.logger.warn({ retryAfterSeconds, securityEvent: refusal.securityEvent }, refusal.message);
35
+ return { allowed: false, retryAfterSeconds };
36
+ }
37
+ };
38
+ ThrottleBudget = __decorate([
39
+ Injectable(),
40
+ __param(0, Inject(RATE_LIMIT_COUNTER)),
41
+ __param(1, Inject(RATE_LIMIT_LOGGER)),
42
+ __metadata("design:paramtypes", [Object, Object])
43
+ ], ThrottleBudget);
44
+ export { ThrottleBudget };