{"id":28054,"date":"2026-11-20T18:32:20","date_gmt":"2026-11-20T18:32:20","guid":{"rendered":"https:\/\/capskip.com\/?p=28054"},"modified":"2026-11-20T18:32:20","modified_gmt":"2026-11-20T18:32:20","slug":"nestjs-captcha-service","status":"publish","type":"post","link":"https:\/\/capskip.com\/zh\/nestjs-captcha-service\/","title":{"rendered":"NestJS \u9a8c\u8bc1\u7801\u670d\u52a1\uff1a\u4e00\u4e2a\u8bc6\u522b Turnstile \u7684\u6a21\u5757"},"content":{"rendered":"<p>Most searches for a NestJS captcha want to protect a Nest site with one. This guide is for the other direction: a service of yours has to get past a Cloudflare Turnstile widget on a page you may automate, and it needs a token. You wrap the capskip package in a dynamic module, turn its errors into HTTP statuses and test it with Vitest and supertest. The solving is done by the <a href=\"https:\/\/capskip.com\/cloudflare-turnstile-solver\/\">CapSkip Turnstile solver<\/a> on a Windows PC you own, with no per-solve fee. No queue is involved; solves that belong in one are covered by the <a href=\"https:\/\/capskip.com\/bullmq-captcha-worker\/\">BullMQ worker guide<\/a>.<\/p>\n<h2 style=\"font-size:1.6rem;line-height:1.35;\">What you need<\/h2>\n<ul>\n<li>CapSkip on a Windows PC of yours. Where it listens is chosen in the connection settings section of the <a href=\"https:\/\/capskip.com\/setup-guide\/#connection-settings\">setup guide<\/a>: Local mode keeps it on 127.0.0.1, and Server mode opens it to your network.<\/li>\n<li>Node.js 24.15 or later on the 24 line, or 26. The scaffold generator asks for 22.22.3, 24.15 or 26, Vite 8 and its bundler for 20.19 or 22.12, and Nest 12 itself for 20. I ran the project, from the scaffold to the tests, on 24.22.0 and 25.2.1, where npm printed an engine warning for @nestjs\/schematics. On 20.11.1 the scaffold command and Vitest fail.<\/li>\n<li>Nest 12 (12.4.2 here) with @nestjs\/config 12.1.1 and capskip 1.7.0. The scaffold is ESM only (import paths end in .js) and tests with Vitest, so mocks are vi.fn.<\/li>\n<\/ul>\n<p>Every run below used a mock of in.php and res.php that I wrote, plus the real capskip 1.7.0 package. No task reached a real CapSkip, so I quote no solve time, and every delay and reply is the mock&#8217;s rule.<\/p>\n<h2 style=\"font-size:1.6rem;line-height:1.35;\">Step 1: create the project and the settings<\/h2>\n<p>Run this in PowerShell. It scaffolds the app, installs the two packages, deletes the four sample files that the new layout replaces and creates the folder for the module.<\/p>\n<div data-no-translation>\n<pre data-enlighter-language=\"bash\" class=\"EnlighterJSRAW\"># Scaffold the app, then npm install capskip @nestjs\/config\r\nnpx @nestjs\/cli new capskip-nest --package-manager npm --skip-git\r\ncd capskip-nest\r\nnpm install capskip @nestjs\/config\r\nRemove-Item src\/app.controller.ts, src\/app.controller.spec.ts, src\/app.service.ts, test\/app.e2e-spec.ts\r\nNew-Item -ItemType Directory src\/capskip | Out-Null<\/pre>\n<\/div>\n<p>Run the next block in the project folder. It writes .env and .gitignore without an editor, so the file cannot end up named .env.txt. A scaffold made without git has no .gitignore, and .env will hold your key, so list it there before you first use git. The SDK reads no environment variables itself, so the factory in Step 2 reads these. CAPSKIP_API_KEY matters only when API Key Validation is on in CapSkip; left out, the SDK sends the key capskip.<\/p>\n<div data-no-translation>\n<pre data-enlighter-language=\"bash\" class=\"EnlighterJSRAW\"># Create .env and .gitignore without an editor\r\n@'\r\nCAPSKIP_HOST=127.0.0.1\r\nCAPSKIP_PORT=8080\r\nCAPSKIP_API_KEY=YOUR_API_KEY\r\nCAPSKIP_TIMEOUT=20\r\nTARGET_HOSTS=example.com\r\n'@ | Set-Content -Path .env -Encoding ascii\r\nSet-Content -Path .gitignore -Value '.env', 'node_modules', 'dist' -Encoding ascii<\/pre>\n<\/div>\n<h2 style=\"font-size:1.6rem;line-height:1.35;\">Step 2: build the module<\/h2>\n<h3 style=\"font-size:1.3rem;line-height:1.4;\">The options, described once<\/h3>\n<p>Save the next block as src\/capskip\/capskip.options.ts. Nest ships a ConfigurableModuleBuilder that generates the static forRoot and forRootAsync methods and an injection token for the options. The extras argument adds an isGlobal flag that stays on the module, out of the options. The builder is described in the <a href=\"https:\/\/docs.nestjs.com\/fundamentals\/dynamic-modules\" rel=\"noopener nofollow\" target=\"_blank\">Nest dynamic modules chapter<\/a>.<\/p>\n<div data-no-translation>\n<pre data-enlighter-language=\"typescript\" class=\"EnlighterJSRAW\">\/\/ src\/capskip\/capskip.options.ts\r\nimport { ConfigurableModuleBuilder } from '@nestjs\/common';\r\n\r\nexport interface CapSkipModuleOptions {\r\n  host?: string;\r\n  port?: number;\r\n  apiKey?: string;\r\n  \/** Seconds the SDK may poll for one solve. *\/\r\n  timeoutSeconds?: number;\r\n}\r\n\r\nexport const { ConfigurableModuleClass, MODULE_OPTIONS_TOKEN } =\r\n  new ConfigurableModuleBuilder&lt;CapSkipModuleOptions&gt;()\r\n    .setClassMethodName('forRoot')\r\n    .setExtras({ isGlobal: false }, (definition, extras) =&gt; ({\r\n      ...definition,\r\n      global: extras.isGlobal,\r\n    }))\r\n    .build();<\/pre>\n<\/div>\n<h3 style=\"font-size:1.3rem;line-height:1.4;\">The service, with the client behind a token<\/h3>\n<p>Save this as src\/capskip\/capskip.service.ts. The SDK client is not created inside the service. It arrives through the CAPSKIP_CLIENT token, typed as the one SDK method the service uses, so a test can pass one function and the compiler still checks its signature.<\/p>\n<div data-no-translation>\n<pre data-enlighter-language=\"typescript\" class=\"EnlighterJSRAW\">\/\/ src\/capskip\/capskip.service.ts\r\nimport { Inject, Injectable } from '@nestjs\/common';\r\nimport { TimeoutException, type CapSkip } from 'capskip';\r\nimport { MODULE_OPTIONS_TOKEN, type CapSkipModuleOptions } from '.\/capskip.options.js';\r\n\r\nexport const CAPSKIP_CLIENT = Symbol('CAPSKIP_CLIENT');\r\n\r\n\/** The one SDK method this service calls, so a test double stays small. *\/\r\nexport type TurnstileClient = Pick&lt;CapSkip, 'turnstile'&gt;;\r\n\r\nexport interface TurnstileToken {\r\n  token: string;\r\n  \/** Submit the token with this User-Agent when CapSkip reports one. *\/\r\n  userAgent?: string;\r\n}\r\n\r\n@Injectable()\r\nexport class CapSkipService {\r\n  constructor(\r\n    @Inject(CAPSKIP_CLIENT) private readonly client: TurnstileClient,\r\n    @Inject(MODULE_OPTIONS_TOKEN) private readonly options: CapSkipModuleOptions,\r\n  ) {}\r\n\r\n  async solveTurnstile(sitekey: string, url: string): Promise&lt;TurnstileToken&gt; {\r\n    const seconds = this.options.timeoutSeconds ?? 60;\r\n    \/\/ The SDK sets no timeout on its HTTP calls and checks its deadline only\r\n    \/\/ between polls, so a CapSkip that stops answering would hold this call\r\n    \/\/ forever. The race ends it 6 seconds after the SDK deadline at the latest.\r\n    let timer: NodeJS.Timeout | undefined;\r\n    const giveUp = new Promise&lt;never&gt;((_, reject) =&gt; {\r\n      timer = setTimeout(\r\n        () =&gt; reject(new TimeoutException(`no answer from CapSkip within ${seconds + 6} s`)),\r\n        (seconds + 6) * 1000,\r\n      );\r\n    });\r\n    try {\r\n      const result = await Promise.race([\r\n        this.client.turnstile(sitekey, url, { timeout: seconds }),\r\n        giveUp,\r\n      ]);\r\n      if (typeof result.code !== 'string') {\r\n        throw new Error('Unexpected CapSkip result for turnstile');\r\n      }\r\n      return { token: result.code, userAgent: result.userAgent };\r\n    } finally {\r\n      clearTimeout(timer);\r\n    }\r\n  }\r\n}<\/pre>\n<\/div>\n<p>Turnstile is the example because its result carries a User-Agent that the SDK types say to use when you submit the token. The service returns it with the token as a small object, not as the raw SDK result, whose code field is typed as a string or an object and is rejected here when it is not a string. Other types follow the same shape: add a method each for recaptcha, hcaptcha or mtcaptcha, passing the timeout, for the reason in Step 3. The fields each type takes are in the <a href=\"https:\/\/capskip.com\/api-docs\/\">API docs<\/a>.<\/p>\n<h3 style=\"font-size:1.3rem;line-height:1.4;\">SDK errors as HTTP statuses<\/h3>\n<p>The SDK has four exception classes, all extending CapSkipError: ValidationException, NetworkException, ApiException and TimeoutException. An ApiException carries only the reply text of CapSkip as its message, with no code field, so the mapping reads the ERROR_ code out of the message. Save this as src\/capskip\/capskip.errors.ts.<\/p>\n<div data-no-translation>\n<pre data-enlighter-language=\"typescript\" class=\"EnlighterJSRAW\">\/\/ src\/capskip\/capskip.errors.ts\r\nimport { Catch, HttpException, HttpStatus, Logger, type ArgumentsHost } from '@nestjs\/common';\r\nimport { BaseExceptionFilter } from '@nestjs\/core';\r\nimport {\r\n  ApiException,\r\n  CapSkipError,\r\n  NetworkException,\r\n  TimeoutException,\r\n  ValidationException,\r\n} from 'capskip';\r\n\r\nconst BAD_INPUT = \/ERROR_(RECAPTCHA_INVALID_(SITEKEY|DOMAIN)|BAD_PARAMETERS|PAGEURL)\/;\r\nconst BAD_CREDENTIALS = \/ERROR_(KEY_DOES_NOT_EXIST|WRONG_USER_KEY|ZERO_BALANCE)\/;\r\n\r\nexport function toHttpException(err: CapSkipError): HttpException {\r\n  const code = \/ERROR_[A-Z_]+\/.exec(err.message)?.[0];\r\n  const body = (status: HttpStatus, error: string) =&gt; ({\r\n    statusCode: status,\r\n    error,\r\n    code: code ?? err.name,\r\n  });\r\n\r\n  if (err instanceof TimeoutException) {\r\n    return new HttpException(body(HttpStatus.GATEWAY_TIMEOUT, 'Solver timeout'), 504);\r\n  }\r\n  if (err instanceof NetworkException) {\r\n    return new HttpException(body(HttpStatus.SERVICE_UNAVAILABLE, 'Solver unreachable'), 503);\r\n  }\r\n  if (err instanceof ApiException &amp;&amp; BAD_INPUT.test(err.message)) {\r\n    return new HttpException(body(HttpStatus.BAD_REQUEST, 'Solver refused the task'), 400);\r\n  }\r\n  if (err instanceof ApiException &amp;&amp; code === 'ERROR_CAPTCHA_UNSOLVABLE') {\r\n    return new HttpException(body(HttpStatus.UNPROCESSABLE_ENTITY, 'Not solved, retry'), 422);\r\n  }\r\n  if (err instanceof ValidationException) {\r\n    \/\/ The SDK refused a task this service built: a bug here, not the caller's.\r\n    return new HttpException(body(HttpStatus.INTERNAL_SERVER_ERROR, 'Task refused by the SDK'), 500);\r\n  }\r\n  \/\/ Wrong key, empty balance or anything else: our side of the link, not the caller's.\r\n  const error = err instanceof ApiException &amp;&amp; BAD_CREDENTIALS.test(err.message)\r\n    ? 'Solver credentials rejected'\r\n    : 'Solver error';\r\n  return new HttpException(body(HttpStatus.BAD_GATEWAY, error), 502);\r\n}\r\n\r\n@Catch(CapSkipError)\r\nexport class CapSkipExceptionFilter extends BaseExceptionFilter {\r\n  private readonly logger = new Logger(CapSkipExceptionFilter.name);\r\n\r\n  override catch(err: CapSkipError, host: ArgumentsHost) {\r\n    \/\/ The SDK message is the reply text of CapSkip and never holds the key.\r\n    this.logger.warn(`${err.name} ${err.message}`);\r\n    super.catch(toHttpException(err), host);\r\n  }\r\n}<\/pre>\n<\/div>\n<p>The filter extends BaseExceptionFilter and delegates, the pattern the <a href=\"https:\/\/docs.nestjs.com\/exception-filters\" rel=\"noopener nofollow\" target=\"_blank\">Nest exception filter chapter<\/a> shows, so it works on any HTTP adapter. It catches only CapSkipError, logs one warning with the error name and message (the reply text of CapSkip, never your key) and keeps that raw message out of the response.<\/p>\n<table>\n<thead>\n<tr>\n<th>What the SDK raised<\/th>\n<th>HTTP<\/th>\n<th>Why that status<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>TimeoutException<\/td>\n<td>504<\/td>\n<td>No token within the timeout. A CapSkip that goes quiet between polls ends here too<\/td>\n<\/tr>\n<tr>\n<td>NetworkException<\/td>\n<td>503<\/td>\n<td>CapSkip could not be reached when the task was submitted<\/td>\n<\/tr>\n<tr>\n<td>ApiException with ERROR_CAPTCHA_UNSOLVABLE<\/td>\n<td>422<\/td>\n<td>Not solved. The CapSkip API docs say to submit a new task<\/td>\n<\/tr>\n<tr>\n<td>ApiException with ERROR_RECAPTCHA_INVALID_SITEKEY, ERROR_RECAPTCHA_INVALID_DOMAIN, ERROR_BAD_PARAMETERS or ERROR_PAGEURL<\/td>\n<td>400<\/td>\n<td>The caller sent a sitekey or page address that CapSkip refuses<\/td>\n<\/tr>\n<tr>\n<td>ApiException with ERROR_KEY_DOES_NOT_EXIST, ERROR_WRONG_USER_KEY or ERROR_ZERO_BALANCE<\/td>\n<td>502<\/td>\n<td>Your service&#8217;s own key is the problem, not the caller&#8217;s input<\/td>\n<\/tr>\n<tr>\n<td>ValidationException<\/td>\n<td>500<\/td>\n<td>The SDK refused a task this service built, which is a bug here<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>Any other ApiException becomes a 502. The module registers the filter with APP_FILTER, so every app that imports the module gets the mapping.<\/p>\n<h3 style=\"font-size:1.3rem;line-height:1.4;\">The module, the app and a controller<\/h3>\n<p>Save the module as src\/capskip\/capskip.module.ts. It builds the client from the options in a factory provider, adds the service and registers the filter.<\/p>\n<div data-no-translation>\n<pre data-enlighter-language=\"typescript\" class=\"EnlighterJSRAW\">\/\/ src\/capskip\/capskip.module.ts\r\nimport { Module } from '@nestjs\/common';\r\nimport { APP_FILTER } from '@nestjs\/core';\r\nimport { CapSkip } from 'capskip';\r\nimport { CapSkipExceptionFilter } from '.\/capskip.errors.js';\r\nimport {\r\n  ConfigurableModuleClass,\r\n  MODULE_OPTIONS_TOKEN,\r\n  type CapSkipModuleOptions,\r\n} from '.\/capskip.options.js';\r\nimport { CAPSKIP_CLIENT, CapSkipService } from '.\/capskip.service.js';\r\n\r\n@Module({\r\n  providers: [\r\n    {\r\n      provide: CAPSKIP_CLIENT,\r\n      inject: [MODULE_OPTIONS_TOKEN],\r\n      useFactory: ({ host, port, apiKey }: CapSkipModuleOptions) =&gt;\r\n        new CapSkip({ host, port, apiKey }),\r\n    },\r\n    CapSkipService,\r\n    { provide: APP_FILTER, useClass: CapSkipExceptionFilter },\r\n  ],\r\n  exports: [CapSkipService],\r\n})\r\nexport class CapSkipModule extends ConfigurableModuleClass {}<\/pre>\n<\/div>\n<p>Replace src\/app.module.ts with the next block. forRootAsync runs the factory with whatever you list in inject. ConfigModule is global here, so CapSkipModule finds ConfigService without importing it.<\/p>\n<div data-no-translation>\n<pre data-enlighter-language=\"typescript\" class=\"EnlighterJSRAW\">\/\/ src\/app.module.ts\r\nimport { Module } from '@nestjs\/common';\r\nimport { ConfigModule, ConfigService } from '@nestjs\/config';\r\nimport { CapSkipModule } from '.\/capskip\/capskip.module.js';\r\nimport { TurnstileController } from '.\/turnstile.controller.js';\r\n\r\n@Module({\r\n  imports: [\r\n    ConfigModule.forRoot({ isGlobal: true }),\r\n    CapSkipModule.forRootAsync({\r\n      inject: [ConfigService],\r\n      useFactory: (config: ConfigService) =&gt; ({\r\n        host: config.get&lt;string&gt;('CAPSKIP_HOST', '127.0.0.1'),\r\n        port: Number(config.get('CAPSKIP_PORT', 8080)),\r\n        apiKey: config.get&lt;string&gt;('CAPSKIP_API_KEY'),\r\n        timeoutSeconds: Number(config.get('CAPSKIP_TIMEOUT', 60)),\r\n      }),\r\n    }),\r\n  ],\r\n  controllers: [TurnstileController],\r\n})\r\nexport class AppModule {}<\/pre>\n<\/div>\n<p>Last, save src\/turnstile.controller.ts. The url decides which page CapSkip solves for, so an open route would let anyone spend your solver. The check against TARGET_HOSTS is the minimum: it accepts only https addresses, trims the list and refuses every request when the list is empty or unset. Put your own authentication guard in front of it.<\/p>\n<div data-no-translation>\n<pre data-enlighter-language=\"typescript\" class=\"EnlighterJSRAW\">\/\/ src\/turnstile.controller.ts\r\nimport { BadRequestException, Body, Controller, Post } from '@nestjs\/common';\r\nimport { ConfigService } from '@nestjs\/config';\r\nimport { CapSkipService } from '.\/capskip\/capskip.service.js';\r\n\r\n@Controller('captcha')\r\nexport class TurnstileController {\r\n  constructor(\r\n    private readonly capskip: CapSkipService,\r\n    private readonly config: ConfigService,\r\n  ) {}\r\n\r\n  @Post('turnstile')\r\n  solve(@Body() body: { sitekey?: unknown; url?: unknown }) {\r\n    const hosts = this.config\r\n      .get&lt;string&gt;('TARGET_HOSTS', '')\r\n      .split(',')\r\n      .map((host) =&gt; host.trim())\r\n      .filter(Boolean);\r\n    const page =\r\n      typeof body.url === 'string' &amp;&amp; URL.canParse(body.url) ? new URL(body.url) : null;\r\n    if (\r\n      typeof body.sitekey !== 'string' ||\r\n      !body.sitekey ||\r\n      !page ||\r\n      page.protocol !== 'https:' ||\r\n      !hosts.includes(page.host)\r\n    ) {\r\n      throw new BadRequestException('sitekey or url missing, or host not allowed');\r\n    }\r\n    return this.capskip.solveTurnstile(body.sitekey, page.href);\r\n  }\r\n}<\/pre>\n<\/div>\n<h2 style=\"font-size:1.6rem;line-height:1.35;\">Step 3: the request timeout and the SDK deadline<\/h2>\n<p>I set no timeout in Nest, and the requests below waited their full 7.8 seconds, so the SDK deadline is the only one here. It is counted in seconds and behaves in four ways that matter to a waiting request.<\/p>\n<p>First, the deadline is checked when the next poll is due, not when it passes. The SDK polls at about 0, 0.25, 0.75, 1.75 and 3.75 seconds, then at 7.75 and every 5 seconds after, so a timeout of 5 ends at about 7.8. Measured against a mock that never answers, on Node.js 24.22.0 (20.11.1 agreed within 0.1 seconds on all four rows):<\/p>\n<table>\n<thead>\n<tr>\n<th>Timeout option<\/th>\n<th>TimeoutException after<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>5 seconds<\/td>\n<td>7.82 seconds<\/td>\n<\/tr>\n<tr>\n<td>10 seconds<\/td>\n<td>12.83 seconds<\/td>\n<\/tr>\n<tr>\n<td>20 seconds<\/td>\n<td>22.82 seconds<\/td>\n<\/tr>\n<tr>\n<td>30 seconds<\/td>\n<td>32.86 seconds<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>So give every caller, and every proxy in front, a timeout of the SDK value plus at least 5 seconds. Through Nest, CAPSKIP_TIMEOUT 5 answered 504 after 7.84 seconds.<\/p>\n<p>Second, turnstile() uses the client defaultTimeout, 120 seconds, not recaptchaTimeout, although a comment in the SDK type definitions lists Turnstile under recaptchaTimeout. With defaultTimeout 3 and recaptchaTimeout 30 it ended after 3.81 seconds; swapped, after 32.87. The source has recaptcha reading recaptchaTimeout and mtcaptcha defaultTimeout, so the service passes the timeout option on every call.<\/p>\n<p>Third, a caller who gives up does not stop the solve: the SDK takes no AbortSignal and Nest does not cancel a handler on disconnect. A supertest client that left at 3.0 seconds was followed by a fifth poll at 3.79 seconds. A short timeout is the only brake, so CAPSKIP_TIMEOUT stays small.<\/p>\n<p>Fourth, and worst: the SDK sets no timeout on its HTTP requests and checks the deadline only between polls. If CapSkip accepts a poll and never replies, because the PC slept or a firewall drops packets, the deadline is never checked. Against a mock that did that, the SDK with timeout 5 was still pending after 30 seconds. So the service races the SDK call against its own timer, 6 seconds past the SDK deadline: with CAPSKIP_TIMEOUT at 5, the hung poll became a 504 after 11.0 seconds. The abandoned SDK call stays pending, so keep the race and a short timeout together.<\/p>\n<h2 style=\"font-size:1.6rem;line-height:1.35;\">Step 4: tests for the NestJS captcha service<\/h2>\n<h3 style=\"font-size:1.3rem;line-height:1.4;\">A unit test with a mocked client<\/h3>\n<p>Save this as src\/capskip\/capskip.service.spec.ts. Test.createTestingModule builds a module from the real service and two plain values: a fake client and fake options. The scaffold&#8217;s npm test script runs it. It also covers a non-string result and the hung CapSkip timer.<\/p>\n<div data-no-translation>\n<pre data-enlighter-language=\"typescript\" class=\"EnlighterJSRAW\">\/\/ src\/capskip\/capskip.service.spec.ts\r\nimport { HttpException } from '@nestjs\/common';\r\nimport { Test } from '@nestjs\/testing';\r\nimport { ApiException, NetworkException, TimeoutException, ValidationException } from 'capskip';\r\nimport { toHttpException } from '.\/capskip.errors.js';\r\nimport { MODULE_OPTIONS_TOKEN } from '.\/capskip.options.js';\r\nimport { CAPSKIP_CLIENT, CapSkipService } from '.\/capskip.service.js';\r\n\r\ndescribe('CapSkipService', () =&gt; {\r\n  const turnstile = vi.fn();\r\n  let service: CapSkipService;\r\n\r\n  beforeEach(async () =&gt; {\r\n    turnstile.mockReset();\r\n    const moduleRef = await Test.createTestingModule({\r\n      providers: [\r\n        CapSkipService,\r\n        { provide: CAPSKIP_CLIENT, useValue: { turnstile } },\r\n        { provide: MODULE_OPTIONS_TOKEN, useValue: { timeoutSeconds: 20 } },\r\n      ],\r\n    }).compile();\r\n    service = moduleRef.get(CapSkipService);\r\n  });\r\n\r\n  it('passes the timeout and returns token and User-Agent', async () =&gt; {\r\n    turnstile.mockResolvedValue({ captchaId: '7', code: 'tok', userAgent: 'UA' });\r\n    await expect(service.solveTurnstile('0xKEY', 'https:\/\/example.com\/')).resolves.toEqual({\r\n      token: 'tok',\r\n      userAgent: 'UA',\r\n    });\r\n    expect(turnstile).toHaveBeenCalledWith('0xKEY', 'https:\/\/example.com\/', { timeout: 20 });\r\n  });\r\n\r\n  afterEach(() =&gt; vi.useRealTimers());\r\n\r\n  it('refuses a result whose code is not a string', async () =&gt; {\r\n    turnstile.mockResolvedValue({ captchaId: '7', code: { token: 'x' } });\r\n    await expect(service.solveTurnstile('0xKEY', 'https:\/\/example.com\/')).rejects.toThrow(\r\n      'Unexpected CapSkip result',\r\n    );\r\n  });\r\n\r\n  it('gives up 6 seconds after the SDK deadline when CapSkip never answers', async () =&gt; {\r\n    vi.useFakeTimers();\r\n    turnstile.mockReturnValue(new Promise(() =&gt; {}));\r\n    const outcome = expect(service.solveTurnstile('0xKEY', 'https:\/\/example.com\/')).rejects.toBeInstanceOf(\r\n      TimeoutException,\r\n    );\r\n    await vi.advanceTimersByTimeAsync(26_000);\r\n    await outcome;\r\n  });\r\n\r\n  it.each([\r\n    [new TimeoutException('timeout 20 exceeded'), 504],\r\n    [new NetworkException('connect ECONNREFUSED'), 503],\r\n    [new ApiException('ERROR_CAPTCHA_UNSOLVABLE'), 422],\r\n    [new ApiException('ERROR_RECAPTCHA_INVALID_SITEKEY'), 400],\r\n    [new ApiException('ERROR_WRONG_USER_KEY'), 502],\r\n    [new ValidationException('Unsupported parameters'), 500],\r\n  ])('maps %s to HTTP %i', (err, status) =&gt; {\r\n    const mapped = toHttpException(err);\r\n    expect(mapped).toBeInstanceOf(HttpException);\r\n    expect(mapped.getStatus()).toBe(status);\r\n  });\r\n});<\/pre>\n<\/div>\n<p>The controller gets a spec of its own, src\/turnstile.controller.spec.ts, because the empty-list case needs no running app.<\/p>\n<div data-no-translation>\n<pre data-enlighter-language=\"typescript\" class=\"EnlighterJSRAW\">\/\/ src\/turnstile.controller.spec.ts\r\nimport { BadRequestException } from '@nestjs\/common';\r\nimport { TurnstileController } from '.\/turnstile.controller.js';\r\n\r\ndescribe('TurnstileController', () =&gt; {\r\n  const solveTurnstile = vi.fn().mockResolvedValue({ token: 'tok' });\r\n  const controller = (hosts?: string) =&gt;\r\n    new TurnstileController(\r\n      { solveTurnstile } as never,\r\n      { get: (_name: string, fallback: string) =&gt; hosts ?? fallback } as never,\r\n    );\r\n  const page = { sitekey: '0xKEY', url: 'https:\/\/example.com\/login' };\r\n\r\n  beforeEach(() =&gt; solveTurnstile.mockClear());\r\n\r\n  it.each([undefined, '', ' , '])('refuses every request when TARGET_HOSTS is %j', (hosts) =&gt; {\r\n    expect(() =&gt; controller(hosts).solve(page)).toThrow(BadRequestException);\r\n    expect(solveTurnstile).not.toHaveBeenCalled();\r\n  });\r\n\r\n  it('accepts a listed host and passes the parsed address on', async () =&gt; {\r\n    await controller(' example.com , ').solve(page);\r\n    expect(solveTurnstile).toHaveBeenCalledWith('0xKEY', 'https:\/\/example.com\/login');\r\n  });\r\n});<\/pre>\n<\/div>\n<h3 style=\"font-size:1.3rem;line-height:1.4;\">An e2e test against a mock CapSkip<\/h3>\n<p>A NestJS captcha service should be tested without a live CapSkip, so this mock stands in for in.php and res.php. It listens on port 0, so the system picks a free port, and it records what it receives. Its replies and delays are my rules, not the behaviour of a real CapSkip. Save it as test\/mock-capskip.ts.<\/p>\n<div data-no-translation>\n<pre data-enlighter-language=\"typescript\" class=\"EnlighterJSRAW\">\/\/ test\/mock-capskip.ts\r\nimport { createServer } from 'node:http';\r\nimport type { AddressInfo } from 'node:net';\r\n\r\n\/\/ A stand-in for CapSkip's in.php and res.php. Not the real app: the\r\n\/\/ delay and the replies below are this file's own rules.\r\nexport async function startMock(listenPort = 0) {\r\n  const mock = {\r\n    port: 0,\r\n    solveMs: 0, \/\/ how long a task stays &quot;not ready&quot;\r\n    submitReply: '', \/\/ set to ERROR_... to refuse every submit\r\n    pollReply: '', \/\/ set to ERROR_... to fail every poll\r\n    hangPolls: false, \/\/ accept a poll and never answer it\r\n    submits: [] as Record&lt;string, string&gt;[],\r\n    polls: [] as number[], \/\/ Date.now() of each res.php call\r\n    close: () =&gt; {\r\n      server.closeAllConnections();\r\n      return new Promise&lt;void&gt;((done) =&gt; server.close(() =&gt; done()));\r\n    },\r\n  };\r\n  let submittedAt = 0;\r\n\r\n  const server = createServer((req, res) =&gt; {\r\n    const url = new URL(req.url!, 'http:\/\/mock');\r\n    let raw = '';\r\n    req.on('data', (chunk) =&gt; (raw += chunk));\r\n    req.on('end', () =&gt; {\r\n      if (url.pathname === '\/in.php') {\r\n        mock.submits.push(Object.fromEntries(new URLSearchParams(raw)));\r\n        submittedAt = Date.now();\r\n        res.end(mock.submitReply || 'OK|7');\r\n      } else if (url.pathname === '\/res.php') {\r\n        mock.polls.push(Date.now());\r\n        if (mock.hangPolls) return;\r\n        const waiting = Date.now() - submittedAt &lt; mock.solveMs;\r\n        if (mock.pollReply) res.end(JSON.stringify({ status: 0, request: mock.pollReply }));\r\n        else if (waiting) res.end(JSON.stringify({ status: 0, request: 'CAPCHA_NOT_READY' }));\r\n        else res.end(JSON.stringify({ status: 1, request: '0.mock-token', useragent: 'Mock UA' }));\r\n      } else {\r\n        res.statusCode = 404;\r\n        res.end();\r\n      }\r\n    });\r\n  });\r\n\r\n  await new Promise&lt;void&gt;((ready) =&gt; server.listen(listenPort, '127.0.0.1', ready));\r\n  mock.port = (server.address() as AddressInfo).port;\r\n  return mock;\r\n}<\/pre>\n<\/div>\n<p>The e2e spec boots the real AppModule, points the environment variables at the mock and sends requests with supertest. Save it as test\/turnstile.e2e-spec.ts and run npm run test:e2e. Variables already in the environment win over .env, so the spec can override them.<\/p>\n<div data-no-translation>\n<pre data-enlighter-language=\"typescript\" class=\"EnlighterJSRAW\">\/\/ test\/turnstile.e2e-spec.ts\r\nimport { Logger, type INestApplication } from '@nestjs\/common';\r\nimport { Test } from '@nestjs\/testing';\r\nimport request from 'supertest';\r\nimport { AppModule } from '..\/src\/app.module.js';\r\nimport { startMock } from '.\/mock-capskip.js';\r\n\r\ndescribe('POST \/captcha\/turnstile', () =&gt; {\r\n  let app: INestApplication;\r\n  let mock: Awaited&lt;ReturnType&lt;typeof startMock&gt;&gt;;\r\n  const body = { sitekey: '0xKEY', url: 'https:\/\/example.com\/login' };\r\n\r\n  beforeAll(async () =&gt; {\r\n    mock = await startMock();\r\n    process.env.CAPSKIP_HOST = '127.0.0.1';\r\n    process.env.CAPSKIP_PORT = String(mock.port);\r\n    process.env.CAPSKIP_TIMEOUT = '5';\r\n    process.env.TARGET_HOSTS = ' example.com, '; \/\/ spaces and a trailing comma are harmless\r\n    const moduleRef = await Test.createTestingModule({ imports: [AppModule] }).compile();\r\n    app = moduleRef.createNestApplication();\r\n    await app.init();\r\n  });\r\n\r\n  afterAll(async () =&gt; {\r\n    await app.close();\r\n    await mock.close();\r\n  });\r\n\r\n  beforeEach(() =&gt; {\r\n    Object.assign(mock, { solveMs: 0, submitReply: '', pollReply: '', hangPolls: false, submits: [], polls: [] });\r\n  });\r\n\r\n  it('returns the token and sends a turnstile task', async () =&gt; {\r\n    const res = await request(app.getHttpServer()).post('\/captcha\/turnstile').send(body).expect(201);\r\n    expect(res.body).toEqual({ token: '0.mock-token', userAgent: 'Mock UA' });\r\n    expect(mock.submits[0]).toMatchObject({ method: 'turnstile', sitekey: '0xKEY', pageurl: body.url });\r\n  });\r\n\r\n  it('refuses a host that is not on the list, before CapSkip is called', async () =&gt; {\r\n    await request(app.getHttpServer())\r\n      .post('\/captcha\/turnstile')\r\n      .send({ ...body, url: 'https:\/\/evil.test\/' })\r\n      .expect(400);\r\n    expect(mock.submits).toHaveLength(0);\r\n  });\r\n\r\n  it.each([\r\n    { sitekey: '0xKEY', url: 'http:\/\/example.com\/login' },\r\n    { sitekey: '0xKEY', url: 'file:\/\/\/C:\/Windows\/win.ini' },\r\n    { sitekey: '0xKEY', url: 'not a url' },\r\n    { sitekey: { a: 1 }, url: 'https:\/\/example.com\/login' },\r\n    { url: 'https:\/\/example.com\/login' },\r\n  ])('refuses %j before CapSkip is called', async (bad) =&gt; {\r\n    await request(app.getHttpServer()).post('\/captcha\/turnstile').send(bad).expect(400);\r\n    expect(mock.submits).toHaveLength(0);\r\n  });\r\n\r\n  it('maps an unsolvable task to 422 and logs one warning', async () =&gt; {\r\n    const warn = vi.spyOn(Logger.prototype, 'warn');\r\n    mock.pollReply = 'ERROR_CAPTCHA_UNSOLVABLE';\r\n    const res = await request(app.getHttpServer()).post('\/captcha\/turnstile').send(body).expect(422);\r\n    expect(res.body).toMatchObject({ code: 'ERROR_CAPTCHA_UNSOLVABLE' });\r\n    expect(warn).toHaveBeenCalledWith(expect.stringContaining('ERROR_CAPTCHA_UNSOLVABLE'));\r\n    warn.mockRestore();\r\n  });\r\n\r\n  it('maps a refused key to 502', async () =&gt; {\r\n    mock.submitReply = 'ERROR_WRONG_USER_KEY';\r\n    await request(app.getHttpServer()).post('\/captcha\/turnstile').send(body).expect(502);\r\n  });\r\n\r\n  it('answers 504 after the timeout of 5 seconds, not before it', async () =&gt; {\r\n    mock.solveMs = 60_000;\r\n    const started = Date.now();\r\n    await request(app.getHttpServer()).post('\/captcha\/turnstile').send(body).expect(504);\r\n    const seconds = (Date.now() - started) \/ 1000;\r\n    expect(seconds).toBeGreaterThan(5);\r\n    expect(seconds).toBeLessThan(9);\r\n  }, 15_000);\r\n\r\n  it('answers 504 when CapSkip accepts a poll and never replies', async () =&gt; {\r\n    mock.hangPolls = true;\r\n    const started = Date.now();\r\n    await request(app.getHttpServer()).post('\/captcha\/turnstile').send(body).expect(504);\r\n    const seconds = (Date.now() - started) \/ 1000;\r\n    expect(seconds).toBeGreaterThan(10.5);\r\n    expect(seconds).toBeLessThan(13);\r\n  }, 20_000);\r\n});<\/pre>\n<\/div>\n<p>These are the results, with the mock and capskip 1.7.0, on Windows 11:<\/p>\n<table>\n<thead>\n<tr>\n<th>Runtime<\/th>\n<th>Unit tests<\/th>\n<th>E2E tests<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Node.js 24.22.0<\/td>\n<td>13 passed in 2 files<\/td>\n<td>11 passed, about 19 s<\/td>\n<\/tr>\n<tr>\n<td>Node.js 25.2.1<\/td>\n<td>13 passed in 2 files<\/td>\n<td>11 passed, about 19 s<\/td>\n<\/tr>\n<tr>\n<td>Node.js 20.11.1<\/td>\n<td>The scaffold command and Vitest fail<\/td>\n<td>The scaffold command and Vitest fail<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>On 20.11.1 the scaffold command and Vitest stop with an error that node:util has no export named styleText, which that release does not provide.<\/p>\n<h2 style=\"font-size:1.6rem;line-height:1.35;\">Running it on another machine: Server mode<\/h2>\n<p>A Nest service rarely lives on the PC that runs CapSkip. Put the address of that PC in CAPSKIP_HOST and nothing else changes. CapSkip must then be in Server mode, described in the <a href=\"https:\/\/capskip.com\/setup-guide\/#connection-settings\">connection settings<\/a> section of the setup guide, which says Server mode needs CapSkip to run as administrator. The SDK speaks plain http and sends the key in the query string of every res.php call, so keep that link on a private network.<\/p>\n<p>CapSkip opens its port to every address when Server mode starts, so to keep it to the machines you expect, add a Windows Firewall block rule for the others, and switch on API Key Validation so CAPSKIP_API_KEY means something. With CapSkip not running, the submit fails with a NetworkException (a refused connection on 127.0.0.1 in my run) and the filter answers 503. An unroutable address (192.0.2.1) made the SDK give up after 21.1 seconds, so the service answered 503 after about 21 seconds with the timeout at 20; with the timeout at 5 the race answered 504 after 11.0 seconds. These runs used the mock and Node.js 24.22.0.<\/p>\n<h2 style=\"font-size:1.6rem;line-height:1.35;\">Common errors<\/h2>\n<table>\n<thead>\n<tr>\n<th>What you see<\/th>\n<th>Cause<\/th>\n<th>Fix<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Nest can&#8217;t resolve dependencies of the CapSkipService, argument Symbol(CAPSKIP_CLIENT) at index [0]<\/td>\n<td>A test module lists the service but not the client token<\/td>\n<td>Add a provider for CAPSKIP_CLIENT with a fake<\/td>\n<\/tr>\n<tr>\n<td>Nest can&#8217;t resolve dependencies of the CONFIGURABLE_MODULE_OPTIONS provider, argument ConfigService<\/td>\n<td>forRootAsync injects ConfigService, but ConfigModule is neither global nor imported<\/td>\n<td>Pass imports with ConfigModule, or set isGlobal in ConfigModule.forRoot<\/td>\n<\/tr>\n<tr>\n<td><code>TypeError: Cannot read properties of undefined (reading &quot;get&quot;)<\/code><\/td>\n<td>The factory has a config parameter but forRootAsync has no inject list<\/td>\n<td>Add inject with ConfigService<\/td>\n<\/tr>\n<tr>\n<td>Nest can&#8217;t resolve dependencies of the Symbol(CAPSKIP_CLIENT) provider, argument CONFIGURABLE_MODULE_OPTIONS<\/td>\n<td>CapSkipModule was imported bare, without forRoot or forRootAsync<\/td>\n<td>Import the result of one of those two calls<\/td>\n<\/tr>\n<tr>\n<td>HTTP 502 with code ERROR_WRONG_USER_KEY or ERROR_KEY_DOES_NOT_EXIST<\/td>\n<td>API Key Validation is on in CapSkip. The first code means the key is missing or empty, the second that it is invalid<\/td>\n<td>Set CAPSKIP_API_KEY to a valid key, then restart the service<\/td>\n<\/tr>\n<tr>\n<td>HTTP 504 long after you gave up<\/td>\n<td>The SDK keeps polling to its own deadline, or the race gave up on a silent CapSkip<\/td>\n<td>Lower CAPSKIP_TIMEOUT and read Step 3<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>The four Nest messages are the real wording of Nest 12.4.2 as printed by my test module, shortened. The CapSkip error codes are listed in the <a href=\"https:\/\/capskip.com\/api-docs\/\">API docs<\/a>.<\/p>\n<h2 style=\"font-size:1.6rem;line-height:1.35;\">FAQ<\/h2>\n<details style=\"border:1px solid #e2e5ee;border-radius:10px;padding:14px 18px;margin:0 0 12px;\">\n<summary style=\"cursor:pointer;\">\n<h3 style=\"font-size:1.15rem;line-height:1.4;display:inline;margin:0;\">Can a NestJS captcha service run on a different machine than CapSkip?<\/h3>\n<\/summary>\n<p style=\"margin:12px 0 0;\">Yes. Set CAPSKIP_HOST to the address of the CapSkip PC and switch CapSkip to Server mode. Server mode makes CapSkip accept connections on every address, so add a Windows Firewall block rule for machines you do not expect and turn on API Key Validation. No code change is needed.<\/p>\n<\/details>\n<details style=\"border:1px solid #e2e5ee;border-radius:10px;padding:14px 18px;margin:0 0 12px;\">\n<summary style=\"cursor:pointer;\">\n<h3 style=\"font-size:1.15rem;line-height:1.4;display:inline;margin:0;\">When should I use a queue instead of a controller?<\/h3>\n<\/summary>\n<p style=\"margin:12px 0 0;\">When the caller can&#8217;t wait for a solve, or when many arrive at once. A controller holds the request open for the whole solve, which is fine for one or two at a time. A queue processor can import the same CapSkipModule, and the BullMQ worker guide covers that side.<\/p>\n<\/details>\n<details style=\"border:1px solid #e2e5ee;border-radius:10px;padding:14px 18px;margin:0 0 12px;\">\n<summary style=\"cursor:pointer;\">\n<h3 style=\"font-size:1.15rem;line-height:1.4;display:inline;margin:0;\">Why does the service return a User-Agent next to the token?<\/h3>\n<\/summary>\n<p style=\"margin:12px 0 0;\">The SDK types say that for Turnstile the result&#8217;s User-Agent is the one to use when you submit the token, and it is present only when CapSkip reports one. The service passes it on so the caller can send it.<\/p>\n<\/details>\n<p>A NestJS captcha service that must pass Turnstile needs three things in the right place: the client behind a token so it can be faked, one place that turns SDK errors into statuses, and a timeout on every call plus a race for the silent case. CapSkip is an <a href=\"https:\/\/capskip.com\/\">unlimited captcha solver<\/a> running on hardware you own, so a retry or a failing test run never shows up on an invoice. Solving the other CAPTCHA types from Node.js is covered on the <a href=\"https:\/\/capskip.com\/nodejs-captcha-solver\/\">Node.js CAPTCHA solver page<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>\u4e00\u4e2a\u5fc5\u987b\u901a\u8fc7 Turnstile \u5c0f\u7ec4\u4ef6\u7684 Nest \u670d\u52a1\uff1a\u56f4\u7ed5 capskip SDK \u7684 dynamic module\u3001\u9519\u8bef\u6620\u5c04\u3001\u884c\u4e3a\u53ef\u9760\u7684\u8d85\u65f6\uff0c\u4ee5\u53ca\u5355\u5143\u6d4b\u8bd5\u548c e2e \u6d4b\u8bd5\u3002<\/p>","protected":false},"author":1,"featured_media":28053,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"rank_math_title":"NestJS CAPTCHA Service: Solve Turnstile | CapSkip","rank_math_description":"Build a nestjs captcha service: wrap the capskip SDK in a Nest dynamic module, map its errors to HTTP statuses and test it with Vitest and supertest.","rank_math_focus_keyword":"nestjs captcha","footnotes":""},"categories":[70],"tags":[],"class_list":["post-28054","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-captcha"],"_links":{"self":[{"href":"https:\/\/capskip.com\/zh\/wp-json\/wp\/v2\/posts\/28054","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/capskip.com\/zh\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/capskip.com\/zh\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/capskip.com\/zh\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/capskip.com\/zh\/wp-json\/wp\/v2\/comments?post=28054"}],"version-history":[{"count":1,"href":"https:\/\/capskip.com\/zh\/wp-json\/wp\/v2\/posts\/28054\/revisions"}],"predecessor-version":[{"id":28461,"href":"https:\/\/capskip.com\/zh\/wp-json\/wp\/v2\/posts\/28054\/revisions\/28461"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/capskip.com\/zh\/wp-json\/wp\/v2\/media\/28053"}],"wp:attachment":[{"href":"https:\/\/capskip.com\/zh\/wp-json\/wp\/v2\/media?parent=28054"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/capskip.com\/zh\/wp-json\/wp\/v2\/categories?post=28054"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/capskip.com\/zh\/wp-json\/wp\/v2\/tags?post=28054"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}