@jellyfungus/hono-rate-limiter 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.
@@ -0,0 +1,168 @@
1
+ import { Env, Context, MiddlewareHandler } from 'hono';
2
+
3
+ /**
4
+ * @module
5
+ * Rate Limit Middleware for Hono.
6
+ */
7
+
8
+ /**
9
+ * Rate limit information for a single request
10
+ */
11
+ type RateLimitInfo = {
12
+ /** Maximum requests allowed in window */
13
+ limit: number;
14
+ /** Remaining requests in current window */
15
+ remaining: number;
16
+ /** Unix timestamp (ms) when window resets */
17
+ reset: number;
18
+ };
19
+ /**
20
+ * Result from store increment operation
21
+ */
22
+ type StoreResult = {
23
+ /** Current request count in window */
24
+ count: number;
25
+ /** When the window resets (Unix timestamp ms) */
26
+ reset: number;
27
+ };
28
+ /**
29
+ * Header format versions
30
+ */
31
+ type HeadersFormat = "draft-6" | "draft-7" | false;
32
+ /**
33
+ * Rate limit algorithm
34
+ */
35
+ type Algorithm = "fixed-window" | "sliding-window";
36
+ /**
37
+ * Store interface for rate limit state
38
+ */
39
+ type RateLimitStore = {
40
+ /**
41
+ * Initialize store. Called once before first use.
42
+ */
43
+ init?: (windowMs: number) => void | Promise<void>;
44
+ /**
45
+ * Increment counter for key and return current state.
46
+ */
47
+ increment: (key: string) => StoreResult | Promise<StoreResult>;
48
+ /**
49
+ * Decrement counter for key.
50
+ */
51
+ decrement?: (key: string) => void | Promise<void>;
52
+ /**
53
+ * Reset a specific key.
54
+ */
55
+ resetKey: (key: string) => void | Promise<void>;
56
+ /**
57
+ * Get current state for key.
58
+ */
59
+ get?: (key: string) => StoreResult | Promise<StoreResult | undefined> | undefined;
60
+ /**
61
+ * Graceful shutdown.
62
+ */
63
+ shutdown?: () => void | Promise<void>;
64
+ };
65
+ /**
66
+ * Options for rate limit middleware
67
+ */
68
+ type RateLimitOptions<E extends Env = Env> = {
69
+ /**
70
+ * Maximum requests allowed in the time window.
71
+ * @default 60
72
+ */
73
+ limit?: number | ((c: Context<E>) => number | Promise<number>);
74
+ /**
75
+ * Time window in milliseconds.
76
+ * @default 60000 (1 minute)
77
+ */
78
+ windowMs?: number;
79
+ /**
80
+ * Rate limiting algorithm.
81
+ * @default 'sliding-window'
82
+ */
83
+ algorithm?: Algorithm;
84
+ /**
85
+ * Storage backend for rate limit state.
86
+ * @default MemoryStore
87
+ */
88
+ store?: RateLimitStore;
89
+ /**
90
+ * Generate unique key for each client.
91
+ * @default IP address from headers
92
+ */
93
+ keyGenerator?: (c: Context<E>) => string | Promise<string>;
94
+ /**
95
+ * Handler called when rate limit is exceeded.
96
+ */
97
+ handler?: (c: Context<E>, info: RateLimitInfo) => Response | Promise<Response>;
98
+ /**
99
+ * HTTP header format to use.
100
+ * @default 'draft-6'
101
+ */
102
+ headers?: HeadersFormat;
103
+ /**
104
+ * Skip rate limiting for certain requests.
105
+ */
106
+ skip?: (c: Context<E>) => boolean | Promise<boolean>;
107
+ /**
108
+ * Don't count successful (2xx) requests against limit.
109
+ * @default false
110
+ */
111
+ skipSuccessfulRequests?: boolean;
112
+ /**
113
+ * Don't count failed (4xx, 5xx) requests against limit.
114
+ * @default false
115
+ */
116
+ skipFailedRequests?: boolean;
117
+ /**
118
+ * Callback when a request is rate limited.
119
+ */
120
+ onRateLimited?: (c: Context<E>, info: RateLimitInfo) => void | Promise<void>;
121
+ };
122
+ declare module "hono" {
123
+ interface ContextVariableMap {
124
+ rateLimit?: RateLimitInfo;
125
+ }
126
+ }
127
+ /**
128
+ * In-memory store for rate limiting.
129
+ * Suitable for single-instance deployments.
130
+ */
131
+ declare class MemoryStore implements RateLimitStore {
132
+ private entries;
133
+ private windowMs;
134
+ private cleanupTimer?;
135
+ init(windowMs: number): void;
136
+ increment(key: string): StoreResult;
137
+ get(key: string): StoreResult | undefined;
138
+ decrement(key: string): void;
139
+ resetKey(key: string): void;
140
+ shutdown(): void;
141
+ }
142
+ declare function getClientIP(c: Context): string;
143
+ /**
144
+ * Rate Limit Middleware for Hono.
145
+ *
146
+ * @param {RateLimitOptions} [options] - Configuration options
147
+ * @returns {MiddlewareHandler} Middleware handler
148
+ *
149
+ * @example
150
+ * ```ts
151
+ * import { Hono } from 'hono'
152
+ * import { rateLimiter } from 'hono-rate-limit'
153
+ *
154
+ * const app = new Hono()
155
+ *
156
+ * // Basic usage - 60 requests per minute
157
+ * app.use(rateLimiter())
158
+ *
159
+ * // Custom configuration
160
+ * app.use('/api/*', rateLimiter({
161
+ * limit: 100,
162
+ * windowMs: 60 * 1000,
163
+ * }))
164
+ * ```
165
+ */
166
+ declare const rateLimiter: <E extends Env = Env>(options?: RateLimitOptions<E>) => MiddlewareHandler<E>;
167
+
168
+ export { type Algorithm, type HeadersFormat, MemoryStore, type RateLimitInfo, type RateLimitOptions, type RateLimitStore, type StoreResult, getClientIP, rateLimiter };
package/dist/index.js ADDED
@@ -0,0 +1,193 @@
1
+ // src/index.ts
2
+ var MemoryStore = class {
3
+ entries = /* @__PURE__ */ new Map();
4
+ windowMs = 6e4;
5
+ cleanupTimer;
6
+ init(windowMs) {
7
+ this.windowMs = windowMs;
8
+ this.cleanupTimer = setInterval(() => {
9
+ const now = Date.now();
10
+ for (const [key, entry] of this.entries) {
11
+ if (entry.reset <= now) {
12
+ this.entries.delete(key);
13
+ }
14
+ }
15
+ }, 6e4);
16
+ if (typeof this.cleanupTimer.unref === "function") {
17
+ this.cleanupTimer.unref();
18
+ }
19
+ }
20
+ increment(key) {
21
+ const now = Date.now();
22
+ const existing = this.entries.get(key);
23
+ if (!existing || existing.reset <= now) {
24
+ const reset = now + this.windowMs;
25
+ this.entries.set(key, { count: 1, reset });
26
+ return { count: 1, reset };
27
+ }
28
+ existing.count++;
29
+ return { count: existing.count, reset: existing.reset };
30
+ }
31
+ get(key) {
32
+ const entry = this.entries.get(key);
33
+ if (!entry || entry.reset <= Date.now()) {
34
+ return void 0;
35
+ }
36
+ return { count: entry.count, reset: entry.reset };
37
+ }
38
+ decrement(key) {
39
+ const entry = this.entries.get(key);
40
+ if (entry && entry.count > 0) {
41
+ entry.count--;
42
+ }
43
+ }
44
+ resetKey(key) {
45
+ this.entries.delete(key);
46
+ }
47
+ shutdown() {
48
+ if (this.cleanupTimer) {
49
+ clearInterval(this.cleanupTimer);
50
+ }
51
+ this.entries.clear();
52
+ }
53
+ };
54
+ var defaultStore;
55
+ function setHeaders(c, info, format) {
56
+ if (format === false) {
57
+ return;
58
+ }
59
+ const resetSeconds = Math.max(0, Math.ceil((info.reset - Date.now()) / 1e3));
60
+ switch (format) {
61
+ case "draft-7":
62
+ c.header("RateLimit-Limit", String(info.limit));
63
+ c.header("RateLimit-Remaining", String(info.remaining));
64
+ c.header("RateLimit-Reset", String(resetSeconds));
65
+ break;
66
+ case "draft-6":
67
+ default:
68
+ c.header("X-RateLimit-Limit", String(info.limit));
69
+ c.header("X-RateLimit-Remaining", String(info.remaining));
70
+ c.header("X-RateLimit-Reset", String(Math.ceil(info.reset / 1e3)));
71
+ break;
72
+ }
73
+ }
74
+ function getClientIP(c) {
75
+ const cfIP = c.req.header("cf-connecting-ip");
76
+ if (cfIP) {
77
+ return cfIP;
78
+ }
79
+ const xRealIP = c.req.header("x-real-ip");
80
+ if (xRealIP) {
81
+ return xRealIP;
82
+ }
83
+ const xff = c.req.header("x-forwarded-for");
84
+ if (xff) {
85
+ return xff.split(",")[0].trim();
86
+ }
87
+ return "unknown";
88
+ }
89
+ function createDefaultResponse(info) {
90
+ const retryAfter = Math.max(0, Math.ceil((info.reset - Date.now()) / 1e3));
91
+ return new Response("Rate limit exceeded", {
92
+ status: 429,
93
+ headers: {
94
+ "Content-Type": "text/plain",
95
+ "Retry-After": String(retryAfter)
96
+ }
97
+ });
98
+ }
99
+ async function checkSlidingWindow(store, key, limit, windowMs) {
100
+ const now = Date.now();
101
+ const currentWindowStart = Math.floor(now / windowMs) * windowMs;
102
+ const previousWindowStart = currentWindowStart - windowMs;
103
+ const previousKey = `${key}:${previousWindowStart}`;
104
+ const currentKey = `${key}:${currentWindowStart}`;
105
+ const current = await store.increment(currentKey);
106
+ let previousCount = 0;
107
+ if (store.get) {
108
+ const prev = await store.get(previousKey);
109
+ previousCount = prev?.count ?? 0;
110
+ }
111
+ const elapsedMs = now - currentWindowStart;
112
+ const weight = (windowMs - elapsedMs) / windowMs;
113
+ const estimatedCount = Math.floor(previousCount * weight) + current.count;
114
+ const remaining = Math.max(0, limit - estimatedCount);
115
+ const allowed = estimatedCount <= limit;
116
+ const reset = currentWindowStart + windowMs;
117
+ return {
118
+ allowed,
119
+ info: { limit, remaining, reset }
120
+ };
121
+ }
122
+ async function checkFixedWindow(store, key, limit, windowMs) {
123
+ const now = Date.now();
124
+ const windowStart = Math.floor(now / windowMs) * windowMs;
125
+ const windowKey = `${key}:${windowStart}`;
126
+ const { count, reset } = await store.increment(windowKey);
127
+ const remaining = Math.max(0, limit - count);
128
+ const allowed = count <= limit;
129
+ return {
130
+ allowed,
131
+ info: { limit, remaining, reset }
132
+ };
133
+ }
134
+ var rateLimiter = (options) => {
135
+ const opts = {
136
+ limit: 60,
137
+ windowMs: 6e4,
138
+ algorithm: "sliding-window",
139
+ store: void 0,
140
+ keyGenerator: getClientIP,
141
+ handler: void 0,
142
+ headers: "draft-6",
143
+ skip: void 0,
144
+ skipSuccessfulRequests: false,
145
+ skipFailedRequests: false,
146
+ onRateLimited: void 0,
147
+ ...options
148
+ };
149
+ const store = opts.store ?? (defaultStore ??= new MemoryStore());
150
+ let initialized = false;
151
+ return async function rateLimiter2(c, next) {
152
+ if (!initialized && store.init) {
153
+ await store.init(opts.windowMs);
154
+ initialized = true;
155
+ }
156
+ if (opts.skip) {
157
+ const shouldSkip = await opts.skip(c);
158
+ if (shouldSkip) {
159
+ return next();
160
+ }
161
+ }
162
+ const key = await opts.keyGenerator(c);
163
+ const limit = typeof opts.limit === "function" ? await opts.limit(c) : opts.limit;
164
+ const { allowed, info } = opts.algorithm === "sliding-window" ? await checkSlidingWindow(store, key, limit, opts.windowMs) : await checkFixedWindow(store, key, limit, opts.windowMs);
165
+ c.set("rateLimit", info);
166
+ setHeaders(c, info, opts.headers);
167
+ if (!allowed) {
168
+ if (opts.onRateLimited) {
169
+ await opts.onRateLimited(c, info);
170
+ }
171
+ if (opts.handler) {
172
+ return opts.handler(c, info);
173
+ }
174
+ return createDefaultResponse(info);
175
+ }
176
+ await next();
177
+ if (opts.skipSuccessfulRequests || opts.skipFailedRequests) {
178
+ const status = c.res.status;
179
+ const shouldDecrement = opts.skipSuccessfulRequests && status >= 200 && status < 300 || opts.skipFailedRequests && status >= 400;
180
+ if (shouldDecrement && store.decrement) {
181
+ const windowStart = Math.floor(Date.now() / opts.windowMs) * opts.windowMs;
182
+ const windowKey = `${key}:${windowStart}`;
183
+ await store.decrement(windowKey);
184
+ }
185
+ }
186
+ };
187
+ };
188
+ export {
189
+ MemoryStore,
190
+ getClientIP,
191
+ rateLimiter
192
+ };
193
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * @module\n * Rate Limit Middleware for Hono.\n */\n\nimport type { Context, Env, MiddlewareHandler } from \"hono\";\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * Rate limit information for a single request\n */\nexport type RateLimitInfo = {\n /** Maximum requests allowed in window */\n limit: number;\n /** Remaining requests in current window */\n remaining: number;\n /** Unix timestamp (ms) when window resets */\n reset: number;\n};\n\n/**\n * Result from store increment operation\n */\nexport type StoreResult = {\n /** Current request count in window */\n count: number;\n /** When the window resets (Unix timestamp ms) */\n reset: number;\n};\n\n/**\n * Header format versions\n */\nexport type HeadersFormat =\n | \"draft-6\" // X-RateLimit-* headers\n | \"draft-7\" // RateLimit-* without structured fields\n | false; // Disable headers\n\n/**\n * Rate limit algorithm\n */\nexport type Algorithm = \"fixed-window\" | \"sliding-window\";\n\n/**\n * Store interface for rate limit state\n */\nexport type RateLimitStore = {\n /**\n * Initialize store. Called once before first use.\n */\n init?: (windowMs: number) => void | Promise<void>;\n\n /**\n * Increment counter for key and return current state.\n */\n increment: (key: string) => StoreResult | Promise<StoreResult>;\n\n /**\n * Decrement counter for key.\n */\n decrement?: (key: string) => void | Promise<void>;\n\n /**\n * Reset a specific key.\n */\n resetKey: (key: string) => void | Promise<void>;\n\n /**\n * Get current state for key.\n */\n get?: (\n key: string,\n ) => StoreResult | Promise<StoreResult | undefined> | undefined;\n\n /**\n * Graceful shutdown.\n */\n shutdown?: () => void | Promise<void>;\n};\n\n/**\n * Options for rate limit middleware\n */\nexport type RateLimitOptions<E extends Env = Env> = {\n /**\n * Maximum requests allowed in the time window.\n * @default 60\n */\n limit?: number | ((c: Context<E>) => number | Promise<number>);\n\n /**\n * Time window in milliseconds.\n * @default 60000 (1 minute)\n */\n windowMs?: number;\n\n /**\n * Rate limiting algorithm.\n * @default 'sliding-window'\n */\n algorithm?: Algorithm;\n\n /**\n * Storage backend for rate limit state.\n * @default MemoryStore\n */\n store?: RateLimitStore;\n\n /**\n * Generate unique key for each client.\n * @default IP address from headers\n */\n keyGenerator?: (c: Context<E>) => string | Promise<string>;\n\n /**\n * Handler called when rate limit is exceeded.\n */\n handler?: (\n c: Context<E>,\n info: RateLimitInfo,\n ) => Response | Promise<Response>;\n\n /**\n * HTTP header format to use.\n * @default 'draft-6'\n */\n headers?: HeadersFormat;\n\n /**\n * Skip rate limiting for certain requests.\n */\n skip?: (c: Context<E>) => boolean | Promise<boolean>;\n\n /**\n * Don't count successful (2xx) requests against limit.\n * @default false\n */\n skipSuccessfulRequests?: boolean;\n\n /**\n * Don't count failed (4xx, 5xx) requests against limit.\n * @default false\n */\n skipFailedRequests?: boolean;\n\n /**\n * Callback when a request is rate limited.\n */\n onRateLimited?: (c: Context<E>, info: RateLimitInfo) => void | Promise<void>;\n};\n\n// ============================================================================\n// Context Variable Type Extension\n// ============================================================================\n\ndeclare module \"hono\" {\n interface ContextVariableMap {\n rateLimit?: RateLimitInfo;\n }\n}\n\n// ============================================================================\n// Memory Store\n// ============================================================================\n\ntype MemoryEntry = {\n count: number;\n reset: number;\n};\n\n/**\n * In-memory store for rate limiting.\n * Suitable for single-instance deployments.\n */\nexport class MemoryStore implements RateLimitStore {\n private entries = new Map<string, MemoryEntry>();\n private windowMs = 60_000;\n private cleanupTimer?: ReturnType<typeof setInterval>;\n\n init(windowMs: number): void {\n this.windowMs = windowMs;\n\n // Cleanup expired entries every minute\n this.cleanupTimer = setInterval(() => {\n const now = Date.now();\n for (const [key, entry] of this.entries) {\n if (entry.reset <= now) {\n this.entries.delete(key);\n }\n }\n }, 60_000);\n\n // Don't keep process alive for cleanup\n if (typeof this.cleanupTimer.unref === \"function\") {\n this.cleanupTimer.unref();\n }\n }\n\n increment(key: string): StoreResult {\n const now = Date.now();\n const existing = this.entries.get(key);\n\n if (!existing || existing.reset <= now) {\n // New window\n const reset = now + this.windowMs;\n this.entries.set(key, { count: 1, reset });\n return { count: 1, reset };\n }\n\n // Increment existing\n existing.count++;\n return { count: existing.count, reset: existing.reset };\n }\n\n get(key: string): StoreResult | undefined {\n const entry = this.entries.get(key);\n if (!entry || entry.reset <= Date.now()) {\n return undefined;\n }\n return { count: entry.count, reset: entry.reset };\n }\n\n decrement(key: string): void {\n const entry = this.entries.get(key);\n if (entry && entry.count > 0) {\n entry.count--;\n }\n }\n\n resetKey(key: string): void {\n this.entries.delete(key);\n }\n\n shutdown(): void {\n if (this.cleanupTimer) {\n clearInterval(this.cleanupTimer);\n }\n this.entries.clear();\n }\n}\n\n// Singleton default store\nlet defaultStore: MemoryStore | undefined;\n\n// ============================================================================\n// Header Generation\n// ============================================================================\n\nfunction setHeaders(\n c: Context,\n info: RateLimitInfo,\n format: HeadersFormat,\n): void {\n if (format === false) {\n return;\n }\n\n const resetSeconds = Math.max(0, Math.ceil((info.reset - Date.now()) / 1000));\n\n switch (format) {\n case \"draft-7\":\n c.header(\"RateLimit-Limit\", String(info.limit));\n c.header(\"RateLimit-Remaining\", String(info.remaining));\n c.header(\"RateLimit-Reset\", String(resetSeconds));\n break;\n\n case \"draft-6\":\n default:\n c.header(\"X-RateLimit-Limit\", String(info.limit));\n c.header(\"X-RateLimit-Remaining\", String(info.remaining));\n c.header(\"X-RateLimit-Reset\", String(Math.ceil(info.reset / 1000)));\n break;\n }\n}\n\n// ============================================================================\n// Default Key Generator\n// ============================================================================\n\nfunction getClientIP(c: Context): string {\n // Platform-specific headers (most reliable)\n const cfIP = c.req.header(\"cf-connecting-ip\");\n if (cfIP) {\n return cfIP;\n }\n\n const xRealIP = c.req.header(\"x-real-ip\");\n if (xRealIP) {\n return xRealIP;\n }\n\n // X-Forwarded-For - take first IP\n const xff = c.req.header(\"x-forwarded-for\");\n if (xff) {\n return xff.split(\",\")[0].trim();\n }\n\n return \"unknown\";\n}\n\n// ============================================================================\n// Default Handler\n// ============================================================================\n\nfunction createDefaultResponse(info: RateLimitInfo): Response {\n const retryAfter = Math.max(0, Math.ceil((info.reset - Date.now()) / 1000));\n\n return new Response(\"Rate limit exceeded\", {\n status: 429,\n headers: {\n \"Content-Type\": \"text/plain\",\n \"Retry-After\": String(retryAfter),\n },\n });\n}\n\n// ============================================================================\n// Sliding Window Algorithm\n// ============================================================================\n\nasync function checkSlidingWindow(\n store: RateLimitStore,\n key: string,\n limit: number,\n windowMs: number,\n): Promise<{ allowed: boolean; info: RateLimitInfo }> {\n const now = Date.now();\n const currentWindowStart = Math.floor(now / windowMs) * windowMs;\n const previousWindowStart = currentWindowStart - windowMs;\n\n const previousKey = `${key}:${previousWindowStart}`;\n const currentKey = `${key}:${currentWindowStart}`;\n\n // Increment current window\n const current = await store.increment(currentKey);\n\n // Get previous window (may not exist)\n let previousCount = 0;\n if (store.get) {\n const prev = await store.get(previousKey);\n previousCount = prev?.count ?? 0;\n }\n\n // Cloudflare's weighted formula\n const elapsedMs = now - currentWindowStart;\n const weight = (windowMs - elapsedMs) / windowMs;\n const estimatedCount = Math.floor(previousCount * weight) + current.count;\n\n const remaining = Math.max(0, limit - estimatedCount);\n const allowed = estimatedCount <= limit;\n const reset = currentWindowStart + windowMs;\n\n return {\n allowed,\n info: { limit, remaining, reset },\n };\n}\n\n// ============================================================================\n// Fixed Window Algorithm\n// ============================================================================\n\nasync function checkFixedWindow(\n store: RateLimitStore,\n key: string,\n limit: number,\n windowMs: number,\n): Promise<{ allowed: boolean; info: RateLimitInfo }> {\n const now = Date.now();\n const windowStart = Math.floor(now / windowMs) * windowMs;\n const windowKey = `${key}:${windowStart}`;\n\n const { count, reset } = await store.increment(windowKey);\n\n const remaining = Math.max(0, limit - count);\n const allowed = count <= limit;\n\n return {\n allowed,\n info: { limit, remaining, reset },\n };\n}\n\n// ============================================================================\n// Main Middleware\n// ============================================================================\n\n/**\n * Rate Limit Middleware for Hono.\n *\n * @param {RateLimitOptions} [options] - Configuration options\n * @returns {MiddlewareHandler} Middleware handler\n *\n * @example\n * ```ts\n * import { Hono } from 'hono'\n * import { rateLimiter } from 'hono-rate-limit'\n *\n * const app = new Hono()\n *\n * // Basic usage - 60 requests per minute\n * app.use(rateLimiter())\n *\n * // Custom configuration\n * app.use('/api/*', rateLimiter({\n * limit: 100,\n * windowMs: 60 * 1000,\n * }))\n * ```\n */\nexport const rateLimiter = <E extends Env = Env>(\n options?: RateLimitOptions<E>,\n): MiddlewareHandler<E> => {\n // Merge with defaults\n const opts = {\n limit: 60 as number | ((c: Context<E>) => number | Promise<number>),\n windowMs: 60_000,\n algorithm: \"sliding-window\" as Algorithm,\n store: undefined as RateLimitStore | undefined,\n keyGenerator: getClientIP as (c: Context<E>) => string | Promise<string>,\n handler: undefined as\n | ((c: Context<E>, info: RateLimitInfo) => Response | Promise<Response>)\n | undefined,\n headers: \"draft-6\" as HeadersFormat,\n skip: undefined as\n | ((c: Context<E>) => boolean | Promise<boolean>)\n | undefined,\n skipSuccessfulRequests: false,\n skipFailedRequests: false,\n onRateLimited: undefined as\n | ((c: Context<E>, info: RateLimitInfo) => void | Promise<void>)\n | undefined,\n ...options,\n };\n\n // Use default store if none provided\n const store = opts.store ?? (defaultStore ??= new MemoryStore());\n\n // Track initialization\n let initialized = false;\n\n return async function rateLimiter(c, next) {\n // Initialize store on first request\n if (!initialized && store.init) {\n await store.init(opts.windowMs);\n initialized = true;\n }\n\n // Check if should skip\n if (opts.skip) {\n const shouldSkip = await opts.skip(c);\n if (shouldSkip) {\n return next();\n }\n }\n\n // Generate key\n const key = await opts.keyGenerator(c);\n\n // Get limit (may be dynamic)\n const limit =\n typeof opts.limit === \"function\" ? await opts.limit(c) : opts.limit;\n\n // Check rate limit\n const { allowed, info } =\n opts.algorithm === \"sliding-window\"\n ? await checkSlidingWindow(store, key, limit, opts.windowMs)\n : await checkFixedWindow(store, key, limit, opts.windowMs);\n\n // Set context variable for downstream middleware\n c.set(\"rateLimit\", info);\n\n // Set headers\n setHeaders(c, info, opts.headers);\n\n // Handle rate limited\n if (!allowed) {\n // Fire callback\n if (opts.onRateLimited) {\n await opts.onRateLimited(c, info);\n }\n\n // Custom handler or default\n if (opts.handler) {\n return opts.handler(c, info);\n }\n return createDefaultResponse(info);\n }\n\n // Continue\n await next();\n\n // Handle skip options after response\n if (opts.skipSuccessfulRequests || opts.skipFailedRequests) {\n const status = c.res.status;\n const shouldDecrement =\n (opts.skipSuccessfulRequests && status >= 200 && status < 300) ||\n (opts.skipFailedRequests && status >= 400);\n\n if (shouldDecrement && store.decrement) {\n const windowStart =\n Math.floor(Date.now() / opts.windowMs) * opts.windowMs;\n const windowKey = `${key}:${windowStart}`;\n await store.decrement(windowKey);\n }\n }\n };\n};\n\n// ============================================================================\n// Exports\n// ============================================================================\n\nexport { getClientIP };\n"],"mappings":";AAiLO,IAAM,cAAN,MAA4C;AAAA,EACzC,UAAU,oBAAI,IAAyB;AAAA,EACvC,WAAW;AAAA,EACX;AAAA,EAER,KAAK,UAAwB;AAC3B,SAAK,WAAW;AAGhB,SAAK,eAAe,YAAY,MAAM;AACpC,YAAM,MAAM,KAAK,IAAI;AACrB,iBAAW,CAAC,KAAK,KAAK,KAAK,KAAK,SAAS;AACvC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;AACF;","names":["rateLimiter"]}
@@ -0,0 +1,89 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/store/cloudflare-kv.ts
21
+ var cloudflare_kv_exports = {};
22
+ __export(cloudflare_kv_exports, {
23
+ CloudflareKVStore: () => CloudflareKVStore
24
+ });
25
+ module.exports = __toCommonJS(cloudflare_kv_exports);
26
+ var CloudflareKVStore = class {
27
+ namespace;
28
+ prefix;
29
+ windowMs = 6e4;
30
+ constructor(options) {
31
+ this.namespace = options.namespace;
32
+ this.prefix = options.prefix ?? "rl:";
33
+ }
34
+ init(windowMs) {
35
+ this.windowMs = windowMs;
36
+ }
37
+ async increment(key) {
38
+ const fullKey = `${this.prefix}${key}`;
39
+ const now = Date.now();
40
+ const ttlSeconds = Math.max(60, Math.ceil(this.windowMs / 1e3));
41
+ const existing = await this.namespace.get(fullKey, {
42
+ type: "json"
43
+ });
44
+ let count;
45
+ let reset;
46
+ if (!existing || existing.reset <= now) {
47
+ count = 1;
48
+ reset = now + this.windowMs;
49
+ } else {
50
+ count = existing.count + 1;
51
+ reset = existing.reset;
52
+ }
53
+ await this.namespace.put(fullKey, JSON.stringify({ count, reset }), {
54
+ expirationTtl: ttlSeconds
55
+ });
56
+ return { count, reset };
57
+ }
58
+ async get(key) {
59
+ const fullKey = `${this.prefix}${key}`;
60
+ const data = await this.namespace.get(fullKey, { type: "json" });
61
+ if (!data || data.reset <= Date.now()) {
62
+ return void 0;
63
+ }
64
+ return { count: data.count, reset: data.reset };
65
+ }
66
+ async decrement(key) {
67
+ const fullKey = `${this.prefix}${key}`;
68
+ const now = Date.now();
69
+ const existing = await this.namespace.get(fullKey, {
70
+ type: "json"
71
+ });
72
+ if (existing && existing.count > 0 && existing.reset > now) {
73
+ const ttlSeconds = Math.max(60, Math.ceil((existing.reset - now) / 1e3));
74
+ await this.namespace.put(
75
+ fullKey,
76
+ JSON.stringify({ count: existing.count - 1, reset: existing.reset }),
77
+ { expirationTtl: ttlSeconds }
78
+ );
79
+ }
80
+ }
81
+ async resetKey(key) {
82
+ await this.namespace.delete(`${this.prefix}${key}`);
83
+ }
84
+ };
85
+ // Annotate the CommonJS export names for ESM import in node:
86
+ 0 && (module.exports = {
87
+ CloudflareKVStore
88
+ });
89
+ //# sourceMappingURL=cloudflare-kv.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/store/cloudflare-kv.ts"],"sourcesContent":["/**\n * Cloudflare KV store for rate limiting.\n *\n * Note: KV is eventually consistent (~60s propagation).\n * For strict rate limiting, consider Durable Objects.\n */\n\nimport type { RateLimitStore, StoreResult } from \"../index\";\n\n/**\n * Cloudflare KV Namespace interface\n */\nexport type KVNamespace = {\n get: <T = string>(\n key: string,\n options?: { type: \"json\" },\n ) => Promise<T | null>;\n put: (\n key: string,\n value: string,\n options?: { expirationTtl?: number },\n ) => Promise<void>;\n delete: (key: string) => Promise<void>;\n};\n\n/**\n * Options for Cloudflare KV store\n */\nexport type CloudflareKVStoreOptions = {\n /**\n * KV Namespace binding\n */\n namespace: KVNamespace;\n\n /**\n * Key prefix for rate limit entries\n * @default 'rl:'\n */\n prefix?: string;\n};\n\ntype KVEntry = {\n count: number;\n reset: number;\n};\n\n/**\n * Cloudflare KV store for rate limiting in Workers.\n *\n * @example\n * ```ts\n * import { rateLimiter } from 'hono-rate-limit'\n * import { CloudflareKVStore } from 'hono-rate-limit/store/cloudflare-kv'\n *\n * type Bindings = { RATE_LIMIT_KV: KVNamespace }\n *\n * app.use('*', async (c, next) => {\n * const limiter = rateLimiter({\n * store: new CloudflareKVStore({ namespace: c.env.RATE_LIMIT_KV }),\n * })\n * return limiter(c, next)\n * })\n * ```\n */\nexport class CloudflareKVStore implements RateLimitStore {\n private namespace: KVNamespace;\n private prefix: string;\n private windowMs = 60_000;\n\n constructor(options: CloudflareKVStoreOptions) {\n this.namespace = options.namespace;\n this.prefix = options.prefix ?? \"rl:\";\n }\n\n init(windowMs: number): void {\n this.windowMs = windowMs;\n }\n\n async increment(key: string): Promise<StoreResult> {\n const fullKey = `${this.prefix}${key}`;\n const now = Date.now();\n\n // KV minimum TTL is 60 seconds\n const ttlSeconds = Math.max(60, Math.ceil(this.windowMs / 1000));\n\n const existing = await this.namespace.get<KVEntry>(fullKey, {\n type: \"json\",\n });\n\n let count: number;\n let reset: number;\n\n if (!existing || existing.reset <= now) {\n // New window\n count = 1;\n reset = now + this.windowMs;\n } else {\n // Increment\n count = existing.count + 1;\n reset = existing.reset;\n }\n\n await this.namespace.put(fullKey, JSON.stringify({ count, reset }), {\n expirationTtl: ttlSeconds,\n });\n\n return { count, reset };\n }\n\n async get(key: string): Promise<StoreResult | undefined> {\n const fullKey = `${this.prefix}${key}`;\n const data = await this.namespace.get<KVEntry>(fullKey, { type: \"json\" });\n\n if (!data || data.reset <= Date.now()) {\n return undefined;\n }\n\n return { count: data.count, reset: data.reset };\n }\n\n async decrement(key: string): Promise<void> {\n const fullKey = `${this.prefix}${key}`;\n const now = Date.now();\n\n const existing = await this.namespace.get<KVEntry>(fullKey, {\n type: \"json\",\n });\n\n if (existing && existing.count > 0 && existing.reset > now) {\n const ttlSeconds = Math.max(60, Math.ceil((existing.reset - now) / 1000));\n await this.namespace.put(\n fullKey,\n JSON.stringify({ count: existing.count - 1, reset: existing.reset }),\n { expirationTtl: ttlSeconds },\n );\n }\n }\n\n async resetKey(key: string): Promise<void> {\n await this.namespace.delete(`${this.prefix}${key}`);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAgEO,IAAM,oBAAN,MAAkD;AAAA,EAC/C;AAAA,EACA;AAAA,EACA,WAAW;AAAA,EAEnB,YAAY,SAAmC;AAC7C,SAAK,YAAY,QAAQ;AACzB,SAAK,SAAS,QAAQ,UAAU;AAAA,EAClC;AAAA,EAEA,KAAK,UAAwB;AAC3B,SAAK,WAAW;AAAA,EAClB;AAAA,EAEA,MAAM,UAAU,KAAmC;AACjD,UAAM,UAAU,GAAG,KAAK,MAAM,GAAG,GAAG;AACpC,UAAM,MAAM,KAAK,IAAI;AAGrB,UAAM,aAAa,KAAK,IAAI,IAAI,KAAK,KAAK,KAAK,WAAW,GAAI,CAAC;AAE/D,UAAM,WAAW,MAAM,KAAK,UAAU,IAAa,SAAS;AAAA,MAC1D,MAAM;AAAA,IACR,CAAC;AAED,QAAI;AACJ,QAAI;AAEJ,QAAI,CAAC,YAAY,SAAS,SAAS,KAAK;AAEtC,cAAQ;AACR,cAAQ,MAAM,KAAK;AAAA,IACrB,OAAO;AAEL,cAAQ,SAAS,QAAQ;AACzB,cAAQ,SAAS;AAAA,IACnB;AAEA,UAAM,KAAK,UAAU,IAAI,SAAS,KAAK,UAAU,EAAE,OAAO,MAAM,CAAC,GAAG;AAAA,MAClE,eAAe;AAAA,IACjB,CAAC;AAED,WAAO,EAAE,OAAO,MAAM;AAAA,EACxB;AAAA,EAEA,MAAM,IAAI,KAA+C;AACvD,UAAM,UAAU,GAAG,KAAK,MAAM,GAAG,GAAG;AACpC,UAAM,OAAO,MAAM,KAAK,UAAU,IAAa,SAAS,EAAE,MAAM,OAAO,CAAC;AAExE,QAAI,CAAC,QAAQ,KAAK,SAAS,KAAK,IAAI,GAAG;AACrC,aAAO;AAAA,IACT;AAEA,WAAO,EAAE,OAAO,KAAK,OAAO,OAAO,KAAK,MAAM;AAAA,EAChD;AAAA,EAEA,MAAM,UAAU,KAA4B;AAC1C,UAAM,UAAU,GAAG,KAAK,MAAM,GAAG,GAAG;AACpC,UAAM,MAAM,KAAK,IAAI;AAErB,UAAM,WAAW,MAAM,KAAK,UAAU,IAAa,SAAS;AAAA,MAC1D,MAAM;AAAA,IACR,CAAC;AAED,QAAI,YAAY,SAAS,QAAQ,KAAK,SAAS,QAAQ,KAAK;AAC1D,YAAM,aAAa,KAAK,IAAI,IAAI,KAAK,MAAM,SAAS,QAAQ,OAAO,GAAI,CAAC;AACxE,YAAM,KAAK,UAAU;AAAA,QACnB;AAAA,QACA,KAAK,UAAU,EAAE,OAAO,SAAS,QAAQ,GAAG,OAAO,SAAS,MAAM,CAAC;AAAA,QACnE,EAAE,eAAe,WAAW;AAAA,MAC9B;AAAA,IACF;AAAA,EACF;AAAA,EAEA,MAAM,SAAS,KAA4B;AACzC,UAAM,KAAK,UAAU,OAAO,GAAG,KAAK,MAAM,GAAG,GAAG,EAAE;AAAA,EACpD;AACF;","names":[]}
@@ -0,0 +1,67 @@
1
+ import { RateLimitStore, StoreResult } from '../index.cjs';
2
+ import 'hono';
3
+
4
+ /**
5
+ * Cloudflare KV store for rate limiting.
6
+ *
7
+ * Note: KV is eventually consistent (~60s propagation).
8
+ * For strict rate limiting, consider Durable Objects.
9
+ */
10
+
11
+ /**
12
+ * Cloudflare KV Namespace interface
13
+ */
14
+ type KVNamespace = {
15
+ get: <T = string>(key: string, options?: {
16
+ type: "json";
17
+ }) => Promise<T | null>;
18
+ put: (key: string, value: string, options?: {
19
+ expirationTtl?: number;
20
+ }) => Promise<void>;
21
+ delete: (key: string) => Promise<void>;
22
+ };
23
+ /**
24
+ * Options for Cloudflare KV store
25
+ */
26
+ type CloudflareKVStoreOptions = {
27
+ /**
28
+ * KV Namespace binding
29
+ */
30
+ namespace: KVNamespace;
31
+ /**
32
+ * Key prefix for rate limit entries
33
+ * @default 'rl:'
34
+ */
35
+ prefix?: string;
36
+ };
37
+ /**
38
+ * Cloudflare KV store for rate limiting in Workers.
39
+ *
40
+ * @example
41
+ * ```ts
42
+ * import { rateLimiter } from 'hono-rate-limit'
43
+ * import { CloudflareKVStore } from 'hono-rate-limit/store/cloudflare-kv'
44
+ *
45
+ * type Bindings = { RATE_LIMIT_KV: KVNamespace }
46
+ *
47
+ * app.use('*', async (c, next) => {
48
+ * const limiter = rateLimiter({
49
+ * store: new CloudflareKVStore({ namespace: c.env.RATE_LIMIT_KV }),
50
+ * })
51
+ * return limiter(c, next)
52
+ * })
53
+ * ```
54
+ */
55
+ declare class CloudflareKVStore implements RateLimitStore {
56
+ private namespace;
57
+ private prefix;
58
+ private windowMs;
59
+ constructor(options: CloudflareKVStoreOptions);
60
+ init(windowMs: number): void;
61
+ increment(key: string): Promise<StoreResult>;
62
+ get(key: string): Promise<StoreResult | undefined>;
63
+ decrement(key: string): Promise<void>;
64
+ resetKey(key: string): Promise<void>;
65
+ }
66
+
67
+ export { CloudflareKVStore, type CloudflareKVStoreOptions, type KVNamespace };
@@ -0,0 +1,67 @@
1
+ import { RateLimitStore, StoreResult } from '../index.js';
2
+ import 'hono';
3
+
4
+ /**
5
+ * Cloudflare KV store for rate limiting.
6
+ *
7
+ * Note: KV is eventually consistent (~60s propagation).
8
+ * For strict rate limiting, consider Durable Objects.
9
+ */
10
+
11
+ /**
12
+ * Cloudflare KV Namespace interface
13
+ */
14
+ type KVNamespace = {
15
+ get: <T = string>(key: string, options?: {
16
+ type: "json";
17
+ }) => Promise<T | null>;
18
+ put: (key: string, value: string, options?: {
19
+ expirationTtl?: number;
20
+ }) => Promise<void>;
21
+ delete: (key: string) => Promise<void>;
22
+ };
23
+ /**
24
+ * Options for Cloudflare KV store
25
+ */
26
+ type CloudflareKVStoreOptions = {
27
+ /**
28
+ * KV Namespace binding
29
+ */
30
+ namespace: KVNamespace;
31
+ /**
32
+ * Key prefix for rate limit entries
33
+ * @default 'rl:'
34
+ */
35
+ prefix?: string;
36
+ };
37
+ /**
38
+ * Cloudflare KV store for rate limiting in Workers.
39
+ *
40
+ * @example
41
+ * ```ts
42
+ * import { rateLimiter } from 'hono-rate-limit'
43
+ * import { CloudflareKVStore } from 'hono-rate-limit/store/cloudflare-kv'
44
+ *
45
+ * type Bindings = { RATE_LIMIT_KV: KVNamespace }
46
+ *
47
+ * app.use('*', async (c, next) => {
48
+ * const limiter = rateLimiter({
49
+ * store: new CloudflareKVStore({ namespace: c.env.RATE_LIMIT_KV }),
50
+ * })
51
+ * return limiter(c, next)
52
+ * })
53
+ * ```
54
+ */
55
+ declare class CloudflareKVStore implements RateLimitStore {
56
+ private namespace;
57
+ private prefix;
58
+ private windowMs;
59
+ constructor(options: CloudflareKVStoreOptions);
60
+ init(windowMs: number): void;
61
+ increment(key: string): Promise<StoreResult>;
62
+ get(key: string): Promise<StoreResult | undefined>;
63
+ decrement(key: string): Promise<void>;
64
+ resetKey(key: string): Promise<void>;
65
+ }
66
+
67
+ export { CloudflareKVStore, type CloudflareKVStoreOptions, type KVNamespace };