@mondart/nestjs-common-module-google-recaptcha
v3.1.11
Published
Google reCAPTCHA module, decorators and guards for NestJS.
Downloads
856
Readme
@mondart/nestjs-common-module-google-recaptcha
Google reCAPTCHA verification for NestJS: a module that configures a validator for either standard reCAPTCHA (v2/v3) or reCAPTCHA Enterprise, a guard that verifies the token on incoming requests, and decorators to opt a route in and read the verification result back out.
Registration
Standard reCAPTCHA (v2/v3), verified against Google's siteverify endpoint:
import { GoogleRecaptchaModule } from '@mondart/nestjs-common-module-google-recaptcha';
@Module({
imports: [
GoogleRecaptchaModule.forRoot({
secretKey: 'your-secret-key',
response: (req) => req.headers.recaptcha, // where to read the token from
score: 0.8, // reject v3 tokens scored below this (or a custom (score) => boolean)
}),
],
})
export class AppModule {}Or asynchronously:
GoogleRecaptchaModule.forRootAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: (config: ConfigService) => ({
secretKey: config.get('RECAPTCHA_SECRET_KEY'),
response: (req) => req.headers.recaptcha,
}),
});reCAPTCHA Enterprise instead, by providing enterprise instead of
secretKey (the two are mutually exclusive — the module throws at startup
if neither, or both incompletely, are configured):
GoogleRecaptchaModule.forRoot({
enterprise: {
projectId: 'your-gcp-project-id',
siteKey: 'your-site-key',
apiKey: 'your-api-key',
},
response: (req) => req.headers.recaptcha,
});RecaptchaValidatorResolver picks the right validator at request time based
on which of secretKey/enterprise is set — GoogleRecaptchaValidator for
standard reCAPTCHA, GoogleRecaptchaEnterpriseValidator for Enterprise.
Both validators apply the same score/actions checks, but Enterprise
requests go to the Enterprise Assessment API instead of siteverify and
map Google's Enterprise-specific invalidReason codes onto the same
ErrorCode enum via EnterpriseReasonTransformer.
Other module options: disable (skip verification entirely, e.g. in
tests), skipIf (per-request bypass, sync or async), remoteIp (extract
the caller's IP for Google's abuse signal), debug (log request/response
bodies), network (point standard reCAPTCHA at an alternate verify
endpoint, e.g. GoogleRecaptchaNetwork.Recaptcha), and axiosConfig.
Protecting a route
import { Recaptcha, RecaptchaResult } from '@mondart/nestjs-common-module-google-recaptcha';
import { RecaptchaVerificationResult } from '@mondart/nestjs-common-module-google-recaptcha';
@Recaptcha({ action: 'submit', score: 0.9 })
@Post('submit')
submit(@RecaptchaResult() result: RecaptchaVerificationResult) {
// result.success, result.score, result.action, result.errors, ...
}@Recaptcha(options?) applies GoogleRecaptchaGuard to the route and
overrides, per route, how the token/IP/score are resolved and which
action is expected — falling back to the module-level response/
remoteIp/score when omitted. On failure the guard throws
GoogleRecaptchaException (a BadRequestException for validation-style
failures, InternalServerErrorException for unknown errors) carrying the
Google ErrorCodes that caused it; a network failure reaching Google is
raised as the more specific GoogleRecaptchaNetworkException.
@RecaptchaResult() is a param decorator that returns the
RecaptchaVerificationResult the guard attached to the request (works for
both HTTP and GraphQL handlers). Enterprise responses also expose risk
analysis via result.getEnterpriseRiskAnalytics().
To apply the guard without the convenience decorator (e.g. to reuse a
different VerifyResponseDecoratorOptions), use @SetRecaptchaOptions()
together with @UseGuards(GoogleRecaptchaGuard) — this is exactly what
@Recaptcha() does under the hood.
