Skip to content
Open
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
19 changes: 19 additions & 0 deletions src/admin/admin.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,23 @@
import {
Body,
Controller,
Delete,
Get,
NotFoundException,
Param,
Patch,
Post,
Put,
Query,
Res,
UseGuards,
UseInterceptors,
HttpException,
HttpStatus,
} from '@nestjs/common';
import { Response } from 'express';
import * as fs from 'fs';
import * as path from 'path';
import { CurrentUser } from '../auth/decorators/current-user.decorator';
import { Roles } from '../auth/decorators/roles.decorator';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
Expand All @@ -37,6 +42,7 @@
UpdateTransactionStatusDto,
} from './dto/admin.dto';
import { RestoreBackupDto, UpdateBackupScheduleDto } from '../backup/dto/backup.dto';
import { AdminAuditInterceptor } from './admin-audit.interceptor';

@Controller('admin')
@UseGuards(JwtAuthGuard, RolesGuard)
Expand All @@ -49,22 +55,22 @@
) {}

@Get('dashboard')
getDashboard() {

Check warning on line 58 in src/admin/admin.controller.ts

View workflow job for this annotation

GitHub Actions / lint

Missing return type on function

Check warning on line 58 in src/admin/admin.controller.ts

View workflow job for this annotation

GitHub Actions / lint

Missing return type on function
return this.adminService.getDashboard();
}

@Get('backups')
listBackups() {

Check warning on line 63 in src/admin/admin.controller.ts

View workflow job for this annotation

GitHub Actions / lint

Missing return type on function

Check warning on line 63 in src/admin/admin.controller.ts

View workflow job for this annotation

GitHub Actions / lint

Missing return type on function
return this.adminService.listBackups();
}

@Get('backups/status')
getBackupStatus() {

Check warning on line 68 in src/admin/admin.controller.ts

View workflow job for this annotation

GitHub Actions / lint

Missing return type on function

Check warning on line 68 in src/admin/admin.controller.ts

View workflow job for this annotation

GitHub Actions / lint

Missing return type on function
return this.adminService.getBackupStatus();
}

@Get('backups/schedule')
getBackupSchedule() {

Check warning on line 73 in src/admin/admin.controller.ts

View workflow job for this annotation

GitHub Actions / lint

Missing return type on function
return this.adminService.getBackupSchedule();
}

Expand Down Expand Up @@ -270,4 +276,17 @@
note: 'This is a preview with sample data. Actual emails will use real data.',
};
}

@Delete('exports/:filename')
deleteExport(@Param('filename') filename: string) {
const filepath = path.join(process.cwd(), 'exports', filename);

if (!fs.existsSync(filepath)) {
throw new NotFoundException('Export file not found');
}

fs.unlinkSync(filepath);

return { message: 'Export file deleted successfully' };
}
}
16 changes: 10 additions & 6 deletions src/auth/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@ import {
comparePassword,
createSha256,
generateBackupCodes,
getPasswordHistoryLimit,
hashPassword,
parseDuration,
randomBase32Secret,
Expand Down Expand Up @@ -111,7 +110,7 @@ export class AuthService {
throw new BadRequestException('A user with that email already exists');
}

const passwordErrors = validatePassword(data.password);
const passwordErrors = validatePassword(data.password, this.configService);
if (passwordErrors.length > 0) {
throw new BadRequestException(
`Password does not meet complexity requirements: ${passwordErrors.join('; ')}`,
Expand Down Expand Up @@ -663,7 +662,7 @@ export class AuthService {
}

async changePassword(user: AuthUserPayload, data: ChangePasswordDto) {
const passwordHistoryLimit = getPasswordHistoryLimit();
const passwordHistoryLimit = this.getPasswordHistoryLimit();
const existingUser = await this.prisma.user.findUnique({
where: { id: user.sub },
include: {
Expand All @@ -685,7 +684,7 @@ export class AuthService {
throw new UnauthorizedException('Current password is incorrect');
}

const passwordErrors = validatePassword(data.newPassword);
const passwordErrors = validatePassword(data.newPassword, this.configService);
if (passwordErrors.length > 0) {
throw new BadRequestException(
`Password does not meet complexity requirements: ${passwordErrors.join('; ')}`,
Expand Down Expand Up @@ -1294,9 +1293,9 @@ export class AuthService {
throw new BadRequestException('Account is blocked');
}

const passwordHistoryLimit = getPasswordHistoryLimit();
const passwordHistoryLimit = this.getPasswordHistoryLimit();

const passwordErrors = validatePassword(data.newPassword);
const passwordErrors = validatePassword(data.newPassword, this.configService);
if (passwordErrors.length > 0) {
throw new BadRequestException(
`Password does not meet complexity requirements: ${passwordErrors.join('; ')}`,
Expand Down Expand Up @@ -1396,6 +1395,11 @@ export class AuthService {
});
}

private getPasswordHistoryLimit(): number {
const parsed = Number(this.configService.get('PASSWORD_HISTORY_LIMIT') ?? 5);
return Number.isFinite(parsed) && parsed > 0 ? parsed : 5;
}

private async verifyCaptcha(token: string): Promise<boolean> {
const secret = this.configService.get<string>('RECAPTCHA_SECRET');
if (!secret) {
Expand Down
20 changes: 11 additions & 9 deletions src/auth/password.utils.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
// @ts-nocheck

import { ConfigService } from '@nestjs/config';

export type PasswordPolicy = {
minLength: number;
requireUppercase: boolean;
Expand All @@ -9,22 +11,22 @@ export type PasswordPolicy = {
specialChars?: string;
};

export function getPasswordPolicy(): PasswordPolicy {
const minLength = Number(process.env.PASSWORD_MIN_LENGTH ?? 8);
export function getPasswordPolicy(configService: ConfigService): PasswordPolicy {
const minLength = Number(configService.get('PASSWORD_MIN_LENGTH') ?? 8);
return {
minLength: Number.isFinite(minLength) && minLength > 0 ? minLength : 8,
requireUppercase: (process.env.PASSWORD_REQUIRE_UPPERCASE ?? 'true') === 'true',
requireLowercase: (process.env.PASSWORD_REQUIRE_LOWERCASE ?? 'true') === 'true',
requireDigit: (process.env.PASSWORD_REQUIRE_DIGIT ?? 'true') === 'true',
requireSpecial: (process.env.PASSWORD_REQUIRE_SPECIAL ?? 'true') === 'true',
requireUppercase: (configService.get('PASSWORD_REQUIRE_UPPERCASE') ?? 'true') === 'true',
requireLowercase: (configService.get('PASSWORD_REQUIRE_LOWERCASE') ?? 'true') === 'true',
requireDigit: (configService.get('PASSWORD_REQUIRE_DIGIT') ?? 'true') === 'true',
requireSpecial: (configService.get('PASSWORD_REQUIRE_SPECIAL') ?? 'true') === 'true',
specialChars:
process.env.PASSWORD_SPECIAL_CHARS ?? '!@#$%^&*()_+-=[]{}|;:\",./<>?'.slice(0, 32),
configService.get('PASSWORD_SPECIAL_CHARS') ?? '!@#$%^&*()_+-=[]{}|;:\",./<>?'.slice(0, 32),
};
}

export function validatePassword(password: string): string[] {
export function validatePassword(password: string, configService: ConfigService): string[] {
const errors: string[] = [];
const policy = getPasswordPolicy();
const policy = getPasswordPolicy(configService);

if (!password || password.length < policy.minLength) {
errors.push(`Password must be at least ${policy.minLength} characters long`);
Expand Down
5 changes: 0 additions & 5 deletions src/auth/security.utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,11 +78,6 @@ export function generateBackupCodes(count = 8): string[] {
return Array.from({ length: count }, () => randomBytes(4).toString('hex').toUpperCase());
}

export function getPasswordHistoryLimit(): number {
const parsed = Number(process.env.PASSWORD_HISTORY_LIMIT ?? 5);
return Number.isFinite(parsed) && parsed > 0 ? parsed : 5;
}

export function verifyBackupCode(candidate: string, backupCodeHashes: string[]) {
const digest = createSha256(candidate.trim().toUpperCase());
const digestBuffer = Buffer.from(digest);
Expand Down
2 changes: 1 addition & 1 deletion src/email/email.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { EmailWebhookController } from './email-webhook.controller';
import { PrismaModule } from '../database/prisma.module';
import { TrackingModule } from '../tracking/tracking.module';
import { MailerModule } from '@nestjs-modules/mailer';
import { EjsAdapter } from '@nestjs-modules/mailer/dist/adapters/ejs.adapter';
import { EjsAdapter } from '@nestjs-modules/mailer/adapters/ejs.adapter';
import { ConfigService } from '@nestjs/config';
import { join } from 'path';
import { BullModule } from '@nestjs/bullmq';
Expand Down
2 changes: 0 additions & 2 deletions src/favorites/favorites.controller.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
// @ts-nocheck

import {
Controller,
Delete,
Expand Down
9 changes: 8 additions & 1 deletion src/transactions/dto/transaction.dto.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// @ts-nocheck

import { IsString, IsNumber, IsOptional, IsEnum, IsUUID, IsDate, IsIn, Min } from 'class-validator';
import { IsString, IsNumber, IsOptional, IsEnum, IsUUID, IsDate, IsIn, Min, Max } from 'class-validator';
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { Type } from 'class-transformer';

Expand Down Expand Up @@ -213,6 +213,13 @@ export class TransactionAnalyticsQueryDto {
@IsOptional()
@IsEnum(TransactionTypeDto)
type?: TransactionTypeDto;

@ApiPropertyOptional({ description: 'Maximum number of days for the date range (1-365)' })
@IsOptional()
@IsNumber()
@Min(1)
@Max(365)
maxDays?: number = 365;
}

export class TransactionVolumeTrendDto {
Expand Down
13 changes: 4 additions & 9 deletions src/transactions/transaction-notes.service.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
// @ts-nocheck

import { ForbiddenException, Injectable, NotFoundException } from '@nestjs/common';
import { PrismaService } from '../database/prisma.service';
import { CreateNoteDto } from './dto/transaction-note.dto';
Expand All @@ -12,7 +10,7 @@ export class TransactionNotesService {
const tx = await this.prisma.transaction.findUnique({ where: { id: transactionId } });
if (!tx) throw new NotFoundException('Transaction not found');

return (this.prisma as any).transactionNote.create({
return this.prisma.transactionNote.create({
data: {
transactionId,
authorId,
Expand All @@ -31,15 +29,12 @@ export class TransactionNotesService {

const where: any = { transactionId };
if (!isPrivileged && !isParty) {
// Non-party/non-admin can only see public notes authored by themselves
where.isPublic = true;
} else if (!isPrivileged) {
// Transaction parties see public notes and their own private notes
where.OR = [{ isPublic: true }, { authorId: viewerId }];
}
// Admins/agents see all notes

return (this.prisma as any).transactionNote.findMany({
return this.prisma.transactionNote.findMany({
where,
orderBy: { createdAt: 'asc' },
include: {
Expand All @@ -49,14 +44,14 @@ export class TransactionNotesService {
}

async remove(noteId: string, requesterId: string, requesterRole: string) {
const note = await (this.prisma as any).transactionNote.findUnique({ where: { id: noteId } });
const note = await this.prisma.transactionNote.findUnique({ where: { id: noteId } });
if (!note) throw new NotFoundException('Note not found');

const isPrivileged = requesterRole === 'ADMIN';
if (note.authorId !== requesterId && !isPrivileged) {
throw new ForbiddenException('Only the author or admin can delete this note');
}

return (this.prisma as any).transactionNote.delete({ where: { id: noteId } });
return this.prisma.transactionNote.delete({ where: { id: noteId } });
}
}
2 changes: 0 additions & 2 deletions src/transactions/transactions.controller.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
// @ts-nocheck

import {
Controller,
Delete,
Expand Down
19 changes: 19 additions & 0 deletions src/transactions/transactions.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -315,6 +315,7 @@ export class TransactionsService {
*/
async getAnalytics(query: TransactionAnalyticsQueryDto = {}): Promise<TransactionAnalyticsDto> {
const where: Record<string, any> = {};
const maxDays = query.maxDays ?? 365;

if (query.type) {
where.type = query.type;
Expand All @@ -324,6 +325,24 @@ export class TransactionsService {
where.createdAt = {};
if (query.startDate) where.createdAt.gte = query.startDate;
if (query.endDate) where.createdAt.lte = query.endDate;

if (query.startDate && query.endDate) {
const diffMs = new Date(query.endDate).getTime() - new Date(query.startDate).getTime();
const diffDays = Math.ceil(diffMs / (1000 * 60 * 60 * 24));
if (diffDays > maxDays) {
const cappedEnd = new Date(query.startDate);
cappedEnd.setDate(cappedEnd.getDate() + maxDays);
where.createdAt.lte = cappedEnd;
}
} else if (query.startDate && !query.endDate) {
const cappedEnd = new Date(query.startDate);
cappedEnd.setDate(cappedEnd.getDate() + maxDays);
where.createdAt.lte = cappedEnd;
} else if (!query.startDate && query.endDate) {
const cappedStart = new Date(query.endDate);
cappedStart.setDate(cappedStart.getDate() - maxDays);
where.createdAt.gte = cappedStart;
}
}

const transactions = await this.prisma.transaction.findMany({
Expand Down
9 changes: 5 additions & 4 deletions src/users/avatar-upload.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ import {
import { FileInterceptor } from '@nestjs/platform-express';
import { AvatarUploadService } from './avatar-upload.service';
import { UsersService } from './users.service';
import { AvatarUploadResponseDto, AvatarDeleteDto } from './dto/avatar-upload.dto';
import { AvatarUploadResponseDto } from './dto/avatar-upload.dto';
import { FilenameValidationPipe } from './pipes/filename-validation.pipe';

// Multer type definition
interface MulterFile {
Expand Down Expand Up @@ -67,7 +68,7 @@ export class AvatarUploadController {

@Delete('delete')
async deleteAvatar(
@Body() deleteDto: AvatarDeleteDto,
@Body('filename', FilenameValidationPipe) filename: string,
@Request() req: { user: { id: string } },
): Promise<{ message: string }> {
if (!req.user || !req.user.id) {
Expand All @@ -76,7 +77,7 @@ export class AvatarUploadController {

try {
// Delete avatar file
await this.avatarUploadService.deleteAvatar(req.user.id, deleteDto.filename);
await this.avatarUploadService.deleteAvatar(req.user.id, filename);

// Remove avatar URL from user's record
await this.usersService.updateAvatar(req.user.id, null);
Expand All @@ -89,7 +90,7 @@ export class AvatarUploadController {

@Get(':filename')
async getAvatar(
@Param('filename') filename: string,
@Param('filename', FilenameValidationPipe) filename: string,
@Request() req: { user: { id: string } },
): Promise<{ avatarUrl: string }> {
if (!req.user || !req.user.id) {
Expand Down
31 changes: 31 additions & 0 deletions src/users/pipes/filename-validation.pipe.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { PipeTransform, Injectable, BadRequestException } from '@nestjs/common';

const FILENAME_REGEX = /^[a-zA-Z0-9._-]+$/;
const MAX_FILENAME_LENGTH = 255;

@Injectable()
export class FilenameValidationPipe implements PipeTransform<string, string> {
transform(value: string): string {
if (!value || value.trim().length === 0) {
throw new BadRequestException('Filename must not be empty');
}

if (value.length > MAX_FILENAME_LENGTH) {
throw new BadRequestException(
`Filename must not exceed ${MAX_FILENAME_LENGTH} characters`,
);
}

if (value.includes('..') || value.includes('/') || value.includes('\\')) {
throw new BadRequestException('Filename must not contain path traversal sequences');
}

if (!FILENAME_REGEX.test(value)) {
throw new BadRequestException(
'Filename must only contain alphanumeric characters, dots, hyphens, and underscores',
);
}

return value;
}
}
Loading
Loading