feat: 追溯码客户端预览(TOTP式令牌保护,不激活不计数,可切换激活状态预览)

This commit is contained in:
Nixevol
2026-07-12 23:16:37 +08:00
parent 8fd417aa87
commit c1d8fb9ca4
17 changed files with 696 additions and 191 deletions
+1
View File
@@ -250,6 +250,7 @@
- 出库/上链防重复(2026-07-10):按「一物一码只能出库一次、已上链不可再上」补齐幂等校验。① 出库:`outbound.service.updateSingle`(单件)、`import-preview.processor`(导入预览)、`import.processor`(导入提交,防预览→提交竞态)三处均对 `code.outTime` 已存在拒绝「该追溯码已登记出库,不可重复出库」。② 上链:`attestation.service.trigger` 新增查重——存在 ONCHAIN/CONFIRMING/PENDING 的 proof 即拒绝(已上链→「不可重复上链」,处理中→「请稍候」);仅 FAILED 可通过独立 `retry` 接口重试(retry 原地更新既有 proof、不走 trigger,不受影响)。实测重复上链/重复出库均返回 400 拒绝。
- 天河链确认节奏调整(2026-07-10):`onchain.processor` 确认查询改为「提交完立即查 1 次 → 未到 10s → 再 30s」共 3 次自动尝试,之后停等手动重新确认(原为 30s/60s 两次)。用延迟数组 `AUTO_CONFIRM_DELAYS_MS=[0,10_000,30_000]`、`MAX_AUTO_CONFIRM_ATTEMPTS=数组长度`,第 attempt 次延迟取 `[attempt-1]`。实测:提交同秒即查到 mint 已进块(status 0x0、blockHeight、tokenId),直接 ONCHAIN。
- 天河链方案 B 落地(存证+发行+轮换,2026-07-10,dev/refine):按甲方决策「其余全做、媒体待定」实现。① 数据模型:`blockchain_proof` 加 `token_id`/`contract_address`(迁移 `20260710110000_add_proof_token_fields`);schema 补 `@db.VarChar` 注解消除历史 drift(operation_log.path 512 / outbound_import_session.file_key 512 / backup_record.file_path 1024)。② `TianheProvider` 新增 `publish`(接口2,operateId≤20,name≤42,author≤120,feature≤500)与 `updateUserKey`(接口7)。③ `BlockchainService.attestWithTianhe`:upload 存证→publish 铸 1 NFT(productId=追溯码、feature=存证链接)→ 主 txHash 切为 mint 交易、confirmationRequired=true 走接口9确认→ONCHAIN;合约地址存 `tianheContractAddress`、已发行最大 tokenId 存 `tianheMaxTokenId`(指定合约时作 baseTokenId,队列串行无争用);缺 product 时退化纯存证。`confirmTransaction` 确认成功回填 tokenId、更新 maxTokenId。④ `rotateTianheUserKey`:生成新随机 key→接口7链上改→持久化→接口8校验地址,`/settings/tianhe/identity/rotate` + 设置页「轮换密钥」(二次确认+回显强提示)。⑤ C 端:public-trace + Trace.vue 区块链卡增 tokenId/合约地址展示(i18n chain.tokenId/chain.contract)。⑥ 实测(测试环境):追溯码 412680781069 走通 upload→publish(合约 0xc96ae8a4... tokenId=0)→确认(区块高度 5820347)→ONCHAIN,C 端展示数字藏品编号 0/合约地址/区块高度;轮换 UserKey 成功(钱包地址不变),新 key 回填测试文档。验证:4 包构建 + 27 单测通过。**唯一待定:媒体上链层级 L1/L2/L3 待甲方确认「链上放什么」,当前维持 JSON 存证。**
- 追溯码客户端预览功能(2026-07-12,分支 `dev/tianhe-no-metadata-upload`):后台可预览 C 端页面且**零副作用**(不激活/不计数/不写查询日志)。① 令牌:`common/utils/preview-token.util.ts` 类 TOTP——HMAC-SHA256(jwt.secret, `preview:窗口号`) 取 16 hex,周期 10 分钟,校验接受当前+上一窗口(实际有效 10~20 分钟),无状态不落库,`timingSafeEqual` 防时序;外泄地址最长 2 窗口失效。② 后端:`GET /trace-codes/preview-token`(登录态)返回 `{token, clientBase, periodMs}`;`GET public/trace/:shortCode/preview?token&state`(@Public+限流)校验失败返回 `{status:'PREVIEW_EXPIRED'}`,成功走 `PublicTraceService.preview(state)`——与 trace() 共用 `buildArtworkPayload`(作品/时间线/证书/链上),但无任何 update/writeLog;`state=inactive` 时 antiCounterfeit 演示为首次扫码,`active` 用库中现值(0 时占位 2)。③ C 端:路由 `/trace/preview/:code` 复用 Trace.vue;`isPreview` 按路径判定,预览条(sticky 橙色)含「未激活/已激活」切换(切换重新请求),PREVIEW_EXPIRED 显示「预览链接已过期请回后台重开」。④ 后台:`traceCodeApi.previewToken`;TraceCodePanel 令牌缓存 8 分钟;**点追溯码=进预览页**(hover 提示「点击进入预览页(不激活、不计入查询次数)」;先同步 window.open('about:blank') 再异步填 URL 防弹窗拦截);**点链接列=弹确认框**告知直接访问会激活/计数,按钮[取消][访问预览页面][访问实际页面]。⑤ 预览 URL 仅点击时临时拼接不进行数据,导出仍只含真实短链。验证:5 项令牌单测 + API 实测(preview 前后 queryCount=0/INACTIVE 不变、查询日志 0 条、坏令牌拒绝、双状态正确)+ 全量构建 + 32 单测通过。
- 追溯码列表列重排+关联跳转(2026-07-12,分支 `dev/tianhe-no-metadata-upload`,两页共用 `TraceCodePanel` 同时生效):列顺序改为 追溯码→名称→档案编号→批次编号→分组→出库状态→上链状态→出库时间→激活状态→查询次数→激活时间→链接→创建时间→操作;名称/档案编号仅全局页显示(`fixedArtworkId` 时隐藏,档案内为同一作品)。关联:追溯码列渲染为 `<a target=_blank href=r.url>` 点击开 C 端溯源页;名称/档案编号渲染为 `.cell-link` 点击 `goArtwork(id)` → `router.push({name:'artwork-detail'})`。`status` 列标题改用 `pages.traceCode.activationStatus`(激活状态),`firstActivatedAt` 标签改为「激活时间」,新增 `openTrace` i18n。追溯码列 `fixed:'left'`、操作列 `fixed:'right'`。浏览器双页实测通过。
- 出库/上链弹窗 UI 打磨(2026-07-10,分支 `dev/tianhe-no-metadata-upload`):① 出库时间加红星必填标识(`n-form-item-gi :required="!outboundReadonly"`);② 修复「关闭」按钮显示字面量——`common.action` 原缺 `close` 键,已补中英;③「区块链存证」详情用 `n-descriptions` 的 `label-style` 设 `whiteSpace:nowrap + verticalAlign:middle`,标题不再折行、垂直居中;④ 除「上链状态」外每项(数据哈希/交易哈希/tokenId/合约/区块高度/上链时间/存证查询)加复制按钮(`CopyOutline` + `navigator.clipboard`,`copyValue` 提示 `common.msg.copied/copyFailed`)。浏览器实测通过。
- 出库/上链一致性强化(2026-07-10,分支 `dev/tianhe-no-metadata-upload`):按甲方口径补三条不变量。① 确认中即已上链:前端 `rowIsOnchain` 由仅认 ONCHAIN 改为认 `ONCHAIN/CONFIRMING/PENDING`(这些状态菜单均显示「上链信息」、不给再触发;仅 FAILED 显示「上链」可重试),与后端 `attestation.trigger` 早有的防重复拦截对齐(天河 publish 一返回 mint 哈希即已广播上链、必进块,除非明确失败,故确认中不可重复上链);`targetProof` 回退用 `latestAnyProof` 使确认中也能展示上链信息。② 出库时间必填默认此刻:弹窗未出库时默认 `dayjs()` 此刻、前端空值拦截、后端 `outbound.updateSingle` 强制 `outTime` 非空。③ 上链必先出库:后端 `attestation.trigger` 增 `isOutbound(code)` 校验,未出库拒绝「请先登记出库再上链」,杜绝「已上链未登记」不一致(防直连 API 绕过)。注:这些为通用改进,暂随本分支;方案二合并时一并进 dev/refine,若方案二被否再单独回植。
+2
View File
@@ -85,6 +85,7 @@ export const traceCodeApi = {
qrBlob: (id: string) => download(`/trace-codes/${id}/qrcode`),
onchain: (id: string) => post(`/trace-codes/${id}/onchain`, {}),
confirmProof: (id: number) => post(`/blockchain-proofs/${id}/confirm`, {}),
previewToken: () => get<{ token: string; clientBase: string; periodMs: number }>('/trace-codes/preview-token'),
// 分组
groups: (params?: object) => get<any[]>('/trace-code-groups', params),
createGroup: (data: { name: string; remark?: string }) => post('/trace-code-groups', data),
@@ -138,6 +139,7 @@ export const settingsApi = {
tianheVerify: (data: { userId: string; userKey: string }) =>
post<{ userId: string; address: string }>('/settings/tianhe/verify', data),
tianheIdentity: () => get<{ userId: string; address: string; userKeyMasked: string }>('/settings/tianhe/identity'),
tianheRevealAppKey: () => post<{ appKeyMasked: string }>('/settings/tianhe/app-key/reveal', {}),
tianheReveal: () => post<{ userId: string; userKey: string; address: string }>('/settings/tianhe/identity/reveal', {}),
tianheRotate: () => post<{ userId: string; userKey: string; address: string }>('/settings/tianhe/identity/rotate', {}),
};
+74 -4
View File
@@ -366,7 +366,7 @@ const outboundModalTitle = computed(() => outboundMenuLabel(outboundTarget.value
const columns = computed<DataTableColumns<any>>(() => {
const cols: DataTableColumns<any> = [
{ type: 'selection' },
// 追溯码:点击打开该码的 C 端溯源页
// 追溯码:点击进入预览页(不激活、不计数)
{
title: () => t('pages.traceCode.shortCode'),
key: 'shortCode',
@@ -376,7 +376,7 @@ const columns = computed<DataTableColumns<any>>(() => {
render: (r) =>
h(
'a',
{ href: r.url, target: '_blank', rel: 'noopener', class: 'cell-link', title: t('pages.traceCode.openTrace') },
{ class: 'cell-link', title: t('pages.traceCode.previewHint'), onClick: () => openPreview(r) },
r.shortCode,
),
},
@@ -464,7 +464,7 @@ const columns = computed<DataTableColumns<any>>(() => {
{ title: () => t('pages.traceCode.queryCount'), key: 'queryCount', width: 100, align: 'center' },
// 激活时间
{ title: () => t('pages.traceCode.firstActivatedAt'), key: 'firstActivatedAt', width: 150, align: 'center', render: (r) => fmt(r.firstActivatedAt), ...sortProps('firstActivatedAt') },
// 链接
// 链接:拦截直跳,先告知「直接访问会激活/计数」,再让用户选预览或实际访问
{
title: () => t('pages.traceCode.url'),
key: 'url',
@@ -473,7 +473,15 @@ const columns = computed<DataTableColumns<any>>(() => {
render: (r) =>
h(
'a',
{ href: r.url, target: '_blank', rel: 'noopener', style: 'color: var(--brand); text-decoration: none' },
{
href: r.url,
style: 'color: var(--brand); text-decoration: none',
title: t('pages.traceCode.visitWarnTitle'),
onClick: (e: MouseEvent) => {
e.preventDefault();
confirmVisitReal(r);
},
},
[r.url, h(NIcon, { component: OpenOutline, style: 'vertical-align:-2px;margin-left:4px' })],
),
},
@@ -514,6 +522,68 @@ function goArtwork(id?: number) {
router.push({ name: 'artwork-detail', params: { id: String(id) } });
}
// 预览令牌缓存:令牌自取用起至少 10 分钟有效(当前+上一窗口),缓存 8 分钟内复用,过期自动重取。
// 预览 URL 仅在点击时临时拼接,不进入行数据,因此导出永远只含真实短链。
let previewCache: { token: string; clientBase: string; fetchedAt: number } | null = null;
async function getPreviewInfo() {
if (!previewCache || Date.now() - previewCache.fetchedAt > 8 * 60_000) {
const res = await traceCodeApi.previewToken();
previewCache = { token: res.token, clientBase: res.clientBase, fetchedAt: Date.now() };
}
return previewCache;
}
// 先同步开空白窗口再异步填充地址,避免 await 后 window.open 被浏览器拦截
function openPreview(row: any) {
const win = window.open('about:blank', '_blank');
getPreviewInfo()
.then((info) => {
const url = `${info.clientBase}/#/trace/preview/${encodeURIComponent(row.shortCode)}?token=${info.token}&state=inactive`;
if (win) win.location.href = url;
else window.open(url, '_blank');
})
.catch(() => {
win?.close();
message.error(t('pages.traceCode.previewOpenFailed'));
});
}
// 点「链接」列:告知直接访问会激活/计数,提供预览与实际两个入口
function confirmVisitReal(row: any) {
const d = dialog.warning({
title: t('pages.traceCode.visitWarnTitle'),
content: t('pages.traceCode.visitWarnContent'),
action: () =>
h('div', { style: 'display:flex;gap:8px;justify-content:flex-end' }, [
h(NButton, { size: 'small', onClick: () => d.destroy() }, { default: () => t('common.action.cancel') }),
h(
NButton,
{
size: 'small',
type: 'primary',
onClick: () => {
d.destroy();
openPreview(row);
},
},
{ default: () => t('pages.traceCode.visitPreview') },
),
h(
NButton,
{
size: 'small',
type: 'warning',
onClick: () => {
d.destroy();
window.open(row.url, '_blank');
},
},
{ default: () => t('pages.traceCode.visitReal') },
),
]),
});
}
type HeaderFilterField = 'batchId' | 'groupId' | 'status' | 'outboundStatus';
type HeaderFilterValue = string | number | null;
type HeaderFilterOption = { label: string; value: string | number };
+15
View File
@@ -386,6 +386,12 @@
"firstActivatedAt": "Activated At",
"activationStatus": "Activation",
"openTrace": "Open trace page",
"previewHint": "Click to open preview (no activation, no query counting)",
"previewOpenFailed": "Failed to open preview, please retry",
"visitWarnTitle": "Visit Notice",
"visitWarnContent": "Visiting the real trace link will activate the code and increase its query count. To just check the page, use the preview page (no activation, no counting).",
"visitPreview": "Open Preview Page",
"visitReal": "Open Real Page",
"exportBatch": "Export Batch",
"exportCurrent": "Current filter",
"bindArtwork": "Link Artwork File",
@@ -510,6 +516,11 @@
"platformInfo": "Platform Settings",
"logAndDisplay": "Log Settings",
"backupPolicy": "Backup Policy",
"tabPlatform": "Platform",
"tabLogsBackup": "Logs & Backup",
"tabBlockchain": "Blockchain",
"tabStorage": "Storage",
"backupList": "Backup List",
"appName": "Platform Name",
"appIcon": "System Icon",
"logRetentionDays": "Query Log Days",
@@ -572,6 +583,10 @@
"tianheRevealConfirmContent": "The User Key is the sole credential for the platform custodial wallet. Revealing it will be recorded in the operation log. Make sure your environment is secure before continuing.",
"tianheCopy": "Copy",
"tianheCopied": "User Key copied",
"tianheCopyConfirmTitle": "Copy User Key",
"tianheCopyConfirmContent": "Copying writes the full User Key to the clipboard and will be recorded in the operation log. Make sure your environment is secure before continuing.",
"tianheAppKeyRevealTitle": "View App Key",
"tianheAppKeyRevealContent": "This action will be recorded in the operation log. Make sure your environment is secure before continuing. Only the masked form is shown; the full App Key is never displayed.",
"tianheIdentityHint": "The User Key is the only credential to open the platform custodial wallet. TiChain does not store it and it cannot be recovered. Keep the User ID and User Key offline; after reinstalling or migrating, use Manual Entry to continue with the same on-chain identity.",
"tianheRegisterDone": "On-chain identity registered",
"tianheSaveKeyWarning": "Save these credentials offline immediately (losing them means you cannot attest with the same identity again): User ID: {userId}; User Key: {userKey}",
+15
View File
@@ -386,6 +386,12 @@
"firstActivatedAt": "激活时间",
"activationStatus": "激活状态",
"openTrace": "打开溯源页",
"previewHint": "点击进入预览页(不激活、不计入查询次数)",
"previewOpenFailed": "预览页打开失败,请重试",
"visitWarnTitle": "访问提示",
"visitWarnContent": "直接访问追溯码链接会激活该码并增加查询次数。如仅需查看页面效果,请使用预览页面(不激活、不计入查询次数)。",
"visitPreview": "访问预览页面",
"visitReal": "访问实际页面",
"exportBatch": "导出本批",
"exportCurrent": "当前筛选",
"bindArtwork": "关联作品档案",
@@ -510,6 +516,11 @@
"platformInfo": "平台设置",
"logAndDisplay": "日志设置",
"backupPolicy": "备份策略",
"tabPlatform": "平台设置",
"tabLogsBackup": "日志与备份",
"tabBlockchain": "区块链存证",
"tabStorage": "存储配置",
"backupList": "备份列表",
"appName": "平台名称",
"appIcon": "系统图标",
"logRetentionDays": "查询日志保留天数",
@@ -572,6 +583,10 @@
"tianheRevealConfirmContent": "User Key 是平台托管钱包的唯一凭据,揭示操作将被记入操作日志。请确认当前环境安全后再继续。",
"tianheCopy": "复制",
"tianheCopied": "User Key 已复制",
"tianheCopyConfirmTitle": "复制 User Key",
"tianheCopyConfirmContent": "复制会将完整 User Key 写入剪贴板,该操作将记入操作日志。请确认当前环境安全后再继续。",
"tianheAppKeyRevealTitle": "查看 App Key",
"tianheAppKeyRevealContent": "该操作将记入操作日志,请确认当前环境安全后再继续。查看仅显示掩码形式,不会显示完整 App Key。",
"tianheIdentityHint": "User Key 是打开平台托管钱包的唯一凭据,天河链不留存、无法找回。请务必离线保存 User ID 与 User Key;重装或迁移系统后可通过「手动录入」继续使用同一链上身份。",
"tianheRegisterDone": "链上身份注册成功",
"tianheSaveKeyWarning": "请立即离线保存以下凭据(丢失将无法继续以同一身份存证):User ID:{userId};User Key:{userKey}",
+281 -181
View File
@@ -1,14 +1,16 @@
<template>
<div class="page settings-page">
<div class="settings-shell">
<div class="settings-content">
<n-form class="settings-form" label-placement="top">
<div class="settings-save">
<n-button type="primary" :loading="saving" @click="save">{{ t('common.action.save') }}</n-button>
</div>
<n-tabs class="settings-tabs" type="line" :value="activeTab" @update:value="onTabChange">
<template #suffix>
<n-button v-if="activeTab !== 'storage'" type="primary" size="small" :loading="saving" @click="save">
{{ t('common.action.save') }}
</n-button>
</template>
<div class="settings-card-grid">
<section class="settings-card platform-card">
<n-tab-pane name="platform" :tab="t('pages.settings.tabPlatform')">
<div class="tab-body">
<div class="tab-stack stack-narrow">
<section class="settings-card">
<div class="card-title">{{ t('pages.settings.platformInfo') }}</div>
<div class="setting-row">
<n-form-item :label="t('pages.settings.appName')">
@@ -49,12 +51,18 @@
</div>
<div class="setting-row">
<n-form-item :label="t('pages.settings.clientBaseUrl')">
<n-input v-model:value="form.clientBaseUrl" class="url-control" />
<n-input v-model:value="form.clientBaseUrl" class="text-control" />
</n-form-item>
</div>
</section>
</div>
</div>
</n-tab-pane>
<div class="settings-side-stack">
<n-tab-pane name="logsBackup" :tab="t('pages.settings.tabLogsBackup')">
<div class="tab-body">
<div class="tab-stack stack-wide">
<div class="stack-row">
<section class="settings-card">
<div class="card-title">{{ t('pages.settings.logAndDisplay') }}</div>
<div class="setting-row">
@@ -89,7 +97,20 @@
</section>
</div>
<section class="settings-card blockchain-card">
<section class="settings-card">
<div class="card-title">{{ t('pages.settings.backupList') }}</div>
<div class="backup-body">
<backup-restore-panel />
</div>
</section>
</div>
</div>
</n-tab-pane>
<n-tab-pane name="blockchain" :tab="t('pages.settings.tabBlockchain')">
<div class="tab-body">
<div class="tab-stack stack-mid">
<section class="settings-card">
<div class="card-title">{{ t('pages.settings.blockchainSettings') }}</div>
<div class="setting-row">
<n-form-item :label="t('pages.settings.blockchainDriver')">
@@ -103,7 +124,7 @@
</div>
<div class="setting-row">
<n-form-item :label="t('pages.settings.tianheBaseUrl')">
<n-input v-model:value="form.tianheBaseUrl" class="url-control" :disabled="form.tianheEnv !== 'custom'" />
<n-input v-model:value="form.tianheBaseUrl" class="text-control" :disabled="form.tianheEnv !== 'custom'" />
</n-form-item>
</div>
<div class="setting-row">
@@ -113,18 +134,33 @@
</div>
<div class="setting-row">
<n-form-item :label="t('pages.settings.tianheAppKey')">
<n-input v-model:value="form.tianheAppKey" type="password" show-password-on="click" class="text-control" />
<div class="secret-field">
<n-input v-model:value="form.tianheAppKey" :type="appKeyRevealed ? 'text' : 'password'" class="secret-input" />
<n-button
quaternary
circle
size="small"
:title="appKeyRevealed ? t('pages.settings.tianheHide') : t('pages.settings.tianheReveal')"
@click="toggleAppKeyReveal"
>
<template #icon>
<n-icon :component="appKeyRevealed ? EyeOffOutline : EyeOutline" />
</template>
</n-button>
</div>
</n-form-item>
</div>
<template v-if="form.blockchainDriver === 'tianhe'">
<div class="setting-row identity-head">
<div class="identity-head">
<span class="identity-title">{{ t('pages.settings.tianheIdentity') }}</span>
<div class="card-actions">
<div class="identity-actions">
<n-button size="small" :loading="registeringIdentity" @click="registerIdentity">
{{ identity.address ? t('pages.settings.tianheReRegister') : t('pages.settings.tianheRegister') }}
</n-button>
<n-button size="small" @click="manualEntryVisible = true">{{ t('pages.settings.tianheManualEntry') }}</n-button>
<n-button v-if="identity.userKeyMasked" size="small" :loading="rotatingIdentity" @click="rotateUserKey">{{ t('pages.settings.tianheRotate') }}</n-button>
<n-button v-if="identity.userKeyMasked" size="small" :loading="rotatingIdentity" @click="rotateUserKey">
{{ t('pages.settings.tianheRotate') }}
</n-button>
</div>
</div>
<div class="setting-row">
@@ -141,36 +177,44 @@
<n-form-item label="User Key">
<div class="identity-key">
<span class="identity-value mono">{{ identityKeyDisplay }}</span>
<n-button v-if="identity.userKeyMasked" size="tiny" quaternary @click="revealUserKey">
{{ revealKey ? t('pages.settings.tianheHide') : t('pages.settings.tianheReveal') }}
<n-button
v-if="identity.userKeyMasked"
quaternary
circle
size="small"
:title="revealKey ? t('pages.settings.tianheHide') : t('pages.settings.tianheReveal')"
@click="revealUserKey"
>
<template #icon>
<n-icon :component="revealKey ? EyeOffOutline : EyeOutline" />
</template>
</n-button>
<n-button
v-if="identity.userKeyMasked"
quaternary
circle
size="small"
:title="t('pages.settings.tianheCopy')"
@click="copyUserKey"
>
<template #icon>
<n-icon :component="CopyOutline" />
</template>
</n-button>
<n-button v-if="identity.userKeyMasked" size="tiny" quaternary @click="copyUserKey">{{ t('pages.settings.tianheCopy') }}</n-button>
</div>
</n-form-item>
</div>
<p class="identity-hint">{{ t('pages.settings.tianheIdentityHint') }}</p>
</template>
</section>
</div>
</div>
</n-tab-pane>
<n-modal
v-model:show="manualEntryVisible"
preset="dialog"
:title="t('pages.settings.tianheManualEntry')"
:positive-text="t('pages.settings.tianheVerifySave')"
:negative-text="t('common.action.cancel')"
:loading="verifyingIdentity"
@positive-click="verifyIdentity"
>
<p class="identity-hint">{{ t('pages.settings.tianheManualHint') }}</p>
<n-form-item label="User ID">
<n-input v-model:value="manualEntry.userId" :placeholder="t('pages.settings.tianheManualUserIdPh')" />
</n-form-item>
<n-form-item label="User Key">
<n-input v-model:value="manualEntry.userKey" type="password" show-password-on="click" :placeholder="t('pages.settings.tianheManualUserKeyPh')" />
</n-form-item>
</n-modal>
<section class="settings-card storage-card">
<n-tab-pane name="storage" :tab="t('pages.settings.tabStorage')">
<div class="tab-body">
<div class="tab-stack stack-narrow">
<section class="settings-card">
<div class="card-title">
<span class="card-title-text">
{{ t('pages.settings.storageSettings') }}
@@ -194,18 +238,18 @@
</div>
<div class="setting-row">
<n-form-item :label="t('pages.settings.storageLocalDir')">
<n-input v-model:value="form.storageLocalDir" class="url-control" />
<n-input v-model:value="form.storageLocalDir" class="text-control" />
</n-form-item>
</div>
<div class="setting-row">
<n-form-item :label="t('pages.settings.cdnBaseUrl')">
<n-input v-model:value="form.cdnBaseUrl" class="url-control" />
<n-input v-model:value="form.cdnBaseUrl" class="text-control" />
</n-form-item>
</div>
<template v-if="form.storageDriver === 'oss'">
<div class="setting-row">
<n-form-item :label="t('pages.settings.ossEndpoint')">
<n-input v-model:value="form.ossEndpoint" class="url-control" />
<n-input v-model:value="form.ossEndpoint" class="text-control" />
</n-form-item>
</div>
<div class="setting-row">
@@ -231,27 +275,46 @@
</template>
</section>
</div>
</n-form>
<div class="settings-backup-panel">
<backup-restore-panel />
</div>
</div>
</div>
</n-tab-pane>
</n-tabs>
<n-modal
v-model:show="manualEntryVisible"
preset="dialog"
:title="t('pages.settings.tianheManualEntry')"
:positive-text="t('pages.settings.tianheVerifySave')"
:negative-text="t('common.action.cancel')"
:loading="verifyingIdentity"
@positive-click="verifyIdentity"
>
<p class="identity-hint">{{ t('pages.settings.tianheManualHint') }}</p>
<n-form-item label="User ID">
<n-input v-model:value="manualEntry.userId" :placeholder="t('pages.settings.tianheManualUserIdPh')" />
</n-form-item>
<n-form-item label="User Key">
<n-input v-model:value="manualEntry.userKey" type="password" show-password-on="click" :placeholder="t('pages.settings.tianheManualUserKeyPh')" />
</n-form-item>
</n-modal>
</div>
</template>
<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRoute, useRouter } from 'vue-router';
import { settingsApi, storageApi } from '@/api';
import { dialog, message } from '@/utils/feedback';
import { HelpCircleOutline } from '@vicons/ionicons5';
import { CopyOutline, EyeOffOutline, EyeOutline, HelpCircleOutline } from '@vicons/ionicons5';
import BackupRestorePanel from '@/components/BackupRestorePanel.vue';
import MediaUpload from '@/components/MediaUpload.vue';
import { DEFAULT_APP_ICON_URL, resolveAppIcon, setFavicon } from '@/utils/appIcon';
const { t } = useI18n();
const route = useRoute();
const router = useRouter();
const TAB_NAMES = ['platform', 'logsBackup', 'blockchain', 'storage'];
const activeTab = ref(TAB_NAMES.includes(String(route.query.tab)) ? String(route.query.tab) : 'platform');
const saving = ref(false);
const testingStorage = ref(false);
const migratingStorage = ref(false);
@@ -260,9 +323,12 @@ const registeringIdentity = ref(false);
const verifyingIdentity = ref(false);
const rotatingIdentity = ref(false);
const revealKey = ref(false);
const appKeyRevealed = ref(false);
const manualEntryVisible = ref(false);
const identity = reactive({ userId: '', userKey: '', userKeyMasked: '', address: '' });
const manualEntry = reactive({ userId: '', userKey: '' });
// load() 时记录的 AppKey 掩码值,用于区分「服务端掩码」与「用户新填的值」
let loadedTianheAppKey = '';
const TIANHE_TEST_URL = 'https://test.api.tichain.tianhecloud.com';
const TIANHE_PRODUCTION_URL = 'https://api.tichain.tianhecloud.com';
const blockchainDriverOptions = computed(() => [
@@ -319,6 +385,11 @@ const form = reactive({
ossAccessKeySecret: '',
});
function onTabChange(name: string) {
activeTab.value = name;
void router.replace({ query: { ...route.query, tab: name } });
}
async function load() {
const s = await settingsApi.getAll();
form.appName = s.appName || '';
@@ -339,6 +410,8 @@ async function load() {
form.tianheBaseUrl = s.tianheBaseUrl || TIANHE_TEST_URL;
form.tianheAppId = s.tianheAppId || '';
form.tianheAppKey = s.tianheAppKey || '';
loadedTianheAppKey = form.tianheAppKey;
appKeyRevealed.value = false;
form.storageDriver = s.storageDriver || 'local';
form.storageLocalDir = s.storageLocalDir || './storage';
form.storagePublicPrefix = s.storagePublicPrefix || '/uploads';
@@ -368,6 +441,29 @@ async function loadIdentity() {
}
}
// 查看 AppKey:二次确认后经审计 POST 接口获取掩码(服务端只回掩码,永不回明文)
function toggleAppKeyReveal() {
if (appKeyRevealed.value) {
appKeyRevealed.value = false;
return;
}
dialog.warning({
title: t('pages.settings.tianheAppKeyRevealTitle'),
content: t('pages.settings.tianheAppKeyRevealContent'),
positiveText: t('common.action.confirm'),
negativeText: t('common.action.cancel'),
onPositiveClick: async () => {
const res = await settingsApi.tianheRevealAppKey();
// 仅在输入框仍是服务端掩码(未被编辑)时刷新掩码,避免覆盖用户新填的值
if (form.tianheAppKey === loadedTianheAppKey && res.appKeyMasked) {
form.tianheAppKey = res.appKeyMasked;
loadedTianheAppKey = res.appKeyMasked;
}
appKeyRevealed.value = true;
},
});
}
// 揭示明文 userKey:二次确认后经 POST 接口获取(写操作日志、避免缓存)
async function revealUserKey() {
if (revealKey.value) {
@@ -387,15 +483,21 @@ async function revealUserKey() {
});
}
async function copyUserKey() {
let key = identity.userKey;
if (!key) {
const res = await settingsApi.tianheReveal();
key = res.userKey || '';
identity.userKey = key;
}
await navigator.clipboard.writeText(key);
message.success(t('pages.settings.tianheCopied'));
// 复制 userKey:二次确认后强制经审计 POST 接口取明文再写剪贴板,保证留痕
function copyUserKey() {
dialog.warning({
title: t('pages.settings.tianheCopyConfirmTitle'),
content: t('pages.settings.tianheCopyConfirmContent'),
positiveText: t('common.action.confirm'),
negativeText: t('common.action.cancel'),
onPositiveClick: async () => {
const res = await settingsApi.tianheReveal();
const key = res.userKey || '';
identity.userKey = key;
await navigator.clipboard.writeText(key);
message.success(t('pages.settings.tianheCopied'));
},
});
}
// 注册(或确认)平台托管钱包;注册前先保存表单里的 AppID/AppKey,避免「填了没存」
@@ -472,7 +574,7 @@ async function save() {
saving.value = true;
try {
const appIconUrl = form.appIconFiles[0]?.url || form.appIconFiles[0]?.key || '';
await settingsApi.update({
const s = await settingsApi.update({
appName: form.appName,
appIconUrl,
logRetentionDays: String(form.logRetentionDays),
@@ -491,6 +593,10 @@ async function save() {
tianheAppId: form.tianheAppId,
tianheAppKey: form.tianheAppKey,
});
// 保存后回填服务端掩码,避免输入框继续持有刚填的明文
form.tianheAppKey = (s as Record<string, string>)?.tianheAppKey || '';
loadedTianheAppKey = form.tianheAppKey;
appKeyRevealed.value = false;
setFavicon(appIconUrl);
window.dispatchEvent(new CustomEvent('artveris-settings-updated'));
message.success(t('pages.settings.saved'));
@@ -561,54 +667,55 @@ const identityKeyDisplay = computed(() => {
display: flex;
flex-direction: column;
overflow: hidden;
padding: 14px 16px 16px;
padding: 8px 24px 0;
}
.settings-shell {
width: 100%;
height: 100%;
min-width: 0;
.settings-tabs {
flex: 1 1 auto;
min-height: 0;
display: flex;
flex-direction: column;
}
.settings-save {
position: absolute;
top: 0;
right: 0;
z-index: 8;
}
.settings-content {
display: flex;
flex-direction: column;
height: 100%;
min-height: 0;
gap: 12px;
overflow: auto;
padding: 0 10px 24px 0;
}
.settings-form {
position: relative;
.settings-tabs :deep(.n-tabs-nav) {
flex: 0 0 auto;
width: 1300px;
max-width: 100%;
}
.settings-card-grid {
.settings-tabs :deep(.n-tabs-nav-scroll-content) {
justify-content: center;
}
.settings-tabs :deep(.n-tabs-pane-wrapper) {
flex: 1 1 auto;
min-height: 0;
}
.settings-tabs :deep(.n-tab-pane) {
height: 100%;
overflow: auto;
padding: 16px 0 24px;
box-sizing: border-box;
}
.tab-body {
min-height: 100%;
display: flex;
}
.tab-stack {
margin: auto;
display: flex;
flex-direction: column;
gap: 14px;
width: 100%;
}
.stack-narrow {
max-width: 560px;
}
.stack-mid {
max-width: 640px;
}
.stack-wide {
max-width: 1080px;
}
.stack-row {
display: grid;
grid-template-columns: 448px 376px 376px;
grid-template-columns: 1fr 1fr;
gap: 14px;
align-items: start;
gap: 12px;
padding-right: 76px;
}
.settings-side-stack {
display: grid;
gap: 12px;
width: 376px;
}
.platform-card {
width: 448px;
}
.blockchain-card {
width: 376px;
}
.settings-card {
overflow: hidden;
@@ -620,8 +727,8 @@ const identityKeyDisplay = computed(() => {
.card-title {
display: flex;
align-items: center;
min-height: 36px;
padding: 0 12px;
min-height: 38px;
padding: 4px 14px;
border-bottom: 1px solid var(--n-border-color);
background: rgba(148, 163, 184, 0.08);
color: var(--n-text-color);
@@ -655,19 +762,81 @@ const identityKeyDisplay = computed(() => {
font-size: 12px;
line-height: 1.7;
}
.setting-row {
padding: 9px 14px;
border-bottom: 1px solid var(--n-border-color);
}
.setting-row:last-child {
border-bottom: 0;
}
.settings-card :deep(.n-form-item) {
display: grid;
grid-template-columns: 150px minmax(0, 1fr);
align-items: center;
column-gap: 16px;
margin-bottom: 0;
}
.settings-card :deep(.n-form-item-label) {
min-height: auto;
padding: 0;
color: var(--n-text-color-2);
font-weight: 600;
line-height: 20px;
white-space: nowrap;
}
.settings-card :deep(.n-form-item-blank) {
min-height: 32px;
}
.setting-row :deep(.n-form-item-feedback-wrapper) {
display: none;
}
.text-control {
width: 100%;
}
.number-control {
width: 200px;
}
.number-control :deep(.n-input__input-el) {
text-align: center;
}
.select-control {
width: 200px;
}
.secret-field {
display: flex;
align-items: center;
gap: 6px;
width: 100%;
}
.secret-input {
flex: 1 1 auto;
min-width: 0;
}
.identity-head {
display: flex;
align-items: center;
justify-content: space-between;
flex-wrap: wrap;
gap: 8px;
padding: 9px 14px;
border-bottom: 1px solid var(--n-border-color);
background: rgba(148, 163, 184, 0.06);
}
.identity-title {
font-size: 13px;
font-weight: 600;
font-weight: 700;
color: var(--n-text-color-2, #526070);
white-space: nowrap;
}
.identity-actions {
display: flex;
gap: 6px;
flex-wrap: wrap;
justify-content: flex-end;
}
.identity-value {
font-size: 12px;
line-height: 20px;
word-break: break-all;
}
.identity-value.mono {
@@ -676,66 +845,15 @@ const identityKeyDisplay = computed(() => {
.identity-key {
display: flex;
align-items: center;
gap: 6px;
gap: 4px;
flex-wrap: wrap;
}
.identity-hint {
margin: 4px 12px 10px;
margin: 8px 14px 12px;
font-size: 12px;
line-height: 1.6;
color: #d03050;
}
.setting-row {
padding: 8px 12px;
border-bottom: 1px solid var(--n-border-color);
}
.setting-row:last-child {
border-bottom: 0;
}
.settings-form :deep(.n-form-item) {
display: grid;
grid-template-columns: 128px max-content;
grid-template-rows: auto;
grid-template-areas: "label blank";
align-items: center;
column-gap: 12px;
margin-bottom: 0;
}
.platform-card :deep(.n-form-item) {
grid-template-columns: 148px max-content;
}
.settings-form :deep(.n-form-item-label) {
min-height: auto;
padding: 0;
color: var(--n-text-color-2);
font-weight: 600;
line-height: 20px;
white-space: nowrap;
}
.settings-form :deep(.n-form-item-blank) {
min-height: 32px;
}
.setting-row :deep(.n-form-item-feedback-wrapper) {
display: none;
}
.control-wide {
width: 100%;
}
.text-control {
width: 180px;
}
.url-control {
width: 220px;
}
.number-control {
width: 128px;
}
.number-control :deep(.n-input__input-el) {
text-align: center;
}
.select-control {
width: 128px;
}
.setting-label {
color: var(--n-text-color-2);
font-weight: 600;
@@ -745,12 +863,9 @@ const identityKeyDisplay = computed(() => {
}
.icon-row {
display: grid;
grid-template-columns: 128px max-content;
grid-template-columns: 150px minmax(0, 1fr);
align-items: center;
column-gap: 12px;
}
.platform-card .icon-row {
grid-template-columns: 148px max-content;
column-gap: 16px;
}
.icon-setting {
display: grid;
@@ -790,39 +905,24 @@ const identityKeyDisplay = computed(() => {
.icon-upload :deep(.image-item.add span) {
display: none;
}
.settings-backup-panel {
flex: 1 1 320px;
.backup-body {
height: 460px;
padding: 0 12px 12px;
display: flex;
flex-direction: column;
width: 100%;
min-height: 320px;
padding: 12px;
box-sizing: border-box;
border: 1px solid var(--n-border-color);
border-radius: 8px;
background: var(--n-card-color);
box-shadow: 0 1px 2px rgba(15, 23, 42, 0.04);
min-height: 0;
}
.settings-backup-panel :deep(.backup-panel) {
.backup-body :deep(.backup-panel) {
flex: 1 1 auto;
min-height: 0;
}
@media (max-width: 900px) {
.settings-shell {
min-width: 0;
}
.settings-card-grid {
grid-template-columns: 448px 376px 376px;
}
.settings-save {
right: 0;
}
.icon-setting {
grid-template-columns: 60px minmax(0, 1fr);
.stack-row {
grid-template-columns: 1fr;
}
}
@media (max-width: 640px) {
.settings-form :deep(.n-form-item),
.settings-card :deep(.n-form-item),
.icon-row {
grid-template-columns: 1fr;
row-gap: 8px;
@@ -0,0 +1,34 @@
import { currentPreviewToken, isValidPreviewToken, PREVIEW_PERIOD_MS } from './preview-token.util';
describe('preview-token.util', () => {
const secret = 'test-secret';
const now = 1_800_000_000_000;
it('当前窗口令牌有效', () => {
const token = currentPreviewToken(secret, now);
expect(isValidPreviewToken(secret, token, now)).toBe(true);
});
it('上一窗口令牌在宽限期内有效', () => {
const prevToken = currentPreviewToken(secret, now - PREVIEW_PERIOD_MS);
expect(prevToken).not.toBe(currentPreviewToken(secret, now));
expect(isValidPreviewToken(secret, prevToken, now)).toBe(true);
});
it('更早窗口令牌失效', () => {
const oldToken = currentPreviewToken(secret, now - 2 * PREVIEW_PERIOD_MS);
expect(isValidPreviewToken(secret, oldToken, now)).toBe(false);
});
it('空/畸形/错误密钥令牌失效', () => {
expect(isValidPreviewToken(secret, undefined, now)).toBe(false);
expect(isValidPreviewToken(secret, '', now)).toBe(false);
expect(isValidPreviewToken(secret, 'short', now)).toBe(false);
expect(isValidPreviewToken(secret, currentPreviewToken('other-secret', now), now)).toBe(false);
});
it('同窗口内令牌稳定,跨窗口轮换', () => {
expect(currentPreviewToken(secret, now)).toBe(currentPreviewToken(secret, now + PREVIEW_PERIOD_MS - 1));
expect(currentPreviewToken(secret, now)).not.toBe(currentPreviewToken(secret, now + PREVIEW_PERIOD_MS));
});
});
@@ -0,0 +1,28 @@
import { createHmac, timingSafeEqual } from 'crypto';
// 追溯码预览令牌:类 TOTP 的时间窗口 HMAC 令牌。
// 周期 10 分钟;校验时接受「当前窗口 + 上一窗口」,即令牌实际有效 10~20 分钟。
// 无状态(不落库/不进 Redis),密钥复用 JWT_SECRET,后台随取随用、自动随时间轮换,
// 防止预览地址被打印/转发后长期有效。
export const PREVIEW_PERIOD_MS = 600_000;
const TOKEN_HEX_LEN = 16;
function tokenForWindow(secret: string, window: number): string {
return createHmac('sha256', secret).update(`preview:${window}`).digest('hex').slice(0, TOKEN_HEX_LEN);
}
export function currentPreviewToken(secret: string, now = Date.now()): string {
return tokenForWindow(secret, Math.floor(now / PREVIEW_PERIOD_MS));
}
export function isValidPreviewToken(secret: string, token: string | undefined, now = Date.now()): boolean {
if (!token || token.length !== TOKEN_HEX_LEN) return false;
const window = Math.floor(now / PREVIEW_PERIOD_MS);
const provided = Buffer.from(token, 'utf8');
// 当前窗口 + 上一窗口(宽限期),常量时间比较防时序侧信道
for (const w of [window, window - 1]) {
const expected = Buffer.from(tokenForWindow(secret, w), 'utf8');
if (provided.length === expected.length && timingSafeEqual(provided, expected)) return true;
}
return false;
}
@@ -1,9 +1,11 @@
import { Controller, Get, Param, Req, Res } from '@nestjs/common';
import { Controller, Get, Param, Query, Req, Res } from '@nestjs/common';
import { Request, Response } from 'express';
import { ApiOperation, ApiTags } from '@nestjs/swagger';
import { Throttle } from '@nestjs/throttler';
import { ConfigService } from '@nestjs/config';
import { Public } from '../common/decorators/public.decorator';
import { extractIp } from '../common/utils/ua.util';
import { isValidPreviewToken } from '../common/utils/preview-token.util';
import { PublicTraceService } from './public-trace.service';
import { SettingsService } from '../settings/settings.service';
@@ -13,6 +15,7 @@ export class PublicTraceController {
constructor(
private readonly service: PublicTraceService,
private readonly settings: SettingsService,
private readonly config: ConfigService,
) {}
@Public()
@@ -26,6 +29,22 @@ export class PublicTraceController {
return this.service.trace(shortCode, { ip, userAgent });
}
// 后台预览:凭时间令牌访问,零副作用(不激活/不计数/不写日志)。令牌过期返回 PREVIEW_EXPIRED。
@Public()
@Get('public/trace/:shortCode/preview')
@Throttle({ default: { limit: 60, ttl: 60_000 } })
@ApiOperation({ summary: 'C 端溯源预览(令牌保护,不激活不计数)' })
preview(
@Param('shortCode') shortCode: string,
@Query('token') token?: string,
@Query('state') state?: string,
) {
if (!isValidPreviewToken(this.config.get<string>('jwt.secret') || '', token)) {
return { status: 'PREVIEW_EXPIRED' as const };
}
return this.service.preview(shortCode, state === 'active' ? 'active' : 'inactive');
}
// 短链跳转:扫码打开 /t/:shortCode -> 重定向到 C 端溯源页(不在 /api 前缀下)
@Public()
@Get('t/:shortCode')
@@ -8,6 +8,13 @@ import { REDIS_CLIENT } from '../redis/redis.module';
import { parseUserAgent } from '../common/utils/ua.util';
type TraceCodeWithRel = Prisma.TraceCodeGetPayload<{ include: { batch: true; artwork: true } }>;
type ArtworkWithRel = Prisma.ArtworkGetPayload<{
include: {
template: { include: { fields: true } };
traceNodes: true;
certificates: true;
};
}>;
export interface TraceContext {
ip: string;
@@ -186,6 +193,81 @@ export class PublicTraceService {
queryCount: updated.queryCount,
firstActivatedAt: updated.firstActivatedAt,
},
...this.buildArtworkPayload(artwork, code, proof),
};
}
// 后台预览:与 trace() 相同的数据组装,但零副作用——不激活、不计数、不写查询日志。
// state 决定防伪区块以「首次扫码」还是「重复访问」形态展示,antiCounterfeit 数值为演示占位/库中现值。
async preview(shortCode: string, state: 'inactive' | 'active') {
if (!TRACE_CODE_PATTERN.test(shortCode)) return { status: 'INVALID' as const };
const id = await this.resolveId(shortCode);
if (id === null) return { status: 'INVALID' as const };
const code = await this.prisma.traceCode.findUnique({
where: { id },
include: { batch: true, artwork: true },
});
if (!code) return { status: 'INVALID' as const };
if (code.status === TraceCodeStatus.DISABLED) return { status: 'DISABLED' as const };
if (code.status === TraceCodeStatus.ABNORMAL) return { status: 'ABNORMAL' as const };
const artwork = await this.prisma.artwork.findFirst({
where: { id: code.artworkId, deletedAt: null },
include: {
template: { include: { fields: { orderBy: { sortOrder: 'asc' } } } },
traceNodes: { orderBy: { sortOrder: 'asc' } },
certificates: { orderBy: { id: 'asc' } },
},
});
if (
!artwork ||
artwork.status === ArtworkStatus.DISABLED ||
artwork.auditStatus !== AuditStatus.APPROVED
) {
return { status: 'INVALID' as const };
}
const proof = await this.prisma.blockchainProof.findFirst({
where: { traceCodeId: id, status: ProofStatus.ONCHAIN },
orderBy: { id: 'desc' },
});
const now = new Date();
const firstQuery = state === 'inactive';
return {
status: 'OK' as const,
preview: true,
code: code.code,
queriedAt: now,
antiCounterfeit: firstQuery
? { firstQuery: true, queryCount: 1, firstActivatedAt: now }
: {
firstQuery: false,
queryCount: code.queryCount > 0 ? code.queryCount : 2,
firstActivatedAt: code.firstActivatedAt ?? now,
},
...this.buildArtworkPayload(artwork, code, proof),
};
}
// trace/preview 共用的作品展示数据(作品信息 / 时间线 / 证书 / 区块链存证)
private buildArtworkPayload(
artwork: ArtworkWithRel,
code: { outTime?: Date | null; outImages?: unknown },
proof: {
txHash: string | null;
dataHash: string;
blockHash: string | null;
blockHeight: bigint | null;
chainName: string | null;
onchainAt: Date | null;
explorerUrl: string | null;
tokenId: bigint | null;
contractAddress: string | null;
} | null,
) {
return {
artwork: {
title: artwork.title,
artist: artwork.artist,
@@ -62,6 +62,15 @@ export class SettingsController {
return { userId, address, userKeyMasked: this.settingsService.maskSecretPublic(userKey) };
}
@ApiBearerAuth()
@Roles(RoleType.SUPER_ADMIN)
@Post('tianhe/app-key/reveal')
@ApiOperation({ summary: '查看天河链 App Key 掩码(仅返回掩码,不返回明文);用 POST 以便写入操作日志' })
async revealTianheAppKey() {
const all = await this.settingsService.getAllRaw();
return { appKeyMasked: this.settingsService.maskSecretPublic(all.tianheAppKey || '') };
}
@ApiBearerAuth()
@Roles(RoleType.SUPER_ADMIN)
@Post('tianhe/identity/reveal')
@@ -11,9 +11,12 @@ import {
Res,
} from '@nestjs/common';
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
import { ConfigService } from '@nestjs/config';
import { Response } from 'express';
import { RoleType } from '@artveris/shared';
import { TraceCodeService } from './trace-code.service';
import { SettingsService } from '../settings/settings.service';
import { currentPreviewToken, PREVIEW_PERIOD_MS } from '../common/utils/preview-token.util';
import {
BatchDeleteDto,
BatchGroupDto,
@@ -34,7 +37,23 @@ import { parseBigId } from '../common/utils/bigint.util';
@ApiBearerAuth()
@Controller()
export class TraceCodeController {
constructor(private readonly service: TraceCodeService) {}
constructor(
private readonly service: TraceCodeService,
private readonly settings: SettingsService,
private readonly config: ConfigService,
) {}
// 预览令牌:类 TOTP,随时间自动轮换(当前+上一窗口有效)。后台点开预览页时随取随用,
// 预览地址外泄后最长 2 个周期即失效,无法长期传播。
@Get('trace-codes/preview-token')
@ApiOperation({ summary: '获取 C 端预览令牌(自动轮换)' })
async previewToken() {
return {
token: currentPreviewToken(this.config.get<string>('jwt.secret') || ''),
clientBase: await this.settings.getClientBaseUrl(),
periodMs: PREVIEW_PERIOD_MS,
};
}
@Post('trace-codes/batch')
@Roles(RoleType.OPERATOR)
+5
View File
@@ -24,6 +24,11 @@ export function fetchTrace(shortCode: string): Promise<any> {
return instance.get(`/public/trace/${shortCode}`) as unknown as Promise<any>;
}
// 后台预览:凭时间令牌访问,零副作用(不激活/不计数/不写日志);state 控制未激活/已激活形态
export function fetchTracePreview(shortCode: string, token: string, state: 'inactive' | 'active'): Promise<any> {
return instance.get(`/public/trace/${shortCode}/preview`, { params: { token, state } }) as unknown as Promise<any>;
}
export function fetchAppInfo(): Promise<any> {
return instance.get('/settings/public') as unknown as Promise<any>;
}
+9 -1
View File
@@ -57,7 +57,15 @@
"disabledTitle": "Code Disabled",
"disabledDesc": "This code has been disabled. Please verify carefully.",
"abnormalTitle": "Abnormal Status",
"abnormalDesc": "This code status is abnormal. Please verify carefully."
"abnormalDesc": "This code status is abnormal. Please verify carefully.",
"previewExpiredTitle": "Preview Link Expired",
"previewExpiredDesc": "Preview links are time-limited. Please reopen the preview from the admin console."
},
"preview": {
"title": "Preview Mode",
"note": "Internal preview only. No activation, no query counting.",
"inactive": "Inactive",
"active": "Activated"
},
"viewer": {
"zoomIn": "Zoom in",
+9 -1
View File
@@ -57,7 +57,15 @@
"disabledTitle": "防伪码已停用",
"disabledDesc": "该防伪码已停用,请谨慎核验。",
"abnormalTitle": "防伪码状态异常",
"abnormalDesc": "该防伪码状态异常,请谨慎核验。"
"abnormalDesc": "该防伪码状态异常,请谨慎核验。",
"previewExpiredTitle": "预览链接已过期",
"previewExpiredDesc": "预览地址具有时效性,请回到管理后台重新打开预览页面。"
},
"preview": {
"title": "预览模式",
"note": "仅供内部预览,不激活、不计入查询次数",
"inactive": "未激活",
"active": "已激活"
},
"viewer": {
"zoomIn": "放大",
+2
View File
@@ -5,6 +5,8 @@ export default createRouter({
routes: [
{ path: '/', component: () => import('@/views/Home.vue') },
{ path: '/trace/:code', component: () => import('@/views/Trace.vue') },
// 后台预览模式:复用 Trace.vue,凭 ?token= 时间令牌访问,不激活/不计数
{ path: '/trace/preview/:code', component: () => import('@/views/Trace.vue') },
{ path: '/:pathMatch(.*)*', redirect: '/' },
],
});
+90 -2
View File
@@ -43,6 +43,30 @@
</div>
</header>
<!-- 预览模式条:后台预览专用,可切换未激活/已激活展示形态 -->
<div v-if="isPreview" class="preview-bar">
<span class="preview-badge">{{ t('preview.title') }}</span>
<span class="preview-note">{{ t('preview.note') }}</span>
<div class="preview-toggle">
<button
type="button"
class="preview-toggle-btn"
:class="{ active: previewState === 'inactive' }"
@click="setPreviewState('inactive')"
>
{{ t('preview.inactive') }}
</button>
<button
type="button"
class="preview-toggle-btn"
:class="{ active: previewState === 'active' }"
@click="setPreviewState('active')"
>
{{ t('preview.active') }}
</button>
</div>
</div>
<!-- 加载 -->
<div v-if="loading" class="state">
<div class="spinner" />
@@ -392,7 +416,7 @@ import { computed, nextTick, onMounted, onUnmounted, ref, watch } from 'vue';
import { useRoute } from 'vue-router';
import { useI18n } from 'vue-i18n';
import dayjs from 'dayjs';
import { fetchTrace, fetchAppInfo } from '@/api';
import { fetchTrace, fetchTracePreview, fetchAppInfo } from '@/api';
import { setLocale, SUPPORTED_LOCALES } from '@/locales';
import { openMediaViewer } from '@/composables/openMediaViewer';
import { resolveAppIcon, setFavicon } from '@/utils/appIcon';
@@ -420,6 +444,17 @@ const antiModalOpen = ref(false);
const certIndex = ref(0);
const currentCert = computed(() => data.value?.certificates?.[certIndex.value] || null);
// 后台预览模式:/trace/preview/:code?token=xxx,零副作用(不激活/不计数),可切换未激活/已激活形态
const isPreview = computed(() => route.path.startsWith('/trace/preview/'));
const previewState = ref<'inactive' | 'active'>('inactive');
const previewExpired = computed(() => data.value?.status === 'PREVIEW_EXPIRED');
function setPreviewState(state: 'inactive' | 'active') {
if (previewState.value === state) return;
previewState.value = state;
const code = route.params.code;
if (code) load(String(code));
}
// 节点图片默认收缩,避免页面过长;点击展开
const expanded = ref<Set<number>>(new Set());
function toggleNode(i: number) {
@@ -432,6 +467,7 @@ const stateKey = computed(() => {
const s = data.value?.status;
if (s === 'DISABLED') return 'disabled';
if (s === 'ABNORMAL') return 'abnormal';
if (s === 'PREVIEW_EXPIRED') return 'previewExpired';
return 'invalid';
});
@@ -703,7 +739,9 @@ async function load(code: string) {
data.value = null;
expanded.value = new Set();
try {
data.value = await fetchTrace(code);
data.value = isPreview.value
? await fetchTracePreview(code, String(route.query.token || ''), previewState.value)
: await fetchTrace(code);
} catch {
data.value = { status: 'INVALID' };
} finally {
@@ -867,6 +905,56 @@ watch(
text-overflow: ellipsis;
white-space: nowrap;
}
.preview-bar {
position: sticky;
top: 48px;
z-index: 4;
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 8px;
padding: 8px 14px;
background: #fff7e6;
color: #ad6800;
border-bottom: 1px solid #ffe7ba;
font-size: 13px;
}
:root[data-theme='dark'] .preview-bar,
.dark .preview-bar {
background: rgba(173, 104, 0, 0.18);
color: #ffd591;
border-bottom-color: rgba(255, 213, 145, 0.25);
}
.preview-badge {
font-weight: 700;
flex-shrink: 0;
}
.preview-note {
flex: 1;
min-width: 120px;
opacity: 0.85;
}
.preview-toggle {
display: inline-flex;
border: 1px solid currentColor;
border-radius: 8px;
overflow: hidden;
flex-shrink: 0;
}
.preview-toggle-btn {
padding: 4px 12px;
border: none;
background: transparent;
color: inherit;
font-size: 13px;
cursor: pointer;
-webkit-tap-highlight-color: transparent;
}
.preview-toggle-btn.active {
background: #ad6800;
color: #fff;
font-weight: 600;
}
.state {
padding: 80px 32px;
text-align: center;