NestJS 验证码服务:一个识别 Turnstile 的模块

nestjs captcha - NestJS CAPTCHA Service: A Module That Solves Turnstile

大多数搜索 NestJS captcha 的人,是想给一个 Nest 站点加上验证码。本文讲的是反过来的情形:你的某个服务要通过一个你可以自动化的页面上的 Cloudflare Turnstile 小组件,并且需要拿到 token。你把 capskip 包封装进一个 dynamic module,把它的错误转换成 HTTP 状态码,再用 Vitest 和 supertest 来测试。识别工作由 CapSkip Turnstile 识别工具 在你自己拥有的 Windows PC 上完成,不按次收费。这里不涉及队列;需要放进队列的识别场景见 BullMQ worker 指南.

你需要什么

  • 你自己的一台 Windows PC 上的 CapSkip。它监听哪个地址,由 设置指南中的连接设置部分决定:Local mode 让它只在 127.0.0.1 上监听,Server mode 则向你的网络开放。
  • Node.js 24 系列的 24.15 或更高版本,或者 26。脚手架生成器要求 22.22.3、24.15 或 26,Vite 8 及其打包器要求 20.19 或 22.12,Nest 12 本身要求 20。我从脚手架到测试把整个项目跑在 24.22.0 和 25.2.1 上,npm 在这两个版本上对 @nestjs/schematics 打印了引擎警告。在 20.11.1 上,脚手架命令和 Vitest 都会失败。
  • Nest 12(这里是 12.4.2),搭配 @nestjs/config 12.1.1 和 capskip 1.7.0。脚手架只支持 ESM(导入路径以 .js 结尾),并使用 Vitest 做测试,所以 mock 用 vi.fn。

下面每一次运行用的都是我自己写的 in.php 和 res.php 的 mock,加上真实的 capskip 1.7.0 包。没有任何任务到达真实的 CapSkip,所以我不给出识别耗时,所有延迟和回复都由这个 mock 的规则决定。

第 1 步:创建项目和设置

在 PowerShell 中运行。它会生成应用脚手架,安装这两个包,删除新目录结构所取代的四个示例文件,并为模块创建文件夹。

# Scaffold the app, then npm install capskip @nestjs/config
npx @nestjs/cli new capskip-nest --package-manager npm --skip-git
cd capskip-nest
npm install capskip @nestjs/config
Remove-Item src/app.controller.ts, src/app.controller.spec.ts, src/app.service.ts, test/app.e2e-spec.ts
New-Item -ItemType Directory src/capskip | Out-Null

在项目文件夹中运行下一个代码块。它不用编辑器就能写出 .env 和 .gitignore,所以文件不会被命名成 .env.txt。不带 git 生成的脚手架没有 .gitignore,而 .env 会存放你的密钥,因此在第一次使用 git 之前要把它列进去。SDK 自己不读取任何环境变量,所以第 2 步中的 factory 会读取这些变量。只有在 CapSkip 中开启 API Key Validation 时,CAPSKIP_API_KEY 才有意义;省略时,SDK 会发送密钥 capskip。

# Create .env and .gitignore without an editor
@'
CAPSKIP_HOST=127.0.0.1
CAPSKIP_PORT=8080
CAPSKIP_API_KEY=YOUR_API_KEY
CAPSKIP_TIMEOUT=20
TARGET_HOSTS=example.com
'@ | Set-Content -Path .env -Encoding ascii
Set-Content -Path .gitignore -Value '.env', 'node_modules', 'dist' -Encoding ascii

第 2 步:构建模块

选项说明(只讲一次)

把下一个代码块保存为 src/capskip/capskip.options.ts。Nest 自带 ConfigurableModuleBuilder,它会生成静态的 forRoot 和 forRootAsync 方法,以及选项的注入 token。extras 参数会加上一个 isGlobal 标志,它留在模块上,不属于选项。这个构建器的说明见 Nest 动态模块章节.

// src/capskip/capskip.options.ts
import { ConfigurableModuleBuilder } from '@nestjs/common';

export interface CapSkipModuleOptions {
  host?: string;
  port?: number;
  apiKey?: string;
  /** Seconds the SDK may poll for one solve. */
  timeoutSeconds?: number;
}

export const { ConfigurableModuleClass, MODULE_OPTIONS_TOKEN } =
  new ConfigurableModuleBuilder<CapSkipModuleOptions>()
    .setClassMethodName('forRoot')
    .setExtras({ isGlobal: false }, (definition, extras) => ({
      ...definition,
      global: extras.isGlobal,
    }))
    .build();

服务,客户端放在 token 之后

把它保存为 src/capskip/capskip.service.ts。SDK 客户端不在服务内部创建,而是通过 CAPSKIP_CLIENT token 传入,类型就是服务用到的那一个 SDK 方法,因此测试时只需传入一个函数,编译器仍会检查它的签名。

// src/capskip/capskip.service.ts
import { Inject, Injectable } from '@nestjs/common';
import { TimeoutException, type CapSkip } from 'capskip';
import { MODULE_OPTIONS_TOKEN, type CapSkipModuleOptions } from './capskip.options.js';

export const CAPSKIP_CLIENT = Symbol('CAPSKIP_CLIENT');

/** The one SDK method this service calls, so a test double stays small. */
export type TurnstileClient = Pick<CapSkip, 'turnstile'>;

export interface TurnstileToken {
  token: string;
  /** Submit the token with this User-Agent when CapSkip reports one. */
  userAgent?: string;
}

@Injectable()
export class CapSkipService {
  constructor(
    @Inject(CAPSKIP_CLIENT) private readonly client: TurnstileClient,
    @Inject(MODULE_OPTIONS_TOKEN) private readonly options: CapSkipModuleOptions,
  ) {}

  async solveTurnstile(sitekey: string, url: string): Promise<TurnstileToken> {
    const seconds = this.options.timeoutSeconds ?? 60;
    // The SDK sets no timeout on its HTTP calls and checks its deadline only
    // between polls, so a CapSkip that stops answering would hold this call
    // forever. The race ends it 6 seconds after the SDK deadline at the latest.
    let timer: NodeJS.Timeout | undefined;
    const giveUp = new Promise<never>((_, reject) => {
      timer = setTimeout(
        () => reject(new TimeoutException(`no answer from CapSkip within ${seconds + 6} s`)),
        (seconds + 6) * 1000,
      );
    });
    try {
      const result = await Promise.race([
        this.client.turnstile(sitekey, url, { timeout: seconds }),
        giveUp,
      ]);
      if (typeof result.code !== 'string') {
        throw new Error('Unexpected CapSkip result for turnstile');
      }
      return { token: result.code, userAgent: result.userAgent };
    } finally {
      clearTimeout(timer);
    }
  }
}

以 Turnstile 为例,是因为它的结果带有 User-Agent,SDK 的类型说明提交 token 时应使用它。服务把它和 token 一起作为一个小对象返回,而不是返回原始的 SDK 结果;原始结果的 code 字段类型是字符串或对象,当它不是字符串时,这里会拒绝它。其他类型的形式相同:为 recaptcha、hcaptcha 或 mtcaptcha 各加一个方法,并传入 timeout,原因见第 3 步。各类型接受的字段见 API 文档.

把 SDK 错误转换成 HTTP 状态码

SDK 有四个异常类,都继承自 CapSkipError:ValidationException、NetworkException、ApiException 和 TimeoutException。ApiException 只把 CapSkip 的回复文本作为 message,没有 code 字段,所以映射时要从 message 中读出 ERROR_ 代码。把它保存为 src/capskip/capskip.errors.ts。

// src/capskip/capskip.errors.ts
import { Catch, HttpException, HttpStatus, Logger, type ArgumentsHost } from '@nestjs/common';
import { BaseExceptionFilter } from '@nestjs/core';
import {
  ApiException,
  CapSkipError,
  NetworkException,
  TimeoutException,
  ValidationException,
} from 'capskip';

const BAD_INPUT = /ERROR_(RECAPTCHA_INVALID_(SITEKEY|DOMAIN)|BAD_PARAMETERS|PAGEURL)/;
const BAD_CREDENTIALS = /ERROR_(KEY_DOES_NOT_EXIST|WRONG_USER_KEY|ZERO_BALANCE)/;

export function toHttpException(err: CapSkipError): HttpException {
  const code = /ERROR_[A-Z_]+/.exec(err.message)?.[0];
  const body = (status: HttpStatus, error: string) => ({
    statusCode: status,
    error,
    code: code ?? err.name,
  });

  if (err instanceof TimeoutException) {
    return new HttpException(body(HttpStatus.GATEWAY_TIMEOUT, 'Solver timeout'), 504);
  }
  if (err instanceof NetworkException) {
    return new HttpException(body(HttpStatus.SERVICE_UNAVAILABLE, 'Solver unreachable'), 503);
  }
  if (err instanceof ApiException && BAD_INPUT.test(err.message)) {
    return new HttpException(body(HttpStatus.BAD_REQUEST, 'Solver refused the task'), 400);
  }
  if (err instanceof ApiException && code === 'ERROR_CAPTCHA_UNSOLVABLE') {
    return new HttpException(body(HttpStatus.UNPROCESSABLE_ENTITY, 'Not solved, retry'), 422);
  }
  if (err instanceof ValidationException) {
    // The SDK refused a task this service built: a bug here, not the caller's.
    return new HttpException(body(HttpStatus.INTERNAL_SERVER_ERROR, 'Task refused by the SDK'), 500);
  }
  // Wrong key, empty balance or anything else: our side of the link, not the caller's.
  const error = err instanceof ApiException && BAD_CREDENTIALS.test(err.message)
    ? 'Solver credentials rejected'
    : 'Solver error';
  return new HttpException(body(HttpStatus.BAD_GATEWAY, error), 502);
}

@Catch(CapSkipError)
export class CapSkipExceptionFilter extends BaseExceptionFilter {
  private readonly logger = new Logger(CapSkipExceptionFilter.name);

  override catch(err: CapSkipError, host: ArgumentsHost) {
    // The SDK message is the reply text of CapSkip and never holds the key.
    this.logger.warn(`${err.name} ${err.message}`);
    super.catch(toHttpException(err), host);
  }
}

这个过滤器继承 BaseExceptionFilter 并委托处理,这正是 Nest 异常过滤器章节 所展示的模式,因此它适用于任何 HTTP 适配器。它只捕获 CapSkipError,记录一条包含错误名称和消息的警告(消息是 CapSkip 的回复文本,绝不包含你的密钥),并且不让这条原始消息出现在响应里。

SDK 抛出的异常HTTP为什么是这个状态码
TimeoutException504超时时间内没有拿到 token。CapSkip 在两次轮询之间没有响应,也会在这里结束
NetworkException503提交任务时无法连接到 CapSkip
带 ERROR_CAPTCHA_UNSOLVABLE 的 ApiException422没有识别成功。CapSkip API 文档说要提交一个新任务
ApiException,附带 ERROR_RECAPTCHA_INVALID_SITEKEY、ERROR_RECAPTCHA_INVALID_DOMAIN、ERROR_BAD_PARAMETERS 或 ERROR_PAGEURL400调用方发来的 sitekey 或页面地址被 CapSkip 拒绝
ApiException,附带 ERROR_KEY_DOES_NOT_EXIST、ERROR_WRONG_USER_KEY 或 ERROR_ZERO_BALANCE502问题出在你的服务自己的密钥,而不是调用方的输入
ValidationException500SDK 拒绝了这个服务构造的任务,这在这里属于程序缺陷

其他任何 ApiException 都会变成 502。模块用 APP_FILTER 注册了这个过滤器,所以每个导入该模块的应用都会获得这套映射。

模块、应用和控制器

把模块保存为 src/capskip/capskip.module.ts。它在一个 factory provider 里根据选项构建客户端,加入服务,并注册过滤器。

// src/capskip/capskip.module.ts
import { Module } from '@nestjs/common';
import { APP_FILTER } from '@nestjs/core';
import { CapSkip } from 'capskip';
import { CapSkipExceptionFilter } from './capskip.errors.js';
import {
  ConfigurableModuleClass,
  MODULE_OPTIONS_TOKEN,
  type CapSkipModuleOptions,
} from './capskip.options.js';
import { CAPSKIP_CLIENT, CapSkipService } from './capskip.service.js';

@Module({
  providers: [
    {
      provide: CAPSKIP_CLIENT,
      inject: [MODULE_OPTIONS_TOKEN],
      useFactory: ({ host, port, apiKey }: CapSkipModuleOptions) =>
        new CapSkip({ host, port, apiKey }),
    },
    CapSkipService,
    { provide: APP_FILTER, useClass: CapSkipExceptionFilter },
  ],
  exports: [CapSkipService],
})
export class CapSkipModule extends ConfigurableModuleClass {}

用下一个代码块替换 src/app.module.ts。forRootAsync 会用你在 inject 中列出的内容来运行 factory。这里 ConfigModule 是全局的,所以 CapSkipModule 不用导入就能找到 ConfigService。

// src/app.module.ts
import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { CapSkipModule } from './capskip/capskip.module.js';
import { TurnstileController } from './turnstile.controller.js';

@Module({
  imports: [
    ConfigModule.forRoot({ isGlobal: true }),
    CapSkipModule.forRootAsync({
      inject: [ConfigService],
      useFactory: (config: ConfigService) => ({
        host: config.get<string>('CAPSKIP_HOST', '127.0.0.1'),
        port: Number(config.get('CAPSKIP_PORT', 8080)),
        apiKey: config.get<string>('CAPSKIP_API_KEY'),
        timeoutSeconds: Number(config.get('CAPSKIP_TIMEOUT', 60)),
      }),
    }),
  ],
  controllers: [TurnstileController],
})
export class AppModule {}

最后,保存 src/turnstile.controller.ts。url 决定 CapSkip 为哪个页面识别,所以一个不设防的路由会让任何人都能消耗你的识别能力。对照 TARGET_HOSTS 检查是最低限度的做法:它只接受 https 地址,会修剪列表中的空白,并且在列表为空或未设置时拒绝所有请求。请在它前面再加上你自己的认证 guard。

// src/turnstile.controller.ts
import { BadRequestException, Body, Controller, Post } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { CapSkipService } from './capskip/capskip.service.js';

@Controller('captcha')
export class TurnstileController {
  constructor(
    private readonly capskip: CapSkipService,
    private readonly config: ConfigService,
  ) {}

  @Post('turnstile')
  solve(@Body() body: { sitekey?: unknown; url?: unknown }) {
    const hosts = this.config
      .get<string>('TARGET_HOSTS', '')
      .split(',')
      .map((host) => host.trim())
      .filter(Boolean);
    const page =
      typeof body.url === 'string' && URL.canParse(body.url) ? new URL(body.url) : null;
    if (
      typeof body.sitekey !== 'string' ||
      !body.sitekey ||
      !page ||
      page.protocol !== 'https:' ||
      !hosts.includes(page.host)
    ) {
      throw new BadRequestException('sitekey or url missing, or host not allowed');
    }
    return this.capskip.solveTurnstile(body.sitekey, page.href);
  }
}

第 3 步:请求超时与 SDK 截止时间

我没有在 Nest 里设置任何超时,下面的请求都等满了 7.8 秒,所以这里唯一的截止时间就是 SDK 的。它以秒计,并且有四个会影响等待中请求的行为。

第一,截止时间是在下一次轮询到期时才检查,而不是在时间一到就检查。SDK 大约在 0、0.25、0.75、1.75 和 3.75 秒时轮询,然后在 7.75 秒轮询,之后每 5 秒一次,所以超时设为 5 时大约在 7.8 秒结束。在永远不回复的 mock 上,用 Node.js 24.22.0 测得的结果如下(20.11.1 在全部四行上的差异都在 0.1 秒以内):

超时选项TimeoutException 出现在
5 秒7.82 秒
10 秒12.83 秒
20 秒22.82 秒
30 秒32.86 秒

所以给每个调用方,以及前面的每个代理,都设置为 SDK 的值再加至少 5 秒的超时。经过 Nest 时,CAPSKIP_TIMEOUT 设为 5,在 7.84 秒后返回了 504。

第二,turnstile() 使用客户端的 defaultTimeout(120 秒),而不是 recaptchaTimeout,尽管 SDK 类型定义里的一条注释把 Turnstile 列在 recaptchaTimeout 之下。defaultTimeout 为 3、recaptchaTimeout 为 30 时,它在 3.81 秒后结束;两者对调后,在 32.87 秒后结束。源码里 recaptcha 读取 recaptchaTimeout,mtcaptcha 读取 defaultTimeout,所以服务在每次调用时都传入 timeout 选项。

第三,调用方放弃并不会让识别停下来:SDK 不接受 AbortSignal,Nest 也不会在连接断开时取消处理器。一个在 3.0 秒离开的 supertest 客户端之后,仍然在 3.79 秒出现了第五次轮询。唯一的刹车是较短的超时,所以 CAPSKIP_TIMEOUT 要保持较小。

第四,也是最糟的一点:SDK 不给它的 HTTP 请求设置超时,只在两次轮询之间检查截止时间。如果 CapSkip 接受了一次轮询却再也不回复,比如 PC 睡眠了或防火墙丢弃了数据包,截止时间就永远不会被检查。在一个这样表现的 mock 上,超时为 5 的 SDK 在 30 秒后仍处于挂起状态。所以服务让 SDK 调用和它自己的计时器竞速,计时器比 SDK 截止时间晚 6 秒:CAPSKIP_TIMEOUT 为 5 时,挂起的轮询在 11.0 秒后变成了 504。被放弃的 SDK 调用仍然处于挂起状态,所以要把这个竞速和较短的超时一起保留。

第 4 步:NestJS 验证码服务的测试

使用 mock 客户端的单元测试

把它保存为 src/capskip/capskip.service.spec.ts。Test.createTestingModule 用真实的服务和两个普通值(一个假的客户端和假的选项)构建一个模块。脚手架的 npm test 脚本会运行它。它还覆盖了非字符串结果和挂起的 CapSkip 计时器。

// src/capskip/capskip.service.spec.ts
import { HttpException } from '@nestjs/common';
import { Test } from '@nestjs/testing';
import { ApiException, NetworkException, TimeoutException, ValidationException } from 'capskip';
import { toHttpException } from './capskip.errors.js';
import { MODULE_OPTIONS_TOKEN } from './capskip.options.js';
import { CAPSKIP_CLIENT, CapSkipService } from './capskip.service.js';

describe('CapSkipService', () => {
  const turnstile = vi.fn();
  let service: CapSkipService;

  beforeEach(async () => {
    turnstile.mockReset();
    const moduleRef = await Test.createTestingModule({
      providers: [
        CapSkipService,
        { provide: CAPSKIP_CLIENT, useValue: { turnstile } },
        { provide: MODULE_OPTIONS_TOKEN, useValue: { timeoutSeconds: 20 } },
      ],
    }).compile();
    service = moduleRef.get(CapSkipService);
  });

  it('passes the timeout and returns token and User-Agent', async () => {
    turnstile.mockResolvedValue({ captchaId: '7', code: 'tok', userAgent: 'UA' });
    await expect(service.solveTurnstile('0xKEY', 'https://example.com/')).resolves.toEqual({
      token: 'tok',
      userAgent: 'UA',
    });
    expect(turnstile).toHaveBeenCalledWith('0xKEY', 'https://example.com/', { timeout: 20 });
  });

  afterEach(() => vi.useRealTimers());

  it('refuses a result whose code is not a string', async () => {
    turnstile.mockResolvedValue({ captchaId: '7', code: { token: 'x' } });
    await expect(service.solveTurnstile('0xKEY', 'https://example.com/')).rejects.toThrow(
      'Unexpected CapSkip result',
    );
  });

  it('gives up 6 seconds after the SDK deadline when CapSkip never answers', async () => {
    vi.useFakeTimers();
    turnstile.mockReturnValue(new Promise(() => {}));
    const outcome = expect(service.solveTurnstile('0xKEY', 'https://example.com/')).rejects.toBeInstanceOf(
      TimeoutException,
    );
    await vi.advanceTimersByTimeAsync(26_000);
    await outcome;
  });

  it.each([
    [new TimeoutException('timeout 20 exceeded'), 504],
    [new NetworkException('connect ECONNREFUSED'), 503],
    [new ApiException('ERROR_CAPTCHA_UNSOLVABLE'), 422],
    [new ApiException('ERROR_RECAPTCHA_INVALID_SITEKEY'), 400],
    [new ApiException('ERROR_WRONG_USER_KEY'), 502],
    [new ValidationException('Unsupported parameters'), 500],
  ])('maps %s to HTTP %i', (err, status) => {
    const mapped = toHttpException(err);
    expect(mapped).toBeInstanceOf(HttpException);
    expect(mapped.getStatus()).toBe(status);
  });
});

控制器有它自己的 spec,即 src/turnstile.controller.spec.ts,因为空列表的情形不需要运行中的应用。

// src/turnstile.controller.spec.ts
import { BadRequestException } from '@nestjs/common';
import { TurnstileController } from './turnstile.controller.js';

describe('TurnstileController', () => {
  const solveTurnstile = vi.fn().mockResolvedValue({ token: 'tok' });
  const controller = (hosts?: string) =>
    new TurnstileController(
      { solveTurnstile } as never,
      { get: (_name: string, fallback: string) => hosts ?? fallback } as never,
    );
  const page = { sitekey: '0xKEY', url: 'https://example.com/login' };

  beforeEach(() => solveTurnstile.mockClear());

  it.each([undefined, '', ' , '])('refuses every request when TARGET_HOSTS is %j', (hosts) => {
    expect(() => controller(hosts).solve(page)).toThrow(BadRequestException);
    expect(solveTurnstile).not.toHaveBeenCalled();
  });

  it('accepts a listed host and passes the parsed address on', async () => {
    await controller(' example.com , ').solve(page);
    expect(solveTurnstile).toHaveBeenCalledWith('0xKEY', 'https://example.com/login');
  });
});

针对 mock CapSkip 的 e2e 测试

NestJS 验证码服务应当在没有真实 CapSkip 的情况下测试,所以这个 mock 代替 in.php 和 res.php。它监听端口 0,因此由系统挑选一个空闲端口,并记录它收到的内容。它的回复和延迟是我定的规则,不是真实 CapSkip 的行为。把它保存为 test/mock-capskip.ts。

// test/mock-capskip.ts
import { createServer } from 'node:http';
import type { AddressInfo } from 'node:net';

// A stand-in for CapSkip's in.php and res.php. Not the real app: the
// delay and the replies below are this file's own rules.
export async function startMock(listenPort = 0) {
  const mock = {
    port: 0,
    solveMs: 0, // how long a task stays "not ready"
    submitReply: '', // set to ERROR_... to refuse every submit
    pollReply: '', // set to ERROR_... to fail every poll
    hangPolls: false, // accept a poll and never answer it
    submits: [] as Record<string, string>[],
    polls: [] as number[], // Date.now() of each res.php call
    close: () => {
      server.closeAllConnections();
      return new Promise<void>((done) => server.close(() => done()));
    },
  };
  let submittedAt = 0;

  const server = createServer((req, res) => {
    const url = new URL(req.url!, 'http://mock');
    let raw = '';
    req.on('data', (chunk) => (raw += chunk));
    req.on('end', () => {
      if (url.pathname === '/in.php') {
        mock.submits.push(Object.fromEntries(new URLSearchParams(raw)));
        submittedAt = Date.now();
        res.end(mock.submitReply || 'OK|7');
      } else if (url.pathname === '/res.php') {
        mock.polls.push(Date.now());
        if (mock.hangPolls) return;
        const waiting = Date.now() - submittedAt < mock.solveMs;
        if (mock.pollReply) res.end(JSON.stringify({ status: 0, request: mock.pollReply }));
        else if (waiting) res.end(JSON.stringify({ status: 0, request: 'CAPCHA_NOT_READY' }));
        else res.end(JSON.stringify({ status: 1, request: '0.mock-token', useragent: 'Mock UA' }));
      } else {
        res.statusCode = 404;
        res.end();
      }
    });
  });

  await new Promise<void>((ready) => server.listen(listenPort, '127.0.0.1', ready));
  mock.port = (server.address() as AddressInfo).port;
  return mock;
}

e2e spec 会启动真实的 AppModule,把环境变量指向这个 mock,并用 supertest 发送请求。把它保存为 test/turnstile.e2e-spec.ts,然后运行 npm run test:e2e。环境中已有的变量优先于 .env,所以 spec 可以覆盖它们。

// test/turnstile.e2e-spec.ts
import { Logger, type INestApplication } from '@nestjs/common';
import { Test } from '@nestjs/testing';
import request from 'supertest';
import { AppModule } from '../src/app.module.js';
import { startMock } from './mock-capskip.js';

describe('POST /captcha/turnstile', () => {
  let app: INestApplication;
  let mock: Awaited<ReturnType<typeof startMock>>;
  const body = { sitekey: '0xKEY', url: 'https://example.com/login' };

  beforeAll(async () => {
    mock = await startMock();
    process.env.CAPSKIP_HOST = '127.0.0.1';
    process.env.CAPSKIP_PORT = String(mock.port);
    process.env.CAPSKIP_TIMEOUT = '5';
    process.env.TARGET_HOSTS = ' example.com, '; // spaces and a trailing comma are harmless
    const moduleRef = await Test.createTestingModule({ imports: [AppModule] }).compile();
    app = moduleRef.createNestApplication();
    await app.init();
  });

  afterAll(async () => {
    await app.close();
    await mock.close();
  });

  beforeEach(() => {
    Object.assign(mock, { solveMs: 0, submitReply: '', pollReply: '', hangPolls: false, submits: [], polls: [] });
  });

  it('returns the token and sends a turnstile task', async () => {
    const res = await request(app.getHttpServer()).post('/captcha/turnstile').send(body).expect(201);
    expect(res.body).toEqual({ token: '0.mock-token', userAgent: 'Mock UA' });
    expect(mock.submits[0]).toMatchObject({ method: 'turnstile', sitekey: '0xKEY', pageurl: body.url });
  });

  it('refuses a host that is not on the list, before CapSkip is called', async () => {
    await request(app.getHttpServer())
      .post('/captcha/turnstile')
      .send({ ...body, url: 'https://evil.test/' })
      .expect(400);
    expect(mock.submits).toHaveLength(0);
  });

  it.each([
    { sitekey: '0xKEY', url: 'http://example.com/login' },
    { sitekey: '0xKEY', url: 'file:///C:/Windows/win.ini' },
    { sitekey: '0xKEY', url: 'not a url' },
    { sitekey: { a: 1 }, url: 'https://example.com/login' },
    { url: 'https://example.com/login' },
  ])('refuses %j before CapSkip is called', async (bad) => {
    await request(app.getHttpServer()).post('/captcha/turnstile').send(bad).expect(400);
    expect(mock.submits).toHaveLength(0);
  });

  it('maps an unsolvable task to 422 and logs one warning', async () => {
    const warn = vi.spyOn(Logger.prototype, 'warn');
    mock.pollReply = 'ERROR_CAPTCHA_UNSOLVABLE';
    const res = await request(app.getHttpServer()).post('/captcha/turnstile').send(body).expect(422);
    expect(res.body).toMatchObject({ code: 'ERROR_CAPTCHA_UNSOLVABLE' });
    expect(warn).toHaveBeenCalledWith(expect.stringContaining('ERROR_CAPTCHA_UNSOLVABLE'));
    warn.mockRestore();
  });

  it('maps a refused key to 502', async () => {
    mock.submitReply = 'ERROR_WRONG_USER_KEY';
    await request(app.getHttpServer()).post('/captcha/turnstile').send(body).expect(502);
  });

  it('answers 504 after the timeout of 5 seconds, not before it', async () => {
    mock.solveMs = 60_000;
    const started = Date.now();
    await request(app.getHttpServer()).post('/captcha/turnstile').send(body).expect(504);
    const seconds = (Date.now() - started) / 1000;
    expect(seconds).toBeGreaterThan(5);
    expect(seconds).toBeLessThan(9);
  }, 15_000);

  it('answers 504 when CapSkip accepts a poll and never replies', async () => {
    mock.hangPolls = true;
    const started = Date.now();
    await request(app.getHttpServer()).post('/captcha/turnstile').send(body).expect(504);
    const seconds = (Date.now() - started) / 1000;
    expect(seconds).toBeGreaterThan(10.5);
    expect(seconds).toBeLessThan(13);
  }, 20_000);
});

以下是使用这个 mock 和 capskip 1.7.0,在 Windows 11 上的结果:

运行时单元测试E2E 测试
Node.js 24.22.02 个文件中 13 个通过11 个通过,约 19 秒
Node.js 25.2.12 个文件中 13 个通过11 个通过,约 19 秒
Node.js 20.11.1脚手架命令和 Vitest 失败脚手架命令和 Vitest 失败

在 20.11.1 上,脚手架命令和 Vitest 会因错误而停止,错误内容是 node:util 没有名为 styleText 的导出,而该版本并不提供它。

在另一台机器上运行:Server mode

Nest 服务很少会运行在运行 CapSkip 的那台 PC 上。把那台 PC 的地址填进 CAPSKIP_HOST,其他都不用改。此时 CapSkip 必须处于 Server mode,说明见 连接设置 一节(在设置指南中),其中提到 Server mode 需要 CapSkip 以管理员身份运行。SDK 使用明文 http,并在每次 res.php 调用的查询字符串中发送密钥,所以要把这条链路放在专用网络内。

Server mode 启动时,CapSkip 会向所有地址开放它的端口,所以要把访问限制在你预期的机器上,就为其他机器添加一条 Windows 防火墙阻止规则,并开启 API Key Validation,让 CAPSKIP_API_KEY 真正起作用。CapSkip 没有运行时,提交会以 NetworkException 失败(在我的运行中是 127.0.0.1 上的连接被拒绝),过滤器返回 503。一个不可路由的地址(192.0.2.1)让 SDK 在 21.1 秒后放弃,所以在超时为 20 时,服务大约在 21 秒后返回 503;超时为 5 时,竞速在 11.0 秒后返回了 504。这些运行使用的是 mock 和 Node.js 24.22.0。

常见错误

你所看到的原因修复
Nest can’t resolve dependencies of the CapSkipService, argument Symbol(CAPSKIP_CLIENT) at index [0]测试模块列出了服务,却没有列出客户端 token为 CAPSKIP_CLIENT 添加一个使用假对象的 provider
Nest can’t resolve dependencies of the CONFIGURABLE_MODULE_OPTIONS provider, argument ConfigServiceforRootAsync 注入了 ConfigService,但 ConfigModule 既不是全局的,也没有被导入传入包含 ConfigModule 的 imports,或在 ConfigModule.forRoot 中设置 isGlobal
TypeError: Cannot read properties of undefined (reading "get")factory 有 config 参数,但 forRootAsync 没有 inject 列表用 ConfigService 添加 inject
Nest can’t resolve dependencies of the Symbol(CAPSKIP_CLIENT) provider, argument CONFIGURABLE_MODULE_OPTIONSCapSkipModule 被直接导入,没有调用 forRoot 或 forRootAsync导入这两个调用之一的返回结果
HTTP 502,code 为 ERROR_WRONG_USER_KEY 或 ERROR_KEY_DOES_NOT_EXISTCapSkip 中开启了 API Key Validation。第一个代码表示密钥缺失或为空,第二个表示密钥无效把 CAPSKIP_API_KEY 设为有效的密钥,然后重启服务
在你放弃很久之后才返回 HTTP 504SDK 一直轮询到它自己的截止时间,或者竞速放弃了一个没有响应的 CapSkip降低 CAPSKIP_TIMEOUT,并阅读第 3 步

这四条 Nest 消息是 Nest 12.4.2 的真实措辞,由我的测试模块打印,并做了缩短。CapSkip 的错误码列在 API 文档.

常见问题

NestJS 验证码服务可以运行在与 CapSkip 不同的机器上吗?

可以。把 CAPSKIP_HOST 设为 CapSkip 所在 PC 的地址,并把 CapSkip 切换到 Server mode。Server mode 会让 CapSkip 在所有地址上接受连接,所以要为你不预期的机器添加一条 Windows 防火墙阻止规则,并开启 API Key Validation。不需要修改代码。

什么时候该用队列而不是控制器?

当调用方等不了一次识别,或者同时来了很多请求时。控制器会在整个识别期间一直保持请求打开,一次一两个还可以。队列处理器可以导入同一个 CapSkipModule,BullMQ worker 指南讲的就是那一侧。

为什么服务在 token 旁边还返回 User-Agent?

SDK 的类型说明,对于 Turnstile,提交 token 时应使用结果中的 User-Agent,并且只有在 CapSkip 报告了它时才会有。服务把它传出去,调用方就可以发送它。

一个必须通过 Turnstile 的 NestJS 验证码服务,需要把三样东西放在正确的位置:把客户端放在 token 之后以便能被替换成假对象,用一个地方把 SDK 错误转换成状态码,以及给每次调用设置超时,并为无响应的情形加上竞速。CapSkip 是一款 无限量验证码识别工具 ,运行在你自己拥有的硬件上,所以重试或测试运行失败都不会出现在账单上。在 Node.js 中识别其他类型的验证码,见 Node.js 验证码识别页面.