fix: 天河链测试环境联调修正(手工 multipart + GET body)与 seed 短码格式
- upload 改手工构造 multipart(userDto 无 filename 带 application/json),修复 undici Blob 强加 filename 导致的 500 - confirm 接口 9 改用 node:https 发送带 body 的 GET,appKey 移出 URL query 避免泄漏 - seed 追溯码短码改为 12 位纯数字,与 TRACE_CODE_PATTERN 一致,修复 C 端公开溯源判 INVALID - 单测适配:https 模块 mock、手工 multipart 断言,27 测试全过 - 问题清单更新 T1-T8 联调结论,新增 F1(已修)/F2(待查)
This commit is contained in:
@@ -1,3 +1,6 @@
|
||||
import { randomBytes } from 'crypto';
|
||||
import { request as httpRequest } from 'node:http';
|
||||
import { request as httpsRequest } from 'node:https';
|
||||
import { AttestPayload, AttestResult, AttestationProvider, ConfirmTransactionResult } from './blockchain.types';
|
||||
|
||||
export interface TianheOptions {
|
||||
@@ -84,6 +87,68 @@ export class TianheProvider implements AttestationProvider {
|
||||
return parseJson(text);
|
||||
}
|
||||
|
||||
// 天河链 upload 要求 userDto 分段「无 filename + Content-Type: application/json」(等价 curl 的 ;type=application/json)。
|
||||
// whatwg FormData/undici 会给 Blob 分段强制加 filename,被服务端判为文件导致 500,故手工构造 multipart。
|
||||
private async postMultipart(
|
||||
path: string,
|
||||
userDtoJson: string,
|
||||
file: { field: string; filename: string; contentType: string; content: Buffer },
|
||||
action: string,
|
||||
): Promise<Record<string, unknown>> {
|
||||
const boundary = `----artveris${randomBytes(12).toString('hex')}`;
|
||||
const head = Buffer.from(
|
||||
`--${boundary}\r\n` +
|
||||
'Content-Disposition: form-data; name="userDto"\r\n' +
|
||||
'Content-Type: application/json\r\n\r\n' +
|
||||
`${userDtoJson}\r\n` +
|
||||
`--${boundary}\r\n` +
|
||||
`Content-Disposition: form-data; name="${file.field}"; filename="${file.filename}"\r\n` +
|
||||
`Content-Type: ${file.contentType}\r\n\r\n`,
|
||||
'utf8',
|
||||
);
|
||||
const body = Buffer.concat([head, file.content, Buffer.from(`\r\n--${boundary}--\r\n`, 'utf8')]);
|
||||
const res = await fetch(`${this.baseUrl()}${path}`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': `multipart/form-data; boundary=${boundary}` },
|
||||
body,
|
||||
});
|
||||
const text = await res.text();
|
||||
if (!res.ok) throw new Error(`${action}请求失败:HTTP ${res.status} ${text.slice(0, 200)}`);
|
||||
return parseJson(text);
|
||||
}
|
||||
|
||||
// 接口 9 为 GET,但服务端要求「请求体传 JSON 参数」(GET query 会返回「Required request body is missing」)。
|
||||
// Node 原生 fetch 不允许 GET 带 body,故用底层 http(s) 模块发送带 body 的 GET。appKey 走 body、不进 URL,避免日志泄漏。
|
||||
private getWithBody(path: string, body: Record<string, unknown>, action: string): Promise<Record<string, unknown>> {
|
||||
const url = new URL(`${this.baseUrl()}${path}`);
|
||||
const payload = Buffer.from(JSON.stringify(body), 'utf8');
|
||||
const requestFn = url.protocol === 'https:' ? httpsRequest : httpRequest;
|
||||
return new Promise((resolve, reject) => {
|
||||
const req = requestFn(
|
||||
url,
|
||||
{
|
||||
method: 'GET',
|
||||
headers: { 'Content-Type': 'application/json', 'Content-Length': payload.length },
|
||||
},
|
||||
(res) => {
|
||||
let text = '';
|
||||
res.on('data', (chunk) => (text += chunk));
|
||||
res.on('end', () => {
|
||||
const status = res.statusCode || 0;
|
||||
if (status < 200 || status >= 300) {
|
||||
reject(new Error(`${action}请求失败:HTTP ${status} ${text.slice(0, 200)}`));
|
||||
return;
|
||||
}
|
||||
resolve(parseJson(text));
|
||||
});
|
||||
},
|
||||
);
|
||||
req.on('error', (e) => reject(new Error(`${action}请求失败:${e.message}`)));
|
||||
req.write(payload);
|
||||
req.end();
|
||||
});
|
||||
}
|
||||
|
||||
// 接口 1「用户链上身份注册」:注册托管钱包,返回链上地址。userKey 是钱包密码,天河链不留存。
|
||||
async registerUser(): Promise<{ address: string }> {
|
||||
const raw = await this.postJson('/api/v2/user', this.credentials(), '天河链链上身份注册');
|
||||
@@ -121,19 +186,17 @@ export class TianheProvider implements AttestationProvider {
|
||||
generatedAt: new Date().toISOString(),
|
||||
};
|
||||
|
||||
const form = new FormData();
|
||||
// userDto 分段必须带 application/json content-type(文档 curl 标注 ;type=application/json,否则 Media Type Error)
|
||||
form.append('userDto', new Blob([JSON.stringify(this.credentials())], { type: 'application/json' }));
|
||||
form.append(
|
||||
'file',
|
||||
new Blob([JSON.stringify(meta, null, 2)], { type: 'application/json' }),
|
||||
`artveris-proof-${payload.dataHash.replace(/^0x/, '').slice(0, 16)}.json`,
|
||||
const raw = await this.postMultipart(
|
||||
'/api/v2/nfr/upload',
|
||||
JSON.stringify(this.credentials()),
|
||||
{
|
||||
field: 'file',
|
||||
filename: `artveris-proof-${payload.dataHash.replace(/^0x/, '').slice(0, 16)}.json`,
|
||||
contentType: 'application/json',
|
||||
content: Buffer.from(JSON.stringify(meta, null, 2), 'utf8'),
|
||||
},
|
||||
'天河链存证',
|
||||
);
|
||||
|
||||
const res = await fetch(`${this.baseUrl()}/api/v2/nfr/upload`, { method: 'POST', body: form });
|
||||
const text = await res.text();
|
||||
if (!res.ok) throw new Error(`天河链存证请求失败:HTTP ${res.status} ${text.slice(0, 200)}`);
|
||||
const raw = parseJson(text);
|
||||
const data = assertOk(raw, '天河链存证');
|
||||
|
||||
// 严格要求返回交易哈希;缺失即视为失败(绝不能用本地 dataHash 冒充链上哈希造成「假上链」)
|
||||
@@ -165,17 +228,17 @@ export class TianheProvider implements AttestationProvider {
|
||||
}
|
||||
|
||||
// 接口 9「根据交易哈希查询」:确认交易是否已进块。
|
||||
// 文档标注 GET,curl 样例却用 body 传参;实现取 GET+query(fetch 不支持 GET body),联调已通过则维持现状。
|
||||
// 联调确认(2026-07-09 测试环境):接口为 GET 但参数须走「请求体 JSON」,query 方式返回「Required request body is missing」。
|
||||
async confirmTransaction(txHash: string): Promise<ConfirmTransactionResult> {
|
||||
const url = new URL(`${this.baseUrl()}/api/v2/nfr/transaction/status`);
|
||||
url.searchParams.set('appId', required(this.opts.appId, 'App ID'));
|
||||
url.searchParams.set('appKey', required(this.opts.appKey, 'App Key'));
|
||||
url.searchParams.set('transactionHash', required(txHash, 'Transaction Hash'));
|
||||
|
||||
const res = await fetch(url);
|
||||
const text = await res.text();
|
||||
if (!res.ok) throw new Error(`天河链交易确认请求失败:HTTP ${res.status} ${text.slice(0, 200)}`);
|
||||
const raw = parseJson(text);
|
||||
const raw = await this.getWithBody(
|
||||
'/api/v2/nfr/transaction/status',
|
||||
{
|
||||
appId: required(this.opts.appId, 'App ID'),
|
||||
appKey: required(this.opts.appKey, 'App Key'),
|
||||
transactionHash: required(txHash, 'Transaction Hash'),
|
||||
},
|
||||
'天河链交易确认',
|
||||
);
|
||||
const data = assertOk(raw, '天河链交易确认');
|
||||
|
||||
const status = pickString(data, ['status']);
|
||||
|
||||
Reference in New Issue
Block a user