Skip to content

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

added GET auto-verifiable endpoint

Blue Mouse943856588e96
diff --git a/.env.example b/.env.example
index adfc0a865..99d258930 100644
--- a/.env.example
+++ b/.env.example
@@ -53,3 +53,4 @@ CDN_ACCESS_TOKEN=SOME_SECRET_TOKEN
# Captcha API
CAPTCHA_SALT=
+CAPTCHA_ENCRYPTION_KEY=
diff --git a/src/captcha/captcha.controller.ts b/src/captcha/captcha.controller.ts
index 797c2ed9c..c6a70801b 100644
--- a/src/captcha/captcha.controller.ts
+++ b/src/captcha/captcha.controller.ts
@@ -1,9 +1,15 @@
import {
- Controller, Post, Body, UseGuards, ForbiddenException, InternalServerErrorException, Headers, Ip, Request, Req,
+ Controller, Post, Body, UseGuards, ForbiddenException, InternalServerErrorException,
+ Headers, Ip, Request, Req, Response, Res, HttpCode, Get,
} from '@nestjs/common'
+import { ApiResponse } from '@nestjs/swagger'
+
import { CaptchaService } from './captcha.service'
import { BotDetectionGuard } from '../common/guards/bot-detection.guard'
import { BotDetection } from '../common/decorators/bot-detection.decorator'
+import { isDevelopment } from '../common/constants'
+
+const CAPTCHA_COOKIE_KEY = 'swetrix-captcha-token'
@Controller({
version: '1',
@@ -14,21 +20,46 @@ export class CaptchaController {
private readonly captchaService: CaptchaService,
) { }
-
- @Post('/auto-verify')
+ @Get('/auto-verifiable')
+ @HttpCode(204)
@UseGuards(BotDetectionGuard)
@BotDetection()
- async logCustom(
- @Body() eventsDTO: EventsDTO,
- @Headers() headers,
- @Req() request: Request
- @Ip() reqIP,
+ @ApiResponse({ status: 204, description: 'Empty body' })
+ async autoVerifiable(
+ @Req() request: Request,
+ @Res({ passthrough: true }) response: Response,
): Promise<any> {
- // request.cookies['cookieKey']
- const { 'user-agent': userAgent, origin } = headers
+ // @ts-ignore
+ const tokenCookie = request?.cookies?.[CAPTCHA_COOKIE_KEY]
+ let verifiable
+
+ try {
+ verifiable = await this.captchaService.autoVerifiable(tokenCookie)
+ } catch (e) {
+ // Either there was no cookie or the cookie was invalid
+
+ // Set a new cookie
+ const newTokenCookie = await this.captchaService.setTokenCaptcha()
+
+ if (isDevelopment) {
+ console.log('New captcha cookie:', newTokenCookie)
- const ip = headers['cf-connecting-ip'] || headers['x-forwarded-for'] || reqIP || ''
+ // @ts-ignore
+ response.cookie(CAPTCHA_COOKIE_KEY, newTokenCookie, {
+ httpOnly: true,
+ })
+ } else {
+ // @ts-ignore
+ response.cookie(CAPTCHA_COOKIE_KEY, newTokenCookie, {
+ httpOnly: true,
+ secure: true,
+ sameSite: 'none',
+ })
+ }
+ }
- // await this.analyticsService.validate(eventsDTO, origin, 'custom', ip)
+ if (!verifiable) {
+ throw new ForbiddenException('Captcha required')
+ }
}
}
diff --git a/src/captcha/captcha.service.ts b/src/captcha/captcha.service.ts
index e4382bd19..2a1cdb896 100644
--- a/src/captcha/captcha.service.ts
+++ b/src/captcha/captcha.service.ts
@@ -3,14 +3,50 @@ import {
} from '@nestjs/common'
import * as svgCaptcha from 'svg-captcha'
import { hash } from 'blake3'
+import * as crypto from 'crypto'
+import { promisify } from 'util'
-import { CAPTCHA_SALT } from '../common/constants'
+import {
+ CAPTCHA_SALT, CAPTCHA_ENCRYPTION_KEY,
+} from '../common/constants'
interface GeneratedCaptcha {
data: string
hash: string
}
+interface TokenCaptcha {
+ manuallyVerified: number
+ automaticallyVerified: number
+}
+
+// Encrypts a string using ChaCha20 algorithm with a given key
+function encryptString(str: string, key: string | undefined = CAPTCHA_ENCRYPTION_KEY): string {
+ const iv = crypto.randomBytes(12)
+ const cipher = crypto.createCipheriv('chacha20', key, iv)
+ const encrypted = Buffer.concat([cipher.update(str, 'utf8'), cipher.final()])
+ return Buffer.concat([iv, encrypted]).toString('hex')
+}
+
+// Decrypts an encrypted string using ChaCha20 algorithm with a given key
+function decryptString(encryptedStr: string, key: string | undefined = CAPTCHA_ENCRYPTION_KEY): string {
+ const input = Buffer.from(encryptedStr, 'hex')
+ const iv = input.slice(0, 12)
+ const encrypted = input.slice(12)
+ const decipher = crypto.createDecipheriv('chacha20', key, iv)
+ const decrypted = Buffer.concat([decipher.update(encrypted), decipher.final()])
+ return decrypted.toString('utf8')
+}
+
+// Promisify the encryption and decryption functions
+const encryptStringAsync = promisify(encryptString)
+const decryptStringAsync = promisify(decryptString)
+
+// Set the weights for the manual and automatic verifications
+const MANUAL_WEIGHT = 2
+const AUTO_WEIGHT = 1
+const THRESHOLD = 1.5
+
@Injectable()
export class CaptchaService {
constructor(
@@ -35,9 +71,61 @@ export class CaptchaService {
return hashedText === hash
}
- async autoVerify(jwtCookie: string | undefined): Promise<boolean> {
- // TODO
+ incrementManuallyVerified(tokenCaptcha: TokenCaptcha): TokenCaptcha {
+ return {
+ ...tokenCaptcha,
+ manuallyVerified: 1 + tokenCaptcha.manuallyVerified,
+ }
+ }
+
+ incrementAutomaticallyVerified(tokenCaptcha: TokenCaptcha): TokenCaptcha {
+ return {
+ ...tokenCaptcha,
+ automaticallyVerified: 1 + tokenCaptcha.automaticallyVerified,
+ }
+ }
+
+ private async canPassWithoutVerification(tokenCaptcha: TokenCaptcha): Promise<boolean> {
+ const { manuallyVerified, automaticallyVerified } = tokenCaptcha
+
+ // Calculate the weighted average of the manual and automatic verifications
+ const weightedAverage = (MANUAL_WEIGHT * manuallyVerified + AUTO_WEIGHT * automaticallyVerified) /
+ (MANUAL_WEIGHT + AUTO_WEIGHT)
+
+ // If the weighted average is above a certain threshold, the user can pass without verification
+ return weightedAverage >= THRESHOLD
+ }
+
+ async decryptTokenCaptcha(jwtCookie: string | undefined): Promise<TokenCaptcha> {
+ const decryptedtokenCaptcha = await decryptStringAsync(jwtCookie, CAPTCHA_ENCRYPTION_KEY)
+
+ try {
+ // @ts-ignore
+ return JSON.parse(decryptedtokenCaptcha)
+ } catch (e) {
+ throw new Error('Invalid JWT captcha')
+ }
+ }
+
+ async setTokenCaptcha(manuallyVerified: number = 0, automaticallyVerified: number = 0): Promise<string> {
+ const tokenCaptcha: TokenCaptcha = {
+ manuallyVerified,
+ automaticallyVerified,
+ }
+
+ // @ts-ignore
+ const encryptedtokenCaptcha: string = await encryptStringAsync(JSON.stringify(tokenCaptcha), CAPTCHA_ENCRYPTION_KEY)
+
+ return encryptedtokenCaptcha
+ }
+
+ async autoVerifiable(tokenCookie: string | undefined): Promise<boolean> {
+ if (!tokenCookie) {
+ throw new Error('No JWT captcha cookie')
+ }
+
+ const tokenCaptcha: TokenCaptcha = await this.decryptTokenCaptcha(tokenCookie)
- return false
+ return this.canPassWithoutVerification(tokenCaptcha)
}
}
diff --git a/src/common/constants.ts b/src/common/constants.ts
index ddeee21d3..717792a1c 100644
--- a/src/common/constants.ts
+++ b/src/common/constants.ts
@@ -40,6 +40,7 @@ const clickhouse = new ClickHouse({
const isSelfhosted = Boolean(process.env.SELFHOSTED)
const isNewRelicEnabled = Boolean(process.env.USE_NEW_RELIC)
+const isDevelopment = process.env.NODE_ENV === 'development'
const CLICKHOUSE_INIT_QUERIES = [
'CREATE DATABASE IF NOT EXISTS analytics',
@@ -173,7 +174,9 @@ const REDIS_PROJECTS_COUNT_KEY = 'stats:projects_count'
const REDIS_PAGEVIEWS_COUNT_KEY = 'stats:pageviews'
const REDIS_PERFORMANCE_COUNT_KEY = 'stats:performance'
+// Captcha service
const CAPTCHA_SALT = process.env.CAPTCHA_SALT
+const CAPTCHA_ENCRYPTION_KEY = process.env.CAPTCHA_ENCRYPTION_KEY
// 3600 sec -> 1 hour
const redisProjectCacheTimeout = 3600
@@ -229,4 +232,6 @@ export {
REDIS_LOG_PERF_CACHE_KEY,
REDIS_PERFORMANCE_COUNT_KEY,
CAPTCHA_SALT,
+ CAPTCHA_ENCRYPTION_KEY,
+ isDevelopment,
}