Files
Artveris/apps/api/src/main.ts
T
Nixevol f712b16c1f fix: 修复后端竞态/安全/数据处理问题并移除冗余 outImage 列
首次激活改条件更新消除并发竞态;备份恢复补模型全集与版本校验防清库;
审核列表分页总数、操作日志未捕获 Promise、出库导入重复码、加密密钥可编辑、
溯源码盐以 env 为准、证书按 originKey reconcile、env 加载去重等修复;
新增 parseBigId 防非法入参 500、全局安全响应头、去除 SVG 上传、接入 throttler 限流、
入队失败补偿、hashData 稳定序列化、无效码负缓存、看板已激活口径调整;
移除冗余 TraceCode.outImage 列统一 outImages(迁移 drop_trace_code_out_image)。
2026-07-09 13:14:26 +08:00

123 lines
4.9 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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<void> {
const installing = isInstallMode();
const rootModule = installing ? InstallAppModule : (await import('./app.module')).AppModule;
const app = await NestFactory.create<NestExpressApplication>(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<string>('adminOrigin') as string,
config.get<string>('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<string>('storage.localDir') || './storage');
if (!existsSync(localDir)) mkdirSync(localDir, { recursive: true });
app.useStaticAssets(localDir, {
prefix: config.get<string>('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<number>('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();