@jellyfungus/hono-rate-limiter 0.1.0 → 0.3.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 +239 -44
- package/dist/index.cjs +68 -4
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +124 -5
- package/dist/index.d.ts +124 -5
- package/dist/index.js +67 -4
- package/dist/index.js.map +1 -1
- package/dist/store/cloudflare-kv.cjs +7 -0
- package/dist/store/cloudflare-kv.cjs.map +1 -1
- package/dist/store/cloudflare-kv.d.cts +6 -0
- package/dist/store/cloudflare-kv.d.ts +6 -0
- package/dist/store/cloudflare-kv.js +7 -0
- package/dist/store/cloudflare-kv.js.map +1 -1
- package/dist/store/redis.cjs +7 -0
- package/dist/store/redis.cjs.map +1 -1
- package/dist/store/redis.d.cts +6 -0
- package/dist/store/redis.d.ts +6 -0
- package/dist/store/redis.js +7 -0
- package/dist/store/redis.js.map +1 -1
- package/dist/websocket.cjs +178 -0
- package/dist/websocket.cjs.map +1 -0
- package/dist/websocket.d.cts +81 -0
- package/dist/websocket.d.ts +81 -0
- package/dist/websocket.js +151 -0
- package/dist/websocket.js.map +1 -0
- package/package.json +10 -3
|
@@ -0,0 +1,151 @@
|
|
|
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
|
+
resetAll() {
|
|
48
|
+
this.entries.clear();
|
|
49
|
+
}
|
|
50
|
+
shutdown() {
|
|
51
|
+
if (this.cleanupTimer) {
|
|
52
|
+
clearInterval(this.cleanupTimer);
|
|
53
|
+
}
|
|
54
|
+
this.entries.clear();
|
|
55
|
+
}
|
|
56
|
+
};
|
|
57
|
+
|
|
58
|
+
// src/websocket.ts
|
|
59
|
+
async function checkSlidingWindow(store, key, limit, windowMs) {
|
|
60
|
+
const now = Date.now();
|
|
61
|
+
const currentWindowStart = Math.floor(now / windowMs) * windowMs;
|
|
62
|
+
const previousWindowStart = currentWindowStart - windowMs;
|
|
63
|
+
const previousKey = `ws:${key}:${previousWindowStart}`;
|
|
64
|
+
const currentKey = `ws:${key}:${currentWindowStart}`;
|
|
65
|
+
const current = await store.increment(currentKey);
|
|
66
|
+
let previousCount = 0;
|
|
67
|
+
if (store.get) {
|
|
68
|
+
const prev = await store.get(previousKey);
|
|
69
|
+
previousCount = prev?.count ?? 0;
|
|
70
|
+
}
|
|
71
|
+
const elapsedMs = now - currentWindowStart;
|
|
72
|
+
const weight = (windowMs - elapsedMs) / windowMs;
|
|
73
|
+
const estimatedCount = Math.floor(previousCount * weight) + current.count;
|
|
74
|
+
const remaining = Math.max(0, limit - estimatedCount);
|
|
75
|
+
const allowed = estimatedCount <= limit;
|
|
76
|
+
const reset = currentWindowStart + windowMs;
|
|
77
|
+
return {
|
|
78
|
+
allowed,
|
|
79
|
+
info: { limit, remaining, reset }
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
async function checkFixedWindow(store, key, limit, windowMs) {
|
|
83
|
+
const now = Date.now();
|
|
84
|
+
const windowStart = Math.floor(now / windowMs) * windowMs;
|
|
85
|
+
const windowKey = `ws:${key}:${windowStart}`;
|
|
86
|
+
const { count, reset } = await store.increment(windowKey);
|
|
87
|
+
const remaining = Math.max(0, limit - count);
|
|
88
|
+
const allowed = count <= limit;
|
|
89
|
+
return {
|
|
90
|
+
allowed,
|
|
91
|
+
info: { limit, remaining, reset }
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
var wsDefaultStore;
|
|
95
|
+
function webSocketLimiter(options) {
|
|
96
|
+
const {
|
|
97
|
+
limit = 100,
|
|
98
|
+
windowMs = 6e4,
|
|
99
|
+
algorithm = "sliding-window",
|
|
100
|
+
store = wsDefaultStore ??= new MemoryStore(),
|
|
101
|
+
keyGenerator,
|
|
102
|
+
handler = (ws, info) => {
|
|
103
|
+
const retryAfter = Math.ceil((info.reset - Date.now()) / 1e3);
|
|
104
|
+
ws.close(1008, `Rate limit exceeded. Retry after ${retryAfter}s`);
|
|
105
|
+
},
|
|
106
|
+
skip
|
|
107
|
+
} = options;
|
|
108
|
+
let initialized = false;
|
|
109
|
+
return (createEvents) => {
|
|
110
|
+
return async (c) => {
|
|
111
|
+
if (!initialized && store.init) {
|
|
112
|
+
await store.init(windowMs);
|
|
113
|
+
initialized = true;
|
|
114
|
+
}
|
|
115
|
+
const key = await keyGenerator(c);
|
|
116
|
+
const currentLimit = typeof limit === "function" ? await limit(c) : limit;
|
|
117
|
+
const events = await createEvents(c);
|
|
118
|
+
return {
|
|
119
|
+
...events,
|
|
120
|
+
onMessage: async (event, ws) => {
|
|
121
|
+
if (skip) {
|
|
122
|
+
const shouldSkip = await skip(event, ws);
|
|
123
|
+
if (shouldSkip) {
|
|
124
|
+
await events.onMessage?.(event, ws);
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
const { allowed, info } = algorithm === "sliding-window" ? await checkSlidingWindow(store, key, currentLimit, windowMs) : await checkFixedWindow(store, key, currentLimit, windowMs);
|
|
129
|
+
if (!allowed) {
|
|
130
|
+
handler(ws, info);
|
|
131
|
+
return;
|
|
132
|
+
}
|
|
133
|
+
await events.onMessage?.(event, ws);
|
|
134
|
+
},
|
|
135
|
+
onOpen: async (event, ws) => {
|
|
136
|
+
await events.onOpen?.(event, ws);
|
|
137
|
+
},
|
|
138
|
+
onClose: async (event, ws) => {
|
|
139
|
+
await events.onClose?.(event, ws);
|
|
140
|
+
},
|
|
141
|
+
onError: async (event, ws) => {
|
|
142
|
+
await events.onError?.(event, ws);
|
|
143
|
+
}
|
|
144
|
+
};
|
|
145
|
+
};
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
export {
|
|
149
|
+
webSocketLimiter
|
|
150
|
+
};
|
|
151
|
+
//# sourceMappingURL=websocket.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/websocket.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 * Quota unit for IETF standard headers.\n * @see https://datatracker.ietf.org/doc/draft-ietf-httpapi-ratelimit-headers/\n */\nexport type QuotaUnit = \"requests\" | \"content-bytes\" | \"concurrent-requests\";\n\n/**\n * Header format options.\n *\n * ## \"legacy\" (default)\n * Common X-RateLimit-* headers used by GitHub, Twitter, and most APIs:\n * - `X-RateLimit-Limit`: max requests in window\n * - `X-RateLimit-Remaining`: remaining requests\n * - `X-RateLimit-Reset`: Unix timestamp (seconds) when window resets\n *\n * ## \"draft-6\"\n * IETF draft-06 format with individual RateLimit-* headers:\n * - `RateLimit-Policy`: policy description (e.g., `100;w=60`)\n * - `RateLimit-Limit`: max requests\n * - `RateLimit-Remaining`: remaining requests\n * - `RateLimit-Reset`: seconds until reset\n *\n * ## \"draft-7\"\n * IETF draft-07 format with combined RateLimit header:\n * - `RateLimit-Policy`: policy description\n * - `RateLimit`: combined (e.g., `limit=100, remaining=50, reset=30`)\n *\n * ## \"standard\"\n * Current IETF draft-08+ format with structured field values (RFC 9651):\n * - `RateLimit-Policy`: `\"name\";q=100;w=60`\n * - `RateLimit`: `\"name\";r=50;t=30`\n *\n * ## false\n * Disable all rate limit headers.\n *\n * @see https://datatracker.ietf.org/doc/draft-ietf-httpapi-ratelimit-headers/\n */\nexport type HeadersFormat =\n | \"legacy\" // X-RateLimit-* headers (GitHub/Twitter style)\n | \"draft-6\" // IETF draft-06: individual RateLimit-* headers\n | \"draft-7\" // IETF draft-07: combined RateLimit header\n | \"standard\" // IETF draft-08+: structured field format (current)\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 * Reset all keys.\n */\n resetAll?: () => 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 * Store access interface exposed in context\n */\nexport type RateLimitStoreAccess = {\n /** Get rate limit info for a key */\n getKey: (\n key: string,\n ) => StoreResult | Promise<StoreResult | undefined> | undefined;\n /** Reset rate limit for a key */\n resetKey: (key: string) => 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 *\n * - \"legacy\": X-RateLimit-* headers (GitHub/Twitter style, default)\n * - \"draft-6\": IETF draft-06 individual headers\n * - \"draft-7\": IETF draft-07 combined header\n * - \"standard\": IETF draft-08+ structured fields (current spec)\n * - false: Disable headers\n *\n * @default 'legacy'\n */\n headers?: HeadersFormat;\n\n /**\n * Policy identifier for IETF headers (draft-6+).\n * Used in RateLimit and RateLimit-Policy headers.\n * @default 'default'\n */\n identifier?: string;\n\n /**\n * Quota unit for IETF standard headers.\n * Only included in \"standard\" format when not \"requests\".\n * @default 'requests'\n */\n quotaUnit?: QuotaUnit;\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 * Cloudflare Rate Limiting binding interface\n */\nexport type RateLimitBinding = {\n limit: (options: { key: string }) => Promise<{ success: boolean }>;\n};\n\n/**\n * Options for Cloudflare Rate Limiting binding\n */\nexport type CloudflareRateLimitOptions<E extends Env = Env> = {\n /**\n * Cloudflare Rate Limiting binding from env\n */\n binding: RateLimitBinding | ((c: Context<E>) => RateLimitBinding);\n\n /**\n * Generate unique key for each client.\n */\n keyGenerator: (c: Context<E>) => string | Promise<string>;\n\n /**\n * Handler called when rate limit is exceeded.\n */\n handler?: (c: Context<E>) => Response | Promise<Response>;\n\n /**\n * Skip rate limiting for certain requests.\n */\n skip?: (c: Context<E>) => boolean | Promise<boolean>;\n};\n\n// ============================================================================\n// Context Variable Type Extension\n// ============================================================================\n\ndeclare module \"hono\" {\n interface ContextVariableMap {\n rateLimit?: RateLimitInfo;\n rateLimitStore?: RateLimitStoreAccess;\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 resetAll(): void {\n this.entries.clear();\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\n/**\n * Set rate limit response headers based on the configured format.\n *\n * @see https://datatracker.ietf.org/doc/draft-ietf-httpapi-ratelimit-headers/\n */\nfunction setHeaders(\n c: Context,\n info: RateLimitInfo,\n format: HeadersFormat,\n windowMs: number,\n identifier: string,\n quotaUnit: QuotaUnit,\n): void {\n if (format === false) {\n return;\n }\n\n const windowSeconds = Math.ceil(windowMs / 1000);\n const resetSeconds = Math.max(0, Math.ceil((info.reset - Date.now()) / 1000));\n\n switch (format) {\n case \"standard\":\n // IETF draft-08+ (current): Structured field values per RFC 9651\n // RateLimit-Policy: describes the quota policy\n // Format: \"name\";q=<quota>;w=<window>[;qu=\"<unit>\"]\n {\n let policy = `\"${identifier}\";q=${info.limit};w=${windowSeconds}`;\n if (quotaUnit !== \"requests\") {\n policy += `;qu=\"${quotaUnit}\"`;\n }\n c.header(\"RateLimit-Policy\", policy);\n // RateLimit: describes current service limits\n // Format: \"name\";r=<remaining>;t=<reset>\n c.header(\n \"RateLimit\",\n `\"${identifier}\";r=${info.remaining};t=${resetSeconds}`,\n );\n }\n break;\n\n case \"draft-7\":\n // IETF draft-07: Combined RateLimit header with comma-separated values\n c.header(\"RateLimit-Policy\", `${info.limit};w=${windowSeconds}`);\n c.header(\n \"RateLimit\",\n `limit=${info.limit}, remaining=${info.remaining}, reset=${resetSeconds}`,\n );\n break;\n\n case \"draft-6\":\n // IETF draft-06: Individual RateLimit-* headers\n c.header(\"RateLimit-Policy\", `${info.limit};w=${windowSeconds}`);\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 \"legacy\":\n default:\n // Common X-RateLimit-* headers (GitHub, Twitter, most APIs)\n // Uses Unix timestamp for reset (seconds since epoch)\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 '@jellyfungus/hono-rate-limiter'\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: \"legacy\" as HeadersFormat,\n identifier: \"default\",\n quotaUnit: \"requests\" as QuotaUnit,\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 // Expose store access in context\n c.set(\"rateLimitStore\", {\n getKey: store.get?.bind(store) ?? (() => undefined),\n resetKey: store.resetKey.bind(store),\n });\n\n // Set headers\n setHeaders(\n c,\n info,\n opts.headers,\n opts.windowMs,\n opts.identifier,\n opts.quotaUnit,\n );\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// Cloudflare Rate Limiting Binding Middleware\n// ============================================================================\n\n/**\n * Rate limiter using Cloudflare's built-in Rate Limiting binding.\n *\n * This uses Cloudflare's globally distributed rate limiting infrastructure,\n * which is ideal for high-traffic applications.\n *\n * @example\n * ```ts\n * import { cloudflareRateLimiter } from '@jellyfungus/hono-rate-limiter'\n *\n * type Bindings = { RATE_LIMITER: RateLimitBinding }\n *\n * const app = new Hono<{ Bindings: Bindings }>()\n *\n * app.use(cloudflareRateLimiter({\n * binding: (c) => c.env.RATE_LIMITER,\n * keyGenerator: (c) => c.req.header('cf-connecting-ip') ?? 'unknown',\n * }))\n * ```\n */\nexport const cloudflareRateLimiter = <E extends Env = Env>(\n options: CloudflareRateLimitOptions<E>,\n): MiddlewareHandler<E> => {\n const { binding, keyGenerator, handler, skip } = options;\n\n return async function cloudflareRateLimiter(c, next) {\n // Check if should skip\n if (skip) {\n const shouldSkip = await skip(c);\n if (shouldSkip) {\n return next();\n }\n }\n\n // Get binding (may be dynamic)\n const rateLimitBinding =\n typeof binding === \"function\" ? binding(c) : binding;\n\n // Generate key\n const key = await keyGenerator(c);\n\n // Check rate limit\n const { success } = await rateLimitBinding.limit({ key });\n\n if (!success) {\n if (handler) {\n return handler(c);\n }\n return new Response(\"Rate limit exceeded\", {\n status: 429,\n headers: { \"Content-Type\": \"text/plain\" },\n });\n }\n\n return next();\n };\n};\n\n// ============================================================================\n// Exports\n// ============================================================================\n\nexport { getClientIP };\n","/**\n * @module\n * WebSocket Rate Limiting for Hono.\n */\n\nimport type { Context, Env } from \"hono\";\nimport type { WSContext, WSEvents } from \"hono/ws\";\nimport {\n MemoryStore,\n type RateLimitStore,\n type RateLimitInfo,\n type StoreResult,\n type Algorithm,\n} from \"./index\";\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * Options for WebSocket rate limiting\n */\nexport type WSRateLimitOptions<E extends Env = Env> = {\n /**\n * Maximum messages allowed in the time window.\n * @default 100\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 * Required for WebSocket rate limiting.\n */\n keyGenerator: (c: Context<E>) => string | Promise<string>;\n\n /**\n * Handler called when rate limit is exceeded.\n * Default: closes connection with code 1008.\n */\n handler?: (ws: WSContext, info: RateLimitInfo) => void;\n\n /**\n * Skip rate limiting for certain messages.\n */\n skip?: (event: MessageEvent, ws: WSContext) => boolean | Promise<boolean>;\n};\n\n// ============================================================================\n// Sliding Window Algorithm (adapted for WS)\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 = `ws:${key}:${previousWindowStart}`;\n const currentKey = `ws:${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 (adapted for WS)\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 = `ws:${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// WebSocket Rate Limiter\n// ============================================================================\n\n// Singleton default store for WebSocket\nlet wsDefaultStore: MemoryStore | undefined;\n\n/**\n * WebSocket rate limiting middleware for Hono.\n *\n * Wraps your WebSocket event handlers to add rate limiting on messages.\n *\n * @example\n * ```ts\n * import { Hono } from 'hono'\n * import { createBunWebSocket } from 'hono/bun'\n * import { webSocketLimiter } from '@jellyfungus/hono-rate-limiter/websocket'\n *\n * const { upgradeWebSocket, websocket } = createBunWebSocket()\n *\n * const app = new Hono()\n *\n * const wsLimiter = webSocketLimiter({\n * limit: 100,\n * windowMs: 60_000,\n * keyGenerator: (c) => c.req.header('cf-connecting-ip') ?? 'unknown',\n * })\n *\n * app.get('/ws', upgradeWebSocket(wsLimiter((c) => ({\n * onMessage(event, ws) {\n * ws.send('Hello!')\n * },\n * }))))\n *\n * export default { port: 3000, fetch: app.fetch, websocket }\n * ```\n */\nexport function webSocketLimiter<E extends Env = Env>(\n options: WSRateLimitOptions<E>,\n): (\n createEvents: (c: Context<E>) => WSEvents | Promise<WSEvents>,\n) => (c: Context<E>) => Promise<WSEvents> {\n const {\n limit = 100,\n windowMs = 60_000,\n algorithm = \"sliding-window\",\n store = (wsDefaultStore ??= new MemoryStore()),\n keyGenerator,\n handler = (ws, info) => {\n const retryAfter = Math.ceil((info.reset - Date.now()) / 1000);\n ws.close(1008, `Rate limit exceeded. Retry after ${retryAfter}s`);\n },\n skip,\n } = options;\n\n // Track initialization\n let initialized = false;\n\n return (createEvents: (c: Context<E>) => WSEvents | Promise<WSEvents>) => {\n return async (c: Context<E>): Promise<WSEvents> => {\n // Initialize store on first use\n if (!initialized && store.init) {\n await store.init(windowMs);\n initialized = true;\n }\n\n // Get the key for this connection\n const key = await keyGenerator(c);\n\n // Get the limit (may be dynamic)\n const currentLimit = typeof limit === \"function\" ? await limit(c) : limit;\n\n // Get the original events\n const events = await createEvents(c);\n\n return {\n ...events,\n\n onMessage: async (event, ws) => {\n // Check if should skip\n if (skip) {\n const shouldSkip = await skip(event, ws);\n if (shouldSkip) {\n await events.onMessage?.(event, ws);\n return;\n }\n }\n\n // Check rate limit\n const { allowed, info } =\n algorithm === \"sliding-window\"\n ? await checkSlidingWindow(store, key, currentLimit, windowMs)\n : await checkFixedWindow(store, key, currentLimit, windowMs);\n\n if (!allowed) {\n handler(ws, info);\n return;\n }\n\n // Call original handler\n await events.onMessage?.(event, ws);\n },\n\n onOpen: async (event, ws) => {\n await events.onOpen?.(event, ws);\n },\n\n onClose: async (event, ws) => {\n await events.onClose?.(event, ws);\n },\n\n onError: async (event, ws) => {\n await events.onError?.(event, ws);\n },\n };\n };\n };\n}\n"],"mappings":";AA4RO,IAAM,cAAN,MAA4C;AAAA,EACzC,UAAU,oBAAI,IAAyB;AAAA,EACvC,WAAW;AAAA,EACX;AAAA,EAER,KAAK,UAAwB;AAC3B,SAAK,WAAW;AA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UAAU,OAAO,EAAE;AAAA,QAClC;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jellyfungus/hono-rate-limiter",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "0.3.0",
|
|
4
|
+
"description": "Production-ready rate limiting middleware for Hono web framework",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.cjs",
|
|
7
7
|
"module": "./dist/index.js",
|
|
@@ -21,6 +21,11 @@
|
|
|
21
21
|
"types": "./dist/store/cloudflare-kv.d.ts",
|
|
22
22
|
"import": "./dist/store/cloudflare-kv.js",
|
|
23
23
|
"require": "./dist/store/cloudflare-kv.cjs"
|
|
24
|
+
},
|
|
25
|
+
"./websocket": {
|
|
26
|
+
"types": "./dist/websocket.d.ts",
|
|
27
|
+
"import": "./dist/websocket.js",
|
|
28
|
+
"require": "./dist/websocket.cjs"
|
|
24
29
|
}
|
|
25
30
|
},
|
|
26
31
|
"files": [
|
|
@@ -43,7 +48,9 @@
|
|
|
43
48
|
"workers",
|
|
44
49
|
"deno",
|
|
45
50
|
"bun",
|
|
46
|
-
"node"
|
|
51
|
+
"node",
|
|
52
|
+
"sliding-window",
|
|
53
|
+
"websocket"
|
|
47
54
|
],
|
|
48
55
|
"author": "",
|
|
49
56
|
"license": "MIT",
|