forked from StellarSplit/StellarSplit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.ts
More file actions
126 lines (109 loc) · 4.61 KB
/
Copy pathmain.ts
File metadata and controls
126 lines (109 loc) · 4.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
import { NestFactory } from '@nestjs/core';
import { ConfigService } from '@nestjs/config';
import { ValidationPipe, VersioningType } from '@nestjs/common';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import 'reflect-metadata';
import { AppModule } from './app.module';
import { GlobalHttpExceptionFilter } from './common/filters/http-exception.filter';
import { TypeOrmExceptionFilter } from './common/filters/typeorm-exception.filter';
import { validateEnvironment, Environment } from './config/env.validation';
import { SocketIoAdapter } from './websocket/socket-io.adapter';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
const configService = app.get(ConfigService);
// ============================================================
// STRICT ENVIRONMENT VALIDATION (run before any other startup)
// ============================================================
const nodeEnv = configService.get<string>('NODE_ENV') || 'development';
// Build config object for validation
const envConfig = {
NODE_ENV: nodeEnv,
DATABASE_HOST: configService.get<string>('DATABASE_HOST'),
DATABASE_PORT: configService.get<number>('DATABASE_PORT'),
DATABASE_USERNAME: configService.get<string>('DATABASE_USERNAME'),
DATABASE_PASSWORD: configService.get<string>('DATABASE_PASSWORD'),
DATABASE_NAME: configService.get<string>('DATABASE_NAME'),
JWT_SECRET: configService.get<string>('JWT_SECRET'),
REDIS_URL: configService.get<string>('REDIS_URL'),
DATABASE_SSL: configService.get<string>('DATABASE_SSL'),
DEBUG: configService.get<string>('DEBUG'),
CORS_ORIGIN: configService.get<string>('CORS_ORIGIN'),
};
// Validate environment configuration
const validation = validateEnvironment(envConfig);
if (!validation.isValid) {
const errorMsg = `Environment validation failed:\n${validation.errors.join('\n')}`;
console.error('❌ ' + errorMsg);
// In production, fail fast on missing required config
if (nodeEnv === Environment.PRODUCTION) {
process.exit(1);
}
}
// Log warnings
if (validation.warnings.length > 0) {
console.warn('⚠️ Environment warnings:');
validation.warnings.forEach(w => console.warn(' - ' + w));
}
// ============================================================
// ENABLE GLOBAL VALIDATION PIPE
// ============================================================
app.useGlobalPipes(
new ValidationPipe({
whitelist: true,
forbidNonWhitelisted: true,
transform: true,
}),
);
// Global exception filters
app.useGlobalFilters(new GlobalHttpExceptionFilter(), new TypeOrmExceptionFilter());
// Enable URI versioning: /api/v1/...
app.enableVersioning({
type: VersioningType.URI,
defaultVersion: '1',
});
// Set global API prefix
app.setGlobalPrefix('api');
// ============================================================
// SAFER CORS DEFAULTS FOR PRODUCTION
// ============================================================
const corsOptions = {
origin: nodeEnv === Environment.PRODUCTION
? configService.get<string[]>('ALLOWED_ORIGINS') || [] // Explicit whitelist in production
: configService.get<string>('CORS_ORIGIN') || true, // Permissive in dev
credentials: true,
methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With'],
maxAge: 86400, // 24 hours preflight cache
};
// Security middleware and production hardening are centralized in SecurityModule.
app.enableCors(corsOptions);
app.useWebSocketAdapter(
new SocketIoAdapter(app, {
cors: {
origin: corsOptions.origin,
credentials: true,
methods: ['GET', 'POST'],
},
}),
);
// Configure Swagger
const appConfig = configService.get('app');
const config = new DocumentBuilder()
.setTitle(appConfig.swagger.title)
.setDescription(appConfig.swagger.description)
.setVersion(appConfig.swagger.version)
.addBearerAuth()
.addTag('Health', 'Application health checks')
.addTag('Receipts', 'OCR receipt scanning and parsing')
.build();
const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup(appConfig.swagger.path, app, document);
const port = appConfig.port;
await app.listen(port);
console.log(`✅ NestJS application running on http://localhost:${port}`);
console.log(`📚 Swagger documentation available at http://localhost:${port}${appConfig.swagger.path}`);
}
bootstrap().catch((error) => {
console.error('❌ Failed to start application:', error);
process.exit(1);
});