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:
Nixevol
2026-07-09 19:34:02 +08:00
parent fa4215bd52
commit e037e460e2
4 changed files with 176 additions and 71 deletions
+10 -1
View File
@@ -12,6 +12,15 @@ const storageDir = resolve(process.env.STORAGE_LOCAL_DIR || './storage');
const ALPHABET = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
const shortId = customAlphabet(ALPHABET, 10);
const codeId = customAlphabet(ALPHABET, 18);
// 公开短码须为 12 位纯数字(与 TRACE_CODE_PATTERN=/^\d{12}$/ 一致),否则 C 端公开溯源会判 INVALID
const numericId = customAlphabet('0123456789', 12);
function uniqueShortCode(used: Set<string>): string {
let code = numericId();
while (used.has(code)) code = numericId();
used.add(code);
return code;
}
const usedShortCodes = new Set<string>();
const watermarkText = process.env.WATERMARK_TEXT || '仅供溯源核验使用';
const DEFAULT_TEMPLATE_FIELDS = [
{ fieldKey: 'craft', label: '工艺', type: 'TEXT', required: true, sortOrder: 0 },
@@ -208,7 +217,7 @@ async function ensureSampleData(): Promise<void> {
const artworkActive = artworkSeq < 2; // 前两款带激活码与查询记录
for (let k = 0; k < CODES_PER_ARTWORK; k++) {
const shortCode = shortId();
const shortCode = uniqueShortCode(usedShortCodes);
const isActive = artworkActive && k < 2; // 该款前两套已激活
const code = await prisma.traceCode.create({
data: {
+34 -11
View File
@@ -1,4 +1,28 @@
import { TianheProvider } from './tianhe.provider';
import { EventEmitter } from 'node:events';
// 模拟 node:https.request:接口 9 用带 body 的 GET,走 https 模块而非 fetch
const httpsRequestMock = jest.fn();
jest.mock('node:https', () => ({ request: (...args: unknown[]) => httpsRequestMock(...args) }));
function mockHttpsRequestOnce(responseJson: unknown, statusCode = 200) {
httpsRequestMock.mockImplementation((_url: unknown, _opts: unknown, cb: unknown) => {
const callback = (typeof _opts === 'function' ? _opts : cb) as (res: EventEmitter & { statusCode: number }) => void;
const req = new EventEmitter() as EventEmitter & { write: () => void; end: () => void };
req.write = () => undefined;
req.end = () => {
const res = new EventEmitter() as EventEmitter & { statusCode: number };
res.statusCode = statusCode;
callback(res);
res.emit('data', JSON.stringify(responseJson));
res.emit('end');
};
return req;
});
}
// 放在 jest.mock 之后导入,确保 provider 拿到被 mock 的 https
// eslint-disable-next-line @typescript-eslint/no-var-requires
const { TianheProvider } = require('./tianhe.provider') as typeof import('./tianhe.provider');
describe('TianheProvider', () => {
const provider = new TianheProvider({
@@ -43,7 +67,7 @@ describe('TianheProvider', () => {
expect(result.blockHeight).toBeNull();
});
it('upload 的 userDto 分段必须为 application/json 类型', async () => {
it('upload 手工 multipart:userDto 分段无 filename 且带 application/json', async () => {
const fetchMock = jest.spyOn(globalThis, 'fetch').mockResolvedValue({
ok: true,
text: async () =>
@@ -52,10 +76,12 @@ describe('TianheProvider', () => {
await provider.attest({ dataHash: '0xhash' });
const body = fetchMock.mock.calls[0][1]?.body as FormData;
const userDto = body.get('userDto');
expect(userDto).toBeInstanceOf(Blob);
expect((userDto as Blob).type).toBe('application/json');
const init = fetchMock.mock.calls[0][1]!;
expect(String((init.headers as Record<string, string>)['Content-Type'])).toContain('multipart/form-data; boundary=');
const body = (init.body as Buffer).toString('utf8');
// userDto 分段:无 filename、带 application/json
expect(body).toContain('Content-Disposition: form-data; name="userDto"\r\nContent-Type: application/json');
expect(body).not.toContain('name="userDto"; filename');
});
it('响应缺少 transactionHash 时抛错,不用本地 dataHash 冒充', async () => {
@@ -114,7 +140,7 @@ describe('TianheProvider', () => {
expect(String(fetchMock.mock.calls[1][0])).toContain('/api/v2/user');
});
it('按交易状态接口确认链上区块信息', async () => {
it('按交易状态接口确认链上区块信息(GET+body 走 https 模块)', async () => {
const response = {
code: 0,
message: 'success',
@@ -126,10 +152,7 @@ describe('TianheProvider', () => {
tokenId: -999,
},
};
jest.spyOn(globalThis, 'fetch').mockResolvedValue({
ok: true,
text: async () => JSON.stringify(response),
} as Response);
mockHttpsRequestOnce(response);
const result = await provider.confirmTransaction(response.data.transactionHash);
+85 -22
View File
@@ -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']);