feat: 天河链 API 调用链路控制台日志(URL/方法/发送/返回,密钥脱敏)

- TianheProvider 三个传输方法统一打印请求与响应,appKey/userKey 脱敏
- OnchainProcessor 补确认查询开始/结果/失败日志,attest 成功带 txHash 与存证链接
This commit is contained in:
Nixevol
2026-07-10 10:13:11 +08:00
parent 6813d5bb34
commit 6e0db6eeb9
3 changed files with 46 additions and 4 deletions
+10 -2
View File
@@ -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);
+35 -2
View File
@@ -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<string, unknown>, action: string): Record<string,
return data && typeof data === 'object' ? (data as Record<string, unknown>) : {};
}
// 天河链 API 链路日志:打印 URL / 方法 / 发送数据 / 返回结果,appKey/userKey 脱敏
function redactSecrets(obj: Record<string, unknown>): Record<string, unknown> {
const masked: Record<string, unknown> = { ...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<string, unknown>, action: string): Promise<Record<string, unknown>> {
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;