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
@@ -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));