rrd108 / nuxt-api-shield

Nuxt API Rate Limiter / Brute Force Protection
5 stars 2 forks source link
nuxt nuxt-module rate-limiter security

Nuxt API Shield

npm version npm downloads License Nuxt

This Nuxt module implements a rate limiting middleware to protect your API endpoints from excessive requests.

Features

Quick Setup

1. Add nuxt-api-shield dependency to your project

# Using pnpm
pnpm add nuxt-api-shield

# Using yarn
yarn add nuxt-api-shield

# Using npm
npm install nuxt-api-shield

2. Add nuxt-api-shield to the modules section of nuxt.config.ts

You should add only the values you want to use differently from the default values.

export default defineNuxtConfig({
  modules: ["nuxt-api-shield"],
  nuxtApiShield: {
    /*limit: {
      max: 12,        // maximum requests per duration time, default is 12/duration
      duration: 108,   // duration time in seconds, default is 108 seconds
      ban: 3600,      // ban time in seconds, default is 3600 seconds = 1 hour
    },
    delayOnBan: true  // delay every response with +1sec when the user is banned, default is true
    errorMessage: "Too Many Requests",  // error message when the user is banned, default is "Too Many Requests"
    retryAfterHeader: false, // when the user is banned add the Retry-After header to the response, default is false
    log: false, // request logging into a file, it accepts a boolean `false`, or an object, default is false - no logging
    log: {
      path: "logs", // path to the log file, every day a new log file will be created
      attempts: 100,    // if an IP reach 100 requests, all the requests will be logged, can be used for further analysis or blocking for example with fail2ban
    }
    */
  },
});

3. Add nitro/storage to nuxt.config.ts

You can use any storage you want, but you have to use shield as the name of the storage.

{
  "nitro": {
    "storage": {
      "shield": {
        // storage name, you **must** use "shield" as the name
        "driver": "memory"
      }
    }
  }
}

4. Add shield:clean to nuxt.config.ts

{
  "nitro": {
    "experimental": {
      "tasks": true
    },
    "scheduledTasks": {
      "*/15 * * * *": ["shield:clean"] // clean the shield storage every 15 minutes
    }
  }
}

5. Create your clean task

In server/tasks/shield/clean.ts you should have something like this.

import type { RateLimit } from "#imports";

export default defineTask({
  meta: {
    description: "Clean expired bans",
  },
  async run() {
    const shieldStorage = useStorage("shield");

    const keys = await shieldStorage.getKeys();
    keys.forEach(async (key) => {
      const rateLimit = (await shieldStorage.getItem(key)) as RateLimit;
      if (isBanExpired(rateLimit)) {
        await shieldStorage.removeItem(key);
      }
    });
    return { result: keys };
  },
});

Development

# Install dependencies
yarn

# Generate type stubs
yarn dev:prepare

# Develop with the playground
yarn dev

# Build the playground
yarn dev:build

# Run ESLint
yarn lint

# Run Vitest
yarn test
yarn test:watch

# Release new version
yarn release:patch
yarn release:minor