diff --git a/apps/api/package.json b/apps/api/package.json index f92883f..c85bda2 100644 --- a/apps/api/package.json +++ b/apps/api/package.json @@ -32,6 +32,7 @@ "@nestjs/schedule": "^6.1.3", "@nestjs/serve-static": "^4.0.2", "@nestjs/swagger": "^8.1.0", + "@nestjs/throttler": "^6.5.0", "@prisma/client": "^5.22.0", "adm-zip": "^0.5.18", "bcryptjs": "^2.4.3", diff --git a/apps/api/prisma/migrations/20260709120000_drop_trace_code_out_image/migration.sql b/apps/api/prisma/migrations/20260709120000_drop_trace_code_out_image/migration.sql new file mode 100644 index 0000000..1c504ce --- /dev/null +++ b/apps/api/prisma/migrations/20260709120000_drop_trace_code_out_image/migration.sql @@ -0,0 +1,7 @@ +-- 统一出库实况图为多图 JSON 字段 out_images,移除冗余的单图列 out_image。 +-- 先把仍只有 out_image 的历史数据并入 out_images,再删除该列。 +UPDATE `trace_code` +SET `out_images` = JSON_ARRAY(JSON_OBJECT('key', `out_image`, 'type', 'image')) +WHERE `out_image` IS NOT NULL AND `out_image` <> '' AND `out_images` IS NULL; + +ALTER TABLE `trace_code` DROP COLUMN `out_image`; diff --git a/apps/api/prisma/schema.prisma b/apps/api/prisma/schema.prisma index 9a2fc40..e1435fc 100644 --- a/apps/api/prisma/schema.prisma +++ b/apps/api/prisma/schema.prisma @@ -313,7 +313,6 @@ model TraceCode { batchId Int @map("batch_id") groupId Int? @map("group_id") outTime DateTime? @map("out_time") - outImage String? @map("out_image") outImages Json? @map("out_images") remark String? status TraceCodeStatus @default(INACTIVE) diff --git a/apps/api/prisma/seed-production.js b/apps/api/prisma/seed-production.js deleted file mode 100644 index 55554ee..0000000 --- a/apps/api/prisma/seed-production.js +++ /dev/null @@ -1,62 +0,0 @@ -const { PrismaClient, RoleType, UserStatus } = require('@prisma/client'); -const bcrypt = require('bcryptjs'); - -const prisma = new PrismaClient(); - -async function ensureAdmin() { - const username = process.env.SEED_ADMIN_USERNAME || 'admin'; - const password = process.env.SEED_ADMIN_PASSWORD || 'Admin@12345'; - const realName = process.env.SEED_ADMIN_NAME || '超级管理员'; - - const existing = await prisma.sysUser.findUnique({ where: { username } }); - if (existing) return; - - await prisma.sysUser.create({ - data: { - username, - passwordHash: await bcrypt.hash(password, 10), - realName, - role: RoleType.SUPER_ADMIN, - status: UserStatus.ACTIVE, - }, - }); - console.log(`[seed-production] 已创建超级管理员:${username}`); -} - -async function ensureSettings() { - const defaults = { - appName: process.env.APP_NAME || '艺术品溯源平台', - appIconUrl: '', - logRetentionDays: process.env.LOG_RETENTION_DAYS || '365', - operationLogRetentionDays: process.env.OPERATION_LOG_RETENTION_DAYS || '365', - watermarkText: process.env.WATERMARK_TEXT || '仅供溯源核验使用', - filingInfo: '备案信息待补充', - backupEnabled: 'false', - backupSchedule: 'off', - backupRetentionDays: '30', - backupRetentionCount: '10', - clientCarouselInterval: '5', - }; - - for (const [key, value] of Object.entries(defaults)) { - await prisma.systemSetting.upsert({ - where: { key }, - update: {}, - create: { key, value }, - }); - } -} - -async function main() { - await ensureAdmin(); - await ensureSettings(); -} - -main() - .catch((error) => { - console.error('[seed-production] 初始化失败', error); - process.exit(1); - }) - .finally(async () => { - await prisma.$disconnect(); - }); diff --git a/apps/api/src/app.module.ts b/apps/api/src/app.module.ts index 38a9ec9..075fbf0 100644 --- a/apps/api/src/app.module.ts +++ b/apps/api/src/app.module.ts @@ -1,6 +1,8 @@ import { Module } from '@nestjs/common'; import { ConfigModule } from '@nestjs/config'; import { ScheduleModule } from '@nestjs/schedule'; +import { APP_GUARD } from '@nestjs/core'; +import { ThrottlerGuard, ThrottlerModule } from '@nestjs/throttler'; import configuration from './config/configuration'; import { PrismaModule } from './prisma/prisma.module'; import { AppController } from './app.controller'; @@ -31,9 +33,11 @@ import { InstallModule } from './install/install.module'; ConfigModule.forRoot({ isGlobal: true, load: [configuration], - envFilePath: ['../../.env', '.env'], + ignoreEnvFile: true, }), ScheduleModule.forRoot(), + // 全局限流:默认每 IP 60 秒 600 次(宽松兜底);登录/公开溯源在各自处理器加严格限流 + ThrottlerModule.forRoot([{ ttl: 60_000, limit: 600 }]), PrismaModule, RedisModule, StorageModule, @@ -58,5 +62,6 @@ import { InstallModule } from './install/install.module'; InstallModule, ], controllers: [AppController], + providers: [{ provide: APP_GUARD, useClass: ThrottlerGuard }], }) export class AppModule {} diff --git a/apps/api/src/artwork/artwork.service.ts b/apps/api/src/artwork/artwork.service.ts index 445cf6a..8160674 100644 --- a/apps/api/src/artwork/artwork.service.ts +++ b/apps/api/src/artwork/artwork.service.ts @@ -326,7 +326,11 @@ export class ArtworkService { } async auditList(query: QueryArtworkRevisionDto) { - const where: Prisma.ArtworkRevisionWhereInput = {}; + // 把作品维度的过滤(未删除、非草稿)下推到 where.artwork, + // 使 count 与 findMany 用同一条件,避免分页总数虚高、末页出现空行 + const where: Prisma.ArtworkRevisionWhereInput = { + artwork: { deletedAt: null, status: { not: ArtworkStatus.DRAFT } }, + }; if (query.status) where.status = query.status; else where.status = ArtworkRevisionStatus.PENDING; if (query.keyword) { @@ -359,7 +363,6 @@ export class ArtworkService { this.prisma.artworkRevision.count({ where }), ]); const list = rows - .filter((r) => !r.artwork.deletedAt && r.artwork.status !== ArtworkStatus.DRAFT) .map((r) => { const after = this.snapshotWithUrls(r.afterSnapshot) as ArtworkSnapshot & { artwork?: { images?: Array }; @@ -680,19 +683,33 @@ export class ArtworkService { })), }); } - await tx.certificate.deleteMany({ where: { artworkId: id } }); - if (snapshot.certificates.length) { - await tx.certificate.createMany({ - data: snapshot.certificates.map((cert) => ({ - artworkId: id, - name: cert.name, - issuer: cert.issuer, - issuedAt: cert.issuedAt ? new Date(cert.issuedAt) : null, - type: cert.type as any, - originFileUrl: cert.originKey, - watermarkFileUrl: cert.watermarkKey ?? null, - })), - }); + // 证书按 originFileUrl(originKey) reconcile,而非全删重建: + // 未变的原件保留原证书 id 与已生成的 watermarkFileUrl,避免 ID 漂移和重复水印任务; + // 只删除快照中不再存在的证书、更新元数据、新增缺失证书。 + const existingCerts = await tx.certificate.findMany({ where: { artworkId: id } }); + const snapshotOriginKeys = new Set(snapshot.certificates.map((c) => c.originKey)); + const staleIds = existingCerts.filter((c) => !snapshotOriginKeys.has(c.originFileUrl)).map((c) => c.id); + if (staleIds.length) await tx.certificate.deleteMany({ where: { id: { in: staleIds } } }); + const byOrigin = new Map(existingCerts.map((c) => [c.originFileUrl, c])); + for (const cert of snapshot.certificates) { + const prev = byOrigin.get(cert.originKey); + const data = { + name: cert.name, + issuer: cert.issuer, + issuedAt: cert.issuedAt ? new Date(cert.issuedAt) : null, + type: cert.type as any, + }; + if (prev) { + // 原件不变:保留 id 与 watermarkFileUrl(快照带则以快照为准,否则沿用已生成的) + await tx.certificate.update({ + where: { id: prev.id }, + data: { ...data, watermarkFileUrl: cert.watermarkKey ?? prev.watermarkFileUrl }, + }); + } else { + await tx.certificate.create({ + data: { ...data, artworkId: id, originFileUrl: cert.originKey, watermarkFileUrl: cert.watermarkKey ?? null }, + }); + } } } diff --git a/apps/api/src/auth/auth.controller.ts b/apps/api/src/auth/auth.controller.ts index 5401c27..d31557b 100644 --- a/apps/api/src/auth/auth.controller.ts +++ b/apps/api/src/auth/auth.controller.ts @@ -1,5 +1,6 @@ import { Body, Controller, Get, Post } from '@nestjs/common'; import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger'; +import { Throttle } from '@nestjs/throttler'; import { AuthService } from './auth.service'; import { LoginDto } from './dto/login.dto'; import { ChangePasswordDto } from './dto/change-password.dto'; @@ -13,6 +14,8 @@ export class AuthController { @Public() @Post('login') + // 登录严格限流:每 IP 每分钟最多 10 次,防止离线字典爆破 + @Throttle({ default: { limit: 10, ttl: 60_000 } }) @ApiOperation({ summary: '登录' }) login(@Body() dto: LoginDto) { return this.authService.login(dto); diff --git a/apps/api/src/backup/backup.service.ts b/apps/api/src/backup/backup.service.ts index d5167e6..89160fa 100644 --- a/apps/api/src/backup/backup.service.ts +++ b/apps/api/src/backup/backup.service.ts @@ -97,10 +97,38 @@ function reviveRow(row: Record): Record { return out; } +const BACKUP_FORMAT_VERSION = '0.1.0'; + function isSafeZipPath(path: string): boolean { return !path.includes('\\') && !path.includes('..') && !path.startsWith('/') && !/^[a-z]:/i.test(path); } +// 恢复前的强校验:确认是 Artveris 备份、版本主号兼容、且 database.json 覆盖全部业务表, +// 防止残缺/异构备份包在「先清空全表再按存在的键写回」时把整库清空。 +function validateBackupPayload(manifest: any, db: unknown): void { + if (!manifest || manifest.app !== 'artveris') { + throw new BusinessException(ErrorCode.BAD_REQUEST, '不是 Artveris 备份包'); + } + const version = String(manifest.version || ''); + if (version.split('.')[0] !== BACKUP_FORMAT_VERSION.split('.')[0]) { + throw new BusinessException( + ErrorCode.BAD_REQUEST, + `备份包版本不兼容(备份 ${version || '未知'},当前 ${BACKUP_FORMAT_VERSION})`, + ); + } + if (!db || typeof db !== 'object' || Array.isArray(db)) { + throw new BusinessException(ErrorCode.BAD_REQUEST, '备份包 database.json 结构无效'); + } + const data = db as Record; + const missing = MODELS.filter((model) => !Array.isArray(data[model])); + if (missing.length) { + throw new BusinessException( + ErrorCode.BAD_REQUEST, + `备份包缺少数据表:${missing.join(', ')};已中止恢复以避免清空现有数据`, + ); + } +} + function isSameOrChildPath(parent: string, child: string): boolean { const rel = relative(resolve(parent), resolve(child)); return rel === '' || (!!rel && !rel.startsWith('..') && !isAbsolute(rel)); @@ -196,7 +224,8 @@ export class BackupService { const dbEntry = zip.getEntry('database.json'); if (!manifestEntry || !dbEntry) throw new BusinessException(ErrorCode.BAD_REQUEST, '备份包缺少 manifest.json 或 database.json'); const manifest = JSON.parse(manifestEntry.getData().toString('utf8')); - if (manifest.app !== 'artveris') throw new BusinessException(ErrorCode.BAD_REQUEST, '不是 Artveris 备份包'); + const db = JSON.parse(dbEntry.getData().toString('utf8')); + validateBackupPayload(manifest, db); const fileName = `restore-${dayjs().format('YYYYMMDDHHmmss')}.zip`; const filePath = join(this.backupRoot, fileName); @@ -304,8 +333,11 @@ export class BackupService { private async restoreDatabase(zip: AdmZip) { const entry = zip.getEntry('database.json'); - if (!entry) throw new Error('备份包缺少 database.json'); + const manifestEntry = zip.getEntry('manifest.json'); + if (!entry || !manifestEntry) throw new Error('备份包缺少 database.json 或 manifest.json'); const db = JSON.parse(entry.getData().toString('utf8')); + // 清库前再次校验,纵深防御,避免绕过 preview 直接 commit 的坏包清空数据 + validateBackupPayload(JSON.parse(manifestEntry.getData().toString('utf8')), db); await this.prisma.$transaction(async (tx) => { for (const model of DELETE_ORDER) { await (tx as any)[model].deleteMany(); diff --git a/apps/api/src/blockchain/attestation.service.ts b/apps/api/src/blockchain/attestation.service.ts index e25f208..2ab721e 100644 --- a/apps/api/src/blockchain/attestation.service.ts +++ b/apps/api/src/blockchain/attestation.service.ts @@ -36,7 +36,6 @@ export class AttestationService { batchNo: code.batch.batchNo, outbound: { outTime: code.outTime, - outImage: code.outImage, outImages: code.outImages, }, dynamicFields: code.artwork.dynamicFields, @@ -52,10 +51,30 @@ export class AttestationService { rawResponse: { requestMeta: summary }, }, }); - await this.queue.add('onchain', { proofId: proof.id }); + // 入队失败(如 Redis 抖动)时把 proof 标记 FAILED,避免留下永远处理不了的 PENDING 悬挂记录 + try { + await this.queue.add('onchain', { proofId: proof.id }); + } catch (e) { + await this.markQueueFailed(proof.id, proof.rawResponse, e); + throw new BusinessException(ErrorCode.INTERNAL_ERROR, '上链任务入队失败,请稍后重试'); + } return proof; } + private async markQueueFailed(proofId: number, raw: unknown, e: unknown) { + await this.prisma.blockchainProof.update({ + where: { id: proofId }, + data: { + status: ProofStatus.FAILED, + rawResponse: { + ...(raw && typeof raw === 'object' ? (raw as object) : {}), + enqueueError: (e as Error).message, + failedAt: new Date().toISOString(), + }, + }, + }); + } + async retry(proofId: number) { const proof = await this.prisma.blockchainProof.findUnique({ where: { id: proofId } }); if (!proof) throw new BusinessException(ErrorCode.NOT_FOUND, '存证记录不存在', 404); @@ -75,7 +94,12 @@ export class AttestationService { }, }, }); - await this.queue.add('onchain', { proofId }); + try { + await this.queue.add('onchain', { proofId }); + } catch (e) { + await this.markQueueFailed(proofId, proof.rawResponse, e); + throw new BusinessException(ErrorCode.INTERNAL_ERROR, '上链任务入队失败,请稍后重试'); + } return { success: true }; } diff --git a/apps/api/src/blockchain/blockchain.controller.ts b/apps/api/src/blockchain/blockchain.controller.ts index 1995596..66e7cea 100644 --- a/apps/api/src/blockchain/blockchain.controller.ts +++ b/apps/api/src/blockchain/blockchain.controller.ts @@ -3,6 +3,7 @@ import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger'; import { RoleType } from '@artveris/shared'; import { AttestationService } from './attestation.service'; import { Roles } from '../common/decorators/roles.decorator'; +import { parseBigId } from '../common/utils/bigint.util'; @ApiTags('区块链存证') @ApiBearerAuth() @@ -14,7 +15,7 @@ export class BlockchainController { @Roles(RoleType.OPERATOR) @ApiOperation({ summary: '为追溯码触发数据存证上链' }) onchain(@Param('id') id: string) { - return this.attestation.trigger(BigInt(id)); + return this.attestation.trigger(parseBigId(id, '追溯码 ID')); } @Post('blockchain-proofs/:id/retry') diff --git a/apps/api/src/blockchain/blockchain.service.ts b/apps/api/src/blockchain/blockchain.service.ts index b9dde70..014f148 100644 --- a/apps/api/src/blockchain/blockchain.service.ts +++ b/apps/api/src/blockchain/blockchain.service.ts @@ -10,6 +10,15 @@ const TIANHE_TEST_URL = 'https://test.api.tichain.tianhecloud.com'; const TIANHE_PRODUCTION_URL = 'https://api.tichain.tianhecloud.com'; const DEFAULT_TIANHE_USER_ID = 'artveris-platform'; +// 递归按 key 排序的稳定序列化,用于内容哈希(与 JSON.stringify 不同,属性顺序不影响结果) +function stableStringify(value: unknown): string { + if (value === null || typeof value !== 'object') return JSON.stringify(value) ?? 'null'; + if (Array.isArray(value)) return `[${value.map(stableStringify).join(',')}]`; + const keys = Object.keys(value as Record).sort(); + const entries = keys.map((k) => `${JSON.stringify(k)}:${stableStringify((value as Record)[k])}`); + return `{${entries.join(',')}}`; +} + @Injectable() export class BlockchainService { private readonly logger = new Logger(BlockchainService.name); @@ -20,7 +29,8 @@ export class BlockchainService { ) {} hashData(data: unknown): string { - return '0x' + createHash('sha256').update(JSON.stringify(data)).digest('hex'); + // 稳定序列化:递归按 key 排序,确保「同数据同哈希」,不受对象属性顺序影响 + return '0x' + createHash('sha256').update(stableStringify(data)).digest('hex'); } async attest(payload: AttestPayload): Promise { diff --git a/apps/api/src/common/utils/bigint.util.ts b/apps/api/src/common/utils/bigint.util.ts new file mode 100644 index 0000000..8fe147f --- /dev/null +++ b/apps/api/src/common/utils/bigint.util.ts @@ -0,0 +1,13 @@ +import { ErrorCode } from '@artveris/shared'; +import { BusinessException } from '../exceptions/business.exception'; + +// 把路径参数/字符串安全转 BigInt。非法输入抛统一 BusinessException(400), +// 避免裸 BigInt() 抛原生 SyntaxError 被全局过滤器归为 500。 +export function parseBigId(value: string | number | bigint, label = 'ID'): bigint { + if (typeof value === 'bigint') return value; + const text = String(value).trim(); + if (!/^\d+$/.test(text)) { + throw new BusinessException(ErrorCode.BAD_REQUEST, `无效的${label}:${value}`, 400); + } + return BigInt(text); +} diff --git a/apps/api/src/config/runtime-config.ts b/apps/api/src/config/runtime-config.ts index 9cda700..147302b 100644 --- a/apps/api/src/config/runtime-config.ts +++ b/apps/api/src/config/runtime-config.ts @@ -26,16 +26,14 @@ function loadEnvFile(path: string): void { } // 启动早期把 .env 载入 process.env:优先 ARTVERIS_ENV_FILE / 运行目录 .env, -// 再兼容仓库根 ../../.env(本地开发时 API 的 cwd 为 apps/api)。 +// 再兼容仓库根 ../../.env(本地开发时 API 的 cwd 为 apps/api)。去重避免重复加载同一文件。 export function preloadRuntimeEnv(): void { - loadEnvFile(envFilePath()); - loadEnvFile(resolve(process.cwd(), '.env')); - loadEnvFile(resolve(process.cwd(), '../../.env')); -} - -export function isInstalled(): boolean { - preloadRuntimeEnv(); - return Boolean(process.env.DATABASE_URL) || existsSync(envFilePath()); + const seen = new Set(); + for (const path of [envFilePath(), resolve(process.cwd(), '.env'), resolve(process.cwd(), '../../.env')]) { + if (seen.has(path)) continue; + seen.add(path); + loadEnvFile(path); + } } export function isInstallMode(): boolean { diff --git a/apps/api/src/dashboard/dashboard.service.ts b/apps/api/src/dashboard/dashboard.service.ts index f730df8..7888d92 100644 --- a/apps/api/src/dashboard/dashboard.service.ts +++ b/apps/api/src/dashboard/dashboard.service.ts @@ -1,6 +1,6 @@ import { Injectable } from '@nestjs/common'; import dayjs from 'dayjs'; -import { QueryResult, TraceCodeStatus } from '@artveris/shared'; +import { QueryResult } from '@artveris/shared'; import { PrismaService } from '../prisma/prisma.service'; export interface DashboardOverviewQuery { @@ -37,7 +37,8 @@ export class DashboardService { ] = await this.prisma.$transaction([ this.prisma.artwork.count({ where: { deletedAt: null } }), this.prisma.traceCode.count(), - this.prisma.traceCode.count({ where: { status: TraceCodeStatus.ACTIVE } }), + // 已激活口径:累计激活过(firstActivatedAt 非空),激活后又被停用/异常的仍计入 + this.prisma.traceCode.count({ where: { firstActivatedAt: { not: null } } }), this.prisma.queryLog.count(), this.prisma.queryLog.count({ where: { queriedAt: { gte: todayStart } } }), this.prisma.queryLog.count({ diff --git a/apps/api/src/install-app.module.ts b/apps/api/src/install-app.module.ts index 79da1f5..effd832 100644 --- a/apps/api/src/install-app.module.ts +++ b/apps/api/src/install-app.module.ts @@ -8,7 +8,7 @@ import { InstallModule } from './install/install.module'; ConfigModule.forRoot({ isGlobal: true, load: [configuration], - envFilePath: ['../../.env', '.env'], + ignoreEnvFile: true, }), InstallModule, ], diff --git a/apps/api/src/main.ts b/apps/api/src/main.ts index 7e85cc5..4afcaaf 100644 --- a/apps/api/src/main.ts +++ b/apps/api/src/main.ts @@ -49,6 +49,18 @@ async function bootstrap(): Promise { 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, @@ -80,6 +92,9 @@ async function bootstrap(): Promise { 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')); diff --git a/apps/api/src/operation-log/operation-log.interceptor.ts b/apps/api/src/operation-log/operation-log.interceptor.ts index 3ae73c8..1f31317 100644 --- a/apps/api/src/operation-log/operation-log.interceptor.ts +++ b/apps/api/src/operation-log/operation-log.interceptor.ts @@ -1,4 +1,4 @@ -import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common'; +import { CallHandler, ExecutionContext, Injectable, Logger, NestInterceptor } from '@nestjs/common'; import { Request } from 'express'; import { Observable, throwError } from 'rxjs'; import { catchError, tap } from 'rxjs/operators'; @@ -79,8 +79,15 @@ function shouldLog(method: string, path: string): boolean { @Injectable() export class OperationLogInterceptor implements NestInterceptor { + private readonly logger = new Logger(OperationLogInterceptor.name); + constructor(private readonly logs: OperationLogService) {} + private write(data: Parameters[0]): void { + // 操作日志写入失败不应影响主流程,也不能抛未捕获 Promise + this.logs.create(data).catch((e) => this.logger.warn(`操作日志写入失败:${(e as Error).message}`)); + } + intercept(context: ExecutionContext, next: CallHandler): Observable { const req = context.switchToHttp().getRequest(); const method = req.method.toUpperCase(); @@ -105,14 +112,14 @@ export class OperationLogInterceptor implements NestInterceptor { return next.handle().pipe( tap(() => { - void this.logs.create({ + this.write({ ...base, status: 'SUCCESS', durationMs: Date.now() - started, }); }), catchError((err) => { - void this.logs.create({ + this.write({ ...base, status: 'FAILED', message: (err as Error)?.message || String(err), diff --git a/apps/api/src/outbound/import-preview.processor.ts b/apps/api/src/outbound/import-preview.processor.ts index 5c48e9e..fd8abcc 100644 --- a/apps/api/src/outbound/import-preview.processor.ts +++ b/apps/api/src/outbound/import-preview.processor.ts @@ -34,6 +34,13 @@ function parseDate(v?: string): Date | undefined | null { return Number.isNaN(d.getTime()) ? null : d; } +function mimeOf(path: string): string { + const ext = path.slice(path.lastIndexOf('.')).toLowerCase(); + if (ext === '.png') return 'image/png'; + if (ext === '.webp') return 'image/webp'; + return 'image/jpeg'; +} + function normalizeImagePath(raw: string): string { const p = raw.trim().replace(/^image\//i, 'images/'); if (!p) return ''; @@ -94,6 +101,7 @@ export class ImportPreviewProcessor extends WorkerHost { }); const storedImages = new Map(); + const seenShortCodes = new Map(); // shortCode -> 首次出现行号,用于包内去重 const rows: any[] = []; let valid = 0; let invalid = 0; @@ -122,6 +130,11 @@ export class ImportPreviewProcessor extends WorkerHost { try { if (!values.shortCode) throw new Error('追溯码为空'); + const firstRow = seenShortCodes.get(values.shortCode); + if (firstRow) { + throw new Error(`追溯码在本次导入中重复(首次出现于第 ${firstRow} 行)`); + } + seenShortCodes.set(values.shortCode, r); const code = await this.prisma.traceCode.findUnique({ where: { shortCode: values.shortCode }, include: { batch: true }, @@ -144,7 +157,7 @@ export class ImportPreviewProcessor extends WorkerHost { if (!img) throw new Error(`图片不存在:${p}`); if (!storedImages.has(p)) { await sharp(img).metadata(); - const saved = await this.storage.save(img, p.split('/').pop() || 'outbound.jpg', `image/${p.endsWith('.png') ? 'png' : 'jpeg'}`); + const saved = await this.storage.save(img, p.split('/').pop() || 'outbound.jpg', mimeOf(p)); storedImages.set(p, { key: saved.key, url: saved.url, name: saved.name, type: 'image' }); } imageItems.push(storedImages.get(p)!); diff --git a/apps/api/src/outbound/import.processor.ts b/apps/api/src/outbound/import.processor.ts index c73827c..3f1ac4e 100644 --- a/apps/api/src/outbound/import.processor.ts +++ b/apps/api/src/outbound/import.processor.ts @@ -47,7 +47,6 @@ export class ImportProcessor extends WorkerHost { where: { id: code.id }, data: { outTime: row.outTime ?? undefined, - outImage: imageItems[0]?.key || undefined, outImages: imageItems.length ? imageItems.map((item) => ({ key: item.key, name: item.name, type: item.type || 'image' })) : undefined, @@ -68,16 +67,22 @@ export class ImportProcessor extends WorkerHost { const resultUrl = await this.buildResultFile(sessionId); const status = fail === 0 ? JobStatus.SUCCESS : success === 0 ? JobStatus.FAILED : JobStatus.PARTIAL; + const imported = fail === 0; + const session = await this.prisma.outboundImportSession.findUnique({ where: { id: sessionId }, select: { fileKey: true } }); await this.prisma.$transaction([ this.prisma.outboundImportSession.update({ where: { id: sessionId }, - data: { status: fail === 0 ? 'IMPORTED' : 'FAILED' }, + data: { status: imported ? 'IMPORTED' : 'FAILED', fileKey: imported ? null : undefined }, }), this.prisma.job.update({ where: { id: jobId }, data: { total: rows.length, successCount: success, failCount: fail, status, resultFileUrl: resultUrl }, }), ]); + // 导入成功后删除原始上传 ZIP,避免长期占用存储(预览图片已成为业务数据,保留) + if (imported && session?.fileKey) { + await this.storage.remove(session.fileKey).catch((e) => this.logger.warn(`删除导入 ZIP 失败:${(e as Error).message}`)); + } this.logger.log(`出库导入完成:成功 ${success},失败 ${fail}`); } diff --git a/apps/api/src/outbound/outbound.controller.ts b/apps/api/src/outbound/outbound.controller.ts index d5c4a8f..3ab4b2f 100644 --- a/apps/api/src/outbound/outbound.controller.ts +++ b/apps/api/src/outbound/outbound.controller.ts @@ -19,6 +19,7 @@ import { OutboundDto } from './dto/outbound.dto'; import { QueryImportRowsDto } from './dto/import-session.dto'; import { Roles } from '../common/decorators/roles.decorator'; import { CurrentUser, AuthUser } from '../common/decorators/current-user.decorator'; +import { parseBigId } from '../common/utils/bigint.util'; @ApiTags('出库与上链') @ApiBearerAuth() @@ -30,7 +31,7 @@ export class OutboundController { @Roles(RoleType.OPERATOR) @ApiOperation({ summary: '单条登记出库 / 上链信息' }) updateSingle(@Param('id') id: string, @Body() dto: OutboundDto) { - return this.outboundService.updateSingle(BigInt(id), dto); + return this.outboundService.updateSingle(parseBigId(id, '追溯码 ID'), dto); } @Get('import/template') diff --git a/apps/api/src/outbound/outbound.service.ts b/apps/api/src/outbound/outbound.service.ts index a915806..64ffecf 100644 --- a/apps/api/src/outbound/outbound.service.ts +++ b/apps/api/src/outbound/outbound.service.ts @@ -6,7 +6,7 @@ import * as ExcelJS from 'exceljs'; import AdmZip from 'adm-zip'; import sharp from 'sharp'; import { Prisma, RoleType } from '@prisma/client'; -import { ErrorCode, JobType, OUTBOUND_IMPORT_COLUMNS, QUEUE_NAMES } from '@artveris/shared'; +import { ErrorCode, JobStatus, JobType, OUTBOUND_IMPORT_COLUMNS, QUEUE_NAMES } from '@artveris/shared'; import { PrismaService } from '../prisma/prisma.service'; import { StorageService } from '../storage/storage.service'; import { JobsService } from '../jobs/jobs.service'; @@ -37,10 +37,10 @@ export class OutboundService { const data: Prisma.TraceCodeUpdateInput = {}; if ('outTime' in dto) data.outTime = dto.outTime ? new Date(dto.outTime) : null; if ('outImageKeys' in dto || 'outImageKey' in dto) { - data.outImage = imageKeys[0] || null; + // 无图时写 DB NULL(而非 JSON null),保证出库状态筛选一致 data.outImages = imageKeys.length ? imageKeys.map((key) => ({ key, type: 'image', name: key.split('/').pop() || '出库实况图' })) - : Prisma.JsonNull; + : Prisma.DbNull; } if ('remark' in dto) data.remark = dto.remark || null; return this.prisma.traceCode.update({ @@ -184,7 +184,14 @@ export class OutboundService { where: { id }, data: { status: 'IMPORTING', committedAt: new Date() }, }); - await this.importQueue.add('import', { jobId: job.id, sessionId: id }); + // 入队失败时回退会话状态为 READY,避免卡在 IMPORTING 且无对应队列任务 + try { + await this.importQueue.add('import', { jobId: job.id, sessionId: id }); + } catch (e) { + await this.prisma.outboundImportSession.update({ where: { id }, data: { status: 'READY', committedAt: null } }); + await this.jobs.finish(job.id, { status: JobStatus.FAILED, error: (e as Error).message }); + throw new BusinessException(ErrorCode.INTERNAL_ERROR, '导入任务入队失败,请稍后重试'); + } return { jobId: job.id, sessionId: id }; } } diff --git a/apps/api/src/public-trace/public-trace.controller.ts b/apps/api/src/public-trace/public-trace.controller.ts index af612ef..ec7f8d8 100644 --- a/apps/api/src/public-trace/public-trace.controller.ts +++ b/apps/api/src/public-trace/public-trace.controller.ts @@ -1,6 +1,7 @@ import { Controller, Get, Param, Req, Res } from '@nestjs/common'; import { Request, Response } from 'express'; import { ApiOperation, ApiTags } from '@nestjs/swagger'; +import { Throttle } from '@nestjs/throttler'; import { Public } from '../common/decorators/public.decorator'; import { extractIp } from '../common/utils/ua.util'; import { PublicTraceService } from './public-trace.service'; @@ -16,6 +17,8 @@ export class PublicTraceController { @Public() @Get('public/trace/:shortCode') + // 公开溯源软限流:每 IP 每分钟 60 次,抑制脚本刷量污染防伪统计与日志 + @Throttle({ default: { limit: 60, ttl: 60_000 } }) @ApiOperation({ summary: 'C 端溯源查询(匿名)' }) trace(@Param('shortCode') shortCode: string, @Req() req: Request) { const ip = extractIp(req.headers as Record, req.ip); diff --git a/apps/api/src/public-trace/public-trace.service.ts b/apps/api/src/public-trace/public-trace.service.ts index fc46629..7860635 100644 --- a/apps/api/src/public-trace/public-trace.service.ts +++ b/apps/api/src/public-trace/public-trace.service.ts @@ -15,8 +15,8 @@ export interface TraceContext { } const MAP_TTL = 3600; // 短码→id 映射缓存 1 小时 -const OUTBOUND_TRACE_TITLE = '本件出库记录'; -const OUTBOUND_TRACE_DESC = '该追溯码对应实物的出库实况记录。'; +const MISS_TTL = 60; // 无效码负缓存 60 秒,降低无效码刷库压力 +const MISS_SENTINEL = '0'; // 负缓存哨兵值(真实 id 从 1 起,不会为 0) @Injectable() export class PublicTraceService { @@ -44,12 +44,13 @@ export class PublicTraceService { description: string | null; mediaFiles: unknown; }>, - code: { outTime?: Date | null; outImage?: string | null; outImages?: unknown }, + code: { outTime?: Date | null; outImages?: unknown }, ) { const timeline = nodes.map((n) => ({ nodeType: n.nodeType, - title: n.title, - occurredAt: n.occurredAt, + system: null as string | null, + title: n.title as string | null, + occurredAt: n.occurredAt as Date | null, location: n.location, description: n.description, media: this.mapMedia(n.mediaFiles), @@ -60,17 +61,17 @@ export class PublicTraceService { .map((item) => (typeof item === 'string' ? { key: item } : item)) .filter((item) => item?.key) .map((item) => ({ name: item.name || '出库实况图', type: item.type || 'image', url: this.storage.getUrl(item.key as string) })) - : code.outImage - ? [{ name: '出库实况图', type: 'image', url: this.storage.getUrl(code.outImage) }] - : []; + : []; if (code.outTime || outMedia.length) { + // 单件出库记录:不下发中文标题/说明,标记 system=OUTBOUND_RECORD 由 C 端按语言本地化 timeline.push({ nodeType: 'OUTBOUND', - title: OUTBOUND_TRACE_TITLE, + system: 'OUTBOUND_RECORD', + title: null, occurredAt: code.outTime ?? null, location: null, - description: OUTBOUND_TRACE_DESC, + description: null, media: outMedia, }); } @@ -81,12 +82,17 @@ export class PublicTraceService { private async resolveId(shortCode: string): Promise { const cacheKey = `trace:map:${shortCode}`; const cached = await this.redis.get(cacheKey); + if (cached === MISS_SENTINEL) return null; if (cached) return BigInt(cached); const code = await this.prisma.traceCode.findUnique({ where: { shortCode }, select: { id: true }, }); - if (!code) return null; + if (!code) { + // 负缓存无效码,避免被脚本高频扫描时每次都落库 + await this.redis.set(cacheKey, MISS_SENTINEL, 'EX', MISS_TTL); + return null; + } await this.redis.set(cacheKey, code.id.toString(), 'EX', MAP_TTL); return code.id; } @@ -137,13 +143,14 @@ export class PublicTraceService { return { status: 'INVALID' as const }; } - // 激活 / 计数 + // 激活 / 计数:用条件更新消除并发首次扫码的竞态。 + // 只有真正把 INACTIVE 抢成 ACTIVE 的那一次请求 firstActivate=true(updateMany 返回 count=1), + // 其余并发请求 count=0,退化为原子自增,避免 queryCount 被双双写成 1、firstActivatedAt 被覆盖。 const now = new Date(); let firstActivate = false; - let updated; if (code.status === TraceCodeStatus.INACTIVE) { - updated = await this.prisma.traceCode.update({ - where: { id }, + const claimed = await this.prisma.traceCode.updateMany({ + where: { id, status: TraceCodeStatus.INACTIVE }, data: { status: TraceCodeStatus.ACTIVE, firstActivatedAt: now, @@ -151,13 +158,16 @@ export class PublicTraceService { lastQueriedAt: now, }, }); - firstActivate = true; - } else { - updated = await this.prisma.traceCode.update({ + firstActivate = claimed.count > 0; + } + if (!firstActivate) { + await this.prisma.traceCode.update({ where: { id }, data: { queryCount: { increment: 1 }, lastQueriedAt: now }, }); } + // 回查最新值组装响应(首次激活时读到自身写入,重复查询读到自增后的值) + const updated = await this.prisma.traceCode.findUniqueOrThrow({ where: { id } }); const proof = await this.prisma.blockchainProof.findFirst({ where: { traceCodeId: id, status: ProofStatus.ONCHAIN }, diff --git a/apps/api/src/settings/settings.service.ts b/apps/api/src/settings/settings.service.ts index 9a47b11..74809f6 100644 --- a/apps/api/src/settings/settings.service.ts +++ b/apps/api/src/settings/settings.service.ts @@ -1,4 +1,4 @@ -import { Injectable } from '@nestjs/common'; +import { Injectable, Logger } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import { createCipheriv, createDecipheriv, createHash, randomBytes } from 'crypto'; import { PrismaService } from '../prisma/prisma.service'; @@ -25,7 +25,6 @@ const EDITABLE_KEYS = [ 'ossBucket', 'ossAccessKeyId', 'ossAccessKeySecret', - 'settingsEncryptionKey', 'storageMigrationTarget', 'storageMigrationFingerprint', 'storageMigrationCopied', @@ -43,6 +42,8 @@ const ENCRYPTED_PREFIX = 'enc:v1:'; @Injectable() export class SettingsService { + private readonly logger = new Logger(SettingsService.name); + constructor( private readonly prisma: PrismaService, private readonly config: ConfigService, @@ -167,7 +168,10 @@ export class SettingsService { const decipher = createDecipheriv('aes-256-gcm', await this.encryptionKey(), iv); decipher.setAuthTag(tag); return Buffer.concat([decipher.update(encrypted), decipher.final()]).toString('utf8'); - } catch { + } catch (e) { + // 解密失败通常意味着 SETTING_ENCRYPTION_KEY 与加密时不一致(配置损坏), + // 显式告警而非静默返回空串,避免把「配置损坏」误当成「未配置」 + this.logger.warn(`密钥解密失败,可能是 SETTING_ENCRYPTION_KEY 已变更:${(e as Error).message}`); return ''; } } diff --git a/apps/api/src/trace-code/trace-code-generator.service.ts b/apps/api/src/trace-code/trace-code-generator.service.ts index 4c09fca..7b3d0ee 100644 --- a/apps/api/src/trace-code/trace-code-generator.service.ts +++ b/apps/api/src/trace-code/trace-code-generator.service.ts @@ -19,6 +19,20 @@ export class TraceCodeGeneratorService { constructor(private readonly prisma: PrismaService) {} async ensureSalt(): Promise { + // 溯源码盐优先以 .env 的 TRACE_CODE_SALT 为权威来源(安装向导写入、升级不覆盖); + // DB 中的 systemSetting.traceCodeSalt 仅作兜底缓存,二者以 env 为准,使「勿更改」注释名副其实。 + const envSalt = process.env.TRACE_CODE_SALT?.trim(); + if (envSalt) { + const existing = await this.prisma.systemSetting.findUnique({ where: { key: TRACE_CODE_SALT_KEY } }); + if (!existing?.value) { + await this.prisma.systemSetting.upsert({ + where: { key: TRACE_CODE_SALT_KEY }, + update: { value: envSalt }, + create: { key: TRACE_CODE_SALT_KEY, value: envSalt }, + }); + } + return envSalt; + } const existing = await this.prisma.systemSetting.findUnique({ where: { key: TRACE_CODE_SALT_KEY } }); if (existing?.value) return existing.value; const salt = randomBytes(32).toString('hex'); diff --git a/apps/api/src/trace-code/trace-code.controller.ts b/apps/api/src/trace-code/trace-code.controller.ts index 7f549b1..ce6a3f0 100644 --- a/apps/api/src/trace-code/trace-code.controller.ts +++ b/apps/api/src/trace-code/trace-code.controller.ts @@ -28,6 +28,7 @@ import { } from './dto/trace-code.dto'; import { Roles } from '../common/decorators/roles.decorator'; import { CurrentUser, AuthUser } from '../common/decorators/current-user.decorator'; +import { parseBigId } from '../common/utils/bigint.util'; @ApiTags('批量生码') @ApiBearerAuth() @@ -134,7 +135,7 @@ export class TraceCodeController { @Get('trace-codes/:id/qrcode') @ApiOperation({ summary: '获取追溯码二维码 PNG' }) async qrcode(@Param('id') id: string, @Res() res: Response) { - const buf = await this.service.getQrPng(BigInt(id)); + const buf = await this.service.getQrPng(parseBigId(id, '追溯码 ID')); res.setHeader('Content-Type', 'image/png'); res.end(buf); } diff --git a/apps/api/src/trace-code/trace-code.service.ts b/apps/api/src/trace-code/trace-code.service.ts index 40fed77..cc44363 100644 --- a/apps/api/src/trace-code/trace-code.service.ts +++ b/apps/api/src/trace-code/trace-code.service.ts @@ -8,12 +8,13 @@ import * as ExcelJS from 'exceljs'; import * as QRCode from 'qrcode'; import AdmZip from 'adm-zip'; import dayjs from 'dayjs'; -import { BatchStatus, ErrorCode, JobType, QUEUE_NAMES, TraceCodeStatus } from '@artveris/shared'; +import { BatchStatus, ErrorCode, JobStatus, JobType, QUEUE_NAMES, TraceCodeStatus } from '@artveris/shared'; import { PrismaService } from '../prisma/prisma.service'; import { StorageService } from '../storage/storage.service'; import { BusinessException } from '../common/exceptions/business.exception'; import { buildPage } from '../common/utils/pagination.util'; import { buildOrderBy } from '../common/utils/sort.util'; +import { parseBigId } from '../common/utils/bigint.util'; import { JobsService } from '../jobs/jobs.service'; import { SettingsService } from '../settings/settings.service'; import { @@ -60,13 +61,12 @@ export class TraceCodeService { } } - private mapOutImages(code: { outImage?: string | null; outImages?: unknown }) { + private mapOutImages(code: { outImages?: unknown }) { const keys = Array.isArray(code.outImages) ? (code.outImages as Array<{ key?: string; name?: string; type?: string }>) .map((item) => (typeof item === 'string' ? { key: item } : item)) .filter((item) => item?.key) : []; - if (!keys.length && code.outImage) keys.push({ key: code.outImage }); return keys.map((item) => ({ ...item, url: this.storage.getUrl(item.key as string), @@ -96,13 +96,20 @@ export class TraceCodeService { artworkId: dto.artworkId, groupId: dto.groupId ?? null, }); - await this.genQueue.add('generate', { - batchId: batch.id, - artworkId: dto.artworkId, - jobId: job.id, - quantity: dto.quantity, - groupId: dto.groupId ?? null, - }); + // 入队失败时回滚 batch 并把 job 标记失败,避免留下永远 PENDING 的悬挂批次 + try { + await this.genQueue.add('generate', { + batchId: batch.id, + artworkId: dto.artworkId, + jobId: job.id, + quantity: dto.quantity, + groupId: dto.groupId ?? null, + }); + } catch (e) { + await this.jobs.finish(job.id, { status: JobStatus.FAILED, error: (e as Error).message }); + await this.prisma.batch.update({ where: { id: batch.id }, data: { status: BatchStatus.FAILED } }); + throw new BusinessException(ErrorCode.INTERNAL_ERROR, '生码任务入队失败,请稍后重试'); + } return { batchId: batch.id, batchNo, jobId: job.id, quantity: dto.quantity }; } @@ -139,41 +146,44 @@ export class TraceCodeService { // ===== 批量操作 ===== async batchSetGroup(dto: BatchGroupDto) { - const ids = dto.ids.map((i) => BigInt(i)); - await this.prisma.traceCode.updateMany({ + const ids = dto.ids.map((i) => parseBigId(i, '追溯码 ID')); + if (dto.groupId !== undefined && dto.groupId !== null) await this.ensureGroup(dto.groupId); + const res = await this.prisma.traceCode.updateMany({ where: { id: { in: ids } }, data: { groupId: dto.groupId ?? null }, }); - return { success: true, count: ids.length }; + return { success: true, count: res.count }; } async batchSetStatus(dto: BatchStatusDto) { - const ids = dto.ids.map((i) => BigInt(i)); + const ids = dto.ids.map((i) => parseBigId(i, '追溯码 ID')); if (dto.abnormal) { // 标记异常:用于运营人员标注疑似被复制/盗用的码 - await this.prisma.traceCode.updateMany({ + const res = await this.prisma.traceCode.updateMany({ where: { id: { in: ids } }, data: { status: TraceCodeStatus.ABNORMAL }, }); - } else if (dto.disabled) { - await this.prisma.traceCode.updateMany({ + return { success: true, count: res.count }; + } + if (dto.disabled) { + const res = await this.prisma.traceCode.updateMany({ where: { id: { in: ids } }, data: { status: TraceCodeStatus.DISABLED }, }); - } else { - // 启用:已激活过的恢复为 ACTIVE,否则恢复为 INACTIVE - await this.prisma.$transaction([ - this.prisma.traceCode.updateMany({ - where: { id: { in: ids }, firstActivatedAt: { not: null } }, - data: { status: TraceCodeStatus.ACTIVE }, - }), - this.prisma.traceCode.updateMany({ - where: { id: { in: ids }, firstActivatedAt: null }, - data: { status: TraceCodeStatus.INACTIVE }, - }), - ]); + return { success: true, count: res.count }; } - return { success: true, count: ids.length }; + // 启用:已激活过的恢复为 ACTIVE,否则恢复为 INACTIVE + const [active, inactive] = await this.prisma.$transaction([ + this.prisma.traceCode.updateMany({ + where: { id: { in: ids }, firstActivatedAt: { not: null } }, + data: { status: TraceCodeStatus.ACTIVE }, + }), + this.prisma.traceCode.updateMany({ + where: { id: { in: ids }, firstActivatedAt: null }, + data: { status: TraceCodeStatus.INACTIVE }, + }), + ]); + return { success: true, count: active.count + inactive.count }; } private async resolveTargetBatch(options: { @@ -223,7 +233,7 @@ export class TraceCodeService { } async batchMove(dto: BatchMoveDto, userId: number) { - const ids = dto.ids.map((i) => BigInt(i)); + const ids = dto.ids.map((i) => parseBigId(i, '追溯码 ID')); const codes = await this.prisma.traceCode.findMany({ where: { id: { in: ids } }, select: { id: true, artworkId: true, batchId: true }, @@ -277,7 +287,7 @@ export class TraceCodeService { } async updateOne(id: string, dto: UpdateTraceCodeDto, userId?: number) { - const traceCodeId = BigInt(id); + const traceCodeId = parseBigId(id, '追溯码 ID'); const code = await this.prisma.traceCode.findUnique({ where: { id: traceCodeId } }); if (!code) throw new BusinessException(ErrorCode.TRACE_CODE_NOT_FOUND, '追溯码不存在', 404); @@ -349,7 +359,7 @@ export class TraceCodeService { } async batchDelete(dto: BatchDeleteDto) { - const ids = dto.ids.map((item) => BigInt(item)); + const ids = dto.ids.map((item) => parseBigId(item, '追溯码 ID')); const codes = await this.prisma.traceCode.findMany({ where: { id: { in: ids } }, select: { id: true, batchId: true }, @@ -404,9 +414,9 @@ export class TraceCodeService { if (query.groupId) where.groupId = query.groupId; if (query.status) where.status = query.status; if (query.outboundStatus === 'OUTBOUND') { - and.push({ OR: [{ outTime: { not: null } }, { outImage: { not: null } }] }); + and.push({ OR: [{ outTime: { not: null } }, { outImages: { not: Prisma.DbNull } }] }); } else if (query.outboundStatus === 'NOT_OUTBOUND') { - and.push({ outTime: null, outImage: null }); + and.push({ outTime: null, outImages: { equals: Prisma.DbNull } }); } if (query.keyword) { and.push({ @@ -452,10 +462,11 @@ export class TraceCodeService { list.map((code) => { const { proofs, ...rest } = code; const latestOnchainProof = proofs.find((p) => p.status === 'ONCHAIN') ?? null; + const outImages = this.mapOutImages(code); return { ...rest, - outImageUrl: code.outImage ? this.storage.getUrl(code.outImage) : null, - outImages: this.mapOutImages(code), + outImageUrl: outImages[0]?.url ?? null, + outImages, latestProof: latestOnchainProof, latestAnyProof: proofs[0] ?? null, }; @@ -483,7 +494,7 @@ export class TraceCodeService { .split(',') .map((s) => s.trim()) .filter(Boolean) - .map((s) => BigInt(s)); + .map((s) => parseBigId(s, '追溯码 ID')); where.id = { in: idList }; } else { Object.assign(where, this.buildTraceCodeWhere(dto)); diff --git a/packages/shared/src/constants.ts b/packages/shared/src/constants.ts index cf2bd30..f1fd0b3 100644 --- a/packages/shared/src/constants.ts +++ b/packages/shared/src/constants.ts @@ -14,7 +14,9 @@ export const TRACE_CODE_PATTERN = /^\d{12}$/; export const MAX_IMAGE_SIZE = 10 * 1024 * 1024; export const MAX_VIDEO_SIZE = 100 * 1024 * 1024; export const MAX_FILE_SIZE = 20 * 1024 * 1024; -export const ALLOWED_IMAGE_TYPES = ['image/jpeg', 'image/png', 'image/webp', 'image/gif', 'image/svg+xml']; +// 不允许上传 SVG:SVG 可内嵌脚本,从同源 /uploads 直接打开会造成存储型 XSS。 +// 内置默认图标是打包进前端的静态 svg(/admin、/trace 下),不经上传,不受影响。 +export const ALLOWED_IMAGE_TYPES = ['image/jpeg', 'image/png', 'image/webp', 'image/gif']; export const ALLOWED_VIDEO_TYPES = ['video/mp4', 'video/webm', 'video/quicktime']; export const ALLOWED_DOC_TYPES = ['application/pdf', 'image/jpeg', 'image/png']; diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index e5e6cea..46b553b 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -95,6 +95,9 @@ importers: '@nestjs/swagger': specifier: ^8.1.0 version: 8.1.1(@nestjs/common@10.4.22(class-transformer@0.5.1)(class-validator@0.14.4)(reflect-metadata@0.2.2)(rxjs@7.8.2))(@nestjs/core@10.4.22)(class-transformer@0.5.1)(class-validator@0.14.4)(reflect-metadata@0.2.2) + '@nestjs/throttler': + specifier: ^6.5.0 + version: 6.5.0(@nestjs/common@10.4.22(class-transformer@0.5.1)(class-validator@0.14.4)(reflect-metadata@0.2.2)(rxjs@7.8.2))(@nestjs/core@10.4.22)(reflect-metadata@0.2.2) '@prisma/client': specifier: ^5.22.0 version: 5.22.0(prisma@5.22.0) @@ -1100,6 +1103,13 @@ packages: '@nestjs/platform-express': optional: true + '@nestjs/throttler@6.5.0': + resolution: {integrity: sha512-9j0ZRfH0QE1qyrj9JjIRDz5gQLPqq9yVC2nHsrosDVAfI5HHw08/aUAWx9DZLSdQf4HDkmhTTEGLrRFHENvchQ==} + peerDependencies: + '@nestjs/common': ^7.0.0 || ^8.0.0 || ^9.0.0 || ^10.0.0 || ^11.0.0 + '@nestjs/core': ^7.0.0 || ^8.0.0 || ^9.0.0 || ^10.0.0 || ^11.0.0 + reflect-metadata: ^0.1.13 || ^0.2.0 + '@nuxtjs/opencollective@0.3.2': resolution: {integrity: sha512-um0xL3fO7Mf4fDxcqx9KryrB7zgRM5JSlvGN5AGkP6JLM5XEKyjeAiPbNxdXVXQ16isuAhYpvP88NgL2BGd6aA==} engines: {node: '>=8.0.0', npm: '>=5.0.0'} @@ -5049,6 +5059,12 @@ snapshots: optionalDependencies: '@nestjs/platform-express': 10.4.22(@nestjs/common@10.4.22(class-transformer@0.5.1)(class-validator@0.14.4)(reflect-metadata@0.2.2)(rxjs@7.8.2))(@nestjs/core@10.4.22) + '@nestjs/throttler@6.5.0(@nestjs/common@10.4.22(class-transformer@0.5.1)(class-validator@0.14.4)(reflect-metadata@0.2.2)(rxjs@7.8.2))(@nestjs/core@10.4.22)(reflect-metadata@0.2.2)': + dependencies: + '@nestjs/common': 10.4.22(class-transformer@0.5.1)(class-validator@0.14.4)(reflect-metadata@0.2.2)(rxjs@7.8.2) + '@nestjs/core': 10.4.22(@nestjs/common@10.4.22(class-transformer@0.5.1)(class-validator@0.14.4)(reflect-metadata@0.2.2)(rxjs@7.8.2))(@nestjs/platform-express@10.4.22)(reflect-metadata@0.2.2)(rxjs@7.8.2) + reflect-metadata: 0.2.2 + '@nuxtjs/opencollective@0.3.2': dependencies: chalk: 4.1.2