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
9 changes: 9 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,15 @@ CACHE_ADAPTIVE_WARMING_LIMIT=30
CACHE_HIT_RATE_TARGET=0.85
REDIS_PASSWORD=redis123

#CDN Delivery
CDN_BASE_URL=https://cdn.example.com
CDN_FALLBACK_URL=https://storage.example.com
CDN_PROVIDER=generic
CDN_PURGE_URL=
CDN_PURGE_TOKEN=
CDN_DEFAULT_TTL_SECONDS=86400
CDN_STALE_WHILE_REVALIDATE_SECONDS=3600

#Backup Configuration
BACKUP_PATH=./backups
BACKUP_RETENTION_DAYS=30
Expand Down
10 changes: 10 additions & 0 deletions src/admin/admin.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,17 @@ import { AdminUsersController } from './controllers/admin-users.controller';
import { AdminAnalyticsController } from './controllers/admin-analytics.controller';
import { AdminModerationController } from './controllers/admin-moderation.controller';
import { AdminMonitoringController } from './controllers/admin-monitoring.controller';
import { AdminAuditController } from './controllers/admin-audit.controller';
import { AdminNotificationsController } from './controllers/admin-notifications.controller';
import { AdminCdnController } from './controllers/admin-cdn.controller';
import { PuzzlesModule } from '../puzzles/puzzles.module';
import { AuthModule } from '../auth/auth.module';
import { AnalyticsModule } from '../analytics/analytics.module';
import { User } from '../auth/entities/user.entity';
import { Role } from '../auth/entities/role.entity';
import { PrivacyModule } from '../privacy/privacy.module';
import { NotificationsModule } from '../notifications/notifications.module';
import { CdnModule } from '../cdn/cdn.module';

@Module({
imports: [
Expand All @@ -22,13 +27,18 @@ import { PrivacyModule } from '../privacy/privacy.module';
AuthModule,
AnalyticsModule,
PrivacyModule,
NotificationsModule,
CdnModule,
],
controllers: [
AdminPuzzlesController,
AdminUsersController,
AdminAnalyticsController,
AdminModerationController,
AdminMonitoringController,
AdminAuditController,
AdminNotificationsController,
AdminCdnController,
],
providers: [AdminAuditLogService, AdminUsersService],
exports: [AdminAuditLogService, AdminUsersService],
Expand Down
41 changes: 41 additions & 0 deletions src/admin/controllers/__tests__/admin-audit.controller.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { Test, TestingModule } from '@nestjs/testing';
import { AdminAuditController } from '../admin-audit.controller';
import { AdminAuditLogService } from '../../services/admin-audit-log.service';

describe('AdminAuditController', () => {
let controller: AdminAuditController;
const auditLogService = { getLogs: jest.fn() };

beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [AdminAuditController],
providers: [{ provide: AdminAuditLogService, useValue: auditLogService }],
}).compile();

controller = module.get(AdminAuditController);
auditLogService.getLogs.mockResolvedValue([[], 0]);
});

it('returns filtered and bounded audit logs', async () => {
await controller.getLogs(
'admin-1',
'UPDATE_USER_ROLE',
'USER',
'2026-01-01T00:00:00.000Z',
undefined,
'500',
'-4',
);

expect(auditLogService.getLogs).toHaveBeenCalledWith(
expect.objectContaining({
adminId: 'admin-1',
action: 'UPDATE_USER_ROLE',
targetType: 'USER',
startDate: new Date('2026-01-01T00:00:00.000Z'),
}),
100,
0,
);
});
});
38 changes: 38 additions & 0 deletions src/admin/controllers/admin-audit.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { Controller, Get, Query, UseGuards } from '@nestjs/common';
import { JwtAuthGuard } from '../../auth/guards/jwt-auth.guard';
import { RolesGuard } from '../../auth/guards/roles.guard';
import { Roles } from '../../auth/decorators/roles.decorator';
import { UserRole } from '../../auth/constants';
import { AdminAuditLogService } from '../services/admin-audit-log.service';

@Controller('admin/audit-logs')
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles(UserRole.ADMIN)
export class AdminAuditController {
constructor(private readonly auditLogService: AdminAuditLogService) {}

@Get()
async getLogs(
@Query('adminId') adminId?: string,
@Query('action') action?: string,
@Query('targetType') targetType?: string,
@Query('startDate') startDate?: string,
@Query('endDate') endDate?: string,
@Query('limit') limit = '50',
@Query('offset') offset = '0',
) {
const [data, total] = await this.auditLogService.getLogs(
{
adminId,
action,
targetType,
startDate: startDate ? new Date(startDate) : undefined,
endDate: endDate ? new Date(endDate) : undefined,
},
Math.min(Math.max(Number(limit) || 50, 1), 100),
Math.max(Number(offset) || 0, 0),
);

return { data, total };
}
}
43 changes: 43 additions & 0 deletions src/admin/controllers/admin-cdn.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { Body, Controller, Get, Post, UseGuards } from '@nestjs/common';
import { JwtAuthGuard } from '../../auth/guards/jwt-auth.guard';
import { RolesGuard } from '../../auth/guards/roles.guard';
import { Roles } from '../../auth/decorators/roles.decorator';
import { UserRole } from '../../auth/constants';
import { CdnService } from '../../cdn/cdn.service';
import { AdminAuditLogService } from '../services/admin-audit-log.service';
import { ActiveUser } from '../../auth/decorators/active-user.decorator';

@Controller('admin/cdn')
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles(UserRole.ADMIN)
export class AdminCdnController {
constructor(
private readonly cdnService: CdnService,
private readonly auditLogService: AdminAuditLogService,
) {}

@Get('metrics')
getMetrics() {
return this.cdnService.getMetrics();
}

@Get('health')
health() {
return this.cdnService.healthCheck();
}

@Post('purge')
async purge(
@Body('keys') keys: string[],
@ActiveUser() admin: { id: string },
) {
const result = await this.cdnService.purge(keys || []);
await this.auditLogService.log({
adminId: admin.id,
action: 'PURGE_CDN',
targetType: 'CDN',
details: { keys: keys || [], ...result },
});
return result;
}
}
52 changes: 52 additions & 0 deletions src/admin/controllers/admin-notifications.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import { Body, Controller, Post, UseGuards } from '@nestjs/common';
import { JwtAuthGuard } from '../../auth/guards/jwt-auth.guard';
import { RolesGuard } from '../../auth/guards/roles.guard';
import { Roles } from '../../auth/decorators/roles.decorator';
import { UserRole } from '../../auth/constants';
import { NotificationsService } from '../../notifications/services/notifications.service';
import { AdminAuditLogService } from '../services/admin-audit-log.service';
import { ActiveUser } from '../../auth/decorators/active-user.decorator';

@Controller('admin/notifications')
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles(UserRole.ADMIN)
export class AdminNotificationsController {
constructor(
private readonly notificationsService: NotificationsService,
private readonly auditLogService: AdminAuditLogService,
) {}

@Post('broadcast')
async broadcast(
@Body()
body: {
userIds: string[];
type: any;
title: string;
message: string;
data?: Record<string, unknown>;
},
@ActiveUser() admin: { id: string },
) {
const notifications = [];
for (const userId of [...new Set(body.userIds || [])]) {
const notification = await this.notificationsService.create({
userId,
type: body.type,
title: body.title,
message: body.message,
data: body.data,
});
if (notification) notifications.push(notification);
}

await this.auditLogService.log({
adminId: admin.id,
action: 'BROADCAST_NOTIFICATION',
targetType: 'USER_BATCH',
details: { requested: body.userIds?.length || 0, delivered: notifications.length },
});

return { requested: body.userIds?.length || 0, created: notifications.length };
}
}
3 changes: 2 additions & 1 deletion src/admin/controllers/admin-puzzles.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
Delete,
UseGuards,
ParseUUIDPipe,
Query,
HttpStatus,
HttpCode,
Req,
Expand Down Expand Up @@ -35,7 +36,7 @@ export class AdminPuzzlesController {
) {}

@Get()
async findAll(@Body() searchDto: SearchPuzzleDto) {
async findAll(@Query() searchDto: SearchPuzzleDto) {
return await this.puzzlesService.findAll(searchDto);
}

Expand Down
5 changes: 5 additions & 0 deletions src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ import { Event } from './events/event.entity';
import { EventsModule } from './events/events.module';
import { JobsModule } from './jobs/jobs.module';
import { Job } from './jobs/job.entity';
import { CdnModule } from './cdn/cdn.module';
import { AdminModule } from './admin/admin.module';

@Module({
imports: [
Expand Down Expand Up @@ -39,6 +41,7 @@ import { Job } from './jobs/job.entity';
password: configService.get<string>('DB_PASSWORD', 'password'),
database: configService.get<string>('DB_NAME', 'cache_warming_db'),
entities: [CacheJob, PreloadData, Metric, Event, DeadLetterEvent, Job],
autoLoadEntities: true,
synchronize: configService.get<string>('NODE_ENV') !== 'production',
logging: configService.get<string>('NODE_ENV') === 'development',
}),
Expand All @@ -48,6 +51,8 @@ import { Job } from './jobs/job.entity';
CacheWarmingModule,
EventsModule,
JobsModule,
CdnModule,
AdminModule,
],
})
export class AppModule {}
30 changes: 30 additions & 0 deletions src/cdn/cdn.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { Controller, Get, Headers, Param, Query, Res } from '@nestjs/common';
import { Response } from 'express';
import { CdnService } from './cdn.service';

@Controller('assets')
export class CdnController {
constructor(private readonly cdnService: CdnService) {}

@Get('*')
redirectToCdn(
@Param('0') key: string,
@Query('v') version = 'latest',
@Headers('if-none-match') ifNoneMatch: string | undefined,
@Res() response: Response,
) {
const asset = this.cdnService.resolveAsset(key, version);
this.cdnService.recordRequest(ifNoneMatch === asset.etag);

if (ifNoneMatch === asset.etag) {
response.status(304).setHeader('ETag', asset.etag).send();
return;
}

response
.status(302)
.setHeader('Cache-Control', asset.cacheControl)
.setHeader('ETag', asset.etag)
.redirect(asset.url);
}
}
14 changes: 14 additions & 0 deletions src/cdn/cdn.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { Global, Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import cdnConfig from './config/cdn.config';
import { CdnController } from './cdn.controller';
import { CdnService } from './cdn.service';

@Global()
@Module({
imports: [ConfigModule.forFeature(cdnConfig)],
controllers: [CdnController],
providers: [CdnService],
exports: [CdnService],
})
export class CdnModule {}
63 changes: 63 additions & 0 deletions src/cdn/cdn.service.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import { Test, TestingModule } from '@nestjs/testing';
import { CdnService } from './cdn.service';

const config = {
primaryUrl: 'https://cdn.example.com',
fallbackUrl: 'https://fallback.example.com',
provider: 'generic',
purgeUrl: '',
purgeToken: '',
defaultTtlSeconds: 3600,
staleWhileRevalidateSeconds: 300,
};

describe('CdnService', () => {
let service: CdnService;

beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
CdnService,
{ provide: 'CONFIGURATION(cdn)', useValue: config },
],
}).compile();

service = module.get(CdnService);
});

it('creates versioned CDN URLs with immutable caching', () => {
const asset = service.resolveAsset('/puzzles/one.png', 'abc123');

expect(asset.url).toBe('https://cdn.example.com/puzzles/one.png?v=abc123');
expect(asset.cacheControl).toContain('immutable');
expect(asset.etag).toBe('"puzzles/one.png:abc123"');
});

it('records cache metrics', () => {
service.recordRequest(true);
service.recordRequest(false);

expect(service.getMetrics()).toMatchObject({
requests: 2,
cacheHits: 1,
cacheMisses: 1,
});
});

it('deduplicates purge keys when no provider endpoint is configured', async () => {
await expect(service.purge(['a.png', 'a.png', ' b.png '])).resolves.toEqual({
purged: 2,
failed: false,
});
});

it('uses the fallback CDN when the primary is unavailable', async () => {
jest.spyOn((service as any).httpClient, 'head').mockRejectedValue(new Error('offline'));

await expect(service.healthCheck()).resolves.toEqual({
available: true,
url: config.fallbackUrl,
});
expect(service.getMetrics().failoverRequests).toBe(1);
});
});
Loading
Loading