Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions .env.sample
Original file line number Diff line number Diff line change
Expand Up @@ -249,3 +249,12 @@

# Maximum number of requests allowed in half-open state
# CIRCUIT_BREAKER_HALF_OPEN_MAX_REQUESTS=

# Captcha
# Enable Captcha for the API
# CAPTCHA_ENABLED=
# Test values for TURNSTILE_SECRET_KEY:
# 1x0000000000000000000000000000000AA Always passes validation Test successful token validation
# 2x0000000000000000000000000000000AA Always fails validation Test validation error handling
# 3x0000000000000000000000000000000AA Returns "token already spent" error Test duplicate token handling
# TURNSTILE_SECRET_KEY=
4 changes: 4 additions & 0 deletions src/config/entities/configuration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -659,6 +659,10 @@ export default () => ({
},
},
},
captcha: {
enabled: process.env.CAPTCHA_ENABLED?.toLowerCase() === 'true',
secretKey: process.env.TURNSTILE_SECRET_KEY,
},
});

// Helper function to parse relay rules from environment variable
Expand Down
2 changes: 2 additions & 0 deletions src/config/entities/schemas/configuration.schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,8 @@ export const RootConfigurationSchema = z
CSV_EXPORT_QUEUE_CONCURRENCY: z.coerce.number().min(1).optional(),
BLOCKAID_CLIENT_API_KEY: z.string().optional(),
TX_SERVICE_API_KEY: z.string().trim().min(1).optional(),
CAPTCHA_ENABLED: z.string().optional().default('false'),
TURNSTILE_SECRET_KEY: z.string().optional(),
})
.superRefine((config, ctx) =>
// Check for AWS_* and Blockaid fields in production and staging environments
Expand Down
3 changes: 2 additions & 1 deletion src/modules/owners/owners.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,10 @@ import { OwnersControllerV2 } from '@/modules/owners/routes/owners.controller.v2
import { OwnersControllerV3 } from '@/modules/owners/routes/owners.controller.v3';
import { OwnersService } from '@/modules/owners/routes/owners.service';
import { SafeRepositoryModule } from '@/modules/safe/domain/safe.repository.interface';
import { CaptchaModule } from '@/routes/captcha/captcha.module';

@Module({
imports: [SafeRepositoryModule],
imports: [SafeRepositoryModule, CaptchaModule],
controllers: [OwnersControllerV1, OwnersControllerV2, OwnersControllerV3],
providers: [OwnersService],
})
Expand Down
4 changes: 3 additions & 1 deletion src/modules/owners/routes/owners.controller.v2.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Controller, Get, Param } from '@nestjs/common';
import { Controller, Get, Param, UseGuards } from '@nestjs/common';
import {
ApiOkResponse,
ApiTags,
Expand All @@ -9,6 +9,7 @@ import { OwnersService } from '@/modules/owners/routes/owners.service';
import { SafesByChainId } from '@/modules/safe/domain/entities/safes-by-chain-id.entity';
import { ValidationPipe } from '@/validation/pipes/validation.pipe';
import { AddressSchema } from '@/validation/entities/schemas/address.schema';
import { CaptchaGuard } from '@/routes/captcha/guards/captcha.guard';
import type { Address } from 'viem';

@ApiTags('owners')
Expand Down Expand Up @@ -45,6 +46,7 @@ export class OwnersControllerV2 {
},
})
@Get('owners/:ownerAddress/safes')
@UseGuards(CaptchaGuard)
async getAllSafesByOwner(
@Param('ownerAddress', new ValidationPipe(AddressSchema))
ownerAddress: Address,
Expand Down
9 changes: 9 additions & 0 deletions src/routes/captcha/captcha.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { Module } from '@nestjs/common';
import { CaptchaService } from '@/routes/captcha/captcha.service';
import { CaptchaGuard } from '@/routes/captcha/guards/captcha.guard';

@Module({
providers: [CaptchaService, CaptchaGuard],
exports: [CaptchaGuard, CaptchaService],
})
export class CaptchaModule {}
80 changes: 80 additions & 0 deletions src/routes/captcha/captcha.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import { Inject, Injectable } from '@nestjs/common';
import { IConfigurationService } from '@/config/configuration.service.interface';
import {
NetworkService,
type INetworkService,
} from '@/datasources/network/network.service.interface';
import { ILoggingService, LoggingService } from '@/logging/logging.interface';

interface TurnstileVerifyResponse {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should extract it to a separate interface/entity file.

success: boolean;
'error-codes'?: Array<string>;
challenge_ts?: string;
hostname?: string;
}

@Injectable()
export class CaptchaService {
private readonly verifyUrl =
'https://challenges.cloudflare.com/turnstile/v0/siteverify';

constructor(
@Inject(IConfigurationService)
private readonly configurationService: IConfigurationService,
@Inject(NetworkService)
private readonly networkService: INetworkService,
@Inject(LoggingService)
private readonly loggingService: ILoggingService,
) {}

async verifyToken(token: string, remoteip?: string): Promise<boolean> {
const isEnabled = this.configurationService.get<boolean>('captcha.enabled');
if (!isEnabled) {
return true;
}

const secretKey =
this.configurationService.get<string>('captcha.secretKey');
if (!secretKey) {
this.loggingService.warn(
'CAPTCHA is enabled but secret key is not configured',
);
return false;
}

if (!token) {
return false;
}

try {
const response = await this.networkService.post<TurnstileVerifyResponse>({
url: this.verifyUrl,
data: {
secret: secretKey,
response: token,
...(remoteip && { remoteip }),
},
});

// response.data is Raw<TurnstileVerifyResponse>, cast to actual type
const verifyResponse =
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We usually validate the responses coming from the networkService using our validator i.e. Zod which also gives you the actual type. e.g.:

return PositionsSchema.parse(positions);

response.data as unknown as TurnstileVerifyResponse;
const isValid = verifyResponse?.success === true;

if (!isValid) {
this.loggingService.debug({
type: 'captcha_verification_failed',
errorCodes: verifyResponse?.['error-codes'] || [],
});
}

return isValid;
} catch (error) {
this.loggingService.error({
type: 'captcha_verification_error',
error: error instanceof Error ? error.message : String(error),
});
return false;
}
}
}
46 changes: 46 additions & 0 deletions src/routes/captcha/guards/captcha.guard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import {
CanActivate,
ExecutionContext,
Inject,
Injectable,
UnauthorizedException,
} from '@nestjs/common';
import { Request } from 'express';
import { CaptchaService } from '@/routes/captcha/captcha.service';
import { IConfigurationService } from '@/config/configuration.service.interface';

@Injectable()
export class CaptchaGuard implements CanActivate {
constructor(
private readonly captchaService: CaptchaService,
@Inject(IConfigurationService)
private readonly configurationService: IConfigurationService,
) {}

async canActivate(context: ExecutionContext): Promise<boolean> {
const isEnabled = this.configurationService.get<boolean>('captcha.enabled');
if (!isEnabled) {
return true;
}

const request: Request = context.switchToHttp().getRequest();
const token = request.headers['x-captcha-token'] as string | undefined;

if (!token) {
throw new UnauthorizedException('CAPTCHA token is required');
}

const remoteip =
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit(recommendation): We could extract this to a separate helper for reusability as we are fetching the client IP in different places.

(request.headers['x-forwarded-for'] as string)?.split(',')[0]?.trim() ||
request.ip ||
request.socket.remoteAddress;

const isValid = await this.captchaService.verifyToken(token, remoteip);

if (!isValid) {
throw new UnauthorizedException('Invalid CAPTCHA token');
}

return true;
}
}
Loading