import 'reflect-metadata'; import { NestFactory } from '@nestjs/core'; import { Logger, RequestMethod, ValidationPipe } from '@nestjs/common'; import { NestExpressApplication } from '@nestjs/platform-express'; import { ConfigService } from '@nestjs/config'; import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger'; import { existsSync, mkdirSync } from 'fs'; import { join, resolve } from 'path'; import { InstallAppModule } from './install-app.module'; import { AllExceptionsFilter } from './common/filters/all-exceptions.filter'; import { TransformInterceptor } from './common/interceptors/transform.interceptor'; import { OperationLogInterceptor } from './operation-log/operation-log.interceptor'; import { STATIC_ASSET_CACHE_CONTROL } from './storage/storage.service'; import { isInstallMode } from './config/runtime-config'; (BigInt.prototype as unknown as { toJSON: () => string }).toJSON = function () { return this.toString(); }; function mountSpa(app: NestExpressApplication, prefix: string, root: string): void { if (!existsSync(root)) return; app.useStaticAssets(root, { prefix }); const http = app.getHttpAdapter().getInstance(); const index = resolve(root, 'index.html'); http.get(prefix, (_req, res) => res.sendFile(index)); http.get(`${prefix}/*`, (_req, res) => res.sendFile(index)); } async function bootstrap(): Promise { const installing = isInstallMode(); const rootModule = installing ? InstallAppModule : (await import('./app.module')).AppModule; const app = await NestFactory.create(rootModule, { bodyParser: true, }); const config = app.get(ConfigService); const logger = new Logger('Bootstrap'); app.setGlobalPrefix('api', { exclude: [{ path: 't/:shortCode', method: RequestMethod.GET }], }); app.enableCors({ origin: [ config.get('adminOrigin') as string, config.get('clientOrigin') as string, /^http:\/\/localhost(:\d+)?$/, /^http:\/\/127\.0\.0\.1(:\d+)?$/, ], credentials: true, }); // 最小安全响应头:禁止 MIME 嗅探、禁止被 iframe 嵌套、限制 Referer 外泄 const httpAdapter = app.getHttpAdapter().getInstance(); httpAdapter.disable('x-powered-by'); // 信任前置反代(Nginx/宝塔/1Panel)的 X-Forwarded-For,使限流与日志拿到真实客户端 IP httpAdapter.set('trust proxy', 1); app.use((_req: unknown, res: { setHeader: (k: string, v: string) => void }, next: () => void) => { res.setHeader('X-Content-Type-Options', 'nosniff'); res.setHeader('X-Frame-Options', 'SAMEORIGIN'); res.setHeader('Referrer-Policy', 'strict-origin-when-cross-origin'); next(); }); app.useGlobalPipes( new ValidationPipe({ whitelist: true, transform: true, transformOptions: { enableImplicitConversion: true }, }), ); app.useGlobalFilters(new AllExceptionsFilter()); if (installing) { app.useGlobalInterceptors(new TransformInterceptor()); } else { app.useGlobalInterceptors(app.get(OperationLogInterceptor), new TransformInterceptor()); } const publicRoot = resolve(process.env.ARTVERIS_PUBLIC_DIR || join(process.cwd(), 'public')); const http = app.getHttpAdapter().getInstance(); if (installing) { // 安装模式:由 admin 静态页承载首次安装向导(admin 启动时探测 /api/install/status) mountSpa(app, '/admin', resolve(publicRoot, 'admin')); http.get('/', (_req, res) => res.redirect('/admin')); } else { const localDir = resolve(config.get('storage.localDir') || './storage'); if (!existsSync(localDir)) mkdirSync(localDir, { recursive: true }); app.useStaticAssets(localDir, { prefix: config.get('storage.publicPrefix') || '/uploads', etag: true, lastModified: true, maxAge: '1y', immutable: true, setHeaders: (res) => { res.setHeader('Cache-Control', STATIC_ASSET_CACHE_CONTROL); // 纵深防御:即便历史遗留 svg 等,直接打开也不作为可执行文档渲染 res.setHeader('X-Content-Type-Options', 'nosniff'); res.setHeader('Content-Disposition', 'inline'); }, }); mountSpa(app, '/admin', resolve(publicRoot, 'admin')); mountSpa(app, '/trace', resolve(publicRoot, 'trace')); if (existsSync(resolve(publicRoot, 'admin', 'index.html'))) { http.get('/', (_req, res) => res.redirect('/admin')); } } const swaggerConfig = new DocumentBuilder() .setTitle('Artveris API') .setDescription('Artveris traceability and certification API') .setVersion('0.1.0') .addBearerAuth() .build(); const document = SwaggerModule.createDocument(app, swaggerConfig); SwaggerModule.setup('api/docs', app, document); const port = config.get('port') || 3000; await app.listen(port); logger.log(`${installing ? 'Install server' : 'API'} started: http://localhost:${port}/api`); logger.log(`Swagger: http://localhost:${port}/api/docs`); } void bootstrap();