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!

CAPTCHA support for Swetrix CE

Blue Mouse39e346e8b840
diff --git a/backend/apps/community/src/app.module.ts b/backend/apps/community/src/app.module.ts
index af68678bd..05526d7f8 100644
--- a/backend/apps/community/src/app.module.ts
+++ b/backend/apps/community/src/app.module.ts
@@ -12,6 +12,7 @@ import { TaskManagerModule } from './task-manager/task-manager.module'
import { PingModule } from './ping/ping.module'
import { GoalModule } from './goal/goal.module'
import { FeatureFlagModule } from './feature-flag/feature-flag.module'
+import { CaptchaModule } from './captcha/captcha.module'
import { getI18nConfig } from './configs'
import { AuthModule } from './auth/auth.module'
import { AppController } from './app.controller'
@@ -68,6 +69,7 @@ const modules = [
PingModule,
GoalModule,
FeatureFlagModule,
+ CaptchaModule,
AuthModule,
]
diff --git a/backend/apps/community/src/captcha/captcha.controller.ts b/backend/apps/community/src/captcha/captcha.controller.ts
new file mode 100644
index 000000000..b6f64975d
--- /dev/null
+++ b/backend/apps/community/src/captcha/captcha.controller.ts
@@ -0,0 +1,183 @@
+import {
+ Controller,
+ Post,
+ Body,
+ UseGuards,
+ ForbiddenException,
+ Headers,
+ Ip,
+ HttpCode,
+} from '@nestjs/common'
+import dayjs from 'dayjs'
+import utc from 'dayjs/plugin/utc'
+
+import { AppLoggerService } from '../logger/logger.service'
+import { getIPFromHeaders, checkRateLimit } from '../common/utils'
+import { CaptchaService, DUMMY_PIDS } from './captcha.service'
+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 } from './dtos/generate.dto'
+
+dayjs.extend(utc)
+
+// Rate limit: 30 requests per IP per minute for challenge generation
+const CAPTCHA_GENERATE_RL_REQUESTS_IP = 30
+const CAPTCHA_GENERATE_RL_TIMEOUT = 60 // 1 minute
+
+// Rate limit: 100 requests per project per minute for challenge generation
+const CAPTCHA_GENERATE_RL_REQUESTS_PID = 100
+
+// Rate limit: verification attempts per IP per minute
+const CAPTCHA_VERIFY_RL_REQUESTS_IP = 60
+const CAPTCHA_VERIFY_RL_TIMEOUT = 60 // 1 minute
+
+// Rate limit: token validations per IP per minute
+const CAPTCHA_VALIDATE_RL_REQUESTS_IP = 120
+const CAPTCHA_VALIDATE_RL_TIMEOUT = 60 // 1 minute
+
+@Controller({
+ version: '1',
+ path: 'captcha',
+})
+export class CaptchaController {
+ constructor(
+ private readonly captchaService: CaptchaService,
+ private readonly logger: AppLoggerService,
+ ) {}
+
+ @Post('/generate')
+ @HttpCode(200)
+ @UseGuards(BotDetectionGuard)
+ @BotDetection()
+ async generateCaptcha(
+ @Body() generateDTO: GenerateDto,
+ @Headers() headers,
+ @Ip() reqIP,
+ ): Promise<any> {
+ const { pid } = generateDTO
+ const ip = getIPFromHeaders(headers) || reqIP || ''
+
+ this.logger.log({ pid }, 'POST /captcha/generate')
+
+ await checkRateLimit(
+ ip,
+ 'captcha-generate',
+ CAPTCHA_GENERATE_RL_REQUESTS_IP,
+ CAPTCHA_GENERATE_RL_TIMEOUT,
+ )
+ await checkRateLimit(
+ pid,
+ 'captcha-generate',
+ CAPTCHA_GENERATE_RL_REQUESTS_PID,
+ CAPTCHA_GENERATE_RL_TIMEOUT,
+ )
+
+ await this.captchaService.validatePIDForCAPTCHA(pid)
+
+ return this.captchaService.generateChallenge(pid)
+ }
+
+ @Post('/verify')
+ @HttpCode(200)
+ @UseGuards(BotDetectionGuard)
+ @BotDetection()
+ async verify(
+ @Body() verifyDto: VerifyDto,
+ @Headers() headers,
+ @Ip() reqIP,
+ ): Promise<any> {
+ const { challenge, nonce, solution, pid } = verifyDto
+
+ this.logger.log({ pid }, 'POST /captcha/verify')
+
+ const ip = getIPFromHeaders(headers) || reqIP || ''
+
+ await checkRateLimit(
+ ip,
+ 'captcha-verify',
+ CAPTCHA_VERIFY_RL_REQUESTS_IP,
+ CAPTCHA_VERIFY_RL_TIMEOUT,
+ )
+
+ await this.captchaService.validatePIDForCAPTCHA(pid)
+
+ const timestamp = dayjs.utc().unix() * 1000
+
+ // For dummy (test) PIDs
+ if (pid === DUMMY_PIDS.ALWAYS_PASS) {
+ const dummyToken = await this.captchaService.generateDummyToken()
+ return {
+ success: true,
+ token: dummyToken,
+ timestamp,
+ challenge,
+ pid,
+ }
+ }
+
+ if (pid === DUMMY_PIDS.ALWAYS_FAIL) {
+ throw new ForbiddenException('PoW verification failed')
+ }
+
+ // Verify the PoW solution
+ const isValid = await this.captchaService.verifyPoW(
+ challenge,
+ nonce,
+ solution,
+ pid,
+ )
+
+ if (!isValid) {
+ throw new ForbiddenException('PoW verification failed')
+ }
+
+ const token = await this.captchaService.generateToken(
+ pid,
+ challenge,
+ timestamp,
+ )
+
+ try {
+ await this.captchaService.logCaptchaPass(pid, headers, timestamp, ip)
+ } catch (reason) {
+ this.logger.error(
+ `[CaptchaController -> verify] Failed to log captcha pass: ${reason}`,
+ )
+ }
+
+ return {
+ success: true,
+ token,
+ timestamp,
+ challenge,
+ pid,
+ }
+ }
+
+ @Post('/validate')
+ @HttpCode(200)
+ async validateToken(
+ @Body() validateDTO: ValidateDto,
+ @Headers() headers,
+ @Ip() reqIP,
+ ): Promise<any> {
+ this.logger.log(validateDTO, 'POST /captcha/validate')
+
+ const { token, secret } = validateDTO
+ const ip = getIPFromHeaders(headers) || reqIP || ''
+
+ await checkRateLimit(
+ ip,
+ 'captcha-validate',
+ CAPTCHA_VALIDATE_RL_REQUESTS_IP,
+ CAPTCHA_VALIDATE_RL_TIMEOUT,
+ )
+
+ return {
+ success: true,
+ data: await this.captchaService.validateToken(token, secret),
+ }
+ }
+}
diff --git a/backend/apps/community/src/captcha/captcha.module.ts b/backend/apps/community/src/captcha/captcha.module.ts
new file mode 100644
index 000000000..5178ef136
--- /dev/null
+++ b/backend/apps/community/src/captcha/captcha.module.ts
@@ -0,0 +1,14 @@
+import { Module } from '@nestjs/common'
+
+import { AppLoggerModule } from '../logger/logger.module'
+import { CaptchaController } from './captcha.controller'
+import { CaptchaService } from './captcha.service'
+import { ProjectModule } from '../project/project.module'
+
+@Module({
+ imports: [AppLoggerModule, ProjectModule],
+ providers: [CaptchaService],
+ exports: [CaptchaService],
+ controllers: [CaptchaController],
+})
+export class CaptchaModule {}
diff --git a/backend/apps/community/src/captcha/captcha.service.ts b/backend/apps/community/src/captcha/captcha.service.ts
new file mode 100644
index 000000000..b824326ed
--- /dev/null
+++ b/backend/apps/community/src/captcha/captcha.service.ts
@@ -0,0 +1,389 @@
+import { Injectable, BadRequestException } from '@nestjs/common'
+import * as crypto from 'crypto'
+import CryptoJS from 'crypto-js'
+import { UAParser } from '@ua-parser-js/pro-business'
+import _values from 'lodash/values'
+import _includes from 'lodash/includes'
+import dayjs from 'dayjs'
+import utc from 'dayjs/plugin/utc'
+
+import { ProjectService } from '../project/project.service'
+import { AppLoggerService } from '../logger/logger.service'
+import {
+ redis,
+ isValidPID,
+ getRedisCaptchaKey,
+ CAPTCHA_TOKEN_LIFETIME,
+} from '../common/constants'
+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)
+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',
+}
+
+const DUMMY_SECRETS = {
+ ALWAYS_PASS: 'PASS000000000000000000',
+ ALWAYS_FAIL: 'FAIL000000000000000000',
+ TOKEN_USED_FAIL: 'USED000000000000000000',
+}
+
+const isDummyPID = (pid: string): boolean => {
+ return _includes(_values(DUMMY_PIDS), pid)
+}
+
+const encryptString = (text: string, key: string): string => {
+ return CryptoJS.Rabbit.encrypt(text, key).toString()
+}
+
+const decryptString = (text: string, key: string): string => {
+ const bytes = CryptoJS.Rabbit.decrypt(text, key)
+ return bytes.toString(CryptoJS.enc.Utf8)
+}
+
+const getChallengeCacheKey = (challenge: string): string => {
+ return `pow_challenge:${challenge}`
+}
+
+const signCaptchaCiphertext = (ciphertext: string, key: string): string => {
+ // NOTE: Encryption alone (CryptoJS.Rabbit) is malleable; we add an HMAC to
+ // prevent token tampering and replay-bypass via ciphertext bitflips.
+ return crypto.createHmac('sha256', key).update(ciphertext).digest('base64url')
+}
+
+const timingSafeEqualString = (a: string, b: string): boolean => {
+ try {
+ const aBuf = Buffer.from(a)
+ const bBuf = Buffer.from(b)
+ if (aBuf.length !== bBuf.length) return false
+ return crypto.timingSafeEqual(aBuf, bBuf)
+ } catch {
+ return false
+ }
+}
+
+const isTokenAlreadyUsed = async (token: string): Promise<boolean> => {
+ const captchaKey = getRedisCaptchaKey(token)
+ const setResult = await redis.set(
+ captchaKey,
+ '1',
+ 'EX',
+ CAPTCHA_TOKEN_LIFETIME / 1000,
+ 'NX',
+ )
+
+ // ioredis returns null when key already exists (i.e. token already used)
+ return setResult === null
+}
+
+@Injectable()
+export class CaptchaService {
+ constructor(
+ private readonly logger: AppLoggerService,
+ private readonly projectService: ProjectService,
+ ) {}
+
+ // checks if captcha is enabled for pid (by checking if captchaSecretKey exists)
+ async _isCaptchaEnabledForPID(pid: string) {
+ const project = await this.projectService.getRedisProject(pid)
+
+ if (!project) {
+ return false
+ }
+
+ 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)) {
+ return
+ }
+
+ if (!isValidPID(pid)) {
+ throw new BadRequestException(
+ 'The provided Project ID (pid) is incorrect',
+ )
+ }
+
+ if (!(await this._isCaptchaEnabledForPID(pid))) {
+ throw new BadRequestException('CAPTCHA is not enabled for this Project')
+ }
+ }
+
+ async logCaptchaPass(
+ pid: string,
+ headers: Record<string, string>,
+ timestamp: number,
+ ip: string,
+ ) {
+ const ua = await UAParser(
+ headers?.['user-agent'],
+ undefined,
+ headers,
+ ).withClientHints()
+ const deviceType = ua.device.type || 'desktop'
+ const browserName = ua.browser.name
+ const osName = ua.os.name
+
+ const { country } = getGeoDetails(ip)
+ const transformed = captchaTransformer(
+ pid,
+ deviceType,
+ browserName,
+ osName,
+ country,
+ timestamp,
+ )
+
+ try {
+ await clickhouse.insert({
+ table: 'captcha',
+ format: 'JSONEachRow',
+ values: [transformed],
+ clickhouse_settings: {
+ async_insert: 1,
+ },
+ })
+ } catch (e) {
+ this.logger.error(`[CaptchaService -> logCaptchaPass] ${e}`)
+ }
+ }
+
+ async generateDummyToken() {
+ return encryptString(
+ 'DUMMY_TOKEN00000111112222233333444445555566666777778888899999',
+ DUMMY_SECRETS.ALWAYS_PASS,
+ )
+ }
+
+ async generateToken(pid: string, challenge: string, timestamp: number) {
+ if (isDummyPID(pid)) {
+ return this.generateDummyToken()
+ }
+
+ const project = await this.projectService.getRedisProject(pid)
+
+ if (!project) {
+ throw new BadRequestException('Project not found')
+ }
+
+ if (!project.captchaSecretKey) {
+ throw new BadRequestException('No secret key generated for this project')
+ }
+
+ const token = {
+ challenge,
+ timestamp,
+ pid,
+ }
+
+ const ciphertext = encryptString(
+ JSON.stringify(token),
+ project.captchaSecretKey,
+ )
+ const signature = signCaptchaCiphertext(
+ ciphertext,
+ project.captchaSecretKey,
+ )
+
+ // Token format: <ciphertext>.<hmac_sha256(ciphertext)>
+ return `${ciphertext}.${signature}`
+ }
+
+ async validateToken(token: string, secretKey: string) {
+ let parsed
+
+ if (secretKey === DUMMY_SECRETS.ALWAYS_FAIL) {
+ throw new BadRequestException('Could not decrypt token')
+ }
+
+ if (secretKey === DUMMY_SECRETS.TOKEN_USED_FAIL) {
+ throw new BadRequestException('Token already used')
+ }
+
+ if (secretKey === DUMMY_SECRETS.ALWAYS_PASS) {
+ return {
+ challenge:
+ 'DUMMY_CHALLENGE00000111112222233333444445555566666777778888899999',
+ timestamp: dayjs().unix() * 1000,
+ pid: DUMMY_PIDS.ALWAYS_PASS,
+ }
+ }
+
+ try {
+ const parts = token.split('.')
+
+ if (parts.length !== 2) {
+ throw new BadRequestException('Invalid token format')
+ }
+
+ const [ciphertext, providedSignature] = parts
+ const expectedSignature = signCaptchaCiphertext(ciphertext, secretKey)
+
+ if (!timingSafeEqualString(providedSignature, expectedSignature)) {
+ throw new BadRequestException('Invalid token signature')
+ }
+
+ const decrypted = decryptString(ciphertext, secretKey)
+ parsed = JSON.parse(decrypted)
+ } catch {
+ throw new BadRequestException('Could not decrypt token')
+ }
+
+ if (
+ !parsed ||
+ typeof parsed !== 'object' ||
+ typeof parsed.pid !== 'string' ||
+ typeof parsed.challenge !== 'string' ||
+ typeof parsed.timestamp !== 'number' ||
+ !Number.isFinite(parsed.timestamp)
+ ) {
+ throw new BadRequestException('Invalid token payload')
+ }
+
+ // Guard against obviously invalid pid values to reduce accidental misuse.
+ if (!isDummyPID(parsed.pid) && !isValidPID(parsed.pid)) {
+ throw new BadRequestException('Invalid token payload')
+ }
+
+ if (dayjs().unix() * 1000 - parsed.timestamp > CAPTCHA_TOKEN_LIFETIME) {
+ throw new BadRequestException('Token expired')
+ }
+
+ const tokenUsed = await isTokenAlreadyUsed(token)
+
+ if (tokenUsed) {
+ throw new BadRequestException('Token already used')
+ }
+
+ return parsed
+ }
+
+ // Generate SHA-256 hash of the input
+ sha256(input: string): string {
+ return crypto.createHash('sha256').update(input).digest('hex')
+ }
+
+ // 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
+ // Include pid to prevent cross-project difficulty bypass
+ const cacheKey = getChallengeCacheKey(challenge)
+ const challengeData = JSON.stringify({ pid, difficulty })
+ await redis.set(cacheKey, challengeData, 'EX', CHALLENGE_TTL)
+
+ return {
+ challenge,
+ difficulty,
+ }
+ }
+
+ // Verify a PoW solution
+ async verifyPoW(
+ challenge: string,
+ nonce: number,
+ solution: string,
+ pid: string,
+ ): Promise<boolean> {
+ // Check if challenge exists and hasn't been used
+ const cacheKey = getChallengeCacheKey(challenge)
+ const storedData = await redis.get(cacheKey)
+
+ if (!storedData) {
+ throw new BadRequestException('Invalid or expired challenge')
+ }
+
+ let difficulty: number
+ let storedPid: string | undefined
+
+ // Parse stored data - support both old string format (difficulty only)
+ // and new JSON format (pid + difficulty) for backward compatibility
+ try {
+ const parsed = JSON.parse(storedData)
+ if (
+ typeof parsed === 'object' &&
+ parsed !== null &&
+ 'difficulty' in parsed
+ ) {
+ difficulty = parsed.difficulty
+ storedPid = parsed.pid
+ } else {
+ // Fallback: treat as raw difficulty number
+ difficulty = parseInt(storedData, 10)
+ }
+ } catch {
+ // Old format: just the difficulty as a string
+ difficulty = parseInt(storedData, 10)
+ }
+
+ // Validate difficulty to prevent bypass via NaN or invalid values
+ if (
+ typeof difficulty !== 'number' ||
+ !Number.isFinite(difficulty) ||
+ difficulty < 1 ||
+ difficulty > 6
+ ) {
+ throw new BadRequestException('Invalid challenge difficulty')
+ }
+
+ // If the challenge was bound to a specific project, verify it matches
+ if (storedPid !== undefined && storedPid !== pid) {
+ throw new BadRequestException(
+ 'Challenge was issued for a different project',
+ )
+ }
+
+ // 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/community/src/captcha/dtos/generate.dto.ts b/backend/apps/community/src/captcha/dtos/generate.dto.ts
new file mode 100644
index 000000000..7a8e4869f
--- /dev/null
+++ b/backend/apps/community/src/captcha/dtos/generate.dto.ts
@@ -0,0 +1,13 @@
+import { ApiProperty } from '@nestjs/swagger'
+import { IsNotEmpty, IsString } from 'class-validator'
+
+export class GenerateDto {
+ @ApiProperty({
+ example: 'aUn1quEid-3',
+ required: true,
+ description: 'A unique project ID',
+ })
+ @IsNotEmpty()
+ @IsString()
+ pid: string
+}
diff --git a/backend/apps/community/src/captcha/dtos/manual.dto.ts b/backend/apps/community/src/captcha/dtos/manual.dto.ts
new file mode 100644
index 000000000..e50b2b3ba
--- /dev/null
+++ b/backend/apps/community/src/captcha/dtos/manual.dto.ts
@@ -0,0 +1,37 @@
+import { ApiProperty } from '@nestjs/swagger'
+import { IsNotEmpty, IsString, IsNumber } from 'class-validator'
+
+export class VerifyDto {
+ @ApiProperty({
+ example: 'aUn1quEid-3',
+ required: true,
+ description: 'A unique project ID',
+ })
+ @IsNotEmpty()
+ @IsString()
+ pid: string
+
+ @ApiProperty({
+ required: true,
+ description: 'The challenge string received from /generate',
+ })
+ @IsNotEmpty()
+ @IsString()
+ challenge: string
+
+ @ApiProperty({
+ required: true,
+ 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()
+ solution: string
+}
diff --git a/backend/apps/community/src/captcha/dtos/validate.dto.ts b/backend/apps/community/src/captcha/dtos/validate.dto.ts
new file mode 100644
index 000000000..7652c2100
--- /dev/null
+++ b/backend/apps/community/src/captcha/dtos/validate.dto.ts
@@ -0,0 +1,20 @@
+import { ApiProperty } from '@nestjs/swagger'
+import { IsNotEmpty, IsString } from 'class-validator'
+
+export class ValidateDto {
+ @ApiProperty({
+ required: true,
+ description: 'Catpcha pass token',
+ })
+ @IsNotEmpty()
+ @IsString()
+ token: string
+
+ @ApiProperty({
+ required: true,
+ description: 'Secret API key',
+ })
+ @IsNotEmpty()
+ @IsString()
+ secret: string
+}
diff --git a/backend/apps/community/src/captcha/interfaces/generated-captcha.ts b/backend/apps/community/src/captcha/interfaces/generated-captcha.ts
new file mode 100644
index 000000000..fa5780aa3
--- /dev/null
+++ b/backend/apps/community/src/captcha/interfaces/generated-captcha.ts
@@ -0,0 +1,4 @@
+export interface GeneratedChallenge {
+ challenge: string
+ difficulty: number
+}
diff --git a/backend/apps/community/src/captcha/utils/transformers.ts b/backend/apps/community/src/captcha/utils/transformers.ts
new file mode 100644
index 000000000..3a0d21d43
--- /dev/null
+++ b/backend/apps/community/src/captcha/utils/transformers.ts
@@ -0,0 +1,22 @@
+import dayjs from 'dayjs'
+import utc from 'dayjs/plugin/utc'
+
+dayjs.extend(utc)
+
+export const captchaTransformer = (
+ pid: string,
+ dv: string | null,
+ br: string | null,
+ os: string | null,
+ cc: string | null,
+ timestamp: number,
+) => {
+ return {
+ pid,
+ dv: dv || null,
+ br: br || null,
+ os: os || null,
+ cc: cc || null,
+ created: dayjs.utc(timestamp).format('YYYY-MM-DD HH:mm:ss'),
+ }
+}
diff --git a/backend/apps/community/src/common/constants.ts b/backend/apps/community/src/common/constants.ts
index 7d937d399..6bd927ff2 100644
--- a/backend/apps/community/src/common/constants.ts
+++ b/backend/apps/community/src/common/constants.ts
@@ -1,5 +1,6 @@
import Redis from 'ioredis'
import _toNumber from 'lodash/toNumber'
+import crypto from 'crypto'
import 'dotenv/config'
import { deriveKey } from './utils'
@@ -14,6 +15,23 @@ const redis = new Redis(
},
)
+// Returns a 32-character hash of the provided string
+const hash = (content: string): string => {
+ return crypto
+ .createHash('sha256')
+ .update(content)
+ .digest('hex')
+ .substring(0, 32)
+}
+
+// CAPTCHA related constants
+const CAPTCHA_TOKEN_LIFETIME = 300 * 1000 // milliseconds (5 minutes)
+const CAPTCHA_SECRET_KEY_LENGTH = 50
+const CAPTCHA_COLUMNS = ['cc', 'br', 'os', 'dv']
+
+// redis keys for captcha
+const getRedisCaptchaKey = (token: string) => `captcha_${hash(token)}`
+
export const JWT_ACCESS_TOKEN_SECRET = deriveKey('access-token')
export const JWT_REFRESH_TOKEN_SECRET = deriveKey('refresh-token')
@@ -125,4 +143,9 @@ export {
OIDC_ENABLED,
OIDC_ONLY_AUTH,
REDIS_OIDC_SESSION_KEY,
+ // CAPTCHA
+ getRedisCaptchaKey,
+ CAPTCHA_TOKEN_LIFETIME,
+ CAPTCHA_SECRET_KEY_LENGTH,
+ CAPTCHA_COLUMNS,
}
diff --git a/backend/apps/community/src/common/decorators/bot-detection.decorator.ts b/backend/apps/community/src/common/decorators/bot-detection.decorator.ts
new file mode 100644
index 000000000..f3be8c233
--- /dev/null
+++ b/backend/apps/community/src/common/decorators/bot-detection.decorator.ts
@@ -0,0 +1,4 @@
+import { SetMetadata } from '@nestjs/common'
+
+export const IS_BOT_DETECTION_ENABLED = 'isBotDetectionEnabled'
+export const BotDetection = () => SetMetadata(IS_BOT_DETECTION_ENABLED, true)
diff --git a/backend/apps/community/src/common/guards/bot-detection.guard.ts b/backend/apps/community/src/common/guards/bot-detection.guard.ts
new file mode 100644
index 000000000..7af8ccaf4
--- /dev/null
+++ b/backend/apps/community/src/common/guards/bot-detection.guard.ts
@@ -0,0 +1,34 @@
+import {
+ CanActivate,
+ ExecutionContext,
+ ForbiddenException,
+ Injectable,
+} from '@nestjs/common'
+import { Reflector } from '@nestjs/core'
+import { isbot } from 'isbot'
+import { IS_BOT_DETECTION_ENABLED } from '../decorators/bot-detection.decorator'
+
+@Injectable()
+export class BotDetectionGuard implements CanActivate {
+ constructor(private readonly reflector: Reflector) {}
+
+ canActivate(context: ExecutionContext): boolean {
+ const enabled = this.reflector.getAllAndOverride<boolean>(
+ IS_BOT_DETECTION_ENABLED,
+ [context.getHandler(), context.getClass()],
+ )
+
+ if (!enabled) {
+ return true
+ }
+
+ const { headers } = context.switchToHttp().getRequest()
+ const userAgent = String(headers?.['user-agent'] ?? '')
+
+ if (isbot(userAgent)) {
+ throw new ForbiddenException('Bot traffic is ignored')
+ }
+
+ return true
+ }
+}
diff --git a/backend/apps/community/src/project/entity/project.entity.ts b/backend/apps/community/src/project/entity/project.entity.ts
index 20abbf82d..89bd58471 100644
--- a/backend/apps/community/src/project/entity/project.entity.ts
+++ b/backend/apps/community/src/project/entity/project.entity.ts
@@ -18,6 +18,10 @@ export class Project {
adminId: string | null
// Optional website URL - used to display favicon and construct page links
websiteUrl: string | null
+ // CAPTCHA fields
+ isCaptchaProject: boolean
+ captchaSecretKey?: string
+ captchaDifficulty?: number
}
export enum Role {
diff --git a/backend/apps/community/src/project/project.service.ts b/backend/apps/community/src/project/project.service.ts
index c79bf0c23..b8d679c0a 100644
--- a/backend/apps/community/src/project/project.service.ts
+++ b/backend/apps/community/src/project/project.service.ts
@@ -374,6 +374,10 @@ export class ProjectService {
updProject.public = Number(updProject.public)
updProject.isPasswordProtected = Number(updProject.isPasswordProtected)
+ if (updProject.isCaptchaProject !== undefined) {
+ updProject.isCaptchaProject = Number(updProject.isCaptchaProject)
+ }
+
if (!_isNull(updProject.origins)) {
updProject.origins = _isString(updProject.origins)
? updProject.origins
@@ -400,6 +404,7 @@ export class ProjectService {
updProject.active = Boolean(updProject.active)
updProject.public = Boolean(updProject.public)
updProject.isPasswordProtected = Boolean(updProject.isPasswordProtected)
+ updProject.isCaptchaProject = Boolean(updProject.isCaptchaProject)
updProject.origins = _isEmpty(updProject.origins)
? []
diff --git a/backend/migrations/clickhouse/initialise_selfhosted.js b/backend/migrations/clickhouse/initialise_selfhosted.js
index 487b03b5f..0596e00f5 100644
--- a/backend/migrations/clickhouse/initialise_selfhosted.js
+++ b/backend/migrations/clickhouse/initialise_selfhosted.js
@@ -32,6 +32,9 @@ const CLICKHOUSE_INIT_QUERIES = [
passwordHash Nullable(String) CODEC(ZSTD(3)),
adminId Nullable(String) CODEC(ZSTD(3)),
websiteUrl Nullable(String) CODEC(ZSTD(3)),
+ isCaptchaProject Int8 DEFAULT 0,
+ captchaSecretKey Nullable(String) CODEC(ZSTD(3)),
+ captchaDifficulty UInt8 DEFAULT 4,
created DateTime CODEC(Delta(4), LZ4)
)
ENGINE = MergeTree()
diff --git a/backend/migrations/clickhouse/selfhosted_2026_01_02_captcha.js b/backend/migrations/clickhouse/selfhosted_2026_01_02_captcha.js
new file mode 100644
index 000000000..586ea290c
--- /dev/null
+++ b/backend/migrations/clickhouse/selfhosted_2026_01_02_captcha.js
@@ -0,0 +1,25 @@
+const { queriesRunner, dbName } = require('./setup')
+
+const queries = [
+ // Add CAPTCHA fields to project table
+ `ALTER TABLE ${dbName}.project ADD COLUMN IF NOT EXISTS isCaptchaProject Int8 DEFAULT 0;`,
+ `ALTER TABLE ${dbName}.project ADD COLUMN IF NOT EXISTS captchaSecretKey Nullable(String) CODEC(ZSTD(3));`,
+ `ALTER TABLE ${dbName}.project ADD COLUMN IF NOT EXISTS captchaDifficulty UInt8 DEFAULT 4;`,
+
+ // Create CAPTCHA analytics table (same structure as in initialise_database.js)
+ `CREATE TABLE IF NOT EXISTS ${dbName}.captcha
+ (
+ pid FixedString(12),
+ dv LowCardinality(Nullable(String)),
+ br LowCardinality(Nullable(String)),
+ os Nullable(String) CODEC(ZSTD(3)),
+ cc Nullable(FixedString(2)),
+ manuallyPassed UInt8,
+ created DateTime('UTC') CODEC(Delta(4), LZ4)
+ )
+ ENGINE = MergeTree()
+ PARTITION BY toYYYYMM(created)
+ ORDER BY (pid, created);`,
+]
+
+queriesRunner(queries)
diff --git a/web/app/lib/constants/index.ts b/web/app/lib/constants/index.ts
index b1f05f76c..e96017bcb 100644
--- a/web/app/lib/constants/index.ts
+++ b/web/app/lib/constants/index.ts
@@ -381,13 +381,13 @@ export const FUNNELS_PERIOD_PAIRS = ['1h', '1d', '7d', '4w', '3M', '12M', 'all',
const SELFHOSTED_PROJECT_TABS = {
traffic: 'traffic',
performance: 'performance',
- profiles: 'profiles',
funnels: 'funnels',
+ profiles: 'profiles',
sessions: 'sessions',
errors: 'errors',
goals: 'goals',
- experiments: 'experiments',
featureFlags: 'featureFlags',
+ captcha: 'captcha',
} as const
const PRODUCTION_PROJECT_TABS = {
diff --git a/web/app/pages/Project/View/ViewProject.tsx b/web/app/pages/Project/View/ViewProject.tsx
index 6a55e615a..b22f0f9ca 100644
--- a/web/app/pages/Project/View/ViewProject.tsx
+++ b/web/app/pages/Project/View/ViewProject.tsx
@@ -560,6 +560,11 @@ const ViewProjectContent = () => {
label: t('dashboard.featureFlags'),
icon: FlagIcon,
},
+ {
+ id: PROJECT_TABS.captcha,
+ label: t('common.captcha'),
+ icon: PuzzleIcon,
+ },
]
const adminTabs = allowedToManage
@@ -588,11 +593,6 @@ const ViewProjectContent = () => {
label: t('dashboard.alerts'),
icon: BellRingIcon,
},
- {
- id: PROJECT_TABS.captcha,
- label: t('common.captcha'),
- icon: PuzzleIcon,
- },
{
id: PROJECT_TABS.experiments,
label: t('dashboard.experiments'),