@nathapp/nestjs-captcha
v4.1.0
Published
nestjs-captcha
Readme
nestjs-captcha Library
Configuration
import { CaptchaModule, CaptchaType } from '@nathapp/nestjs-captcha';
@Module({
imports: [
CaptchaModule.register({
enabled: true,
extract: { type: 'header', key: 'x-captcha-token' },
type: CaptchaType.Recaptcha,
options: {
secret: process.env.CAPTCHA_SECRET,
// reCAPTCHA v3 score policy: reject responses scoring below 0.9.
threshold: 0.9,
// Exact hostname the upstream response must report.
expectedHostname: 'api.example.com',
},
}),
],
})
export class AppModule {}Both policies are optional but validated at provider construction, so a
misconfigured threshold (must be a finite number within [0, 1]) or an
empty/whitespace expectedHostname fails application bootstrap rather than the
first guarded request. When an enabled recaptcha provider sets neither
policy, a one-time warning is logged at construction (never including the
secret or a token).
reCAPTCHA v3 score checks vs. scoreless v2 / Turnstile
- reCAPTCHA v3: set
thresholdto enforce thescorereturned by Google. The guard rejects a missing, non-numeric, non-finite, or out-of-[0, 1]score whenever a threshold is configured.threshold: 0is honored — a score of0passes, but a missing/invalid score still fails. With nothreshold, scoreless reCAPTCHA v2 responses are accepted onsuccessalone. - reCAPTCHA v2: do not set
threshold; there is no score to check, so the guard verifiessuccessonly. - Turnstile: there is no score policy. Turnstile responses are accepted on
successalone;thresholddoes not apply. expectedHostname: applies to both reCAPTCHA and Turnstile. When set, the upstreamhostnamemust match exactly (api.example.com); a different domain, a subdomain, a suffix host, or an absent hostname is rejected. There is no wildcard matching and no request-Host-derived allowlist.- In every case the guard requires
success === true; a truthy non-boolean value (such as the string"true") is not treated as success.
DefaultCaptchaModuleFactory
DefaultCaptchaModuleFactory reads configuration from ConfigService (env):
- CAPTCHA_ENABLED = true/false, 1/0
- CAPTCHA_TYPE = recaptcha, turnstile
- CAPTCHA_SECRET = the secret
- CAPTCHA_ENDPOINT = custom endpoint
- CAPTCHA_THRESHOLD = for recaptcha
DefaultCaptchaModuleFactory extracts the token from the header with key
x-captcha-token.
