Skip to content
Merged
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
11 changes: 11 additions & 0 deletions backend/src/app.module.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { ScheduleModule } from '@nestjs/schedule';
import { ThrottlerModule } from '@nestjs/throttler';
import { APP_GUARD, APP_INTERCEPTOR } from '@nestjs/core';
import { CorrelationIdInterceptor } from './common/interceptors/correlation-id.interceptor';
Expand All @@ -17,6 +18,9 @@ import { AuthModule } from './auth/auth.module';
import { HealthModule } from './modules/health/health.module';
import { BlockchainModule } from './modules/blockchain/blockchain.module';
import { UserModule } from './modules/user/user.module';
import { KycModule } from './modules/kyc/kyc.module';
import { ChallengesModule } from './modules/challenges/challenges.module';
import { AlertsModule } from './modules/alerts/alerts.module';
import { AdminModule } from './modules/admin/admin.module';
import { MailModule } from './modules/mail/mail.module';
import { RedisCacheModule } from './modules/cache/cache.module';
Expand Down Expand Up @@ -66,6 +70,9 @@ const envValidationSchema = Joi.object({
MAIL_USER: Joi.string().optional(),
MAIL_PASS: Joi.string().optional(),
MAIL_FROM: Joi.string().optional(),
KYC_PROVIDER_BASE_URL: Joi.string().uri().optional(),
KYC_PROVIDER_API_KEY: Joi.string().optional(),
KYC_PII_ENCRYPTION_KEY: Joi.string().min(16).optional(),
});

@Module({
Expand Down Expand Up @@ -114,6 +121,7 @@ const envValidationSchema = Joi.object({
},
}),
EventEmitterModule.forRoot(),
ScheduleModule.forRoot(),
TypeOrmModule.forRootAsync({
inject: [ConfigService],
useFactory: (configService: ConfigService) => {
Expand Down Expand Up @@ -154,6 +162,9 @@ const envValidationSchema = Joi.object({
HealthModule,
BlockchainModule,
UserModule,
KycModule,
ChallengesModule,
AlertsModule,
AdminModule,
MailModule,
WebhooksModule,
Expand Down
5 changes: 4 additions & 1 deletion backend/src/auth/auth.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,10 @@ export class AuthController {
'Returns a TOTP secret, otpauth:// URL for QR code generation, and backup codes. ' +
'Call POST /auth/2fa/verify with a valid token to activate.',
})
@ApiResponse({ status: 201, description: 'Secret and backup codes generated' })
@ApiResponse({
status: 201,
description: 'Secret and backup codes generated',
})
@ApiResponse({ status: 400, description: '2FA already enabled' })
enable2fa(@Request() req: { user: { id: string } }) {
return this.twoFactorService.enable(req.user.id);
Expand Down
13 changes: 3 additions & 10 deletions backend/src/auth/two-factor.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,10 +82,7 @@ export class TwoFactorService {
return { enabled: true, message: '2FA has been enabled successfully' };
}

async validateLogin(
userId: string,
token: string,
): Promise<boolean> {
async validateLogin(userId: string, token: string): Promise<boolean> {
const user = await this.findUser(userId);

if (!user.twoFactorEnabled || !user.twoFactorSecret) {
Expand Down Expand Up @@ -129,9 +126,7 @@ export class TwoFactorService {
return { message: '2FA has been disabled' };
}

async adminDisable(
targetUserId: string,
): Promise<{ message: string }> {
async adminDisable(targetUserId: string): Promise<{ message: string }> {
const user = await this.findUser(targetUserId);

if (!user.twoFactorEnabled) {
Expand All @@ -154,9 +149,7 @@ export class TwoFactorService {
return { enabled: user.twoFactorEnabled };
}

async completeLogin(
userId: string,
): Promise<{ accessToken: string }> {
async completeLogin(userId: string): Promise<{ accessToken: string }> {
const user = await this.findUser(userId);
return {
accessToken: this.jwtService.sign({
Expand Down
5 changes: 3 additions & 2 deletions backend/src/common/common.module.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { Global, Module } from '@nestjs/common';
import { PiiEncryptionService } from './services/pii-encryption.service';
import { RateLimitMonitorService } from './services/rate-limit-monitor.service';

@Global()
@Module({
providers: [RateLimitMonitorService],
exports: [RateLimitMonitorService],
providers: [RateLimitMonitorService, PiiEncryptionService],
exports: [RateLimitMonitorService, PiiEncryptionService],
})
export class CommonModule {}
33 changes: 14 additions & 19 deletions backend/src/common/guards/tiered-throttler.guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,21 +114,19 @@ export class TieredThrottlerGuard extends ThrottlerGuard {
return `tiered-throttle:${ip}`;
}

protected async handleRequest(
requestProps: {
context: ExecutionContext;
limit: number;
ttl: number;
throttler: { name: string; limit: number; ttl: number };
blockDuration: number;
getTracker: (req: Record<string, any>) => Promise<string>;
generateKey: (
context: ExecutionContext,
tracker: string,
throttlerName: string,
) => string;
},
): Promise<boolean> {
protected async handleRequest(requestProps: {
context: ExecutionContext;
limit: number;
ttl: number;
throttler: { name: string; limit: number; ttl: number };
blockDuration: number;
getTracker: (req: Record<string, any>) => Promise<string>;
generateKey: (
context: ExecutionContext,
tracker: string,
throttlerName: string,
) => string;
}): Promise<boolean> {
const { context, throttler } = requestProps;
const request = context.switchToHttp().getRequest<Request>();
const response = context.switchToHttp().getResponse<Response>();
Expand Down Expand Up @@ -172,10 +170,7 @@ export class TieredThrottlerGuard extends ThrottlerGuard {
timestamp: new Date(),
});

response.setHeader(
'Retry-After',
Math.ceil(tierLimits.ttl / 1000),
);
response.setHeader('Retry-After', Math.ceil(tierLimits.ttl / 1000));
response.setHeader('X-RateLimit-Remaining', 0);
response.setHeader(
'X-RateLimit-Reset',
Expand Down
81 changes: 81 additions & 0 deletions backend/src/common/services/pii-encryption.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
import { Injectable, InternalServerErrorException } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import {
createCipheriv,
createDecipheriv,
createHash,
randomBytes,
} from 'crypto';

@Injectable()
export class PiiEncryptionService {
private readonly algorithm = 'aes-256-gcm';
private readonly key: Buffer;

constructor(private readonly configService: ConfigService) {
const secret =
this.configService.get<string>('KYC_PII_ENCRYPTION_KEY') ||
this.configService.get<string>('jwt.secret') ||
'nestera-dev-fallback-key';

this.key = createHash('sha256').update(secret).digest();
}

encrypt(value: unknown): string {
try {
const iv = randomBytes(12);
const cipher = createCipheriv(this.algorithm, this.key, iv);
const plaintext =
typeof value === 'string' ? value : JSON.stringify(value ?? {});

const encrypted = Buffer.concat([
cipher.update(plaintext, 'utf8'),
cipher.final(),
]);
const tag = cipher.getAuthTag();

return [
iv.toString('base64'),
tag.toString('base64'),
encrypted.toString('base64'),
].join('.');
} catch (error) {
throw new InternalServerErrorException(
'Failed to encrypt sensitive data',
);
}
}

decrypt<T = Record<string, unknown>>(payload?: string | null): T | null {
if (!payload) {
return null;
}

try {
const [ivB64, tagB64, dataB64] = payload.split('.');
if (!ivB64 || !tagB64 || !dataB64) {
return null;
}

const decipher = createDecipheriv(
this.algorithm,
this.key,
Buffer.from(ivB64, 'base64'),
);
decipher.setAuthTag(Buffer.from(tagB64, 'base64'));

const decrypted = Buffer.concat([
decipher.update(Buffer.from(dataB64, 'base64')),
decipher.final(),
]).toString('utf8');

try {
return JSON.parse(decrypted) as T;
} catch {
return decrypted as T;
}
} catch {
return null;
}
}
}
5 changes: 5 additions & 0 deletions backend/src/config/configuration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,11 @@ export default () => ({
pass: process.env.MAIL_PASS,
from: process.env.MAIL_FROM || '"Nestera" <noreply@nestera.io>',
},
kyc: {
providerBaseUrl: process.env.KYC_PROVIDER_BASE_URL,
providerApiKey: process.env.KYC_PROVIDER_API_KEY,
piiEncryptionKey: process.env.KYC_PII_ENCRYPTION_KEY,
},
hospital: {
endpoints: {
// Hospital endpoints from environment variables
Expand Down
7 changes: 6 additions & 1 deletion backend/src/modules/admin/admin.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,12 @@ import {
UseGuards,
BadRequestException,
} from '@nestjs/common';
import { ApiTags, ApiBearerAuth, ApiOperation, ApiResponse } from '@nestjs/swagger';
import {
ApiTags,
ApiBearerAuth,
ApiOperation,
ApiResponse,
} from '@nestjs/swagger';
import { UserService } from '../user/user.service';
import { JwtAuthGuard } from '../../auth/guards/jwt-auth.guard';
import { RolesGuard } from '../../common/guards/roles.guard';
Expand Down
70 changes: 70 additions & 0 deletions backend/src/modules/alerts/alerts.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import {
Body,
Controller,
Delete,
Get,
Param,
Patch,
Post,
UseGuards,
} from '@nestjs/common';
import {
ApiBearerAuth,
ApiOperation,
ApiResponse,
ApiTags,
} from '@nestjs/swagger';
import { JwtAuthGuard } from '../../auth/guards/jwt-auth.guard';
import { CurrentUser } from '../../common/decorators/current-user.decorator';
import { CreateAlertDto } from './dto/create-alert.dto';
import { SnoozeAlertDto } from './dto/snooze-alert.dto';
import { AlertsService } from './alerts.service';

@ApiTags('alerts')
@ApiBearerAuth()
@UseGuards(JwtAuthGuard)
@Controller('alerts')
export class AlertsController {
constructor(private readonly alertsService: AlertsService) {}

@Post('create')
@ApiOperation({ summary: 'Create product alert or watch' })
@ApiResponse({ status: 201, description: 'Alert created' })
create(@CurrentUser() user: { id: string }, @Body() dto: CreateAlertDto) {
return this.alertsService.createAlert(user.id, dto);
}

@Get()
@ApiOperation({ summary: 'List active alerts for current user' })
list(@CurrentUser() user: { id: string }) {
return this.alertsService.getUserAlerts(user.id);
}

@Get('history')
@ApiOperation({ summary: 'Get alert history' })
history(@CurrentUser() user: { id: string }) {
return this.alertsService.getAlertHistory(user.id);
}

@Patch(':id/snooze')
@ApiOperation({ summary: 'Snooze an alert' })
snooze(
@CurrentUser() user: { id: string },
@Param('id') alertId: string,
@Body() dto: SnoozeAlertDto,
) {
return this.alertsService.snoozeAlert(user.id, alertId, dto.hours);
}

@Delete(':id')
@ApiOperation({ summary: 'Disable an alert' })
disable(@CurrentUser() user: { id: string }, @Param('id') alertId: string) {
return this.alertsService.disableAlert(user.id, alertId);
}

@Get('templates/common')
@ApiOperation({ summary: 'Common alert templates' })
templates() {
return this.alertsService.alertTemplates();
}
}
27 changes: 27 additions & 0 deletions backend/src/modules/alerts/alerts.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { MailModule } from '../mail/mail.module';
import { NotificationsModule } from '../notifications/notifications.module';
import { SavingsProduct } from '../savings/entities/savings-product.entity';
import { User } from '../user/entities/user.entity';
import { AlertsController } from './alerts.controller';
import { AlertsService } from './alerts.service';
import { AlertHistory } from './entities/alert-history.entity';
import { ProductAlert } from './entities/product-alert.entity';

@Module({
imports: [
TypeOrmModule.forFeature([
ProductAlert,
AlertHistory,
SavingsProduct,
User,
]),
NotificationsModule,
MailModule,
],
controllers: [AlertsController],
providers: [AlertsService],
exports: [AlertsService],
})
export class AlertsModule {}
Loading
Loading