Created
May 18, 2025 09:15
-
-
Save Silent-Watcher/08052ddefd973f75bf7dedea6093d8a5 to your computer and use it in GitHub Desktop.
reCaptcha fraud detector
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { safeIncrWithTTL } from "#app/common/helpers/redis"; | |
| import { unwrap } from "#app/config/db/global"; | |
| import type { MultiExecResult } from "#app/config/db/redis.config"; | |
| import { redis } from "#app/config/db/redis.config"; | |
| import { logger } from "../logger.util"; | |
| const FAILURE_PREFIX = "recaptcha:fail:ip-"; | |
| const THRESHOLD = 5; // max allowed failures | |
| const WINDOW_SEC = 60 * 60; // rolling window for failures (1h) | |
| const BLOCK_PREFIX = "recaptcha:block:ip-"; | |
| const BLOCK_SEC = 60 * 60 * 24; // block duration (24h) | |
| /** | |
| * @returns true if IP is currently blocked | |
| */ | |
| export async function isBlocked(ip: string): Promise<boolean> { | |
| const blockKey = BLOCK_PREFIX + ip; | |
| const isBlocked = unwrap(await redis.fire("get", blockKey)); | |
| if (isBlocked) { | |
| return true; | |
| } | |
| return false; | |
| } | |
| export async function recordFailure(ip: string): Promise<void> { | |
| const failureKey = FAILURE_PREFIX + ip; | |
| // increment failures, set expiry if first time | |
| // ? race condition danger | |
| // const count = unwrap(await redis.fire("incr", failureKey)) as number; | |
| // if (count === 1) { | |
| // await redis.fire("expire", failureKey, WINDOW_SEC); | |
| // } | |
| const count = await safeIncrWithTTL(failureKey, WINDOW_SEC); | |
| // if too many failures, block the IP | |
| if (count >= THRESHOLD) { | |
| // ? bad code: | |
| // await redis.fire("set", BLOCK_PREFIX + ip, "1", "EX", BLOCK_SEC); | |
| // await redis.fire("del", failureKey); | |
| // ? better code: | |
| const results = unwrap( | |
| await redis.fire("multi", [ | |
| ["set", BLOCK_PREFIX + ip, "1", "EX", BLOCK_SEC], | |
| ["del", failureKey], | |
| ]), | |
| ) as MultiExecResult; | |
| if (!results || results.length === 0) { | |
| logger.error("[REDIS TRANSACTION FAILED]"); | |
| return; | |
| } | |
| for (let index = 0; index < results.length; index++) { | |
| const element = results[index] as NonNullable< | |
| Awaited<MultiExecResult> | |
| >[number]; | |
| if (element[0]) { | |
| logger.error(`[REDIS TRANSACTION FAILED] : ${element[0]}`); | |
| return; | |
| } | |
| } | |
| logger.warn( | |
| `[recaptcha][fraud] IP ${ip} blocked for ${BLOCK_SEC}s after ${count} failed attempts`, | |
| ); | |
| } | |
| } | |
| /** | |
| * Reset failure count after a successful verify | |
| */ | |
| export async function resetFailures(ip: string): Promise<void> { | |
| await redis.fire("del", FAILURE_PREFIX + ip); | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import type { NextFunction, Request, Response } from 'express'; | |
| import { z } from 'zod'; | |
| import { fromZodError } from 'zod-validation-error'; | |
| import { httpStatus } from '#app/common/helpers/httpstatus'; | |
| import { createHttpError } from '#app/common/utils/http.util'; | |
| import { decideRecaptchaAction } from '#app/common/utils/recaptcha/recaptchaProcessor'; | |
| import { verifyWithGoolge } from '#app/common/utils/recaptcha/verifyWithGoogle'; | |
| const zCaptcha = z | |
| .string() | |
| .nonempty({ message: 'captcha token required!' }) | |
| .min(1); | |
| /** | |
| * Middleware to verify Google reCAPTCHA and determine access level. | |
| * | |
| * @param action - The expected action name (used to validate token's action). | |
| * @returns An Express middleware that validates the captcha and enforces action-based logic. | |
| */ | |
| export function verifyCaptcha(action: string) { | |
| return async (req: Request, res: Response, next: NextFunction) => { | |
| const token = req.body?.captchaToken as string; | |
| if (!token) { | |
| throw createHttpError(httpStatus.BAD_REQUEST, { | |
| code: 'BAD REQUEST', | |
| message: 'captcha token not found', | |
| }); | |
| } | |
| try { | |
| const validationResult = zCaptcha.safeParse(token); | |
| if (!validationResult.success) { | |
| throw createHttpError(httpStatus.BAD_REQUEST, { | |
| code: 'BAD REQUEST', | |
| message: `[recaptcha]: ${fromZodError( | |
| validationResult.error, | |
| ).toString()}`, | |
| }); | |
| } | |
| const verificationResult = await verifyWithGoolge( | |
| token, | |
| req.ip as string, | |
| ); | |
| if (!verificationResult.success) { | |
| throw createHttpError(httpStatus.BAD_REQUEST, { | |
| code: 'BAD REQUEST', | |
| message: 'google captcha verification failed', | |
| details: { | |
| errorCodes: verificationResult['error-codes'], | |
| }, | |
| }); | |
| } | |
| const score = verificationResult.score; | |
| const recievedAction = verificationResult.action; | |
| if (recievedAction !== action) { | |
| throw createHttpError(httpStatus.BAD_REQUEST, { | |
| code: 'BAD REQUEST', | |
| message: 'invalid captcha action!', | |
| }); | |
| } | |
| const { type, method } = decideRecaptchaAction(score as number); | |
| if (type === 'allow') next(); | |
| // !TODO: IMPLEMENT the recaptcha stepUp logic! | |
| if (type === 'stepUp') { | |
| res.sendSuccess( | |
| httpStatus.ACCEPTED, | |
| { | |
| next: { | |
| type: `require_${method}`, | |
| endpoint: 'COMING SOON ! ...', | |
| reason: 'Suspicious behavior detected. Please complete additional verification.', | |
| }, | |
| }, | |
| 'We need to verify your ${act.method} due to unusual activity.', | |
| ); | |
| return; | |
| } | |
| // !TODO: IMPLEMENT the recaptcha manualReview logic! | |
| if (type === 'manualReview') { | |
| res.sendSuccess( | |
| httpStatus.ACCEPTED, | |
| { | |
| next: { | |
| type: `require_${method}`, | |
| endpoint: 'COMING SOON ! ...', | |
| reason: 'Your request is pending manual review by an administrator.', | |
| }, | |
| }, | |
| "Your request is being reviewed by our team. We'll notify you soon.", | |
| ); | |
| return; | |
| } | |
| } catch (error) { | |
| next(error); | |
| } | |
| }; | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { z } from 'zod'; | |
| import { fromZodError } from 'zod-validation-error'; | |
| import { logger } from '#app/common/utils/logger.util'; | |
| import { CONFIG } from '#app/config'; | |
| import { isBlocked, recordFailure, resetFailures } from './recaptchaFraud'; | |
| /** | |
| * Possible error codes returned by Google reCAPTCHA. | |
| */ | |
| const zRecaptchaErrorCodes = z.enum([ | |
| 'missing-input-secret', | |
| 'invalid-input-secret', | |
| 'missing-input-response', | |
| 'invalid-input-response', | |
| 'bad-request', | |
| 'timeout-or-duplicate', | |
| 'blocked-ip', | |
| ]); | |
| /** | |
| * Schema representing the expected response from Google's reCAPTCHA API. | |
| */ | |
| const zGoogleCaptchaResponse = z.object({ | |
| success: z.boolean(), | |
| action: z.string().optional(), | |
| score: z.number().optional(), | |
| hostname: z.string().optional(), | |
| 'error-codes': z.array(zRecaptchaErrorCodes).optional(), | |
| }); | |
| type GoogleCaptchaResponse = z.infer<typeof zGoogleCaptchaResponse>; | |
| /** | |
| * Verifies a reCAPTCHA token with Google's API. | |
| * | |
| * @param token - The reCAPTCHA token received from the client. | |
| * @param remoteip - The user's IP address to pass to the verification request. | |
| * @returns A promise that resolves to a structured object containing reCAPTCHA verification results. | |
| */ | |
| export async function verifyWithGoolge( | |
| token: string, | |
| remoteip: string, | |
| ): Promise<GoogleCaptchaResponse> { | |
| // Quick fail if this IP is already blocked | |
| if (await isBlocked(remoteip)) { | |
| logger.error(`[recaptcha][fraud] request from blocked IP ${remoteip}`); | |
| return { | |
| success: false, | |
| 'error-codes': ['blocked-ip'], | |
| }; | |
| } | |
| const params = new URLSearchParams({ | |
| secret: CONFIG.RECAPTCHA.SECRET_KEY, | |
| response: token, | |
| remoteip, | |
| }); | |
| let response: unknown; | |
| try { | |
| const res = await fetch( | |
| 'https://www.google.com/recaptcha/api/siteverify', | |
| { | |
| method: 'POST', | |
| body: params, | |
| }, | |
| ); | |
| response = await res.json(); | |
| } catch (error) { | |
| // Treat network errors as failures | |
| recordFailure(remoteip); | |
| logger.error(`[recaptcha] network error: ${error}`); | |
| return { | |
| success: false, | |
| }; | |
| } | |
| const parsedResponse = zGoogleCaptchaResponse.safeParse(response); | |
| if (!parsedResponse.success) { | |
| await recordFailure(remoteip); | |
| logger.error( | |
| `[recaptcha] malformed response ${fromZodError( | |
| parsedResponse.error, | |
| ).toString()}`, | |
| ); | |
| return { | |
| success: false, | |
| 'error-codes': parsedResponse.data?.['error-codes'], | |
| }; | |
| } | |
| if (!parsedResponse.data.success) { | |
| await recordFailure(remoteip); | |
| logger.warn( | |
| '[recaptcha] verification failed:', | |
| parsedResponse.data['error-codes'], | |
| ); | |
| } | |
| // Success → reset failure count | |
| if (parsedResponse.data.success) { | |
| await resetFailures(remoteip); | |
| } | |
| return { | |
| success: parsedResponse.data.success, | |
| ...(parsedResponse.data.success | |
| ? { | |
| score: parsedResponse.data.score, | |
| action: parsedResponse.data.action, | |
| hostname: parsedResponse.data.hostname, | |
| } | |
| : { | |
| 'error-codes': parsedResponse.data?.['error-codes'] | |
| ? parsedResponse.data['error-codes'] | |
| : undefined, | |
| }), | |
| }; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment