hono-rate-limiter 0.2.0 → 0.2.1
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/index.cjs.d.ts +1 -0
- package/index.cjs.js +18 -0
- package/index.esm.js +14 -0
- package/package.json +4 -5
- package/src/core.d.ts +1 -1
- package/src/headers.d.ts +1 -1
- package/src/index.d.ts +2 -2
- package/src/memoryStore.d.ts +1 -1
- package/src/core.js +0 -1
- package/src/defaultKeyGenerator.js +0 -1
- package/src/headers.js +0 -1
- package/src/index.js +0 -1
- package/src/memoryStore.js +0 -1
- package/src/types.js +0 -1
- package/src/validations.js +0 -1
package/index.cjs.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from "./src/index";
|
package/index.cjs.js
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
Object.defineProperty(exports, '__esModule', { value: true });
|
|
4
|
+
|
|
5
|
+
var factory = require('hono/factory');
|
|
6
|
+
var adapter = require('hono/adapter');
|
|
7
|
+
|
|
8
|
+
function defaultKeyGenerator(c){const runtime=adapter.getRuntimeKey();let key=null;switch(runtime){case"workerd":key=c.req.raw.headers.get("CF-Connecting-IP");break;case"fastly":key=c.req.raw.headers.get("Fastly-Client-IP");break;case"other":key=c.req.raw.headers.get("x-real-ip");break;}return key??""}
|
|
9
|
+
|
|
10
|
+
const getResetSeconds=(resetTime,windowMs)=>{let resetSeconds;if(resetTime){const deltaSeconds=Math.ceil((resetTime.getTime()-Date.now())/1e3);resetSeconds=Math.max(0,deltaSeconds);}else if(windowMs){resetSeconds=Math.ceil(windowMs/1e3);}return resetSeconds};const setDraft6Headers=(context,info,windowMs)=>{if(context.finalized)return;const windowSeconds=Math.ceil(windowMs/1e3);const resetSeconds=getResetSeconds(info.resetTime);context.header("RateLimit-Policy",`${info.limit};w=${windowSeconds}`);context.header("RateLimit-Limit",info.limit.toString());context.header("RateLimit-Remaining",info.remaining.toString());if(resetSeconds)context.header("RateLimit-Reset",resetSeconds.toString());};const setDraft7Headers=(context,info,windowMs)=>{if(context.finalized)return;const windowSeconds=Math.ceil(windowMs/1e3);const resetSeconds=getResetSeconds(info.resetTime,windowMs);context.header("RateLimit-Policy",`${info.limit};w=${windowSeconds}`);context.header("RateLimit",`limit=${info.limit}, remaining=${info.remaining}, reset=${resetSeconds}`);};const setRetryAfterHeader=(context,info,windowMs)=>{if(context.finalized)return;const resetSeconds=getResetSeconds(info.resetTime,windowMs);context.header("Retry-After",resetSeconds?.toString());};
|
|
11
|
+
|
|
12
|
+
class MemoryStore{init(options){this.windowMs=options.windowMs;if(this.interval)clearInterval(this.interval);this.interval=setInterval(()=>{this.clearExpired();},this.windowMs);if(this.interval.unref)this.interval.unref();}async get(key){return this.current.get(key)??this.previous.get(key)}async increment(key){const client=this.getClient(key);const now=Date.now();if(client.resetTime.getTime()<=now){this.resetClient(client,now);}client.totalHits++;return client}async decrement(key){const client=this.getClient(key);if(client.totalHits>0)client.totalHits--;}async resetKey(key){this.current.delete(key);this.previous.delete(key);}async resetAll(){this.current.clear();this.previous.clear();}shutdown(){clearInterval(this.interval);void this.resetAll();}resetClient(client,now=Date.now()){client.totalHits=0;client.resetTime.setTime(now+this.windowMs);return client}getClient(key){if(this.current.has(key))return this.current.get(key);let client;if(this.previous.has(key)){client=this.previous.get(key);this.previous.delete(key);}else {client={totalHits:0,resetTime:new Date};this.resetClient(client);}this.current.set(key,client);return client}clearExpired(){this.previous=this.current;this.current=new Map;}constructor(){this.previous=new Map;this.current=new Map;this.localKeys=true;}}
|
|
13
|
+
|
|
14
|
+
const isValidStore=value=>!!value?.increment;
|
|
15
|
+
|
|
16
|
+
function rateLimiter(config){const{windowMs=6e4,limit=5,message="Too many requests, please try again later.",statusCode=429,standardHeaders="draft-6",requestPropertyName="rateLimit",requestStorePropertyName="rateLimitStore",skipFailedRequests=false,skipSuccessfulRequests=false,keyGenerator=defaultKeyGenerator,skip=()=>false,requestWasSuccessful=c=>c.res.status<400,handler=async(c,_next,options)=>{c.status(options.statusCode);const responseMessage=typeof options.message==="function"?await options.message(c):options.message;if(typeof responseMessage==="string")return c.text(responseMessage);return c.json(responseMessage)},store=new MemoryStore}=config??{};const options={windowMs,limit,message,statusCode,standardHeaders,requestPropertyName,requestStorePropertyName,skipFailedRequests,skipSuccessfulRequests,keyGenerator,skip,requestWasSuccessful,handler,store};if(!isValidStore(store))throw new Error("The store is not correctly implmented!");if(typeof store.init==="function")store.init(options);return factory.createMiddleware(async(c,next)=>{const isSkippable=await skip(c);if(isSkippable){await next();return}const key=await keyGenerator(c);const{totalHits,resetTime}=await store.increment(key);const retrieveLimit=typeof limit==="function"?limit(c):limit;const _limit=await retrieveLimit;const info={limit:_limit,used:totalHits,remaining:Math.max(_limit-totalHits,0),resetTime};c.set(requestPropertyName,info);c.set(requestStorePropertyName,{getKey:store.get?.bind(store),resetKey:store.resetKey.bind(store)});if(standardHeaders&&!c.finalized){if(standardHeaders==="draft-7"){setDraft7Headers(c,info,windowMs);}else {setDraft6Headers(c,info,windowMs);}}let decremented=false;const decrementKey=async()=>{if(!decremented){await store.decrement(key);decremented=true;}};const shouldSkipRequest=async()=>{if(skipFailedRequests||skipSuccessfulRequests){const wasRequestSuccessful=await requestWasSuccessful(c);if(skipFailedRequests&&!wasRequestSuccessful||skipSuccessfulRequests&&wasRequestSuccessful)await decrementKey();}};if(totalHits>_limit){if(standardHeaders){setRetryAfterHeader(c,info,windowMs);}await shouldSkipRequest();return handler(c,next,options)}try{await next();await shouldSkipRequest();}catch(error){if(skipFailedRequests)await decrementKey();}finally{if(!c.finalized)await decrementKey();}})}
|
|
17
|
+
|
|
18
|
+
exports.rateLimiter = rateLimiter;
|
package/index.esm.js
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { createMiddleware } from 'hono/factory';
|
|
2
|
+
import { getRuntimeKey } from 'hono/adapter';
|
|
3
|
+
|
|
4
|
+
function defaultKeyGenerator(c){const runtime=getRuntimeKey();let key=null;switch(runtime){case"workerd":key=c.req.raw.headers.get("CF-Connecting-IP");break;case"fastly":key=c.req.raw.headers.get("Fastly-Client-IP");break;case"other":key=c.req.raw.headers.get("x-real-ip");break;}return key??""}
|
|
5
|
+
|
|
6
|
+
const getResetSeconds=(resetTime,windowMs)=>{let resetSeconds;if(resetTime){const deltaSeconds=Math.ceil((resetTime.getTime()-Date.now())/1e3);resetSeconds=Math.max(0,deltaSeconds);}else if(windowMs){resetSeconds=Math.ceil(windowMs/1e3);}return resetSeconds};const setDraft6Headers=(context,info,windowMs)=>{if(context.finalized)return;const windowSeconds=Math.ceil(windowMs/1e3);const resetSeconds=getResetSeconds(info.resetTime);context.header("RateLimit-Policy",`${info.limit};w=${windowSeconds}`);context.header("RateLimit-Limit",info.limit.toString());context.header("RateLimit-Remaining",info.remaining.toString());if(resetSeconds)context.header("RateLimit-Reset",resetSeconds.toString());};const setDraft7Headers=(context,info,windowMs)=>{if(context.finalized)return;const windowSeconds=Math.ceil(windowMs/1e3);const resetSeconds=getResetSeconds(info.resetTime,windowMs);context.header("RateLimit-Policy",`${info.limit};w=${windowSeconds}`);context.header("RateLimit",`limit=${info.limit}, remaining=${info.remaining}, reset=${resetSeconds}`);};const setRetryAfterHeader=(context,info,windowMs)=>{if(context.finalized)return;const resetSeconds=getResetSeconds(info.resetTime,windowMs);context.header("Retry-After",resetSeconds?.toString());};
|
|
7
|
+
|
|
8
|
+
class MemoryStore{init(options){this.windowMs=options.windowMs;if(this.interval)clearInterval(this.interval);this.interval=setInterval(()=>{this.clearExpired();},this.windowMs);if(this.interval.unref)this.interval.unref();}async get(key){return this.current.get(key)??this.previous.get(key)}async increment(key){const client=this.getClient(key);const now=Date.now();if(client.resetTime.getTime()<=now){this.resetClient(client,now);}client.totalHits++;return client}async decrement(key){const client=this.getClient(key);if(client.totalHits>0)client.totalHits--;}async resetKey(key){this.current.delete(key);this.previous.delete(key);}async resetAll(){this.current.clear();this.previous.clear();}shutdown(){clearInterval(this.interval);void this.resetAll();}resetClient(client,now=Date.now()){client.totalHits=0;client.resetTime.setTime(now+this.windowMs);return client}getClient(key){if(this.current.has(key))return this.current.get(key);let client;if(this.previous.has(key)){client=this.previous.get(key);this.previous.delete(key);}else {client={totalHits:0,resetTime:new Date};this.resetClient(client);}this.current.set(key,client);return client}clearExpired(){this.previous=this.current;this.current=new Map;}constructor(){this.previous=new Map;this.current=new Map;this.localKeys=true;}}
|
|
9
|
+
|
|
10
|
+
const isValidStore=value=>!!value?.increment;
|
|
11
|
+
|
|
12
|
+
function rateLimiter(config){const{windowMs=6e4,limit=5,message="Too many requests, please try again later.",statusCode=429,standardHeaders="draft-6",requestPropertyName="rateLimit",requestStorePropertyName="rateLimitStore",skipFailedRequests=false,skipSuccessfulRequests=false,keyGenerator=defaultKeyGenerator,skip=()=>false,requestWasSuccessful=c=>c.res.status<400,handler=async(c,_next,options)=>{c.status(options.statusCode);const responseMessage=typeof options.message==="function"?await options.message(c):options.message;if(typeof responseMessage==="string")return c.text(responseMessage);return c.json(responseMessage)},store=new MemoryStore}=config??{};const options={windowMs,limit,message,statusCode,standardHeaders,requestPropertyName,requestStorePropertyName,skipFailedRequests,skipSuccessfulRequests,keyGenerator,skip,requestWasSuccessful,handler,store};if(!isValidStore(store))throw new Error("The store is not correctly implmented!");if(typeof store.init==="function")store.init(options);return createMiddleware(async(c,next)=>{const isSkippable=await skip(c);if(isSkippable){await next();return}const key=await keyGenerator(c);const{totalHits,resetTime}=await store.increment(key);const retrieveLimit=typeof limit==="function"?limit(c):limit;const _limit=await retrieveLimit;const info={limit:_limit,used:totalHits,remaining:Math.max(_limit-totalHits,0),resetTime};c.set(requestPropertyName,info);c.set(requestStorePropertyName,{getKey:store.get?.bind(store),resetKey:store.resetKey.bind(store)});if(standardHeaders&&!c.finalized){if(standardHeaders==="draft-7"){setDraft7Headers(c,info,windowMs);}else {setDraft6Headers(c,info,windowMs);}}let decremented=false;const decrementKey=async()=>{if(!decremented){await store.decrement(key);decremented=true;}};const shouldSkipRequest=async()=>{if(skipFailedRequests||skipSuccessfulRequests){const wasRequestSuccessful=await requestWasSuccessful(c);if(skipFailedRequests&&!wasRequestSuccessful||skipSuccessfulRequests&&wasRequestSuccessful)await decrementKey();}};if(totalHits>_limit){if(standardHeaders){setRetryAfterHeader(c,info,windowMs);}await shouldSkipRequest();return handler(c,next,options)}try{await next();await shouldSkipRequest();}catch(error){if(skipFailedRequests)await decrementKey();}finally{if(!c.finalized)await decrementKey();}})}
|
|
13
|
+
|
|
14
|
+
export { rateLimiter };
|
package/package.json
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "hono-rate-limiter",
|
|
3
|
-
"version": "0.2.
|
|
4
|
-
"type": "module",
|
|
3
|
+
"version": "0.2.1",
|
|
5
4
|
"license": "MIT",
|
|
6
5
|
"keywords": [
|
|
7
6
|
"hono",
|
|
@@ -27,7 +26,7 @@
|
|
|
27
26
|
"peerDependencies": {
|
|
28
27
|
"hono": "^4.1.1"
|
|
29
28
|
},
|
|
30
|
-
"
|
|
31
|
-
"
|
|
32
|
-
"
|
|
29
|
+
"types": "./index.cjs.d.ts",
|
|
30
|
+
"module": "./index.esm.js",
|
|
31
|
+
"main": "./index.cjs.js"
|
|
33
32
|
}
|
package/src/core.d.ts
CHANGED
package/src/headers.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { Context } from "hono";
|
|
2
|
-
import type { RateLimitInfo } from "./types
|
|
2
|
+
import type { RateLimitInfo } from "./types";
|
|
3
3
|
/**
|
|
4
4
|
* Sets `RateLimit-*`` headers based on the sixth draft of the IETF specification.
|
|
5
5
|
* See https://datatracker.ietf.org/doc/html/draft-ietf-httpapi-ratelimit-headers-06.
|
package/src/index.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export { rateLimiter
|
|
2
|
-
export
|
|
1
|
+
export { rateLimiter } from "./core";
|
|
2
|
+
export * from "./types";
|
package/src/memoryStore.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/// <reference types="node" />
|
|
2
|
-
import type { ClientRateLimitInfo, ConfigType, Store } from "./types
|
|
2
|
+
import type { ClientRateLimitInfo, ConfigType, Store } from "./types";
|
|
3
3
|
/**
|
|
4
4
|
* The record that stores information about a client - namely, how many times
|
|
5
5
|
* they have hit the endpoint, and when their hit count resets.
|
package/src/core.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{createMiddleware}from"hono/factory";import{defaultKeyGenerator}from"./defaultKeyGenerator.js";import{setDraft6Headers,setDraft7Headers,setRetryAfterHeader}from"./headers.js";import MemoryStore from"./memoryStore.js";import{isValidStore}from"./validations.js";export function rateLimiter(config){const{windowMs=6e4,limit=5,message="Too many requests, please try again later.",statusCode=429,standardHeaders="draft-6",requestPropertyName="rateLimit",requestStorePropertyName="rateLimitStore",skipFailedRequests=false,skipSuccessfulRequests=false,keyGenerator=defaultKeyGenerator,skip=()=>false,requestWasSuccessful=c=>c.res.status<400,handler=async(c,_next,options)=>{c.status(options.statusCode);const responseMessage=typeof options.message==="function"?await options.message(c):options.message;if(typeof responseMessage==="string")return c.text(responseMessage);return c.json(responseMessage)},store=new MemoryStore}=config??{};const options={windowMs,limit,message,statusCode,standardHeaders,requestPropertyName,requestStorePropertyName,skipFailedRequests,skipSuccessfulRequests,keyGenerator,skip,requestWasSuccessful,handler,store};if(!isValidStore(store))throw new Error("The store is not correctly implmented!");if(typeof store.init==="function")store.init(options);return createMiddleware(async(c,next)=>{const isSkippable=await skip(c);if(isSkippable){await next();return}const key=await keyGenerator(c);const{totalHits,resetTime}=await store.increment(key);const retrieveLimit=typeof limit==="function"?limit(c):limit;const _limit=await retrieveLimit;const info={limit:_limit,used:totalHits,remaining:Math.max(_limit-totalHits,0),resetTime};c.set(requestPropertyName,info);c.set(requestStorePropertyName,{getKey:store.get?.bind(store),resetKey:store.resetKey.bind(store)});if(standardHeaders&&!c.finalized){if(standardHeaders==="draft-7"){setDraft7Headers(c,info,windowMs)}else{setDraft6Headers(c,info,windowMs)}}let decremented=false;const decrementKey=async()=>{if(!decremented){await store.decrement(key);decremented=true}};const shouldSkipRequest=async()=>{if(skipFailedRequests||skipSuccessfulRequests){const wasRequestSuccessful=await requestWasSuccessful(c);if(skipFailedRequests&&!wasRequestSuccessful||skipSuccessfulRequests&&wasRequestSuccessful)await decrementKey()}};if(totalHits>_limit){if(standardHeaders){setRetryAfterHeader(c,info,windowMs)}await shouldSkipRequest();return handler(c,next,options)}try{await next();await shouldSkipRequest()}catch(error){if(skipFailedRequests)await decrementKey()}finally{if(!c.finalized)await decrementKey()}})}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{getRuntimeKey}from"hono/adapter";export function defaultKeyGenerator(c){const runtime=getRuntimeKey();let key=null;switch(runtime){case"workerd":key=c.req.raw.headers.get("CF-Connecting-IP");break;case"fastly":key=c.req.raw.headers.get("Fastly-Client-IP");break;case"other":key=c.req.raw.headers.get("x-real-ip");break;default:break}return key??""}
|
package/src/headers.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const getResetSeconds=(resetTime,windowMs)=>{let resetSeconds;if(resetTime){const deltaSeconds=Math.ceil((resetTime.getTime()-Date.now())/1e3);resetSeconds=Math.max(0,deltaSeconds)}else if(windowMs){resetSeconds=Math.ceil(windowMs/1e3)}return resetSeconds};export const setDraft6Headers=(context,info,windowMs)=>{if(context.finalized)return;const windowSeconds=Math.ceil(windowMs/1e3);const resetSeconds=getResetSeconds(info.resetTime);context.header("RateLimit-Policy",`${info.limit};w=${windowSeconds}`);context.header("RateLimit-Limit",info.limit.toString());context.header("RateLimit-Remaining",info.remaining.toString());if(resetSeconds)context.header("RateLimit-Reset",resetSeconds.toString())};export const setDraft7Headers=(context,info,windowMs)=>{if(context.finalized)return;const windowSeconds=Math.ceil(windowMs/1e3);const resetSeconds=getResetSeconds(info.resetTime,windowMs);context.header("RateLimit-Policy",`${info.limit};w=${windowSeconds}`);context.header("RateLimit",`limit=${info.limit}, remaining=${info.remaining}, reset=${resetSeconds}`)};export const setRetryAfterHeader=(context,info,windowMs)=>{if(context.finalized)return;const resetSeconds=getResetSeconds(info.resetTime,windowMs);context.header("Retry-After",resetSeconds?.toString())};
|
package/src/index.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export{rateLimiter as default,rateLimiter}from"./core.js";
|
package/src/memoryStore.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export class MemoryStore{init(options){this.windowMs=options.windowMs;if(this.interval)clearInterval(this.interval);this.interval=setInterval(()=>{this.clearExpired()},this.windowMs);if(this.interval.unref)this.interval.unref()}async get(key){return this.current.get(key)??this.previous.get(key)}async increment(key){const client=this.getClient(key);const now=Date.now();if(client.resetTime.getTime()<=now){this.resetClient(client,now)}client.totalHits++;return client}async decrement(key){const client=this.getClient(key);if(client.totalHits>0)client.totalHits--}async resetKey(key){this.current.delete(key);this.previous.delete(key)}async resetAll(){this.current.clear();this.previous.clear()}shutdown(){clearInterval(this.interval);void this.resetAll()}resetClient(client,now=Date.now()){client.totalHits=0;client.resetTime.setTime(now+this.windowMs);return client}getClient(key){if(this.current.has(key))return this.current.get(key);let client;if(this.previous.has(key)){client=this.previous.get(key);this.previous.delete(key)}else{client={totalHits:0,resetTime:new Date};this.resetClient(client)}this.current.set(key,client);return client}clearExpired(){this.previous=this.current;this.current=new Map}constructor(){this.previous=new Map;this.current=new Map;this.localKeys=true}}export default MemoryStore;
|
package/src/types.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export{};
|
package/src/validations.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export const isValidStore=value=>!!value?.increment;
|