From 6e0db6eeb922f934f15cf908ecf88b311056615e Mon Sep 17 00:00:00 2001 From: Nixevol Date: Fri, 10 Jul 2026 10:13:11 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=A4=A9=E6=B2=B3=E9=93=BE=20API=20?= =?UTF-8?q?=E8=B0=83=E7=94=A8=E9=93=BE=E8=B7=AF=E6=8E=A7=E5=88=B6=E5=8F=B0?= =?UTF-8?q?=E6=97=A5=E5=BF=97=EF=BC=88URL/=E6=96=B9=E6=B3=95/=E5=8F=91?= =?UTF-8?q?=E9=80=81/=E8=BF=94=E5=9B=9E=EF=BC=8C=E5=AF=86=E9=92=A5?= =?UTF-8?q?=E8=84=B1=E6=95=8F=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - TianheProvider 三个传输方法统一打印请求与响应,appKey/userKey 脱敏 - OnchainProcessor 补确认查询开始/结果/失败日志,attest 成功带 txHash 与存证链接 --- aidocs/project_context.md | 1 + apps/api/src/blockchain/onchain.processor.ts | 12 +++++-- apps/api/src/blockchain/tianhe.provider.ts | 37 ++++++++++++++++++-- 3 files changed, 46 insertions(+), 4 deletions(-) diff --git a/aidocs/project_context.md b/aidocs/project_context.md index 6e267c2..6a2d398 100644 --- a/aidocs/project_context.md +++ b/aidocs/project_context.md @@ -245,6 +245,7 @@ - 完善版分支 dev/qa-polish(2026-07-09,从 dev/qa-fix 分出):在保守版基础上实现「待完善清单」中收益明确的项。① P-2 admin bundle 拆分:`apps/admin/vite.config.ts` 加 `build.rollupOptions.output.manualChunks`(naive/echarts/vendor 独立 chunk),`index` chunk 从 ~1652KB 降到 ~69KB、Dashboard 从 474KB 降到 10KB,第三方库独立缓存。② P-3 揭示 userKey 加固:`GET /settings/tianhe/identity` 改为只回 `userKeyMasked`(不再 GET 明文);新增 `POST /settings/tianhe/identity/reveal` 回明文——POST 使其被操作日志记录、避免缓存;前端揭示前二次确认(`Settings.vue` `revealUserKey`),实测揭示动作已落操作日志。P-1(天河链 confirm status 偶发 500)、P-4(C 端骨架屏)判定为过度设计,保持现状。三分支:`dev/refine`(基线未动)、`dev/qa-fix`(保守版,严守红线)、`dev/qa-polish`(本分支,含 P-2/P-3 完善)。验证:4 包构建 + 27 单测通过。 +- 天河链 API 链路日志(2026-07-10,dev/qa-polish):`TianheProvider` 增加 `Logger('TianheAPI')`,三个传输方法(`postJson`/`postMultipart`/`getWithBody`)统一打印「→ 方法 URL 发送=payload」与「← 方法 URL HTTP 状态 返回=body(截断500)」;`appKey/userKey` 在日志中脱敏(`redactSecrets` 前3后3);multipart 的 file 分段只打元信息(filename/contentType/bytes)。`OnchainProcessor` 补充:确认查询开始/结果概要(confirmed/blockHash/blockHeight/status/响应)、确认失败 warn、attest 成功带 txHash+存证链接。用于开发期追踪与天河链的完整调用链路。 - dev 短链不可达修复(2026-07-10,dev/qa-polish):用户实测 `localhost:5173/t/xxx` 提示 "did you mean /admin/t/..."。根因:生产是 API 单端口托管全部路径(短链 `/t` 天然可用),但本地 5173 是 admin vite dev server、只代理了 `/api`/`/uploads`,`/t` 与 `/trace` 均未代理。修复:`apps/admin/vite.config.ts` dev proxy 增加 `'^/t/.*'`→3000(API 302 跳转)与 `'/trace'`→5174(C 端 dev server,含 ws),本地 5173 成为与生产一致的单入口。实测浏览器完整链路:5173 短链→302→5173/trace/#/trace/xxx→C 端溯源页正常渲染并弹首次激活。 - 追溯码列表链接缺失修复(2026-07-10,dev/qa-polish):用户反馈新生码「链接」列只剩图标无 URL。根因是「动态短链」重构不彻底——`gen-code.processor` 有意写 `url: null`(DB 不固化 url,换域名自动跟随),导出/二维码已改用 `buildDynamicShortLink` 动态生成,但**列表接口 `list()` 仍直接返回 DB 的 null url**(seed 码写了 url 所以有显示,向导生成的码没有)。修复:`trace-code.service.ts` 抽出 `shortLinkOrigin()`(settings.clientBaseUrl 优先、env baseUrl 兜底),`list()` 每页计算一次 origin 后为每行动态拼 `url`,`updateOne` 返回值同样补 url。契约固化:**短链一律动态生成,勿依赖 DB 的 url 列**(该列仅剩 keyword 搜索的历史用途)。验证:build+27 单测过,实测新旧码列表均返回完整链接。 diff --git a/apps/api/src/blockchain/onchain.processor.ts b/apps/api/src/blockchain/onchain.processor.ts index 9e54c13..416e19d 100644 --- a/apps/api/src/blockchain/onchain.processor.ts +++ b/apps/api/src/blockchain/onchain.processor.ts @@ -77,9 +77,9 @@ export class OnchainProcessor extends WorkerHost { }); if (result.confirmationRequired) { await this.scheduleConfirm(proofId, 1, FIRST_CONFIRM_DELAY_MS); - this.logger.log(`存证 ${proofId} 已提交链上,等待确认`); + this.logger.log(`存证 ${proofId} 已提交链上,等待确认:txHash=${result.txHash} 存证链接=${result.explorerUrl ?? '-'}`); } else { - this.logger.log(`存证 ${proofId} 上链成功`); + this.logger.log(`存证 ${proofId} 上链成功:txHash=${result.txHash} blockHeight=${result.blockHeight ?? '-'}`); } } catch (e) { const message = (e as Error).message; @@ -107,8 +107,14 @@ export class OnchainProcessor extends WorkerHost { return; } + this.logger.log(`存证 ${proofId} 开始链上确认查询(第 ${attempt} 次${manual ? ',手动' : ''}):txHash=${proof.txHash}`); try { const result = await this.blockchain.confirmTransaction(proof.txHash); + this.logger.log( + `存证 ${proofId} 链上查询结果:confirmed=${result.confirmed} blockHash=${result.blockHash ?? '-'} ` + + `blockHeight=${result.blockHeight ?? '-'} status=${(result.raw as { status?: string })?.status ?? '-'} ` + + `响应=${JSON.stringify((result.raw as { response?: unknown })?.response ?? result.raw).slice(0, 300)}`, + ); if (result.confirmed) { await this.prisma.blockchainProof.update({ where: { id: proofId }, @@ -141,8 +147,10 @@ export class OnchainProcessor extends WorkerHost { await this.scheduleConfirm(proofId, attempt + 1, SECOND_CONFIRM_DELAY_MS); } catch (e) { const message = (e as Error).message; + this.logger.warn(`存证 ${proofId} 链上确认查询失败(第 ${attempt} 次):${message}`); if (manual || attempt >= MAX_AUTO_CONFIRM_ATTEMPTS) { await this.recordWaiting(proofId, proof.rawResponse, { error: message }, attempt, manual); + this.logger.warn(`存证 ${proofId} 自动确认已达上限,等待手动重新确认`); return; } await this.recordWaiting(proofId, proof.rawResponse, { error: message }, attempt, manual); diff --git a/apps/api/src/blockchain/tianhe.provider.ts b/apps/api/src/blockchain/tianhe.provider.ts index 3ef9bba..6fb6d75 100644 --- a/apps/api/src/blockchain/tianhe.provider.ts +++ b/apps/api/src/blockchain/tianhe.provider.ts @@ -1,3 +1,4 @@ +import { Logger } from '@nestjs/common'; import { randomBytes } from 'crypto'; import { request as httpRequest } from 'node:http'; import { request as httpsRequest } from 'node:https'; @@ -58,11 +59,32 @@ function assertOk(raw: Record, action: string): Record) : {}; } +// 天河链 API 链路日志:打印 URL / 方法 / 发送数据 / 返回结果,appKey/userKey 脱敏 +function redactSecrets(obj: Record): Record { + const masked: Record = { ...obj }; + for (const key of ['appKey', 'userKey']) { + const v = masked[key]; + if (typeof v === 'string' && v) { + masked[key] = v.length > 8 ? `${v.slice(0, 3)}***${v.slice(-3)}` : '***'; + } + } + return masked; +} + export class TianheProvider implements AttestationProvider { readonly name = 'tianhe'; + private readonly logger = new Logger('TianheAPI'); constructor(private readonly opts: TianheOptions) {} + private logRequest(method: string, url: string, payload: unknown): void { + this.logger.log(`→ ${method} ${url} 发送=${JSON.stringify(payload)}`); + } + + private logResponse(method: string, url: string, status: number, text: string): void { + this.logger.log(`← ${method} ${url} HTTP ${status} 返回=${text.slice(0, 500)}`); + } + private baseUrl(): string { return required(this.opts.baseUrl, 'Base URL').replace(/\/+$/, ''); } @@ -77,12 +99,15 @@ export class TianheProvider implements AttestationProvider { } private async postJson(path: string, body: Record, action: string): Promise> { - const res = await fetch(`${this.baseUrl()}${path}`, { + const url = `${this.baseUrl()}${path}`; + this.logRequest('POST', url, redactSecrets(body)); + const res = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body), }); const text = await res.text(); + this.logResponse('POST', url, res.status, text); if (!res.ok) throw new Error(`${action}请求失败:HTTP ${res.status} ${text.slice(0, 200)}`); return parseJson(text); } @@ -107,12 +132,18 @@ export class TianheProvider implements AttestationProvider { 'utf8', ); const body = Buffer.concat([head, file.content, Buffer.from(`\r\n--${boundary}--\r\n`, 'utf8')]); - const res = await fetch(`${this.baseUrl()}${path}`, { + const url = `${this.baseUrl()}${path}`; + this.logRequest('POST(multipart)', url, { + userDto: redactSecrets(parseJson(userDtoJson)), + file: { field: file.field, filename: file.filename, contentType: file.contentType, bytes: file.content.length }, + }); + const res = await fetch(url, { method: 'POST', headers: { 'Content-Type': `multipart/form-data; boundary=${boundary}` }, body, }); const text = await res.text(); + this.logResponse('POST(multipart)', url, res.status, text); if (!res.ok) throw new Error(`${action}请求失败:HTTP ${res.status} ${text.slice(0, 200)}`); return parseJson(text); } @@ -123,6 +154,7 @@ export class TianheProvider implements AttestationProvider { const url = new URL(`${this.baseUrl()}${path}`); const payload = Buffer.from(JSON.stringify(body), 'utf8'); const requestFn = url.protocol === 'https:' ? httpsRequest : httpRequest; + this.logRequest('GET(body)', url.toString(), redactSecrets(body)); return new Promise((resolve, reject) => { const req = requestFn( url, @@ -135,6 +167,7 @@ export class TianheProvider implements AttestationProvider { res.on('data', (chunk) => (text += chunk)); res.on('end', () => { const status = res.statusCode || 0; + this.logResponse('GET(body)', url.toString(), status, text); if (status < 200 || status >= 300) { reject(new Error(`${action}请求失败:HTTP ${status} ${text.slice(0, 200)}`)); return;