npm package: @hubspire/rate-limiter
Description: 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
Author: sijeeshmiziha
Latest version: 1.0.8

# 🚀 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

```bash
npm install @hubspire/rate-limiter
```

## 🚦 Usage

### For skipping ratelimiter pass this environment variable

```ts
process.env.SKIP_HUBSPIRE_RATELIMITER = true;
```

### Identifier as IP address

Update the Middleware Configuration

```ts
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: String(
          payload.req?.headers["x-forwarded-for"] || payload.req.ip
        ),
      };
    },
  })
);
```

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

```ts
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

```ts
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

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

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

### 💻 Example Usage

```graphql
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.

---

## ✨ **Meet the Author** ✨ 🎯

<div align="center">
  <img src="https://github.com/sijeeshmiziha.png" width="150px" style="border-radius: 50%;" alt="Sijeesh Miziha"/>
  
  [![GitHub](https://img.shields.io/badge/GitHub-sijeeshmiziha-181717?style=for-the-badge&logo=github)](https://github.com/sijeeshmiziha)
  [![LinkedIn](https://img.shields.io/badge/LinkedIn-Connect-0077B5?style=for-the-badge&logo=linkedin)](https://linkedin.com/in/sijeeshmiziha)
  [![Instagram](https://img.shields.io/badge/Instagram-Follow-E4405F?style=for-the-badge&logo=instagram)](https://instagram.com/sijeeshmiziha)
  
  _"Building scalable solutions with passion and precision"_
  
  
  _Built with ❤️ for the GraphQL community_
</div>

---