📈 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
added some validation
Blue Mouse25ec86d70eae
diff --git a/src/captcha/captcha.controller.ts b/src/captcha/captcha.controller.tsindex 26eaf3cb5..14c2b0fe1 100644--- a/src/captcha/captcha.controller.ts+++ b/src/captcha/captcha.controller.ts@@ -2,15 +2,22 @@ import {Controller, Post, Body, UseGuards, ForbiddenException, InternalServerErrorException,Headers, Ip, Request, Req, Response, Res, HttpCode, Get,} from '@nestjs/common'+import * as dayjs from 'dayjs'+import * as utc from 'dayjs/plugin/utc'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'import { ManualDTO } from './dtos/manual.dto'+import { ValidateDTO } from './dtos/validate.dto'++dayjs.extend(utc)const CAPTCHA_COOKIE_KEY = 'swetrix-captcha-token'+const TEST_PUBLIC_KEY = 'test'+@Controller({version: '1',path: 'captcha',@@ -59,37 +66,22 @@ export class CaptchaController {}}- console.log(decrypted)-const {manuallyVerified, automaticallyVerified,} = this.captchaService.incrementManuallyVerified(decrypted)const newTokenCookie = this.captchaService.getTokenCaptcha(manuallyVerified, automaticallyVerified)+ this.captchaService.setTokenCookie(response, newTokenCookie)- // Set the new cookie- if (isDevelopment) {- // @ts-ignore- response.cookie(CAPTCHA_COOKIE_KEY, newTokenCookie, {- httpOnly: true,- // 300 days- maxAge: 300 * 24 * 60 * 60 * 1000,- })- } else {- // @ts-ignore- response.cookie(CAPTCHA_COOKIE_KEY, newTokenCookie, {- httpOnly: true,- secure: true,- sameSite: 'none',- // 300 days- maxAge: 300 * 24 * 60 * 60 * 1000,- })- }+ const timestamp = dayjs.utc().unix()++ const token = this.captchaService.generateToken(TEST_PUBLIC_KEY, hash, timestamp, false)- // TODO: return tokenreturn {success: true,- token: 'token',+ token,+ timestamp,+ hash,}}@@ -102,7 +94,7 @@ export class CaptchaController {@Res({ passthrough: true }) response: Response,): Promise<any> {// @ts-ignore- const tokenCookie = request?.cookies?.[CAPTCHA_COOKIE_KEY]+ let tokenCookie = request?.cookies?.[CAPTCHA_COOKIE_KEY]let verifiable@@ -114,41 +106,58 @@ export class CaptchaController {// Set a new cookietry {- newTokenCookie = await this.captchaService.getTokenCaptcha()+ newTokenCookie = this.captchaService.getTokenCaptcha()} catch (e) {console.error(e)throw new InternalServerErrorException('Could not generate a captcha cookie')}- if (isDevelopment) {- // @ts-ignore- response.cookie(CAPTCHA_COOKIE_KEY, newTokenCookie, {- httpOnly: true,- // 300 days- maxAge: 300 * 24 * 60 * 60 * 1000,- })- } else {- // @ts-ignore- response.cookie(CAPTCHA_COOKIE_KEY, newTokenCookie, {- httpOnly: true,- secure: true,- sameSite: 'none',- // 300 days- maxAge: 300 * 24 * 60 * 60 * 1000,- })- }+ tokenCookie = newTokenCookie++ this.captchaService.setTokenCookie(response, newTokenCookie)}if (!verifiable) {throw new ForbiddenException('Captcha required')}- // TODO: Increase auto+ let decrypted++ try {+ decrypted = await this.captchaService.decryptTokenCaptcha(tokenCookie)+ } catch (e) {+ throw new InternalServerErrorException('Could not decrypt captcha cookie')+ }++ const {+ manuallyVerified, automaticallyVerified,+ } = this.captchaService.incrementAutomaticallyVerified(decrypted)++ const newTokenCookie = this.captchaService.getTokenCaptcha(manuallyVerified, automaticallyVerified)++ this.captchaService.setTokenCookie(response, newTokenCookie)++ const timestamp = dayjs.utc().unix()++ const token = this.captchaService.generateToken(TEST_PUBLIC_KEY, null, timestamp, true)- // TODO: return tokenreturn {success: true,- token: 'token',+ token,+ timestamp,+ hash: null,}}++ @Post('/validate')+ @HttpCode(200)+ async validateToken(+ @Body() validateDTO: ValidateDTO,+ ): Promise<any> {+ const {+ token, secret, hash, timestamp,+ } = validateDTO++ return this.captchaService.validateToken(token, secret, hash, timestamp)+ }}diff --git a/src/captcha/captcha.service.ts b/src/captcha/captcha.service.tsindex bf2a48852..b04bf9e9b 100644--- a/src/captcha/captcha.service.ts+++ b/src/captcha/captcha.service.ts@@ -1,5 +1,5 @@import {- Injectable,+ Injectable, BadRequestException,} from '@nestjs/common'import * as svgCaptcha from 'svg-captcha'import * as CryptoJS from 'crypto-js'@@ -7,6 +7,8 @@ import { hash } from 'blake3'import * as _toLower from 'lodash/toLower'import * as _toUpper from 'lodash/toUpper'+import { isDevelopment } from '../common/constants'+import {CAPTCHA_SALT, CAPTCHA_ENCRYPTION_KEY,} from '../common/constants'@@ -35,13 +37,50 @@ const MANUAL_WEIGHT = 2const AUTO_WEIGHT = 1const THRESHOLD = 1.5+// 300 days+const COOKIE_MAX_AGE = 300 * 24 * 60 * 60 * 1000++const TEST_SECRET_KEY = 'wfOw1Jw3JAjcrHaQFvIvBS4qdG'+@Injectable()export class CaptchaService {constructor() { }+ generateToken(publicKey: string, hash: string, timestamp: number, autoVerified: boolean): string {+ // todo: lookup the secret key from the public key in the database+ const secretKey = TEST_SECRET_KEY++ const token = {+ hash, timestamp, autoVerified,+ }++ return encryptString(JSON.stringify(token), secretKey)+ }++ validateToken(token: string, secretKey: string, hash: string, timestamp: number): boolean {+ let parsed++ try {+ const decrypted = decryptString(token, secretKey)+ parsed = JSON.parse(decrypted)+ } catch (e) {+ throw new BadRequestException('Could not decrypt token')+ }++ if (!parsed.autoVerified && parsed.hash !== hash) {+ throw new BadRequestException('Token: captcha pass hash does not match')+ }++ if (parsed.timestamp !== timestamp) {+ throw new BadRequestException('Token: timestamp does not match')+ }++ return true+ }+hashCaptcha(text: string): string {- return hash(`${text}${CAPTCHA_SALT}`).toString('hex')+ return encryptString(`${text}${CAPTCHA_SALT}`, CAPTCHA_ENCRYPTION_KEY)}async generateCaptcha(): Promise<GeneratedCaptcha> {@@ -50,7 +89,11 @@ export class CaptchaService {ignoreChars: '0o1il',noise: 2,})- const hash = this.hashCaptcha(captcha.text)+ const hash = this.hashCaptcha(+ _toLower(captcha.text)+ )++ console.log(captcha.text, hash)return {data: captcha.data,@@ -60,7 +103,8 @@ export class CaptchaService {verifyCaptcha(text: string, hash: string): boolean {// Checking for both lower, upper case and the original text- return hash === this.hashCaptcha(text) || hash === this.hashCaptcha(_toLower(text)) || hash === this.hashCaptcha(_toUpper(text))+ // return hash === this.hashCaptcha(text) || hash === this.hashCaptcha(_toLower(text)) || hash === this.hashCaptcha(_toUpper(text))+ return text === _toLower(decryptString(hash, CAPTCHA_ENCRYPTION_KEY))}incrementManuallyVerified(tokenCaptcha: TokenCaptcha): TokenCaptcha {@@ -99,7 +143,7 @@ export class CaptchaService {}}- async getTokenCaptcha(manuallyVerified: number = 0, automaticallyVerified: number = 0): Promise<string> {+ getTokenCaptcha(manuallyVerified: number = 0, automaticallyVerified: number = 0): string {const tokenCaptcha: TokenCaptcha = {manuallyVerified,automaticallyVerified,@@ -120,4 +164,22 @@ export class CaptchaService {return this.canPassWithoutVerification(tokenCaptcha)}++ setTokenCookie(response: any, tokenCookie: string): void {+ if (isDevelopment) {+ // @ts-ignore+ response.cookie(CAPTCHA_COOKIE_KEY, tokenCookie, {+ httpOnly: true,+ maxAge: COOKIE_MAX_AGE,+ })+ } else {+ // @ts-ignore+ response.cookie(CAPTCHA_COOKIE_KEY, tokenCookie, {+ httpOnly: true,+ secure: true,+ sameSite: 'none',+ maxAge: COOKIE_MAX_AGE,+ })+ }+ }}diff --git a/src/captcha/dtos/manual.dto.ts b/src/captcha/dtos/manual.dto.tsindex 6a0c764dd..9b32ea7bd 100644--- a/src/captcha/dtos/manual.dto.ts+++ b/src/captcha/dtos/manual.dto.ts@@ -6,7 +6,7 @@ export class ManualDTO {required: true,})@IsNotEmpty()- hash?: string+ hash: string@ApiProperty({required: true,@@ -14,5 +14,5 @@ export class ManualDTO {description: 'Captcha code',})@IsNotEmpty()- code?: string+ code: string}diff --git a/src/captcha/dtos/validate.dto.ts b/src/captcha/dtos/validate.dto.tsnew file mode 100644index 000000000..7d12bf091--- /dev/null+++ b/src/captcha/dtos/validate.dto.ts@@ -0,0 +1,32 @@+import { ApiProperty } from '@nestjs/swagger'+import { IsNotEmpty } from 'class-validator'++export class ValidateDTO {+ @ApiProperty({+ required: true,+ description: 'Catpcha pass token',+ })+ @IsNotEmpty()+ token: string++ @ApiProperty({+ required: true,+ description: 'Secret API key',+ })+ @IsNotEmpty()+ secret: string++ @ApiProperty({+ required: false,+ description: 'Captcha hash (if available)',+ })+ @IsNotEmpty()+ hash?: string++ @ApiProperty({+ required: true,+ description: 'Captcha pass timestamp',+ })+ @IsNotEmpty()+ timestamp: number+}