173 lines
5.5 KiB
TypeScript
173 lines
5.5 KiB
TypeScript
import { NestFactory } from "@nestjs/core";
|
|
import { NestExpressApplication } from "@nestjs/platform-express";
|
|
import { AppModule } from "./app.module";
|
|
import { join } from "path";
|
|
import { ValidationPipe, BadRequestException } from "@nestjs/common";
|
|
import { SwaggerModule, DocumentBuilder } from "@nestjs/swagger";
|
|
import { CustomHttpExceptionFilter } from "./common/filters/http-exception.filter";
|
|
import { PrismaExceptionFilter } from "./common/filters/prisma-exception.filter";
|
|
import { DecimalInterceptor } from "./common/interceptors/decimal.interceptor";
|
|
import { validateEnv } from "./common/env.validation";
|
|
import helmet from "helmet";
|
|
import compression from "compression";
|
|
import * as crypto from "crypto";
|
|
|
|
// Ensure BigInt can be serialized to JSON across all NestJS / Express responses
|
|
(BigInt.prototype as any).toJSON = function () {
|
|
return Number(this);
|
|
};
|
|
|
|
async function bootstrap() {
|
|
validateEnv(process.env);
|
|
|
|
const app = await NestFactory.create<NestExpressApplication>(AppModule);
|
|
|
|
// Trust 1 reverse proxy hop (Nginx / Cloudflare / Ingress) to prevent IP spoofing
|
|
app.set("trust proxy", 1);
|
|
|
|
// Serve static uploads folder with 1-year aggressive browser caching (immutable)
|
|
const staticUploadOptions = {
|
|
maxAge: 31536000000, // 1 year in ms
|
|
immutable: true,
|
|
setHeaders: (res: any) => {
|
|
res.setHeader("Cache-Control", "public, max-age=31536000, immutable");
|
|
},
|
|
};
|
|
|
|
app.useStaticAssets(join(process.cwd(), "uploads"), {
|
|
prefix: "/uploads/",
|
|
...staticUploadOptions,
|
|
});
|
|
app.useStaticAssets(join(process.cwd(), "uploads"), {
|
|
prefix: "/api/uploads/",
|
|
...staticUploadOptions,
|
|
});
|
|
|
|
app.use(compression());
|
|
|
|
// SEC-013: Dynamic cryptographically-secure nonce per request for CSP
|
|
app.use((req: any, res: any, next: any) => {
|
|
res.locals.cspNonce = crypto.randomBytes(16).toString("base64");
|
|
next();
|
|
});
|
|
|
|
app.use(
|
|
helmet({
|
|
contentSecurityPolicy:
|
|
process.env.NODE_ENV === "production"
|
|
? {
|
|
directives: {
|
|
defaultSrc: ["'self'"],
|
|
scriptSrc: [
|
|
"'self'",
|
|
(req: any, res: any) => `'nonce-${res.locals.cspNonce}'`,
|
|
],
|
|
styleSrc: [
|
|
"'self'",
|
|
"'unsafe-inline'", // Needed for inline styles across dashboards/UI
|
|
(req: any, res: any) => `'nonce-${res.locals.cspNonce}'`,
|
|
],
|
|
imgSrc: ["'self'", "data:", "blob:", "https:"],
|
|
connectSrc: ["'self'", "https:"],
|
|
fontSrc: ["'self'", "data:"],
|
|
objectSrc: ["'none'"],
|
|
baseUri: ["'self'"],
|
|
frameAncestors: ["'none'"],
|
|
upgradeInsecureRequests: [],
|
|
},
|
|
}
|
|
: false,
|
|
crossOriginEmbedderPolicy: false,
|
|
}),
|
|
);
|
|
|
|
app.setGlobalPrefix("api");
|
|
|
|
const allowedOrigins = process.env.ALLOWED_ORIGINS
|
|
? process.env.ALLOWED_ORIGINS.split(",").map((o) => o.trim())
|
|
: [
|
|
"http://localhost:3000",
|
|
"http://localhost:3001",
|
|
"http://localhost:5173",
|
|
"https://canina.ir",
|
|
"https://www.canina.ir",
|
|
"https://admin.canina.ir",
|
|
"https://stage.canina.ir",
|
|
"https://stageadmin.canina.ir",
|
|
];
|
|
|
|
app.enableCors({
|
|
origin: (origin, callback) => {
|
|
// Allow requests with no origin (e.g. mobile apps, curl, server-to-server)
|
|
if (!origin || allowedOrigins.includes(origin)) {
|
|
callback(null, true);
|
|
} else {
|
|
callback(new Error(`Origin ${origin} not allowed by CORS`));
|
|
}
|
|
},
|
|
credentials: true,
|
|
});
|
|
|
|
app.useGlobalPipes(
|
|
new ValidationPipe({
|
|
transform: true,
|
|
whitelist: true,
|
|
forbidNonWhitelisted: true,
|
|
exceptionFactory: (errors) => {
|
|
const formattedDetails = errors.map((err) => {
|
|
const constraints = err.constraints
|
|
? Object.values(err.constraints)
|
|
: [];
|
|
return {
|
|
field: err.property,
|
|
message:
|
|
constraints.length > 0
|
|
? constraints[0]
|
|
: "مقدار وارد شده نامعتبر است.",
|
|
};
|
|
});
|
|
|
|
return new BadRequestException({
|
|
message:
|
|
"اطلاعات ورودی فرم معتبر نمیباشد. لطفاً موارد مشخص شده را اصلاح نمایید.",
|
|
error: "INVALID_INPUT_DATA",
|
|
details: formattedDetails,
|
|
});
|
|
},
|
|
}),
|
|
);
|
|
|
|
app.useGlobalFilters(
|
|
new CustomHttpExceptionFilter(),
|
|
new PrismaExceptionFilter(),
|
|
);
|
|
|
|
app.useGlobalInterceptors(new DecimalInterceptor());
|
|
|
|
const isProduction = process.env.NODE_ENV === "production";
|
|
const isSwaggerExplicitlyDisabled = process.env.ENABLE_SWAGGER === "false";
|
|
|
|
if (!isProduction && !isSwaggerExplicitlyDisabled) {
|
|
const config = new DocumentBuilder()
|
|
.setTitle("Canina Iran API")
|
|
.setDescription(
|
|
"API Documentation for Canina Iran Pet Health & Supplement Platform",
|
|
)
|
|
.setVersion("1.0.0")
|
|
.addBearerAuth()
|
|
.build();
|
|
|
|
const document = SwaggerModule.createDocument(app, config);
|
|
SwaggerModule.setup("api/docs", app, document);
|
|
console.log("Swagger UI is ACTIVE on /api/docs");
|
|
} else {
|
|
console.log("Swagger UI is DISABLED for security (production environment)");
|
|
}
|
|
|
|
await app.listen(process.env.PORT ?? 4001);
|
|
}
|
|
bootstrap().catch((err: unknown) => {
|
|
console.error("Bootstrap error:", err);
|
|
process.exit(1);
|
|
});
|