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
2 changes: 2 additions & 0 deletions src/admin/admin.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
Query,
Res,
UseGuards,
UseInterceptors,
HttpException,
HttpStatus,
} from '@nestjs/common';
Expand All @@ -37,6 +38,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 +51,22 @@
) {}

@Get('dashboard')
getDashboard() {

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

View workflow job for this annotation

GitHub Actions / lint

Missing return type on function

Check warning on line 54 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 59 in src/admin/admin.controller.ts

View workflow job for this annotation

GitHub Actions / lint

Missing return type on function

Check warning on line 59 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 64 in src/admin/admin.controller.ts

View workflow job for this annotation

GitHub Actions / lint

Missing return type on function

Check warning on line 64 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 69 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
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
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
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;
}
}
70 changes: 57 additions & 13 deletions test/auth/password.utils.spec.ts
Original file line number Diff line number Diff line change
@@ -1,30 +1,74 @@
import { validatePassword } from '../../src/auth/password.utils';
import { ConfigService } from '@nestjs/config';
import { getPasswordPolicy, validatePassword } from '../../src/auth/password.utils';

describe('validatePassword', () => {
const OLD_ENV = process.env;
function mockConfig(overrides: Record<string, string> = {}): ConfigService {
const defaults: Record<string, string> = {
PASSWORD_MIN_LENGTH: '8',
PASSWORD_REQUIRE_UPPERCASE: 'true',
PASSWORD_REQUIRE_LOWERCASE: 'true',
PASSWORD_REQUIRE_DIGIT: 'true',
PASSWORD_REQUIRE_SPECIAL: 'true',
};
return {
get(key: string) {
return overrides[key] ?? defaults[key] ?? undefined;
},
} as unknown as ConfigService;
}

describe('getPasswordPolicy', () => {
it('returns default values when config service has no overrides', () => {
const configService = mockConfig();
const policy = getPasswordPolicy(configService);

expect(policy.minLength).toBe(8);
expect(policy.requireUppercase).toBe(true);
expect(policy.requireLowercase).toBe(true);
expect(policy.requireDigit).toBe(true);
expect(policy.requireSpecial).toBe(true);
expect(policy.specialChars).toBeDefined();
});

afterEach(() => {
process.env = { ...OLD_ENV };
it('reflects env-driven overrides', () => {
const configService = mockConfig({
PASSWORD_MIN_LENGTH: '12',
PASSWORD_REQUIRE_UPPERCASE: 'false',
PASSWORD_SPECIAL_CHARS: '!@#$',
});

const policy = getPasswordPolicy(configService);

expect(policy.minLength).toBe(12);
expect(policy.requireUppercase).toBe(false);
expect(policy.requireLowercase).toBe(true);
expect(policy.requireDigit).toBe(true);
expect(policy.requireSpecial).toBe(true);
expect(policy.specialChars).toBe('!@#$');
});
});

describe('validatePassword', () => {
it('accepts a strong password by default policy', () => {
const errors = validatePassword('Str0ng!Pass');
const configService = mockConfig();
const errors = validatePassword('Str0ng!Pass', configService);
expect(errors).toHaveLength(0);
});

it('rejects short or simple passwords', () => {
process.env.PASSWORD_MIN_LENGTH = '12';
const errors = validatePassword('weak');
const configService = mockConfig({ PASSWORD_MIN_LENGTH: '12' });
const errors = validatePassword('weak', configService);
expect(errors.length).toBeGreaterThan(0);
});

it('requires uppercase/lowercase/digit/special as configured', () => {
process.env.PASSWORD_REQUIRE_UPPERCASE = 'true';
process.env.PASSWORD_REQUIRE_LOWERCASE = 'true';
process.env.PASSWORD_REQUIRE_DIGIT = 'true';
process.env.PASSWORD_REQUIRE_SPECIAL = 'true';
const configService = mockConfig({
PASSWORD_REQUIRE_UPPERCASE: 'true',
PASSWORD_REQUIRE_LOWERCASE: 'true',
PASSWORD_REQUIRE_DIGIT: 'true',
PASSWORD_REQUIRE_SPECIAL: 'true',
});

const errors = validatePassword('noupper1!');
const errors = validatePassword('noupper1!', configService);
expect(errors).toContain('Password must include at least one uppercase letter');
});
});
Loading
Loading