Skip to content

📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!

migrate captcha to proof-of-work mechanism

Blue Moused58938cffbff
diff --git a/backend/apps/cloud/src/captcha/captcha.controller.ts b/backend/apps/cloud/src/captcha/captcha.controller.ts
index 1235e2fa9..8077ec813 100644
--- a/backend/apps/cloud/src/captcha/captcha.controller.ts
+++ b/backend/apps/cloud/src/captcha/captcha.controller.ts
@@ -18,7 +18,7 @@ import { BotDetectionGuard } from '../common/guards/bot-detection.guard'
import { BotDetection } from '../common/decorators/bot-detection.decorator'
import { VerifyDto } from './dtos/manual.dto'
import { ValidateDto } from './dtos/validate.dto'
-import { GenerateDto, DEFAULT_THEME } from './dtos/generate.dto'
+import { GenerateDto } from './dtos/generate.dto'
dayjs.extend(utc)
@@ -39,11 +39,11 @@ export class CaptchaController {
async generateCaptcha(@Body() generateDTO: GenerateDto): Promise<any> {
this.logger.log({ generateDTO }, 'POST /captcha/generate')
- const { theme = DEFAULT_THEME, pid } = generateDTO
+ const { pid } = generateDTO
await this.captchaService.validatePIDForCAPTCHA(pid)
- return this.captchaService.generateCaptcha(theme)
+ return this.captchaService.generateChallenge(pid)
}
@Post('/verify')
@@ -55,10 +55,9 @@ export class CaptchaController {
@Headers() headers,
@Ip() reqIP,
): Promise<any> {
- this.logger.log({ manualDTO: verifyDto }, 'POST /captcha/verify')
- // todo: add origin checks
+ this.logger.log({ verifyDto }, 'POST /captcha/verify')
- const { code, hash, pid } = verifyDto
+ const { challenge, nonce, solution, pid } = verifyDto
await this.captchaService.validatePIDForCAPTCHA(pid)
@@ -66,24 +65,36 @@ export class CaptchaController {
// For dummy (test) PIDs
if (pid === DUMMY_PIDS.ALWAYS_PASS) {
- const dummyToken = this.captchaService.generateDummyToken()
+ const dummyToken = await this.captchaService.generateDummyToken()
return {
success: true,
token: dummyToken,
timestamp,
- hash,
+ challenge,
pid,
}
}
- if (
- pid === DUMMY_PIDS.ALWAYS_FAIL ||
- !this.captchaService.verifyCaptcha(code, hash)
- ) {
- throw new ForbiddenException('Incorrect captcha')
+ if (pid === DUMMY_PIDS.ALWAYS_FAIL) {
+ throw new ForbiddenException('PoW verification failed')
}
- const token = await this.captchaService.generateToken(pid, hash, timestamp)
+ // Verify the PoW solution
+ const isValid = await this.captchaService.verifyPoW(
+ challenge,
+ nonce,
+ solution,
+ )
+
+ if (!isValid) {
+ throw new ForbiddenException('PoW verification failed')
+ }
+
+ const token = await this.captchaService.generateToken(
+ pid,
+ challenge,
+ timestamp,
+ )
const ip = getIPFromHeaders(headers) || reqIP || ''
@@ -99,7 +110,7 @@ export class CaptchaController {
success: true,
token,
timestamp,
- hash,
+ challenge,
pid,
}
}
diff --git a/backend/apps/cloud/src/captcha/captcha.service.ts b/backend/apps/cloud/src/captcha/captcha.service.ts
index 00c0832e4..9383fae85 100644
--- a/backend/apps/cloud/src/captcha/captcha.service.ts
+++ b/backend/apps/cloud/src/captcha/captcha.service.ts
@@ -1,7 +1,6 @@
import { Injectable, BadRequestException } from '@nestjs/common'
-import svgCaptcha from 'svg-captcha'
+import * as crypto from 'crypto'
import CryptoJS from 'crypto-js'
-import _toLower from 'lodash/toLower'
import { UAParser } from '@ua-parser-js/pro-business'
import _values from 'lodash/values'
import _includes from 'lodash/includes'
@@ -14,16 +13,21 @@ import {
redis,
isValidPID,
getRedisCaptchaKey,
- CAPTCHA_SALT,
CAPTCHA_TOKEN_LIFETIME,
} from '../common/constants'
-import { getGeoDetails, hash } from '../common/utils'
-import { GeneratedCaptcha } from './interfaces/generated-captcha'
+import { getGeoDetails } from '../common/utils'
+import { GeneratedChallenge } from './interfaces/generated-captcha'
import { captchaTransformer } from './utils/transformers'
import { clickhouse } from '../common/integrations/clickhouse'
dayjs.extend(utc)
+// Default difficulty: number of leading hex zeros required (4 = ~65k iterations avg)
+export const DEFAULT_POW_DIFFICULTY = 4
+
+// Challenge TTL in seconds (5 minutes)
+const CHALLENGE_TTL = 300
+
export const DUMMY_PIDS = {
ALWAYS_PASS: 'AP00000000000',
ALWAYS_FAIL: 'FAIL000000000',
@@ -48,7 +52,9 @@ const decryptString = (text: string, key: string): string => {
return bytes.toString(CryptoJS.enc.Utf8)
}
-const captchaString = (text: string) => `${_toLower(text)}${CAPTCHA_SALT}`
+const getChallengeCacheKey = (challenge: string): string => {
+ return `pow_challenge:${challenge}`
+}
const isTokenAlreadyUsed = async (token: string): Promise<boolean> => {
const captchaKey = getRedisCaptchaKey(token)
@@ -58,7 +64,7 @@ const isTokenAlreadyUsed = async (token: string): Promise<boolean> => {
return true
}
- await redis.set(captchaKey, '1', 'EX', CAPTCHA_TOKEN_LIFETIME)
+ await redis.set(captchaKey, '1', 'EX', CAPTCHA_TOKEN_LIFETIME / 1000)
return false
}
@@ -81,6 +87,18 @@ export class CaptchaService {
return !!project.captchaSecretKey
}
+ // Get project's configured PoW difficulty, or default
+ async _getProjectDifficulty(pid: string): Promise<number> {
+ if (isDummyPID(pid)) {
+ return DEFAULT_POW_DIFFICULTY
+ }
+
+ const project = await this.projectService.getRedisProject(pid)
+
+ // Use project's configured difficulty if available, otherwise default
+ return project?.captchaDifficulty || DEFAULT_POW_DIFFICULTY
+ }
+
// validates pid, checks if captcha is enabled and throws an error otherwise
async validatePIDForCAPTCHA(pid: string) {
if (isDummyPID(pid)) {
@@ -144,7 +162,7 @@ export class CaptchaService {
)
}
- async generateToken(pid: string, captchaHash: string, timestamp: number) {
+ async generateToken(pid: string, challenge: string, timestamp: number) {
if (isDummyPID(pid)) {
return this.generateDummyToken()
}
@@ -160,7 +178,7 @@ export class CaptchaService {
}
const token = {
- hash: captchaHash,
+ challenge,
timestamp,
pid,
}
@@ -181,7 +199,8 @@ export class CaptchaService {
if (secretKey === DUMMY_SECRETS.ALWAYS_PASS) {
return {
- hash: 'DUMMY_HASH00000111112222233333444445555566666777778888899999',
+ challenge:
+ 'DUMMY_CHALLENGE00000111112222233333444445555566666777778888899999',
timestamp: dayjs().unix() * 1000,
pid: DUMMY_PIDS.ALWAYS_PASS,
}
@@ -207,34 +226,66 @@ export class CaptchaService {
return parsed
}
- hashCaptcha(text: string): string {
- return hash(captchaString(text))
+ // Generate SHA-256 hash of the input
+ sha256(input: string): string {
+ return crypto.createHash('sha256').update(input).digest('hex')
}
- async generateCaptcha(theme: string): Promise<GeneratedCaptcha> {
- const themeParams =
- theme === 'light'
- ? {}
- : {
- background: '#1f2937',
- color: true,
- }
-
- const captcha = svgCaptcha.create({
- size: 6,
- ignoreChars: '0o1iIl',
- noise: 2,
- ...themeParams,
- })
- const captchaHash = this.hashCaptcha(_toLower(captcha.text))
+ // Check if hash has required number of leading zeros
+ hasValidPrefix(hash: string, difficulty: number): boolean {
+ const prefix = '0'.repeat(difficulty)
+ return hash.startsWith(prefix)
+ }
+
+ // Generate a PoW challenge
+ async generateChallenge(pid: string): Promise<GeneratedChallenge> {
+ const difficulty = await this._getProjectDifficulty(pid)
+
+ // Generate a random challenge string
+ const challenge = crypto.randomBytes(32).toString('hex')
+
+ // Store challenge in Redis with TTL to prevent replay attacks
+ const cacheKey = getChallengeCacheKey(challenge)
+ await redis.set(cacheKey, difficulty.toString(), 'EX', CHALLENGE_TTL)
return {
- data: captcha.data,
- hash: captchaHash,
+ challenge,
+ difficulty,
}
}
- verifyCaptcha(text: string, captchaHash: string) {
- return captchaHash === this.hashCaptcha(text)
+ // Verify a PoW solution
+ async verifyPoW(
+ challenge: string,
+ nonce: number,
+ solution: string,
+ ): Promise<boolean> {
+ // Check if challenge exists and hasn't been used
+ const cacheKey = getChallengeCacheKey(challenge)
+ const storedDifficulty = await redis.get(cacheKey)
+
+ if (!storedDifficulty) {
+ throw new BadRequestException('Invalid or expired challenge')
+ }
+
+ const difficulty = parseInt(storedDifficulty, 10)
+
+ // Compute the expected hash
+ const input = `${challenge}:${nonce}`
+ const computedHash = this.sha256(input)
+
+ // Verify the solution matches and has required prefix
+ if (computedHash !== solution) {
+ return false
+ }
+
+ if (!this.hasValidPrefix(computedHash, difficulty)) {
+ return false
+ }
+
+ // Mark challenge as used by deleting it
+ await redis.del(cacheKey)
+
+ return true
}
}
diff --git a/backend/apps/cloud/src/captcha/dtos/generate.dto.ts b/backend/apps/cloud/src/captcha/dtos/generate.dto.ts
index 17b7720aa..7a8e4869f 100644
--- a/backend/apps/cloud/src/captcha/dtos/generate.dto.ts
+++ b/backend/apps/cloud/src/captcha/dtos/generate.dto.ts
@@ -1,7 +1,5 @@
import { ApiProperty } from '@nestjs/swagger'
-import { IsOptional, IsNotEmpty, IsString } from 'class-validator'
-
-export const DEFAULT_THEME = 'light'
+import { IsNotEmpty, IsString } from 'class-validator'
export class GenerateDto {
@ApiProperty({
@@ -12,12 +10,4 @@ export class GenerateDto {
@IsNotEmpty()
@IsString()
pid: string
-
- @ApiProperty({
- default: DEFAULT_THEME,
- required: false,
- description: 'Captcha theme',
- })
- @IsOptional()
- theme?: string
}
diff --git a/backend/apps/cloud/src/captcha/dtos/manual.dto.ts b/backend/apps/cloud/src/captcha/dtos/manual.dto.ts
index 7c7c1d206..e50b2b3ba 100644
--- a/backend/apps/cloud/src/captcha/dtos/manual.dto.ts
+++ b/backend/apps/cloud/src/captcha/dtos/manual.dto.ts
@@ -1,5 +1,5 @@
import { ApiProperty } from '@nestjs/swagger'
-import { IsNotEmpty, IsString } from 'class-validator'
+import { IsNotEmpty, IsString, IsNumber } from 'class-validator'
export class VerifyDto {
@ApiProperty({
@@ -13,17 +13,25 @@ export class VerifyDto {
@ApiProperty({
required: true,
+ description: 'The challenge string received from /generate',
})
@IsNotEmpty()
@IsString()
- hash: string
+ challenge: string
@ApiProperty({
required: true,
- example: '4vic2',
- description: 'Captcha code',
+ description: 'The nonce that solves the PoW challenge',
+ })
+ @IsNotEmpty()
+ @IsNumber()
+ nonce: number
+
+ @ApiProperty({
+ required: true,
+ description: 'The resulting hash (SHA-256 of challenge + nonce)',
})
@IsNotEmpty()
@IsString()
- code: string
+ solution: string
}
diff --git a/backend/apps/cloud/src/captcha/interfaces/generated-captcha.ts b/backend/apps/cloud/src/captcha/interfaces/generated-captcha.ts
index 1057935f0..fa5780aa3 100644
--- a/backend/apps/cloud/src/captcha/interfaces/generated-captcha.ts
+++ b/backend/apps/cloud/src/captcha/interfaces/generated-captcha.ts
@@ -1,4 +1,4 @@
-export interface GeneratedCaptcha {
- data: string
- hash: string
+export interface GeneratedChallenge {
+ challenge: string
+ difficulty: number
}