fix: 修复后端竞态/安全/数据处理问题并移除冗余 outImage 列

首次激活改条件更新消除并发竞态;备份恢复补模型全集与版本校验防清库;
审核列表分页总数、操作日志未捕获 Promise、出库导入重复码、加密密钥可编辑、
溯源码盐以 env 为准、证书按 originKey reconcile、env 加载去重等修复;
新增 parseBigId 防非法入参 500、全局安全响应头、去除 SVG 上传、接入 throttler 限流、
入队失败补偿、hashData 稳定序列化、无效码负缓存、看板已激活口径调整;
移除冗余 TraceCode.outImage 列统一 outImages(迁移 drop_trace_code_out_image)。
This commit is contained in:
Nixevol
2026-07-09 13:14:26 +08:00
parent c39974e72d
commit f712b16c1f
29 changed files with 328 additions and 170 deletions
+6 -1
View File
@@ -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 {}
+32 -15
View File
@@ -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<MediaItem & { url: string }> };
@@ -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 },
});
}
}
}
+3
View File
@@ -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);
+34 -2
View File
@@ -97,10 +97,38 @@ function reviveRow(row: Record<string, any>): Record<string, any> {
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<string, unknown>;
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();
+27 -3
View File
@@ -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 };
}
@@ -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')
+11 -1
View File
@@ -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<string, unknown>).sort();
const entries = keys.map((k) => `${JSON.stringify(k)}:${stableStringify((value as Record<string, unknown>)[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<AttestResult> {
+13
View File
@@ -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);
}
+7 -9
View File
@@ -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<string>();
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 {
+3 -2
View File
@@ -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({
+1 -1
View File
@@ -8,7 +8,7 @@ import { InstallModule } from './install/install.module';
ConfigModule.forRoot({
isGlobal: true,
load: [configuration],
envFilePath: ['../../.env', '.env'],
ignoreEnvFile: true,
}),
InstallModule,
],
+15
View File
@@ -49,6 +49,18 @@ async function bootstrap(): Promise<void> {
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<void> {
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'));
@@ -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<OperationLogService['create']>[0]): void {
// 操作日志写入失败不应影响主流程,也不能抛未捕获 Promise
this.logs.create(data).catch((e) => this.logger.warn(`操作日志写入失败:${(e as Error).message}`));
}
intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {
const req = context.switchToHttp().getRequest<Request & { user?: AuthUser }>();
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),
@@ -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<string, { key: string; url: string; name: string; type: string }>();
const seenShortCodes = new Map<string, number>(); // 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)!);
+7 -2
View File
@@ -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}`);
}
+2 -1
View File
@@ -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')
+11 -4
View File
@@ -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 };
}
}
@@ -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<string, unknown>, req.ip);
@@ -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<bigint | null> {
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 },
+7 -3
View File
@@ -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 '';
}
}
@@ -19,6 +19,20 @@ export class TraceCodeGeneratorService {
constructor(private readonly prisma: PrismaService) {}
async ensureSalt(): Promise<string> {
// 溯源码盐优先以 .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');
@@ -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);
}
+49 -38
View File
@@ -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));