fix: 天河链对接修复 T1-T3/T6-T8(托管钱包注册与身份生命周期)

- TianheProvider 新增 registerUser/userInfo/ensureRegistered(接口1/8),attest 前幂等确保钱包已注册
- userDto 分段改为 application/json 类型 Blob,避免 Media Type Error
- 严格校验 code===0 且必须返回 transactionHash,杜绝以本地 dataHash 冒充链上哈希的假上链
- upload 响应不再提取恒空的区块信息,注释固化"每物一条 proof、独立 txHash"不变量
- userKey 改为一次性随机生成并明文持久化(不再从 appKey 派生),明文存储保证备份跨重装可恢复
- 新增 /settings/tianhe/register|verify|identity 接口与设置页链上身份区(注册/显示地址/揭示复制/手动录入校验)
- 单测扩至 27 个:新增注册、严格校验、userDto 类型、ensureRegistered 回退用例
This commit is contained in:
Nixevol
2026-07-09 19:05:32 +08:00
parent 8a7032070a
commit fa4215bd52
9 changed files with 512 additions and 104 deletions
+4
View File
@@ -134,6 +134,10 @@ export const userApi = {
export const settingsApi = {
getAll: () => get<Record<string, string>>('/settings'),
update: (data: object) => put('/settings', data),
tianheRegister: () => post<{ userId: string; userKey: string; address: string }>('/settings/tianhe/register', {}),
tianheVerify: (data: { userId: string; userKey: string }) =>
post<{ userId: string; address: string }>('/settings/tianhe/verify', data),
tianheIdentity: () => get<{ userId: string; userKey: string; address: string }>('/settings/tianhe/identity'),
};
export const storageApi = {
+19 -1
View File
@@ -545,7 +545,25 @@
"tianheEnvCustom": "Custom",
"tianheBaseUrl": "API URL",
"tianheAppId": "App ID",
"tianheAppKey": "App Key"
"tianheAppKey": "App Key",
"tianheIdentity": "On-chain Identity (Platform Custodial Wallet)",
"tianheWalletAddress": "Wallet Address",
"tianheNotRegistered": "Not registered",
"tianheRegister": "Register Identity",
"tianheReRegister": "Re-verify Identity",
"tianheManualEntry": "Manual Entry",
"tianheReveal": "Reveal",
"tianheHide": "Hide",
"tianheCopy": "Copy",
"tianheCopied": "User Key copied",
"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}",
"tianheVerifySave": "Verify & Save",
"tianheVerifyOk": "Verified. On-chain identity saved",
"tianheManualHint": "Enter the saved User ID and User Key. The system verifies them with TiChain before saving (for reusing the existing wallet after reinstall/migration).",
"tianheManualUserIdPh": "e.g. artveris-platform",
"tianheManualUserKeyPh": "The User Key you saved offline"
},
"profile": {
"title": "Personal Info",
+19 -1
View File
@@ -545,7 +545,25 @@
"tianheEnvCustom": "自定义",
"tianheBaseUrl": "接口地址",
"tianheAppId": "App ID",
"tianheAppKey": "App Key"
"tianheAppKey": "App Key",
"tianheIdentity": "链上身份(平台托管钱包)",
"tianheWalletAddress": "钱包地址",
"tianheNotRegistered": "未注册",
"tianheRegister": "注册链上身份",
"tianheReRegister": "重新确认身份",
"tianheManualEntry": "手动录入",
"tianheReveal": "揭示",
"tianheHide": "隐藏",
"tianheCopy": "复制",
"tianheCopied": "User Key 已复制",
"tianheIdentityHint": "User Key 是打开平台托管钱包的唯一凭据,天河链不留存、无法找回。请务必离线保存 User ID 与 User Key;重装或迁移系统后可通过「手动录入」继续使用同一链上身份。",
"tianheRegisterDone": "链上身份注册成功",
"tianheSaveKeyWarning": "请立即离线保存以下凭据(丢失将无法继续以同一身份存证):User ID:{userId};User Key:{userKey}",
"tianheVerifySave": "校验并保存",
"tianheVerifyOk": "校验通过,链上身份已保存",
"tianheManualHint": "输入已保存的 User ID 与 User Key,系统将向天河链校验后保存(用于重装/迁移后复用既有钱包)。",
"tianheManualUserIdPh": "如 artveris-platform",
"tianheManualUserKeyPh": "已离线保存的 User Key"
},
"profile": {
"title": "个人信息",
+152 -2
View File
@@ -116,8 +116,59 @@
<n-input v-model:value="form.tianheAppKey" type="password" show-password-on="click" class="text-control" />
</n-form-item>
</div>
<template v-if="form.blockchainDriver === 'tianhe'">
<div class="setting-row identity-head">
<span class="identity-title">{{ t('pages.settings.tianheIdentity') }}</span>
<div class="card-actions">
<n-button size="small" :loading="registeringIdentity" @click="registerIdentity">
{{ identity.address ? t('pages.settings.tianheReRegister') : t('pages.settings.tianheRegister') }}
</n-button>
<n-button size="small" @click="manualEntryVisible = true">{{ t('pages.settings.tianheManualEntry') }}</n-button>
</div>
</div>
<div class="setting-row">
<n-form-item :label="t('pages.settings.tianheWalletAddress')">
<span class="identity-value mono">{{ identity.address || t('pages.settings.tianheNotRegistered') }}</span>
</n-form-item>
</div>
<div class="setting-row">
<n-form-item label="User ID">
<span class="identity-value mono">{{ identity.userId || '-' }}</span>
</n-form-item>
</div>
<div class="setting-row">
<n-form-item label="User Key">
<div class="identity-key">
<span class="identity-value mono">{{ identity.userKey ? (revealKey ? identity.userKey : maskKey(identity.userKey)) : '-' }}</span>
<n-button v-if="identity.userKey" size="tiny" quaternary @click="revealKey = !revealKey">
{{ revealKey ? t('pages.settings.tianheHide') : t('pages.settings.tianheReveal') }}
</n-button>
<n-button v-if="identity.userKey" size="tiny" quaternary @click="copyUserKey">{{ t('pages.settings.tianheCopy') }}</n-button>
</div>
</n-form-item>
</div>
<p class="identity-hint">{{ t('pages.settings.tianheIdentityHint') }}</p>
</template>
</section>
<n-modal
v-model:show="manualEntryVisible"
preset="dialog"
:title="t('pages.settings.tianheManualEntry')"
:positive-text="t('pages.settings.tianheVerifySave')"
:negative-text="t('common.action.cancel')"
:loading="verifyingIdentity"
@positive-click="verifyIdentity"
>
<p class="identity-hint">{{ t('pages.settings.tianheManualHint') }}</p>
<n-form-item label="User ID">
<n-input v-model:value="manualEntry.userId" :placeholder="t('pages.settings.tianheManualUserIdPh')" />
</n-form-item>
<n-form-item label="User Key">
<n-input v-model:value="manualEntry.userKey" type="password" show-password-on="click" :placeholder="t('pages.settings.tianheManualUserKeyPh')" />
</n-form-item>
</n-modal>
<section class="settings-card storage-card">
<div class="card-title">
<span class="card-title-text">
@@ -193,7 +244,7 @@
import { computed, onMounted, reactive, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { settingsApi, storageApi } from '@/api';
import { message } from '@/utils/feedback';
import { dialog, message } from '@/utils/feedback';
import { HelpCircleOutline } from '@vicons/ionicons5';
import BackupRestorePanel from '@/components/BackupRestorePanel.vue';
import MediaUpload from '@/components/MediaUpload.vue';
@@ -204,6 +255,12 @@ const saving = ref(false);
const testingStorage = ref(false);
const migratingStorage = ref(false);
const confirmingStorage = ref(false);
const registeringIdentity = ref(false);
const verifyingIdentity = ref(false);
const revealKey = ref(false);
const manualEntryVisible = ref(false);
const identity = reactive({ userId: '', userKey: '', address: '' });
const manualEntry = reactive({ userId: '', userKey: '' });
const TIANHE_TEST_URL = 'https://test.api.tichain.tianhecloud.com';
const TIANHE_PRODUCTION_URL = 'https://api.tichain.tianhecloud.com';
const blockchainDriverOptions = computed(() => [
@@ -296,6 +353,66 @@ function onTianheEnvChange(value: string) {
if (value === 'production') form.tianheBaseUrl = TIANHE_PRODUCTION_URL;
}
async function loadIdentity() {
try {
const res = await settingsApi.tianheIdentity();
identity.userId = res.userId || '';
identity.userKey = res.userKey || '';
identity.address = res.address || '';
} catch {
// 身份信息读取失败不阻塞设置页
}
}
function maskKey(value: string): string {
if (!value || value.length <= 8) return '******';
return `${value.slice(0, 4)}******${value.slice(-4)}`;
}
async function copyUserKey() {
await navigator.clipboard.writeText(identity.userKey);
message.success(t('pages.settings.tianheCopied'));
}
// 注册(或确认)平台托管钱包;注册前先保存表单里的 AppID/AppKey,避免「填了没存」
async function registerIdentity() {
registeringIdentity.value = true;
try {
await save();
const res = await settingsApi.tianheRegister();
identity.userId = res.userId;
identity.userKey = res.userKey;
identity.address = res.address;
revealKey.value = true;
dialog.warning({
title: t('pages.settings.tianheRegisterDone'),
content: t('pages.settings.tianheSaveKeyWarning', { userId: res.userId, userKey: res.userKey }),
positiveText: t('common.action.confirm'),
});
} finally {
registeringIdentity.value = false;
}
}
async function verifyIdentity() {
verifyingIdentity.value = true;
try {
const res = await settingsApi.tianheVerify({ userId: manualEntry.userId, userKey: manualEntry.userKey });
identity.userId = res.userId;
identity.userKey = manualEntry.userKey;
identity.address = res.address;
manualEntry.userId = '';
manualEntry.userKey = '';
manualEntryVisible.value = false;
message.success(t('pages.settings.tianheVerifyOk'));
return true;
} catch {
return false;
} finally {
verifyingIdentity.value = false;
}
}
async function save() {
saving.value = true;
try {
@@ -370,7 +487,10 @@ async function confirmStorage() {
}
}
onMounted(load);
onMounted(async () => {
await load();
await loadIdentity();
});
const currentIconUrl = computed(() => resolveAppIcon(form.appIconFiles[0]?.url || form.appIconFiles[0]?.key));
</script>
@@ -476,6 +596,36 @@ const currentIconUrl = computed(() => resolveAppIcon(form.appIconFiles[0]?.url |
font-size: 12px;
line-height: 1.7;
}
.identity-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
}
.identity-title {
font-size: 13px;
font-weight: 600;
color: var(--n-text-color-2, #526070);
}
.identity-value {
font-size: 12px;
word-break: break-all;
}
.identity-value.mono {
font-family: Consolas, Menlo, monospace;
}
.identity-key {
display: flex;
align-items: center;
gap: 6px;
flex-wrap: wrap;
}
.identity-hint {
margin: 4px 12px 10px;
font-size: 12px;
line-height: 1.6;
color: #d03050;
}
.setting-row {
padding: 8px 12px;
border-bottom: 1px solid var(--n-border-color);
+100 -18
View File
@@ -1,6 +1,8 @@
import { Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { createHash } from 'crypto';
import { createHash, randomBytes } from 'crypto';
import { ErrorCode } from '@artveris/shared';
import { BusinessException } from '../common/exceptions/business.exception';
import { SettingsService } from '../settings/settings.service';
import { AttestPayload, AttestResult, AttestationProvider, ConfirmTransactionResult } from './blockchain.types';
import { MockProvider } from './mock.provider';
@@ -8,6 +10,8 @@ import { TianheProvider } from './tianhe.provider';
const TIANHE_TEST_URL = 'https://test.api.tichain.tianhecloud.com';
const TIANHE_PRODUCTION_URL = 'https://api.tichain.tianhecloud.com';
// 单平台钱包:全平台共用一个托管钱包(公证者身份)。每件实物的存证仍各自独立
// (每物一条 proof、独立 txHash/digest),钱包只标识「谁提交的存证」,不标识物品。
const DEFAULT_TIANHE_USER_ID = 'artveris-platform';
// 递归按 key 排序的稳定序列化,用于内容哈希(与 JSON.stringify 不同,属性顺序不影响结果)
@@ -36,6 +40,9 @@ export class BlockchainService {
async attest(payload: AttestPayload): Promise<AttestResult> {
const provider = await this.buildProvider();
this.logger.log(`区块链存证驱动:${provider.name}`);
if (provider instanceof TianheProvider) {
await this.ensureTianheWallet(provider);
}
return provider.attest(payload);
}
@@ -47,37 +54,112 @@ export class BlockchainService {
return provider.confirmTransaction(txHash);
}
// ===== 天河链链上身份(userId/userKey/钱包地址)生命周期 =====
// 注册(或确认)平台托管钱包:userKey 缺失时一次性随机生成并明文持久化(不从 appKey 派生),
// 成功后保存钱包地址。返回明文 userId/userKey 供管理员离线保存(天河链不留存 userKey)。
async registerTianheIdentity(): Promise<{ userId: string; userKey: string; address: string }> {
const settings = await this.settings.getAllRaw();
if (!settings.tianheAppId || !settings.tianheAppKey) {
throw new BusinessException(ErrorCode.BAD_REQUEST, '请先填写并保存天河链 App ID / App Key');
}
const userId = (settings.tianheUserId || '').trim() || DEFAULT_TIANHE_USER_ID;
let userKey = (settings.tianheUserKey || '').trim();
if (!userKey) {
userKey = randomBytes(32).toString('hex');
}
const provider = this.buildTianheProvider(settings, userId, userKey);
let address: string;
try {
address = (await provider.ensureRegistered()).address;
} catch (e) {
throw new BusinessException(ErrorCode.BAD_REQUEST, (e as Error).message);
}
await this.settings.setRaw('tianheUserId', userId);
await this.settings.setRaw('tianheUserKey', userKey);
await this.settings.setRaw('tianheWalletAddress', address);
return { userId, userKey, address };
}
// 手动重录(重装/迁移复用既有钱包):经接口 8 校验 userId/userKey 能解析出钱包地址后才落库。
async verifyTianheIdentity(userId: string, userKey: string): Promise<{ userId: string; address: string }> {
const settings = await this.settings.getAllRaw();
if (!settings.tianheAppId || !settings.tianheAppKey) {
throw new BusinessException(ErrorCode.BAD_REQUEST, '请先填写并保存天河链 App ID / App Key');
}
const uid = (userId || '').trim();
const key = (userKey || '').trim();
if (!uid || !key) throw new BusinessException(ErrorCode.BAD_REQUEST, 'User ID 与 User Key 均不能为空');
const provider = this.buildTianheProvider(settings, uid, key);
let address: string;
try {
address = (await provider.userInfo()).address;
} catch (e) {
throw new BusinessException(ErrorCode.BAD_REQUEST, (e as Error).message);
}
await this.settings.setRaw('tianheUserId', uid);
await this.settings.setRaw('tianheUserKey', key);
await this.settings.setRaw('tianheWalletAddress', address);
return { userId: uid, address };
}
// 揭示明文 userKey(管理员离线备份用;该值本就明文存库,不加密的理由见 settings.service)
async revealTianheUserKey(): Promise<{ userId: string; userKey: string; address: string }> {
const settings = await this.settings.getAllRaw();
return {
userId: settings.tianheUserId || '',
userKey: settings.tianheUserKey || '',
address: settings.tianheWalletAddress || '',
};
}
// 存证前确保托管钱包已注册(以 tianheWalletAddress 为「已注册」标记,避免每次都调注册接口)
private async ensureTianheWallet(provider: TianheProvider): Promise<void> {
const settings = await this.settings.getAllRaw();
if (settings.tianheWalletAddress) return;
const { address } = await provider.ensureRegistered();
await this.settings.setRaw('tianheUserId', await this.resolvedUserId());
await this.settings.setRaw('tianheWalletAddress', address);
this.logger.log(`天河链托管钱包已注册:${address}`);
}
private async resolvedUserId(): Promise<string> {
const settings = await this.settings.getAllRaw();
return (settings.tianheUserId || '').trim() || DEFAULT_TIANHE_USER_ID;
}
private async buildProvider(): Promise<AttestationProvider> {
const settings = await this.settings.getAllRaw();
const driver = (settings.blockchainDriver || this.config.get<string>('blockchain.driver') || 'mock') as 'mock' | 'tianhe';
if (driver !== 'tianhe') return new MockProvider();
const userId = (settings.tianheUserId || '').trim() || DEFAULT_TIANHE_USER_ID;
let userKey = (settings.tianheUserKey || '').trim();
if (!userKey) {
// 一次性生成并持久化(明文)。不从 appKey 派生:派生会让换 appKey 时 userKey 变化,
// 与已注册钱包不匹配(天河链不留存 userKey,改 key 需旧 key)。
userKey = randomBytes(32).toString('hex');
await this.settings.setRaw('tianheUserId', userId);
await this.settings.setRaw('tianheUserKey', userKey);
this.logger.log('已生成天河链平台钱包 userKey 并持久化,请在系统设置中揭示并离线保存');
}
return this.buildTianheProvider(settings, userId, userKey);
}
private buildTianheProvider(settings: Record<string, string>, userId: string, userKey: string): TianheProvider {
const env = settings.tianheEnv || 'test';
const configuredBaseUrl =
const baseUrl =
env === 'test'
? TIANHE_TEST_URL
: env === 'production'
? TIANHE_PRODUCTION_URL
: settings.tianheBaseUrl || this.config.get<string>('blockchain.tianhe.baseUrl') || TIANHE_TEST_URL;
return new TianheProvider({
baseUrl: configuredBaseUrl,
baseUrl,
appId: settings.tianheAppId || this.config.get<string>('blockchain.tianhe.appId') || '',
appKey: settings.tianheAppKey || this.config.get<string>('blockchain.tianhe.appKey') || '',
userId: this.tianheUserId(settings),
userKey: this.tianheUserKey(settings),
userId,
userKey,
});
}
private tianheUserId(settings: Record<string, string>): string {
return settings.tianheUserId || this.config.get<string>('blockchain.tianhe.userId') || DEFAULT_TIANHE_USER_ID;
}
private tianheUserKey(settings: Record<string, string>): string {
const configured = settings.tianheUserKey || this.config.get<string>('blockchain.tianhe.userKey');
if (configured) return configured;
const appId = settings.tianheAppId || this.config.get<string>('blockchain.tianhe.appId') || '';
const appKey = settings.tianheAppKey || this.config.get<string>('blockchain.tianhe.appKey') || '';
return createHash('sha256').update(`artveris:tianhe:${appId}:${appKey}`).digest('hex');
}
}
@@ -38,6 +38,80 @@ describe('TianheProvider', () => {
expect(result.raw.digest).toBe(response.data.digest);
expect(result.raw.transactionStatus).toBe('submitted');
expect(result.confirmationRequired).toBe(true);
// upload 不返回区块信息,由 confirm 阶段补齐
expect(result.blockHash).toBeNull();
expect(result.blockHeight).toBeNull();
});
it('upload 的 userDto 分段必须为 application/json 类型', async () => {
const fetchMock = jest.spyOn(globalThis, 'fetch').mockResolvedValue({
ok: true,
text: async () =>
JSON.stringify({ code: 0, data: { digest: 'd', url: 'u', transactionHash: '0xtx' } }),
} as Response);
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');
});
it('响应缺少 transactionHash 时抛错,不用本地 dataHash 冒充', async () => {
jest.spyOn(globalThis, 'fetch').mockResolvedValue({
ok: true,
text: async () => JSON.stringify({ code: 0, message: 'success', data: { digest: 'only-digest' } }),
} as Response);
await expect(provider.attest({ dataHash: '0xlocal' })).rejects.toThrow('transactionHash');
});
it('响应缺少 code 字段时视为异常而非成功', async () => {
jest.spyOn(globalThis, 'fetch').mockResolvedValue({
ok: true,
text: async () => JSON.stringify({ something: 'else' }),
} as Response);
await expect(provider.attest({ dataHash: '0xlocal' })).rejects.toThrow('code=缺失');
});
it('code 非 0 时抛出接口错误信息', async () => {
jest.spyOn(globalThis, 'fetch').mockResolvedValue({
ok: true,
text: async () => JSON.stringify({ code: 500, message: 'appKey invalid' }),
} as Response);
await expect(provider.attest({ dataHash: '0xlocal' })).rejects.toThrow('appKey invalid');
});
it('registerUser 按接口 1 解析托管钱包地址', async () => {
jest.spyOn(globalThis, 'fetch').mockResolvedValue({
ok: true,
text: async () =>
JSON.stringify({ code: 0, data: { pubKey: { address: '0xwallet', publicKey: 'ignored' } } }),
} as Response);
const result = await provider.registerUser();
expect(result.address).toBe('0xwallet');
});
it('ensureRegistered 优先查询接口 8,失败则回退注册', async () => {
const fetchMock = jest
.spyOn(globalThis, 'fetch')
.mockResolvedValueOnce({
ok: true,
text: async () => JSON.stringify({ code: 1, message: 'user not found' }),
} as Response)
.mockResolvedValueOnce({
ok: true,
text: async () => JSON.stringify({ code: 0, data: { pubKey: { address: '0xnewwallet' } } }),
} as Response);
const result = await provider.ensureRegistered();
expect(result.address).toBe('0xnewwallet');
expect(String(fetchMock.mock.calls[0][0])).toContain('/api/v2/user/info');
expect(String(fetchMock.mock.calls[1][0])).toContain('/api/v2/user');
});
it('按交易状态接口确认链上区块信息', async () => {
+95 -73
View File
@@ -36,11 +36,23 @@ function pickNumber(source: unknown, keys: string[]): number | null {
return null;
}
function responseData(raw: unknown): Record<string, unknown> {
if (!raw || typeof raw !== 'object') return {};
const obj = raw as Record<string, unknown>;
const data = obj.data;
return data && typeof data === 'object' ? { ...obj, ...(data as Record<string, unknown>) } : obj;
function parseJson(text: string): Record<string, unknown> {
try {
return text ? (JSON.parse(text) as Record<string, unknown>) : {};
} catch {
return { text };
}
}
// 天河链响应统一为 { code, message, data };code=0 为成功(缺失 code 视为异常响应,不再宽松放行)
function assertOk(raw: Record<string, unknown>, action: string): Record<string, unknown> {
const code = pickString(raw, ['code']);
if (code !== '0') {
const msg = pickString(raw, ['message', 'msg', 'error']) || `接口返回异常(code=${code ?? '缺失'})`;
throw new Error(`${action}失败:${msg}`);
}
const data = raw.data;
return data && typeof data === 'object' ? (data as Record<string, unknown>) : {};
}
export class TianheProvider implements AttestationProvider {
@@ -48,14 +60,61 @@ export class TianheProvider implements AttestationProvider {
constructor(private readonly opts: TianheOptions) {}
async attest(payload: AttestPayload): Promise<AttestResult> {
const baseUrl = required(this.opts.baseUrl, 'Base URL').replace(/\/+$/, '');
const userDto = {
private baseUrl(): string {
return required(this.opts.baseUrl, 'Base URL').replace(/\/+$/, '');
}
private credentials() {
return {
appId: required(this.opts.appId, 'App ID'),
appKey: required(this.opts.appKey, 'App Key'),
userId: required(this.opts.userId, 'User ID'),
userKey: required(this.opts.userKey, 'User Key'),
};
}
private async postJson(path: string, body: Record<string, unknown>, action: string): Promise<Record<string, unknown>> {
const res = await fetch(`${this.baseUrl()}${path}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
const text = await res.text();
if (!res.ok) throw new Error(`${action}请求失败:HTTP ${res.status} ${text.slice(0, 200)}`);
return parseJson(text);
}
// 接口 1「用户链上身份注册」:注册托管钱包,返回链上地址。userKey 是钱包密码,天河链不留存。
async registerUser(): Promise<{ address: string }> {
const raw = await this.postJson('/api/v2/user', this.credentials(), '天河链链上身份注册');
const data = assertOk(raw, '天河链链上身份注册');
const pubKey = (data.pubKey && typeof data.pubKey === 'object' ? data.pubKey : data) as Record<string, unknown>;
const address = pickString(pubKey, ['address']) || pickString(data, ['address']);
if (!address) throw new Error('天河链链上身份注册失败:响应缺少钱包地址');
return { address };
}
// 接口 8「用户链上身份查询」:校验 userId/userKey 是否对应已注册钱包,返回其地址。
async userInfo(): Promise<{ address: string }> {
const raw = await this.postJson('/api/v2/user/info', this.credentials(), '天河链链上身份查询');
const data = assertOk(raw, '天河链链上身份查询');
const address = pickString(data, ['address']);
if (!address) throw new Error('天河链链上身份查询失败:响应缺少钱包地址');
return { address };
}
// 幂等确保托管钱包存在:先查询(接口 8),不存在再注册(接口 1)。
async ensureRegistered(): Promise<{ address: string }> {
try {
return await this.userInfo();
} catch {
return this.registerUser();
}
}
// 接口 6「元数据上链存证」:上传存证文件,返回 { digest, url, transactionHash }。
// 每个追溯码(每件实物)各自调用一次 → 每物一条 proof、独立 txHash(不变量,勿改为按档案共用)。
async attest(payload: AttestPayload): Promise<AttestResult> {
const meta = {
dataHash: payload.dataHash,
...(payload.meta || {}),
@@ -63,65 +122,41 @@ export class TianheProvider implements AttestationProvider {
};
const form = new FormData();
form.append('userDto', JSON.stringify(userDto));
// 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 res = await fetch(`${baseUrl}/api/v2/nfr/upload`, {
method: 'POST',
body: form,
});
const res = await fetch(`${this.baseUrl()}/api/v2/nfr/upload`, { method: 'POST', body: form });
const text = await res.text();
let raw: Record<string, unknown> = { text };
try {
raw = text ? JSON.parse(text) : {};
} catch {
raw = { text };
}
if (!res.ok) {
throw new Error(`天河链存证请求失败:HTTP ${res.status} ${text.slice(0, 200)}`);
}
if (!res.ok) throw new Error(`天河链存证请求失败:HTTP ${res.status} ${text.slice(0, 200)}`);
const raw = parseJson(text);
const data = assertOk(raw, '天河链存证');
const code = pickString(raw, ['code', 'statusCode', 'errCode']);
const success = code === null || code === '0' || code.toLowerCase() === 'success' || code === '200';
if (!success) {
const msg = pickString(raw, ['message', 'msg', 'error']) || '接口返回失败';
throw new Error(`天河链存证失败:${msg}`);
}
const data = responseData(raw);
const txHash =
pickString(data, [
'transactionHash',
'txHash',
'hash',
'proofHash',
'certHash',
'attestationHash',
'chainHash',
]) || payload.dataHash;
// 严格要求返回交易哈希;缺失即视为失败(绝不能用本地 dataHash 冒充链上哈希造成「假上链」)
const txHash = pickString(data, ['transactionHash', 'txHash']);
if (!txHash) throw new Error('天河链存证失败:响应缺少 transactionHash');
const digest = pickString(data, ['digest']);
const explorerUrl = pickString(data, ['url', 'link', 'proofUrl', 'viewUrl', 'certUrl', 'explorerUrl', 'uri']);
const blockHash = pickString(data, ['blockHash']);
const blockHeight = pickNumber(data, ['blockHeight', 'blockNum', 'height']);
const onchainAtText = pickString(data, ['onchainAt', 'chainTime', 'createdAt', 'time']);
const onchainAt = onchainAtText ? new Date(onchainAtText) : new Date();
// url 为「存证链接」(文件下载地址/链上 URI,可对外展示),并非区块浏览器交易页
const proofUrl = pickString(data, ['url']);
return {
dataHash: payload.dataHash,
txHash,
blockHash,
blockHeight,
// upload 接口不返回区块信息,blockHash/blockHeight 由后续 confirm 阶段补齐
blockHash: null,
blockHeight: null,
chainName: '天河链',
explorerUrl,
onchainAt: Number.isNaN(onchainAt.getTime()) ? new Date() : onchainAt,
explorerUrl: proofUrl,
onchainAt: new Date(),
raw: {
requestMeta: meta,
response: raw,
digest,
proofUrl,
transactionStatus: 'submitted',
transactionStatusNote: '天河链接口成功仅表示交易已提交;最终链上结果需通过交易查询接口确认。',
},
@@ -129,37 +164,24 @@ export class TianheProvider implements AttestationProvider {
};
}
// 接口 9「根据交易哈希查询」:确认交易是否已进块。
// 文档标注 GET,curl 样例却用 body 传参;实现取 GET+query(fetch 不支持 GET body),联调已通过则维持现状。
async confirmTransaction(txHash: string): Promise<ConfirmTransactionResult> {
const baseUrl = required(this.opts.baseUrl, 'Base URL').replace(/\/+$/, '');
const appId = required(this.opts.appId, 'App ID');
const appKey = required(this.opts.appKey, 'App Key');
const url = new URL(`${baseUrl}/api/v2/nfr/transaction/status`);
url.searchParams.set('appId', appId);
url.searchParams.set('appKey', appKey);
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();
let raw: Record<string, unknown> = { text };
try {
raw = text ? JSON.parse(text) : {};
} catch {
raw = { text };
}
if (!res.ok) {
throw new Error(`天河链交易确认请求失败:HTTP ${res.status} ${text.slice(0, 200)}`);
}
if (!res.ok) throw new Error(`天河链交易确认请求失败:HTTP ${res.status} ${text.slice(0, 200)}`);
const raw = parseJson(text);
const data = assertOk(raw, '天河链交易确认');
const code = pickString(raw, ['code', 'statusCode', 'errCode']);
const success = code === null || code === '0' || code.toLowerCase() === 'success' || code === '200';
if (!success) {
const msg = pickString(raw, ['message', 'msg', 'error']) || '接口返回失败';
throw new Error(`天河链交易确认失败:${msg}`);
}
const data = responseData(raw);
const status = pickString(data, ['status']);
const blockHash = pickString(data, ['blockHash']);
const blockHeight = pickNumber(data, ['blockNum', 'blockHeight', 'height']);
// 已进块(拿到区块信息)即视为确认;status 字段语义文档未定义,原样记录供排查
const confirmed = Boolean(blockHash || blockHeight !== null);
return {
confirmed,
@@ -170,7 +192,7 @@ export class TianheProvider implements AttestationProvider {
response: raw,
transactionStatus: confirmed ? 'confirmed' : 'waiting',
tokenId: pickString(data, ['tokenId']),
status: pickString(data, ['status']),
status,
},
};
}
+30 -2
View File
@@ -1,14 +1,18 @@
import { Body, Controller, Get, Put } from '@nestjs/common';
import { Body, Controller, Get, Post, Put } from '@nestjs/common';
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
import { RoleType } from '@artveris/shared';
import { SettingsService } from './settings.service';
import { BlockchainService } from '../blockchain/blockchain.service';
import { Roles } from '../common/decorators/roles.decorator';
import { Public } from '../common/decorators/public.decorator';
@ApiTags('系统设置')
@Controller('settings')
export class SettingsController {
constructor(private readonly settingsService: SettingsService) {}
constructor(
private readonly settingsService: SettingsService,
private readonly blockchain: BlockchainService,
) {}
@ApiBearerAuth()
@Get()
@@ -32,4 +36,28 @@ export class SettingsController {
update(@Body() body: Record<string, string>) {
return this.settingsService.update(body);
}
@ApiBearerAuth()
@Roles(RoleType.SUPER_ADMIN)
@Post('tianhe/register')
@ApiOperation({ summary: '注册(或确认)天河链平台链上身份,返回明文 userId/userKey 供离线保存' })
registerTianheIdentity() {
return this.blockchain.registerTianheIdentity();
}
@ApiBearerAuth()
@Roles(RoleType.SUPER_ADMIN)
@Post('tianhe/verify')
@ApiOperation({ summary: '手动录入已有 userId/userKey 并校验(重装/迁移时复用既有钱包)' })
verifyTianheIdentity(@Body() body: { userId: string; userKey: string }) {
return this.blockchain.verifyTianheIdentity(body.userId, body.userKey);
}
@ApiBearerAuth()
@Roles(RoleType.SUPER_ADMIN)
@Get('tianhe/identity')
@ApiOperation({ summary: '揭示天河链链上身份明文(userId/userKey/钱包地址),供管理员离线备份' })
revealTianheIdentity() {
return this.blockchain.revealTianheUserKey();
}
}
+19 -7
View File
@@ -37,7 +37,13 @@ const EDITABLE_KEYS = [
'tianheUserKey',
];
const SECRET_KEYS = new Set(['ossAccessKeySecret', 'tianheAppKey', 'tianheUserKey']);
// 加密存储的密钥(enc:v1:)。注意:tianheUserKey 有意不加密——
// 它是全系统唯一无外部恢复途径的钱包密码,明文存库才能让备份跨重装恢复
// (加密依赖 .env 的 SETTING_ENCRYPTION_KEY,重装换密钥后密文将无法解密);
// 且单有 userKey 无 appKey(仍加密)无法操作钱包。
const SECRET_KEYS = new Set(['ossAccessKeySecret', 'tianheAppKey']);
// 展示层掩码的密钥(getAll 输出打码;明文经专用揭示接口获取)
const MASKED_KEYS = new Set(['ossAccessKeySecret', 'tianheAppKey', 'tianheUserKey']);
const ENCRYPTED_PREFIX = 'enc:v1:';
@Injectable()
@@ -91,14 +97,15 @@ export class SettingsService {
tianheUserKey: this.config.get<string>('blockchain.tianhe.userKey') || '',
};
for (const r of rows) {
const value = SECRET_KEYS.has(r.key) ? await this.decryptSecret(r.value) : r.value;
// 带 enc:v1: 前缀的值统一解密(兼容历史上曾加密存储、现已改为明文的键,如 tianheUserKey)
const value = await this.decryptSecret(r.value);
map[r.key] = r.key === 'appName' && value === '艺术品可信溯源与认证平台' ? '艺术品溯源平台' : value;
}
if (map.appIconUrl === '/app-icon.svg') map.appIconUrl = '';
if (maskSecrets) {
if (map.ossAccessKeySecret) map.ossAccessKeySecret = this.maskSecret(map.ossAccessKeySecret);
if (map.tianheAppKey) map.tianheAppKey = this.maskSecret(map.tianheAppKey);
if (map.tianheUserKey) map.tianheUserKey = this.maskSecret(map.tianheUserKey);
for (const key of MASKED_KEYS) {
if (map[key]) map[key] = this.maskSecret(map[key]);
}
delete map.settingsEncryptionKey;
}
return map;
@@ -107,7 +114,7 @@ export class SettingsService {
async get(key: string): Promise<string | null> {
const row = await this.prisma.systemSetting.findUnique({ where: { key } });
if (!row) return null;
return SECRET_KEYS.has(key) ? this.decryptSecret(row.value) : row.value;
return this.decryptSecret(row.value);
}
async getClientBaseUrl(): Promise<string> {
@@ -127,7 +134,7 @@ export class SettingsService {
async update(values: Record<string, string>): Promise<Record<string, string>> {
for (const [key, value] of Object.entries(values)) {
if (!EDITABLE_KEYS.includes(key)) continue;
if (SECRET_KEYS.has(key) && this.isMaskedSecret(value)) continue;
if (MASKED_KEYS.has(key) && this.isMaskedSecret(value)) continue;
const nextValue = SECRET_KEYS.has(key) ? await this.encryptSecret(String(value)) : String(value);
await this.prisma.systemSetting.upsert({
where: { key },
@@ -138,6 +145,11 @@ export class SettingsService {
return this.getAll();
}
// 服务内部直写(不做白名单/加密处理),用于系统自身生成的运行时值(如天河链钱包身份)
async setRaw(key: string, value: string): Promise<void> {
await this.prisma.systemSetting.upsert({ where: { key }, update: { value }, create: { key, value } });
}
private async encryptionKey(): Promise<Buffer> {
const row = await this.prisma.systemSetting.findUnique({ where: { key: 'settingsEncryptionKey' } }).catch(() => null);
const secret =