From f2d24dff0d7bef512504020143ae09aa3784aa2b Mon Sep 17 00:00:00 2001 From: Nixevol Date: Sun, 20 Sep 2026 01:40:04 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=94=AF=E6=8C=81=E6=B6=88=E8=B4=B9?= =?UTF-8?q?=E8=80=85=E6=8C=89=E5=AE=9E=E7=89=A9=E7=82=B9=E5=87=BB=E7=94=9F?= =?UTF-8?q?=E6=88=90=E5=A4=A9=E6=B2=B3=E9=93=BE=E5=AD=98=E8=AF=81=E8=AF=81?= =?UTF-8?q?=E4=B9=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/admin/src/locales/en-US.json | 4 +- apps/admin/src/locales/zh-CN.json | 4 +- apps/admin/src/views/Settings.vue | 12 ++ .../migration.sql | 13 ++ apps/api/prisma/schema.prisma | 12 ++ apps/api/src/backup/backup.service.ts | 13 ++ apps/api/src/blockchain/blockchain.module.ts | 6 +- .../deposit-certificate.controller.ts | 19 ++ .../deposit-certificate.service.spec.ts | 93 +++++++++ .../blockchain/deposit-certificate.service.ts | 195 ++++++++++++++++++ .../src/blockchain/deposit.provider.spec.ts | 43 ++++ apps/api/src/blockchain/deposit.provider.ts | 90 ++++++++ apps/api/src/settings/settings.service.ts | 13 +- apps/client/src/api.ts | 12 ++ .../trace/TraceBlockchainModule.vue | 62 +++++- .../components/trace/TraceModuleRenderer.vue | 3 + apps/client/src/locales/en-US.json | 31 ++- apps/client/src/locales/zh-CN.json | 31 ++- apps/client/src/router.ts | 1 + apps/client/src/views/Certificate.vue | 79 +++++++ apps/client/src/views/Trace.vue | 1 + docs/天河链按需出证测试结论.md | 43 ++++ docs/消费者按需存证证书.md | 53 +++++ 23 files changed, 810 insertions(+), 23 deletions(-) create mode 100644 apps/api/prisma/migrations/20260920020000_on_demand_certificate/migration.sql create mode 100644 apps/api/src/blockchain/deposit-certificate.controller.ts create mode 100644 apps/api/src/blockchain/deposit-certificate.service.spec.ts create mode 100644 apps/api/src/blockchain/deposit-certificate.service.ts create mode 100644 apps/api/src/blockchain/deposit.provider.spec.ts create mode 100644 apps/api/src/blockchain/deposit.provider.ts create mode 100644 apps/client/src/views/Certificate.vue create mode 100644 docs/天河链按需出证测试结论.md create mode 100644 docs/消费者按需存证证书.md diff --git a/apps/admin/src/locales/en-US.json b/apps/admin/src/locales/en-US.json index 3f59061..ffeaa02 100644 --- a/apps/admin/src/locales/en-US.json +++ b/apps/admin/src/locales/en-US.json @@ -806,7 +806,9 @@ "tianheVerifyOk": "Verified. On-chain identity saved", "tianheManualHint": "Enter the saved User ID and User Key. The system verifies them with TiChain before saving (for reusing the existing wallet after reinstall/migration).", "tianheManualUserIdPh": "e.g. artveris-platform", - "tianheManualUserKeyPh": "The User Key you saved offline" + "tianheManualUserKeyPh": "The User Key you saved offline", + "certificateEnabled": "On-demand certificates", + "certificateDailyLimit": "Daily new certificate limit" }, "profile": { "title": "Personal Info", diff --git a/apps/admin/src/locales/zh-CN.json b/apps/admin/src/locales/zh-CN.json index 009940c..8529736 100644 --- a/apps/admin/src/locales/zh-CN.json +++ b/apps/admin/src/locales/zh-CN.json @@ -806,7 +806,9 @@ "tianheVerifyOk": "校验通过,链上身份已保存", "tianheManualHint": "输入已保存的 User ID 与 User Key,系统将向天河链校验后保存(用于重装/迁移后复用既有钱包)。", "tianheManualUserIdPh": "如 artveris-platform", - "tianheManualUserKeyPh": "已离线保存的 User Key" + "tianheManualUserKeyPh": "已离线保存的 User Key", + "certificateEnabled": "扫码页按需出证", + "certificateDailyLimit": "每日新增证书上限" }, "profile": { "title": "个人信息", diff --git a/apps/admin/src/views/Settings.vue b/apps/admin/src/views/Settings.vue index f0dce2e..66d6043 100644 --- a/apps/admin/src/views/Settings.vue +++ b/apps/admin/src/views/Settings.vue @@ -93,6 +93,12 @@ + + + + + + @@ -317,6 +323,8 @@ const form = reactive({ backupRetentionCount: 10, blockchainDriver: 'mock', tianheEnv: 'test', + certificateEnabled: true, + certificateDailyLimit: 100, tianheBaseUrl: TIANHE_TEST_URL, tianheAppId: '', tianheAppKey: '', @@ -362,6 +370,8 @@ async function load() { form.backupRetentionCount = Number(s.backupRetentionCount || 10); form.blockchainDriver = s.blockchainDriver || 'mock'; form.tianheEnv = s.tianheEnv || 'test'; + form.certificateEnabled = s.certificateEnabled !== 'false'; + form.certificateDailyLimit = Number(s.certificateDailyLimit ?? '100'); form.tianheBaseUrl = s.tianheBaseUrl || TIANHE_TEST_URL; form.tianheAppId = s.tianheAppId || ''; form.tianheAppKey = s.tianheAppKey || ''; @@ -551,6 +561,8 @@ async function save() { backupRetentionCount: String(form.backupRetentionCount), blockchainDriver: form.blockchainDriver, tianheEnv: form.tianheEnv, + certificateEnabled: String(form.certificateEnabled), + certificateDailyLimit: String(form.certificateDailyLimit ?? 0), tianheBaseUrl: form.tianheBaseUrl, tianheAppId: form.tianheAppId, tianheAppKey: form.tianheAppKey, diff --git a/apps/api/prisma/migrations/20260920020000_on_demand_certificate/migration.sql b/apps/api/prisma/migrations/20260920020000_on_demand_certificate/migration.sql new file mode 100644 index 0000000..20c2fab --- /dev/null +++ b/apps/api/prisma/migrations/20260920020000_on_demand_certificate/migration.sql @@ -0,0 +1,13 @@ +ALTER TABLE `blockchain_proof` + ADD COLUMN `certificate_state` VARCHAR(20) NOT NULL DEFAULT 'NONE', + ADD COLUMN `certificate_request` JSON NULL, + ADD COLUMN `certificate_url` TEXT NULL, + ADD COLUMN `certificate_error` TEXT NULL, + ADD COLUMN `certificate_attempts` INTEGER NOT NULL DEFAULT 0, + ADD COLUMN `certificate_next_check` DATETIME(3) NULL, + ADD COLUMN `certificate_lease_until` DATETIME(3) NULL, + ADD COLUMN `certificate_lease_token` VARCHAR(36) NULL, + ADD COLUMN `certificate_requested_at` DATETIME(3) NULL, + ADD COLUMN `certificate_generated_at` DATETIME(3) NULL; +CREATE INDEX `blockchain_proof_certificate_state_certificate_next_check_idx` + ON `blockchain_proof` (`certificate_state`, `certificate_next_check`); diff --git a/apps/api/prisma/schema.prisma b/apps/api/prisma/schema.prisma index 46838c7..73c868b 100644 --- a/apps/api/prisma/schema.prisma +++ b/apps/api/prisma/schema.prisma @@ -391,6 +391,17 @@ model BlockchainProof { failureReason String? @map("failure_reason") @db.Text lastSyncedAt DateTime? @map("last_synced_at") rawResponse Json? @map("raw_response") + // Consumer-requested V3 certificate; separate from the NFT mint transaction. + certificateState String @default("NONE") @map("certificate_state") @db.VarChar(20) + certificateRequest Json? @map("certificate_request") + certificateUrl String? @map("certificate_url") @db.Text + certificateError String? @map("certificate_error") @db.Text + certificateAttempts Int @default(0) @map("certificate_attempts") + certificateNextCheck DateTime? @map("certificate_next_check") + certificateLeaseUntil DateTime? @map("certificate_lease_until") + certificateLeaseToken String? @map("certificate_lease_token") @db.VarChar(36) + certificateRequestedAt DateTime? @map("certificate_requested_at") + certificateGeneratedAt DateTime? @map("certificate_generated_at") createdAt DateTime @default(now()) @map("created_at") updatedAt DateTime @updatedAt @map("updated_at") @@ -399,6 +410,7 @@ model BlockchainProof { jobItems JobItem[] @@unique([traceCodeId]) + @@index([certificateState, certificateNextCheck]) @@index([status]) @@index([onchainChunkId]) @@map("blockchain_proof") diff --git a/apps/api/src/backup/backup.service.ts b/apps/api/src/backup/backup.service.ts index 1f2827b..34c0b3a 100644 --- a/apps/api/src/backup/backup.service.ts +++ b/apps/api/src/backup/backup.service.ts @@ -73,6 +73,10 @@ const PRISMA_MODEL_BY_DELEGATE: Record<(typeof MODELS)[number], string> = { systemSetting: 'SystemSetting', }; const DATE_KEYS = new Set([ + 'certificateRequestedAt', + 'certificateGeneratedAt', + 'certificateNextCheck', + 'certificateLeaseUntil', 'lastLoginAt', 'createdAt', 'updatedAt', @@ -658,6 +662,15 @@ export class BackupService { const rows = Array.isArray(db[model]) ? db[model].map((row: unknown) => { const revived = reviveRow(row as Record) as Record; + // A snapshot cannot prove that the original worker never sent this request. + // Restore unfinished certificates in query-only mode, never resubmit. + if (model === 'blockchainProof' && revived.certificateRequest && + ['PENDING', 'SUBMITTING', 'CHECKING', 'WAITING'].includes(String(revived.certificateState))) { + revived.certificateState = 'UNKNOWN'; + revived.certificateLeaseToken = null; + revived.certificateLeaseUntil = null; + revived.certificateNextCheck = new Date(); + } return revived; }) : []; diff --git a/apps/api/src/blockchain/blockchain.module.ts b/apps/api/src/blockchain/blockchain.module.ts index 52b7e9d..ff9b828 100644 --- a/apps/api/src/blockchain/blockchain.module.ts +++ b/apps/api/src/blockchain/blockchain.module.ts @@ -7,12 +7,14 @@ import { AttestationService } from './attestation.service'; import { BlockchainController } from './blockchain.controller'; import { OnchainProcessor } from './onchain.processor'; import { OnchainRecoveryService } from './onchain-recovery.service'; +import { DepositCertificateService } from './deposit-certificate.service'; +import { DepositCertificateController } from './deposit-certificate.controller'; @Global() @Module({ imports: [BullModule.registerQueue({ name: QUEUE_NAMES.ONCHAIN }), SettingsModule], - controllers: [BlockchainController], - providers: [BlockchainService, AttestationService, OnchainProcessor, OnchainRecoveryService], + controllers: [BlockchainController, DepositCertificateController], + providers: [BlockchainService, AttestationService, OnchainProcessor, OnchainRecoveryService, DepositCertificateService], exports: [BlockchainService, AttestationService], }) export class BlockchainModule {} diff --git a/apps/api/src/blockchain/deposit-certificate.controller.ts b/apps/api/src/blockchain/deposit-certificate.controller.ts new file mode 100644 index 0000000..382e93c --- /dev/null +++ b/apps/api/src/blockchain/deposit-certificate.controller.ts @@ -0,0 +1,19 @@ +import { Controller, Get, Param, Post } from '@nestjs/common'; +import { Throttle } from '@nestjs/throttler'; +import { Public } from '../common/decorators/public.decorator'; +import { DepositCertificateService } from './deposit-certificate.service'; + +@Controller('public/trace/:shortCode/certificate') +export class DepositCertificateController { + constructor(private readonly certificates: DepositCertificateService) {} + + @Public() + @Get() + @Throttle({ default: { limit: 60, ttl: 60_000 } }) + status(@Param('shortCode') shortCode: string) { return this.certificates.status(shortCode); } + + @Public() + @Post() + @Throttle({ default: { limit: 5, ttl: 60_000 } }) + request(@Param('shortCode') shortCode: string) { return this.certificates.request(shortCode); } +} diff --git a/apps/api/src/blockchain/deposit-certificate.service.spec.ts b/apps/api/src/blockchain/deposit-certificate.service.spec.ts new file mode 100644 index 0000000..03039ef --- /dev/null +++ b/apps/api/src/blockchain/deposit-certificate.service.spec.ts @@ -0,0 +1,93 @@ +import { DepositCertificateService } from './deposit-certificate.service'; +import { DepositProvider } from './deposit.provider'; + +const settings = { + certificateEnabled: 'true', certificateDailyLimit: '100', blockchainDriver: 'tianhe', + tianheEnv: 'test', tianheAppId: 'app', tianheAppKey: 'key', tianheWalletAddress: '0x' + 'a'.repeat(40), +}; +function fixture(state = 'PENDING') { + const row: any = { + id: 1, traceCodeId: 1n, status: 'ONCHAIN', txHash: '0x' + 'c'.repeat(64), chainName: '天河链', + certificateState: state, certificateAttempts: 0, certificateLeaseUntil: null, + certificateRequest: { version: 1, environment: 'test', appId: 'app', address: settings.tianheWalletAddress, operateId: 'stable-op', text: 'frozen-evidence' }, + }; + const prisma = { + blockchainProof: { + updateMany: jest.fn().mockResolvedValue({ count: 1 }), + findUniqueOrThrow: jest.fn().mockResolvedValue(row), + }, + traceCode: { findUnique: jest.fn().mockResolvedValue({ shortCode: '123456000001', status: 'ACTIVE', artwork: { status: 'ACTIVE', auditStatus: 'APPROVED' }, proofs: [row] }) }, + $transaction: jest.fn(), + }; + const config = { getAllRaw: jest.fn().mockResolvedValue(settings), get: jest.fn().mockResolvedValue('true') }; + return { row, prisma, config, service: new DepositCertificateService(prisma as any, config as any) }; +} +describe('Consumer certificate lifecycle', () => { + afterEach(() => jest.restoreAllMocks()); + it('GET only reads persisted state and never starts a job or calls Tianhe', async () => { + const { service, prisma, config } = fixture('NONE'); + expect(await service.status('123456000001')).toMatchObject({ status: 'NONE', url: null }); + expect(prisma.blockchainProof.updateMany).not.toHaveBeenCalled(); + expect(prisma.$transaction).not.toHaveBeenCalled(); + expect(config.getAllRaw).not.toHaveBeenCalled(); + }); + it('returns an existing shared certificate without consulting credentials or submitting', async () => { + const { service, row, config } = fixture('READY'); + row.certificateUrl = 'https://test.tichain.tianhecloud.com/#/certificate?address=' + settings.tianheWalletAddress + '&txHash=0x' + 'a'.repeat(64) + '&digest=' + 'b'.repeat(64); + expect(await service.request('123456000001')).toMatchObject({ status: 'READY', url: row.certificateUrl }); + expect(config.getAllRaw).not.toHaveBeenCalled(); + }); + it('does not send when another worker owns the lease', async () => { + const { service, row, prisma } = fixture(); + prisma.blockchainProof.updateMany.mockResolvedValue({ count: 0 }); + const submit = jest.spyOn(DepositProvider.prototype, 'submit'); + await service.process(row); + expect(submit).not.toHaveBeenCalled(); + }); + it('a submission timeout changes to query-only, preserving the exact operation id', async () => { + const { service, row, prisma } = fixture(); + const submit = jest.spyOn(DepositProvider.prototype, 'submit').mockRejectedValue(new Error('timeout')); + await service.process(row); + expect(submit).toHaveBeenCalledWith(settings.tianheWalletAddress, 'stable-op', 'frozen-evidence'); + expect(prisma.blockchainProof.updateMany.mock.calls[1][0].data.certificateState).toBe('WAITING'); + row.certificateState = 'WAITING'; + jest.spyOn(DepositProvider.prototype, 'query').mockResolvedValue({ operateId: 'stable-op', status: 2, createTime: '', txHash: '' }); + const cert = jest.spyOn(DepositProvider.prototype, 'certificate'); + await service.process(row); + expect(submit).toHaveBeenCalledTimes(1); + expect(cert).not.toHaveBeenCalled(); + }); + it('recovers a crashed SUBMITTING worker by querying, not resubmitting', async () => { + const { service, row } = fixture('SUBMITTING'); + const submit = jest.spyOn(DepositProvider.prototype, 'submit'); + const query = jest.spyOn(DepositProvider.prototype, 'query').mockResolvedValue({ status: 2 }); + await service.process(row); + expect(submit).not.toHaveBeenCalled(); expect(query).toHaveBeenCalledWith(settings.tianheWalletAddress, 'stable-op'); + }); + it('stops before network calls if the wallet or environment changed', async () => { + const { service, row, config, prisma } = fixture(); + config.getAllRaw.mockResolvedValue({ ...settings, tianheEnv: 'production' }); + const submit = jest.spyOn(DepositProvider.prototype, 'submit'); + await service.process(row); + expect(submit).not.toHaveBeenCalled(); + expect(prisma.blockchainProof.updateMany.mock.calls[1][0].data.certificateState).toBe('UNKNOWN'); + }); + it('rejects inactive, disabled and unapproved items before creation', async () => { + const { service, prisma } = fixture('NONE'); + prisma.traceCode.findUnique.mockResolvedValue({ status: 'INACTIVE' } as any); + await expect(service.request('123456000001')).rejects.toThrow(); + expect(prisma.$transaction).not.toHaveBeenCalled(); + }); + it('uses an atomic NONE claim so a stale concurrent transaction cannot overwrite the request or consume quota', async () => { + const { service, prisma } = fixture('NONE'); + const tx = { + systemSetting: { upsert: jest.fn(), update: jest.fn() }, + $queryRaw: jest.fn().mockResolvedValue([{ value: '2026-09-20:1' }]), + blockchainProof: { updateMany: jest.fn().mockResolvedValue({ count: 0 }) }, + }; + prisma.$transaction.mockImplementation(async callback => callback(tx)); + await service.request('123456000001'); + expect(tx.blockchainProof.updateMany).toHaveBeenCalledWith(expect.objectContaining({ where: { id: 1, certificateState: 'NONE', status: 'ONCHAIN' } })); + expect(tx.systemSetting.update).not.toHaveBeenCalled(); + }); +}); diff --git a/apps/api/src/blockchain/deposit-certificate.service.ts b/apps/api/src/blockchain/deposit-certificate.service.ts new file mode 100644 index 0000000..8323f2a --- /dev/null +++ b/apps/api/src/blockchain/deposit-certificate.service.ts @@ -0,0 +1,195 @@ +import { Injectable, Logger } from '@nestjs/common'; +import { Interval } from '@nestjs/schedule'; +import { ArtworkStatus, AuditStatus, BlockchainProof, Prisma, ProofStatus, TraceCodeStatus } from '@prisma/client'; +import { randomBytes, randomUUID } from 'crypto'; +import { ErrorCode, TRACE_CODE_PATTERN } from '@artveris/shared'; +import { BusinessException } from '../common/exceptions/business.exception'; +import { PrismaService } from '../prisma/prisma.service'; +import { SettingsService } from '../settings/settings.service'; +import { DepositEnvironment, DepositProvider, DepositRejected, safeCertificateUrl } from './deposit.provider'; + +interface CertificateRequest { + version: 1; + environment: DepositEnvironment; + appId: string; + address: string; + operateId: string; + text: string; +} + +const ACTIVE_STATES = ['PENDING', 'SUBMITTING', 'WAITING', 'CHECKING']; +const MAX_CHECKS = 8; + +@Injectable() +export class DepositCertificateService { + private readonly logger = new Logger(DepositCertificateService.name); + private running = false; + + constructor(private readonly prisma: PrismaService, private readonly settings: SettingsService) {} + + private async eligible(shortCode: string) { + if (!TRACE_CODE_PATTERN.test(shortCode)) throw new BusinessException(ErrorCode.NOT_FOUND, '追溯码不可用', 404); + const code = await this.prisma.traceCode.findUnique({ + where: { shortCode }, include: { artwork: true, proofs: true }, + }); + const proof = code?.proofs[0]; + if (!code || code.status !== TraceCodeStatus.ACTIVE || code.artwork.deletedAt || + code.artwork.status !== ArtworkStatus.ACTIVE || code.artwork.auditStatus !== AuditStatus.APPROVED || + !proof || proof.status !== ProofStatus.ONCHAIN || !proof.txHash || proof.chainName !== '天河链') { + throw new BusinessException(ErrorCode.NOT_FOUND, '当前实物暂不支持出证', 404); + } + return { code, proof }; + } + + private view(proof: BlockchainProof) { + const request = proof.certificateRequest as unknown as CertificateRequest | null; + const url = request && proof.certificateState === 'READY' + ? safeCertificateUrl(proof.certificateUrl, request.environment, request.address) : null; + return { + status: proof.certificateState === 'READY' && !url ? 'FAILED' : proof.certificateState, + url, generatedAt: proof.certificateGeneratedAt, + }; + } + + /** No remote calls, writes, activation, or query-count changes. */ + async status(shortCode: string) { + const { proof } = await this.eligible(shortCode); + return this.view(proof); + } + + async request(shortCode: string) { + const { code, proof } = await this.eligible(shortCode); + if (proof.certificateState === 'READY') return this.view(proof); + const settings = await this.settings.getAllRaw(); + if (settings.certificateEnabled === 'false') throw new BusinessException(ErrorCode.BAD_REQUEST, '证书生成暂时关闭'); + if (proof.certificateState !== 'NONE') { + // An uncertain submission is never submitted again. User action only resumes queries. + if (proof.certificateState === 'UNKNOWN' && (!proof.certificateNextCheck || proof.certificateNextCheck <= new Date())) { + await this.prisma.blockchainProof.updateMany({ + where: { id: proof.id, certificateState: 'UNKNOWN', certificateNextCheck: { lte: new Date() } }, + data: { certificateState: 'WAITING', certificateAttempts: 0, certificateNextCheck: new Date() }, + }); + } + return this.view((await this.prisma.blockchainProof.findUniqueOrThrow({ where: { id: proof.id } }))); + } + const environment = settings.tianheEnv as DepositEnvironment; + if (settings.blockchainDriver !== 'tianhe' || !['test', 'production'].includes(environment) || + !settings.tianheAppId || !settings.tianheAppKey || !/^0x[0-9a-f]{40}$/i.test(settings.tianheWalletAddress || '')) { + throw new BusinessException(ErrorCode.BAD_REQUEST, '平台存证配置尚未就绪'); + } + const now = new Date(); + const request: CertificateRequest = { + version: 1, environment, appId: settings.tianheAppId, address: settings.tianheWalletAddress, + operateId: `avc${randomBytes(8).toString('hex')}`, + // The official TEXT certificate prints this verbatim; use readable labels. + text: [ + `作品:${code.artwork.title}`, + `作者:${code.artwork.artist || '未填写'}`, + `档案编号:${code.artwork.archiveNo}`, + `实物追溯码:${code.shortCode}`, + `数字身份交易:${proof.txHash}`, + `证据记录时间:${now.toISOString()}`, + ].join(';'), + }; + // DB quota lock survives Redis restarts and serializes initial requests across workers. + // No credentials or network calls inside the transaction. + await this.prisma.$transaction(async tx => { + const quotaKey = 'certificateDailyQuota'; + await tx.systemSetting.upsert({ where: { key: quotaKey }, create: { key: quotaKey, value: '' }, update: { key: quotaKey } }); + const [quota] = await tx.$queryRaw>`SELECT value FROM system_setting WHERE \`key\` = ${quotaKey} FOR UPDATE`; + // Use a conditional write, not a snapshot read: MySQL REPEATABLE READ can + // retain an older NONE snapshot while this transaction waited for the lock. + const claimed = await tx.blockchainProof.updateMany({ where: { id: proof.id, certificateState: 'NONE', status: ProofStatus.ONCHAIN }, data: { + certificateState: 'PENDING', certificateRequest: request as unknown as Prisma.InputJsonObject, + certificateRequestedAt: now, certificateNextCheck: now, + } }); + if (!claimed.count) return; + const day = new Date(now.getTime() + 8 * 3600_000).toISOString().slice(0, 10); + const [quotaDay, quotaCount] = (quota?.value || '').split(':'); + const count = quotaDay === day ? Number(quotaCount) || 0 : 0; + const limit = Math.min(10000, Math.max(0, Number(settings.certificateDailyLimit ?? '100') || 0)); + if (count >= limit) throw new BusinessException(ErrorCode.TOO_MANY_REQUESTS, '今日证书生成数量已达上限,请稍后再试', 429); + await tx.systemSetting.update({ where: { key: quotaKey }, data: { value: `${day}:${count + 1}` } }); + }); + return this.view(await this.prisma.blockchainProof.findUniqueOrThrow({ where: { id: proof.id } })); + } + + /** Persistent DB-backed work: only explicit requests enter PENDING. Restart-safe. */ + @Interval(5000) + async tick() { + if (this.running) return; + this.running = true; + try { + if ((await this.settings.get('certificateEnabled')) === 'false') return; + const now = new Date(); + const rows = await this.prisma.blockchainProof.findMany({ + where: { certificateState: { in: ACTIVE_STATES }, certificateNextCheck: { lte: now }, + OR: [{ certificateLeaseUntil: null }, { certificateLeaseUntil: { lt: now } }] }, + orderBy: { certificateRequestedAt: 'asc' }, take: 5, + }); + for (const row of rows) await this.process(row); + } catch { + this.logger.warn('Certificate worker unavailable; persisted requests will be checked again'); + } finally { this.running = false; } + } + + async process(row: BlockchainProof) { + const now = new Date(); + const token = randomUUID(); + const submit = row.certificateState === 'PENDING'; + const claimed = await this.prisma.blockchainProof.updateMany({ + where: { id: row.id, certificateState: row.certificateState, + certificateAttempts: row.certificateAttempts, certificateNextCheck: { lte: now }, + OR: [{ certificateLeaseUntil: null }, { certificateLeaseUntil: { lt: now } }] }, + data: { certificateState: submit ? 'SUBMITTING' : 'CHECKING', certificateLeaseToken: token, + certificateLeaseUntil: new Date(now.getTime() + 120_000) }, + }); + if (!claimed.count) return; + const finish = (data: Prisma.BlockchainProofUpdateManyMutationInput) => this.prisma.blockchainProof.updateMany({ + where: { id: row.id, certificateLeaseToken: token }, + data: { ...data, certificateLeaseUntil: null, certificateLeaseToken: null }, + }); + const attempts = row.certificateAttempts + 1; + let accepted = false; + try { + const request = row.certificateRequest as unknown as CertificateRequest; + const settings = await this.settings.getAllRaw(); + if (!request || request.version !== 1 || settings.blockchainDriver !== 'tianhe' || + settings.tianheEnv !== request.environment || settings.tianheAppId !== request.appId || + settings.tianheWalletAddress !== request.address || !settings.tianheAppKey) { + await finish({ certificateState: 'UNKNOWN', certificateError: '存证环境或钱包已变更,请恢复原配置后继续查询', certificateNextCheck: now }); + return; + } + const provider = new DepositProvider(request.environment, request.appId, settings.tianheAppKey); + if (submit) { + const current = await this.prisma.traceCode.findUnique({ where: { id: row.traceCodeId }, select: { shortCode: true } }); + try { await this.eligible(current?.shortCode || ''); } + catch { + await finish({ certificateState: 'FAILED', certificateError: '实物当前状态不允许出证', certificateNextCheck: null }); + return; + } + await provider.submit(request.address, request.operateId, request.text); + accepted = true; + await finish({ certificateState: 'WAITING', certificateError: null, certificateNextCheck: new Date(Date.now() + 5000) }); + return; + } + // A crashed/timed-out SUBMITTING job also comes here, never back to submit(). + const result = await provider.query(request.address, request.operateId); + const exists = result?.operateId === request.operateId && (Boolean(result?.createTime) || Boolean(result?.txHash)); + const url = exists ? await provider.certificate(request.address, request.operateId, request.text) : null; + if (url) { + await finish({ certificateState: 'READY', certificateUrl: url, certificateGeneratedAt: new Date(), + certificateError: null, certificateNextCheck: null, certificateAttempts: attempts }); + return; + } + await finish({ certificateState: attempts >= MAX_CHECKS ? 'UNKNOWN' : 'WAITING', + certificateAttempts: attempts, certificateError: '证书尚未就绪,后续仅查询原存证', + certificateNextCheck: new Date(Date.now() + 30_000) }); + } catch (error) { + const rejected = submit && !accepted && error instanceof DepositRejected; + await finish({ certificateState: rejected ? 'FAILED' : attempts >= MAX_CHECKS ? 'UNKNOWN' : 'WAITING', + certificateAttempts: attempts, certificateError: rejected ? '存证提交被拒绝,请联系平台管理员' : '远端结果暂未确认,后续仅查询原存证', + certificateNextCheck: new Date(Date.now() + 30_000) }); + } + } +} diff --git a/apps/api/src/blockchain/deposit.provider.spec.ts b/apps/api/src/blockchain/deposit.provider.spec.ts new file mode 100644 index 0000000..33324cf --- /dev/null +++ b/apps/api/src/blockchain/deposit.provider.spec.ts @@ -0,0 +1,43 @@ +import { depositSignature, DepositProvider, DepositRejected, safeCertificateUrl } from './deposit.provider'; +import { createHash } from 'crypto'; + +describe('V3 deposit protocol', () => { + afterEach(() => jest.restoreAllMocks()); + it('signs parameters deterministically with the V3 prefix convention', () => { + expect(depositSignature('/v1/deposit/query', { operateId: 'x', address: 'y' }, {}, '1000', 'secret')) + .toBe(depositSignature('/v1/deposit/query', { address: 'y', operateId: 'x' }, {}, '1000', 'secret')); + expect(depositSignature('/v1/deposit/query', { address: 'y' }, {}, '1000', 'secret')) + .not.toBe(depositSignature('/v1/deposit/query', {}, { address: 'y' }, '1000', 'secret')); + }); + it('rejects foreign, wrong-environment and credential-bearing certificate URLs', () => { + const suffix = '#/certificate?address=abc&txHash=0x' + 'a'.repeat(64) + '&digest=' + 'b'.repeat(64); + expect(safeCertificateUrl('https://test.tichain.tianhecloud.com/' + suffix, 'test', 'abc')).toBeTruthy(); + for (const base of ['https://evil.example/', 'https://tichain.tianhecloud.com/', 'https://user@test.tichain.tianhecloud.com/']) { + expect(safeCertificateUrl(base + suffix, 'test', 'abc')).toBeNull(); + } + expect(safeCertificateUrl('https://test.tichain.tianhecloud.com/' + suffix, 'test', 'wrong')).toBeNull(); + }); + it('uses signed headers, does not expose keys in URL/body and rejects ambiguous acceptance', async () => { + const fetcher = jest.spyOn(global, 'fetch').mockResolvedValue({ ok: true, json: async () => ({ code: 200, success: true, data: 'different-id' }) } as any); + await expect(new DepositProvider('test', 'app', 'secret').submit('address', 'op', '证据')) + .rejects.toThrow('uncertain'); + const [url, options] = fetcher.mock.calls[0]; + expect(String(url)).toBe('https://test.api.tichain.tianhecloud.com/v1/deposit/text/save'); + expect(JSON.stringify(options)).not.toContain('secret'); + expect(options?.redirect).toBe('error'); + }); + it('distinguishes explicit rejection from uncertain transport failure', async () => { + jest.spyOn(global, 'fetch').mockResolvedValue({ ok: true, json: async () => ({ code: 400, success: false }) } as any); + await expect(new DepositProvider('test', 'app', 'key').submit('addr', 'op', 'test')).rejects.toBeInstanceOf(DepositRejected); + }); + it('binds the returned certificate to the exact frozen evidence and preserves reserved characters', async () => { + const text = '作品:A&B + 100% #茶器'; + const digest = createHash('sha256').update(text).digest('hex'); + const value = 'https://test.tichain.tianhecloud.com/#/certificate?depositContent=broken&type=TEXT&address=addr&txHash=0x' + 'a'.repeat(64) + '&digest=' + digest; + jest.spyOn(global, 'fetch').mockResolvedValue({ ok: true, json: async () => ({ code: 200, success: true, data: value }) } as any); + const provider = new DepositProvider('test', 'app', 'key'); + const result = await provider.certificate('addr', 'op', text); + expect(new URLSearchParams(new URL(result!).hash.split('?')[1]).get('depositContent')).toBe(text); + await expect(provider.certificate('addr', 'op', 'different evidence')).rejects.toThrow('digest'); + }); +}); diff --git a/apps/api/src/blockchain/deposit.provider.ts b/apps/api/src/blockchain/deposit.provider.ts new file mode 100644 index 0000000..b3e899b --- /dev/null +++ b/apps/api/src/blockchain/deposit.provider.ts @@ -0,0 +1,90 @@ +import { createHash } from 'crypto'; + +export type DepositEnvironment = 'test' | 'production'; +export const DEPOSIT_ENDPOINTS = { + test: 'https://test.api.tichain.tianhecloud.com', + production: 'https://api.tichain.tianhecloud.com', +} as const; + +export function depositSignature(path: string, query: Record, body: Record, timestamp: string, key: string): string { + const params: Record = { path_url: path }; + for (const [k, v] of Object.entries(query)) params[`query_${k}`] = v; + for (const [k, v] of Object.entries(body)) params[`body_${k}`] = v; + const json = JSON.stringify(Object.fromEntries(Object.keys(params).sort().map(k => [k, params[k]]))); + return createHash('sha256').update(json + timestamp + key, 'utf8').digest('hex'); +} + +export function safeCertificateUrl(value: unknown, environment: DepositEnvironment, address?: string): string | null { + if (typeof value !== 'string') return null; + try { + const url = new URL(value); + const host = environment === 'test' ? 'test.tichain.tianhecloud.com' : 'tichain.tianhecloud.com'; + if (url.protocol !== 'https:' || url.hostname !== host || url.port || url.username || url.password || url.pathname !== '/' || !url.hash.startsWith('#/certificate?')) return null; + const params = new URLSearchParams(url.hash.slice('#/certificate?'.length)); + if (address && params.get('address')?.toLowerCase() !== address.toLowerCase()) return null; + if (!/^0x[0-9a-f]{64}$/i.test(params.get('txHash') || '') || !/^[0-9a-f]{64}$/i.test(params.get('digest') || '')) return null; + return url.toString(); + } catch { return null; } +} + +export class DepositRejected extends Error {} + +/** V3 uses signed headers and code=200, unlike the existing V2 provider. */ +export class DepositProvider { + constructor(private readonly environment: DepositEnvironment, private readonly appId: string, private readonly appKey: string) {} + + private async request(path: string, query: Record, body?: Record): Promise { + const stamp = String(Date.now()); + const url = new URL(path, DEPOSIT_ENDPOINTS[this.environment]); + for (const [key, value] of Object.entries(query)) url.searchParams.set(key, value); + // Do not log request headers, signed material, credentials, or evidence text. + const response = await fetch(url, { + method: body ? 'POST' : 'GET', + redirect: 'error', + signal: AbortSignal.timeout(25_000), + headers: { + 'Content-Type': 'application/json', + 'ti-appid': this.appId, + 'ti-timestamp': stamp, + 'ti-signature': depositSignature(path, query, body || {}, stamp, this.appKey), + }, + ...(body ? { body: JSON.stringify(body) } : {}), + }); + if (!response.ok) throw new Error(`Deposit HTTP ${response.status}`); + const result = await response.json() as any; + if (!result || typeof result !== 'object') throw new Error('Invalid deposit response'); + return result; + } + + async submit(address: string, operateId: string, text: string): Promise { + const result = await this.request('/v1/deposit/text/save', {}, { text, address, operateId, noDigest: false }); + if (result.success === false && result.code !== undefined) throw new DepositRejected(`Deposit rejected (${result.code})`); + if (Number(result.code) !== 200 || result.success !== true || result.data !== operateId) throw new Error('Deposit submission result uncertain'); + } + + async query(address: string, operateId: string): Promise { + const result = await this.request('/v1/deposit/query', { address, operateId }); + if (Number(result.code) !== 200 || result.success !== true) throw new Error('Deposit query failed'); + return result.data; + } + + async certificate(address: string, operateId: string, evidenceText: string): Promise { + const result = await this.request('/v1/deposit/certificate', { address, operateId }); + // Pending/not-found is not grounds for resubmitting a deposit. + if (Number(result.code) === 400 && result.success === false) return null; + if (Number(result.code) !== 200 || result.success !== true) throw new Error('Certificate query failed'); + const url = safeCertificateUrl(result.data, this.environment, address); + if (!url) throw new Error('Invalid certificate URL'); + const parsed = new URL(url); + const params = new URLSearchParams(parsed.hash.slice('#/certificate?'.length)); + if (params.get('digest') !== createHash('sha256').update(evidenceText, 'utf8').digest('hex')) { + throw new Error('Certificate digest does not match the submitted evidence'); + } + if (params.get('type') !== 'TEXT') throw new Error('Unexpected certificate type'); + // The provider returns partially unescaped text. Preserve &, #, +, % and Unicode + // from our frozen evidence, rather than allowing them to become URL parameters. + params.set('depositContent', evidenceText); + parsed.hash = '/certificate?' + params.toString(); + return parsed.toString(); + } +} diff --git a/apps/api/src/settings/settings.service.ts b/apps/api/src/settings/settings.service.ts index 6bac107..4f27331 100644 --- a/apps/api/src/settings/settings.service.ts +++ b/apps/api/src/settings/settings.service.ts @@ -1,4 +1,4 @@ -import { Injectable, Logger } from '@nestjs/common'; +import { BadRequestException, Injectable, Logger } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import { createCipheriv, createDecipheriv, createHash, randomBytes } from 'crypto'; import { PrismaService } from '../prisma/prisma.service'; @@ -29,6 +29,8 @@ const EDITABLE_KEYS = [ 'storageMigrationFingerprint', 'storageMigrationCopied', 'blockchainDriver', + 'certificateEnabled', + 'certificateDailyLimit', 'tianheEnv', 'tianheBaseUrl', 'tianheAppId', @@ -89,6 +91,8 @@ export class SettingsService { ossAccessKeySecret: this.config.get('storage.oss.accessKeySecret') || '', settingsEncryptionKey: this.config.get('settingsEncryptionKey') || '', blockchainDriver: this.config.get('blockchain.driver') || 'mock', + certificateEnabled: 'true', + certificateDailyLimit: '100', tianheEnv: 'test', tianheBaseUrl: this.config.get('blockchain.tianhe.baseUrl') || 'https://test.api.tichain.tianhecloud.com', tianheAppId: this.config.get('blockchain.tianhe.appId') || '', @@ -142,6 +146,13 @@ export class SettingsService { } async updateAtomic(values: Record): Promise { + if (values.certificateEnabled !== undefined && !['true', 'false'].includes(String(values.certificateEnabled))) { + throw new BadRequestException('Invalid certificate switch'); + } + if (values.certificateDailyLimit !== undefined && + (!/^\d+$/.test(String(values.certificateDailyLimit)) || Number(values.certificateDailyLimit) > 10000)) { + throw new BadRequestException('Certificate daily limit must be between 0 and 10000'); + } const updates: Array<{ key: string; value: string }> = []; for (const [key, value] of Object.entries(values)) { if (!EDITABLE_KEYS.includes(key)) continue; diff --git a/apps/client/src/api.ts b/apps/client/src/api.ts index e3f974b..1c4ed2c 100644 --- a/apps/client/src/api.ts +++ b/apps/client/src/api.ts @@ -43,3 +43,15 @@ export function fetchTracePreview(shortCode: string, token: string, state: 'inac export function fetchAppInfo(): Promise { return instance.get('/settings/public') as unknown as Promise; } + +export interface TraceCertificateResult { + status: 'NONE' | 'PENDING' | 'SUBMITTING' | 'CHECKING' | 'WAITING' | 'READY' | 'UNKNOWN' | 'FAILED'; + url: string | null; + generatedAt: string | null; +} +export function requestTraceCertificate(shortCode: string): Promise { + return instance.post(`/public/trace/${encodeURIComponent(shortCode)}/certificate`, {}) as unknown as Promise; +} +export function fetchTraceCertificate(shortCode: string): Promise { + return instance.get(`/public/trace/${encodeURIComponent(shortCode)}/certificate`) as unknown as Promise; +} diff --git a/apps/client/src/components/trace/TraceBlockchainModule.vue b/apps/client/src/components/trace/TraceBlockchainModule.vue index 6fe2b26..5bcefce 100644 --- a/apps/client/src/components/trace/TraceBlockchainModule.vue +++ b/apps/client/src/components/trace/TraceBlockchainModule.vue @@ -57,22 +57,31 @@ {{ t('chain.onchainAt') }} {{ formatTime(blockchain.onchainAt) }} - - {{ t('chain.explorer') }} → - +
+ + {{ t('chain.explorer') }} → + + +
+

{{ t('chain.certificatePreview') }}

+
{{ t('chain.notOnchain') }}
+ + diff --git a/apps/client/src/views/Trace.vue b/apps/client/src/views/Trace.vue index 8f533d7..29a0e77 100644 --- a/apps/client/src/views/Trace.vue +++ b/apps/client/src/views/Trace.vue @@ -84,6 +84,7 @@