@geekmidas/rate-limit 0.1.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/README.md +504 -0
- package/dist/index.cjs +88 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +139 -0
- package/dist/index.d.mts +139 -0
- package/dist/index.mjs +84 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +30 -0
- package/src/__tests__/rate-limit.spec.ts +321 -0
- package/src/index.ts +290 -0
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import { Cache } from "@geekmidas/cache";
|
|
2
|
+
import { Logger } from "@geekmidas/logger";
|
|
3
|
+
import { Service, ServiceRecord } from "@geekmidas/services";
|
|
4
|
+
|
|
5
|
+
//#region src/index.d.ts
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Error thrown when rate limit is exceeded
|
|
9
|
+
*/
|
|
10
|
+
declare class TooManyRequestsError extends Error {
|
|
11
|
+
readonly statusCode = 429;
|
|
12
|
+
readonly retryAfter?: number;
|
|
13
|
+
constructor(message?: string, retryAfter?: number);
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Rate limit configuration for an endpoint
|
|
17
|
+
*/
|
|
18
|
+
interface RateLimitConfig<T = RateLimitData> {
|
|
19
|
+
/**
|
|
20
|
+
* Maximum number of requests allowed in the window
|
|
21
|
+
*/
|
|
22
|
+
limit: number;
|
|
23
|
+
/**
|
|
24
|
+
* Time window in milliseconds
|
|
25
|
+
*/
|
|
26
|
+
windowMs: number;
|
|
27
|
+
/**
|
|
28
|
+
* Cache instance to store rate limit data
|
|
29
|
+
*/
|
|
30
|
+
cache: Cache<T>;
|
|
31
|
+
/**
|
|
32
|
+
* Key generator function to identify clients
|
|
33
|
+
* Defaults to using IP address
|
|
34
|
+
*/
|
|
35
|
+
keyGenerator?: RateLimitKeyGenerator;
|
|
36
|
+
/**
|
|
37
|
+
* Skip rate limiting for certain requests
|
|
38
|
+
*/
|
|
39
|
+
skip?: RateLimitSkipFn;
|
|
40
|
+
/**
|
|
41
|
+
* Optional message to return when rate limit is exceeded
|
|
42
|
+
*/
|
|
43
|
+
message?: string;
|
|
44
|
+
/**
|
|
45
|
+
* Optional custom handler when rate limit is exceeded
|
|
46
|
+
*/
|
|
47
|
+
handler?: RateLimitExceededHandler;
|
|
48
|
+
/**
|
|
49
|
+
* Whether to include rate limit headers in response
|
|
50
|
+
* @default true
|
|
51
|
+
*/
|
|
52
|
+
standardHeaders?: boolean;
|
|
53
|
+
/**
|
|
54
|
+
* Whether to include legacy rate limit headers
|
|
55
|
+
* @default false
|
|
56
|
+
*/
|
|
57
|
+
legacyHeaders?: boolean;
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Context for rate limiting decisions
|
|
61
|
+
*/
|
|
62
|
+
interface RateLimitContext<TServices extends Service[] = [], TLogger extends Logger = Logger, TSession = unknown> {
|
|
63
|
+
header: (key: string) => string | undefined;
|
|
64
|
+
services: ServiceRecord<TServices>;
|
|
65
|
+
logger: TLogger;
|
|
66
|
+
session: TSession;
|
|
67
|
+
path: string;
|
|
68
|
+
method: string;
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Function to generate a unique key for rate limiting
|
|
72
|
+
*/
|
|
73
|
+
type RateLimitKeyGenerator<TServices extends Service[] = [], TLogger extends Logger = Logger, TSession = unknown> = (ctx: RateLimitContext<TServices, TLogger, TSession>) => string | Promise<string>;
|
|
74
|
+
/**
|
|
75
|
+
* Function to determine if rate limiting should be skipped
|
|
76
|
+
*/
|
|
77
|
+
type RateLimitSkipFn<TServices extends Service[] = [], TLogger extends Logger = Logger, TSession = unknown> = (ctx: RateLimitContext<TServices, TLogger, TSession>) => boolean | Promise<boolean>;
|
|
78
|
+
/**
|
|
79
|
+
* Handler for when rate limit is exceeded
|
|
80
|
+
*/
|
|
81
|
+
type RateLimitExceededHandler<TServices extends Service[] = [], TLogger extends Logger = Logger, TSession = unknown> = (ctx: RateLimitContext<TServices, TLogger, TSession>, info: RateLimitInfo) => void | Promise<void>;
|
|
82
|
+
/**
|
|
83
|
+
* Information about current rate limit status
|
|
84
|
+
*/
|
|
85
|
+
interface RateLimitInfo {
|
|
86
|
+
/**
|
|
87
|
+
* Current request count in the window
|
|
88
|
+
*/
|
|
89
|
+
count: number;
|
|
90
|
+
/**
|
|
91
|
+
* Maximum allowed requests
|
|
92
|
+
*/
|
|
93
|
+
limit: number;
|
|
94
|
+
/**
|
|
95
|
+
* Remaining requests allowed
|
|
96
|
+
*/
|
|
97
|
+
remaining: number;
|
|
98
|
+
/**
|
|
99
|
+
* Time when the window resets (Unix timestamp)
|
|
100
|
+
*/
|
|
101
|
+
resetTime: number;
|
|
102
|
+
/**
|
|
103
|
+
* Time until reset in milliseconds
|
|
104
|
+
*/
|
|
105
|
+
retryAfter: number;
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Headers to be set on responses
|
|
109
|
+
*/
|
|
110
|
+
interface RateLimitHeaders {
|
|
111
|
+
'X-RateLimit-Limit'?: string;
|
|
112
|
+
'X-RateLimit-Remaining'?: string;
|
|
113
|
+
'X-RateLimit-Reset'?: string;
|
|
114
|
+
'Retry-After'?: string;
|
|
115
|
+
'X-RateLimit-Retry-After'?: string;
|
|
116
|
+
'X-RateLimit-Reset-After'?: string;
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* Data stored in cache for rate limiting
|
|
120
|
+
*/
|
|
121
|
+
interface RateLimitData {
|
|
122
|
+
count: number;
|
|
123
|
+
resetTime: number;
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* Default key generator using IP address
|
|
127
|
+
*/
|
|
128
|
+
declare const defaultKeyGenerator: RateLimitKeyGenerator;
|
|
129
|
+
/**
|
|
130
|
+
* Check rate limit and throw error if exceeded
|
|
131
|
+
*/
|
|
132
|
+
declare function checkRateLimit<TServices extends Service[] = [], TLogger extends Logger = Logger, TSession = unknown>(config: RateLimitConfig<RateLimitData>, ctx: RateLimitContext<TServices, TLogger, TSession>): Promise<RateLimitInfo>;
|
|
133
|
+
/**
|
|
134
|
+
* Generate rate limit headers
|
|
135
|
+
*/
|
|
136
|
+
declare function getRateLimitHeaders(info: RateLimitInfo, config: RateLimitConfig): RateLimitHeaders;
|
|
137
|
+
//#endregion
|
|
138
|
+
export { RateLimitConfig, RateLimitContext, RateLimitData, RateLimitExceededHandler, RateLimitHeaders, RateLimitInfo, RateLimitKeyGenerator, RateLimitSkipFn, TooManyRequestsError, checkRateLimit, defaultKeyGenerator, getRateLimitHeaders };
|
|
139
|
+
//# sourceMappingURL=index.d.cts.map
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import { Cache } from "@geekmidas/cache";
|
|
2
|
+
import { Logger } from "@geekmidas/logger";
|
|
3
|
+
import { Service, ServiceRecord } from "@geekmidas/services";
|
|
4
|
+
|
|
5
|
+
//#region src/index.d.ts
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Error thrown when rate limit is exceeded
|
|
9
|
+
*/
|
|
10
|
+
declare class TooManyRequestsError extends Error {
|
|
11
|
+
readonly statusCode = 429;
|
|
12
|
+
readonly retryAfter?: number;
|
|
13
|
+
constructor(message?: string, retryAfter?: number);
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Rate limit configuration for an endpoint
|
|
17
|
+
*/
|
|
18
|
+
interface RateLimitConfig<T = RateLimitData> {
|
|
19
|
+
/**
|
|
20
|
+
* Maximum number of requests allowed in the window
|
|
21
|
+
*/
|
|
22
|
+
limit: number;
|
|
23
|
+
/**
|
|
24
|
+
* Time window in milliseconds
|
|
25
|
+
*/
|
|
26
|
+
windowMs: number;
|
|
27
|
+
/**
|
|
28
|
+
* Cache instance to store rate limit data
|
|
29
|
+
*/
|
|
30
|
+
cache: Cache<T>;
|
|
31
|
+
/**
|
|
32
|
+
* Key generator function to identify clients
|
|
33
|
+
* Defaults to using IP address
|
|
34
|
+
*/
|
|
35
|
+
keyGenerator?: RateLimitKeyGenerator;
|
|
36
|
+
/**
|
|
37
|
+
* Skip rate limiting for certain requests
|
|
38
|
+
*/
|
|
39
|
+
skip?: RateLimitSkipFn;
|
|
40
|
+
/**
|
|
41
|
+
* Optional message to return when rate limit is exceeded
|
|
42
|
+
*/
|
|
43
|
+
message?: string;
|
|
44
|
+
/**
|
|
45
|
+
* Optional custom handler when rate limit is exceeded
|
|
46
|
+
*/
|
|
47
|
+
handler?: RateLimitExceededHandler;
|
|
48
|
+
/**
|
|
49
|
+
* Whether to include rate limit headers in response
|
|
50
|
+
* @default true
|
|
51
|
+
*/
|
|
52
|
+
standardHeaders?: boolean;
|
|
53
|
+
/**
|
|
54
|
+
* Whether to include legacy rate limit headers
|
|
55
|
+
* @default false
|
|
56
|
+
*/
|
|
57
|
+
legacyHeaders?: boolean;
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Context for rate limiting decisions
|
|
61
|
+
*/
|
|
62
|
+
interface RateLimitContext<TServices extends Service[] = [], TLogger extends Logger = Logger, TSession = unknown> {
|
|
63
|
+
header: (key: string) => string | undefined;
|
|
64
|
+
services: ServiceRecord<TServices>;
|
|
65
|
+
logger: TLogger;
|
|
66
|
+
session: TSession;
|
|
67
|
+
path: string;
|
|
68
|
+
method: string;
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Function to generate a unique key for rate limiting
|
|
72
|
+
*/
|
|
73
|
+
type RateLimitKeyGenerator<TServices extends Service[] = [], TLogger extends Logger = Logger, TSession = unknown> = (ctx: RateLimitContext<TServices, TLogger, TSession>) => string | Promise<string>;
|
|
74
|
+
/**
|
|
75
|
+
* Function to determine if rate limiting should be skipped
|
|
76
|
+
*/
|
|
77
|
+
type RateLimitSkipFn<TServices extends Service[] = [], TLogger extends Logger = Logger, TSession = unknown> = (ctx: RateLimitContext<TServices, TLogger, TSession>) => boolean | Promise<boolean>;
|
|
78
|
+
/**
|
|
79
|
+
* Handler for when rate limit is exceeded
|
|
80
|
+
*/
|
|
81
|
+
type RateLimitExceededHandler<TServices extends Service[] = [], TLogger extends Logger = Logger, TSession = unknown> = (ctx: RateLimitContext<TServices, TLogger, TSession>, info: RateLimitInfo) => void | Promise<void>;
|
|
82
|
+
/**
|
|
83
|
+
* Information about current rate limit status
|
|
84
|
+
*/
|
|
85
|
+
interface RateLimitInfo {
|
|
86
|
+
/**
|
|
87
|
+
* Current request count in the window
|
|
88
|
+
*/
|
|
89
|
+
count: number;
|
|
90
|
+
/**
|
|
91
|
+
* Maximum allowed requests
|
|
92
|
+
*/
|
|
93
|
+
limit: number;
|
|
94
|
+
/**
|
|
95
|
+
* Remaining requests allowed
|
|
96
|
+
*/
|
|
97
|
+
remaining: number;
|
|
98
|
+
/**
|
|
99
|
+
* Time when the window resets (Unix timestamp)
|
|
100
|
+
*/
|
|
101
|
+
resetTime: number;
|
|
102
|
+
/**
|
|
103
|
+
* Time until reset in milliseconds
|
|
104
|
+
*/
|
|
105
|
+
retryAfter: number;
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Headers to be set on responses
|
|
109
|
+
*/
|
|
110
|
+
interface RateLimitHeaders {
|
|
111
|
+
'X-RateLimit-Limit'?: string;
|
|
112
|
+
'X-RateLimit-Remaining'?: string;
|
|
113
|
+
'X-RateLimit-Reset'?: string;
|
|
114
|
+
'Retry-After'?: string;
|
|
115
|
+
'X-RateLimit-Retry-After'?: string;
|
|
116
|
+
'X-RateLimit-Reset-After'?: string;
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* Data stored in cache for rate limiting
|
|
120
|
+
*/
|
|
121
|
+
interface RateLimitData {
|
|
122
|
+
count: number;
|
|
123
|
+
resetTime: number;
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* Default key generator using IP address
|
|
127
|
+
*/
|
|
128
|
+
declare const defaultKeyGenerator: RateLimitKeyGenerator;
|
|
129
|
+
/**
|
|
130
|
+
* Check rate limit and throw error if exceeded
|
|
131
|
+
*/
|
|
132
|
+
declare function checkRateLimit<TServices extends Service[] = [], TLogger extends Logger = Logger, TSession = unknown>(config: RateLimitConfig<RateLimitData>, ctx: RateLimitContext<TServices, TLogger, TSession>): Promise<RateLimitInfo>;
|
|
133
|
+
/**
|
|
134
|
+
* Generate rate limit headers
|
|
135
|
+
*/
|
|
136
|
+
declare function getRateLimitHeaders(info: RateLimitInfo, config: RateLimitConfig): RateLimitHeaders;
|
|
137
|
+
//#endregion
|
|
138
|
+
export { RateLimitConfig, RateLimitContext, RateLimitData, RateLimitExceededHandler, RateLimitHeaders, RateLimitInfo, RateLimitKeyGenerator, RateLimitSkipFn, TooManyRequestsError, checkRateLimit, defaultKeyGenerator, getRateLimitHeaders };
|
|
139
|
+
//# sourceMappingURL=index.d.mts.map
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
//#region src/index.ts
|
|
2
|
+
/**
|
|
3
|
+
* Error thrown when rate limit is exceeded
|
|
4
|
+
*/
|
|
5
|
+
var TooManyRequestsError = class extends Error {
|
|
6
|
+
statusCode = 429;
|
|
7
|
+
retryAfter;
|
|
8
|
+
constructor(message, retryAfter) {
|
|
9
|
+
super(message || "Too many requests, please try again later.");
|
|
10
|
+
this.name = "TooManyRequestsError";
|
|
11
|
+
this.retryAfter = retryAfter;
|
|
12
|
+
}
|
|
13
|
+
};
|
|
14
|
+
/**
|
|
15
|
+
* Default key generator using IP address
|
|
16
|
+
*/
|
|
17
|
+
const defaultKeyGenerator = (ctx) => {
|
|
18
|
+
const ip = ctx.header("x-forwarded-for")?.split(",")[0]?.trim() || ctx.header("x-real-ip") || ctx.header("x-client-ip") || ctx.header("cf-connecting-ip") || "unknown";
|
|
19
|
+
return `rate-limit:${ctx.method}:${ctx.path}:${ip}`;
|
|
20
|
+
};
|
|
21
|
+
/**
|
|
22
|
+
* Check rate limit and throw error if exceeded
|
|
23
|
+
*/
|
|
24
|
+
async function checkRateLimit(config, ctx) {
|
|
25
|
+
if (config.skip && await config.skip(ctx)) return {
|
|
26
|
+
count: 0,
|
|
27
|
+
limit: config.limit,
|
|
28
|
+
remaining: config.limit,
|
|
29
|
+
resetTime: Date.now() + config.windowMs,
|
|
30
|
+
retryAfter: config.windowMs
|
|
31
|
+
};
|
|
32
|
+
const keyGenerator = config.keyGenerator || defaultKeyGenerator;
|
|
33
|
+
const key = await keyGenerator(ctx);
|
|
34
|
+
const now = Date.now();
|
|
35
|
+
let data = await config.cache.get(key);
|
|
36
|
+
if (!data || data.resetTime <= now) {
|
|
37
|
+
const resetTime = now + config.windowMs;
|
|
38
|
+
data = {
|
|
39
|
+
count: 1,
|
|
40
|
+
resetTime
|
|
41
|
+
};
|
|
42
|
+
const ttlSeconds = Math.ceil(config.windowMs / 1e3);
|
|
43
|
+
await config.cache.set(key, data, ttlSeconds);
|
|
44
|
+
} else {
|
|
45
|
+
data.count++;
|
|
46
|
+
const remainingMs = data.resetTime - now;
|
|
47
|
+
const ttlSeconds = Math.ceil(remainingMs / 1e3);
|
|
48
|
+
await config.cache.set(key, data, ttlSeconds);
|
|
49
|
+
}
|
|
50
|
+
const info = {
|
|
51
|
+
count: data.count,
|
|
52
|
+
limit: config.limit,
|
|
53
|
+
remaining: Math.max(0, config.limit - data.count),
|
|
54
|
+
resetTime: data.resetTime,
|
|
55
|
+
retryAfter: data.resetTime - now
|
|
56
|
+
};
|
|
57
|
+
if (data.count > config.limit) {
|
|
58
|
+
if (config.handler) await config.handler(ctx, info);
|
|
59
|
+
const retryAfterSeconds = Math.ceil(info.retryAfter / 1e3);
|
|
60
|
+
throw new TooManyRequestsError(config.message || "Too many requests, please try again later.", retryAfterSeconds);
|
|
61
|
+
}
|
|
62
|
+
return info;
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Generate rate limit headers
|
|
66
|
+
*/
|
|
67
|
+
function getRateLimitHeaders(info, config) {
|
|
68
|
+
const headers = {};
|
|
69
|
+
if (config.standardHeaders !== false) {
|
|
70
|
+
headers["X-RateLimit-Limit"] = info.limit.toString();
|
|
71
|
+
headers["X-RateLimit-Remaining"] = info.remaining.toString();
|
|
72
|
+
headers["X-RateLimit-Reset"] = new Date(info.resetTime).toISOString();
|
|
73
|
+
}
|
|
74
|
+
if (config.legacyHeaders) {
|
|
75
|
+
headers["X-RateLimit-Retry-After"] = info.retryAfter.toString();
|
|
76
|
+
headers["X-RateLimit-Reset-After"] = Math.ceil(info.retryAfter / 1e3).toString();
|
|
77
|
+
}
|
|
78
|
+
if (info.remaining === 0) headers["Retry-After"] = Math.ceil(info.retryAfter / 1e3).toString();
|
|
79
|
+
return headers;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
//#endregion
|
|
83
|
+
export { TooManyRequestsError, checkRateLimit, defaultKeyGenerator, getRateLimitHeaders };
|
|
84
|
+
//# sourceMappingURL=index.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["message?: string","retryAfter?: number","defaultKeyGenerator: RateLimitKeyGenerator","config: RateLimitConfig<RateLimitData>","ctx: RateLimitContext<TServices, TLogger, TSession>","info: RateLimitInfo","config: RateLimitConfig","headers: RateLimitHeaders"],"sources":["../src/index.ts"],"sourcesContent":["import type { Cache } from '@geekmidas/cache';\nimport type { Logger } from '@geekmidas/logger';\nimport type { Service, ServiceRecord } from '@geekmidas/services';\n\n/**\n * Error thrown when rate limit is exceeded\n */\nexport class TooManyRequestsError extends Error {\n public readonly statusCode = 429;\n public readonly retryAfter?: number;\n\n constructor(message?: string, retryAfter?: number) {\n super(message || 'Too many requests, please try again later.');\n this.name = 'TooManyRequestsError';\n this.retryAfter = retryAfter;\n }\n}\n\n/**\n * Rate limit configuration for an endpoint\n */\nexport interface RateLimitConfig<T = RateLimitData> {\n /**\n * Maximum number of requests allowed in the window\n */\n limit: number;\n\n /**\n * Time window in milliseconds\n */\n windowMs: number;\n\n /**\n * Cache instance to store rate limit data\n */\n cache: Cache<T>;\n\n /**\n * Key generator function to identify clients\n * Defaults to using IP address\n */\n keyGenerator?: RateLimitKeyGenerator;\n\n /**\n * Skip rate limiting for certain requests\n */\n skip?: RateLimitSkipFn;\n\n /**\n * Optional message to return when rate limit is exceeded\n */\n message?: string;\n\n /**\n * Optional custom handler when rate limit is exceeded\n */\n handler?: RateLimitExceededHandler;\n\n /**\n * Whether to include rate limit headers in response\n * @default true\n */\n standardHeaders?: boolean;\n\n /**\n * Whether to include legacy rate limit headers\n * @default false\n */\n legacyHeaders?: boolean;\n}\n\n/**\n * Context for rate limiting decisions\n */\nexport interface RateLimitContext<\n TServices extends Service[] = [],\n TLogger extends Logger = Logger,\n TSession = unknown,\n> {\n header: (key: string) => string | undefined;\n services: ServiceRecord<TServices>;\n logger: TLogger;\n session: TSession;\n path: string;\n method: string;\n}\n\n/**\n * Function to generate a unique key for rate limiting\n */\nexport type RateLimitKeyGenerator<\n TServices extends Service[] = [],\n TLogger extends Logger = Logger,\n TSession = unknown,\n> = (\n ctx: RateLimitContext<TServices, TLogger, TSession>,\n) => string | Promise<string>;\n\n/**\n * Function to determine if rate limiting should be skipped\n */\nexport type RateLimitSkipFn<\n TServices extends Service[] = [],\n TLogger extends Logger = Logger,\n TSession = unknown,\n> = (\n ctx: RateLimitContext<TServices, TLogger, TSession>,\n) => boolean | Promise<boolean>;\n\n/**\n * Handler for when rate limit is exceeded\n */\nexport type RateLimitExceededHandler<\n TServices extends Service[] = [],\n TLogger extends Logger = Logger,\n TSession = unknown,\n> = (\n ctx: RateLimitContext<TServices, TLogger, TSession>,\n info: RateLimitInfo,\n) => void | Promise<void>;\n\n/**\n * Information about current rate limit status\n */\nexport interface RateLimitInfo {\n /**\n * Current request count in the window\n */\n count: number;\n\n /**\n * Maximum allowed requests\n */\n limit: number;\n\n /**\n * Remaining requests allowed\n */\n remaining: number;\n\n /**\n * Time when the window resets (Unix timestamp)\n */\n resetTime: number;\n\n /**\n * Time until reset in milliseconds\n */\n retryAfter: number;\n}\n\n/**\n * Headers to be set on responses\n */\nexport interface RateLimitHeaders {\n 'X-RateLimit-Limit'?: string;\n 'X-RateLimit-Remaining'?: string;\n 'X-RateLimit-Reset'?: string;\n 'Retry-After'?: string;\n 'X-RateLimit-Retry-After'?: string;\n 'X-RateLimit-Reset-After'?: string;\n}\n\n/**\n * Data stored in cache for rate limiting\n */\nexport interface RateLimitData {\n count: number;\n resetTime: number;\n}\n\n/**\n * Default key generator using IP address\n */\nexport const defaultKeyGenerator: RateLimitKeyGenerator = (ctx) => {\n // Try various headers for IP address\n const ip =\n ctx.header('x-forwarded-for')?.split(',')[0]?.trim() ||\n ctx.header('x-real-ip') ||\n ctx.header('x-client-ip') ||\n ctx.header('cf-connecting-ip') ||\n 'unknown';\n\n return `rate-limit:${ctx.method}:${ctx.path}:${ip}`;\n};\n\n/**\n * Check rate limit and throw error if exceeded\n */\nexport async function checkRateLimit<\n TServices extends Service[] = [],\n TLogger extends Logger = Logger,\n TSession = unknown,\n>(\n config: RateLimitConfig<RateLimitData>,\n ctx: RateLimitContext<TServices, TLogger, TSession>,\n): Promise<RateLimitInfo> {\n // Check if we should skip rate limiting\n if (config.skip && (await config.skip(ctx))) {\n return {\n count: 0,\n limit: config.limit,\n remaining: config.limit,\n resetTime: Date.now() + config.windowMs,\n retryAfter: config.windowMs,\n };\n }\n\n // Generate key for this request\n const keyGenerator = config.keyGenerator || defaultKeyGenerator;\n const key = await keyGenerator(ctx);\n\n // Get current data from cache\n const now = Date.now();\n let data = await config.cache.get(key);\n\n // If no data or window expired, create new entry\n if (!data || data.resetTime <= now) {\n const resetTime = now + config.windowMs;\n data = { count: 1, resetTime };\n\n // Store with TTL matching the window\n const ttlSeconds = Math.ceil(config.windowMs / 1000);\n await config.cache.set(key, data, ttlSeconds);\n } else {\n // Increment count\n data.count++;\n\n // Calculate remaining TTL\n const remainingMs = data.resetTime - now;\n const ttlSeconds = Math.ceil(remainingMs / 1000);\n await config.cache.set(key, data, ttlSeconds);\n }\n\n // Calculate rate limit info\n const info: RateLimitInfo = {\n count: data.count,\n limit: config.limit,\n remaining: Math.max(0, config.limit - data.count),\n resetTime: data.resetTime,\n retryAfter: data.resetTime - now,\n };\n\n // Check if limit exceeded\n if (data.count > config.limit) {\n // Call custom handler if provided\n if (config.handler) {\n await config.handler(ctx, info);\n }\n\n // Throw rate limit error\n const retryAfterSeconds = Math.ceil(info.retryAfter / 1000);\n throw new TooManyRequestsError(\n config.message || 'Too many requests, please try again later.',\n retryAfterSeconds,\n );\n }\n\n return info;\n}\n\n/**\n * Generate rate limit headers\n */\nexport function getRateLimitHeaders(\n info: RateLimitInfo,\n config: RateLimitConfig,\n): RateLimitHeaders {\n const headers: RateLimitHeaders = {};\n\n if (config.standardHeaders !== false) {\n headers['X-RateLimit-Limit'] = info.limit.toString();\n headers['X-RateLimit-Remaining'] = info.remaining.toString();\n headers['X-RateLimit-Reset'] = new Date(info.resetTime).toISOString();\n }\n\n if (config.legacyHeaders) {\n headers['X-RateLimit-Retry-After'] = info.retryAfter.toString();\n headers['X-RateLimit-Reset-After'] = Math.ceil(\n info.retryAfter / 1000,\n ).toString();\n }\n\n // Always set Retry-After when limit is exceeded\n if (info.remaining === 0) {\n headers['Retry-After'] = Math.ceil(info.retryAfter / 1000).toString();\n }\n\n return headers;\n}\n"],"mappings":";;;;AAOA,IAAa,uBAAb,cAA0C,MAAM;CAC9C,AAAgB,aAAa;CAC7B,AAAgB;CAEhB,YAAYA,SAAkBC,YAAqB;AACjD,QAAM,WAAW,6CAA6C;AAC9D,OAAK,OAAO;AACZ,OAAK,aAAa;CACnB;AACF;;;;AA8JD,MAAaC,sBAA6C,CAAC,QAAQ;CAEjE,MAAM,KACJ,IAAI,OAAO,kBAAkB,EAAE,MAAM,IAAI,CAAC,IAAI,MAAM,IACpD,IAAI,OAAO,YAAY,IACvB,IAAI,OAAO,cAAc,IACzB,IAAI,OAAO,mBAAmB,IAC9B;AAEF,SAAQ,aAAa,IAAI,OAAO,GAAG,IAAI,KAAK,GAAG,GAAG;AACnD;;;;AAKD,eAAsB,eAKpBC,QACAC,KACwB;AAExB,KAAI,OAAO,QAAS,MAAM,OAAO,KAAK,IAAI,CACxC,QAAO;EACL,OAAO;EACP,OAAO,OAAO;EACd,WAAW,OAAO;EAClB,WAAW,KAAK,KAAK,GAAG,OAAO;EAC/B,YAAY,OAAO;CACpB;CAIH,MAAM,eAAe,OAAO,gBAAgB;CAC5C,MAAM,MAAM,MAAM,aAAa,IAAI;CAGnC,MAAM,MAAM,KAAK,KAAK;CACtB,IAAI,OAAO,MAAM,OAAO,MAAM,IAAI,IAAI;AAGtC,MAAK,QAAQ,KAAK,aAAa,KAAK;EAClC,MAAM,YAAY,MAAM,OAAO;AAC/B,SAAO;GAAE,OAAO;GAAG;EAAW;EAG9B,MAAM,aAAa,KAAK,KAAK,OAAO,WAAW,IAAK;AACpD,QAAM,OAAO,MAAM,IAAI,KAAK,MAAM,WAAW;CAC9C,OAAM;AAEL,OAAK;EAGL,MAAM,cAAc,KAAK,YAAY;EACrC,MAAM,aAAa,KAAK,KAAK,cAAc,IAAK;AAChD,QAAM,OAAO,MAAM,IAAI,KAAK,MAAM,WAAW;CAC9C;CAGD,MAAMC,OAAsB;EAC1B,OAAO,KAAK;EACZ,OAAO,OAAO;EACd,WAAW,KAAK,IAAI,GAAG,OAAO,QAAQ,KAAK,MAAM;EACjD,WAAW,KAAK;EAChB,YAAY,KAAK,YAAY;CAC9B;AAGD,KAAI,KAAK,QAAQ,OAAO,OAAO;AAE7B,MAAI,OAAO,QACT,OAAM,OAAO,QAAQ,KAAK,KAAK;EAIjC,MAAM,oBAAoB,KAAK,KAAK,KAAK,aAAa,IAAK;AAC3D,QAAM,IAAI,qBACR,OAAO,WAAW,8CAClB;CAEH;AAED,QAAO;AACR;;;;AAKD,SAAgB,oBACdA,MACAC,QACkB;CAClB,MAAMC,UAA4B,CAAE;AAEpC,KAAI,OAAO,oBAAoB,OAAO;AACpC,UAAQ,uBAAuB,KAAK,MAAM,UAAU;AACpD,UAAQ,2BAA2B,KAAK,UAAU,UAAU;AAC5D,UAAQ,uBAAuB,IAAI,KAAK,KAAK,WAAW,aAAa;CACtE;AAED,KAAI,OAAO,eAAe;AACxB,UAAQ,6BAA6B,KAAK,WAAW,UAAU;AAC/D,UAAQ,6BAA6B,KAAK,KACxC,KAAK,aAAa,IACnB,CAAC,UAAU;CACb;AAGD,KAAI,KAAK,cAAc,EACrB,SAAQ,iBAAiB,KAAK,KAAK,KAAK,aAAa,IAAK,CAAC,UAAU;AAGvE,QAAO;AACR"}
|
package/package.json
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@geekmidas/rate-limit",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"private": false,
|
|
5
|
+
"type": "module",
|
|
6
|
+
"exports": {
|
|
7
|
+
".": {
|
|
8
|
+
"types": "./dist/index.d.ts",
|
|
9
|
+
"import": "./dist/index.mjs",
|
|
10
|
+
"require": "./dist/index.cjs"
|
|
11
|
+
}
|
|
12
|
+
},
|
|
13
|
+
"repository": {
|
|
14
|
+
"type": "git",
|
|
15
|
+
"url": "https://github.com/geekmidas/toolbox.git"
|
|
16
|
+
},
|
|
17
|
+
"publishConfig": {
|
|
18
|
+
"registry": "https://registry.npmjs.org/",
|
|
19
|
+
"access": "public"
|
|
20
|
+
},
|
|
21
|
+
"dependencies": {
|
|
22
|
+
"@geekmidas/logger": "0.0.1",
|
|
23
|
+
"@geekmidas/services": "0.0.1",
|
|
24
|
+
"@geekmidas/cache": "0.0.7"
|
|
25
|
+
},
|
|
26
|
+
"peerDependencies": {},
|
|
27
|
+
"scripts": {
|
|
28
|
+
"ts": "tsc --noEmit --skipLibCheck src/**/*.ts"
|
|
29
|
+
}
|
|
30
|
+
}
|