# 限流

来源：https://docs.nestjs.com/security/rate-limiting

保护应用免受暴力破解攻击的一种常见技术是**限流**（rate limiting）。要开始使用，请安装 `@nestjs/throttler` 包。

```bash
$ npm i --save @nestjs/throttler
```

安装完成后，像其他 Nest 包一样用 `forRoot()` 或 `forRootAsync()` 方法配置 `ThrottlerModule`。

```typescript
@@filename(app.module)
@Module({
  imports: [
    ThrottlerModule.forRoot({
      throttlers: [
        {
          ttl: 60000,
          limit: 10,
        },
      ],
    }),
  ],
})
export class AppModule {}
```

这为应用中受守卫的路由设置全局选项：`ttl` 是生存时间（毫秒），`limit` 是在 `ttl` 内的最大请求数。

模块导入之后，选择如何绑定 `ThrottlerGuard`。[守卫](/guards#binding-guards)一章中描述的任何绑定方式都可用。例如，要全局绑定该守卫，请把下面这个提供者加入任意模块：

```typescript
{
  provide: APP_GUARD,
  useClass: ThrottlerGuard
}
```

#### 多个限流定义

有时你想要多套限流定义，例如每秒不超过 3 次、每 10 秒不超过 20 次、每分钟不超过 100 次。为此，在数组中用带名字的选项定义它们。之后可以在 `@SkipThrottle()` 和 `@Throttle()` 装饰器中引用这些名字，按路由或控制器改变选项。

```typescript
@@filename(app.module)
@Module({
  imports: [
    ThrottlerModule.forRoot([
      {
        name: 'short',
        ttl: 1000,
        limit: 3,
      },
      {
        name: 'medium',
        ttl: 10000,
        limit: 20
      },
      {
        name: 'long',
        ttl: 60000,
        limit: 100
      }
    ]),
  ],
})
export class AppModule {}
```

#### 自定义

你可能想把守卫绑定到某个控制器或全局，但对一个或多个端点禁用限流。为此，用 `@SkipThrottle()` 装饰器为整个类或单个路由禁用限流器。`@SkipThrottle()` 装饰器也接受一个对象，键为字符串（限流器名字），值为布尔值。当你想排除控制器中的_大部分_路由而不是全部路由，或者在有多套限流器时按套配置跳过，这会很有用。如果不传对象，默认为 `{ default: true }`。

```typescript
@SkipThrottle()
@Controller('users')
export class UsersController {}
```

`@SkipThrottle()` 装饰器可以跳过某个路由或某个类，也可以在被跳过的类中反转某个路由的跳过状态。

```typescript
@SkipThrottle()
@Controller('users')
export class UsersController {
  // Rate limiting is applied to this route.
  @SkipThrottle({ default: false })
  dontSkip() {
    return 'List users work with Rate limiting.';
  }
  // This route will skip rate limiting.
  doSkip() {
    return 'List users work without Rate limiting.';
  }
}
```

`@Throttle()` 装饰器覆盖根模块中设置的 `limit` 和 `ttl`，以提供更严格或更宽松的安全选项。你可以把它应用于类或方法。自 v5 起，该装饰器接受一个对象，键为限流器套的名字，值为含 `limit` 和 `ttl` 键（以及可选的 `blockDuration`）的对象，与传给根模块的选项类似。如果你没有在根选项中设置名字，请使用 `default` 键：

```typescript
// Override default configuration for Rate limiting and duration.
@Throttle({ default: { limit: 3, ttl: 60000 } })
@Get()
findAll() {
  return "List users works with custom rate limiting.";
}
```

#### 代理

如果你的应用运行在代理服务器之后，请配置 HTTP 适配器信任该代理。参见 [Express](http://expressjs.com/en/guide/behind-proxies.html)、[Fastify](https://www.fastify.io/docs/latest/Reference/Server/#trustproxy) 和 [Node 适配器](/http/performance#node-adapter-options)的 `trust proxy` 选项。

下面的示例为 Express 适配器启用 `trust proxy`：

```typescript
@@filename(main)
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module.js';
import { NestExpressApplication } from '@nestjs/platform-express';

async function bootstrap() {
  const app = await NestFactory.create<NestExpressApplication>(AppModule);
  app.set('trust proxy', 'loopback'); // Trust requests from the loopback address
  await app.listen(3000);
}

await bootstrap();
```

对 Fastify 适配器，改为传入 `trustProxy` 选项：

```typescript
@@filename(main)
const app = await NestFactory.create<NestFastifyApplication>(
  AppModule,
  new FastifyAdapter({ trustProxy: 'loopback' }), // Trust requests from the loopback address
);
```

> warning **警告** 在 Fastify v5.12.1 及更高版本（`@nestjs/platform-fastify` v12 安装的版本）中，把数字（如表示跳数的 `1`）作为 `trustProxy` 传入会让 Fastify 完全不信任任何代理。此时 `request.ip` 是代理的地址，限流器会把代理后面的所有客户端算作一个。请像上面的示例那样，改传代理的地址或地址范围。

对 Node 适配器，传入它的 `trustProxy` 选项，取值与 Fastify 相同（在这里数字同样表示不信任任何代理）：

```typescript
@@filename(main)
const app = await NestFactory.create<NestNodeApplication>(
  AppModule,
  new NodeAdapter({ trustProxy: 'loopback' }), // Trust requests from the loopback address
);
```

启用 `trust proxy` 后，你就可以从 `X-Forwarded-For` 头中取出原始 IP 地址。你也可以重写 `getTracker()` 方法，改为从该头提取 IP，而不依赖 `req.ip`。下面的示例适用于 Express 和 Node 适配器，它们对 `req.ips` 的排序方式相同：

```typescript
@@filename(throttler-behind-proxy.guard)
import { ThrottlerGuard } from '@nestjs/throttler';
import { Injectable } from '@nestjs/common';

@Injectable()
export class ThrottlerBehindProxyGuard extends ThrottlerGuard {
  protected async getTracker(req: Record<string, any>): Promise<string> {
    return req.ips.length ? req.ips[0] : req.ip; // individualize IP extraction to meet your own needs
  }
}
```

> info **提示** 在 Fastify 上，`request.ips` 按从最近到最远的顺序排列，因此它的第一项是代理的地址，这个守卫会把代理后面的所有客户端算作一个。那里请保留默认的跟踪器，它使用 `request.ip`。参见 [Express](https://expressjs.com/en/api.html#req.ips) 和 [Fastify](https://www.fastify.io/docs/latest/Reference/Request/) 的请求对象 API。

#### WebSocket

本模块可用于 WebSocket，但需要继承 `ThrottlerGuard` 类并重写其 `handleRequest()` 方法，如下所示：

```typescript
@Injectable()
export class WsThrottlerGuard extends ThrottlerGuard {
  async handleRequest(requestProps: ThrottlerRequest): Promise<boolean> {
    const { context, limit, ttl, throttler, blockDuration, generateKey } =
      requestProps;

    const client = context.switchToWs().getClient();
    const tracker = client._socket.remoteAddress;
    const key = generateKey(context, tracker, throttler.name);
    const { totalHits, timeToExpire, isBlocked, timeToBlockExpire } =
      await this.storageService.increment(
        key,
        ttl,
        limit,
        blockDuration,
        throttler.name,
      );

    // Throw an error when the user reached their limit.
    if (isBlocked) {
      await this.throwThrottlingException(context, {
        limit,
        ttl,
        key,
        tracker,
        totalHits,
        timeToExpire,
        isBlocked,
        timeToBlockExpire,
      });
    }

    return true;
  }
}
```

> info **提示** 上面的示例从 `client._socket` 读取客户端地址，这适用于 `@nestjs/platform-ws` 包。如果你使用 `@nestjs/platform-socket.io`，请把 `client._socket` 换成 `client.conn`。

使用 WebSocket 时请注意以下几点：

- 不要用 `APP_GUARD` 或 `app.useGlobalGuards()` 注册这个守卫。全局守卫也会对 HTTP 路由运行，而这个守卫只处理 WebSocket 上下文。
- 达到限制时，Nest 会发出 `exception` 事件，因此请确保有监听器准备好接收它。

> info **提示** 当你配置了[多个限流定义](/security/rate-limiting#multiple-throttler-definitions)时，`handleRequest()` 会为每套限流器各运行一次。生成存储键以及调用 `storageService.increment()` 时，请像上面那样传入 `ThrottlerRequest` 中的 `throttler.name`，以便每个具名限流器跟踪各自的限制。

#### GraphQL

`ThrottlerGuard` 也能用于 GraphQL 请求。同样需要继承该守卫，但这次重写 `getRequestResponse()` 方法：

```typescript
@Injectable()
export class GqlThrottlerGuard extends ThrottlerGuard {
  getRequestResponse(context: ExecutionContext) {
    const gqlCtx = GqlExecutionContext.create(context);
    const ctx = gqlCtx.getContext();
    return { req: ctx.req, res: ctx.res };
  }
}
```

#### 配置

下面这些选项对传给 `ThrottlerModule` 的数组中每个对象都有效：

<table>
  <tr>
    <td><code>name</code></td>
    <td>内部用于跟踪当前使用哪套限流器的名字。未传时默认为 <code>default</code>。对具名限流器，该名字还会附加到限流响应头上（例如 <code>X-RateLimit-Remaining-long</code>）</td>
  </tr>
  <tr>
    <td><code>ttl</code></td>
    <td>每个请求在存储中保留的毫秒数</td>
  </tr>
  <tr>
    <td><code>limit</code></td>
    <td>TTL 内的最大请求数</td>
  </tr>
  <tr>
    <td><code>blockDuration</code></td>
    <td>达到限制后请求被封锁的毫秒数。默认为 <code>ttl</code> 的值</td>
  </tr>
  <tr>
    <td><code>ignoreUserAgents</code></td>
    <td>一组正则表达式，匹配在限流时要忽略的用户代理</td>
  </tr>
  <tr>
    <td><code>skipIf</code></td>
    <td>一个接收 <code>ExecutionContext</code> 并返回 <code>boolean</code> 的函数，用于短路限流逻辑。类似 <code>@SkipThrottle()</code>，但基于请求判断</td>
  </tr>
  <tr>
    <td><code>getTracker</code></td>
    <td>一个覆盖该限流器套默认跟踪逻辑的函数（见下表）</td>
  </tr>
  <tr>
    <td><code>generateKey</code></td>
    <td>一个覆盖该限流器套默认键生成逻辑的函数（见下表）</td>
  </tr>
  <tr>
    <td><code>setHeaders</code></td>
    <td>是否把限流响应头加入响应。默认为 <code>true</code></td>
  </tr>
</table>

要配置自定义存储，或把上述某些选项全局应用到每套限流器，请传选项对象而不是数组。在它的 `throttlers` 属性中定义各套限流器，并使用下表中的选项：

<table>
  <tr>
    <td><code>storage</code></td>
    <td>用于跟踪限流的自定义存储服务。见<a href="/security/rate-limiting#storages">存储</a></td>
  </tr>
  <tr>
    <td><code>ignoreUserAgents</code></td>
    <td>一组正则表达式，匹配在限流时要忽略的用户代理</td>
  </tr>
  <tr>
    <td><code>skipIf</code></td>
    <td>一个接收 <code>ExecutionContext</code> 并返回 <code>boolean</code> 的函数，用于短路限流逻辑。类似 <code>@SkipThrottle()</code>，但基于请求判断</td>
  </tr>
  <tr>
    <td><code>throttlers</code></td>
    <td>一组限流器套，用上面的表格定义</td>
  </tr>
  <tr>
    <td><code>errorMessage</code></td>
    <td>一个 <code>string</code>，或一个接收 <code>ExecutionContext</code> 与 <code>ThrottlerLimitDetail</code> 并返回 <code>string</code> 的函数，用于覆盖默认的限流错误消息</td>
  </tr>
  <tr>
    <td><code>getTracker</code></td>
    <td>一个接收请求与 <code>ExecutionContext</code> 并返回 <code>string</code>（或其 <code>Promise</code>）的函数，覆盖 <code>getTracker()</code> 方法的默认逻辑</td>
  </tr>
  <tr>
    <td><code>generateKey</code></td>
    <td>一个接收 <code>ExecutionContext</code>、跟踪器 <code>string</code> 和限流器名字 <code>string</code>，并返回用作限流值存储键的 <code>string</code> 的函数。它覆盖 <code>generateKey()</code> 方法的默认逻辑</td>
  </tr>
  <tr>
    <td><code>setHeaders</code></td>
    <td>是否把限流响应头加入响应。默认为 <code>true</code></td>
  </tr>
  <tr>
    <td><code>ipv6SubnetPrefix</code></td>
    <td>把 IPv6 地址归并到单个跟踪器所用的前缀长度，从而让客户端无法通过轮换其子网内的地址来规避限制。仅对内置跟踪器生效（不影响自定义 <code>getTracker</code>）。默认为 <code>64</code></td>
  </tr>
</table>

#### 异步配置

你可能想异步加载限流配置。请使用 `forRootAsync()` 方法，它支持依赖注入和 `async` 方法。

一种方式是使用工厂函数：

```typescript
@Module({
  imports: [
    ThrottlerModule.forRootAsync({
      imports: [ConfigModule],
      inject: [ConfigService],
      useFactory: (config: ConfigService) => [
        {
          ttl: config.get('THROTTLE_TTL'),
          limit: config.get('THROTTLE_LIMIT'),
        },
      ],
    }),
  ],
})
export class AppModule {}
```

你也可以使用 `useClass` 写法：

```typescript
@Module({
  imports: [
    ThrottlerModule.forRootAsync({
      imports: [ConfigModule],
      useClass: ThrottlerConfigService,
    }),
  ],
})
export class AppModule {}
```

只要 `ThrottlerConfigService` 实现了 `ThrottlerOptionsFactory` 接口，这种写法就能工作。

#### 存储

内置存储是一个内存缓存，它跟踪请求直到其 TTL 过去。你可以把自己的存储传给 `ThrottlerModule` 的 `storage` 选项，只要该类实现了 `ThrottlerStorage` 接口。

对于分布式服务器，你可以使用社区提供的 [Redis](https://github.com/jmcdo29/nest-lab/tree/main/packages/throttler-storage-redis) 存储，以获得单一可信数据源。

> info **注意** `ThrottlerStorage` 可从 `@nestjs/throttler` 导入。

#### 时间辅助函数

`@nestjs/throttler` 导出五个辅助函数，让时间值比裸毫秒数更易读：`seconds`、`minutes`、`hours`、`days` 和 `weeks`。每个都返回等价的毫秒数。例如 `seconds(5)` 返回 `5000`。

#### 迁移指南

升级到 v5 或更高版本时，对大多数应用来说，把选项包进数组即可。

如果你使用自定义存储，请把 `ttl` 和 `limit` 包进数组，并赋给选项对象的 `throttlers` 属性。

`@SkipThrottle()` 装饰器现在接受一个可选对象，键为字符串（限流器名字），值为布尔值，默认为 `{ default: true }`。

`@Throttle()` 装饰器现在接受一个对象，键为字符串（限流器套的名字，若未设名字同样用 `'default'`），值为含 `limit` 和 `ttl` 键的对象。

> warning **警告** `ttl` 现在以**毫秒**为单位。若为了可读性想继续以秒为单位表示 `ttl`，请使用本包的 `seconds` 辅助函数，它会把值乘以 1000。

更多信息见 [5.0 变更日志](https://github.com/nestjs/throttler/blob/master/CHANGELOG.md#501)。
