-
Notifications
You must be signed in to change notification settings - Fork 312
Expand file tree
/
Copy pathmain.ts
More file actions
219 lines (195 loc) · 7.32 KB
/
main.ts
File metadata and controls
219 lines (195 loc) · 7.32 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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
import './config/load-env';
import type { INestApplication } from '@nestjs/common';
import { ValidationPipe, VersioningType } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import type { OpenAPIObject } from '@nestjs/swagger';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import * as express from 'express';
import helmet from 'helmet';
import path from 'path';
import { AppModule } from './app.module';
import { isTrustedOrigin } from './auth/auth.server';
import { adminAuthRateLimiter } from './auth/admin-rate-limit.middleware';
import { originCheckMiddleware } from './auth/origin-check.middleware';
import { mkdirSync, writeFileSync, existsSync } from 'fs';
declare module 'express-serve-static-core' {
interface Request {
rawBody?: Buffer;
}
}
let app: INestApplication | null = null;
function describeServer(baseUrl: string): string {
if (baseUrl.includes('api.staging.trycomp.ai')) return 'Staging API Server';
if (baseUrl.includes('api.trycomp.ai')) return 'Production API Server';
if (baseUrl.startsWith('http://localhost')) return 'Local API Server';
return 'API Server';
}
async function bootstrap(): Promise<void> {
// Disable body parser - required for better-auth NestJS integration
// The library will re-add body parsers after handling auth routes
app = await NestFactory.create(AppModule, {
bodyParser: false,
});
// Enable CORS with origin validation.
// Uses a callback to support dynamic trust portal subdomains
// (e.g. security.trycomp.ai, acme.trust.inc) and verified custom domains.
app.enableCors({
origin: (origin, callback) => {
// Allow requests with no origin (non-browser clients, same-origin, etc.)
if (!origin) {
return callback(null, true);
}
isTrustedOrigin(origin)
.then((trusted) => callback(null, trusted))
.catch(() => callback(null, false));
},
credentials: true,
exposedHeaders: ['Content-Disposition'],
});
// STEP 2: Security headers
app.use(
helmet({
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
styleSrc: ["'self'", "'unsafe-inline'"], // Swagger needs inline styles
scriptSrc: ["'self'", "'unsafe-inline'"], // Swagger needs inline scripts
imgSrc: ["'self'", 'data:', 'https:'],
connectSrc: ["'self'"],
},
},
crossOriginEmbedderPolicy: false, // Allow embedding
}),
);
// STEP 3a: Origin header validation for CSRF protection
// Rejects state-changing requests from untrusted origins.
// Defense-in-depth: CORS blocks fetch-based CSRF, this blocks form-based CSRF.
app.use(originCheckMiddleware);
// STEP 3b: Rate-limit better-auth admin routes (impersonation, ban, set-role, etc.)
// These bypass NestJS controllers so the global ThrottlerGuard doesn't apply.
app.use(adminAuthRateLimiter);
// STEP 4a: Configure body parser
// NOTE: Attachment uploads are sent as base64 in JSON, so request payloads are
// larger than the raw file size. Keep this above the user-facing max file size.
// IMPORTANT: Skip body parsing for /api/auth routes — better-auth needs the raw
// request stream to properly read the body (including OAuth callbackURL).
// Express-level middleware runs BEFORE NestJS module middleware, so without this
// skip, express.json() would consume the stream before better-auth's handler.
// Routes that need the exact request bytes for HMAC signature verification.
// Anything matched here gets `req.rawBody` populated; everything else uses
// the standard parser which discards the buffer to avoid keeping a 150MB
// copy of every JSON payload alive on the heap.
const RAW_BODY_PATHS = [
'/v1/security-penetration-tests/webhook',
'/security-penetration-tests/webhook',
];
const needsRawBody = (req: express.Request): boolean =>
RAW_BODY_PATHS.some((p) => req.path.endsWith(p));
const jsonParserWithRaw = express.json({
limit: '150mb',
verify: (req, _res, buf) => {
(req as express.Request).rawBody = buf;
},
});
const jsonParser = express.json({ limit: '150mb' });
const urlencodedParser = express.urlencoded({
limit: '150mb',
extended: true,
});
app.use(
(
req: express.Request,
res: express.Response,
next: express.NextFunction,
) => {
if (req.path.startsWith('/api/auth')) {
return next();
}
const parser = needsRawBody(req) ? jsonParserWithRaw : jsonParser;
parser(req, res, (err?: unknown) => {
if (err) return next(err);
urlencodedParser(req, res, next);
});
},
);
// STEP 4b: Enable global pipes and filters
app.useGlobalPipes(
new ValidationPipe({
whitelist: true,
forbidNonWhitelisted: true,
transform: true,
transformOptions: {
enableImplicitConversion: true,
},
}),
);
// Enable API versioning
app.enableVersioning({
type: VersioningType.URI,
defaultVersion: '1',
});
// Get server configuration from environment variables
const port = process.env.PORT ?? 3333;
// Swagger/OpenAPI configuration — single server derived from BASE_URL
const baseUrl = process.env.BASE_URL ?? `http://localhost:${port}`;
const serverDescription = describeServer(baseUrl);
const config = new DocumentBuilder()
.setTitle('API Documentation')
.setDescription('The API documentation for this application')
.setVersion('1.0')
.addApiKey(
{
type: 'apiKey',
name: 'X-API-Key',
in: 'header',
description: 'API key for authentication',
},
'apikey',
)
.addServer(baseUrl, serverDescription)
.build();
const document: OpenAPIObject = SwaggerModule.createDocument(app, config);
// Setup Swagger UI at /api/docs
SwaggerModule.setup('api/docs', app, document, {
raw: ['json'],
swaggerOptions: {
persistAuthorization: true, // Keep auth between page refreshes
},
});
const server = await app.listen(port);
const address = server.address();
const actualPort = typeof address === 'string' ? port : address?.port || port;
const actualUrl = `http://localhost:${actualPort}`;
console.log(`Application is running on: ${actualUrl}`);
console.log(`API Documentation available at: ${actualUrl}/api/docs`);
// Write OpenAPI documentation to packages/docs/openapi.json only in development
if (process.env.NODE_ENV !== 'production') {
const openapiPath = path.join(
__dirname,
'../../../../packages/docs/openapi.json',
);
const docsDir = path.dirname(openapiPath);
if (!existsSync(docsDir)) {
mkdirSync(docsDir, { recursive: true });
}
writeFileSync(openapiPath, JSON.stringify(document, null, 2));
console.log('OpenAPI documentation written to packages/docs/openapi.json');
}
}
// Graceful shutdown handler
async function shutdown(signal: string): Promise<void> {
console.log(`\n${signal} received, shutting down gracefully...`);
if (app) {
await app.close();
console.log('Application closed');
}
process.exit(0);
}
// Handle shutdown signals (important for hot reload)
process.on('SIGTERM', () => void shutdown('SIGTERM'));
process.on('SIGINT', () => void shutdown('SIGINT'));
// Handle bootstrap errors properly
void bootstrap().catch((error: unknown) => {
console.error('Error starting application:', error);
process.exit(1);
});