📈 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!
TypeScript chartsclickhousedockergdprgoogle-analyticsmetricsmonitoringmysqlnestjsprivacyredisself-hostedselfhostedstatisticstailwindcssweb-analyticswebanalyticswebsite
feat: Captcha Auto mode & other improvements
Blue Mouse2ec8eb6e9948
diff --git a/backend/apps/cloud/src/analytics/analytics.service.ts b/backend/apps/cloud/src/analytics/analytics.service.tsindex 2757ace60..0bc008d5e 100644--- a/backend/apps/cloud/src/analytics/analytics.service.ts+++ b/backend/apps/cloud/src/analytics/analytics.service.ts@@ -288,6 +288,25 @@ const ERROR_COLUMN_MAP: Record<string, string> = {const mapErrorColumn = (type: string): string => ERROR_COLUMN_MAP[type] || type+const captchaMetaValue = (key: string, fallback: string) =>+ `if(indexOf(\`meta.key\`, '${key}') = 0, '${fallback}', arrayElement(\`meta.value\`, indexOf(\`meta.key\`, '${key}')))`++const CAPTCHA_EVENT_SQL = captchaMetaValue('captcha_event', 'pass')+const CAPTCHA_DIFFICULTY_SQL = captchaMetaValue('captcha_difficulty', '0')+const CAPTCHA_REASON_SQL = captchaMetaValue('captcha_reason', '')+const CAPTCHA_SOLVE_MS_SQL = `toUInt32OrZero(${captchaMetaValue('solve_ms', '0')})`+const CAPTCHA_SOLVE_TIME_SQL = `multiIf(${CAPTCHA_SOLVE_MS_SQL} = 0, 'unknown', ${CAPTCHA_SOLVE_MS_SQL} < 1000, '<1s', ${CAPTCHA_SOLVE_MS_SQL} < 3000, '1-3s', ${CAPTCHA_SOLVE_MS_SQL} < 10000, '3-10s', ${CAPTCHA_SOLVE_MS_SQL} < 30000, '10-30s', '30s+')`++const CAPTCHA_META_COLUMN_MAP: Record<string, string> = {+ captcha_event: CAPTCHA_EVENT_SQL,+ captcha_difficulty: CAPTCHA_DIFFICULTY_SQL,+ captcha_reason: CAPTCHA_REASON_SQL,+ solve_time: CAPTCHA_SOLVE_TIME_SQL,+}++const getCaptchaColumnExpression = (col: string): string =>+ CAPTCHA_META_COLUMN_MAP[col] || col+const generateParamsQuery = (col: string,subQuery: string,@@ -332,7 +351,20 @@ const generateParamsQuery = (}if (type === 'captcha') {- return `SELECT ${columnsQuery}, count(*) as count ${subQuery} GROUP BY ${col}`+ const captchaColumn = getCaptchaColumnExpression(col)+ let captchaFilter = ''++ if (['cc', 'br', 'os', 'dv'].includes(col)) {+ captchaFilter = `AND ${CAPTCHA_EVENT_SQL} = 'pass'`+ } else if (col === 'captcha_difficulty') {+ captchaFilter = `AND ${CAPTCHA_EVENT_SQL} = 'generate' AND toUInt8OrZero(${CAPTCHA_DIFFICULTY_SQL}) > 0`+ } else if (col === 'captcha_reason') {+ captchaFilter = `AND ${CAPTCHA_EVENT_SQL} = 'generate' AND ${CAPTCHA_REASON_SQL} NOT IN ('', 'baseline', 'manual')`+ } else if (col === 'solve_time') {+ captchaFilter = `AND ${CAPTCHA_EVENT_SQL} = 'pass' AND ${CAPTCHA_SOLVE_MS_SQL} > 0`+ }++ return `SELECT ${captchaColumn} as name, count(*) as count ${subQuery} ${captchaFilter} GROUP BY name`}if (customEVFilterApplied) {@@ -1322,6 +1354,8 @@ export class AnalyticsService {sqlColumn = 'event_name'} else if (dataType === DataType.ERRORS) {sqlColumn = mapErrorColumn(column)+ } else if (dataType === DataType.CAPTCHA) {+ sqlColumn = getCaptchaColumnExpression(column)}const isNullFilter =@@ -3643,9 +3677,14 @@ export class AnalyticsService {const baseQuery = `SELECT${selector},- count() as count+ countIf(captcha_event = 'generate') as generated,+ countIf(captcha_event = 'pass') as passed,+ countIf(captcha_event = 'verify_fail') as failed,+ countIf(captcha_event = 'validation_fail') as validationFailed,+ countIf(captcha_event = 'replay') as replayedFROM (- SELECT *,+ SELECT+ ${CAPTCHA_EVENT_SQL} as captcha_event,${timeBucketFunc}(toTimeZone(created, {timezone:String})) as tz_createdFROM eventsWHERE@@ -3661,9 +3700,12 @@ export class AnalyticsService {if (mode === ChartRenderMode.CUMULATIVE) {return `SELECT- *,- sum(pageviews) OVER (ORDER BY ${groupBy}) as pageviews,- sum(uniques) OVER (ORDER BY ${groupBy}) as uniques+ ${groupBy},+ sum(generated) OVER (ORDER BY ${groupBy}) as generated,+ sum(passed) OVER (ORDER BY ${groupBy}) as passed,+ sum(failed) OVER (ORDER BY ${groupBy}) as failed,+ sum(validationFailed) OVER (ORDER BY ${groupBy}) as validationFailed,+ sum(replayed) OVER (ORDER BY ${groupBy}) as replayedFROM (${baseQuery})`}@@ -4079,7 +4121,11 @@ export class AnalyticsService {}extractCaptchaChartData(result, x: string[]): any {- const count = Array(x.length).fill(0)+ const generated = Array(x.length).fill(0)+ const passed = Array(x.length).fill(0)+ const failed = Array(x.length).fill(0)+ const validationFailed = Array(x.length).fill(0)+ const replayed = Array(x.length).fill(0)for (let row = 0; row < _size(result); ++row) {const dateString = this.generateDateString(result[row])@@ -4087,12 +4133,125 @@ export class AnalyticsService {const index = x.indexOf(dateString)if (index !== -1) {- count[index] = result[row].count+ generated[index] = Number(result[row].generated || 0)+ passed[index] = Number(result[row].passed || 0)+ failed[index] = Number(result[row].failed || 0)+ validationFailed[index] = Number(result[row].validationFailed || 0)+ replayed[index] = Number(result[row].replayed || 0)}}return {- count,+ generated,+ passed,+ failed,+ validationFailed,+ replayed,+ results: passed,+ }+ }++ async getCaptchaSummary(+ filtersQuery: string,+ paramsData: any,+ ): Promise<object> {+ const baseWhere = `+ FROM events+ WHERE+ pid = {pid:FixedString(12)}+ AND type = 'captcha'+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}+ ${filtersQuery}+ `++ const summaryQuery = `+ WITH+ ${CAPTCHA_EVENT_SQL} as captcha_event,+ ${CAPTCHA_SOLVE_MS_SQL} as solve_ms+ SELECT+ countIf(captcha_event = 'generate') as generated,+ countIf(captcha_event = 'pass') as passed,+ countIf(captcha_event = 'verify_fail') as failed,+ countIf(captcha_event = 'validation_fail') as validationFailed,+ countIf(captcha_event = 'replay') as replayed,+ round(if(generated = 0, 0, passed / generated * 100), 2) as passRate,+ round(if(passed + failed = 0, 0, failed / (passed + failed) * 100), 2) as failRate,+ round(quantileExactIf(0.5)(solve_ms, captcha_event = 'pass' AND solve_ms > 0) / 1000, 2) as solveP50,+ round(quantileExactIf(0.75)(solve_ms, captcha_event = 'pass' AND solve_ms > 0) / 1000, 2) as solveP75,+ round(quantileExactIf(0.95)(solve_ms, captcha_event = 'pass' AND solve_ms > 0) / 1000, 2) as solveP95+ ${baseWhere}+ `++ const difficultyQuery = `+ WITH+ ${CAPTCHA_EVENT_SQL} as captcha_event,+ toUInt8OrZero(${CAPTCHA_DIFFICULTY_SQL}) as difficulty+ SELECT toString(difficulty) as name, count() as count+ ${baseWhere}+ AND captcha_event = 'generate'+ AND difficulty > 0+ GROUP BY difficulty+ ORDER BY difficulty ASC+ `++ const reasonQuery = `+ WITH+ ${CAPTCHA_EVENT_SQL} as captcha_event,+ ${CAPTCHA_REASON_SQL} as reason+ SELECT reason as name, count() as count+ ${baseWhere}+ AND captcha_event = 'generate'+ AND reason NOT IN ('', 'baseline', 'manual')+ GROUP BY reason+ ORDER BY count DESC+ LIMIT 10+ `++ const solveTimeQuery = `+ WITH+ ${CAPTCHA_EVENT_SQL} as captcha_event,+ ${CAPTCHA_SOLVE_MS_SQL} as solve_ms,+ ${CAPTCHA_SOLVE_TIME_SQL} as bucket+ SELECT bucket as name, count() as count+ ${baseWhere}+ AND captcha_event = 'pass'+ AND solve_ms > 0+ GROUP BY bucket+ ORDER BY min(solve_ms) ASC+ `++ const queryParams = paramsData.params+ const [summary, difficulty, reasons, solveTime] = await Promise.all([+ clickhouse+ .query({ query: summaryQuery, query_params: queryParams })+ .then((resultSet) => resultSet.json<any>()),+ clickhouse+ .query({ query: difficultyQuery, query_params: queryParams })+ .then((resultSet) => resultSet.json<any>()),+ clickhouse+ .query({ query: reasonQuery, query_params: queryParams })+ .then((resultSet) => resultSet.json<any>()),+ clickhouse+ .query({ query: solveTimeQuery, query_params: queryParams })+ .then((resultSet) => resultSet.json<any>()),+ ])++ const row = summary.data?.[0] || {}++ return {+ generated: Number(row.generated || 0),+ passed: Number(row.passed || 0),+ failed: Number(row.failed || 0),+ validationFailed: Number(row.validationFailed || 0),+ replayed: Number(row.replayed || 0),+ passRate: Number(row.passRate || 0),+ failRate: Number(row.failRate || 0),+ solveP50: Number(row.solveP50 || 0),+ solveP75: Number(row.solveP75 || 0),+ solveP95: Number(row.solveP95 || 0),+ difficulty: difficulty.data || [],+ reasons: reasons.data || [],+ solveTime: solveTime.data || [],}}@@ -4108,6 +4267,7 @@ export class AnalyticsService {): Promise<object | void> {let params: unknown = {}let chart: unknown = {}+ let summary: unknown = {}const promises = [// Getting params@@ -4148,13 +4308,17 @@ export class AnalyticsService {query_params: { ...paramsData.params, timezone: safeTimezone },}).then((resultSet) => resultSet.json<TrafficCEFilterCHResponse>())- const { count } = this.extractCaptchaChartData(data, xShifted)+ const captchaChart = this.extractCaptchaChartData(data, xShifted)chart = {x: xShifted,- results: count,+ ...captchaChart,}})(),++ (async () => {+ summary = await this.getCaptchaSummary(filtersQuery, paramsData)+ })(),]await Promise.all(promises)@@ -4162,6 +4326,7 @@ export class AnalyticsService {return Promise.resolve({params,chart,+ summary,})}diff --git a/backend/apps/cloud/src/analytics/utils/transformers.ts b/backend/apps/cloud/src/analytics/utils/transformers.tsindex 7ec1ed491..eae2b2cf8 100644--- a/backend/apps/cloud/src/analytics/utils/transformers.ts+++ b/backend/apps/cloud/src/analytics/utils/transformers.ts@@ -105,6 +105,7 @@ interface CaptchaOptions {br?: string | nullos?: string | nullcc?: string | null+ meta?: Record<string, string> | nulltimestamp?: number}@@ -220,6 +221,7 @@ export const eventTransformer = (opts: EventTransformerOptions) => {br: opts.br || null,os: opts.os || null,cc: opts.cc || null,+ ...processMetaKV(opts.meta),created:typeof opts.timestamp === 'number'? dayjs.utc(opts.timestamp).format('YYYY-MM-DD HH:mm:ss')diff --git a/backend/apps/cloud/src/captcha/captcha.controller.ts b/backend/apps/cloud/src/captcha/captcha.controller.tsindex b6f64975d..f3baa927d 100644--- a/backend/apps/cloud/src/captcha/captcha.controller.ts+++ b/backend/apps/cloud/src/captcha/captcha.controller.ts@@ -76,7 +76,7 @@ export class CaptchaController {await this.captchaService.validatePIDForCAPTCHA(pid)- return this.captchaService.generateChallenge(pid)+ return this.captchaService.generateChallenge(pid, headers, ip)}@Post('/verify')@@ -121,15 +121,42 @@ export class CaptchaController {throw new ForbiddenException('PoW verification failed')}- // Verify the PoW solution- const isValid = await this.captchaService.verifyPoW(- challenge,- nonce,- solution,- pid,- )+ let verification++ try {+ verification = await this.captchaService.verifyPoW(+ challenge,+ nonce,+ solution,+ pid,+ )+ } catch (reason) {+ try {+ await this.captchaService.logCaptchaReplay(pid, headers, timestamp, ip)+ } catch (logReason) {+ this.logger.error(+ `[CaptchaController -> verify] Failed to log captcha replay: ${logReason}`,+ )+ }++ throw reason+ }++ if (!verification.valid) {+ try {+ await this.captchaService.logCaptchaFailure(+ pid,+ headers,+ timestamp,+ ip,+ verification,+ )+ } catch (reason) {+ this.logger.error(+ `[CaptchaController -> verify] Failed to log captcha failure: ${reason}`,+ )+ }- if (!isValid) {throw new ForbiddenException('PoW verification failed')}@@ -140,7 +167,13 @@ export class CaptchaController {)try {- await this.captchaService.logCaptchaPass(pid, headers, timestamp, ip)+ await this.captchaService.logCaptchaPass(+ pid,+ headers,+ timestamp,+ ip,+ verification,+ )} catch (reason) {this.logger.error(`[CaptchaController -> verify] Failed to log captcha pass: ${reason}`,@@ -163,7 +196,13 @@ export class CaptchaController {@Headers() headers,@Ip() reqIP,): Promise<any> {- this.logger.log(validateDTO, 'POST /captcha/validate')+ this.logger.log(+ {+ hasToken: Boolean(validateDTO?.token),+ hasSecret: Boolean(validateDTO?.secret),+ },+ 'POST /captcha/validate',+ )const { token, secret } = validateDTOconst ip = getIPFromHeaders(headers) || reqIP || ''@@ -177,7 +216,7 @@ export class CaptchaController {return {success: true,- data: await this.captchaService.validateToken(token, secret),+ data: await this.captchaService.validateToken(token, secret, headers, ip),}}}diff --git a/backend/apps/cloud/src/captcha/captcha.service.ts b/backend/apps/cloud/src/captcha/captcha.service.tsindex 99ac3516c..99fe63d15 100644--- a/backend/apps/cloud/src/captcha/captcha.service.ts+++ b/backend/apps/cloud/src/captcha/captcha.service.ts@@ -24,9 +24,53 @@ dayjs.extend(utc)// Default difficulty: number of leading hex zeros required (4 = ~65k iterations avg)const DEFAULT_POW_DIFFICULTY = 4+const MIN_POW_DIFFICULTY = 2+const MAX_POW_DIFFICULTY = 6// Challenge TTL in seconds (5 minutes)const CHALLENGE_TTL = 300+const CAPTCHA_COUNTER_PREFIX = 'captcha:auto'++type CaptchaDifficultyMode = 'manual' | 'auto'+type CaptchaEventName =+ | 'generate'+ | 'pass'+ | 'verify_fail'+ | 'validation_fail'+ | 'replay'++interface CaptchaHeaders {+ [key: string]: string | string[] | undefined+}++interface CaptchaDifficultyDecision {+ difficulty: number+ mode: CaptchaDifficultyMode+ reasons: string[]+ score: number+}++interface ChallengePayload {+ pid?: string+ difficulty: number+ difficultyMode?: CaptchaDifficultyMode+ autoReasons?: string[]+ issuedAt?: number+}++interface PowVerificationResult extends ChallengePayload {+ valid: boolean+ solveMs?: number+ failureReason?: string+}++interface CaptchaEventMeta {+ difficulty?: number+ difficultyMode?: CaptchaDifficultyMode+ autoReasons?: string[]+ solveMs?: number+ failureReason?: string+}export const DUMMY_PIDS = {ALWAYS_PASS: 'AP00000000000',@@ -56,6 +100,92 @@ const getChallengeCacheKey = (challenge: string): string => {return `pow_challenge:${challenge}`}+const clampDifficulty = (difficulty?: number | null): number => {+ if (!Number.isFinite(difficulty)) {+ return DEFAULT_POW_DIFFICULTY+ }++ return Math.min(+ MAX_POW_DIFFICULTY,+ Math.max(MIN_POW_DIFFICULTY, Number(difficulty)),+ )+}++const getHeaderValue = (+ headers: CaptchaHeaders | undefined,+ name: string,+): string => {+ const value = headers?.[name] ?? headers?.[name.toLowerCase()]+ if (Array.isArray(value)) {+ return value[0] || ''+ }++ return value ? String(value) : ''+}++const hasSuspiciousHeaders = (headers: CaptchaHeaders | undefined): boolean => {+ const required = ['accept', 'accept-language', 'accept-encoding']+ const missing = required.filter((header) => !getHeaderValue(headers, header))++ return missing.length >= 2+}++const hasHeadlessUserAgent = (headers: CaptchaHeaders | undefined): boolean => {+ return /HeadlessChrome|PhantomJS|SlimerJS|Selenium|WebDriver|Puppeteer|Playwright|Cypress|Nightmare|Splash/i.test(+ getHeaderValue(headers, 'user-agent'),+ )+}++const hashIP = (pid: string, ip: string): string => {+ return crypto+ .createHash('sha256')+ .update(`${pid}:${ip}`)+ .digest('hex')+ .slice(0, 16)+}++const getCounterKey = (+ pid: string,+ event: string,+ window: string,+ scope = 'project',+ bucket = 'all',+): string =>+ `${CAPTCHA_COUNTER_PREFIX}:${window}:${event}:${scope}:${pid}:${bucket}`++const incrCounter = async (key: string, ttl: number): Promise<number> => {+ const value = await redis.incr(key)++ if (value === 1) {+ await redis.expire(key, ttl)+ }++ return value+}++const getCounter = async (key: string): Promise<number> => {+ const value = await redis.get(key)+ const parsed = Number(value || 0)++ return Number.isFinite(parsed) ? parsed : 0+}++const consumeChallenge = async (cacheKey: string): Promise<string | null> => {+ const getdel = (redis as any).getdel++ if (typeof getdel === 'function') {+ return getdel.call(redis, cacheKey)+ }++ const result = await redis.eval(+ "local value = redis.call('GET', KEYS[1]); if value then redis.call('DEL', KEYS[1]); end; return value",+ 1,+ cacheKey,+ )++ return typeof result === 'string' ? result : null+}+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.@@ -113,8 +243,7 @@ export class CaptchaService {const project = await this.projectService.getRedisProject(pid)- // Use project's configured difficulty if available, otherwise default- return project?.captchaDifficulty || DEFAULT_POW_DIFFICULTY+ return clampDifficulty(project?.captchaDifficulty)}// validates pid, checks if captcha is enabled and throws an error otherwise@@ -136,14 +265,20 @@ export class CaptchaService {}}- async logCaptchaPass(+ private async logCaptchaEvent(pid: string,- headers: Record<string, string>,+ event: CaptchaEventName,+ headers: CaptchaHeaders,timestamp: number,ip: string,+ meta: CaptchaEventMeta = {},) {+ if (isDummyPID(pid)) {+ return+ }+const ua = await UAParser(- headers?.['user-agent'],+ getHeaderValue(headers, 'user-agent'),undefined,headers,).withClientHints()@@ -152,6 +287,30 @@ export class CaptchaService {const osName = ua.os.nameconst { country } = getIPDetails(ip)+ const eventMeta: Record<string, string> = {+ captcha_event: event,+ }++ if (meta.difficulty !== undefined) {+ eventMeta.captcha_difficulty = String(meta.difficulty)+ }++ if (meta.difficultyMode) {+ eventMeta.captcha_difficulty_mode = meta.difficultyMode+ }++ if (meta.autoReasons?.length) {+ eventMeta.captcha_reason = meta.autoReasons[0]+ }++ if (meta.solveMs !== undefined) {+ eventMeta.solve_ms = String(Math.max(0, Math.round(meta.solveMs)))+ }++ if (meta.failureReason) {+ eventMeta.failure_reason = meta.failureReason+ }+const transformed = eventTransformer({type: 'captcha',pid,@@ -159,6 +318,7 @@ export class CaptchaService {br: browserName,os: osName,cc: country,+ meta: eventMeta,timestamp,})@@ -176,6 +336,76 @@ export class CaptchaService {}}+ async logCaptchaPass(+ pid: string,+ headers: CaptchaHeaders,+ timestamp: number,+ ip: string,+ verification: PowVerificationResult,+ ) {+ await this.recordCaptchaOutcome(pid, 'pass', ip, verification)+ await this.logCaptchaEvent(pid, 'pass', headers, timestamp, ip, {+ difficulty: verification.difficulty,+ difficultyMode: verification.difficultyMode || 'manual',+ autoReasons: verification.autoReasons,+ solveMs: verification.solveMs,+ })+ }++ async logCaptchaFailure(+ pid: string,+ headers: CaptchaHeaders,+ timestamp: number,+ ip: string,+ verification: PowVerificationResult,+ ) {+ await this.recordCaptchaOutcome(pid, 'verify_fail', ip, verification)+ await this.logCaptchaEvent(pid, 'verify_fail', headers, timestamp, ip, {+ difficulty: verification.difficulty,+ difficultyMode: verification.difficultyMode || 'manual',+ autoReasons: verification.autoReasons,+ solveMs: verification.solveMs,+ failureReason: verification.failureReason || 'invalid_pow',+ })+ }++ async logCaptchaReplay(+ pid: string,+ headers: CaptchaHeaders,+ timestamp: number,+ ip: string,+ failureReason = 'expired_or_replayed',+ ) {+ await this.recordCaptchaOutcome(pid, 'replay', ip)+ await this.logCaptchaEvent(pid, 'replay', headers, timestamp, ip, {+ failureReason,+ })+ }++ private async recordCaptchaOutcome(+ pid: string,+ event: CaptchaEventName,+ ip: string,+ verification?: Partial<PowVerificationResult>,+ ) {+ if (isDummyPID(pid)) {+ return+ }++ const ipHash = ip ? hashIP(pid, ip) : 'unknown'+ const promises = [+ incrCounter(getCounterKey(pid, event, '5m'), 300),+ incrCounter(getCounterKey(pid, event, '15m'), 900),+ incrCounter(getCounterKey(pid, event, '5m', 'ip', ipHash), 300),+ ]++ if (verification?.solveMs !== undefined) {+ promises.push(incrCounter(getCounterKey(pid, 'solve', '5m'), 300))+ }++ await Promise.all(promises)+ }+async generateDummyToken() {return encryptString('DUMMY_TOKEN00000111112222233333444445555566666777778888899999',@@ -217,7 +447,12 @@ export class CaptchaService {return `${ciphertext}.${signature}`}- async validateToken(token: string, secretKey: string) {+ async validateToken(+ token: string,+ secretKey: string,+ headers: CaptchaHeaders = {},+ ip = '',+ ) {let parsedif (secretKey === DUMMY_SECRETS.ALWAYS_FAIL) {@@ -265,27 +500,60 @@ export class CaptchaService {typeof parsed.timestamp !== 'number' ||!Number.isFinite(parsed.timestamp)) {+ if (typeof parsed?.pid === 'string') {+ await this.logValidationFailure(+ parsed.pid,+ headers,+ ip,+ 'invalid_payload',+ )+ }+throw new BadRequestException('Invalid token payload')}- // Guard against obviously invalid pid values to reduce accidental misuse.if (!isDummyPID(parsed.pid) && !isValidPID(parsed.pid)) {+ await this.logValidationFailure(parsed.pid, headers, ip, 'invalid_pid')throw new BadRequestException('Invalid token payload')}if (dayjs().unix() * 1000 - parsed.timestamp > CAPTCHA_TOKEN_LIFETIME) {+ await this.logValidationFailure(parsed.pid, headers, ip, 'token_expired')throw new BadRequestException('Token expired')}const tokenUsed = await isTokenAlreadyUsed(token)if (tokenUsed) {+ await this.recordCaptchaOutcome(parsed.pid, 'replay', ip)+ await this.logValidationFailure(parsed.pid, headers, ip, 'token_replay')throw new BadRequestException('Token already used')}return parsed}+ private async logValidationFailure(+ pid: string,+ headers: CaptchaHeaders,+ ip: string,+ failureReason: string,+ ) {+ if (isDummyPID(pid) || !isValidPID(pid)) {+ return+ }++ await this.recordCaptchaOutcome(pid, 'validation_fail', ip)+ await this.logCaptchaEvent(+ pid,+ 'validation_fail',+ headers,+ dayjs.utc().unix() * 1000,+ ip,+ { failureReason },+ )+ }+// Generate SHA-256 hash of the inputsha256(input: string): string {return crypto.createHash('sha256').update(input).digest('hex')@@ -297,45 +565,147 @@ export class CaptchaService {return hash.startsWith(prefix)}- // Generate a PoW challenge- async generateChallenge(pid: string): Promise<GeneratedChallenge> {- const difficulty = await this._getProjectDifficulty(pid)+ private async selectDifficulty(+ pid: string,+ headers: CaptchaHeaders,+ ip: string,+ ): Promise<CaptchaDifficultyDecision> {+ const project = isDummyPID(pid)+ ? null+ : await this.projectService.getRedisProject(pid)+ const mode = (project?.captchaDifficultyMode ||+ 'manual') as CaptchaDifficultyMode+ const baseDifficulty = clampDifficulty(project?.captchaDifficulty)++ if (mode !== 'auto' || isDummyPID(pid)) {+ return {+ difficulty: baseDifficulty,+ mode: 'manual',+ reasons: ['manual'],+ score: 0,+ }+ }++ const { country, isHosting } = getIPDetails(ip)+ const countryBucket = country || 'xx'+ const ipHash = ip ? hashIP(pid, ip) : 'unknown'++ const [+ projectGenerate1m,+ projectGenerate5m,+ countryGenerate5m,+ ipGenerate1m,+ ] = await Promise.all([+ incrCounter(getCounterKey(pid, 'generate', '1m'), 60),+ incrCounter(getCounterKey(pid, 'generate', '5m'), 300),+ incrCounter(+ getCounterKey(pid, 'generate', '5m', 'country', countryBucket),+ 300,+ ),+ incrCounter(getCounterKey(pid, 'generate', '1m', 'ip', ipHash), 60),+ ])++ const [+ projectPass5m,+ projectFail5m,+ projectReplay5m,+ projectValidationFail5m,+ ipFail5m,+ ipReplay5m,+ ] = await Promise.all([+ getCounter(getCounterKey(pid, 'pass', '5m')),+ getCounter(getCounterKey(pid, 'verify_fail', '5m')),+ getCounter(getCounterKey(pid, 'replay', '5m')),+ getCounter(getCounterKey(pid, 'validation_fail', '5m')),+ getCounter(getCounterKey(pid, 'verify_fail', '5m', 'ip', ipHash)),+ getCounter(getCounterKey(pid, 'replay', '5m', 'ip', ipHash)),+ ])++ const reasons: string[] = []+ let score = 0+ const passRatio =+ projectGenerate5m > 0 ? projectPass5m / projectGenerate5m : 1+ const verifyAttempts = projectPass5m + projectFail5m+ const failRatio = verifyAttempts > 0 ? projectFail5m / verifyAttempts : 0++ const addRisk = (condition: boolean, reason: string, weight = 1) => {+ if (!condition) {+ return+ }++ score += weight+ reasons.push(reason)+ }++ addRisk(isHosting, 'hosting_ip')+ addRisk(hasHeadlessUserAgent(headers), 'headless_browser')+ addRisk(hasSuspiciousHeaders(headers), 'suspicious_headers')+ addRisk(projectGenerate1m >= 50, 'project_spike')+ addRisk(countryGenerate5m >= 50, 'country_spike')+ addRisk(ipGenerate1m >= 8, 'ip_pressure')+ addRisk(projectGenerate5m >= 30 && passRatio < 0.25, 'low_pass_ratio')+ addRisk(verifyAttempts >= 20 && failRatio > 0.35, 'verify_failures')+ addRisk(projectValidationFail5m >= 5, 'validation_failures')+ addRisk(projectReplay5m >= 2 || ipReplay5m >= 1, 'replay_attempts')+ addRisk(ipFail5m >= 3, 'ip_verify_failures')++ const adjustment = score >= 5 ? 2 : score >= 2 ? 1 : 0++ return {+ difficulty: clampDifficulty(baseDifficulty + adjustment),+ mode: 'auto',+ reasons: adjustment > 0 ? reasons.slice(0, 4) : ['baseline'],+ score,+ }+ }++ async generateChallenge(+ pid: string,+ headers: CaptchaHeaders = {},+ ip = '',+ ): Promise<GeneratedChallenge> {+ const decision = await this.selectDifficulty(pid, headers, ip)- // Generate a random challenge stringconst challenge = crypto.randomBytes(32).toString('hex')+ const issuedAt = dayjs.utc().unix() * 1000- // Store challenge in Redis with TTL to prevent replay attacks- // Include pid to prevent cross-project difficulty bypassconst cacheKey = getChallengeCacheKey(challenge)- const challengeData = JSON.stringify({ pid, difficulty })+ const challengeData = JSON.stringify({+ pid,+ difficulty: decision.difficulty,+ difficultyMode: decision.mode,+ autoReasons: decision.reasons,+ issuedAt,+ })await redis.set(cacheKey, challengeData, 'EX', CHALLENGE_TTL)+ await this.logCaptchaEvent(pid, 'generate', headers, issuedAt, ip, {+ difficulty: decision.difficulty,+ difficultyMode: decision.mode,+ autoReasons: decision.reasons,+ })+return {challenge,- difficulty,+ difficulty: decision.difficulty,}}- // Verify a PoW solutionasync verifyPoW(challenge: string,nonce: number,solution: string,pid: string,- ): Promise<boolean> {- // Check if challenge exists and hasn't been used+ ): Promise<PowVerificationResult> {const cacheKey = getChallengeCacheKey(challenge)- const storedData = await redis.get(cacheKey)+ const storedData = await consumeChallenge(cacheKey)if (!storedData) {throw new BadRequestException('Invalid or expired challenge')}- let difficulty: number- let storedPid: string | undefined+ let payload: ChallengePayload- // Parse stored data - support both old string format (difficulty only)- // and new JSON format (pid + difficulty) for backward compatibilitytry {const parsed = JSON.parse(storedData)if (@@ -343,50 +713,62 @@ export class CaptchaService {parsed !== null &&'difficulty' in parsed) {- difficulty = parsed.difficulty- storedPid = parsed.pid+ payload = parsed} else {- // Fallback: treat as raw difficulty number- difficulty = parseInt(storedData, 10)+ payload = { difficulty: parseInt(storedData, 10) }}} catch {- // Old format: just the difficulty as a string- difficulty = parseInt(storedData, 10)+ payload = { difficulty: parseInt(storedData, 10) }}- // Validate difficulty to prevent bypass via NaN or invalid values+ const difficulty = Number(payload.difficulty)+if (- typeof difficulty !== 'number' ||!Number.isFinite(difficulty) ||- difficulty < 1 ||- difficulty > 6+ difficulty < MIN_POW_DIFFICULTY ||+ difficulty > MAX_POW_DIFFICULTY) {throw new BadRequestException('Invalid challenge difficulty')}- // If the challenge was bound to a specific project, verify it matches- if (storedPid !== undefined && storedPid !== pid) {+ if (payload.pid !== undefined && payload.pid !== pid) {throw new BadRequestException('Challenge was issued for a different project',)}- // Compute the expected hashconst input = `${challenge}:${nonce}`const computedHash = this.sha256(input)+ const solveMs = payload.issuedAt+ ? dayjs.utc().unix() * 1000 - payload.issuedAt+ : undefined+ const resultBase = {+ difficulty,+ difficultyMode: payload.difficultyMode || 'manual',+ autoReasons: payload.autoReasons || [],+ issuedAt: payload.issuedAt,+ solveMs,+ }- // Verify the solution matches and has required prefixif (computedHash !== solution) {- return false+ return {+ ...resultBase,+ valid: false,+ failureReason: 'solution_mismatch',+ }}if (!this.hasValidPrefix(computedHash, difficulty)) {- return false+ return {+ ...resultBase,+ valid: false,+ failureReason: 'difficulty_mismatch',+ }}- // Mark challenge as used by deleting it- await redis.del(cacheKey)-- return true+ return {+ ...resultBase,+ valid: true,+ }}}diff --git a/backend/apps/cloud/src/captcha/dtos/validate.dto.ts b/backend/apps/cloud/src/captcha/dtos/validate.dto.tsindex 7652c2100..70857ec8c 100644--- a/backend/apps/cloud/src/captcha/dtos/validate.dto.ts+++ b/backend/apps/cloud/src/captcha/dtos/validate.dto.ts@@ -4,7 +4,7 @@ import { IsNotEmpty, IsString } from 'class-validator'export class ValidateDto {@ApiProperty({required: true,- description: 'Catpcha pass token',+ description: 'Captcha pass token',})@IsNotEmpty()@IsString()diff --git a/backend/apps/cloud/src/common/constants.ts b/backend/apps/cloud/src/common/constants.tsindex 57bedb8bc..c76a3f69a 100644--- a/backend/apps/cloud/src/common/constants.ts+++ b/backend/apps/cloud/src/common/constants.ts@@ -106,7 +106,16 @@ const TRAFFIC_COLUMNS = [const TRAFFIC_METAKEY_COLUMNS = ['tag:key', 'tag:value']const ALL_COLUMNS = [...TRAFFIC_COLUMNS, 'ev', 'entryPage', 'exitPage']-const CAPTCHA_COLUMNS = ['cc', 'br', 'os', 'dv']+const CAPTCHA_COLUMNS = [+ 'cc',+ 'br',+ 'os',+ 'dv',+ 'captcha_event',+ 'captcha_difficulty',+ 'captcha_reason',+ 'solve_time',+]const PERFORMANCE_COLUMNS = ['cc','rg',diff --git a/backend/apps/cloud/src/project/dto/update-project.dto.ts b/backend/apps/cloud/src/project/dto/update-project.dto.tsindex f9e019015..68a517fee 100644--- a/backend/apps/cloud/src/project/dto/update-project.dto.ts+++ b/backend/apps/cloud/src/project/dto/update-project.dto.ts@@ -1,4 +1,4 @@-import { IsBoolean, IsOptional, IsInt, Min, Max } from 'class-validator'+import { IsBoolean, IsOptional, IsInt, Min, Max, IsIn } from 'class-validator'import { IntersectionType, PartialType } from '@nestjs/mapped-types'import { ApiProperty } from '@nestjs/swagger'import { ProjectDTO } from './project.dto'@@ -45,4 +45,15 @@ export class UpdateProjectDto extends IntersectionType(@Max(6)@IsOptional()captchaDifficulty?: number++ @ApiProperty({+ required: false,+ description:+ 'CAPTCHA difficulty mode. Manual uses captchaDifficulty directly; auto raises it dynamically when risk signals increase.',+ enum: ['manual', 'auto'],+ default: 'manual',+ })+ @IsIn(['manual', 'auto'])+ @IsOptional()+ captchaDifficultyMode?: 'manual' | 'auto'}diff --git a/backend/apps/cloud/src/project/entity/project.entity.ts b/backend/apps/cloud/src/project/entity/project.entity.tsindex 99d55e1e0..5acc2adf0 100644--- a/backend/apps/cloud/src/project/entity/project.entity.ts+++ b/backend/apps/cloud/src/project/entity/project.entity.ts@@ -20,6 +20,11 @@ export enum BotsProtectionLevel {STRICT = 'strict',}+enum CaptchaDifficultyMode {+ MANUAL = 'manual',+ AUTO = 'auto',+}+// In case of modifying some properties here add them to the GDPR data export email template@Entity()export class Project {@@ -72,6 +77,14 @@ export class Project {@Column('tinyint', { default: 4, unsigned: true })captchaDifficulty: number+ @ApiProperty()+ @Column({+ type: 'enum',+ enum: CaptchaDifficultyMode,+ default: CaptchaDifficultyMode.MANUAL,+ })+ captchaDifficultyMode: CaptchaDifficultyMode+@ApiProperty()@Column({type: 'enum',diff --git a/backend/apps/cloud/src/project/project.controller.ts b/backend/apps/cloud/src/project/project.controller.tsindex 57616512b..c06c5527c 100644--- a/backend/apps/cloud/src/project/project.controller.ts+++ b/backend/apps/cloud/src/project/project.controller.ts@@ -802,6 +802,36 @@ export class ProjectController {return { captchaSecretKey: secret }}+ @ApiBearerAuth()+ @Delete('/secret-gen/:pid')+ @HttpCode(200)+ @Auth()+ @ApiResponse({ status: 200, description: 'CAPTCHA secret key deleted' })+ async deleteSecretKey(+ @Param('pid') pid: string,+ @CurrentUserId() uid: string,+ ): Promise<void> {+ this.logger.log({ uid, pid }, 'DELETE /project/secret-gen/:pid')++ if (!isValidPID(pid)) {+ throw new BadRequestException(+ 'The provided Project ID (pid) is incorrect',+ )+ }++ const project = await this.projectService.getFullProject(pid)++ if (_isEmpty(project)) {+ throw new NotFoundException()+ }++ this.projectService.allowedToManage(project, uid)++ await this.projectService.update({ id: pid }, { captchaSecretKey: null })++ await deleteProjectRedis(pid)+ }+@Delete('/partially/:pid')@ApiQuery({name: 'from',@@ -1747,25 +1777,22 @@ export class ProjectController {project.isArchived = projectDTO.isArchived}- if (projectDTO.origins) {- project.origins = _map(projectDTO.origins, _trim) as string[]- } else {- project.origins = []+ if (projectDTO.origins !== undefined) {+ project.origins = projectDTO.origins+ ? (_map(projectDTO.origins, _trim) as string[])+ : []}- if (projectDTO.ipBlacklist) {- project.ipBlacklist = _map(projectDTO.ipBlacklist, _trim) as string[]- } else {- project.ipBlacklist = null+ if (projectDTO.ipBlacklist !== undefined) {+ project.ipBlacklist = projectDTO.ipBlacklist+ ? (_map(projectDTO.ipBlacklist, _trim) as string[])+ : null}- if (projectDTO.countryBlacklist) {- project.countryBlacklist = _map(- projectDTO.countryBlacklist,- _trim,- ) as string[]- } else {- project.countryBlacklist = null+ if (projectDTO.countryBlacklist !== undefined) {+ project.countryBlacklist = projectDTO.countryBlacklist+ ? (_map(projectDTO.countryBlacklist, _trim) as string[])+ : null}if (projectDTO.botsProtectionLevel) {@@ -1776,6 +1803,11 @@ export class ProjectController {project.captchaDifficulty = projectDTO.captchaDifficulty}+ if (projectDTO.captchaDifficultyMode !== undefined) {+ project.captchaDifficultyMode =+ projectDTO.captchaDifficultyMode as Project['captchaDifficultyMode']+ }+if (projectDTO.name) {project.name = _trim(projectDTO.name)}diff --git a/backend/apps/cloud/src/project/project.service.ts b/backend/apps/cloud/src/project/project.service.tsindex 4a750f25e..1ec374e11 100644--- a/backend/apps/cloud/src/project/project.service.ts+++ b/backend/apps/cloud/src/project/project.service.ts@@ -188,6 +188,7 @@ export class ProjectService {'project.botsProtectionLevel','project.captchaSecretKey','project.captchaDifficulty',+ 'project.captchaDifficultyMode','project.passwordHash','project.isPasswordProtected','admin.id',diff --git a/backend/apps/community/src/analytics/analytics.service.ts b/backend/apps/community/src/analytics/analytics.service.tsindex 982f8d294..10fdc4042 100644--- a/backend/apps/community/src/analytics/analytics.service.ts+++ b/backend/apps/community/src/analytics/analytics.service.ts@@ -280,6 +280,25 @@ const ERROR_COLUMN_MAP: Record<string, string> = {const mapErrorColumn = (type: string): string => ERROR_COLUMN_MAP[type] || type+const captchaMetaValue = (key: string, fallback: string) =>+ `if(indexOf(\`meta.key\`, '${key}') = 0, '${fallback}', arrayElement(\`meta.value\`, indexOf(\`meta.key\`, '${key}')))`++const CAPTCHA_EVENT_SQL = captchaMetaValue('captcha_event', 'pass')+const CAPTCHA_DIFFICULTY_SQL = captchaMetaValue('captcha_difficulty', '0')+const CAPTCHA_REASON_SQL = captchaMetaValue('captcha_reason', '')+const CAPTCHA_SOLVE_MS_SQL = `toUInt32OrZero(${captchaMetaValue('solve_ms', '0')})`+const CAPTCHA_SOLVE_TIME_SQL = `multiIf(${CAPTCHA_SOLVE_MS_SQL} = 0, 'unknown', ${CAPTCHA_SOLVE_MS_SQL} < 1000, '<1s', ${CAPTCHA_SOLVE_MS_SQL} < 3000, '1-3s', ${CAPTCHA_SOLVE_MS_SQL} < 10000, '3-10s', ${CAPTCHA_SOLVE_MS_SQL} < 30000, '10-30s', '30s+')`++const CAPTCHA_META_COLUMN_MAP: Record<string, string> = {+ captcha_event: CAPTCHA_EVENT_SQL,+ captcha_difficulty: CAPTCHA_DIFFICULTY_SQL,+ captcha_reason: CAPTCHA_REASON_SQL,+ solve_time: CAPTCHA_SOLVE_TIME_SQL,+}++const getCaptchaColumnExpression = (col: string): string =>+ CAPTCHA_META_COLUMN_MAP[col] || col+const generateParamsQuery = (col: string,subQuery: string,@@ -324,7 +343,20 @@ const generateParamsQuery = (}if (type === 'captcha') {- return `SELECT ${columnsQuery}, count(*) as count ${subQuery} GROUP BY ${col}`+ const captchaColumn = getCaptchaColumnExpression(col)+ let captchaFilter = ''++ if (['cc', 'br', 'os', 'dv'].includes(col)) {+ captchaFilter = `AND ${CAPTCHA_EVENT_SQL} = 'pass'`+ } else if (col === 'captcha_difficulty') {+ captchaFilter = `AND ${CAPTCHA_EVENT_SQL} = 'generate' AND toUInt8OrZero(${CAPTCHA_DIFFICULTY_SQL}) > 0`+ } else if (col === 'captcha_reason') {+ captchaFilter = `AND ${CAPTCHA_EVENT_SQL} = 'generate' AND ${CAPTCHA_REASON_SQL} NOT IN ('', 'baseline', 'manual')`+ } else if (col === 'solve_time') {+ captchaFilter = `AND ${CAPTCHA_EVENT_SQL} = 'pass' AND ${CAPTCHA_SOLVE_MS_SQL} > 0`+ }++ return `SELECT ${captchaColumn} as name, count(*) as count ${subQuery} ${captchaFilter} GROUP BY name`}if (customEVFilterApplied) {@@ -1253,7 +1285,11 @@ export class AnalyticsService {const { filter, isExclusive, isContains } = converted[column][f]let sqlColumn =- dataType === DataType.ERRORS ? mapErrorColumn(column) : column+ dataType === DataType.ERRORS+ ? mapErrorColumn(column)+ : dataType === DataType.CAPTCHA+ ? getCaptchaColumnExpression(column)+ : columnlet isArrayDataset = falseconst param = `qf_${col}_${f}`@@ -3816,9 +3852,14 @@ export class AnalyticsService {const baseQuery = `SELECT${selector},- count() as count+ countIf(captcha_event = 'generate') as generated,+ countIf(captcha_event = 'pass') as passed,+ countIf(captcha_event = 'verify_fail') as failed,+ countIf(captcha_event = 'validation_fail') as validationFailed,+ countIf(captcha_event = 'replay') as replayedFROM (- SELECT *,+ SELECT+ ${CAPTCHA_EVENT_SQL} as captcha_event,${timeBucketFunc}(toTimeZone(created, {timezone:String})) as tz_createdFROM eventsWHERE@@ -3834,8 +3875,12 @@ export class AnalyticsService {if (mode === ChartRenderMode.CUMULATIVE) {return `SELECT- *,- sum(count) OVER (ORDER BY ${groupBy}) as count+ ${groupBy},+ sum(generated) OVER (ORDER BY ${groupBy}) as generated,+ sum(passed) OVER (ORDER BY ${groupBy}) as passed,+ sum(failed) OVER (ORDER BY ${groupBy}) as failed,+ sum(validationFailed) OVER (ORDER BY ${groupBy}) as validationFailed,+ sum(replayed) OVER (ORDER BY ${groupBy}) as replayedFROM (${baseQuery})`}@@ -3844,7 +3889,11 @@ export class AnalyticsService {}extractCaptchaChartData(result, x: string[]): any {- const count = Array(x.length).fill(0)+ const generated = Array(x.length).fill(0)+ const passed = Array(x.length).fill(0)+ const failed = Array(x.length).fill(0)+ const validationFailed = Array(x.length).fill(0)+ const replayed = Array(x.length).fill(0)for (let row = 0; row < _size(result); ++row) {const dateString = this.generateDateString(result[row])@@ -3852,12 +3901,125 @@ export class AnalyticsService {const index = x.indexOf(dateString)if (index !== -1) {- count[index] = result[row].count+ generated[index] = Number(result[row].generated || 0)+ passed[index] = Number(result[row].passed || 0)+ failed[index] = Number(result[row].failed || 0)+ validationFailed[index] = Number(result[row].validationFailed || 0)+ replayed[index] = Number(result[row].replayed || 0)}}return {- count,+ generated,+ passed,+ failed,+ validationFailed,+ replayed,+ results: passed,+ }+ }++ async getCaptchaSummary(+ filtersQuery: string,+ paramsData: any,+ ): Promise<object> {+ const baseWhere = `+ FROM events+ WHERE+ pid = {pid:FixedString(12)}+ AND type = 'captcha'+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}+ ${filtersQuery}+ `++ const summaryQuery = `+ WITH+ ${CAPTCHA_EVENT_SQL} as captcha_event,+ ${CAPTCHA_SOLVE_MS_SQL} as solve_ms+ SELECT+ countIf(captcha_event = 'generate') as generated,+ countIf(captcha_event = 'pass') as passed,+ countIf(captcha_event = 'verify_fail') as failed,+ countIf(captcha_event = 'validation_fail') as validationFailed,+ countIf(captcha_event = 'replay') as replayed,+ round(if(generated = 0, 0, passed / generated * 100), 2) as passRate,+ round(if(passed + failed = 0, 0, failed / (passed + failed) * 100), 2) as failRate,+ round(quantileExactIf(0.5)(solve_ms, captcha_event = 'pass' AND solve_ms > 0) / 1000, 2) as solveP50,+ round(quantileExactIf(0.75)(solve_ms, captcha_event = 'pass' AND solve_ms > 0) / 1000, 2) as solveP75,+ round(quantileExactIf(0.95)(solve_ms, captcha_event = 'pass' AND solve_ms > 0) / 1000, 2) as solveP95+ ${baseWhere}+ `++ const difficultyQuery = `+ WITH+ ${CAPTCHA_EVENT_SQL} as captcha_event,+ toUInt8OrZero(${CAPTCHA_DIFFICULTY_SQL}) as difficulty+ SELECT toString(difficulty) as name, count() as count+ ${baseWhere}+ AND captcha_event = 'generate'+ AND difficulty > 0+ GROUP BY difficulty+ ORDER BY difficulty ASC+ `++ const reasonQuery = `+ WITH+ ${CAPTCHA_EVENT_SQL} as captcha_event,+ ${CAPTCHA_REASON_SQL} as reason+ SELECT reason as name, count() as count+ ${baseWhere}+ AND captcha_event = 'generate'+ AND reason NOT IN ('', 'baseline', 'manual')+ GROUP BY reason+ ORDER BY count DESC+ LIMIT 10+ `++ const solveTimeQuery = `+ WITH+ ${CAPTCHA_EVENT_SQL} as captcha_event,+ ${CAPTCHA_SOLVE_MS_SQL} as solve_ms,+ ${CAPTCHA_SOLVE_TIME_SQL} as bucket+ SELECT bucket as name, count() as count+ ${baseWhere}+ AND captcha_event = 'pass'+ AND solve_ms > 0+ GROUP BY bucket+ ORDER BY min(solve_ms) ASC+ `++ const queryParams = paramsData.params+ const [summary, difficulty, reasons, solveTime] = await Promise.all([+ clickhouse+ .query({ query: summaryQuery, query_params: queryParams })+ .then((resultSet) => resultSet.json<any>()),+ clickhouse+ .query({ query: difficultyQuery, query_params: queryParams })+ .then((resultSet) => resultSet.json<any>()),+ clickhouse+ .query({ query: reasonQuery, query_params: queryParams })+ .then((resultSet) => resultSet.json<any>()),+ clickhouse+ .query({ query: solveTimeQuery, query_params: queryParams })+ .then((resultSet) => resultSet.json<any>()),+ ])++ const row = summary.data?.[0] || {}++ return {+ generated: Number(row.generated || 0),+ passed: Number(row.passed || 0),+ failed: Number(row.failed || 0),+ validationFailed: Number(row.validationFailed || 0),+ replayed: Number(row.replayed || 0),+ passRate: Number(row.passRate || 0),+ failRate: Number(row.failRate || 0),+ solveP50: Number(row.solveP50 || 0),+ solveP75: Number(row.solveP75 || 0),+ solveP95: Number(row.solveP95 || 0),+ difficulty: difficulty.data || [],+ reasons: reasons.data || [],+ solveTime: solveTime.data || [],}}@@ -3873,6 +4035,7 @@ export class AnalyticsService {): Promise<object | void> {let params: unknown = {}let chart: unknown = {}+ let summary: unknown = {}const promises = [// Getting params@@ -3913,13 +4076,17 @@ export class AnalyticsService {query_params: { ...paramsData.params, timezone: safeTimezone },}).then((resultSet) => resultSet.json<TrafficCEFilterCHResponse>())- const { count } = this.extractCaptchaChartData(data, xShifted)+ const captchaChart = this.extractCaptchaChartData(data, xShifted)chart = {x: xShifted,- results: count,+ ...captchaChart,}})(),++ (async () => {+ summary = await this.getCaptchaSummary(filtersQuery, paramsData)+ })(),]await Promise.all(promises)@@ -3927,6 +4094,7 @@ export class AnalyticsService {return Promise.resolve({params,chart,+ summary,})}diff --git a/backend/apps/community/src/analytics/utils/transformers.ts b/backend/apps/community/src/analytics/utils/transformers.tsindex 7ec1ed491..eae2b2cf8 100644--- a/backend/apps/community/src/analytics/utils/transformers.ts+++ b/backend/apps/community/src/analytics/utils/transformers.ts@@ -105,6 +105,7 @@ interface CaptchaOptions {br?: string | nullos?: string | nullcc?: string | null+ meta?: Record<string, string> | nulltimestamp?: number}@@ -220,6 +221,7 @@ export const eventTransformer = (opts: EventTransformerOptions) => {br: opts.br || null,os: opts.os || null,cc: opts.cc || null,+ ...processMetaKV(opts.meta),created:typeof opts.timestamp === 'number'? dayjs.utc(opts.timestamp).format('YYYY-MM-DD HH:mm:ss')diff --git a/backend/apps/community/src/captcha/captcha.controller.ts b/backend/apps/community/src/captcha/captcha.controller.tsindex b6f64975d..f3baa927d 100644--- a/backend/apps/community/src/captcha/captcha.controller.ts+++ b/backend/apps/community/src/captcha/captcha.controller.ts@@ -76,7 +76,7 @@ export class CaptchaController {await this.captchaService.validatePIDForCAPTCHA(pid)- return this.captchaService.generateChallenge(pid)+ return this.captchaService.generateChallenge(pid, headers, ip)}@Post('/verify')@@ -121,15 +121,42 @@ export class CaptchaController {throw new ForbiddenException('PoW verification failed')}- // Verify the PoW solution- const isValid = await this.captchaService.verifyPoW(- challenge,- nonce,- solution,- pid,- )+ let verification++ try {+ verification = await this.captchaService.verifyPoW(+ challenge,+ nonce,+ solution,+ pid,+ )+ } catch (reason) {+ try {+ await this.captchaService.logCaptchaReplay(pid, headers, timestamp, ip)+ } catch (logReason) {+ this.logger.error(+ `[CaptchaController -> verify] Failed to log captcha replay: ${logReason}`,+ )+ }++ throw reason+ }++ if (!verification.valid) {+ try {+ await this.captchaService.logCaptchaFailure(+ pid,+ headers,+ timestamp,+ ip,+ verification,+ )+ } catch (reason) {+ this.logger.error(+ `[CaptchaController -> verify] Failed to log captcha failure: ${reason}`,+ )+ }- if (!isValid) {throw new ForbiddenException('PoW verification failed')}@@ -140,7 +167,13 @@ export class CaptchaController {)try {- await this.captchaService.logCaptchaPass(pid, headers, timestamp, ip)+ await this.captchaService.logCaptchaPass(+ pid,+ headers,+ timestamp,+ ip,+ verification,+ )} catch (reason) {this.logger.error(`[CaptchaController -> verify] Failed to log captcha pass: ${reason}`,@@ -163,7 +196,13 @@ export class CaptchaController {@Headers() headers,@Ip() reqIP,): Promise<any> {- this.logger.log(validateDTO, 'POST /captcha/validate')+ this.logger.log(+ {+ hasToken: Boolean(validateDTO?.token),+ hasSecret: Boolean(validateDTO?.secret),+ },+ 'POST /captcha/validate',+ )const { token, secret } = validateDTOconst ip = getIPFromHeaders(headers) || reqIP || ''@@ -177,7 +216,7 @@ export class CaptchaController {return {success: true,- data: await this.captchaService.validateToken(token, secret),+ data: await this.captchaService.validateToken(token, secret, headers, ip),}}}diff --git a/backend/apps/community/src/captcha/captcha.service.ts b/backend/apps/community/src/captcha/captcha.service.tsindex 99ac3516c..99fe63d15 100644--- a/backend/apps/community/src/captcha/captcha.service.ts+++ b/backend/apps/community/src/captcha/captcha.service.ts@@ -24,9 +24,53 @@ dayjs.extend(utc)// Default difficulty: number of leading hex zeros required (4 = ~65k iterations avg)const DEFAULT_POW_DIFFICULTY = 4+const MIN_POW_DIFFICULTY = 2+const MAX_POW_DIFFICULTY = 6// Challenge TTL in seconds (5 minutes)const CHALLENGE_TTL = 300+const CAPTCHA_COUNTER_PREFIX = 'captcha:auto'++type CaptchaDifficultyMode = 'manual' | 'auto'+type CaptchaEventName =+ | 'generate'+ | 'pass'+ | 'verify_fail'+ | 'validation_fail'+ | 'replay'++interface CaptchaHeaders {+ [key: string]: string | string[] | undefined+}++interface CaptchaDifficultyDecision {+ difficulty: number+ mode: CaptchaDifficultyMode+ reasons: string[]+ score: number+}++interface ChallengePayload {+ pid?: string+ difficulty: number+ difficultyMode?: CaptchaDifficultyMode+ autoReasons?: string[]+ issuedAt?: number+}++interface PowVerificationResult extends ChallengePayload {+ valid: boolean+ solveMs?: number+ failureReason?: string+}++interface CaptchaEventMeta {+ difficulty?: number+ difficultyMode?: CaptchaDifficultyMode+ autoReasons?: string[]+ solveMs?: number+ failureReason?: string+}export const DUMMY_PIDS = {ALWAYS_PASS: 'AP00000000000',@@ -56,6 +100,92 @@ const getChallengeCacheKey = (challenge: string): string => {return `pow_challenge:${challenge}`}+const clampDifficulty = (difficulty?: number | null): number => {+ if (!Number.isFinite(difficulty)) {+ return DEFAULT_POW_DIFFICULTY+ }++ return Math.min(+ MAX_POW_DIFFICULTY,+ Math.max(MIN_POW_DIFFICULTY, Number(difficulty)),+ )+}++const getHeaderValue = (+ headers: CaptchaHeaders | undefined,+ name: string,+): string => {+ const value = headers?.[name] ?? headers?.[name.toLowerCase()]+ if (Array.isArray(value)) {+ return value[0] || ''+ }++ return value ? String(value) : ''+}++const hasSuspiciousHeaders = (headers: CaptchaHeaders | undefined): boolean => {+ const required = ['accept', 'accept-language', 'accept-encoding']+ const missing = required.filter((header) => !getHeaderValue(headers, header))++ return missing.length >= 2+}++const hasHeadlessUserAgent = (headers: CaptchaHeaders | undefined): boolean => {+ return /HeadlessChrome|PhantomJS|SlimerJS|Selenium|WebDriver|Puppeteer|Playwright|Cypress|Nightmare|Splash/i.test(+ getHeaderValue(headers, 'user-agent'),+ )+}++const hashIP = (pid: string, ip: string): string => {+ return crypto+ .createHash('sha256')+ .update(`${pid}:${ip}`)+ .digest('hex')+ .slice(0, 16)+}++const getCounterKey = (+ pid: string,+ event: string,+ window: string,+ scope = 'project',+ bucket = 'all',+): string =>+ `${CAPTCHA_COUNTER_PREFIX}:${window}:${event}:${scope}:${pid}:${bucket}`++const incrCounter = async (key: string, ttl: number): Promise<number> => {+ const value = await redis.incr(key)++ if (value === 1) {+ await redis.expire(key, ttl)+ }++ return value+}++const getCounter = async (key: string): Promise<number> => {+ const value = await redis.get(key)+ const parsed = Number(value || 0)++ return Number.isFinite(parsed) ? parsed : 0+}++const consumeChallenge = async (cacheKey: string): Promise<string | null> => {+ const getdel = (redis as any).getdel++ if (typeof getdel === 'function') {+ return getdel.call(redis, cacheKey)+ }++ const result = await redis.eval(+ "local value = redis.call('GET', KEYS[1]); if value then redis.call('DEL', KEYS[1]); end; return value",+ 1,+ cacheKey,+ )++ return typeof result === 'string' ? result : null+}+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.@@ -113,8 +243,7 @@ export class CaptchaService {const project = await this.projectService.getRedisProject(pid)- // Use project's configured difficulty if available, otherwise default- return project?.captchaDifficulty || DEFAULT_POW_DIFFICULTY+ return clampDifficulty(project?.captchaDifficulty)}// validates pid, checks if captcha is enabled and throws an error otherwise@@ -136,14 +265,20 @@ export class CaptchaService {}}- async logCaptchaPass(+ private async logCaptchaEvent(pid: string,- headers: Record<string, string>,+ event: CaptchaEventName,+ headers: CaptchaHeaders,timestamp: number,ip: string,+ meta: CaptchaEventMeta = {},) {+ if (isDummyPID(pid)) {+ return+ }+const ua = await UAParser(- headers?.['user-agent'],+ getHeaderValue(headers, 'user-agent'),undefined,headers,).withClientHints()@@ -152,6 +287,30 @@ export class CaptchaService {const osName = ua.os.nameconst { country } = getIPDetails(ip)+ const eventMeta: Record<string, string> = {+ captcha_event: event,+ }++ if (meta.difficulty !== undefined) {+ eventMeta.captcha_difficulty = String(meta.difficulty)+ }++ if (meta.difficultyMode) {+ eventMeta.captcha_difficulty_mode = meta.difficultyMode+ }++ if (meta.autoReasons?.length) {+ eventMeta.captcha_reason = meta.autoReasons[0]+ }++ if (meta.solveMs !== undefined) {+ eventMeta.solve_ms = String(Math.max(0, Math.round(meta.solveMs)))+ }++ if (meta.failureReason) {+ eventMeta.failure_reason = meta.failureReason+ }+const transformed = eventTransformer({type: 'captcha',pid,@@ -159,6 +318,7 @@ export class CaptchaService {br: browserName,os: osName,cc: country,+ meta: eventMeta,timestamp,})@@ -176,6 +336,76 @@ export class CaptchaService {}}+ async logCaptchaPass(+ pid: string,+ headers: CaptchaHeaders,+ timestamp: number,+ ip: string,+ verification: PowVerificationResult,+ ) {+ await this.recordCaptchaOutcome(pid, 'pass', ip, verification)+ await this.logCaptchaEvent(pid, 'pass', headers, timestamp, ip, {+ difficulty: verification.difficulty,+ difficultyMode: verification.difficultyMode || 'manual',+ autoReasons: verification.autoReasons,+ solveMs: verification.solveMs,+ })+ }++ async logCaptchaFailure(+ pid: string,+ headers: CaptchaHeaders,+ timestamp: number,+ ip: string,+ verification: PowVerificationResult,+ ) {+ await this.recordCaptchaOutcome(pid, 'verify_fail', ip, verification)+ await this.logCaptchaEvent(pid, 'verify_fail', headers, timestamp, ip, {+ difficulty: verification.difficulty,+ difficultyMode: verification.difficultyMode || 'manual',+ autoReasons: verification.autoReasons,+ solveMs: verification.solveMs,+ failureReason: verification.failureReason || 'invalid_pow',+ })+ }++ async logCaptchaReplay(+ pid: string,+ headers: CaptchaHeaders,+ timestamp: number,+ ip: string,+ failureReason = 'expired_or_replayed',+ ) {+ await this.recordCaptchaOutcome(pid, 'replay', ip)+ await this.logCaptchaEvent(pid, 'replay', headers, timestamp, ip, {+ failureReason,+ })+ }++ private async recordCaptchaOutcome(+ pid: string,+ event: CaptchaEventName,+ ip: string,+ verification?: Partial<PowVerificationResult>,+ ) {+ if (isDummyPID(pid)) {+ return+ }++ const ipHash = ip ? hashIP(pid, ip) : 'unknown'+ const promises = [+ incrCounter(getCounterKey(pid, event, '5m'), 300),+ incrCounter(getCounterKey(pid, event, '15m'), 900),+ incrCounter(getCounterKey(pid, event, '5m', 'ip', ipHash), 300),+ ]++ if (verification?.solveMs !== undefined) {+ promises.push(incrCounter(getCounterKey(pid, 'solve', '5m'), 300))+ }++ await Promise.all(promises)+ }+async generateDummyToken() {return encryptString('DUMMY_TOKEN00000111112222233333444445555566666777778888899999',@@ -217,7 +447,12 @@ export class CaptchaService {return `${ciphertext}.${signature}`}- async validateToken(token: string, secretKey: string) {+ async validateToken(+ token: string,+ secretKey: string,+ headers: CaptchaHeaders = {},+ ip = '',+ ) {let parsedif (secretKey === DUMMY_SECRETS.ALWAYS_FAIL) {@@ -265,27 +500,60 @@ export class CaptchaService {typeof parsed.timestamp !== 'number' ||!Number.isFinite(parsed.timestamp)) {+ if (typeof parsed?.pid === 'string') {+ await this.logValidationFailure(+ parsed.pid,+ headers,+ ip,+ 'invalid_payload',+ )+ }+throw new BadRequestException('Invalid token payload')}- // Guard against obviously invalid pid values to reduce accidental misuse.if (!isDummyPID(parsed.pid) && !isValidPID(parsed.pid)) {+ await this.logValidationFailure(parsed.pid, headers, ip, 'invalid_pid')throw new BadRequestException('Invalid token payload')}if (dayjs().unix() * 1000 - parsed.timestamp > CAPTCHA_TOKEN_LIFETIME) {+ await this.logValidationFailure(parsed.pid, headers, ip, 'token_expired')throw new BadRequestException('Token expired')}const tokenUsed = await isTokenAlreadyUsed(token)if (tokenUsed) {+ await this.recordCaptchaOutcome(parsed.pid, 'replay', ip)+ await this.logValidationFailure(parsed.pid, headers, ip, 'token_replay')throw new BadRequestException('Token already used')}return parsed}+ private async logValidationFailure(+ pid: string,+ headers: CaptchaHeaders,+ ip: string,+ failureReason: string,+ ) {+ if (isDummyPID(pid) || !isValidPID(pid)) {+ return+ }++ await this.recordCaptchaOutcome(pid, 'validation_fail', ip)+ await this.logCaptchaEvent(+ pid,+ 'validation_fail',+ headers,+ dayjs.utc().unix() * 1000,+ ip,+ { failureReason },+ )+ }+// Generate SHA-256 hash of the inputsha256(input: string): string {return crypto.createHash('sha256').update(input).digest('hex')@@ -297,45 +565,147 @@ export class CaptchaService {return hash.startsWith(prefix)}- // Generate a PoW challenge- async generateChallenge(pid: string): Promise<GeneratedChallenge> {- const difficulty = await this._getProjectDifficulty(pid)+ private async selectDifficulty(+ pid: string,+ headers: CaptchaHeaders,+ ip: string,+ ): Promise<CaptchaDifficultyDecision> {+ const project = isDummyPID(pid)+ ? null+ : await this.projectService.getRedisProject(pid)+ const mode = (project?.captchaDifficultyMode ||+ 'manual') as CaptchaDifficultyMode+ const baseDifficulty = clampDifficulty(project?.captchaDifficulty)++ if (mode !== 'auto' || isDummyPID(pid)) {+ return {+ difficulty: baseDifficulty,+ mode: 'manual',+ reasons: ['manual'],+ score: 0,+ }+ }++ const { country, isHosting } = getIPDetails(ip)+ const countryBucket = country || 'xx'+ const ipHash = ip ? hashIP(pid, ip) : 'unknown'++ const [+ projectGenerate1m,+ projectGenerate5m,+ countryGenerate5m,+ ipGenerate1m,+ ] = await Promise.all([+ incrCounter(getCounterKey(pid, 'generate', '1m'), 60),+ incrCounter(getCounterKey(pid, 'generate', '5m'), 300),+ incrCounter(+ getCounterKey(pid, 'generate', '5m', 'country', countryBucket),+ 300,+ ),+ incrCounter(getCounterKey(pid, 'generate', '1m', 'ip', ipHash), 60),+ ])++ const [+ projectPass5m,+ projectFail5m,+ projectReplay5m,+ projectValidationFail5m,+ ipFail5m,+ ipReplay5m,+ ] = await Promise.all([+ getCounter(getCounterKey(pid, 'pass', '5m')),+ getCounter(getCounterKey(pid, 'verify_fail', '5m')),+ getCounter(getCounterKey(pid, 'replay', '5m')),+ getCounter(getCounterKey(pid, 'validation_fail', '5m')),+ getCounter(getCounterKey(pid, 'verify_fail', '5m', 'ip', ipHash)),+ getCounter(getCounterKey(pid, 'replay', '5m', 'ip', ipHash)),+ ])++ const reasons: string[] = []+ let score = 0+ const passRatio =+ projectGenerate5m > 0 ? projectPass5m / projectGenerate5m : 1+ const verifyAttempts = projectPass5m + projectFail5m+ const failRatio = verifyAttempts > 0 ? projectFail5m / verifyAttempts : 0++ const addRisk = (condition: boolean, reason: string, weight = 1) => {+ if (!condition) {+ return+ }++ score += weight+ reasons.push(reason)+ }++ addRisk(isHosting, 'hosting_ip')+ addRisk(hasHeadlessUserAgent(headers), 'headless_browser')+ addRisk(hasSuspiciousHeaders(headers), 'suspicious_headers')+ addRisk(projectGenerate1m >= 50, 'project_spike')+ addRisk(countryGenerate5m >= 50, 'country_spike')+ addRisk(ipGenerate1m >= 8, 'ip_pressure')+ addRisk(projectGenerate5m >= 30 && passRatio < 0.25, 'low_pass_ratio')+ addRisk(verifyAttempts >= 20 && failRatio > 0.35, 'verify_failures')+ addRisk(projectValidationFail5m >= 5, 'validation_failures')+ addRisk(projectReplay5m >= 2 || ipReplay5m >= 1, 'replay_attempts')+ addRisk(ipFail5m >= 3, 'ip_verify_failures')++ const adjustment = score >= 5 ? 2 : score >= 2 ? 1 : 0++ return {+ difficulty: clampDifficulty(baseDifficulty + adjustment),+ mode: 'auto',+ reasons: adjustment > 0 ? reasons.slice(0, 4) : ['baseline'],+ score,+ }+ }++ async generateChallenge(+ pid: string,+ headers: CaptchaHeaders = {},+ ip = '',+ ): Promise<GeneratedChallenge> {+ const decision = await this.selectDifficulty(pid, headers, ip)- // Generate a random challenge stringconst challenge = crypto.randomBytes(32).toString('hex')+ const issuedAt = dayjs.utc().unix() * 1000- // Store challenge in Redis with TTL to prevent replay attacks- // Include pid to prevent cross-project difficulty bypassconst cacheKey = getChallengeCacheKey(challenge)- const challengeData = JSON.stringify({ pid, difficulty })+ const challengeData = JSON.stringify({+ pid,+ difficulty: decision.difficulty,+ difficultyMode: decision.mode,+ autoReasons: decision.reasons,+ issuedAt,+ })await redis.set(cacheKey, challengeData, 'EX', CHALLENGE_TTL)+ await this.logCaptchaEvent(pid, 'generate', headers, issuedAt, ip, {+ difficulty: decision.difficulty,+ difficultyMode: decision.mode,+ autoReasons: decision.reasons,+ })+return {challenge,- difficulty,+ difficulty: decision.difficulty,}}- // Verify a PoW solutionasync verifyPoW(challenge: string,nonce: number,solution: string,pid: string,- ): Promise<boolean> {- // Check if challenge exists and hasn't been used+ ): Promise<PowVerificationResult> {const cacheKey = getChallengeCacheKey(challenge)- const storedData = await redis.get(cacheKey)+ const storedData = await consumeChallenge(cacheKey)if (!storedData) {throw new BadRequestException('Invalid or expired challenge')}- let difficulty: number- let storedPid: string | undefined+ let payload: ChallengePayload- // Parse stored data - support both old string format (difficulty only)- // and new JSON format (pid + difficulty) for backward compatibilitytry {const parsed = JSON.parse(storedData)if (@@ -343,50 +713,62 @@ export class CaptchaService {parsed !== null &&'difficulty' in parsed) {- difficulty = parsed.difficulty- storedPid = parsed.pid+ payload = parsed} else {- // Fallback: treat as raw difficulty number- difficulty = parseInt(storedData, 10)+ payload = { difficulty: parseInt(storedData, 10) }}} catch {- // Old format: just the difficulty as a string- difficulty = parseInt(storedData, 10)+ payload = { difficulty: parseInt(storedData, 10) }}- // Validate difficulty to prevent bypass via NaN or invalid values+ const difficulty = Number(payload.difficulty)+if (- typeof difficulty !== 'number' ||!Number.isFinite(difficulty) ||- difficulty < 1 ||- difficulty > 6+ difficulty < MIN_POW_DIFFICULTY ||+ difficulty > MAX_POW_DIFFICULTY) {throw new BadRequestException('Invalid challenge difficulty')}- // If the challenge was bound to a specific project, verify it matches- if (storedPid !== undefined && storedPid !== pid) {+ if (payload.pid !== undefined && payload.pid !== pid) {throw new BadRequestException('Challenge was issued for a different project',)}- // Compute the expected hashconst input = `${challenge}:${nonce}`const computedHash = this.sha256(input)+ const solveMs = payload.issuedAt+ ? dayjs.utc().unix() * 1000 - payload.issuedAt+ : undefined+ const resultBase = {+ difficulty,+ difficultyMode: payload.difficultyMode || 'manual',+ autoReasons: payload.autoReasons || [],+ issuedAt: payload.issuedAt,+ solveMs,+ }- // Verify the solution matches and has required prefixif (computedHash !== solution) {- return false+ return {+ ...resultBase,+ valid: false,+ failureReason: 'solution_mismatch',+ }}if (!this.hasValidPrefix(computedHash, difficulty)) {- return false+ return {+ ...resultBase,+ valid: false,+ failureReason: 'difficulty_mismatch',+ }}- // Mark challenge as used by deleting it- await redis.del(cacheKey)-- return true+ return {+ ...resultBase,+ valid: true,+ }}}diff --git a/backend/apps/community/src/captcha/dtos/validate.dto.ts b/backend/apps/community/src/captcha/dtos/validate.dto.tsindex 7652c2100..70857ec8c 100644--- a/backend/apps/community/src/captcha/dtos/validate.dto.ts+++ b/backend/apps/community/src/captcha/dtos/validate.dto.ts@@ -4,7 +4,7 @@ import { IsNotEmpty, IsString } from 'class-validator'export class ValidateDto {@ApiProperty({required: true,- description: 'Catpcha pass token',+ description: 'Captcha pass token',})@IsNotEmpty()@IsString()diff --git a/backend/apps/community/src/common/constants.ts b/backend/apps/community/src/common/constants.tsindex 96e924132..4c779973e 100644--- a/backend/apps/community/src/common/constants.ts+++ b/backend/apps/community/src/common/constants.ts@@ -27,7 +27,16 @@ const hash = (content: string): string => {// CAPTCHA related constantsconst CAPTCHA_TOKEN_LIFETIME = 300 * 1000 // milliseconds (5 minutes)const CAPTCHA_SECRET_KEY_LENGTH = 50-const CAPTCHA_COLUMNS = ['cc', 'br', 'os', 'dv']+const CAPTCHA_COLUMNS = [+ 'cc',+ 'br',+ 'os',+ 'dv',+ 'captcha_event',+ 'captcha_difficulty',+ 'captcha_reason',+ 'solve_time',+]// redis keys for captchaconst getRedisCaptchaKey = (token: string) => `captcha_${hash(token)}`diff --git a/backend/apps/community/src/common/utils.ts b/backend/apps/community/src/common/utils.tsindex 53d5f9f0a..1cac71d46 100644--- a/backend/apps/community/src/common/utils.ts+++ b/backend/apps/community/src/common/utils.ts@@ -132,6 +132,7 @@ const ALLOWED_KEYS = ['websiteUrl','captchaSecretKey','captchaDifficulty',+ 'captchaDifficultyMode','brandKeywords',]diff --git a/backend/apps/community/src/project/dto/update-project.dto.ts b/backend/apps/community/src/project/dto/update-project.dto.tsindex 8cfbbbde7..87f5a791c 100644--- a/backend/apps/community/src/project/dto/update-project.dto.ts+++ b/backend/apps/community/src/project/dto/update-project.dto.ts@@ -1,6 +1,6 @@import { IntersectionType, PartialType } from '@nestjs/mapped-types'import { ApiProperty } from '@nestjs/swagger'-import { IsInt, IsOptional, Max, Min } from 'class-validator'+import { IsIn, IsInt, IsOptional, Max, Min } from 'class-validator'import { ProjectDTO } from './project.dto'import { ProjectPasswordDto } from './project-password.dto'@@ -31,4 +31,15 @@ export class UpdateProjectDto extends IntersectionType(@Max(6)@IsOptional()captchaDifficulty?: number++ @ApiProperty({+ required: false,+ description:+ 'CAPTCHA difficulty mode. Manual uses captchaDifficulty directly; auto raises it dynamically when risk signals increase.',+ enum: ['manual', 'auto'],+ default: 'manual',+ })+ @IsIn(['manual', 'auto'])+ @IsOptional()+ captchaDifficultyMode?: 'manual' | 'auto'}diff --git a/backend/apps/community/src/project/entity/project.entity.ts b/backend/apps/community/src/project/entity/project.entity.tsindex cdd426f9a..077458f86 100644--- a/backend/apps/community/src/project/entity/project.entity.ts+++ b/backend/apps/community/src/project/entity/project.entity.ts@@ -4,6 +4,8 @@ export enum BotsProtectionLevel {STRICT = 'strict',}+type CaptchaDifficultyMode = 'manual' | 'auto'+export class Project {id: stringname: string@@ -23,6 +25,7 @@ export class Project {isCaptchaProject: booleancaptchaSecretKey?: stringcaptchaDifficulty?: number+ captchaDifficultyMode?: CaptchaDifficultyMode// Google Search Console integration fieldsgscPropertyUri?: string | nullgscAccessTokenEnc?: string | nulldiff --git a/backend/apps/community/src/project/project.controller.ts b/backend/apps/community/src/project/project.controller.tsindex 1c98b7939..07c4bdea2 100644--- a/backend/apps/community/src/project/project.controller.ts+++ b/backend/apps/community/src/project/project.controller.ts@@ -1060,25 +1060,22 @@ export class ProjectController {project.active = projectDTO.active}- if (projectDTO.origins) {- project.origins = _map(projectDTO.origins, _trim) as string[]- } else {- project.origins = []+ if (projectDTO.origins !== undefined) {+ project.origins = projectDTO.origins+ ? (_map(projectDTO.origins, _trim) as string[])+ : []}- if (projectDTO.ipBlacklist) {- project.ipBlacklist = _map(projectDTO.ipBlacklist, _trim) as string[]- } else {- project.ipBlacklist = []+ if (projectDTO.ipBlacklist !== undefined) {+ project.ipBlacklist = projectDTO.ipBlacklist+ ? (_map(projectDTO.ipBlacklist, _trim) as string[])+ : []}- if (projectDTO.countryBlacklist) {- project.countryBlacklist = _map(- projectDTO.countryBlacklist,- _trim,- ) as string[]- } else {- project.countryBlacklist = []+ if (projectDTO.countryBlacklist !== undefined) {+ project.countryBlacklist = projectDTO.countryBlacklist+ ? (_map(projectDTO.countryBlacklist, _trim) as string[])+ : []}if (projectDTO.botsProtectionLevel) {@@ -1111,6 +1108,10 @@ export class ProjectController {project.captchaDifficulty = projectDTO.captchaDifficulty}+ if (projectDTO.captchaDifficultyMode !== undefined) {+ project.captchaDifficultyMode = projectDTO.captchaDifficultyMode+ }+if (projectDTO.brandKeywords !== undefined) {project.brandKeywords = projectDTO.brandKeywords}diff --git a/backend/migrations/clickhouse/initialise_selfhosted.js b/backend/migrations/clickhouse/initialise_selfhosted.jsindex 2cbc4a48b..cd6f7c5a2 100644--- a/backend/migrations/clickhouse/initialise_selfhosted.js+++ b/backend/migrations/clickhouse/initialise_selfhosted.js@@ -38,6 +38,7 @@ const CLICKHOUSE_INIT_QUERIES = [isCaptchaProject Int8 DEFAULT 0,captchaSecretKey Nullable(String) CODEC(ZSTD(3)),captchaDifficulty UInt8 DEFAULT 4,+ captchaDifficultyMode String DEFAULT 'manual' CODEC(ZSTD(3)),gscPropertyUri Nullable(String) DEFAULT NULL CODEC(ZSTD(3)),gscAccessTokenEnc Nullable(String) DEFAULT NULL CODEC(ZSTD(3)),gscRefreshTokenEnc Nullable(String) DEFAULT NULL CODEC(ZSTD(3)),diff --git a/backend/migrations/clickhouse/selfhosted_2026_01_02_captcha.js b/backend/migrations/clickhouse/selfhosted_2026_01_02_captcha.jsindex 586ea290c..117facded 100644--- a/backend/migrations/clickhouse/selfhosted_2026_01_02_captcha.js+++ b/backend/migrations/clickhouse/selfhosted_2026_01_02_captcha.js@@ -5,6 +5,7 @@ const queries = [`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;`,+ `ALTER TABLE ${dbName}.project ADD COLUMN IF NOT EXISTS captchaDifficultyMode String DEFAULT 'manual' CODEC(ZSTD(3));`,// Create CAPTCHA analytics table (same structure as in initialise_database.js)`CREATE TABLE IF NOT EXISTS ${dbName}.captchadiff --git a/backend/migrations/clickhouse/selfhosted_2026_05_20_captcha_auto_difficulty.js b/backend/migrations/clickhouse/selfhosted_2026_05_20_captcha_auto_difficulty.jsnew file mode 100644index 000000000..2aa24c792--- /dev/null+++ b/backend/migrations/clickhouse/selfhosted_2026_05_20_captcha_auto_difficulty.js@@ -0,0 +1,7 @@+const { queriesRunner, dbName } = require('./setup')++const queries = [+ `ALTER TABLE ${dbName}.project ADD COLUMN IF NOT EXISTS captchaDifficultyMode String DEFAULT 'manual' CODEC(ZSTD(3));`,+]++queriesRunner(queries)diff --git a/backend/migrations/mysql/2026_05_20_captcha_auto_difficulty.sql b/backend/migrations/mysql/2026_05_20_captcha_auto_difficulty.sqlnew file mode 100644index 000000000..02821b461--- /dev/null+++ b/backend/migrations/mysql/2026_05_20_captcha_auto_difficulty.sql@@ -0,0 +1 @@+ALTER TABLE project ADD COLUMN `captchaDifficultyMode` enum('manual','auto') NOT NULL DEFAULT 'manual' AFTER `captchaDifficulty`;diff --git a/docs/content/docs/analytics-dashboard/captcha.mdx b/docs/content/docs/analytics-dashboard/captcha.mdxindex 311fdea2d..9276b35a5 100644--- a/docs/content/docs/analytics-dashboard/captcha.mdx+++ b/docs/content/docs/analytics-dashboard/captcha.mdx@@ -4,7 +4,7 @@ title: Captcha Analyticssidebar_label: Captcha Analytics----The Captcha Analytics dashboard provides detailed insights into how users are interacting with the Swetrix CAPTCHA on your website. It helps you monitor completion rates and understand the demographics of users solving your CAPTCHAs.+The Captcha Analytics dashboard provides detailed insights into how users are interacting with the Swetrix CAPTCHA on your website. It helps you monitor generation volume, pass rates, failures, replay attempts, solve time, selected difficulty, and the demographics of users solving your CAPTCHAs.<img alt="Captcha Dashboard" src="/docs/img/analytics-dashboard/captcha-view.png" />@@ -19,15 +19,24 @@ For more details on how Swetrix CAPTCHA works and how to integrate it, please re## Key Metrics-### Captcha Completions+### Captcha events-The main chart displays the **Captcha Completions** metric. This represents the number of times users have successfully solved the CAPTCHA challenge on your site within the selected timeframe.+The main chart displays CAPTCHA generations, successful passes, verification failures, validation failures, and replay attempts within the selected timeframe. Older CAPTCHA data that does not include event metadata is treated as successful passes.Visualising this data helps you:- Monitor traffic spikes that might indicate bot attacks.- Ensure the CAPTCHA is functioning correctly for legitimate users.- Correlate CAPTCHA completions with specific events or campaigns.+- Identify validation or replay issues in your backend integration.++### Auto difficulty++If Auto difficulty is enabled, the dashboard shows the selected difficulty distribution and the reason categories that caused Swetrix to raise the difficulty. These reason categories are intentionally coarse, such as hosting IP, project spike, country spike, replay attempts, verification failures, or low pass ratio.++### Solve time++Solve-time panels and summary values show how long successful challenges took from generation to verification. This helps you spot when a configured fallback difficulty is too aggressive for legitimate users.## Detailed Breakdown@@ -42,6 +51,9 @@ Below the main chart, you can find detailed panels that categorise the CAPTCHA c- **Browser**: Identify which web browsers are being used to solve CAPTCHAs.- **Operating System (OS)**: View the operating systems of your users.- **Device Type**: Breakdown by device category (e.g., Desktop, Mobile, Tablet).+- **Difficulty**: Chosen challenge difficulty distribution.+- **Auto difficulty reasons**: Coarse categories explaining why Auto raised difficulty.+- **Solve time**: Distribution of successful solve durations.## Filtering and Analysisdiff --git a/docs/content/docs/captcha/introduction.mdx b/docs/content/docs/captcha/introduction.mdxindex 951077878..10175bd29 100644--- a/docs/content/docs/captcha/introduction.mdx+++ b/docs/content/docs/captcha/introduction.mdx@@ -27,6 +27,15 @@ Unlike traditional CAPTCHAs that require users to identify objects in images orThis approach provides a seamless user experience (no more "select all traffic lights") while effectively deterring automated bots.+## Difficulty modes++CAPTCHA projects can use either **Manual** or **Auto** difficulty.++- **Manual** always uses the configured Proof of Work difficulty.+- **Auto** starts from the configured fallback difficulty and raises the challenge difficulty when privacy-safe risk signals increase, such as short-lived project traffic spikes, country-level spikes, replay attempts, validation failures, hosting IPs, suspicious headers, or low pass ratios.++Auto difficulty uses bounded Redis counters with short TTLs and stores only coarse analytics metadata such as the selected difficulty and the reason category that caused a raise. It does not store raw IP addresses in analytics.+<Callout type="info">You can find the demonstration of the CAPTCHA widget [here](https://swetrix.com/captcha/demo).</Callout>diff --git a/docs/content/docs/captcha/server-side-validation.mdx b/docs/content/docs/captcha/server-side-validation.mdxindex c9e93830d..2ace1f628 100644--- a/docs/content/docs/captcha/server-side-validation.mdx+++ b/docs/content/docs/captcha/server-side-validation.mdx@@ -7,7 +7,7 @@ slug: /captcha/server-side-validationYou have to validate the user's response to the CAPTCHA on your server. The token should be considered valid only if you validated it on your backend, otherwise it can be easily spoofed (the presence of the token in the request is not enough to consider it valid as an attacker can easily send a request with any string as a token).-The validation endpoint accepts the CAPTHCA token and your project-specific secret key and returns a JSON response with the validation result.+The validation endpoint accepts the CAPTCHA token and your project-specific secret key and returns a JSON response with the validation result.<Callout type="info">Token validation can only be performed once, if you try to validate the same token twice, the second validation will fail. This is done to prevent token reuse attacks.@@ -21,7 +21,7 @@ Token validation can only be performed once, if you try to validate the same tok</TabsList><TabsContent value="http">-To validate the token, you have to send a POST request to the `https://api.swetrix.com/v1/captcha/validate` URL, with the following parameters:+To validate the token, you have to send a POST request to the `https://api.swetrixcaptcha.com/v1/captcha/validate` URL, with the following parameters:| Parameter | Type | Description || --------- | ------ | ----------------------------------------- |@@ -30,17 +30,17 @@ To validate the token, you have to send a POST request to the `https://api.swetrThe successful response will have the `success` field set to `true` and the `data` field will contain the following fields:-| Field | Type | Description |-| --------- | ------ | ------------------------------------- |-| hash | string | The hash of CAPTCHA user passed. |-| timestamp | number | The timestamp of CAPTCHA user passed. |-| pid | string | The ID of the CAPTCHA project. |+| Field | Type | Description |+| --------- | ------ | ------------------------------------------------ |+| challenge | string | The challenge ID that was solved by the widget. |+| timestamp | number | The timestamp when the CAPTCHA token was issued. |+| pid | string | The ID of the CAPTCHA project. |```json{"success": true,"data": {- "hash": "HASH_12345678",+ "challenge": "CHALLENGE_12345678","timestamp": 1111111111,"pid": "PROJECTID123"}@@ -63,7 +63,7 @@ Here's an example of how to validate the token using `curl`:curl -X POST\-H "Content-Type: application/json"\-d '{"token": "<token>", "secret": "<secret>"}'\- https://api.swetrix.com/v1/captcha/validate+ https://api.swetrixcaptcha.com/v1/captcha/validate```</TabsContent>@@ -74,11 +74,11 @@ You can use the [@swetrix/captcha-validator](https://www.npmjs.com/package/@swetYou can use this package in your Node.js (or NestJS, ExpressJS, etc.) project to validate the user's response to the CAPTCHA.The package exports a single function `validateToken` which takes arguments listed below and returns a Promise.-| Argument | Type | Description | Required |-| --------- | ------ | ------------------------------------------------------------------------------------------------------------------------- | -------- |-| token | string | The token returned by the CAPTCHA widget. | YES |-| secretKey | string | Your CAPTCHA project secret key. | YES |-| apiURL | string | The API URL to use (default: `https://api.swetrix.com/captcha`), this one may be used in case you're selfhosting the API. | NO |+| Argument | Type | Description | Required |+| --------- | ------ | ----------------------------------------------------------------------------------------------------------------------------------- | -------- |+| token | string | The token returned by the CAPTCHA widget. | YES |+| secretKey | string | Your CAPTCHA project secret key. | YES |+| apiURL | string | The API URL to use (default: `https://api.swetrixcaptcha.com/v1/captcha`), this one may be used in case you're selfhosting the API. | NO |Here's an example of how to use the package in your project:diff --git a/packages/captcha-validator/README.md b/packages/captcha-validator/README.mdindex 38ceebb56..cea4b3c63 100644--- a/packages/captcha-validator/README.md+++ b/packages/captcha-validator/README.md@@ -18,7 +18,7 @@ The package exports a single function `validateToken` which takes arguments list| --- | --- | --- | --- || token | string | The token returned by the CAPTCHA widget. | YES || secretKey | string | Your CAPTCHA project secret key. | YES |-| apiURL | string | The API URL to use (default: https://api.swetrix.com/captcha), this one may be used in case you're selfhosting the API. | NO |+| apiURL | string | The API URL to use (default: https://api.swetrixcaptcha.com/v1/captcha), this one may be used in case you're selfhosting the API. | NO |Here's an example of how to use the package in your project:```jsdiff --git a/packages/captcha-validator/src/index.ts b/packages/captcha-validator/src/index.tsindex 13f2daea1..e95e48fe4 100644--- a/packages/captcha-validator/src/index.ts+++ b/packages/captcha-validator/src/index.ts@@ -5,7 +5,7 @@ import { makeAPIRequest, ENDPOINTS } from './utils'** @param {string | object} token The CAPTCHA token.* @param {string} secret The secret API key.- * @param {string | null} apiURL The API URL to use (default: https://api.swetrix.com/captcha).+ * @param {string | null} apiURL The API URL to use (default: https://api.swetrixcaptcha.com/v1/captcha).* @returns {Promise<[boolean, object | null]>} The result of the validation.*/export async function validateToken(token: string | any, secret: string, apiURL?: string): Promise<[boolean, object | string]> {diff --git a/packages/captcha-validator/src/utils.ts b/packages/captcha-validator/src/utils.tsindex 46ec0e89a..8ecc42bd1 100644--- a/packages/captcha-validator/src/utils.ts+++ b/packages/captcha-validator/src/utils.ts@@ -1,7 +1,7 @@import https from 'https'import http from 'http'-const DEFAULT_API_HOST = 'https://api.swetrix.com/v1/captcha'+const DEFAULT_API_HOST = 'https://api.swetrixcaptcha.com/v1/captcha'export const ENDPOINTS = {VALIDATE: '/validate',diff --git a/web/app/api/api.server.ts b/web/app/api/api.server.tsindex 780469c0a..b1e5beca9 100644--- a/web/app/api/api.server.ts+++ b/web/app/api/api.server.ts@@ -1535,11 +1535,33 @@ interface CaptchaPanelData {interface CaptchaChartData {x: string[]results: number[]+ generated?: number[]+ passed?: number[]+ failed?: number[]+ validationFailed?: number[]+ replayed?: number[]+}++interface CaptchaSummaryData {+ generated: number+ passed: number+ failed: number+ validationFailed: number+ replayed: number+ passRate: number+ failRate: number+ solveP50: number+ solveP75: number+ solveP95: number+ difficulty: CaptchaPanelData[]+ reasons: CaptchaPanelData[]+ solveTime: CaptchaPanelData[]}export interface CaptchaDataResponse {params: Record<string, CaptchaPanelData[]>chart?: CaptchaChartData+ summary?: CaptchaSummaryData}export async function getCaptchaDataServer(diff --git a/web/app/lib/models/Project.ts b/web/app/lib/models/Project.tsindex 184ddcc4e..a8d435f26 100644--- a/web/app/lib/models/Project.ts+++ b/web/app/lib/models/Project.ts@@ -230,6 +230,7 @@ export interface Project {public: booleancaptchaSecretKey: string | nullcaptchaDifficulty: number+ captchaDifficultyMode?: 'manual' | 'auto'created: stringshare?: ShareOwnerProject[]overall: OverallObjectdiff --git a/web/app/pages/Project/Settings/ProjectSettings.tsx b/web/app/pages/Project/Settings/ProjectSettings.tsxindex a40eb7925..ec04807ae 100644--- a/web/app/pages/Project/Settings/ProjectSettings.tsx+++ b/web/app/pages/Project/Settings/ProjectSettings.tsx@@ -548,7 +548,12 @@ const ProjectSettings = () => {const [captchaSecretKey, setCaptchaSecretKey] = useState<string | null>(() => initialProject.captchaSecretKey || null,)- const [captchaDifficulty, setCaptchaDifficulty] = useState<number>(4)+ const [captchaDifficulty, setCaptchaDifficulty] = useState<number>(+ () => initialProject.captchaDifficulty || 4,+ )+ const [captchaDifficultyMode, setCaptchaDifficultyMode] = useState<+ 'manual' | 'auto'+ >(() => initialProject.captchaDifficultyMode || 'manual')const [showRegenerateSecret, setShowRegenerateSecret] = useState(false)// for reset data via filters@@ -722,6 +727,12 @@ const ProjectSettings = () => {setProject((prev) =>prev ? { ...prev, ...updatedProject } : updatedProject,)+ if (updatedProject.captchaDifficulty) {+ setCaptchaDifficulty(updatedProject.captchaDifficulty)+ }+ if (updatedProject.captchaDifficultyMode) {+ setCaptchaDifficultyMode(updatedProject.captchaDifficultyMode)+ }}setBeenSubmitted(false)toast.success(t('project.settings.updated'))@@ -1421,9 +1432,56 @@ const ProjectSettings = () => {</div><div className='mt-6'>+ <Select+ label={t('project.settings.captcha.difficultyMode')}+ hint={t(+ 'project.settings.captcha.difficultyModeHint',+ )}+ className='mb-4 lg:w-1/2'+ hintClassName='lg:w-2/3'+ items={[+ {+ value: 'manual' as const,+ label: t(+ 'project.settings.captcha.difficultyModes.manual',+ ),+ },+ {+ value: 'auto' as const,+ label: t(+ 'project.settings.captcha.difficultyModes.auto',+ ),+ },+ ]}+ keyExtractor={(item) => item.value}+ labelExtractor={(item) => item.label}+ selectedItem={{+ value: captchaDifficultyMode,+ label: '',+ }}+ onSelect={(item: {+ value: 'manual' | 'auto'+ label: string+ }) => {+ setCaptchaDifficultyMode(item.value)+ }}+ title={+ captchaDifficultyMode === 'auto'+ ? t(+ 'project.settings.captcha.difficultyModes.auto',+ )+ : t(+ 'project.settings.captcha.difficultyModes.manual',+ )+ }+ /><Selectlabel={t('project.settings.captcha.difficulty')}- hint={t('project.settings.captcha.difficultyHint')}+ hint={+ captchaDifficultyMode === 'auto'+ ? t('project.settings.captcha.difficultyAutoHint')+ : t('project.settings.captcha.difficultyHint')+ }className='lg:w-1/2'hintClassName='lg:w-2/3'items={[@@ -1500,6 +1558,10 @@ const ProjectSettings = () => {'captchaDifficulty',captchaDifficulty.toString(),)+ formData.set(+ 'captchaDifficultyMode',+ captchaDifficultyMode,+ )fetcher.submit(formData, { method: 'post' })}}>diff --git a/web/app/pages/Project/View/ViewProject.helpers.tsx b/web/app/pages/Project/View/ViewProject.helpers.tsxindex 996080ad1..e5eeaa132 100644--- a/web/app/pages/Project/View/ViewProject.helpers.tsx+++ b/web/app/pages/Project/View/ViewProject.helpers.tsx@@ -2563,26 +2563,49 @@ export const getConnectionTypeLabel = (}) as stringconst getSettingsCaptcha = (- chart: { x: string[]; results: number[] },+ chart: {+ x: string[]+ results?: number[]+ generated?: number[]+ passed?: number[]+ failed?: number[]+ validationFailed?: number[]+ replayed?: number[]+ },timeBucket: string,timeFormat: string,rotateXAxis: boolean,chartType: string,): ChartOptions => {const xAxisSize = _size(chart.x)+ const series = [+ 'generated',+ 'passed',+ 'failed',+ 'validationFailed',+ 'replayed',+ ] as const+ const activeSeries = series.filter((key) => chart[key]?.length)+ const fallbackSeries: Array<+ | 'generated'+ | 'passed'+ | 'failed'+ | 'validationFailed'+ | 'replayed'+ | 'results'+ > = activeSeries.length ? [...activeSeries] : ['results']- // Build columns directly since getColumns doesn't handle 'results'const columns: any[] = [['x', ..._map(chart.x, (el) => dayjs(el).toDate())],- ['results', ...chart.results],+ ...fallbackSeries.map((key) => [key, ...(chart[key] || [])]),]const allYValues: number[] = []- if (chart.results) {+ fallbackSeries.forEach((key) => {allYValues.push(- ...chart.results.filter((n: any) => n !== undefined && n !== null),+ ...(chart[key] || []).filter((n: any) => n !== undefined && n !== null),)- }+ })const optimalTicks =allYValues.length > 0 ? calculateOptimalTicks(allYValues) : undefined@@ -2594,28 +2617,39 @@ const getSettingsCaptcha = (} else {regionStart = dayjs(chart.x[xAxisSize - 1]).toDate()}+ const regions = Object.fromEntries(+ fallbackSeries.map((key) => [+ key,+ [+ {+ start: regionStart,+ style: {+ dasharray: '6 2',+ },+ },+ ],+ ]),+ ) as anyreturn {data: {x: 'x',columns,- types: {- results: chartType === chartTypes.line ? area() : bar(),- },+ types: Object.fromEntries(+ fallbackSeries.map((key) => [+ key,+ chartType === chartTypes.line ? area() : bar(),+ ]),+ ),colors: {+ generated: '#2563eb',+ passed: '#16a34a',+ failed: '#dc2626',+ validationFailed: '#f97316',+ replayed: '#7c3aed',results: '#16a34a',},- regions: {- results: [- {- // @ts-expect-error- start: regionStart,- style: {- dasharray: '6 2',- },- },- ],- },+ regions,},grid: {y: {diff --git a/web/app/pages/Project/tabs/Captcha/CaptchaChart.tsx b/web/app/pages/Project/tabs/Captcha/CaptchaChart.tsxindex 527638f3b..2d6693e26 100644--- a/web/app/pages/Project/tabs/Captcha/CaptchaChart.tsx+++ b/web/app/pages/Project/tabs/Captcha/CaptchaChart.tsx@@ -7,7 +7,12 @@ import { getSettingsCaptcha } from '../../View/ViewProject.helpers'interface CaptchaChartProps {chart?: {x: string[]- results: number[]+ results?: number[]+ generated?: number[]+ passed?: number[]+ failed?: number[]+ validationFailed?: number[]+ replayed?: number[]}timeBucket: stringtimeFormat: stringdiff --git a/web/app/pages/Project/tabs/Captcha/CaptchaView.tsx b/web/app/pages/Project/tabs/Captcha/CaptchaView.tsxindex e48d0546b..638560651 100644--- a/web/app/pages/Project/tabs/Captcha/CaptchaView.tsx+++ b/web/app/pages/Project/tabs/Captcha/CaptchaView.tsx@@ -8,6 +8,10 @@ import {MonitorIcon,DevicesIcon,GlobeIcon,+ GaugeIcon,+ WarningIcon,+ ClockIcon,+ ShieldCheckIcon,} from '@phosphor-icons/react'import { useState, useEffect, useMemo, useContext, useRef } from 'react'import { useTranslation } from 'react-i18next'@@ -43,7 +47,16 @@ import { CaptchaChart } from './CaptchaChart'import NoCaptchaEvents from './NoCaptchaEvents'import WaitingForCaptchaEvent from './WaitingForCaptchaEvent'-const PANELS_ORDER = ['cc', 'br', 'os', 'dv']+const PANELS_ORDER = [+ 'captcha_event',+ 'captcha_difficulty',+ 'captcha_reason',+ 'solve_time',+ 'cc',+ 'br',+ 'os',+ 'dv',+]const iconClassName = 'w-6 h-6'const panelIconMapping: Record<string, React.ReactNode> = {@@ -51,6 +64,10 @@ const panelIconMapping: Record<string, React.ReactNode> = {dv: <DevicesIcon className={iconClassName} />,br: <CompassIcon className={iconClassName} />,os: <MonitorIcon className={iconClassName} />,+ captcha_event: <ShieldCheckIcon className={iconClassName} />,+ captcha_difficulty: <GaugeIcon className={iconClassName} />,+ captcha_reason: <WarningIcon className={iconClassName} />,+ solve_time: <ClockIcon className={iconClassName} />,}export const captchaTypeNameMapping = (t: any) => ({@@ -58,6 +75,10 @@ export const captchaTypeNameMapping = (t: any) => ({dv: t('project.mapping.dv'),br: t('project.mapping.br'),os: t('project.mapping.os'),+ captcha_event: t('project.mapping.captcha_event'),+ captcha_difficulty: t('project.mapping.captcha_difficulty'),+ captcha_reason: t('project.mapping.captcha_reason'),+ solve_time: t('project.mapping.solve_time'),})interface CaptchaViewProps {@@ -83,8 +104,14 @@ const CaptchaView = ({ projectId }: CaptchaViewProps) => {const [panelsData, setPanelsData] = useState<any>({})const [chartData, setChartData] = useState<{x: string[]- results: number[]+ results?: number[]+ generated?: number[]+ passed?: number[]+ failed?: number[]+ validationFailed?: number[]+ replayed?: number[]} | null>(null)+ const [summaryData, setSummaryData] = useState<any | null>(null)const [isPanelsDataEmpty, setIsPanelsDataEmpty] = useState(false)const [analyticsLoading, setAnalyticsLoading] = useState(true)const [dataLoading, setDataLoading] = useState(false)@@ -94,6 +121,11 @@ const CaptchaView = ({ projectId }: CaptchaViewProps) => {const dataNames = useMemo(() => ({results: t('project.captchaCompletions'),+ generated: t('project.captchaAnalytics.generated'),+ passed: t('project.captchaAnalytics.passed'),+ failed: t('project.captchaAnalytics.failed'),+ validationFailed: t('project.captchaAnalytics.validationFailed'),+ replayed: t('project.captchaAnalytics.replayed'),}),[t],)@@ -148,10 +180,11 @@ const CaptchaView = ({ projectId }: CaptchaViewProps) => {setDataLoading(false)setIsPanelsDataEmpty(true)setChartData(null)+ setSummaryData(null)return}- const { params, chart } = data+ const { params, chart, summary } = dataif (chart && chart.x && chart.results) {setChartData(chart)@@ -169,6 +202,7 @@ const CaptchaView = ({ projectId }: CaptchaViewProps) => {setIsPanelsDataEmpty(false)}+ setSummaryData(summary || null)setAnalyticsLoading(false)setDataLoading(false)} catch (reason) {@@ -177,6 +211,7 @@ const CaptchaView = ({ projectId }: CaptchaViewProps) => {setDataLoading(false)setIsPanelsDataEmpty(true)setChartData(null)+ setSummaryData(null)console.error('[ERROR](loadCaptcha) Loading captcha data failed:', reason)}}@@ -212,6 +247,45 @@ const CaptchaView = ({ projectId }: CaptchaViewProps) => {// Check if we have existing dataconst hasExistingData = chartData !== null || !_isEmpty(panelsData.types)+ const formatPercent = (value?: number) => `${Number(value || 0).toFixed(1)}%`+ const formatSeconds = (value?: number) =>+ value ? `${Number(value).toFixed(2)}s` : 'N/A'+ const formatReason = (value?: string | null) =>+ value+ ? t(`project.captchaAnalytics.reasons.${value}`, { defaultValue: value })+ : 'N/A'+ const summaryCards = summaryData+ ? [+ {+ label: t('project.captchaAnalytics.generated'),+ value: summaryData.generated || 0,+ },+ {+ label: t('project.captchaAnalytics.passRate'),+ value: formatPercent(summaryData.passRate),+ },+ {+ label: t('project.captchaAnalytics.failRate'),+ value: formatPercent(summaryData.failRate),+ },+ {+ label: t('project.captchaAnalytics.validationFailed'),+ value: summaryData.validationFailed || 0,+ },+ {+ label: t('project.captchaAnalytics.replayed'),+ value: summaryData.replayed || 0,+ },+ {+ label: t('project.captchaAnalytics.medianSolve'),+ value: formatSeconds(summaryData.solveP50),+ },+ {+ label: t('project.captchaAnalytics.topAutoReason'),+ value: formatReason(summaryData.reasons?.[0]?.name),+ },+ ]+ : []// Show waiting state if project has no captcha data yetif (!_isEmpty(project) && !project?.isCaptchaDataExists) {@@ -254,6 +328,23 @@ const CaptchaView = ({ projectId }: CaptchaViewProps) => {{dataLoading && hasExistingData ? <LoadingBar /> : null}<div><Filters className='mb-3' tnMapping={tnMapping} />+ {summaryCards.length ? (+ <div className='mb-3 grid grid-cols-2 gap-3 md:grid-cols-4 xl:grid-cols-7'>+ {summaryCards.map((card) => (+ <div+ key={card.label}+ className='rounded-lg border border-gray-200 bg-white p-3 dark:border-slate-800/60 dark:bg-slate-900/25'+ >+ <div className='text-xs font-medium text-gray-500 dark:text-gray-400'>+ {card.label}+ </div>+ <div className='mt-1 truncate text-lg font-semibold text-gray-900 dark:text-gray-50'>+ {card.value}+ </div>+ </div>+ ))}+ </div>+ ) : null}{chartData ? (<CaptchaChartchart={chartData}@@ -267,6 +358,10 @@ const CaptchaView = ({ projectId }: CaptchaViewProps) => {<div className='mt-3 grid grid-cols-1 gap-3 sm:grid-cols-2'>{!_isEmpty(panelsData.types)? _map(PANELS_ORDER, (type: keyof typeof tnMapping) => {+ if (_isEmpty(panelsData.data[type])) {+ return null+ }+const panelName = tnMapping[type]const panelIcon = panelIconMapping[type]@@ -411,6 +506,59 @@ const CaptchaView = ({ projectId }: CaptchaViewProps) => {)}+ if (type === 'captcha_event') {+ return (+ <Panel+ key={type}+ icon={panelIcon}+ id={type}+ getFilterLink={getFilterLink}+ name={panelName}+ data={panelsData.data[type]}+ rowMapper={(entry: any) =>+ t(`project.captchaAnalytics.events.${entry.name}`, {+ defaultValue: entry.name,+ })+ }+ activeTabId={type}+ />+ )+ }++ if (type === 'captcha_reason') {+ return (+ <Panel+ key={type}+ icon={panelIcon}+ id={type}+ getFilterLink={getFilterLink}+ name={panelName}+ data={panelsData.data[type]}+ rowMapper={(entry: any) => formatReason(entry.name)}+ activeTabId={type}+ />+ )+ }++ if (type === 'captcha_difficulty') {+ return (+ <Panel+ key={type}+ icon={panelIcon}+ id={type}+ getFilterLink={getFilterLink}+ name={panelName}+ data={panelsData.data[type]}+ rowMapper={(entry: any) =>+ t('project.captchaAnalytics.difficultyValue', {+ value: entry.name,+ })+ }+ activeTabId={type}+ />+ )+ }+return (<Panelkey={type}diff --git a/web/app/routes/projects.settings.$id.tsx b/web/app/routes/projects.settings.$id.tsxindex b650eac67..b38928c93 100644--- a/web/app/routes/projects.settings.$id.tsx+++ b/web/app/routes/projects.settings.$id.tsx@@ -111,8 +111,12 @@ export async function action({ request, params }: ActionFunctionArgs) {switch (intent) {case 'update-project': {const name = formData.get('name')?.toString()- const isPublic = formData.get('public') === 'true'- const isPasswordProtected = formData.get('isPasswordProtected') === 'true'+ const isPublic = formData.has('public')+ ? formData.get('public') === 'true'+ : undefined+ const isPasswordProtected = formData.has('isPasswordProtected')+ ? formData.get('isPasswordProtected') === 'true'+ : undefinedconst password = formData.get('password')?.toString()const origins = formData.get('origins')?.toString()const ipBlacklist = formData.get('ipBlacklist')?.toString()@@ -123,6 +127,9 @@ export async function action({ request, params }: ActionFunctionArgs) {const websiteUrl = formData.get('websiteUrl')?.toString()const brandKeywords = formData.get('brandKeywords')?.toString()const captchaDifficulty = formData.get('captchaDifficulty')?.toString()+ const captchaDifficultyMode = formData+ .get('captchaDifficultyMode')+ ?.toString()const fieldErrors: ProjectSettingsActionData['fieldErrors'] = {}@@ -139,8 +146,9 @@ export async function action({ request, params }: ActionFunctionArgs) {const updateData: Record<string, unknown> = {}if (name !== undefined) updateData.name = name- updateData.public = isPublic- updateData.isPasswordProtected = isPasswordProtected+ if (isPublic !== undefined) updateData.public = isPublic+ if (isPasswordProtected !== undefined)+ updateData.isPasswordProtected = isPasswordProtectedif (password !== undefined) updateData.password = passwordif (origins !== undefined)updateData.origins = origins@@ -166,6 +174,8 @@ export async function action({ request, params }: ActionFunctionArgs) {: nullif (captchaDifficulty !== undefined)updateData.captchaDifficulty = Number(captchaDifficulty)+ if (captchaDifficultyMode !== undefined)+ updateData.captchaDifficultyMode = captchaDifficultyModeconst result = await serverFetch<Project>(request, `project/${id}`, {method: 'PUT',diff --git a/web/app/ui/CaptchaSetup.tsx b/web/app/ui/CaptchaSetup.tsxindex 962ff641a..a06c1f038 100644--- a/web/app/ui/CaptchaSetup.tsx+++ b/web/app/ui/CaptchaSetup.tsx@@ -37,12 +37,12 @@ const getWidgetSnippet = (pid: string) =>`<div class="swecaptcha" data-project-id="${pid}"></div>`const getValidationSnippet = () =>- `const response = await fetch('https://api.swetrixcaptcha.com/v1/captcha/verify', {+ `const response = await fetch('https://api.swetrixcaptcha.com/v1/captcha/validate', {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({+ token: captchaToken,secret: 'YOUR_SECRET_KEY',- response: captchaToken,}),})diff --git a/web/public/locales/en.json b/web/public/locales/en.jsonindex ddcf7fb0c..509dddc63 100644--- a/web/public/locales/en.json+++ b/web/public/locales/en.json@@ -1688,6 +1688,38 @@},"passwordProtectedHint": "Please enter the password to view this dashboard.","captchaCompletions": "CAPTCHA completions",+ "captchaAnalytics": {+ "generated": "Generated",+ "passed": "Passed",+ "failed": "Failed",+ "validationFailed": "Validation failed",+ "replayed": "Replayed",+ "passRate": "Pass rate",+ "failRate": "Fail rate",+ "medianSolve": "Median solve",+ "topAutoReason": "Top Auto reason",+ "difficultyValue": "Difficulty {{value}}",+ "events": {+ "generate": "Generated",+ "pass": "Passed",+ "verify_fail": "Verification failed",+ "validation_fail": "Validation failed",+ "replay": "Replay"+ },+ "reasons": {+ "hosting_ip": "Hosting IP",+ "headless_browser": "Headless browser",+ "suspicious_headers": "Suspicious headers",+ "project_spike": "Project spike",+ "country_spike": "Country spike",+ "ip_pressure": "IP pressure",+ "low_pass_ratio": "Low pass ratio",+ "verify_failures": "Verification failures",+ "validation_failures": "Validation failures",+ "replay_attempts": "Replay attempts",+ "ip_verify_failures": "IP verification failures"+ }+ },"addAnnotation": "Add annotation","editAnnotation": "Edit annotation","deleteAnnotation": "Delete annotation",@@ -1925,7 +1957,11 @@"ut": "Usage type","ctp": "Connection type","searchEngine": "Search engine",- "aiReferral": "AI referral"+ "aiReferral": "AI referral",+ "captcha_event": "CAPTCHA events",+ "captcha_difficulty": "Difficulty",+ "captcha_reason": "Auto difficulty reasons",+ "solve_time": "Solve time"},"usageTypeMapping": {"business": "Business",@@ -2252,8 +2288,15 @@"regenerateKeyWarning": "Are you sure you want to regenerate the secret key? This will invalidate the current key and all applications using it will need to be updated.","noKeyGenerated": "No secret key has been generated yet. Generate one to enable CAPTCHA for this project.","learnMore": "Use this secret key in your backend to verify CAPTCHA tokens. Learn more in our documentation.",+ "difficultyMode": "Difficulty mode",+ "difficultyModeHint": "Manual always uses the selected difficulty. Auto starts from the selected fallback and raises difficulty when risk signals increase.",+ "difficultyModes": {+ "manual": "Manual",+ "auto": "Auto"+ },"difficulty": "CAPTCHA difficulty","difficultyHint": "Higher difficulty levels provide better bot protection but may be more challenging for users to solve.",+ "difficultyAutoHint": "Auto uses this as the fallback difficulty, then raises it for traffic spikes, replay attempts, hosting IPs, and other risk signals.","difficultyLevels": {"veryEasy": "Very easy","easy": "Easy",