NestJS कैप्चा सर्विस: एक module जो Turnstile हल करता है

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

NestJS कैप्चा के लिए ज़्यादातर सर्च का मतलब होता है किसी Nest साइट को कैप्चा से बचाना। यह गाइड उलटी दिशा की है: आपकी एक service को ऐसे पेज पर Cloudflare Turnstile widget पार करना है जिसे ऑटोमेट करने की आपको इजाज़त है, और उसे एक token चाहिए। आप capskip package को एक dynamic module में लपेटते हैं, उसकी errors को HTTP statuses में बदलते हैं और Vitest व supertest से उसे टेस्ट करते हैं। हल करने का काम CapSkip Turnstile सॉल्वर करता है, जो आपके अपने Windows PC पर चलता है और प्रति-हल शुल्क नहीं लेता। इसमें कोई queue शामिल नहीं है; जिन solves को queue में होना चाहिए, उनके लिए देखें BullMQ worker गाइड.

आपको क्या चाहिए

  • आपके अपने Windows PC पर चलता CapSkip। वह कहाँ सुनता है, यह सेटअप गाइडके कनेक्शन सेटिंग्स सेक्शन में तय होता है। Local mode उसे 127.0.0.1 पर रखता है, और Server mode उसे आपके network के लिए खोल देता है।
  • Node.js 24.15 या बाद का, 24 लाइन में, या 26। scaffold generator 22.22.3, 24.15 या 26 माँगता है, Vite 8 और उसका bundler 20.19 या 22.12 माँगता है, और Nest 12 खुद 20 माँगता है। मैंने scaffold से लेकर tests तक पूरा प्रोजेक्ट 24.22.0 और 25.2.1 पर चलाया, जहाँ npm ने @nestjs/schematics के लिए engine warning दिखाई। 20.11.1 पर scaffold command और Vitest फ़ेल हो जाते हैं।
  • Nest 12 (यहाँ 12.4.2) के साथ @nestjs/config 12.1.1 और capskip 1.7.0। scaffold सिर्फ़ ESM है (import paths .js पर खत्म होते हैं) और tests Vitest से चलते हैं, इसलिए mocks vi.fn हैं।

नीचे हर रन में मेरा लिखा in.php और res.php का एक mock इस्तेमाल हुआ, साथ में असली capskip 1.7.0 package। कोई task असली CapSkip तक नहीं पहुँचा, इसलिए मैं solve का कोई समय नहीं बताता, और हर देरी और जवाब mock का अपना नियम है।

चरण 1: प्रोजेक्ट और settings बनाएँ

इसे PowerShell में चलाएँ। यह ऐप का scaffold बनाता है, दोनों packages इंस्टॉल करता है, नए layout से बदले जाने वाली चार sample फ़ाइलें हटाता है और module के लिए फ़ोल्डर बनाता है।

# 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

अगला block प्रोजेक्ट फ़ोल्डर में चलाएँ। यह बिना editor के .env और .gitignore लिख देता है, इसलिए फ़ाइल का नाम .env.txt नहीं बन सकता। git के बिना बनाए scaffold में .gitignore नहीं होता, और .env में आपकी key रहेगी, इसलिए git पहली बार इस्तेमाल करने से पहले उसे वहाँ जोड़ दें। SDK खुद कोई environment variable नहीं पढ़ता, इसलिए चरण 2 की factory इन्हें पढ़ती है। CAPSKIP_API_KEY तभी मायने रखता है जब CapSkip में API Key Validation चालू हो; छोड़ देने पर SDK key के तौर पर 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: module बनाएँ

options, एक बार समझाए हुए

अगले block को src/capskip/capskip.options.ts नाम से सेव करें। Nest के साथ ConfigurableModuleBuilder आता है, जो static forRoot और forRootAsync methods और options के लिए एक injection token बना देता है। extras argument एक isGlobal flag जोड़ता है, जो options में नहीं जाता और module पर ही रहता है। इस builder की जानकारी यहाँ मिलती है: Nest dynamic modules चैप्टर.

// 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();

service, और token के पीछे client

इसे src/capskip/capskip.service.ts नाम से सेव करें। SDK client service के अंदर नहीं बनता। वह CAPSKIP_CLIENT token से आता है, और उसका type सिर्फ़ उस एक SDK method जितना है जो service इस्तेमाल करती है, इसलिए test एक function दे सकता है और compiler फिर भी उसका signature जाँचता है।

// 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 के types के अनुसार token submit करते समय इस्तेमाल करना है। service उसे token के साथ एक छोटे object के रूप में लौटाती है, कच्चे SDK नतीजे के रूप में नहीं, जिसकी code field का type string या object है और जो string न होने पर यहाँ reject कर दी जाती है। बाकी types भी इसी ढाँचे पर चलते हैं: recaptcha, hcaptcha या mtcaptcha के लिए एक-एक method जोड़ें और timeout पास करें, जिसकी वजह चरण 3 में है। हर type जो fields लेता है, वे यहाँ मिलेंगे: API दस्तावेज़.

SDK errors, HTTP statuses के रूप में

SDK में चार exception classes हैं, सब CapSkipError को extend करती हैं: ValidationException, NetworkException, ApiException और TimeoutException। ApiException के message में सिर्फ़ CapSkip का जवाब होता है, कोई code field नहीं, इसलिए mapping ERROR_ code को message से निकालती है। इसे 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);
  }
}

filter BaseExceptionFilter को extend करता है और काम उसे सौंप देता है, वही pattern जो Nest exception filter चैप्टर में दिखाया गया है, इसलिए वह किसी भी HTTP adapter पर चलता है। वह सिर्फ़ CapSkipError पकड़ता है, error का नाम और message (CapSkip का जवाब, आपकी key कभी नहीं) लेकर एक warning लॉग करता है और उस कच्चे message को response से बाहर रखता है।

SDK ने क्या raise कियाHTTPयही status क्यों
TimeoutException504timeout के भीतर कोई token नहीं आया। polls के बीच चुप हो गया CapSkip भी यहीं खत्म होता है
NetworkException503task submit करते समय CapSkip तक पहुँचा नहीं जा सका
ERROR_CAPTCHA_UNSOLVABLE वाला ApiException422हल नहीं हुआ। CapSkip API docs कहते हैं कि नया task submit करें
ERROR_RECAPTCHA_INVALID_SITEKEY, ERROR_RECAPTCHA_INVALID_DOMAIN, ERROR_BAD_PARAMETERS या ERROR_PAGEURL वाला ApiException400caller ने ऐसा sitekey या पेज का पता भेजा जिसे CapSkip नहीं मानता
ERROR_KEY_DOES_NOT_EXIST, ERROR_WRONG_USER_KEY या ERROR_ZERO_BALANCE वाला ApiException502दिक्कत आपकी service की अपनी key में है, caller के input में नहीं
ValidationException500SDK ने इस service का बनाया task ठुकरा दिया, यानी यहाँ bug है

कोई भी दूसरा ApiException 502 बन जाता है। module filter को APP_FILTER से register करता है, इसलिए जो भी ऐप इस module को import करता है उसे यह mapping मिल जाती है।

module, ऐप और एक controller

module को src/capskip/capskip.module.ts नाम से सेव करें। यह एक factory provider में options से client बनाता है, service जोड़ता है और filter को register करता है।

// 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 को अगले block से बदल दें। forRootAsync factory को वही चलाने देता है जो आप inject में लिखते हैं। यहाँ ConfigModule global है, इसलिए CapSkipModule को ConfigService बिना import किए मिल जाता है।

// 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 किस पेज के लिए हल करे, इसलिए खुला route किसी को भी आपका solver खर्च करने देगा। TARGET_HOSTS से जाँच कम से कम ज़रूरी है: वह सिर्फ़ https पते मानती है, सूची को trim करती है और सूची खाली या unset होने पर हर request ठुकरा देती है। इसके आगे अपना authentication 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: request timeout और SDK deadline

मैंने Nest में कोई timeout नहीं रखा, और नीचे की requests पूरे 7.8 सेकंड तक रुकी रहीं, इसलिए यहाँ अकेला deadline SDK का है। वह सेकंड में गिना जाता है और इंतज़ार कर रही request के लिए चार तरह से बर्ताव करता है।

पहला, deadline तब जाँचा जाता है जब अगला poll बनता है, तब नहीं जब वह बीतता है। SDK लगभग 0, 0.25, 0.75, 1.75 और 3.75 सेकंड पर poll करता है, फिर 7.75 पर और उसके बाद हर 5 सेकंड पर, इसलिए 5 का timeout लगभग 7.8 पर खत्म होता है। ऐसे mock के सामने नापा गया जो कभी जवाब नहीं देता, Node.js 24.22.0 पर (20.11.1 ने चारों पंक्तियों पर 0.1 सेकंड के भीतर वही दिखाया):

Timeout optionTimeoutException कितने बाद
5 सेकंड7.82 सेकंड
10 सेकंड12.83 सेकंड
20 सेकंड22.82 सेकंड
30 सेकंड32.86 सेकंड

इसलिए हर caller को, और उसके आगे के हर proxy को, SDK वाली value से कम से कम 5 सेकंड ज़्यादा का timeout दें। Nest के ज़रिए CAPSKIP_TIMEOUT 5 पर 504 आया 7.84 सेकंड बाद।

दूसरा, turnstile() client का defaultTimeout इस्तेमाल करता है, यानी 120 सेकंड, recaptchaTimeout नहीं, हालाँकि SDK की type definitions की एक टिप्पणी Turnstile को recaptchaTimeout के नीचे गिनाती है। defaultTimeout 3 और recaptchaTimeout 30 पर वह 3.81 सेकंड बाद खत्म हुआ; उलटने पर 32.87 बाद। source में recaptcha recaptchaTimeout पढ़ता है और mtcaptcha defaultTimeout, इसलिए service हर call पर timeout option पास करती है।

तीसरा, हार मान चुका caller solve नहीं रोकता: SDK कोई AbortSignal नहीं लेता और Nest disconnect होने पर handler को cancel नहीं करता। 3.0 सेकंड पर चला गया एक supertest client के बाद 3.79 सेकंड पर पाँचवाँ poll हुआ। छोटा timeout ही अकेला ब्रेक है, इसलिए CAPSKIP_TIMEOUT छोटा रखें।

चौथा, और सबसे बुरा: SDK अपनी HTTP requests पर कोई timeout नहीं लगाता और deadline सिर्फ़ polls के बीच जाँचता है। अगर CapSkip कोई poll ले ले और कभी जवाब न दे, क्योंकि PC सो गया या firewall packets गिरा रहा है, तो deadline कभी जाँचा ही नहीं जाता। ऐसा करने वाले mock के सामने timeout 5 वाला SDK 30 सेकंड बाद भी pending था। इसलिए service SDK call को अपने timer से race कराती है, जो SDK deadline से 6 सेकंड बाद का है: CAPSKIP_TIMEOUT 5 पर अटका poll 11.0 सेकंड बाद 504 बना। छोड़ी गई SDK call pending ही रहती है, इसलिए race और छोटा timeout साथ रखें।

चरण 4: NestJS कैप्चा service के tests

mock किए गए client के साथ unit test

इसे src/capskip/capskip.service.spec.ts नाम से सेव करें। Test.createTestingModule असली service और दो सादे values से एक module बनाता है: एक नकली client और नकली options। scaffold की npm test script इसे चलाती है। यह string न होने वाले नतीजे और अटके CapSkip timer को भी कवर करता है।

// 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);
  });
});

controller का अपना 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 test

NestJS कैप्चा service को live CapSkip के बिना टेस्ट करना चाहिए, इसलिए यह mock in.php और res.php की जगह खड़ा होता है। यह port 0 पर सुनता है, यानी सिस्टम कोई खाली port चुनता है, और जो मिलता है उसे दर्ज करता है। इसके जवाब और देरियाँ मेरे नियम हैं, असली 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 को boot करता है, environment variables को mock की ओर करता है और supertest से requests भेजता है। इसे test/turnstile.e2e-spec.ts नाम से सेव करें और npm run test:e2e चलाएँ। environment में पहले से मौजूद variables .env पर भारी पड़ते हैं, इसलिए spec उन्हें override कर सकता है।

// 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 पर:

RuntimeUnit testsE2E tests
Node.js 24.22.02 फ़ाइलों में 13 पास11 पास, लगभग 19 s
Node.js 25.2.12 फ़ाइलों में 13 पास11 पास, लगभग 19 s
Node.js 20.11.1scaffold command और Vitest फ़ेल हो जाते हैंscaffold command और Vitest फ़ेल हो जाते हैं

20.11.1 पर scaffold command और Vitest इस error के साथ रुक जाते हैं कि node:util में styleText नाम का कोई export नहीं है, जो उस रिलीज़ में मौजूद नहीं।

दूसरी मशीन पर चलाना: Server mode

Nest service शायद ही कभी उसी PC पर रहती है जिस पर CapSkip चलता है। उस PC का पता CAPSKIP_HOST में रख दें और बाकी कुछ नहीं बदलता। तब CapSkip का Server mode में होना ज़रूरी है, जो सेटअप गाइड के कनेक्शन सेटिंग्स सेक्शन में बताया गया है, और वहीं लिखा है कि Server mode के लिए CapSkip को administrator के तौर पर चलना होगा। SDK सादा http बोलता है और हर res.php call की query string में key भेजता है, इसलिए उस link को private network पर ही रखें।

Server mode शुरू होते ही CapSkip अपना port हर पते के लिए खोल देता है, इसलिए उसे सिर्फ़ अपेक्षित मशीनों तक सीमित रखने के लिए बाकी के लिए Windows Firewall की block rule जोड़ें, और API Key Validation चालू करें ताकि CAPSKIP_API_KEY का कोई मतलब बने। CapSkip न चल रहा हो तो submit NetworkException के साथ फ़ेल होता है (मेरे रन में 127.0.0.1 पर refused connection) और filter 503 देता है। एक unroutable पते (192.0.2.1) पर SDK ने 21.1 सेकंड बाद हार मान ली, इसलिए timeout 20 पर service ने लगभग 21 सेकंड बाद 503 दिया; timeout 5 पर race ने 11.0 सेकंड बाद 504 दिया। ये रन mock और Node.js 24.22.0 पर हुए।

आम errors

आप जो देखते हैंकारणफिक्स
Nest can’t resolve dependencies of the CapSkipService, argument Symbol(CAPSKIP_CLIENT) at index [0]test module में service है पर client token नहींCAPSKIP_CLIENT के लिए एक नकली के साथ provider जोड़ें
Nest can’t resolve dependencies of the CONFIGURABLE_MODULE_OPTIONS provider, argument ConfigServiceforRootAsync ConfigService inject करता है, पर ConfigModule न global है न import किया गयाConfigModule के साथ imports पास करें, या ConfigModule.forRoot में isGlobal सेट करें
TypeError: Cannot read properties of undefined (reading "get")factory में config parameter है पर forRootAsync में inject सूची नहींConfigService के साथ inject जोड़ें
Nest can’t resolve dependencies of the Symbol(CAPSKIP_CLIENT) provider, argument CONFIGURABLE_MODULE_OPTIONSCapSkipModule को बिना forRoot या forRootAsync के सीधे import कर लिया गयाउन दोनों calls में से किसी एक का नतीजा import करें
कोड ERROR_WRONG_USER_KEY या ERROR_KEY_DOES_NOT_EXIST के साथ HTTP 502CapSkip में API Key Validation चालू है। पहले कोड का मतलब key गायब या खाली है, दूसरे का कि वह अमान्य हैCAPSKIP_API_KEY को वैध key पर सेट करें, फिर service रीस्टार्ट करें
आपके हार मानने के काफ़ी बाद HTTP 504SDK अपने deadline तक poll करता रहता है, या race ने चुप CapSkip से हार मान लीCAPSKIP_TIMEOUT घटाएँ और चरण 3 पढ़ें

चारों Nest messages Nest 12.4.2 की असली भाषा हैं, जैसी मेरे test module ने छापीं, छोटी करके। CapSkip के error codes की सूची यहाँ है: API दस्तावेज़.

FAQ

क्या NestJS कैप्चा service CapSkip से अलग मशीन पर चल सकती है?

हाँ। CAPSKIP_HOST को CapSkip वाले PC के पते पर सेट करें और CapSkip को Server mode में कर दें। Server mode CapSkip को हर पते से connections लेने वाला बना देता है, इसलिए उन मशीनों के लिए Windows Firewall की block rule जोड़ें जिनकी आपको उम्मीद नहीं, और API Key Validation चालू करें। code में कोई बदलाव नहीं चाहिए।

controller की जगह queue कब इस्तेमाल करूँ?

जब caller solve का इंतज़ार नहीं कर सकता, या जब बहुत सारे एक साथ आते हैं। controller पूरे solve तक request खुली रखता है, जो एक या दो के लिए ठीक है। queue processor वही CapSkipModule import कर सकता है, और वह पक्ष BullMQ worker गाइड में है।

service token के साथ User-Agent क्यों लौटाती है?

SDK के types कहते हैं कि Turnstile में नतीजे का User-Agent ही token submit करते समय इस्तेमाल करना है, और वह तभी मौजूद होता है जब CapSkip बताए। service उसे आगे दे देती है ताकि caller उसे भेज सके।

Turnstile पार करने वाली NestJS कैप्चा service को तीन चीज़ें सही जगह चाहिए: token के पीछे client ताकि उसे नकली बनाया जा सके, एक जगह जो SDK errors को statuses में बदले, और हर call पर timeout के साथ चुप्पी वाले मामले के लिए race। CapSkip एक असीमित कैप्चा सॉल्वर है जो आपके अपने hardware पर चलता है, इसलिए retry या फ़ेल होता test run कभी invoice में नहीं दिखता। Node.js से बाकी CAPTCHA types हल करने की जानकारी यहाँ है: Node.js कैप्चा सॉल्वर पेज.