From d0445c49ee1b213e4582db0c5b4b4f6c48e5177d Mon Sep 17 00:00:00 2001 From: Nixevol Date: Mon, 13 Jul 2026 00:44:29 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20AppKey=E6=8F=AD=E7=A4=BA=E6=94=B9?= =?UTF-8?q?=E4=B8=BA=E6=98=BE=E7=A4=BA=E5=AE=8C=E6=95=B4=E6=98=8E=E6=96=87?= =?UTF-8?q?=E5=B9=B6=E7=95=99=E5=AE=A1=E8=AE=A1;=E8=BF=BD=E6=BA=AF?= =?UTF-8?q?=E7=A0=81=E9=93=BE=E6=8E=A5=E6=94=B9=E4=B8=BA=E7=9B=B4=E8=BF=9E?= =?UTF-8?q?=E7=B3=BB=E7=BB=9F=E8=AE=BE=E7=BD=AE=E7=9A=84=E5=AE=A2=E6=88=B7?= =?UTF-8?q?=E7=AB=AF=E5=9C=B0=E5=9D=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- aidocs/project_context.md | 2 ++ apps/admin/src/api/index.ts | 2 +- apps/admin/src/locales/en-US.json | 2 +- apps/admin/src/locales/zh-CN.json | 2 +- apps/admin/src/views/Settings.vue | 19 +++++++---- apps/api/src/settings/settings.controller.ts | 4 +-- apps/api/src/trace-code/trace-code.service.ts | 33 ++++--------------- 7 files changed, 27 insertions(+), 37 deletions(-) diff --git a/aidocs/project_context.md b/aidocs/project_context.md index 726716e..4292e7e 100644 --- a/aidocs/project_context.md +++ b/aidocs/project_context.md @@ -252,6 +252,8 @@ - 天河链方案 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` 时隐藏,档案内为同一作品)。关联:追溯码列渲染为 `` 点击开 C 端溯源页;名称/档案编号渲染为 `.cell-link` 点击 `goArtwork(id)` → `router.push({name:'artwork-detail'})`。`status` 列标题改用 `pages.traceCode.activationStatus`(激活状态),`firstActivatedAt` 标签改为「激活时间」,新增 `openTrace` i18n。追溯码列 `fixed:'left'`、操作列 `fixed:'right'`。浏览器双页实测通过。 +- AppKey 揭示改为明文(2026-07-13):用户原话「APPKey点击眼睛后显示442******de7 而不是完整的key」实为**吐槽**(点眼睛只看到掩码、看不到完整 key),前两轮误读成"要求只显示掩码"。改正:`POST /settings/tianhe/app-key/reveal`(超管+操作日志)改回返回明文 `appKey`;前端确认框文案改为「将显示完整 App Key 并记入操作日志」,确认后输入框回填明文(type=text 完整可见),收起眼睛时若未编辑则恢复服务端掩码(明文不留输入框);`update()` 的 `isMaskedSecret` 跳过逻辑保证掩码值保存不会覆盖真实 key。教训:**用户描述现象时"显示X而不是Y"大概率是抱怨现状X、想要Y,拿不准先确认**。 +- 追溯码链接直连客户端地址(2026-07-13):用户设置了「客户端地址」但列表/二维码仍生成 `/t/` 短链(仅取 origin 拼 `/t/`,丢了路径且必须经后端跳转)。改为 `buildDynamicShortLink = ${clientBaseUrl}/#/trace/${shortCode}`(完整含路径,列表/详情/二维码/导出四处共用,动态生成换地址自动跟随);删除无人引用的 `buildTraceUrl/buildShortLink/shortLinkOrigin` 与 ConfigService 注入。`GET /t/:shortCode` 跳转端点保留,兼容历史已打印二维码。API 构建+32 单测通过。 - 系统设置页排版返工(2026-07-12,分支 `dev/tianhe-no-metadata-upload`):上一版分页布局被用户否掉(全竖排、控件不自适应、卡片标题与 tab 重复、区块链两卡没有真正左右排、AppKey 掩码被窄输入框截断)。重做要点:① 各 tab 去掉与 tab 同名的内层卡片标题,直接放 `n-form label-placement="left" :label-width="150" :show-feedback="false"`(标题左、控件右、`max-width:720px` 内自适应拉伸);② 备份 tab=顶部横排 inline 表单(定时备份/保留天数/数量)+ 分割线 + `BackupRestorePanel` flex 填满剩余高度(tab-pane 加 `pane-flex` 关外层滚动),表格自适应宽度;③ 区块链 tab=`chain-grid`(`grid-template-columns:repeat(auto-fit,minmax(430px,1fr))`)两卡真左右并排:左卡「接口配置」(新 i18n 键 `chainApiConfig`,避免与 tab 名重复)、右卡「链上身份」按钮在卡头右侧;④ AppKey 输入框拉宽后揭示的掩码 `442******de7` 完整可见(实测);⑤ 补 `watch(route.query.tab)` 支持浏览器前进/后退与手改地址栏同步切 tab。浏览器逐 tab 截图实测通过(URL 跟随、确认框、掩码、备份表格填充)。教训:**转包 UI 布局任务必须附截图级验收标准,否则容易做成"能编译但难看"**。 - 追溯码列表锚点样式与状态列点击(2026-07-12,分支 `dev/tianhe-no-metadata-upload`):① 修复名称/档案编号锚点样式不生效——表格单元格由 `n-data-table` 子组件渲染、不带本组件 scope 属性,`.cell-link` 须用 `:deep()` 才命中,改为 `:deep(.cell-link)`。② 出库状态、上链状态两列渲染包一层 `.cell-click`(cursor:pointer + hover 提亮),点击调 `openOutboundModal(row)` 进「出库上链」详情弹窗。③ 只读角色(`!auth.canWrite`)从状态列点开弹窗时隐藏保存/触发按钮(footer `v-if="!targetOnchain && auth.canWrite"`)。admin 构建通过。 - 出库/上链弹窗 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`)。浏览器实测通过。 diff --git a/apps/admin/src/api/index.ts b/apps/admin/src/api/index.ts index 0b530d1..30405c3 100644 --- a/apps/admin/src/api/index.ts +++ b/apps/admin/src/api/index.ts @@ -139,7 +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', {}), + tianheRevealAppKey: () => post<{ appKey: 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', {}), }; diff --git a/apps/admin/src/locales/en-US.json b/apps/admin/src/locales/en-US.json index 90faa13..f7904a7 100644 --- a/apps/admin/src/locales/en-US.json +++ b/apps/admin/src/locales/en-US.json @@ -589,7 +589,7 @@ "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.", + "tianheAppKeyRevealContent": "This will display the full App Key and be recorded in the operation log. Make sure your environment is secure before continuing.", "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}", diff --git a/apps/admin/src/locales/zh-CN.json b/apps/admin/src/locales/zh-CN.json index eef218c..bd3cd0f 100644 --- a/apps/admin/src/locales/zh-CN.json +++ b/apps/admin/src/locales/zh-CN.json @@ -589,7 +589,7 @@ "tianheCopyConfirmTitle": "复制 User Key", "tianheCopyConfirmContent": "复制会将完整 User Key 写入剪贴板,该操作将记入操作日志。请确认当前环境安全后再继续。", "tianheAppKeyRevealTitle": "查看 App Key", - "tianheAppKeyRevealContent": "该操作将记入操作日志,请确认当前环境安全后再继续。查看仅显示掩码形式,不会显示完整 App Key。", + "tianheAppKeyRevealContent": "该操作将显示完整 App Key 并记入操作日志,请确认当前环境安全后再继续。", "tianheIdentityHint": "User Key 是打开平台托管钱包的唯一凭据,天河链不留存、无法找回。请务必离线保存 User ID 与 User Key;重装或迁移系统后可通过「手动录入」继续使用同一链上身份。", "tianheRegisterDone": "链上身份注册成功", "tianheSaveKeyWarning": "请立即离线保存以下凭据(丢失将无法继续以同一身份存证):User ID:{userId};User Key:{userKey}", diff --git a/apps/admin/src/views/Settings.vue b/apps/admin/src/views/Settings.vue index 34798cb..f0dce2e 100644 --- a/apps/admin/src/views/Settings.vue +++ b/apps/admin/src/views/Settings.vue @@ -396,9 +396,14 @@ async function loadIdentity() { } } -// 查看 AppKey:二次确认后经审计 POST 接口获取掩码(服务端只回掩码,永不回明文) +// 揭示 AppKey 明文:二次确认后经审计 POST 接口获取(写操作日志)。 +// 收起时若用户未编辑过,恢复为服务端掩码,避免明文长期留在输入框。 +let revealedPlainAppKey = ''; function toggleAppKeyReveal() { if (appKeyRevealed.value) { + if (form.tianheAppKey === revealedPlainAppKey) { + form.tianheAppKey = loadedTianheAppKey; + } appKeyRevealed.value = false; return; } @@ -408,11 +413,13 @@ function toggleAppKeyReveal() { 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; + // 仅在输入框仍是服务端掩码(未被编辑)时回填明文,避免覆盖用户新填的值 + if (form.tianheAppKey === loadedTianheAppKey) { + const res = await settingsApi.tianheRevealAppKey(); + if (res.appKey) { + revealedPlainAppKey = res.appKey; + form.tianheAppKey = res.appKey; + } } appKeyRevealed.value = true; }, diff --git a/apps/api/src/settings/settings.controller.ts b/apps/api/src/settings/settings.controller.ts index 35f622e..ef1d29f 100644 --- a/apps/api/src/settings/settings.controller.ts +++ b/apps/api/src/settings/settings.controller.ts @@ -65,10 +65,10 @@ export class SettingsController { @ApiBearerAuth() @Roles(RoleType.SUPER_ADMIN) @Post('tianhe/app-key/reveal') - @ApiOperation({ summary: '查看天河链 App Key 掩码(仅返回掩码,不返回明文);用 POST 以便写入操作日志' }) + @ApiOperation({ summary: '揭示天河链 App Key 明文;用 POST 以便写入操作日志(仅超管)' }) async revealTianheAppKey() { const all = await this.settingsService.getAllRaw(); - return { appKeyMasked: this.settingsService.maskSecretPublic(all.tianheAppKey || '') }; + return { appKey: all.tianheAppKey || '' }; } @ApiBearerAuth() diff --git a/apps/api/src/trace-code/trace-code.service.ts b/apps/api/src/trace-code/trace-code.service.ts index 9a840ba..186623f 100644 --- a/apps/api/src/trace-code/trace-code.service.ts +++ b/apps/api/src/trace-code/trace-code.service.ts @@ -1,6 +1,5 @@ import { Injectable } from '@nestjs/common'; import { InjectQueue } from '@nestjs/bullmq'; -import { ConfigService } from '@nestjs/config'; import { Queue } from 'bullmq'; import { Prisma } from '@prisma/client'; import { Response } from 'express'; @@ -35,34 +34,16 @@ export class TraceCodeService { constructor( private readonly prisma: PrismaService, private readonly jobs: JobsService, - private readonly config: ConfigService, private readonly storage: StorageService, private readonly settings: SettingsService, @InjectQueue(QUEUE_NAMES.GEN_CODE) private readonly genQueue: Queue, ) {} - buildTraceUrl(shortCode: string): string { - const clientBase = (this.config.get('clientOrigin') || this.config.get('baseUrl') || 'http://localhost:3000/trace').replace(/\/$/, ''); - return `${clientBase}/#/trace/${encodeURIComponent(shortCode)}`; - } - - buildShortLink(shortCode: string): string { - const base = (this.config.get('baseUrl') || 'http://localhost:3000').replace(/\/$/, ''); - return `${base}/t/${encodeURIComponent(shortCode)}`; - } - - // 短链 origin 以系统设置 clientBaseUrl 为准(换域名后所有链接自动跟随),失败回退 env baseUrl - private async shortLinkOrigin(): Promise { - try { - const clientBaseUrl = await this.settings.getClientBaseUrl(); - return new URL(clientBaseUrl).origin; - } catch { - return (this.config.get('baseUrl') || 'http://localhost:3000').replace(/\/$/, ''); - } - } - + // 追溯码链接完全以系统设置「客户端地址」为准(含路径),列表/二维码/导出动态生成、换地址自动跟随。 + // 不再经 /t 短链中转(/t 跳转接口保留,兼容历史已打印二维码)。 async buildDynamicShortLink(shortCode: string): Promise { - return `${await this.shortLinkOrigin()}/t/${encodeURIComponent(shortCode)}`; + const clientBase = await this.settings.getClientBaseUrl(); + return `${clientBase}/#/trace/${encodeURIComponent(shortCode)}`; } private mapOutImages(code: { outImages?: unknown }) { @@ -464,8 +445,8 @@ export class TraceCodeService { }), this.prisma.traceCode.count({ where }), ]); - // 短链统一动态生成(DB 不固化 url,换域名后列表/导出/二维码自动跟随);origin 每页只计算一次 - const origin = await this.shortLinkOrigin(); + // 链接统一动态生成(DB 不固化 url,换客户端地址后列表/导出/二维码自动跟随);base 每页只取一次 + const clientBase = await this.settings.getClientBaseUrl(); return buildPage( list.map((code) => { const { proofs, ...rest } = code; @@ -473,7 +454,7 @@ export class TraceCodeService { const outImages = this.mapOutImages(code); return { ...rest, - url: `${origin}/t/${encodeURIComponent(code.shortCode)}`, + url: `${clientBase}/#/trace/${encodeURIComponent(code.shortCode)}`, outImageUrl: outImages[0]?.url ?? null, outImages, latestProof: latestOnchainProof,