Files
backend/src/main.ts

129 lines
4.2 KiB
TypeScript
Raw Normal View History

fix(security): resolve audit findings — secrets, env contract, migrations Removes hardcoded fallback secrets and makes a misconfigured deploy fail loudly instead of silently falling back to development defaults. - Remove insecure JWT fallback secrets (messages.module, configuration) - Remove the 'default-secret' fallback for the 2FA TOTP encryption key and allow a dedicated TWO_FACTOR_ENCRYPTION_KEY so rotating JWT_SECRET no longer locks out every 2FA user (see docs/2fa-key-rotation.md) - Require EMAIL_API_URL; drop the hardcoded vendor email endpoint - Drive WebSocket CORS from CORS_ORIGINS instead of origin:'*' - Load .env before any Nest module is imported (src/load-env.ts). Decorator arguments evaluate at import time, so the gateway previously froze its CORS config to the localhost fallback even when CORS_ORIGINS was set - Add boot-time env validation: missing required vars, weak JWT_SECRET, and inverted access/refresh token lifetimes now abort startup - Enable Redis TLS certificate verification - Require ADMIN_EMAIL/ADMIN_PASSWORD for the seed; remove the published default super-admin credentials and stop printing them - Add the initial Prisma migration and stop gitignoring prisma/migrations - Make .env.example an accurate configuration contract (admin bootstrap, REDIS_TLS, S3_ENDPOINT, 2FA key, Firebase path; drop the dead SMTP block) - Add handover documentation: architecture, ER model, sequence and data-flow diagrams, 2FA key rotation runbook Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-04 11:30:36 +05:30
// MUST stay the first import — see the comment in load-env.ts.
import './load-env';
import { NestFactory } from '@nestjs/core';
import { ValidationPipe, Logger, BadRequestException } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
2026-01-24 22:19:26 +05:30
import { NestExpressApplication } from '@nestjs/platform-express';
import helmet from 'helmet';
import cookieParser from 'cookie-parser';
import { AppModule } from './app.module';
import { AllExceptionsFilter } from './common/filters';
import { TransformInterceptor } from './common/interceptors';
import { RedisIoAdapter } from './common/adapters/redis-io.adapter';
async function bootstrap() {
const logger = new Logger('Bootstrap');
const app = await NestFactory.create<NestExpressApplication>(AppModule, {
rawBody: true,
});
const configService = app.get(ConfigService);
const port = configService.get<number>('app.port') || 3001;
const appEnv = configService.get<string>('app.env') || 'development';
const corsOrigins = configService.get<string[]>('cors.origins') || [];
2026-08-04 03:34:52 -05:00
// Security — allow cross-origin API reads from frontend/admin domains
app.use(
helmet({
crossOriginResourcePolicy: { policy: 'cross-origin' },
crossOriginOpenerPolicy: { policy: 'same-origin-allow-popups' },
}),
);
app.use(cookieParser());
// CORS
app.enableCors({
origin: corsOrigins,
credentials: true,
methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With'],
});
// Global prefix
app.setGlobalPrefix('api/v1');
// Global pipes
app.useGlobalPipes(
new ValidationPipe({
whitelist: true,
forbidNonWhitelisted: true,
transform: true,
transformOptions: {
enableImplicitConversion: true,
},
exceptionFactory: (errors) => {
const messages = errors.map((error) => {
const constraints = error.constraints
? Object.values(error.constraints)
: [`${error.property} is invalid`];
return {
field: error.property,
errors: constraints,
};
});
return new BadRequestException({
message: 'Validation failed',
errors: messages,
});
},
}),
);
// Global filters
app.useGlobalFilters(new AllExceptionsFilter());
// Global interceptors
app.useGlobalInterceptors(new TransformInterceptor());
// Swagger documentation — enabled when NODE_ENV !== 'production' OR SWAGGER_ENABLED=true.
// Lets us turn it on for beta (NODE_ENV=production) without exposing it in real prod.
const swaggerEnabled = appEnv !== 'production' || process.env.SWAGGER_ENABLED === 'true';
if (swaggerEnabled) {
const config = new DocumentBuilder()
.setTitle('Real Estate Agent Platform API')
.setDescription('API documentation for the Real Estate Agent Platform')
.setVersion('1.0')
.addBearerAuth(
{
type: 'http',
scheme: 'bearer',
bearerFormat: 'JWT',
name: 'JWT',
description: 'Enter JWT token',
in: 'header',
},
'JWT-auth',
)
.addTag('Auth', 'Authentication endpoints')
.addTag('Users', 'User management endpoints')
.addTag('Agents', 'Agent management endpoints')
.addTag('Health', 'Health check endpoints')
.build();
const document = SwaggerModule.createDocument(app, config);
// Mount at both /api/docs (existing) and /docs (cleaner subdomain URL).
SwaggerModule.setup('api/docs', app, document, {
swaggerOptions: { persistAuthorization: true },
});
SwaggerModule.setup('docs', app, document, {
swaggerOptions: { persistAuthorization: true },
});
logger.log(`Swagger documentation available at /api/docs and /docs`);
}
// Socket.IO Redis adapter for cross-instance event broadcasting
const redisIoAdapter = new RedisIoAdapter(app, configService);
await redisIoAdapter.connectToRedis();
app.useWebSocketAdapter(redisIoAdapter);
await app.listen(port);
logger.log(`Application is running on: http://localhost:${port}`);
logger.log(`Environment: ${appEnv}`);
}
bootstrap();