Compare commits

...
10 Commits
50 changed files with 1666 additions and 254 deletions
+3
View File
@@ -61,3 +61,6 @@ AGENT.md
# AI 项目记忆已迁移至 MemRelay,本地导出目录不入库
aidocs/
# 临时分析文件
/Temp/
@@ -31,12 +31,6 @@
<n-descriptions-item v-if="proof?.onchainAt" :label="t('pages.blockchain.onchainAt')">
{{ fmt(proof.onchainAt) }}
</n-descriptions-item>
<n-descriptions-item v-if="proof?.explorerUrl" :label="t('pages.blockchain.explorer')">
<a :href="proof.explorerUrl" target="_blank" rel="noopener" class="proof-link">
{{ t('pages.blockchain.openExplorer') }}
<n-icon :component="OpenOutline" />
</a>
</n-descriptions-item>
<n-descriptions-item v-if="failureReason" :label="t('pages.operations.resultReason')">
<n-text type="error">{{ failureReason }}</n-text>
</n-descriptions-item>
@@ -96,7 +90,7 @@
import { computed, defineComponent, h, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { NButton, NIcon } from 'naive-ui';
import { CopyOutline, OpenOutline } from '@vicons/ionicons5';
import { CopyOutline } from '@vicons/ionicons5';
import { onchainApi, traceCodeApi } from '@/api';
import { useAuthStore } from '@/stores/auth';
import { fmt, statusType } from '@/utils/format';
+19 -1
View File
@@ -806,7 +806,25 @@
"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",
"certificateTextTemplate": "Certificate text",
"certificateTextHelpTitle": "Certificate text template help",
"certificateTextHelpIntro": "Wrap a field name in double braces to insert its value for the physical item. Supported fields:",
"certificateTextFields": {
"作品名称": "Artwork title",
"版本": "Value of the artwork template field labelled 版本, e.g. one-piece pack",
"追溯码": "Unique trace code for the physical item",
"档案编号": "Artwork archive number",
"作者": "Artist name"
},
"certificateTextHelpExample": "Default template:",
"certificateTextHelpResult": "Example: 十二生肖莲花手工杯 一个装",
"certificateTextHelpRules": "Reorder fields, add plain text, or press Enter for a newline. Missing values are empty; the resulting text must not be empty. Markdown and expressions are not supported. Maximum 500 characters. The official certificate page may collapse newlines into spaces. Changes apply only to new requests; existing and pending certificates keep their original text and links.",
"certificateTextInvalid": "Enter a template of 1–500 characters using the supported fields in double braces.",
"certificateAuthorMode": "Certificate author",
"certificateAuthorWallet": "Attestation wallet address",
"certificateAuthorArtist": "Artwork artist name",
"certificateAuthorHelp": "Select wallet address (default) or artwork artist name. An empty artist name falls back to the wallet address. This also applies when existing certificates are opened again. Only the displayed author changes; the attesting identity, evidence, hash and timestamp remain unchanged. No new certificate request is made."
},
"profile": {
"title": "Personal Info",
+19 -1
View File
@@ -806,7 +806,25 @@
"tianheVerifyOk": "校验通过,链上身份已保存",
"tianheManualHint": "输入已保存的 User ID 与 User Key,系统将向天河链校验后保存(用于重装/迁移后复用既有钱包)。",
"tianheManualUserIdPh": "如 artveris-platform",
"tianheManualUserKeyPh": "已离线保存的 User Key"
"tianheManualUserKeyPh": "已离线保存的 User Key",
"certificateTextTemplate": "证书文本模板",
"certificateTextHelpTitle": "证书文本模板帮助",
"certificateTextHelpIntro": "使用双花括号包裹字段名,生成证书时会替换为该实物对应的作品资料。支持以下字段:",
"certificateTextFields": {
"作品名称": "作品档案中的名称",
"版本": "作品模板中名为“版本”的字段值,例如“一个装”",
"追溯码": "当前实物的独立追溯码",
"档案编号": "作品档案编号",
"作者": "作品档案中的艺术家姓名"
},
"certificateTextHelpExample": "默认模板:",
"certificateTextHelpResult": "显示示例:十二生肖莲花手工杯 一个装",
"certificateTextHelpRules": "可调整字段顺序、插入普通文字或按 Enter 换行。缺失的字段显示为空;最终文字不能为空。不支持 Markdown 加粗或表达式。模板最多 500 字符;官方证书页可能将换行显示为空格。修改仅影响之后首次申请的证书,已生成或处理中的证书继续使用原文本和链接。",
"certificateTextInvalid": "模板不能为空且最多500字符,请使用帮助中列出的字段及双花括号。",
"certificateAuthorMode": "证书作者显示",
"certificateAuthorWallet": "存证钱包地址",
"certificateAuthorArtist": "作品作者名称",
"certificateAuthorHelp": "作者显示可单选“存证钱包地址”或“作品作者名称”,默认钱包地址。选择作品作者时取作品档案的艺术家姓名,未填写则显示钱包地址。此设置对下次打开的已有证书也生效,仅调整作者显示,不改变链上存证主体、证据正文、哈希和生成时间,不重新申请证书。"
},
"profile": {
"title": "个人信息",
+43
View File
@@ -93,9 +93,28 @@
<n-form-item :label="t('pages.settings.blockchainDriver')">
<n-select v-model:value="form.blockchainDriver" :options="blockchainDriverOptions" />
</n-form-item>
<n-form-item>
<template #label>
<span class="certificate-template-label">
{{ t('pages.settings.certificateTextTemplate') }}
<n-button text :aria-label="t('pages.settings.certificateTextHelpTitle')" @click="certificateHelpVisible = true">
<n-icon :component="HelpCircleOutline" />
</n-button>
</span>
</template>
<n-input v-model:value="form.certificateTextTemplate" type="textarea" :autosize="{ minRows: 2, maxRows: 5 }" :maxlength="500" :placeholder="DEFAULT_CERTIFICATE_TEXT_TEMPLATE" />
</n-form-item>
<n-form-item :label="t('pages.settings.tianheEnv')">
<n-select v-model:value="form.tianheEnv" :options="tianheEnvOptions" @update:value="onTianheEnvChange" />
</n-form-item>
<n-form-item :label="t('pages.settings.certificateAuthorMode')">
<n-radio-group v-model:value="form.certificateAuthorMode">
<n-space vertical :size="6">
<n-radio value="WALLET">{{ t('pages.settings.certificateAuthorWallet') }}</n-radio>
<n-radio value="ARTWORK_ARTIST">{{ t('pages.settings.certificateAuthorArtist') }}</n-radio>
</n-space>
</n-radio-group>
</n-form-item>
<n-form-item :label="t('pages.settings.tianheBaseUrl')">
<n-input v-model:value="form.tianheBaseUrl" :disabled="form.tianheEnv !== 'custom'" />
</n-form-item>
@@ -242,6 +261,16 @@
<n-input v-model:value="manualEntry.userKey" type="password" show-password-on="click" :placeholder="t('pages.settings.tianheManualUserKeyPh')" />
</n-form-item>
</n-modal>
<n-modal v-model:show="certificateHelpVisible" preset="card" :title="t('pages.settings.certificateTextHelpTitle')" style="width: min(560px, 90vw)" :bordered="false">
<p>{{ t('pages.settings.certificateTextHelpIntro') }}</p>
<ul class="certificate-template-help">
<li v-for="field in CERTIFICATE_TEXT_FIELDS" :key="field"><code v-text="'{{' + field + '}}'" /> — {{ t(`pages.settings.certificateTextFields.${field}`) }}</li>
</ul>
<p>{{ t('pages.settings.certificateTextHelpExample') }} <code v-text="DEFAULT_CERTIFICATE_TEXT_TEMPLATE" /></p>
<p>{{ t('pages.settings.certificateTextHelpResult') }}</p>
<p>{{ t('pages.settings.certificateTextHelpRules') }}</p>
<p>{{ t('pages.settings.certificateAuthorHelp') }}</p>
</n-modal>
</div>
</template>
@@ -255,6 +284,7 @@ import { CopyOutline, EyeOffOutline, EyeOutline, HelpCircleOutline } from '@vico
import BackupRestorePanel from '@/components/BackupRestorePanel.vue';
import MediaUpload from '@/components/MediaUpload.vue';
import { DEFAULT_APP_ICON_URL, resolveAppIcon, setFavicon } from '@/utils/appIcon';
import { CERTIFICATE_TEXT_FIELDS, DEFAULT_CERTIFICATE_TEXT_TEMPLATE, validateCertificateTextTemplate } from '@artveris/shared';
const { t } = useI18n();
const route = useRoute();
@@ -271,6 +301,7 @@ const rotatingIdentity = ref(false);
const revealKey = ref(false);
const appKeyRevealed = ref(false);
const manualEntryVisible = ref(false);
const certificateHelpVisible = ref(false);
const identity = reactive({ userId: '', userKey: '', userKeyMasked: '', address: '' });
const manualEntry = reactive({ userId: '', userKey: '' });
// load() 时记录的 AppKey 掩码值,用于区分「服务端掩码」与「用户新填的值」
@@ -316,6 +347,8 @@ const form = reactive({
backupRetentionDays: 30,
backupRetentionCount: 10,
blockchainDriver: 'mock',
certificateTextTemplate: DEFAULT_CERTIFICATE_TEXT_TEMPLATE,
certificateAuthorMode: 'WALLET',
tianheEnv: 'test',
tianheBaseUrl: TIANHE_TEST_URL,
tianheAppId: '',
@@ -362,6 +395,8 @@ async function load() {
form.backupRetentionCount = Number(s.backupRetentionCount || 10);
form.blockchainDriver = s.blockchainDriver || 'mock';
form.tianheEnv = s.tianheEnv || 'test';
form.certificateTextTemplate = s.certificateTextTemplate ?? DEFAULT_CERTIFICATE_TEXT_TEMPLATE;
form.certificateAuthorMode = s.certificateAuthorMode || 'WALLET';
form.tianheBaseUrl = s.tianheBaseUrl || TIANHE_TEST_URL;
form.tianheAppId = s.tianheAppId || '';
form.tianheAppKey = s.tianheAppKey || '';
@@ -533,6 +568,10 @@ async function verifyIdentity() {
}
async function save() {
if (validateCertificateTextTemplate(form.certificateTextTemplate)) {
message.error(t('pages.settings.certificateTextInvalid'));
return;
}
saving.value = true;
try {
const appIconUrl = form.appIconFiles[0]?.url || form.appIconFiles[0]?.key || '';
@@ -550,6 +589,8 @@ async function save() {
backupRetentionDays: String(form.backupRetentionDays),
backupRetentionCount: String(form.backupRetentionCount),
blockchainDriver: form.blockchainDriver,
certificateTextTemplate: form.certificateTextTemplate,
certificateAuthorMode: form.certificateAuthorMode,
tianheEnv: form.tianheEnv,
tianheBaseUrl: form.tianheBaseUrl,
tianheAppId: form.tianheAppId,
@@ -623,6 +664,8 @@ const identityKeyDisplay = computed(() => {
</script>
<style scoped>
.certificate-template-label { display: inline-flex; gap: 5px; align-items: center; }
.certificate-template-help { padding-left: 20px; line-height: 2; }
.settings-page {
height: var(--admin-content-height);
min-height: 0;
+3
View File
@@ -55,6 +55,9 @@ export default defineConfig({
server: {
port: 5173,
host: true,
strictPort: true,
watch: process.env.DOCKER_DEV === '1' ? { usePolling: true, interval: 300 } : undefined,
hmr: process.env.VITE_HMR_CLIENT_PORT ? { clientPort: Number(process.env.VITE_HMR_CLIENT_PORT) } : undefined,
// dev 下把 5173 打造成与生产一致的「单入口」:/api、/uploads、短链 /t 走 API,/trace 走 C 端 dev server。
// 生产由 API 单端口托管全部路径,短链 {BASE_URL}/t/xxx 天然可用;此处让本地行为对齐。
proxy: {
@@ -0,0 +1,21 @@
import { DEFAULT_CERTIFICATE_TEXT_TEMPLATE, renderCertificateText, validateCertificateTextTemplate } from '@artveris/shared';
const values = { '作品名称': '十二生肖莲花手工杯', '版本': '一个装', '追溯码': '295708006702', '档案编号': 'ARTVERIS-000005', '作者': '黄志伟' };
describe('证书文本模板', () => {
it('默认作品名称加版本', () => {
expect(renderCertificateText(DEFAULT_CERTIFICATE_TEXT_TEMPLATE, values)).toBe('十二生肖莲花手工杯 一个装');
});
it('支持自定义次序、普通文字、重复字段和真实换行', () => {
expect(renderCertificateText('{{版本}}:{{作品名称}}\n{{追溯码}} {{ 作者 }} {{档案编号}} {{版本}}', values))
.toBe('一个装:十二生肖莲花手工杯\n295708006702 黄志伟 ARTVERIS-000005 一个装');
});
it('缺少字段显示为空且字段值不进行二次模板替换', () => {
expect(renderCertificateText(DEFAULT_CERTIFICATE_TEXT_TEMPLATE, { ...values, '版本': '' })).toBe(values.作品名称);
expect(renderCertificateText('{{作品名称}}', { ...values, '作品名称': '{{作者}}' })).toBe('{{作者}}');
});
it('拒绝空值、超长、未知字段、错误花括号和表达式', () => {
for (const template of ['', ' ', 'a'.repeat(501), '{{不存在}}', '{作品名称}', '{{作品名称', '{{作品名称.toUpperCase()}}']) {
expect(validateCertificateTextTemplate(template)).not.toBeNull();
}
});
});
@@ -14,9 +14,10 @@ function fixture(state = 'PENDING') {
const prisma = {
blockchainProof: {
updateMany: jest.fn().mockResolvedValue({ count: 1 }),
update: jest.fn().mockResolvedValue(row),
findUniqueOrThrow: jest.fn().mockResolvedValue(row),
},
traceCode: { findUnique: jest.fn().mockResolvedValue({ shortCode: '123456000001', status: 'ACTIVE', artwork: { status: 'ACTIVE', auditStatus: 'APPROVED' }, proofs: [row] }) },
traceCode: { findUnique: jest.fn().mockResolvedValue({ shortCode: '123456000001', status: 'ACTIVE', artwork: { title: '测试作品', archiveNo: 'ARTVERIS-000001', status: 'ACTIVE', auditStatus: 'APPROVED' }, proofs: [row] }) },
$transaction: jest.fn(),
};
const config = { getAllRaw: jest.fn().mockResolvedValue(settings), get: jest.fn().mockResolvedValue('true') };
@@ -26,15 +27,20 @@ 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(await service.status('123456000001')).toMatchObject({ status: 'NONE', certificate: 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 });
row.certificateUrl = 'https://test.tichain.tianhecloud.com/#/certificate?address=' + settings.tianheWalletAddress + '&txHash=0x' + 'a'.repeat(64) + '&digest=' + 'b'.repeat(64) + '&createTime=1789844077000';
const result = await service.request('123456000001');
expect(result).toMatchObject({
status: 'READY',
certificate: { text: 'frozen-evidence', digest: 'b'.repeat(64), txHash: '0x' + 'a'.repeat(64), author: settings.tianheWalletAddress, createdAt: '2026-09-19T18:54:37.000Z' },
});
expect(JSON.stringify(result)).not.toContain('tianhecloud');
expect(config.getAllRaw).not.toHaveBeenCalled();
});
it('does not send when another worker owns the lease', async () => {
@@ -44,6 +50,19 @@ describe('Consumer certificate lifecycle', () => {
await service.process(row);
expect(submit).not.toHaveBeenCalled();
});
it('a refused connection on submit fails instead of querying an unsent deposit', async () => {
const { service, row, prisma } = fixture();
const cause = Object.assign(new Error('connect ECONNREFUSED 127.0.0.1:443'), { code: 'ECONNREFUSED' });
const failure = new TypeError('fetch failed');
(failure as { cause?: unknown }).cause = cause;
jest.spyOn(DepositProvider.prototype, 'submit').mockRejectedValue(failure);
await service.process(row);
expect(prisma.blockchainProof.updateMany.mock.calls[1][0].data).toMatchObject({
certificateState: 'FAILED',
certificateError: '暂时联系不上存证服务,证书没有生成。',
certificateNextCheck: null,
});
});
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'));
@@ -105,4 +124,15 @@ describe('Consumer certificate lifecycle', () => {
expect(row.certificateRequest).toBe(saved);
expect(writes).toBe(1);
});
it('defaults to title and version using the template label rather than assuming a version key', async () => {
const { service, prisma, row } = fixture('NONE');
prisma.traceCode.findUnique.mockResolvedValue({
shortCode: '295708006702', status: 'ACTIVE',
artwork: { title: '十二生肖莲花手工杯', status: 'ACTIVE', auditStatus: 'APPROVED', dynamicFields: { size: '一个装' }, template: { fields: [{ label: '版本', fieldKey: 'size' }] } },
proofs: [row],
} as any);
await service.request('295708006702');
expect(prisma.blockchainProof.updateMany.mock.calls[0][0].data.certificateRequest.text)
.toBe('十二生肖莲花手工杯 一个装');
});
});
@@ -2,11 +2,11 @@ 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 { DEFAULT_CERTIFICATE_TEXT_TEMPLATE, ErrorCode, renderCertificateText, 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';
import { DepositEnvironment, DepositProvider, DepositRejected, presentStoredCertificate } from './deposit.provider';
interface CertificateRequest {
version: 1;
@@ -19,6 +19,19 @@ interface CertificateRequest {
const ACTIVE_STATES = ['PENDING', 'SUBMITTING', 'WAITING', 'CHECKING'];
const MAX_CHECKS = 8;
const UNREACHABLE_MESSAGE = '暂时联系不上存证服务,证书没有生成。';
function depositUnreachable(error: unknown) {
const texts: string[] = [];
let current: unknown = error;
for (let depth = 0; depth < 3 && current instanceof Error; depth += 1) {
texts.push(current.message);
const code = (current as { code?: unknown }).code;
if (typeof code === 'string') texts.push(code);
current = (current as { cause?: unknown }).cause;
}
return /ECONNREFUSED|ENOTFOUND|EAI_AGAIN|EHOSTUNREACH|ECONNRESET/.test(texts.join(' '));
}
@Injectable()
export class DepositCertificateService {
@@ -30,7 +43,7 @@ export class DepositCertificateService {
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 },
where: { shortCode }, include: { artwork: { include: { template: { include: { fields: true } } } }, proofs: true },
});
const proof = code?.proofs[0];
if (!code || code.status !== TraceCodeStatus.ACTIVE || code.artwork.deletedAt ||
@@ -41,27 +54,32 @@ export class DepositCertificateService {
return { code, proof };
}
private view(proof: BlockchainProof) {
private async view(proof: BlockchainProof, artist?: string | null) {
const request = proof.certificateRequest as unknown as CertificateRequest | null;
const url = request && proof.certificateState === 'READY'
? safeCertificateUrl(proof.certificateUrl, request.environment, request.address) : null;
const certificate = request && proof.certificateState === 'READY'
? presentStoredCertificate(proof.certificateUrl, request.environment, request.address, request.text, await this.settings.get('certificateAuthorMode'), artist)
: null;
const status = proof.certificateState === 'READY' && !certificate ? 'FAILED' : proof.certificateState;
return {
status: proof.certificateState === 'READY' && !url ? 'FAILED' : proof.certificateState,
url, generatedAt: proof.certificateGeneratedAt,
status,
generatedAt: proof.certificateGeneratedAt,
certificate: certificate && request ? { ...certificate, environment: request.environment } : certificate,
message: status === 'READY' ? null : proof.certificateError,
};
}
/** No remote calls, writes, activation, or query-count changes. */
async status(shortCode: string) {
const { proof } = await this.eligible(shortCode);
return this.view(proof);
const { code, proof } = await this.eligible(shortCode);
return this.view(proof, code.artwork.artist);
}
async request(shortCode: string) {
const { code, proof } = await this.eligible(shortCode);
if (proof.certificateState === 'READY') return this.view(proof);
if (proof.certificateState === 'READY') return this.view(proof, code.artwork.artist);
const settings = await this.settings.getAllRaw();
if (proof.certificateState !== 'NONE') {
const retryUnreachable = proof.certificateState === 'FAILED' && !proof.certificateUrl && proof.certificateError === UNREACHABLE_MESSAGE;
if (proof.certificateState !== 'NONE' && !retryUnreachable) {
// 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({
@@ -69,7 +87,7 @@ export class DepositCertificateService {
data: { certificateState: 'WAITING', certificateAttempts: 0, certificateNextCheck: new Date() },
});
}
return this.view((await this.prisma.blockchainProof.findUniqueOrThrow({ where: { id: proof.id } })));
return this.view((await this.prisma.blockchainProof.findUniqueOrThrow({ where: { id: proof.id } })), code.artwork.artist);
}
const environment = settings.tianheEnv as DepositEnvironment;
if (settings.blockchainDriver !== 'tianhe' || !['test', 'production'].includes(environment) ||
@@ -77,29 +95,37 @@ export class DepositCertificateService {
throw new BusinessException(ErrorCode.BAD_REQUEST, '平台存证配置尚未就绪');
}
const now = new Date();
// “版本”是作品模板的动态字段;按显示名查键,不能假定数据库键叫version。
const versionField = code.artwork.template?.fields.find(field => field.label.trim() === '版本');
const dynamic = code.artwork.dynamicFields as Record<string, unknown> | null;
const versionValue = versionField ? dynamic?.[versionField.fieldKey] : undefined;
let text: string;
try {
text = renderCertificateText(settings.certificateTextTemplate ?? DEFAULT_CERTIFICATE_TEXT_TEMPLATE, {
'作品名称': code.artwork.title,
'版本': typeof versionValue === 'string' || typeof versionValue === 'number' ? String(versionValue) : '',
'追溯码': code.shortCode,
'档案编号': code.artwork.archiveNo || '',
'作者': code.artwork.artist || '',
});
} catch { throw new BusinessException(ErrorCode.BAD_REQUEST, '证书文本模板配置无效,请联系平台管理员'); }
if (!text || text.length > 2000) throw new BusinessException(ErrorCode.BAD_REQUEST, '证书文本为空或过长,请检查模板及作品字段');
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(';'),
// 冻结首次申请时渲染出的文本,模板变化不会改变已提交或已生成证书。
text,
};
// A single conditional write claims this item; concurrent callers cannot
// replace the winner's frozen evidence or operation id. No daily quota.
await this.prisma.blockchainProof.updateMany({
where: { id: proof.id, certificateState: 'NONE', status: ProofStatus.ONCHAIN },
where: { id: proof.id, certificateState: retryUnreachable ? 'FAILED' : 'NONE', status: ProofStatus.ONCHAIN },
data: {
certificateState: 'PENDING', certificateRequest: request as unknown as Prisma.InputJsonObject,
certificateRequestedAt: now, certificateNextCheck: now,
certificateError: null, certificateRequestedAt: now, certificateNextCheck: now,
},
});
return this.view(await this.prisma.blockchainProof.findUniqueOrThrow({ where: { id: proof.id } }));
return this.view(await this.prisma.blockchainProof.findUniqueOrThrow({ where: { id: proof.id } }), code.artwork.artist);
}
/** Persistent DB-backed work: only explicit requests enter PENDING. Restart-safe. */
@@ -174,9 +200,13 @@ export class DepositCertificateService {
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) });
const unreachable = submit && !accepted && depositUnreachable(error);
await finish({
certificateState: rejected || unreachable ? 'FAILED' : attempts >= MAX_CHECKS ? 'UNKNOWN' : 'WAITING',
certificateAttempts: attempts,
certificateError: rejected ? '存证提交被拒绝,请联系平台管理员' : unreachable ? UNREACHABLE_MESSAGE : '远端结果暂未确认,后续仅查询原存证',
certificateNextCheck: rejected || unreachable ? null : new Date(Date.now() + 30_000),
});
}
}
}
@@ -1,7 +1,18 @@
import { depositSignature, DepositProvider, DepositRejected, safeCertificateUrl } from './deposit.provider';
import { certificateAuthorUrl, depositSignature, DepositProvider, DepositRejected, presentStoredCertificate, safeCertificateUrl } from './deposit.provider';
import { createHash } from 'crypto';
describe('V3 deposit protocol', () => {
it('sets only the author display name, preserves wallet and proof data, and falls back when the artist is missing', () => {
const original = 'https://test.tichain.tianhecloud.com/#/certificate?address=wallet&txHash=hash&digest=digest&depositContent=title';
const result = certificateAuthorUrl(original, 'ARTWORK_ARTIST', '黄志伟 & A');
const query = new URLSearchParams(new URL(result).hash.split('?')[1]);
expect(query.get('author')).toBe('黄志伟 & A');
expect(query.get('address')).toBe('wallet');
expect(query.get('txHash')).toBe('hash');
expect(query.get('digest')).toBe('digest');
expect(certificateAuthorUrl(result, 'WALLET')).toBe(original);
expect(certificateAuthorUrl(result, 'ARTWORK_ARTIST', '')).toBe(original);
});
afterEach(() => jest.restoreAllMocks());
it('signs parameters deterministically with the V3 prefix convention', () => {
expect(depositSignature('/v1/deposit/query', { operateId: 'x', address: 'y' }, {}, '1000', 'secret'))
@@ -17,6 +28,16 @@ describe('V3 deposit protocol', () => {
}
expect(safeCertificateUrl('https://test.tichain.tianhecloud.com/' + suffix, 'test', 'wrong')).toBeNull();
});
it('presents stored certificate fields without the Tianhe page address', () => {
const address = '0x' + 'a'.repeat(40);
const txHash = '0x' + 'c'.repeat(64);
const digest = 'd'.repeat(64);
const stored = `https://tichain.tianhecloud.com/#/certificate?address=${address}&txHash=${txHash}&digest=${digest}&createTime=1789867663000`;
const view = presentStoredCertificate(stored, 'production', address, '十二生肖莲花手工杯', 'ARTWORK_ARTIST', '黄志伟');
expect(view).toEqual({ text: '十二生肖莲花手工杯', digest, txHash, author: '黄志伟', createdAt: '2026-09-20T01:27:43.000Z' });
expect(JSON.stringify(view)).not.toContain('tianhecloud');
expect(presentStoredCertificate(stored, 'production', address, '十二生肖莲花手工杯', 'WALLET', '黄志伟')?.author).toBe(address);
});
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', '证据'))
@@ -31,7 +52,7 @@ describe('V3 deposit protocol', () => {
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 text = 'A&B + 100% #茶器\n295708006702';
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);
@@ -14,6 +14,27 @@ export function depositSignature(path: string, query: Record<string, unknown>, b
return createHash('sha256').update(json + timestamp + key, 'utf8').digest('hex');
}
export interface StoredCertificateView {
text: string;
digest: string;
txHash: string;
author: string;
createdAt: string | null;
imageUrl?: string | null;
}
/** 公开页面只接收存证字段。天河链证书网址留在服务端,不进入浏览器。 */
export function presentStoredCertificate(value: unknown, environment: DepositEnvironment, address: string, text: string, mode: string | null, artist?: string | null): StoredCertificateView | null {
if (!safeCertificateUrl(value, environment, address) || !text.trim()) return null;
const params = new URLSearchParams(new URL(String(value)).hash.slice('#/certificate?'.length));
const digest = params.get('digest') || '';
const txHash = params.get('txHash') || '';
const rawTime = params.get('createTime');
const created = rawTime && /^\d+$/.test(rawTime) ? new Date(Number(rawTime)) : null;
const author = mode === 'ARTWORK_ARTIST' && artist?.trim() ? artist.trim() : address;
return { text, digest, txHash, author, createdAt: created && !Number.isNaN(created.getTime()) ? created.toISOString() : null };
}
export function safeCertificateUrl(value: unknown, environment: DepositEnvironment, address?: string): string | null {
if (typeof value !== 'string') return null;
try {
@@ -29,6 +50,16 @@ export function safeCertificateUrl(value: unknown, environment: DepositEnvironme
export class DepositRejected extends Error {}
/** 官方证书页的显示参数;保留原address、digest和txHash,不改变存证身份。 */
export function certificateAuthorUrl(url: string, mode: string | null, artist?: string | null): string {
const parsed = new URL(url);
const params = new URLSearchParams(parsed.hash.slice('#/certificate?'.length));
if (mode === 'ARTWORK_ARTIST' && artist?.trim()) params.set('author', artist.trim());
else params.delete('author');
parsed.hash = '/certificate?' + params.toString();
return parsed.toString();
}
/** 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) {}
+12 -4
View File
@@ -8,6 +8,7 @@ export interface AppConfig {
publicTracePath: string;
adminOrigin: string;
clientOrigin: string;
developmentClientBaseUrl?: string;
traceUrlTemplate: string;
jwt: { secret: string; expiresIn: string };
settingsEncryptionKey: string;
@@ -36,17 +37,24 @@ export interface AppConfig {
export default (): AppConfig => {
preloadRuntimeEnv();
const clientOrigin = process.env.CLIENT_ORIGIN || 'http://localhost:5174';
// Only an explicitly configured local development origin overrides imported settings.
const developmentOrigin = process.env.NODE_ENV === 'development'
? (process.env.ARTVERIS_DEV_ORIGIN || '').replace(/\/$/, '') : '';
if (developmentOrigin && !/^http:\/\/(127\.0\.0\.1|localhost)(:\d+)?$/.test(developmentOrigin)) {
throw new Error('ARTVERIS_DEV_ORIGIN must be a local loopback HTTP origin');
}
const clientOrigin = developmentOrigin ? `${developmentOrigin}/trace` : process.env.CLIENT_ORIGIN || 'http://localhost:5174';
return {
appName: process.env.APP_NAME || '艺术品溯源平台',
env: process.env.NODE_ENV || 'development',
port: parseInt(process.env.API_PORT || '3000', 10),
baseUrl: process.env.BASE_URL || 'http://localhost:3000',
baseUrl: developmentOrigin || process.env.BASE_URL || 'http://localhost:3000',
publicTracePath: process.env.PUBLIC_TRACE_PATH || '/t',
adminOrigin: process.env.ADMIN_ORIGIN || 'http://localhost:5173',
adminOrigin: developmentOrigin || process.env.ADMIN_ORIGIN || 'http://localhost:5173',
clientOrigin,
developmentClientBaseUrl: developmentOrigin ? clientOrigin : undefined,
// 短链跳转到 C 端溯源页的地址模板,{code} 会被替换为短码
traceUrlTemplate: process.env.TRACE_URL_TEMPLATE || `${clientOrigin}/#/trace/{code}`,
traceUrlTemplate: developmentOrigin ? `${clientOrigin}/#/trace/{code}` : process.env.TRACE_URL_TEMPLATE || `${clientOrigin}/#/trace/{code}`,
jwt: {
secret: process.env.JWT_SECRET || 'artveris_dev_secret',
expiresIn: process.env.JWT_EXPIRES_IN || '7d',
@@ -0,0 +1,34 @@
import { parseChainDetail } from './chain-detail';
const info = {
data: {
gasTxUsed: '3388899',
fromAddress: '0x85aa7cdeba55cb08427018d066a26719b956ceff',
toAddress: '0x8c7df15858ee7c2f51ce74899a6d097ed163443f',
timeStamp: 1786261526886,
blockHeight: 39944998,
inputDataBin: '0xsecret',
inputDataDetail: { method: 'mint(address to, string author, string productId, string feature, string initPrice)', methodId: '0xa40d1b10' },
inputInfo: [{ name: 'author', type: 'string', data: '黄志伟' }],
transactionDetail: [{ fromAddress: '0x0000000000000000000000000000000000000000', toAddress: '0xae3ecbac36b5874b0372686e5b88894c22be4296', contractAddress: '0x8c7df15858ee7c2f51ce74899a6d097ed163443f', tokenId: '3051' }],
},
};
const receipt = {
data: [{ logInfo: { address: '0x8c7df15858ee7c2f51ce74899a6d097ed163443f', name: 'Transfer(address from, address to, uint256 tokenId)', data: '0x', topics: ['0xabc'] } }],
};
describe('parseChainDetail', () => {
it('keeps gas, sender and logs and drops the raw input binary', () => {
const detail = parseChainDetail(info, receipt);
expect(detail?.gasUsed).toBe('3388899');
expect(detail?.fromAddress).toBe('0x85aa7cdeba55cb08427018d066a26719b956ceff');
expect(detail?.logs).toHaveLength(1);
expect(detail?.action?.tokenId).toBe('3051');
expect(JSON.stringify(detail)).not.toContain('secret');
});
it('stays empty when gas, sender or logs are missing', () => {
expect(parseChainDetail({ data: { gasTxUsed: '', fromAddress: info.data.fromAddress } }, receipt)).toBeNull();
expect(parseChainDetail(info, { data: [] })).toBeNull();
});
});
+109
View File
@@ -0,0 +1,109 @@
export interface ChainInputField {
name: string;
type: string;
data: string;
}
export interface ChainLogView {
address: string;
name: string;
data: string;
topics: string[];
}
export interface ChainDetail {
gasUsed: string;
fromAddress: string;
toAddress: string;
timeStamp: string | null;
blockHeight: string | null;
method: string;
methodId: string;
inputs: ChainInputField[];
logs: ChainLogView[];
action: { fromAddress: string; toAddress: string; contractAddress: string; tokenId: string } | null;
}
const ADDRESS = /^0x[0-9a-fA-F]{40}$/;
function text(value: unknown): string {
return typeof value === 'string' ? value.trim() : '';
}
export function readStoredChainDetail(raw: unknown): ChainDetail | null {
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
const detail = (raw as { chainDetail?: unknown }).chainDetail;
if (!detail || typeof detail !== 'object' || Array.isArray(detail)) return null;
const row = detail as ChainDetail;
if (!row.gasUsed || !ADDRESS.test(row.fromAddress || '') || !Array.isArray(row.logs) || !row.logs.length) return null;
return row;
}
export function parseChainDetail(info: unknown, receipt: unknown): ChainDetail | null {
const data = info && typeof info === 'object' ? (info as { data?: unknown }).data : null;
if (!data || typeof data !== 'object') return null;
const row = data as Record<string, unknown>;
const gasUsed = text(row.gasTxUsed);
const fromAddress = text(row.fromAddress);
const logs = Array.isArray(receipt && typeof receipt === 'object' ? (receipt as { data?: unknown }).data : null)
? ((receipt as { data: unknown[] }).data)
.map((item) => (item && typeof item === 'object' ? (item as { logInfo?: unknown }).logInfo : null))
.filter((item): item is Record<string, unknown> => Boolean(item && typeof item === 'object'))
.map((item) => ({
address: text(item.address),
name: text(item.name),
data: text(item.data) || '0x',
topics: Array.isArray(item.topics) ? item.topics.filter((topic): topic is string => typeof topic === 'string') : [],
}))
.filter((item) => item.address && item.name && item.topics.length)
: [];
if (!gasUsed || !ADDRESS.test(fromAddress) || !logs.length) return null;
const method = row.inputDataDetail && typeof row.inputDataDetail === 'object'
? row.inputDataDetail as { method?: unknown; methodId?: unknown }
: {};
const action = Array.isArray(row.transactionDetail) ? row.transactionDetail[0] as Record<string, unknown> | undefined : undefined;
return {
gasUsed,
fromAddress,
toAddress: text(row.toAddress),
timeStamp: row.timeStamp == null ? null : String(row.timeStamp),
blockHeight: row.blockHeight == null ? null : String(row.blockHeight),
method: text(method.method),
methodId: text(method.methodId),
inputs: Array.isArray(row.inputInfo)
? row.inputInfo.filter((item): item is Record<string, unknown> => Boolean(item && typeof item === 'object')).map((item) => ({
name: text(item.name),
type: text(item.type),
data: text(item.data),
}))
: [],
logs,
action: action ? {
fromAddress: text(action.fromAddress),
toAddress: text(action.toAddress),
contractAddress: text(action.contractAddress),
tokenId: text(action.tokenId),
} : null,
};
}
export function explorerApiBase(environment: string): string {
const host = environment === 'production' ? 'https://explorer.tianhecloud.com' : 'https://test.explorer.tianhecloud.com';
return `${host}/api/tichain-browser-new`;
}
export async function loadChainDetail(environment: string, txHash: string, blockHeight: string | null, getter: (url: string) => Promise<unknown> = defaultGet): Promise<ChainDetail | null> {
const base = explorerApiBase(environment);
const info = await getter(`${base}/transaction/info?txHash=${encodeURIComponent(txHash)}`);
const infoData = info && typeof info === 'object' ? (info as { data?: { blockHeight?: unknown } }).data : null;
const height = blockHeight || (infoData?.blockHeight == null ? '' : String(infoData.blockHeight));
if (!height) return null;
const receipt = await getter(`${base}/receipt/info?hash=${encodeURIComponent(txHash)}&height=${encodeURIComponent(height)}`);
return parseChainDetail(info, receipt);
}
async function defaultGet(url: string): Promise<unknown> {
const response = await fetch(url, { redirect: 'error', signal: AbortSignal.timeout(15_000) });
if (!response.ok) return null;
return response.json();
}
@@ -0,0 +1,26 @@
import { readMintView } from './public-mint-view';
describe('readMintView', () => {
it('uses the frozen mint fields and ignores the rest of the raw response', () => {
const view = readMintView({
product: { productId: '154109005352', author: '黄志伟', feature: 'https://art.qclh.xyz/uploads/a.png' },
confirmation: { appKey: 'secret' },
}, '154109005352', '后来改名', '0xae3ecbac36b5874b0372686e5b88894c22be4296');
expect(view).toEqual({
author: '黄志伟',
productId: '154109005352',
feature: 'https://art.qclh.xyz/uploads/a.png',
mintTo: '0xae3ecbac36b5874b0372686e5b88894c22be4296',
});
expect(JSON.stringify(view)).not.toContain('secret');
});
it('falls back to the artwork artist and short code when the snapshot is missing', () => {
expect(readMintView(null, '734648008702', '黄志伟', 'not-an-address')).toEqual({
author: '黄志伟',
productId: '734648008702',
feature: null,
mintTo: null,
});
});
});
@@ -0,0 +1,23 @@
export interface PublicMintView {
author: string | null;
productId: string;
feature: string | null;
mintTo: string | null;
}
function text(row: Record<string, unknown>, key: string): string | null {
const value = row[key];
return typeof value === 'string' && value.trim() ? value.trim() : null;
}
/** 只取出发行时保存的产品字段,不把原始响应里的其他内容交给浏览器。 */
export function readMintView(raw: unknown, shortCode: string, artist: string | null, wallet: string | null): PublicMintView {
const product = raw && typeof raw === 'object' ? (raw as { product?: unknown }).product : null;
const row = product && typeof product === 'object' ? product as Record<string, unknown> : {};
return {
author: text(row, 'author') || artist?.trim() || null,
productId: text(row, 'productId') || shortCode,
feature: text(row, 'feature'),
mintTo: wallet && /^0x[0-9a-fA-F]{40}$/.test(wallet) ? wallet : null,
};
}
@@ -1,4 +1,4 @@
import { Controller, Get, Param, Query, Req, Res } from '@nestjs/common';
import { Controller, Get, Param, Post, Query, Req, Res } from '@nestjs/common';
import { Request, Response } from 'express';
import { ApiOperation, ApiTags } from '@nestjs/swagger';
import { Throttle } from '@nestjs/throttler';
@@ -39,6 +39,14 @@ export class PublicTraceController {
private readonly config: ConfigService,
) {}
@Public()
@Post('public/trace/:shortCode/chain-detail')
@Throttle({ default: { limit: 10, ttl: 60_000 } })
@ApiOperation({ summary: '首次补存交易详情;已存档后只读本地' })
chainDetail(@Param('shortCode') shortCode: string) {
return this.service.captureChainDetail(shortCode);
}
@Public()
@Get('public/trace/:shortCode')
// 公开溯源软限流:每 IP 每分钟 60 次,抑制脚本刷量污染防伪统计与日志
@@ -96,8 +96,8 @@ function createHarness(options: {
set: jest.fn().mockResolvedValue('OK'),
};
const storage = { getUrl: jest.fn((key: string) => `/uploads/${key}`) };
const settings = { getAllRaw: jest.fn().mockResolvedValue({}) };
const service = new PublicTraceService(prisma as any, storage as any, settings as any, redis as any);
const settings = { get: jest.fn().mockResolvedValue(null) };
const service = new PublicTraceService(prisma as any, storage as any, redis as any, settings as any);
return { service, prisma };
}
@@ -18,7 +18,8 @@ import { StorageService } from '../storage/storage.service';
import { SettingsService } from '../settings/settings.service';
import { REDIS_CLIENT } from '../redis/redis.module';
import { parseUserAgent } from '../common/utils/ua.util';
import { buildTianheExplorerTxUrl } from '../blockchain/tianhe.provider';
import { readMintView } from './public-mint-view';
import { loadChainDetail, readStoredChainDetail } from './chain-detail';
type TraceCodeWithRel = Prisma.TraceCodeGetPayload<{ include: { batch: true; artwork: true } }>;
type ArtworkWithRel = Prisma.ArtworkGetPayload<{
@@ -45,8 +46,8 @@ export class PublicTraceService {
constructor(
private readonly prisma: PrismaService,
private readonly storage: StorageService,
private readonly settings: SettingsService,
@Inject(REDIS_CLIENT) private readonly redis: Redis,
private readonly settings: SettingsService,
) {}
private mapMedia(
@@ -268,11 +269,10 @@ export class PublicTraceService {
const updated = await this.prisma.traceCode.findUniqueOrThrow({ where: { id } });
const proof = await this.prisma.blockchainProof.findUnique({ where: { traceCodeId: id } });
const mintTo = await this.mintRecipient(proof);
const result = firstActivate ? QueryResult.FIRST_ACTIVATE : QueryResult.REPEAT;
await this.writeLog(id, artwork.id, shortCode, result, ctx, { ...code, ...updated });
const explorerUrl = await this.resolveExplorerUrl(proof);
return {
status: 'OK' as const,
queriedAt: now,
@@ -281,7 +281,7 @@ export class PublicTraceService {
queryCount: updated.queryCount,
firstActivatedAt: updated.firstActivatedAt,
},
...this.buildArtworkPayload(artwork, code, proof, explorerUrl),
...this.buildArtworkPayload(artwork, code, proof, mintTo),
};
}
@@ -326,10 +326,10 @@ export class PublicTraceService {
}
const proof = await this.prisma.blockchainProof.findUnique({ where: { traceCodeId: id } });
const mintTo = await this.mintRecipient(proof);
const now = new Date();
const firstQuery = state === 'inactive';
const explorerUrl = await this.resolveExplorerUrl(proof);
return {
status: 'OK' as const,
preview: true,
@@ -341,7 +341,7 @@ export class PublicTraceService {
queryCount: code.queryCount > 0 ? code.queryCount : 2,
firstActivatedAt: code.firstActivatedAt ?? now,
},
...this.buildArtworkPayload(artwork, code, proof, explorerUrl),
...this.buildArtworkPayload(artwork, code, proof, mintTo),
};
}
@@ -349,6 +349,7 @@ export class PublicTraceService {
private buildArtworkPayload(
artwork: ArtworkWithRel,
code: {
shortCode: string;
outbound?: {
outTime: Date;
remark: string | null;
@@ -362,14 +363,16 @@ export class PublicTraceService {
blockHeight: bigint | null;
chainName: string | null;
onchainAt: Date | null;
explorerUrl: string | null;
contractAddress: string | null;
tokenId: bigint | null;
rawResponse: unknown;
status: string;
failureReason: string | null;
submittedAt: Date | null;
} | null,
explorerUrl: string | null,
mintTo: string | null,
) {
const mint = proof ? readMintView(proof.rawResponse, code.shortCode, artwork.artist, mintTo) : null;
return {
artwork: {
title: artwork.title,
@@ -414,8 +417,13 @@ export class PublicTraceService {
blockHeight: proof.blockHeight,
chainName: proof.chainName,
onchainAt: proof.onchainAt,
explorerUrl,
contractAddress: proof.contractAddress,
tokenId: proof.tokenId === null || proof.tokenId === undefined ? null : proof.tokenId.toString(),
author: mint?.author ?? null,
productId: mint?.productId ?? code.shortCode,
feature: mint?.feature ?? null,
mintTo: mint?.mintTo ?? null,
chainDetail: readStoredChainDetail(proof.rawResponse),
submittedAt: proof.submittedAt,
failureReason: this.publicFailureReason(proof.status, proof.failureReason),
}
@@ -423,6 +431,43 @@ export class PublicTraceService {
};
}
private readonly chainDetailJobs = new Map<string, Promise<{ complete: boolean; detail: unknown }>>();
async captureChainDetail(shortCode: string) {
const current = this.chainDetailJobs.get(shortCode);
if (current) return current;
const job = this.captureChainDetailOnce(shortCode).finally(() => this.chainDetailJobs.delete(shortCode));
this.chainDetailJobs.set(shortCode, job);
return job;
}
private async captureChainDetailOnce(shortCode: string) {
if (!TRACE_CODE_PATTERN.test(shortCode)) return { complete: false, detail: null };
const code = await this.prisma.traceCode.findUnique({ where: { shortCode }, select: { id: true } });
if (!code) return { complete: false, detail: null };
const proof = await this.prisma.blockchainProof.findUnique({ where: { traceCodeId: code.id } });
const stored = readStoredChainDetail(proof?.rawResponse);
if (stored) return { complete: true, detail: stored };
if (!proof?.txHash || proof.chainName !== '天河链') return { complete: false, detail: null };
const environment = await this.settings.get('tianheEnv');
const detail = await loadChainDetail(environment || 'test', proof.txHash, proof.blockHeight == null ? null : proof.blockHeight.toString());
if (!detail) return { complete: false, detail: null };
const current = proof.rawResponse && typeof proof.rawResponse === 'object' && !Array.isArray(proof.rawResponse)
? proof.rawResponse as Record<string, unknown>
: {};
await this.prisma.blockchainProof.update({
where: { id: proof.id },
data: { rawResponse: { ...current, chainDetail: detail } as unknown as Prisma.InputJsonValue },
});
return { complete: true, detail };
}
private async mintRecipient(proof: { chainName: string | null } | null): Promise<string | null> {
if (proof?.chainName !== '天河链') return null;
const value = await this.settings.get('tianheWalletAddress');
return typeof value === 'string' && /^0x[0-9a-fA-F]{40}$/.test(value) ? value : null;
}
private publicFailureReason(status: string, reason: string | null): string | null {
if (status === ProofStatus.UNKNOWN) return '链上结果暂时无法确认,请稍后重试或联系平台管理员';
if (status === ProofStatus.FAILED) return reason ? '上链处理失败,请联系平台管理员' : '上链处理失败';
@@ -471,18 +516,6 @@ export class PublicTraceService {
};
}
private async resolveExplorerUrl(
proof: { txHash: string | null; chainName: string | null; explorerUrl: string | null } | null,
): Promise<string | null> {
const tianheProof =
proof?.chainName === '天河链' ||
/tianhe|tichain/i.test(proof?.chainName || '') ||
/tianhecloud\.com/i.test(proof?.explorerUrl || '');
if (!proof?.txHash || !tianheProof) return proof?.explorerUrl ?? null;
const settings = await this.settings.getAllRaw();
return buildTianheExplorerTxUrl(settings.tianheBaseUrl || '', proof.txHash, settings.tianheEnv);
}
private buildFields(
fields: Array<{ fieldKey: string; label: string; type: string }>,
dynamic: unknown,
@@ -1,6 +1,24 @@
import { SettingsService } from './settings.service';
describe('SettingsService.update', () => {
it('rejects invalid certificate templates before any settings are persisted', async () => {
const prisma = { $transaction: jest.fn() };
const service = new SettingsService(prisma as any, {} as any);
await expect(service.updateAtomic({ certificateTextTemplate: '{{错误字段}}' })).rejects.toThrow();
expect(prisma.$transaction).not.toHaveBeenCalled();
});
it('uses the explicit development URL for links and displayed settings after importing production data', async () => {
const prisma = { systemSetting: {
findMany: jest.fn().mockResolvedValue([{ key: 'clientBaseUrl', value: 'https://art.qclh.xyz/trace' }]),
findUnique: jest.fn().mockResolvedValue({ value: 'https://art.qclh.xyz/trace' }),
} };
const config = { get: jest.fn((key: string) => key === 'developmentClientBaseUrl' ? 'http://127.0.0.1:18080/trace' : undefined) };
const service = new SettingsService(prisma as any, config as any);
expect(await service.getClientBaseUrl()).toBe('http://127.0.0.1:18080/trace');
expect((await service.getAll()).clientBaseUrl).toBe('http://127.0.0.1:18080/trace');
config.get.mockImplementation(() => undefined);
expect(await service.getClientBaseUrl()).toBe('https://art.qclh.xyz/trace');
});
it('writes a multi-key settings change inside one database transaction', async () => {
const tx = {
systemSetting: { upsert: jest.fn().mockResolvedValue(undefined) },
+16 -1
View File
@@ -1,4 +1,5 @@
import { Injectable, Logger } from '@nestjs/common';
import { BadRequestException, Injectable, Logger } from '@nestjs/common';
import { DEFAULT_CERTIFICATE_TEXT_TEMPLATE, validateCertificateTextTemplate } from '@artveris/shared';
import { ConfigService } from '@nestjs/config';
import { createCipheriv, createDecipheriv, createHash, randomBytes } from 'crypto';
import { PrismaService } from '../prisma/prisma.service';
@@ -29,6 +30,8 @@ const EDITABLE_KEYS = [
'storageMigrationFingerprint',
'storageMigrationCopied',
'blockchainDriver',
'certificateTextTemplate',
'certificateAuthorMode',
'tianheEnv',
'tianheBaseUrl',
'tianheAppId',
@@ -89,6 +92,8 @@ export class SettingsService {
ossAccessKeySecret: this.config.get<string>('storage.oss.accessKeySecret') || '',
settingsEncryptionKey: this.config.get<string>('settingsEncryptionKey') || '',
blockchainDriver: this.config.get<string>('blockchain.driver') || 'mock',
certificateTextTemplate: DEFAULT_CERTIFICATE_TEXT_TEMPLATE,
certificateAuthorMode: 'WALLET',
tianheEnv: 'test',
tianheBaseUrl: this.config.get<string>('blockchain.tianhe.baseUrl') || 'https://test.api.tichain.tianhecloud.com',
tianheAppId: this.config.get<string>('blockchain.tianhe.appId') || '',
@@ -101,6 +106,8 @@ export class SettingsService {
const value = await this.decryptSecret(r.value);
map[r.key] = r.key === 'appName' && value === '艺术品可信溯源与认证平台' ? '艺术品溯源平台' : value;
}
const localClient = this.config.get<string>('developmentClientBaseUrl');
if (localClient) map.clientBaseUrl = localClient;
if (map.appIconUrl === '/app-icon.svg') map.appIconUrl = '';
if (maskSecrets) {
for (const key of MASKED_KEYS) {
@@ -118,6 +125,8 @@ export class SettingsService {
}
async getClientBaseUrl(): Promise<string> {
const localClient = this.config.get<string>('developmentClientBaseUrl');
if (localClient) return localClient.replace(/\/$/, '');
const fromDb = await this.get('clientBaseUrl');
return (fromDb || this.config.get<string>('clientOrigin') || 'http://localhost:5174').replace(/\/$/, '');
}
@@ -142,6 +151,12 @@ export class SettingsService {
}
async updateAtomic(values: Record<string, string>): Promise<void> {
if (values.certificateAuthorMode !== undefined && !['WALLET', 'ARTWORK_ARTIST'].includes(values.certificateAuthorMode)) {
throw new BadRequestException('证书作者显示方式无效');
}
if (values.certificateTextTemplate !== undefined && validateCertificateTextTemplate(values.certificateTextTemplate)) {
throw new BadRequestException('证书文本模板不能为空,最多500字符,支持:作品名称、版本、追溯码、档案编号、作者,字段使用双花括号');
}
const updates: Array<{ key: string; value: string }> = [];
for (const [key, value] of Object.entries(values)) {
if (!EDITABLE_KEYS.includes(key)) continue;
+2
View File
@@ -14,7 +14,9 @@
"@artveris/shared": "workspace:*",
"axios": "^1.7.9",
"dayjs": "^1.11.13",
"html2canvas": "^1.4.1",
"photoswipe": "^5.4.4",
"qrcode": "^1.5.4",
"vue": "^3.5.13",
"vue-i18n": "^9.14.2",
"vue-router": "^4.5.0"
+32 -2
View File
@@ -44,13 +44,43 @@ export function fetchAppInfo(): Promise<any> {
return instance.get('/settings/public') as unknown as Promise<any>;
}
export interface TraceCertificateRecord {
text: string;
digest: string;
txHash: string;
author: string;
createdAt: string | null;
environment?: 'test' | 'production';
}
export interface ChainDetailLog {
address: string;
name: string;
data: string;
topics: string[];
}
export interface ChainDetail {
gasUsed: string;
fromAddress: string;
toAddress: string;
timeStamp: string | null;
blockHeight: string | null;
method: string;
methodId: string;
inputs: Array<{ name: string; type: string; data: string }>;
logs: ChainDetailLog[];
action: { fromAddress: string; toAddress: string; contractAddress: string; tokenId: string } | null;
}
export function fetchChainDetail(shortCode: string): Promise<{ complete: boolean; detail: ChainDetail | null }> {
return instance.post(`/public/trace/${encodeURIComponent(shortCode)}/chain-detail`, {}, { timeout: 30_000 }) as unknown as Promise<{ complete: boolean; detail: ChainDetail | null }>;
}
export interface TraceCertificateResult {
status: 'NONE' | 'PENDING' | 'SUBMITTING' | 'CHECKING' | 'WAITING' | 'READY' | 'UNKNOWN' | 'FAILED';
url: string | null;
generatedAt: string | null;
certificate: TraceCertificateRecord | null;
message?: string | null;
}
export function requestTraceCertificate(shortCode: string): Promise<TraceCertificateResult> {
return instance.post(`/public/trace/${encodeURIComponent(shortCode)}/certificate`, {}) as unknown as Promise<TraceCertificateResult>;
return instance.post(`/public/trace/${encodeURIComponent(shortCode)}/certificate`, {}, { timeout: 90_000 }) as unknown as Promise<TraceCertificateResult>;
}
export function fetchTraceCertificate(shortCode: string): Promise<TraceCertificateResult> {
return instance.get(`/public/trace/${encodeURIComponent(shortCode)}/certificate`) as unknown as Promise<TraceCertificateResult>;
Binary file not shown.

After

Width:  |  Height:  |  Size: 43 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 548 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

@@ -58,33 +58,23 @@
<span class="chain-v">{{ formatTime(blockchain.onchainAt) }}</span>
</div>
<div class="chain-actions">
<a
v-if="explorerUrl"
class="chain-link"
:href="explorerUrl"
target="_blank"
rel="noopener noreferrer"
>
{{ t('chain.explorer') }} →
</a>
<button v-if="canViewCertificate" class="chain-link certificate-link" :disabled="opening || preview" @click="viewCertificate">
{{ t(opening ? 'chain.certificateOpening' : 'chain.certificateView') }} →
<button v-if="blockchain.txHash" class="chain-link" type="button" @click="openProof">{{ t('chain.explorer') }}</button>
<button v-if="canViewCertificate" class="chain-link certificate-link" type="button" :disabled="preview" @click="openCertificate">
{{ t('chain.certificateView') }}
</button>
</div>
<p v-if="preview && canViewCertificate" class="muted chain-status-note">{{ t('chain.certificatePreview') }}</p>
<p v-if="certificateError" role="alert" class="chain-status-note">{{ certificateError }}</p>
</template>
<div v-else class="chain-empty muted">{{ t('chain.notOnchain') }}</div>
</section>
</template>
<script setup lang="ts">
import { computed, ref } from 'vue';
import { useRouter } from 'vue-router';
import { fetchTraceCertificate, requestTraceCertificate } from '@/api';
import { computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import type { ChainDetail } from '@/api';
import { useI18n } from 'vue-i18n';
import dayjs from 'dayjs';
import { safeTraceUrl } from './media';
type ProofStatus = 'PENDING' | 'SUBMITTING' | 'CONFIRMING' | 'ONCHAIN' | 'FAILED' | 'UNKNOWN';
const STATUSES = new Set<ProofStatus>([
@@ -107,54 +97,50 @@ const props = defineProps<{
contractAddress?: string | null;
blockHeight?: string | number | null;
onchainAt?: string | null;
explorerUrl?: string | null;
blockHash?: string | null;
tokenId?: string | number | null;
author?: string | null;
productId?: string | null;
feature?: string | null;
mintTo?: string | null;
chainDetail?: ChainDetail | null;
failureReason?: string | null;
chainName?: string | null;
} | null;
}>();
defineEmits<{ (event: 'copy', value: string): void }>();
const { t } = useI18n();
const route = useRoute();
const router = useRouter();
const opening = ref(false);
const certificateError = ref('');
const canViewCertificate = computed(() => status.value === 'ONCHAIN' && props.blockchain?.chainName === '天河链');
const canViewCertificate = computed(() => props.blockchain?.status === 'ONCHAIN' && Boolean(props.blockchain.txHash) && props.blockchain.chainName === '天河链');
async function viewCertificate() {
if (opening.value || props.preview) return;
certificateError.value = '';
const href = router.resolve({ path: `/certificate/${props.shortCode}` }).href;
// Open while the click gesture is active. The waiting page never starts a deposit itself.
const popup = window.open(href, '_blank');
if (popup) popup.opener = null;
opening.value = true;
try {
const cached = await fetchTraceCertificate(props.shortCode);
const result = cached.status === 'NONE' || cached.status === 'UNKNOWN'
? await requestTraceCertificate(props.shortCode) : cached;
if (!popup) {
await router.push(`/certificate/${props.shortCode}`);
} else if (result.status === 'READY' && result.url) {
popup.location.replace(result.url);
}
} catch {
if (popup && !popup.closed) popup.close();
certificateError.value = t('chain.certificateRequestFailed');
} finally { opening.value = false; }
function openProof() {
const key = `artveris.trace.proof.${props.preview ? 'preview.' : ''}${props.shortCode}`;
sessionStorage.setItem(key, JSON.stringify(props.blockchain || null));
router.push({
name: props.preview ? 'trace-preview-proof' : 'trace-proof',
params: { code: props.shortCode },
query: props.preview ? { token: route.query.token, state: route.query.state } : {},
});
}
function openCertificate() {
if (props.preview || !canViewCertificate.value) return;
router.push({ name: 'trace-certificate', params: { code: props.shortCode } });
}
const status = computed<ProofStatus>(() => {
const value = props.blockchain?.status as ProofStatus | undefined;
return value && STATUSES.has(value) ? value : 'ONCHAIN';
});
const explorerUrl = computed(() => safeTraceUrl(props.blockchain?.explorerUrl || undefined));
function ellipsis(value?: string | null) {
if (!value) return '-';
return value.length > 16 ? `${value.slice(0, 8)}…${value.slice(-6)}` : value;
}
function formatTime(value: string) {
return dayjs(value).format('YYYY-MM-DD HH:mm');
function formatTime(value?: string | null) {
if (!value) return '-';
const parsed = dayjs(value);
return parsed.isValid() ? parsed.format('YYYY-MM-DD HH:mm') : '-';
}
</script>
@@ -244,15 +230,20 @@ function formatTime(value: string) {
.chain-link {
display: inline-block;
margin-top: 10px;
padding: 0;
border: 0;
background: none;
color: var(--brand-2);
font: inherit;
font-size: 14px;
text-decoration: none;
cursor: pointer;
}
.chain-empty {
font-size: 13px;
padding: 8px 0;
}
.chain-actions { display: flex; align-items: center; gap: 24px; flex-wrap: wrap; }
.certificate-link { padding: 0; border: 0; background: none; cursor: pointer; font-family: inherit; }
.certificate-link { margin-left: auto; }
.certificate-link:disabled { opacity: .55; cursor: default; }
</style>
@@ -0,0 +1,103 @@
<template>
<div ref="sheet" class="certificate-prove">
<div class="cert-logo">
<img :src="logoUrl" alt="" />
</div>
<h1 class="cert-title">区块链存证证书</h1>
<p class="cert-notice"> 本证书由天河链签发,证明该文件由作者在存证时间操作上链,且链上内容未经篡改 </p>
<div class="row-mod">
<p class="row-title">天河链-区块链ID:</p>
<p class="row-value"> {{ record.txHash || '未知' }} </p>
</div>
<div class="row-mod">
<p class="row-title">电子证据SHA256值:</p>
<p class="row-value"> {{ record.digest || '未知' }} </p>
</div>
<div class="cert-divider el-divider el-divider--horizontal"></div>
<div class="prove-area prove-area-2">
<div class="form-mod">
<div class="form-item">
<div class="form-item-label">作者:</div>
<div class="form-item-value"> {{ record.author }} </div>
</div>
<div class="form-item">
<div class="form-item-label">存证时间:</div>
<div class="form-item-value"> {{ created }} </div>
</div>
<div v-if="record.text" class="form-item">
<div class="form-item-label">文本内容:</div>
<div class="form-item-value"> {{ record.text }} </div>
</div>
</div>
<div class="check-img">
<img :src="stampUrl" alt="" height="100%" />
</div>
</div>
<div class="prove-area prove-area-3">
<div class="prove-notice">
说明:<br /><br />
1、本文件通过天河链网络进行存证,链上数据不可删除、不可篡改。<br /><br />
2、本文件根据SHA256加密算法加密。
</div>
<div class="wx-link">
<div id="qrcode">
<img v-if="qrUrl" :src="qrUrl" alt="" width="88" height="88" />
</div>
<img class="qrcode-logo" :src="qrLogoUrl" alt="" width="16" />
</div>
</div>
<div class="prove-wrapper"></div>
</div>
</template>
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue';
import dayjs from 'dayjs';
import QRCode from 'qrcode';
import type { TraceCertificateRecord } from '@/api';
import logoUrl from '@/assets/certificate/logo.png';
import stampUrl from '@/assets/certificate/check.png';
import qrLogoUrl from '@/assets/certificate/qr-logo.png';
import './certificate-prove.css';
const props = defineProps<{ record: TraceCertificateRecord }>();
const sheet = ref<HTMLElement>();
const qrUrl = ref('');
const created = computed(() => {
if (!props.record.createdAt) return '';
const parsed = dayjs(props.record.createdAt);
return parsed.isValid() ? parsed.format('YYYY-MM-DD HH:mm:ss') : props.record.createdAt;
});
onMounted(async () => {
const host = props.record.environment === 'test' ? 'https://test.explorer.tianhecloud.com' : 'https://explorer.tianhecloud.com';
qrUrl.value = await QRCode.toDataURL(`${host}/#/tiChain/transDetail?hash=${props.record.txHash}`, {
width: 88,
margin: 0,
errorCorrectionLevel: 'H',
color: { dark: '#000000', light: '#ffffff' },
});
});
async function download() {
const target = sheet.value;
if (!target) return;
const host = document.createElement('div');
host.style.cssText = 'position:fixed;left:-10000px;top:0;width:508px;height:720px;';
const clone = target.cloneNode(true) as HTMLElement;
host.appendChild(clone);
document.body.appendChild(host);
try {
const { default: html2canvas } = await import('html2canvas');
const canvas = await html2canvas(clone, { scale: 3, backgroundColor: '#e0e0e0', useCORS: true });
const link = document.createElement('a');
link.href = canvas.toDataURL('image/png');
link.download = `${Date.now()}.png`;
link.click();
} finally {
host.remove();
}
}
defineExpose({ download });
</script>
@@ -0,0 +1,249 @@
<template>
<div class="tx-page">
<div class="tx-top">
<h3 v-if="showHeading">{{ t('chain.txTitle') }}</h3>
<div class="tx-hashbox">{{ txHash || '-' }}</div>
</div>
<section class="tx-card">
<div class="tx-tabs" role="tablist">
<button type="button" role="tab" :class="{ active: tab === 'info' }" :aria-selected="tab === 'info'" @click="tab = 'info'">{{ t('chain.txInfo') }}</button>
<button type="button" role="tab" :class="{ active: tab === 'logs' }" :aria-selected="tab === 'logs'" @click="tab = 'logs'">{{ t('chain.txLogs') }}</button>
</div>
<div v-if="tab === 'info'" class="tx-panel" role="tabpanel">
<div class="tx-row">
<span>{{ t('chain.txHash') }}</span>
<div class="tx-value">
<b class="mono">{{ txHash || '-' }}</b>
<button v-if="txHash" type="button" class="tx-copy" :aria-label="t('chain.copy')" @click="$emit('copy', txHash)">
<CopyIcon />
</button>
</div>
</div>
<div class="tx-row">
<span>{{ t('chain.txStatus') }}</span>
<div class="tx-value">
<em v-if="succeeded" class="tx-ok">{{ t('chain.txSuccess') }}</em>
<em v-else class="tx-pending">{{ statusText }}</em>
</div>
</div>
<div v-if="shownBlock != null && shownBlock !== ''" class="tx-row">
<span>{{ t('chain.blockHeight') }}</span>
<div class="tx-value">
<b>{{ shownBlock }}</b>
<button type="button" class="tx-copy" :aria-label="t('chain.copy')" @click="$emit('copy', String(shownBlock))">
<CopyIcon />
</button>
</div>
</div>
<div class="tx-row">
<span>{{ t('chain.txGas') }}</span>
<div class="tx-value"><b>{{ detail?.gasUsed || '' }}</b></div>
</div>
<div class="tx-row">
<span>{{ t('chain.txSender') }}</span>
<div class="tx-value">
<span class="tx-addr">{{ detail?.fromAddress || '' }}</span>
<button v-if="detail?.fromAddress" type="button" class="tx-copy" :aria-label="t('chain.copy')" @click="$emit('copy', detail.fromAddress)">
<CopyIcon />
</button>
</div>
</div>
<div class="tx-row">
<span>{{ t('chain.txAction') }}</span>
<div class="tx-value tx-action">
{{ t('chain.txIssue') }} <b>{{ actionToken || '' }}</b>
<template v-if="actionFrom">
{{ t('chain.txFromNull') }}
<span class="tx-addr">{{ actionFrom }}</span>
</template>
<template v-if="actionTo">
{{ t('chain.txToward') }}
<span class="tx-addr">{{ actionTo }}</span>
</template>
</div>
</div>
<div v-if="contractAddress" class="tx-row">
<span>{{ t('chain.contract') }}</span>
<div class="tx-value">
<span class="tx-addr">{{ contractAddress }}</span>
<button type="button" class="tx-copy" :aria-label="t('chain.copy')" @click="$emit('copy', contractAddress)">
<CopyIcon />
</button>
</div>
</div>
<div v-if="receiver" class="tx-row">
<span>{{ t('chain.txReceiver') }}</span>
<div class="tx-value">
<span class="tx-addr">{{ receiver }}</span>
<button type="button" class="tx-copy" :aria-label="t('chain.copy')" @click="$emit('copy', receiver)">
<CopyIcon />
</button>
</div>
</div>
<div class="tx-row">
<span>{{ t('chain.txTime') }}</span>
<div class="tx-value"><b>{{ timeText }}</b></div>
</div>
<div class="tx-row tx-input-row">
<span>{{ t('chain.txInput') }}</span>
<div class="tx-value">
<div class="tx-method"><i>Method</i><b>{{ detail?.method || '' }}</b></div>
<div class="tx-method"><i>MethodId</i><b class="mono">{{ detail?.methodId || '' }}</b></div>
<table>
<thead>
<tr>
<th>Input</th>
<th>{{ t('chain.txName') }}</th>
<th>{{ t('chain.txType') }}</th>
<th>{{ t('chain.txData') }}</th>
</tr>
</thead>
<tbody>
<tr v-for="row in inputs" :key="row.name">
<td></td>
<td>{{ row.name }}</td>
<td>{{ row.type }}</td>
<td>
<span class="tx-cell">{{ row.value }}</span>
<button v-if="row.copy" type="button" class="tx-copy" :aria-label="t('chain.copy')" @click="$emit('copy', row.copy)">
<CopyIcon />
</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<div v-else class="tx-panel" role="tabpanel">
<p v-if="!detail?.logs?.length" class="tx-empty">{{ t('chain.txLogsEmpty') }}</p>
<template v-else>
<article v-for="(log, logIndex) in detail.logs" :key="logIndex" class="tx-log">
<div class="tx-row">
<span>Address</span>
<div class="tx-value"><span class="tx-addr">{{ log.address }}</span></div>
</div>
<div class="tx-row">
<span>Name</span>
<div class="tx-value"><b>{{ log.name }}</b></div>
</div>
<div class="tx-row">
<span>Topics</span>
<div class="tx-value">
<div v-for="(topic, index) in log.topics" :key="index" class="tx-topic">
<i>[{{ index }}]</i>
<span class="mono">{{ topic }}</span>
</div>
</div>
</div>
<div class="tx-row">
<span>Data</span>
<div class="tx-value"><b class="mono">{{ log.data || '0x' }}</b></div>
</div>
</article>
</template>
</div>
<button v-if="showClose" type="button" class="tx-back" @click="$emit('close')">{{ t('chain.txBack') }}</button>
</section>
</div>
</template>
<script setup lang="ts">
import { computed, defineComponent, h, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import dayjs from 'dayjs';
import type { ChainDetail } from '@/api';
const CopyIcon = defineComponent({
name: 'CopyIcon',
setup() {
return () => h('svg', { viewBox: '0 0 24 24', width: 14, height: 14, 'aria-hidden': 'true' }, [
h('rect', { x: 8, y: 8, width: 11, height: 11, rx: 2, fill: 'none', stroke: 'currentColor', 'stroke-width': 1.7 }),
h('path', { d: 'M5 15V5a2 2 0 0 1 2-2h8', fill: 'none', stroke: 'currentColor', 'stroke-width': 1.7 }),
]);
},
});
const props = withDefaults(defineProps<{
txHash?: string | null;
succeeded: boolean;
statusText: string;
blockHeight?: string | number | null;
contractAddress?: string | null;
onchainAt?: string | null;
tokenId?: string | number | null;
author?: string | null;
productId?: string | null;
feature?: string | null;
mintTo?: string | null;
detail?: ChainDetail | null;
showHeading?: boolean;
showClose?: boolean;
}>(), { showHeading: true, showClose: true });
defineEmits<{ (event: 'copy', value: string): void; (event: 'close'): void }>();
const { t } = useI18n();
const tab = ref<'info' | 'logs'>('info');
const shownBlock = computed(() => props.detail?.blockHeight || props.blockHeight);
const receiver = computed(() => props.detail?.toAddress || props.contractAddress || '');
const actionToken = computed(() => props.detail?.action?.tokenId || (props.tokenId == null ? '' : String(props.tokenId)));
const actionFrom = computed(() => props.detail?.action?.fromAddress || '');
const actionTo = computed(() => props.detail?.action?.toAddress || props.mintTo || '');
const timeText = computed(() => {
const value = props.detail?.timeStamp || props.onchainAt;
if (!value) return '';
const numeric = /^\d+$/.test(String(value)) ? Number(value) : value;
const parsed = dayjs(numeric);
return parsed.isValid() ? parsed.format('YYYY-MM-DD HH:mm:ss') : '';
});
const inputs = computed(() => props.detail?.inputs?.length
? props.detail.inputs.map((row) => ({ ...row, value: row.data, copy: row.data }))
: [
{ name: 'to', type: 'address', value: props.mintTo || '', copy: props.mintTo || '' },
{ name: 'author', type: 'string', value: props.author || '', copy: props.author || '' },
{ name: 'productId', type: 'string', value: props.productId || '', copy: props.productId || '' },
{ name: 'feature', type: 'string', value: props.feature || '', copy: props.feature || '' },
{ name: 'initPrice', type: 'string', value: '', copy: '' },
]);
</script>
<style scoped>
.tx-page { background: #f4f6fa; color: #1f2a37; border-radius: 12px; padding: 18px 18px 22px; }
.tx-top { display: flex; justify-content: space-between; gap: 16px; align-items: center; margin-bottom: 14px; }
.tx-top h3 { margin: 0; font-size: 18px; font-weight: 600; }
.tx-hashbox { max-width: 420px; flex: 1; border: 1px solid #e3e8f0; background: #fff; border-radius: 999px; padding: 7px 14px; color: #667085; font-size: 12px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.tx-card { background: #fff; border: 1px solid #e6ebf2; border-radius: 10px; padding: 8px 22px 22px; }
.tx-tabs { display: flex; gap: 22px; border-bottom: 1px solid #edf1f6; }
.tx-tabs button { border: 0; background: transparent; padding: 12px 0; color: #667085; font: inherit; cursor: pointer; }
.tx-tabs button.active { color: #3b6cff; box-shadow: inset 0 -2px 0 #3b6cff; }
.tx-row { display: grid; grid-template-columns: 108px minmax(0, 1fr); gap: 12px; padding: 13px 0; border-bottom: 1px solid #f2f4f8; font-size: 14px; }
.tx-row > span { color: #8b95a7; }
.tx-value { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; min-width: 0; }
.tx-action { line-height: 1.7; }
.tx-addr { color: #3b6cff; word-break: break-all; }
.tx-ok, .tx-pending { font-style: normal; border-radius: 6px; padding: 2px 8px; font-size: 13px; }
.tx-ok { color: #178a52; background: #e8f8ef; }
.tx-pending { color: #9a4a00; background: #fff4e8; }
.tx-copy { width: 22px; height: 22px; border: 0; background: transparent; color: #98a2b3; display: inline-flex; align-items: center; justify-content: center; cursor: pointer; padding: 0; }
.tx-method { display: grid; grid-template-columns: 88px minmax(0, 1fr); gap: 8px; width: 100%; padding: 4px 0; }
.tx-method i { color: #667085; font-style: normal; }
.tx-input-row .tx-value { display: block; overflow-x: auto; }
table { width: 100%; min-width: 520px; border-collapse: collapse; margin-top: 8px; font-size: 13px; }
th, td { border-bottom: 1px solid #f2f4f8; text-align: left; padding: 8px 6px; vertical-align: top; }
th { color: #667085; font-weight: 500; }
.tx-cell { word-break: break-all; white-space: pre-wrap; }
.tx-topic { display: flex; gap: 8px; align-items: flex-start; width: 100%; padding: 3px 0; }
.tx-topic i, .tx-topic em { color: #98a2b3; font-style: normal; flex: none; }
.mono { font-family: Consolas, 'SFMono-Regular', monospace; word-break: break-all; }
.tx-back { margin-top: 18px; border: 0; background: #3b6cff; color: #fff; border-radius: 6px; padding: 8px 18px; font: inherit; cursor: pointer; }
.tx-empty { margin: 18px 0; color: #98a2b3; font-size: 14px; }
@media (max-width: 720px) {
.tx-page { padding: 12px; }
.tx-top, .tx-row { display: block; }
.tx-hashbox { max-width: none; margin-top: 10px; }
.tx-row > span { display: block; margin-bottom: 6px; }
.tx-card { padding: 8px 12px 16px; }
}
</style>
@@ -0,0 +1,39 @@
.certificate-prove h1,
.certificate-prove p { margin: 0; }
.certificate-prove .el-divider { background-color: #dcdfe6; position: relative; }
.certificate-prove .el-divider--horizontal { display: block; height: 1px; width: 100%; margin: 24px 0; }
.certificate-prove{position:relative;height:720px;min-width:508px;background-color:#e0e0e0;text-align:center;padding:60px;background-image:url('../../assets/certificate/prove-bg.png');background-repeat:no-repeat;background-size:auto 100%}
.certificate-prove .prove-wrapper{position:absolute;left:0;right:0;bottom:0;top:0;background:transparent;z-index:1}
.certificate-prove .cert-logo{height:26px;text-align:center;margin-bottom:17px}
.certificate-prove .cert-logo img{height:26px}
.certificate-prove .cert-title{font-family:PingFangSC-Semibold;font-size:24px;color:#333;letter-spacing:0;margin-bottom:15.6px}
.certificate-prove .cert-notice{font-family:PingFangSC-Regular;font-size:12px;color:#333;letter-spacing:0;word-break:keep-all;width:calc(100% + 60px);transform:translateX(-30px) scale(.833);margin-bottom:40.4px}
.certificate-prove .row-mod{font-family:PingFang-SC-Bold;letter-spacing:0;line-height:17px;word-break:break-all;text-align:left;margin-bottom:17px}
.certificate-prove .row-mod .row-title{font-size:12px;color:#333}
.certificate-prove .row-mod .row-value{width:120%;font-size:12px;transform:translateX(-8.33%) scale(.833);color:#151515}
.certificate-prove .cert-divider{margin:20px 0;background:rgba(155,176,207,.4)}
.certificate-prove .prove-area{display:flex;width:100%;justify-content:space-between}
.certificate-prove .prove-area-2{position:relative;margin-top:94px}
.certificate-prove .prove-area-2 .form-mod{flex:1}
.certificate-prove .prove-area-2 .check-img{position:absolute;right:0;align-self:center;height:100px;width:100px}
.certificate-prove .prove-area-3{margin-top:52px}
.certificate-prove .prove-area-3 .prove-notice{flex:1;text-align:left;font-family:PingFangSC-Regular;font-size:12px;color:#666;letter-spacing:0;width:120%;transform:translateX(-8.33%) scale(.833)}
.certificate-prove .prove-area-3 .wx-link{width:100px;height:100px;display:flex;justify-content:center;align-items:center;position:relative;border:4px solid #999}
.certificate-prove .prove-area-3 .wx-link .qrcode-logo{background:#fff;padding:4px;border-radius:1px;position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);width:16px}
.certificate-prove #qrcode{width:88px;height:88px;line-height:0}
.certificate-prove #qrcode img{display:block;width:88px;height:88px}
.certificate-prove .form-mod{display:flex;flex-direction:column;justify-content:flex-start;align-items:flex-start}
.certificate-prove .form-mod .form-item{display:flex;width:100%;margin-bottom:12px}
.certificate-prove .form-mod .form-item .form-item-label,.certificate-prove .form-mod .form-item .form-item-value{display:inline-block;font-family:PingFangSC-Regular;font-size:12px;letter-spacing:0;transform:translateX(-8.33%) scale(.833)}
.certificate-prove .form-mod .form-item .form-item-label{width:60px;text-align:right;color:#666}
.certificate-prove .form-mod .form-item .form-item-value{box-sizing:border-box;padding-left:4px;width:calc(100% - 60px);text-align:left;word-wrap:break-word;color:#000}
.certificate-prove .form-mod .form-item:last-child{margin-bottom:0}
.certificate-prove {
width: 508px;
box-sizing: border-box;
font-family: Avenir, Helvetica, Arial, sans-serif;
font-size: 16px;
color: #2c3e50;
-webkit-font-smoothing: antialiased;
}
+8 -1
View File
@@ -27,5 +27,12 @@ export function openTraceViewer(items: PublicMediaItem[], index: number): void {
export function safeTraceUrl(value?: string): string {
const url = traceMediaUrl(value);
return /^(https?:\/\/|\/)/i.test(url) ? url : '';
if (!/^(https?:\/\/|\/)/i.test(url)) return '';
if (url.startsWith('/')) return url;
try {
if (/(^|\.)tianhecloud\.com$/i.test(new URL(url).hostname)) return '';
} catch {
return '';
}
return url;
}
+36 -9
View File
@@ -59,24 +59,51 @@
"contract": "Contract",
"blockHeight": "Block Height",
"onchainAt": "On-chain Time",
"blockHash": "Block Hash",
"proofTitle": "Transaction",
"txTitle": "Transaction",
"txInfo": "Details",
"txLogs": "Logs",
"txHash": "Tx Hash",
"txStatus": "Status",
"txSuccess": "Success",
"txAction": "Action",
"txIssue": "Mint NFR ID",
"txFromNull": "from Null Address:",
"txToward": "to",
"txReceiver": "Receiver",
"txTime": "Created",
"txInput": "Input",
"txName": "Name",
"txType": "Type",
"txData": "Data",
"txBack": "Back",
"txGas": "Gas used",
"txSender": "Sender",
"txLogsEmpty": "",
"explorer": "View Proof",
"copy": "Copy",
"copied": "Copied",
"notOnchain": "This artwork has not been recorded on-chain yet.",
"certificateView": "View certificate",
"certificateOpening": "Opening…",
"certificatePreview": "Certificates cannot be generated in preview mode.",
"certificateRequestFailed": "Unable to request a certificate. Please try later or contact the platform.",
"certificateGenerating": "Your certificate is being prepared. The TiChain certificate page will open when it is ready.",
"certificateShared": "One certificate is generated for this physical item and reused on future visits.",
"certificateOpen": "Open certificate",
"certificateCheckAgain": "Check again",
"certificateBack": "Back",
"certificateReady": "Your certificate is ready.",
"certificateFailed": "The attestation request was rejected. Please contact the platform.",
"certificateUnknown": "The result is not yet confirmed. Check again later; the attestation will not be submitted again.",
"certificateNotRequested": "No certificate has been requested. Select View certificate on the item trace page.",
"certificateUnavailable": "Unable to check the certificate. Please try again later."
"certificateUnavailable": "Unable to check the certificate. Please try again later.",
"certificateRetrieving": "Retrieving attestation details",
"certificateAcquiring": "Preparing your certificate",
"certificatePreparing": "Assembling your certificate",
"certificateDelayed": "This certificate is not ready yet, so there is no image. Certificates that are already generated open immediately. You can check again later.",
"certificateContent": "Attestation text",
"certificateDigest": "Digest",
"certificateAuthor": "Author",
"certificateTime": "Created",
"certificateDownload": "Download certificate",
"certificateChainId": "TiChain block ID",
"certificateChainIdTip": "This is the block transaction ID generated when the evidence was recorded. It can be used to look up the file hash on TiChain.",
"certificateDigestTitle": "SHA256 digest",
"certificateDigestTip": "This is the SHA256 hash of the original evidence. It matches that file only, and has been written to TiChain so the file cannot be altered."
},
"field": {
"viewFile": "View file"
+37 -10
View File
@@ -59,24 +59,51 @@
"contract": "合约地址",
"blockHeight": "区块高度",
"onchainAt": "上链时间",
"blockHash": "区块哈希",
"proofTitle": "交易详情",
"txTitle": "交易详情",
"txInfo": "交易信息",
"txLogs": "日志",
"txHash": "交易哈希",
"txStatus": "状态",
"txSuccess": "成功",
"txAction": "交易动作",
"txIssue": "发行 NFR ID",
"txFromNull": "从 Null Address:",
"txToward": "到",
"txReceiver": "接收方",
"txTime": "交易生成时间",
"txInput": "输入信息",
"txName": "名称",
"txType": "类型",
"txData": "数据",
"txBack": "返回",
"txGas": "Gas花费",
"txSender": "发送方",
"txLogsEmpty": "",
"explorer": "查看存证",
"copy": "复制",
"copied": "已复制",
"notOnchain": "该作品暂未上链存证。",
"certificateView": "查看证书",
"certificateOpening": "正在打开…",
"certificatePreview": "预览模式不生成证书。",
"certificateRequestFailed": "暂时无法生成证书,请稍后再试或联系平台。",
"certificateGenerating": "证书生成中,请稍候。完成后将自动打开天河链证书页面。",
"certificateShared": "同一件实物仅生成一次,之后直接查看已有证书。",
"certificateOpen": "打开证书",
"certificateCheckAgain": "重新查询",
"certificateBack": "返回",
"certificateReady": "证书已就绪。",
"certificateFailed": "存证申请未成功,请联系平台处理。",
"certificateUnknown": "结果暂未确认。稍后可重新查询,系统不会重复提交存证。",
"certificateNotRequested": "尚未申请证书,请从该实物溯源页点击“查看证书”。",
"certificateUnavailable": "暂时无法查询证书,请稍后重试。"
"certificateFailed": "暂时联系不上存证服务,证书没有生成。",
"certificateUnavailable": "暂时无法查询证书,请稍后重试。",
"certificateRetrieving": "正在调取存证数据",
"certificateAcquiring": "获取存证证书",
"certificatePreparing": "正在整理存证证书",
"certificateDelayed": "这件证书还没有生成完成,所以暂时没有图片。已经生成过的证书会直接打开,也可以稍后再查。",
"certificateContent": "存证内容",
"certificateDigest": "摘要",
"certificateAuthor": "作者",
"certificateTime": "生成时间",
"certificateDownload": "下载存证证书",
"certificateChainId": "天河链-区块链ID",
"certificateChainIdTip": "该字符串是证据上链过程中生成的区块交易ID值,通过此ID可以在天河链上查询到文件hash的上链信息。",
"certificateDigestTitle": "电子证据SHA256值",
"certificateDigestTip": "该值是通过SHA256算法计算原始证据文件后得出的文件HASH值,与证据文件唯一对应。该HASH值已被实时写入天河链,确保文件的不可篡改。"
},
"field": {
"viewFile": "查看文件"
+6 -3
View File
@@ -4,10 +4,13 @@ export default createRouter({
history: createWebHashHistory(),
routes: [
{ path: '/', component: () => import('@/views/Home.vue') },
{ path: '/trace/:code', component: () => import('@/views/Trace.vue') },
{ path: '/certificate/:code', component: () => import('@/views/Certificate.vue') },
{ path: '/trace/:code/proof', name: 'trace-proof', component: () => import('@/views/TraceProof.vue') },
{ path: '/trace/:code/certificate', name: 'trace-certificate', component: () => import('@/views/TraceCertificate.vue') },
{ path: '/trace/:code', name: 'trace', component: () => import('@/views/Trace.vue') },
// 后台预览模式:复用 Trace.vue,凭 ?token= 时间令牌访问,不激活/不计数
{ path: '/trace/preview/:code', component: () => import('@/views/Trace.vue') },
{ path: '/trace/preview/:code/proof', name: 'trace-preview-proof', component: () => import('@/views/TraceProof.vue') },
{ path: '/trace/preview/:code/certificate', name: 'trace-preview-certificate', component: () => import('@/views/TraceCertificate.vue') },
{ path: '/trace/preview/:code', name: 'trace-preview', component: () => import('@/views/Trace.vue') },
{ path: '/:pathMatch(.*)*', redirect: '/' },
],
});
-79
View File
@@ -1,79 +0,0 @@
<template>
<main class="certificate-page">
<section class="card certificate-card" aria-live="polite">
<h1>{{ t('chain.certificateView') }}</h1>
<p>{{ t(message) }}</p>
<p class="muted">{{ t('chain.certificateShared') }}</p>
<a v-if="url" class="action" :href="url" rel="noopener noreferrer">{{ t('chain.certificateOpen') }} →</a>
<button v-else-if="retryable" class="action" :disabled="busy" @click="resume">{{ t('chain.certificateCheckAgain') }}</button>
<button class="back" @click="router.back()">{{ t('chain.certificateBack') }}</button>
</section>
</main>
</template>
<script setup lang="ts">
import { onMounted, onUnmounted, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { fetchTraceCertificate, requestTraceCertificate } from '@/api';
const route = useRoute();
const router = useRouter();
const { t } = useI18n();
const message = ref('chain.certificateGenerating');
const retryable = ref(false);
const busy = ref(false);
const url = ref('');
let timer: ReturnType<typeof setTimeout> | undefined;
let stopped = false;
let polls = 0;
async function poll() {
if (stopped) return;
try {
const result = await fetchTraceCertificate(String(route.params.code));
if (stopped) return;
if (result.status === 'READY' && result.url) {
url.value = result.url;
message.value = 'chain.certificateReady';
window.location.replace(result.url);
return;
}
if (result.status === 'FAILED') { message.value = 'chain.certificateFailed'; return; }
if (result.status === 'UNKNOWN') {
message.value = 'chain.certificateUnknown'; retryable.value = true; return;
}
// A GET or link preview must never generate a certificate.
if (result.status === 'NONE' && polls >= 5) { message.value = 'chain.certificateNotRequested'; return; }
if (++polls >= 60) { message.value = 'chain.certificateUnknown'; retryable.value = true; return; }
timer = setTimeout(poll, 5000);
} catch {
if (!stopped) { message.value = 'chain.certificateUnavailable'; retryable.value = true; }
}
}
async function resume() {
if (busy.value) return;
busy.value = true;
try {
// Do not create a new request from this waiting page, even when opened directly.
const state = await fetchTraceCertificate(String(route.params.code));
if (state.status === 'NONE') { message.value = 'chain.certificateNotRequested'; retryable.value = false; return; }
if (state.status === 'UNKNOWN') await requestTraceCertificate(String(route.params.code));
polls = 0; retryable.value = false; message.value = 'chain.certificateGenerating';
await poll();
} catch { message.value = 'chain.certificateRequestFailed'; }
finally { busy.value = false; }
}
onMounted(poll);
onUnmounted(() => { stopped = true; if (timer) clearTimeout(timer); });
</script>
<style scoped>
.certificate-page { max-width: 600px; margin: 8vh auto; padding: 20px; }
.certificate-card { padding: 28px; text-align: center; line-height: 1.7; }
h1 { font-size: 23px; }
.action, .back { display: block; margin: 20px auto 0; padding: 10px 18px; border-radius: 8px; font: inherit; cursor: pointer; }
.action { color: white; background: var(--brand); border: none; text-decoration: none; }
.back { background: transparent; border: 1px solid var(--border); color: var(--muted); }
</style>
+198
View File
@@ -0,0 +1,198 @@
<template>
<div class="subpage">
<header class="subpage-bar">
<button type="button" class="subpage-back" @click="back">{{ t('chain.txBack') }}</button>
<h1>{{ t('chain.certificateView') }}</h1>
</header>
<div class="subpage-body">
<p v-if="preview" class="subpage-note">{{ t('chain.certificatePreview') }}</p>
<template v-else>
<p v-if="certificateError" class="subpage-note" role="alert">{{ certificateError }}</p>
<button v-if="certificateError && retryable" type="button" class="subpage-action" @click="load(true)">
{{ t('chain.certificateCheckAgain') }}
</button>
<template v-else-if="certificateRecord">
<div ref="stage" class="cert-stage" :style="{ height: `${720 * scale}px` }">
<div class="cert-fit" :style="{ transform: `scale(${scale})` }">
<trace-certificate-sheet ref="certificateSheet" :record="certificateRecord" />
</div>
</div>
<section class="prove-des">
<h2 class="des-title">
{{ t('chain.certificateChainId') }}
<button type="button" class="des-tip" :aria-label="t('chain.certificateChainId')" @click.stop="toggleTip('tx')">
<TipIcon />
<span class="des-pop" :class="{ open: tip === 'tx' }" role="tooltip">{{ t('chain.certificateChainIdTip') }}</span>
</button>
</h2>
<p class="des-hash">{{ certificateRecord.txHash }}</p>
<h2 class="des-title">
{{ t('chain.certificateDigestTitle') }}
<button type="button" class="des-tip" :aria-label="t('chain.certificateDigestTitle')" @click.stop="toggleTip('digest')">
<TipIcon />
<span class="des-pop" :class="{ open: tip === 'digest' }" role="tooltip">{{ t('chain.certificateDigestTip') }}</span>
</button>
</h2>
<p class="des-digest">{{ certificateRecord.digest }}</p>
<button type="button" class="des-download" @click="certificateSheet?.download()">{{ t('chain.certificateDownload') }}</button>
</section>
</template>
<div v-else class="subpage-wait">
<div class="certificate-spinner" aria-hidden="true" />
<ol class="certificate-steps">
<li v-for="(key, index) in certificateSteps" :key="key" :class="{ current: certificatePhase === index, done: certificatePhase > index }">
<span aria-hidden="true">{{ certificatePhase > index ? '✓' : index + 1 }}</span>{{ t(key) }}
</li>
</ol>
</div>
</template>
</div>
</div>
</template>
<script setup lang="ts">
import { defineComponent, h, nextTick, onMounted, onUnmounted, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { fetchTraceCertificate, requestTraceCertificate, type TraceCertificateRecord, type TraceCertificateResult } from '@/api';
import TraceCertificateSheet from '@/components/trace/TraceCertificateSheet.vue';
const TipIcon = defineComponent({
name: 'TipIcon',
setup() {
return () => h('svg', { viewBox: '0 0 1024 1024', width: 14, height: 14, 'aria-hidden': 'true' }, [
h('path', { fill: 'currentColor', d: 'M512 64a448 448 0 1 0 0 896 448 448 0 0 0 0-896zm0 820.48A372.48 372.48 0 1 1 512 139.52a372.48 372.48 0 0 1 0 744.96zM480 304h64v320h-64zm0 384h64v64h-64z' }),
]);
},
});
const route = useRoute();
const router = useRouter();
const { t } = useI18n();
const preview = route.name === 'trace-preview-certificate';
const code = String(route.params.code || '');
const certificateError = ref('');
const certificatePhase = ref(0);
const certificateRecord = ref<TraceCertificateRecord | null>(null);
const certificateSheet = ref<{ download: () => Promise<void> }>();
const retryable = ref(true);
const certificateSteps = ['chain.certificateRetrieving', 'chain.certificateAcquiring', 'chain.certificatePreparing'];
const stage = ref<HTMLElement>();
const scale = ref(1);
const tip = ref('');
let certificateTimer: ReturnType<typeof setTimeout> | undefined;
let certificateRun = 0;
let certificatePolls = 0;
let observer: ResizeObserver | undefined;
function back() {
const name = preview ? 'trace-preview' : 'trace';
if (window.history.state?.back) router.back();
else router.push({ name, params: { code }, query: route.query });
}
function failCertificate(messageKey: string, canRetry = true) {
certificateError.value = t(messageKey);
retryable.value = canRetry;
}
async function showCertificateResult(result: TraceCertificateResult, run: number) {
if (run !== certificateRun) return;
if (result.status === 'READY' && result.certificate) {
certificatePhase.value = 2;
certificateRecord.value = result.certificate;
await nextTick();
measure();
return;
}
if (result.status === 'FAILED') {
certificateError.value = result.message || t('chain.certificateFailed');
retryable.value = true;
return;
}
if (result.status === 'UNKNOWN') return failCertificate('chain.certificateDelayed');
if (result.status === 'NONE') return failCertificate('chain.certificateUnavailable');
certificatePhase.value = 1;
if (++certificatePolls >= 3) return failCertificate('chain.certificateDelayed');
certificateTimer = setTimeout(async () => {
try { showCertificateResult(await fetchTraceCertificate(code), run); }
catch { if (run === certificateRun) failCertificate('chain.certificateUnavailable'); }
}, 5000);
}
async function load(retry = false) {
if (preview) return;
certificateRun += 1;
if (certificateTimer) clearTimeout(certificateTimer);
const run = certificateRun;
certificateError.value = '';
certificateRecord.value = null;
certificatePhase.value = 0;
certificatePolls = 0;
retryable.value = true;
try {
const cached = await fetchTraceCertificate(code);
if (run !== certificateRun) return;
certificatePhase.value = 1;
const result = retry || cached.status === 'NONE' || cached.status === 'UNKNOWN'
? await requestTraceCertificate(code) : cached;
showCertificateResult(result, run);
} catch {
if (run === certificateRun) failCertificate('chain.certificateRequestFailed');
}
}
function toggleTip(name: string) {
if (window.matchMedia('(hover: hover) and (pointer: fine)').matches) return;
tip.value = tip.value === name ? '' : name;
}
function measure() {
const width = stage.value?.clientWidth || 0;
scale.value = width > 0 ? Math.min(1, width / 508) : 1;
}
onMounted(() => {
load();
observer = new ResizeObserver(measure);
observer.observe(document.documentElement);
});
onUnmounted(() => {
certificateRun += 1;
if (certificateTimer) clearTimeout(certificateTimer);
observer?.disconnect();
});
</script>
<style scoped>
.subpage { max-width: 560px; margin: 0 auto; min-height: 100vh; background: var(--bg); }
.subpage-bar { position: sticky; top: 0; z-index: 5; display: flex; align-items: center; gap: 10px; min-height: 52px; padding: 8px 12px; background: var(--card-bg); border-bottom: 1px solid var(--border); }
.subpage-bar h1 { flex: 1; min-width: 0; margin: 0; font-size: 16px; font-weight: 600; text-align: left; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.subpage-bar { flex-wrap: wrap; }
.subpage-back, .subpage-action { border: 0; background: transparent; color: var(--brand-2); font: inherit; font-size: 14px; cursor: pointer; padding: 6px 0; }
.subpage-action { background: var(--brand); color: #fff; border-radius: 6px; padding: 8px 12px; }
.prove-des { margin-top: 20px; text-align: left; color: #333; }
.des-title { display: flex; align-items: center; margin: 20px 0 12px; padding: 0 8px; border-left: 3px solid #2977f0; font-family: PingFang-SC-Bold, 'PingFang SC', 'Microsoft YaHei', sans-serif; font-size: 14px; font-weight: 700; line-height: 20px; color: #333; letter-spacing: 0.14px; }
.des-title:first-child { margin-top: 0; }
.des-tip { position: relative; display: inline-flex; margin-left: 4px; padding: 0; border: 0; background: transparent; color: #333; cursor: pointer; }
.des-pop { display: none; position: absolute; left: calc(100% + 8px); top: 50%; z-index: 6; width: 200px; transform: translateY(-50%); box-sizing: border-box; padding: 12px; border: 1px solid #ebeef5; border-radius: 4px; background: #fff; color: #606266; font-family: PingFangSC-Regular, 'PingFang SC', 'Microsoft YaHei', sans-serif; font-size: 14px; font-weight: 400; line-height: 1.4; letter-spacing: 0; text-align: left; box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1); }
.des-pop.open { display: block; }
@media (hover: hover) and (pointer: fine) {
.des-tip:hover .des-pop, .des-tip:focus-visible .des-pop { display: block; }
}
.des-hash, .des-digest { margin: 0 0 20px; font-family: PingFangSC-Regular, 'PingFang SC', 'Microsoft YaHei', sans-serif; font-size: 14px; font-weight: 400; line-height: normal; letter-spacing: 0.14px; text-align: left; word-break: break-all; }
.des-hash { margin-bottom: 0; color: #2977f0; }
.des-digest { color: #666; word-break: break-word; }
.des-download { min-width: 112px; height: 36px; padding: 6px 16px; border: 1px solid #2977f0; border-radius: 4px; background: #fff; color: #2977f0; font-family: PingFangSC-Regular, 'PingFang SC', 'Microsoft YaHei', sans-serif; font-size: 14px; font-weight: 500; line-height: 14px; cursor: pointer; }
.des-download:hover { background: rgba(41, 119, 240, 0.06); }
@media (max-width: 420px) {
.des-pop { left: 0; top: calc(100% + 6px); transform: none; }
}
.subpage-body { padding: 12px 12px 28px; }
.subpage-note { margin: 12px 0; font-size: 14px; line-height: 1.6; }
.cert-stage { position: relative; width: 100%; margin: 0 auto; }
.cert-fit { position: absolute; left: 50%; top: 0; width: 508px; margin-left: -254px; transform-origin: top center; }
.subpage-wait { padding: 12px 4px 24px; }
.certificate-spinner { width: 28px; height: 28px; border: 3px solid var(--border); border-top-color: var(--brand); border-radius: 50%; margin: 0 auto 24px; animation: certificate-spin .8s linear infinite; }
.certificate-steps { list-style: none; padding: 0; margin: 0; display: grid; gap: 18px; font-size: 14px; }
.certificate-steps li { display: flex; gap: 12px; align-items: center; color: var(--muted); }
.certificate-steps li span { border: 1px solid var(--border); border-radius: 50%; width: 24px; height: 24px; display: grid; place-items: center; flex-shrink: 0; }
.certificate-steps li.current { color: var(--text); font-weight: 600; }
.certificate-steps li.done { color: var(--brand); }
@keyframes certificate-spin { to { transform: rotate(360deg); } }
@media (prefers-reduced-motion: reduce) { .certificate-spinner { animation: none; } }
</style>
+138
View File
@@ -0,0 +1,138 @@
<template>
<div class="subpage">
<header class="subpage-bar">
<button type="button" class="subpage-back" @click="back">{{ t('chain.txBack') }}</button>
<h1>{{ t('chain.txTitle') }}</h1>
</header>
<div v-if="loading" class="subpage-state">
<div class="spinner" />
<p class="muted">{{ t('state.loading') }}</p>
</div>
<div v-else-if="missing" class="subpage-state">
<p>{{ t('chain.notOnchain') }}</p>
</div>
<trace-tx-detail
v-else
:tx-hash="blockchain?.txHash"
:succeeded="blockchain?.status === 'ONCHAIN'"
:status-text="t(`chain.statuses.${status}`)"
:block-height="blockchain?.blockHeight"
:contract-address="blockchain?.contractAddress"
:onchain-at="blockchain?.onchainAt"
:token-id="blockchain?.tokenId"
:author="blockchain?.author"
:product-id="blockchain?.productId || code"
:feature="blockchain?.feature"
:mint-to="blockchain?.mintTo"
:detail="blockchain?.chainDetail"
:show-heading="false"
:show-close="false"
@copy="copy"
@close="back"
/>
<transition name="toast">
<div v-if="toast" class="toast">{{ toast }}</div>
</transition>
</div>
</template>
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { fetchChainDetail, fetchTrace, fetchTracePreview, type ChainDetail } from '@/api';
import TraceTxDetail from '@/components/trace/TraceTxDetail.vue';
type ProofBlockchain = {
status?: string;
txHash?: string | null;
contractAddress?: string | null;
blockHeight?: string | number | null;
onchainAt?: string | null;
tokenId?: string | number | null;
author?: string | null;
productId?: string | null;
feature?: string | null;
mintTo?: string | null;
chainDetail?: ChainDetail | null;
};
const route = useRoute();
const router = useRouter();
const { t } = useI18n();
const preview = route.name === 'trace-preview-proof';
const code = String(route.params.code || '');
const loading = ref(true);
const missing = ref(false);
const blockchain = ref<ProofBlockchain | null>(null);
const toast = ref('');
const status = computed(() => blockchain.value?.status || 'ONCHAIN');
function storageKey() {
return `artveris.trace.proof.${preview ? 'preview.' : ''}${code}`;
}
function back() {
const name = preview ? 'trace-preview' : 'trace';
if (window.history.state?.back) router.back();
else router.push({ name, params: { code }, query: route.query });
}
async function copy(text?: string) {
if (!text) return;
try {
await navigator.clipboard.writeText(text);
} catch {
const area = document.createElement('textarea');
area.value = text;
document.body.appendChild(area);
area.select();
document.execCommand('copy');
area.remove();
}
toast.value = t('chain.copied');
setTimeout(() => (toast.value = ''), 1500);
}
onMounted(async () => {
const cached = sessionStorage.getItem(storageKey());
if (cached) {
try { blockchain.value = JSON.parse(cached) as ProofBlockchain; } catch { blockchain.value = null; }
}
if (!blockchain.value?.txHash) {
try {
const data = preview
? await fetchTracePreview(code, String(route.query.token || ''), route.query.state === 'inactive' ? 'inactive' : 'active')
: await fetchTrace(code);
blockchain.value = data?.status === 'OK' ? data.blockchain : null;
} catch {
blockchain.value = null;
}
}
if (!blockchain.value?.txHash) {
missing.value = true;
loading.value = false;
return;
}
if (!preview && !blockchain.value.chainDetail) {
try {
const result = await fetchChainDetail(code);
if (result.complete && result.detail) blockchain.value = { ...blockchain.value, chainDetail: result.detail };
} catch { /* 查询不到时保留已有字段 */ }
}
sessionStorage.setItem(storageKey(), JSON.stringify(blockchain.value));
loading.value = false;
});
</script>
<style scoped>
.subpage { max-width: 960px; margin: 0 auto; min-height: 100vh; background: #f4f6fa; }
.subpage-bar { position: sticky; top: 0; z-index: 5; display: flex; align-items: center; gap: 10px; min-height: 52px; padding: 8px 12px; background: var(--card-bg); border-bottom: 1px solid var(--border); }
.subpage-bar { flex-wrap: wrap; }
.subpage-bar h1 { flex: 1; min-width: 0; margin: 0; font-size: 16px; font-weight: 600; text-align: left; }
.subpage-back { border: 0; background: transparent; color: var(--brand-2); font: inherit; font-size: 14px; cursor: pointer; padding: 6px 0; }
.subpage-state { padding: 48px 16px; text-align: center; }
.spinner { width: 28px; height: 28px; border: 3px solid var(--border); border-top-color: var(--brand); border-radius: 50%; margin: 0 auto 12px; animation: spin .8s linear infinite; }
.toast { position: fixed; left: 50%; bottom: 28px; transform: translateX(-50%); background: #111827; color: #fff; border-radius: 999px; padding: 8px 14px; font-size: 13px; }
@media (max-width: 720px) {
.subpage { max-width: none; }
}
@keyframes spin { to { transform: rotate(360deg); } }
</style>
+3
View File
@@ -38,6 +38,9 @@ export default defineConfig({
server: {
port: 5174,
host: true,
strictPort: true,
watch: process.env.DOCKER_DEV === '1' ? { usePolling: true, interval: 300 } : undefined,
hmr: process.env.VITE_HMR_CLIENT_PORT ? { clientPort: Number(process.env.VITE_HMR_CLIENT_PORT) } : undefined,
proxy: {
'/api': { target: 'http://localhost:3000', changeOrigin: true },
'/uploads': { target: 'http://localhost:3000', changeOrigin: true },
+21
View File
@@ -0,0 +1,21 @@
# 本地开发镜像:依赖保存在 Linux 镜像内,源码通过 Compose 挂载。
FROM node:24-slim
ENV COREPACK_ENABLE_DOWNLOAD_PROMPT=0
# Nest watch 的进程树清理依赖 ps;slim 镜像默认没有,缺失会留下旧进程占用端口。
RUN apt-get update && apt-get install -y openssl ca-certificates procps && rm -rf /var/lib/apt/lists/*
RUN corepack enable
WORKDIR /app
COPY pnpm-workspace.yaml package.json pnpm-lock.yaml ./
COPY packages/shared/package.json ./packages/shared/
COPY apps/api/package.json ./apps/api/
COPY apps/admin/package.json ./apps/admin/
COPY apps/client/package.json ./apps/client/
RUN pnpm install --frozen-lockfile
COPY packages/shared ./packages/shared
COPY apps/api ./apps/api
COPY apps/admin ./apps/admin
COPY apps/client ./apps/client
COPY scripts/migrate.cjs /app/migrate.cjs
COPY docker/dev.mjs /app/dev.mjs
ENV NODE_ENV=development
CMD ["node", "/app/dev.mjs"]
+31 -10
View File
@@ -2,7 +2,7 @@ name: artveris-local
services:
mysql:
image: mysql:8.0
restart: unless-stopped
restart: "no"
environment:
MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD:?Required}
MYSQL_DATABASE: artveris_test
@@ -17,7 +17,7 @@ services:
retries: 30
redis:
image: redis:7-alpine
restart: unless-stopped
restart: "no"
environment:
REDIS_PASSWORD: ${REDIS_PASSWORD:?Required}
command: [sh, -c, 'exec redis-server --appendonly yes --requirepass "$${REDIS_PASSWORD}"']
@@ -29,26 +29,47 @@ services:
timeout: 5s
retries: 30
api:
image: artveris-api:local
image: artveris-dev:local
build:
context: ..
dockerfile: docker/Dockerfile.api
restart: unless-stopped
dockerfile: docker/Dockerfile.dev
restart: "no"
init: true
depends_on:
mysql:
condition: service_healthy
redis:
condition: service_healthy
environment:
NODE_ENV: production
NODE_ENV: development
ARTVERIS_DEV_ORIGIN: http://127.0.0.1:18080
DOCKER_DEV: "1"
TSC_WATCHFILE: DynamicPriorityPolling
TSC_WATCHDIRECTORY: DynamicPriorityPolling
CHOKIDAR_USEPOLLING: "true"
VITE_HMR_CLIENT_PORT: "18080"
API_PORT: 3000
ARTVERIS_ENV_FILE: /app/apps/api/config/.env
ARTVERIS_OUTBOUND_TEMP_DIR: /app/apps/api/tmp
TIANHE_BASE_URL: https://test.api.tichain.tianhecloud.com
# Local tests must never reach the paid production chain, even if settings change.
extra_hosts:
- "api.tichain.tianhecloud.com:127.0.0.1"
volumes:
- ../apps/api/src:/app/apps/api/src:ro
- ../apps/api/prisma:/app/apps/api/prisma:ro
- ../apps/api/tsconfig.json:/app/apps/api/tsconfig.json:ro
- ../apps/api/nest-cli.json:/app/apps/api/nest-cli.json:ro
- ../apps/admin/src:/app/apps/admin/src:ro
- ../apps/admin/public:/app/apps/admin/public:ro
- ../apps/admin/index.html:/app/apps/admin/index.html:ro
- ../apps/admin/vite.config.ts:/app/apps/admin/vite.config.ts:ro
- ../apps/admin/tsconfig.json:/app/apps/admin/tsconfig.json:ro
- ../apps/client/src:/app/apps/client/src:ro
- ../apps/client/public:/app/apps/client/public:ro
- ../apps/client/index.html:/app/apps/client/index.html:ro
- ../apps/client/vite.config.ts:/app/apps/client/vite.config.ts:ro
- ../apps/client/tsconfig.json:/app/apps/client/tsconfig.json:ro
- ../packages/shared/src:/app/packages/shared/src:ro
- ../packages/shared/tsconfig.json:/app/packages/shared/tsconfig.json:ro
- ./dev.mjs:/app/dev.mjs:ro
- ../.deploy/local/config:/app/apps/api/config
- ../.deploy/local/storage:/app/apps/api/storage
- ../.deploy/local/backups:/app/apps/api/backups
@@ -61,7 +82,7 @@ services:
retries: 5
web:
image: nginx:alpine
restart: unless-stopped
restart: "no"
depends_on:
- api
ports:
+57
View File
@@ -0,0 +1,57 @@
// 同一开发容器中管理 API、共享包与前后台监听进程;退出时一并清理。
import { spawn } from 'node:child_process';
const children = new Set();
let stopping = false;
function stop(code = 0) {
if (stopping) return;
stopping = true;
for (const child of children) {
try { process.kill(-child.pid, 'SIGTERM'); } catch (error) {
if (error.code !== 'ESRCH') console.error('[dev] 停止子进程失败:', error.message);
}
}
const timer = setTimeout(() => {
for (const child of children) {
try { process.kill(-child.pid, 'SIGKILL'); } catch (error) {
if (error.code !== 'ESRCH') console.error('[dev] 强制停止子进程失败:', error.message);
}
}
process.exit(code);
}, 5000);
timer.unref();
process.exitCode = code;
}
process.on('SIGINT', () => stop());
process.on('SIGTERM', () => stop());
function start(command, args, cwd = '/app') {
const child = spawn(command, args, { cwd, stdio: 'inherit', detached: true, env: process.env });
children.add(child);
child.on('exit', () => children.delete(child));
return child;
}
async function run(command, args, cwd) {
await new Promise((resolve, reject) => {
const child = start(command, args, cwd);
child.on('error', reject);
child.on('exit', code => code === 0 ? resolve() : reject(new Error(`${command} 退出码 ${code}`)));
});
}
try {
await run('pnpm', ['--filter', '@artveris/shared', 'build']);
await run('pnpm', ['--filter', '@artveris/api', 'exec', 'prisma', 'generate']);
// 迁移脚本复用 API 的配置读取实现;启动前全量编译一次。
await run('pnpm', ['--filter', '@artveris/api', 'build']);
await run('node', ['/app/migrate.cjs']);
for (const name of ['dev:shared', 'dev:api', 'dev:admin', 'dev:client']) {
const child = start('pnpm', [name]);
child.on('error', error => { console.error(`[dev] ${name}: ${error.message}`); stop(1); });
child.on('exit', code => {
if (!stopping) { console.error(`[dev] ${name} 已退出 (${code})`); stop(code || 1); }
});
}
} catch (error) {
console.error('[dev] 启动失败:', error.message);
stop(1);
}
+20 -9
View File
@@ -1,17 +1,28 @@
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
server {
listen 80;
server_name localhost;
client_max_body_size 0;
proxy_http_version 1.1;
proxy_read_timeout 3600s;
proxy_send_timeout 3600s;
proxy_request_buffering off;
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-Host $http_host;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
location = / { return 302 /admin/; }
location = /admin { return 302 /admin/; }
location = /trace { return 302 /trace/; }
location /admin/ { proxy_pass http://api:5173; }
location /trace/ { proxy_pass http://api:5174; }
location / {
proxy_pass http://api:3000;
proxy_http_version 1.1;
proxy_read_timeout 3600s;
proxy_send_timeout 3600s;
proxy_request_buffering off;
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-Host $http_host;
}
}
+1 -1
View File
@@ -213,7 +213,7 @@ flowchart LR
## 九、C 端与查验
- C 端溯源页区块链卡展示:链名、交易哈希、合约地址、区块高度、上链时间;tokenId 仍由后端保存,当前不对消费者展示;
- 「查看存证」按当前天河环境动态跳转 DApp 浏览器**交易详情页**(`transDetail?hash=<mintTxHash>`):测试环境使用 `test.explorer.tianhecloud.com`,正式环境使用 `explorer.tianhecloud.com`;链接不沿用数据库中的历史接口 URL;
- 「查看存证」打开站内存证详情,展示已保存的交易哈希、合约地址、区块高度、区块哈希和上链时间。公开溯源接口不返回天河链区块浏览器地址。
- 数据哈希为平台内部计算并保留的结构化内容摘要,不随当前 publish 请求上链,也不是链上交易标识或消费者追溯码,不在 C 端展示。
## 十、生产上线检查单
+14 -6
View File
@@ -3,10 +3,10 @@
在项目根目录执行以下命令。Compose 项目名为 `artveris-local`,与线上宝塔/PM2 部署隔离。
```powershell
# 启动已构建的环境
# 开发时启动(首次需要加 --build)
docker compose --env-file .deploy/local/.env -f docker/compose.local.yml up -d
# 修改源码后重新构建并启动(自动复用构建缓存)
# 仅依赖、锁文件或 Dockerfile 变化后重新构建
docker compose --env-file .deploy/local/.env -f docker/compose.local.yml up -d --build
# 查看状态及 API 日志
@@ -17,8 +17,8 @@ docker compose --env-file .deploy/local/.env -f docker/compose.local.yml logs --
docker compose --env-file .deploy/local/.env -f docker/compose.local.yml stop
```
- 后台:<http://localhost:18080/admin/>
- 客户端:<http://localhost:18080/trace/>
- 后台:<http://127.0.0.1:18080/admin/>
- 客户端:<http://127.0.0.1:18080/trace/>
- 超管账号:`admin`;本机生成的密码位于 `.deploy/local/credentials.json` 的 `admin` 字段。
- Compose 密码:`.deploy/local/.env`。
- 应用配置:`.deploy/local/config/.env`。
@@ -28,9 +28,17 @@ docker compose --env-file .deploy/local/.env -f docker/compose.local.yml stop
上述 `.deploy` 配置与秘密均被 Git 忽略,不应提交。当前环境已按用户要求导入生产业务数据与媒体作为测试数据;天河链凭据重新配置为专用测试环境,运行配置独立于线上。
应用使用现有生产 Dockerfile,前后台源码编译后由 API 托管,Nginx 提供统一入口。此方式用于本地完整集成测试;修改源码后需要重新构建,不提供热更新。
本地使用独立的 `docker/Dockerfile.dev`。API 开发容器内由 `docker/dev.mjs` 管理共享包 TypeScript watch、Nest watch、admin/client Vite 四个进程;Nginx 按 `/admin/`、`/trace/`、`/api` 路由到相应进程,并代理热更新 WebSocket。共享包、API 和前后台源码挂载到容器,Linux 依赖保存在镜像内,不使用 Windows 的 node_modules。
天河链使用测试环境 `https://test.api.tichain.tianhecloud.com`。测试凭据从 MemRelay 中名为“artveris · 天河链测试环境凭据”的条目读取。按需出证联调已经在免费测试链创建独立 NFT 测试记录和文本存证记录,见《消费者按需存证证书》。数据库设置优先于配置文件,因此后台的 `tianheEnv` 必须保持 `test`。Compose 额外将正式 API 域名解析到容器自身 `127.0.0.1`,防止误切正式环境后发出付费请求。不要移除此本地保护。
修改 Vue/样式/前端代码会热更新,修改后端代码会自动编译并重启后端进程,不必重建或重启容器。Windows Docker Desktop 使用轮询监听。开发镜像安装 `procps`,因为 Nest CLI 依赖 `ps` 终止旧进程树,缺失会在重编译后留下旧 API 占用端口。
仅依赖清单、锁文件或 Dockerfile 变化需要重新构建;Prisma schema/迁移变化后执行 `docker compose --env-file .deploy/local/.env -f docker/compose.local.yml restart api`,启动阶段会重新生成 Prisma Client 并应用迁移。编排或 Nginx 配置变化需重新启动相应服务。不要在 API watch 运行时用同一容器执行生产构建,以免同时改写 dist;发布构建使用独立镜像或发布脚本。
四个服务均为 `restart: "no"`,不会随 Docker/系统开机自动启动。开发时手动 `up -d`,结束后 `stop`,业务数据卷和上传文件持续保留。
Compose 明确设置 `NODE_ENV=development` 与 `ARTVERIS_DEV_ORIGIN=http://127.0.0.1:18080`。在这一显式本地模式下,后台链接、二维码、导出、短链跳转及设置页展示的客户端地址均优先使用本地地址,即便导入了生产数据库也不会跳到线上。生产模式忽略此覆盖,继续使用线上自己的配置。
当前导入的数据库是正式环境,`tianheEnv` 为 `production`。2026-11-15 用户明确允许本机调用正式付费接口,因此 Compose 不再把 `api.tichain.tianhecloud.com` 指到 `127.0.0.1`。本机上的出证、上链都会访问正式天河链并产生费用。配置文件里的 `TIANHE_BASE_URL` 仍是测试域名,但数据库设置优先,实际请求以 `tianheEnv` 为准。
本机上传 URL 不能被外部天河链服务访问;后续如测试需要天河链读取作品主图,应使用专用测试对象存储或测试公开图片地址,不复用生产存储写入权限。
+11 -4
View File
@@ -6,11 +6,17 @@
## 消费者使用
扫码页的区块链模块底部,在“查看存证”右侧增加“查看证书”。仅已激活、正常、已审核通过且 NFT 已确认的天河链实物可申请。普通页面打开、刷新与证书状态 GET 都不会提交存证;后台预览模式按钮禁用,不产生付费副作用。
扫码页区块链模块底部左侧为“查看存证”、右侧靠右为“查看证书”,均不显示箭头。仅明确 ONCHAIN 且有交易哈希的天河链实物显示证书按钮,未上链或处理中均不显示。仅已激活、正常、已审核通过的实物可申请。普通页面打开、刷新与证书状态 GET 都不会提交存证;后台预览模式按钮禁用,不产生付费副作用。
点击后立即打开等待页,由原页面 POST 申请。任务完成后等待页跳转到官方证书网页;浏览器阻止弹窗时改用当前页面等待。再次点击直接读取数据库已有链接,未重复生成。官方网页提供证书展示及下载,不保存图片到本平台。
「查看存证」和「查看证书」都进入本平台独立页面,不使用弹窗,手机上按屏幕宽度缩放,证书内部排版不改。证书页底部按天河链说明区展示区块链 ID、SHA256 和下载按钮,说明用悬停提示;哈希只显示文字,不跳转到天河链。证书页文案依次为“正在调取存证数据”“获取存证证书”“正在整理存证证书”。先读取已保存的证书字段,已生成的马上显示。没有时才 POST 申请,并短时间查询几次;仍未完成就停止转圈并提示稍后再查,不再空转数分钟。提交在收到任何响应前就连接失败时,记为未生成并可以重试;请求发出后超时则只查询原操作号,避免重复付费。证书按天河链证书页的版式在浏览器中绘制,下载也由浏览器生成 PNG。之后只读本地。交易详情里的 Gas、发送方和日志在第一次查到前留空,查全后写入本地,之后不再请求天河链。离开页面只停止当前等待,后台已提交任务继续完成。再次进入直接读取数据库已有记录,不重复生成。公开接口不返回天河链网址,客户页面也不能跳转到天河链。
首次点击固定作品名称、作者、档案编号、实物追溯码、NFT 交易哈希及本次记录时间,提交 V3 文本存证。文本以中文标签呈现,不上传作品图片或生产配置。证书证明的是本次提交的文本快照,作品后续编辑不自动重生成。证书 V3 哈希和生成时间独立于原 NFT 发行哈希/时间。
新证书首次点击时按系统设置 `certificateTextTemplate` 渲染并冻结正文,默认 `{{作品名称}} {{版本}}`,例如“十二生肖莲花手工杯 一个装”。设置入口为“系统设置 → 区块链 → 证书文本模板”,帮助按钮点击后才弹出字段说明。支持 `{{作品名称}}`、`{{版本}}`、`{{追溯码}}`、`{{档案编号}}`、`{{作者}}`,可自由排序、重复使用并插入普通文本或换行。版本按作品模板中显示名为“版本”的字段取值,当前数据键为 `size`,不能硬编码成 `version`。
模板最多500字符,拒绝未知占位符、错误花括号及表达式;只做纯文本替换,不执行代码、不解析Markdown。缺失字段替换为空,最终文本不能为空或超过2000字符。模板缺省时自动使用默认值,无需迁移数据库。更改模板只影响之后的首次申请,已经排队、提交或完成的证据保持不变,不重新生成。即使同款同版本渲染出相同文本,仍按每件实物分别保存operateId与状态。
模板允许真实换行。证书证明的是本次提交的文本快照,作品后续编辑不自动重生成。证书 V3 哈希和生成时间独立于原 NFT 发行哈希/时间。
“证书作者显示”使用单选项:默认 `WALLET`(存证钱包地址),可选 `ARTWORK_ARTIST`(作品作者名称)。名称取该实物作品档案的艺术家字段,空值回退钱包地址。公开接口只返回作者显示名和存证字段,不返回天河链网址。此显示设置在已有证书下次打开时也生效,不修改原证据、存证主体、哈希或生成时间,不重新调用天河链接口。它是显示名称,不表示将存证交易签名身份改成艺术家本人。说明集中在帮助按钮弹窗中。
## 服务端状态与恢复
@@ -46,8 +52,9 @@ NONE -> PENDING -> SUBMITTING -> WAITING -> CHECKING -> READY
## 验证
- API 全套 35 组 / 285 用例通过,包含未知结果恢复、防重、证据摘要与 URL 特殊字符用例。
- 最新 API 全套 35 组 / 288 用例通过,包含未知结果恢复、防重、证据摘要、URL 特殊字符与换行、本地链接覆盖用例。
- shared、API、admin、client 镜像构建通过。
- 本地测试实物 `477238000001` 已通过消费者按钮生成证书;`295708006702`、`278977006682` 完成中文证据与并发实测。最终为 5698 条 NONE、3 条 READY,其余实物没有自动生成。
- 并发首次申请只保存一份请求快照、生成一张证书。每日限额已按用户要求移除,新增回归覆盖旧限额为 0 时仍可申请,以及并发申请不覆盖原请求;GET、重复查看和服务重启保持缓存链接及生成时间不变。
- V2 发行 operateId 无法直接获得 V3 证书的测试结论见《天河链按需出证测试结论》。
- 新交互实测:`259394001444` 通过进度弹窗在测试链生成短文本证书并自动跳转;`402300000502` 为未上链实物,无“查看证书”按钮。新文本严格匹配作品名称、一个换行和追溯码。
+1 -1
View File
@@ -55,7 +55,7 @@
| 计费口径 | 按**每次调用上链接口**计费(非按容量)。"是否每件都上链/只上重点件"是纯运营成本决策,与代码无关 |
| 钱包粒度 | **单平台托管钱包**(公证者身份),UserID 固定 `artveris-platform`;每件实物的链上凭据(txHash/tokenId)互相独立,钱包地址不标识物品、不在 C 端展示 |
| 已售出标记 | **不需要**在链上做交易账单/已售出标记(甲方原话"不需要") |
| C 端查验入口 | 「查看存证」跳天河区块浏览器**交易详情页** `#/tiChain/transDetail?hash=<mintTxHash>`(不选藏品详情页,因不传媒体会显示"未获取到媒体内容") |
| C 端查验入口 | 「查看存证」打开站内存证详情;「查看证书」在站内展示并下载。公开接口不返回天河链网址,客户页面不能跳转到天河链。 |
### 3.2 链上身份与密钥安全
+20
View File
@@ -0,0 +1,20 @@
/** 证书正文只做字段替换,不执行表达式,也不渲染 Markdown/HTML。 */
export const DEFAULT_CERTIFICATE_TEXT_TEMPLATE = '{{作品名称}} {{版本}}';
export const CERTIFICATE_TEXT_FIELDS = ['作品名称', '版本', '追溯码', '档案编号', '作者'] as const;
export type CertificateTextField = typeof CERTIFICATE_TEXT_FIELDS[number];
export function validateCertificateTextTemplate(value: unknown): 'empty' | 'length' | 'fields' | null {
if (typeof value !== 'string' || !value.trim()) return 'empty';
if (value.length > 500) return 'length';
let invalid = false;
const remainder = value.replace(/\{\{\s*([^{}]+?)\s*\}\}/g, (_, field: string) => {
if (!(CERTIFICATE_TEXT_FIELDS as readonly string[]).includes(field.trim())) invalid = true;
return '';
});
return invalid || /[{}]/.test(remainder) ? 'fields' : null;
}
export function renderCertificateText(template: string, values: Record<CertificateTextField, string>): string {
if (validateCertificateTextTemplate(template)) throw new Error('证书文本模板格式无效');
return template.replace(/\{\{\s*([^{}]+?)\s*\}\}/g, (_, field: string) => values[field.trim() as CertificateTextField]).trim();
}
+1
View File
@@ -3,3 +3,4 @@ export * from './error-codes';
export * from './response';
export * from './constants';
export * from './trace-modules';
export * from './certificate-text';
+42
View File
@@ -218,9 +218,15 @@ importers:
dayjs:
specifier: ^1.11.13
version: 1.11.21
html2canvas:
specifier: ^1.4.1
version: 1.4.1
photoswipe:
specifier: ^5.4.4
version: 5.4.4
qrcode:
specifier: ^1.5.4
version: 1.5.4
vue:
specifier: ^3.5.13
version: 3.5.39(typescript@5.9.3)
@@ -1862,6 +1868,10 @@ packages:
resolution: {integrity: sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==}
engines: {node: 18 || 20 || >=22}
base64-arraybuffer@1.0.2:
resolution: {integrity: sha512-I3yl4r9QB5ZRY3XuJVEPfc2XhZO6YweFPI+UovAzn+8/hb3oJ6lnysaFcjVpkCPfVWFUDvoZ8kmVDP7WyRtYtQ==}
engines: {node: '>= 0.6.0'}
base64-js@1.5.1:
resolution: {integrity: sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==}
@@ -2167,6 +2177,9 @@ packages:
resolution: {integrity: sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==}
engines: {node: '>= 8'}
css-line-break@2.1.0:
resolution: {integrity: sha512-FHcKFCZcAha3LwfVBhCQbW2nCNbkZXn7KVUJcsT5/P8YmfsVja0FMPJr0B903j/E69HUphKiV9iQArX8SDYA4w==}
css-render@0.15.14:
resolution: {integrity: sha512-9nF4PdUle+5ta4W5SyZdLCCmFd37uVimSjg1evcTqKJCyvCEEj12WKzOSBNak6r4im4J4iYXKH1OWpUV5LBYFg==}
@@ -2568,6 +2581,10 @@ packages:
html-escaper@2.0.2:
resolution: {integrity: sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==}
html2canvas@1.4.1:
resolution: {integrity: sha512-fPU6BHNpsyIhr8yyMpTLLxAbkaK8ArIBcmZIRiBLiDhjeqvXolaEmDGmELFuX9I4xDcaKKcJl+TKZLqruBbmWA==}
engines: {node: '>=8.0.0'}
http-errors@2.0.1:
resolution: {integrity: sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==}
engines: {node: '>= 0.8'}
@@ -3649,6 +3666,9 @@ packages:
resolution: {integrity: sha512-cAGWPIyOHU6zlmg88jwm7VRyXnMN7iV68OGAbYDk/Mh/xC/pzVPlQtY6ngoIH/5/tciuhGfvESU8GrHrcxD56w==}
engines: {node: '>=8'}
text-segmentation@1.0.3:
resolution: {integrity: sha512-iOiPUo/BGnZ6+54OsWxZidGCsdU8YbE4PSpdPinp7DeMtUJNJBoJ/ouUSTJjHkh1KntHaltHl/gDs2FC4i5+Nw==}
tinyglobby@0.2.17:
resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==}
engines: {node: '>=12.0.0'}
@@ -3800,6 +3820,9 @@ packages:
util-deprecate@1.0.2:
resolution: {integrity: sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==}
utrie@1.0.2:
resolution: {integrity: sha512-1MLa5ouZiOmQzUbjbu9VmjLzn1QLXBhwpUa7kdLUQK+KQ5KA9I1vk5U4YHe/X2Ch7PYnJfWuWT+VbuxbGwljhw==}
uuid@11.1.1:
resolution: {integrity: sha512-vIYxrBCC/N/K+Js3qSN88go7kIfNPssr/hHCesKCQNAjmgvYS2oqr69kIufEG+O4+PfezOH4EbIeHCfFov8ZgQ==}
hasBin: true
@@ -5884,6 +5907,8 @@ snapshots:
balanced-match@4.0.4: {}
base64-arraybuffer@1.0.2: {}
base64-js@1.5.1: {}
baseline-browser-mapping@2.10.40: {}
@@ -6188,6 +6213,10 @@ snapshots:
shebang-command: 2.0.0
which: 2.0.2
css-line-break@2.1.0:
dependencies:
utrie: 1.0.2
css-render@0.15.14:
dependencies:
'@emotion/hash': 0.8.0
@@ -6615,6 +6644,11 @@ snapshots:
html-escaper@2.0.2: {}
html2canvas@1.4.1:
dependencies:
css-line-break: 2.1.0
text-segmentation: 1.0.3
http-errors@2.0.1:
dependencies:
depd: 2.0.0
@@ -7881,6 +7915,10 @@ snapshots:
glob: 7.2.3
minimatch: 3.1.5
text-segmentation@1.0.3:
dependencies:
utrie: 1.0.2
tinyglobby@0.2.17:
dependencies:
fdir: 6.5.0(picomatch@4.0.4)
@@ -8022,6 +8060,10 @@ snapshots:
util-deprecate@1.0.2: {}
utrie@1.0.2:
dependencies:
base64-arraybuffer: 1.0.2
uuid@11.1.1: {}
v8-compile-cache-lib@3.0.1: {}