npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@hubspire/rate-limiter

v1.0.5

Published

This package provides a GraphQL directive `@rateLimit` for rate limiting GraphQL queries and mutations. This directive helps to prevent abuse and manage resources efficiently by limiting the number of requests a client can make within a specified time win

Downloads

902

Readme

🚀 GraphQL Rate Limiter Directive 🔥

The @hubspire/rate-limiter package provides a GraphQL directive @rateLimit for rate limiting GraphQL queries and mutations. This directive helps to prevent abuse and manage resources efficiently by limiting the number of requests a client can make within a specified time window. 🔒

🚨 Why Rate Limiting is Important

Imagine a scenario where a hacker is attempting to gain unauthorized access to a server API handling OTP authentication. Using an automated script, the hacker bombards the server with OTP verification attempts in a brute force attack. Without rate limiting in place, the server processes each request, regardless of volume or frequency. This allows the hacker to continue their trial-and-error process until they successfully guess the correct OTP code, ultimately bypassing authentication and gaining unauthorized access to user accounts. 😱

🛡️ Why Use Rate Limiter:

  • ⛔ Prevents Brute Force Attacks: Rate limiting restricts the number of OTP verification attempts within a specified time frame, thwarting brute force attacks by limiting the speed and frequency of requests.
  • 🔒 Enhances Security: By limiting the number of login attempts, rate limiting strengthens authentication mechanisms, reducing the risk of unauthorized access and data breaches.
  • 🛡️ Protects Resources: Rate limiting ensures fair distribution of server resources, preventing one user (or hacker) from monopolizing resources and disrupting service for others.
  • ⚡ Ensures Stability: By managing traffic flow, rate limiting helps maintain server stability and performance, even under heavy load or during attack scenarios.

In conclusion, implementing rate limiting is crucial for safeguarding your server API against malicious actors, ensuring the security, stability, and integrity of your authentication processes.

🚀 Installation

npm install @hubspire/rate-limiter

🚦 Usage

Identifier as IP address

Update the Middleware Configuration

app.use(
  "/app",
  expressMiddleware(server, {
    context: async (
      payload: ExpressContextFunctionArgument
    ): Promise<AppContext> => {
      return {
        // Include other context keys here
        // Add the ipAddress key to the context object to store the client's IP address
        ipAddress: payload.req.ip as string,
      };
    },
  })
);

In the provided code snippet, the middleware configuration is updated to include the ipAddress field in the context object. This field stores the IP address of the incoming request, which is extracted from the payload.req.ip property.

Update the AppContext Type

type AppContext = {
  // Define other context types here
  ipAddress: string; // Add the ipAddress field with the string type to store the client's IP address
};

In the AppContext type definition, the ipAddress field is added with a type of string. This ensures that the context object passed to each GraphQL resolver includes the IP address of the incoming request.

By updating the middleware configuration and the context type definition, we ensure that the IP address is properly identified and included in the context object, allowing for effective use in rate limiting or any other functionality that requires client identification based on IP address.

Applying rate-limiting directive transformer

import { rateLimitDirectiveTransformer } from "@hubspire/rate-limiter";
export const Modules: TModule = {
  //other configs
  // Setting up GraphQL schemas with middleware transformers
  schemas: rateLimitDirectiveTransformer(
    cacheDirectiveTransformer(
      buildSubgraphSchema({
        typeDefs: typeDefs,
        resolvers: {
          ...resolvers,
          ...{ JSON: GraphQLJSON },
          ...{ DateTime: GraphQLDateTime },
          ...{ EmailAddress: GraphQLEmailAddress },
        },
      })
    )
  ),
};

📝 Directive Definition

input rateLimitInput {
  max: Int!
  window: String!
}

directive @rateLimit(
  limits: [rateLimitInput!]!
  message: String
  identityArgs: [String]
  uncountRejected: Boolean
) on FIELD_DEFINITION

💻 Example Usage

type Query {
  getSignedUrl(fileName: String!, fileType: FileType!): String!
    @rateLimit(
      limits: [
        { max: 5, window: "10s" }
        { max: 15, window: "1m" }
        { max: 50, window: "1d" }
      ]
      uncountRejected: true
    )
}

In this example, the getSignedUrl field is rate-limited to 5 requests per 10 seconds, 15 requests per minute, and 50 requests per day. Requests exceeding these limits will receive a rejection response.

🧭 Directive(opions)

  • limits: An array of rate limit configurations specifying the maximum number of requests allowed within a specific time window.
  • message: Optional custom message to return when a request is rejected due to rate limiting.
  • identityArgs: Optional list of arguments to identify the client. This can be useful for personalized rate limiting.
  • uncountRejected: Optional boolean flag. If true, rejected requests won't be counted towards the rate limit.