import { createHash } from 'crypto'; export type DepositEnvironment = 'test' | 'production'; export const DEPOSIT_ENDPOINTS = { test: 'https://test.api.tichain.tianhecloud.com', production: 'https://api.tichain.tianhecloud.com', } as const; export function depositSignature(path: string, query: Record, body: Record, timestamp: string, key: string): string { const params: Record = { path_url: path }; for (const [k, v] of Object.entries(query)) params[`query_${k}`] = v; for (const [k, v] of Object.entries(body)) params[`body_${k}`] = v; const json = JSON.stringify(Object.fromEntries(Object.keys(params).sort().map(k => [k, params[k]]))); return createHash('sha256').update(json + timestamp + key, 'utf8').digest('hex'); } export interface StoredCertificateView { text: string; digest: string; txHash: string; author: string; createdAt: string | null; imageUrl?: string | null; } /** 公开页面只接收存证字段。天河链证书网址留在服务端,不进入浏览器。 */ export function presentStoredCertificate(value: unknown, environment: DepositEnvironment, address: string, text: string, mode: string | null, artist?: string | null): StoredCertificateView | null { if (!safeCertificateUrl(value, environment, address) || !text.trim()) return null; const params = new URLSearchParams(new URL(String(value)).hash.slice('#/certificate?'.length)); const digest = params.get('digest') || ''; const txHash = params.get('txHash') || ''; const rawTime = params.get('createTime'); const created = rawTime && /^\d+$/.test(rawTime) ? new Date(Number(rawTime)) : null; const author = mode === 'ARTWORK_ARTIST' && artist?.trim() ? artist.trim() : address; return { text, digest, txHash, author, createdAt: created && !Number.isNaN(created.getTime()) ? created.toISOString() : null }; } export function safeCertificateUrl(value: unknown, environment: DepositEnvironment, address?: string): string | null { if (typeof value !== 'string') return null; try { const url = new URL(value); const host = environment === 'test' ? 'test.tichain.tianhecloud.com' : 'tichain.tianhecloud.com'; if (url.protocol !== 'https:' || url.hostname !== host || url.port || url.username || url.password || url.pathname !== '/' || !url.hash.startsWith('#/certificate?')) return null; const params = new URLSearchParams(url.hash.slice('#/certificate?'.length)); if (address && params.get('address')?.toLowerCase() !== address.toLowerCase()) return null; if (!/^0x[0-9a-f]{64}$/i.test(params.get('txHash') || '') || !/^[0-9a-f]{64}$/i.test(params.get('digest') || '')) return null; return url.toString(); } catch { return null; } } export class DepositRejected extends Error {} /** 官方证书页的显示参数;保留原address、digest和txHash,不改变存证身份。 */ export function certificateAuthorUrl(url: string, mode: string | null, artist?: string | null): string { const parsed = new URL(url); const params = new URLSearchParams(parsed.hash.slice('#/certificate?'.length)); if (mode === 'ARTWORK_ARTIST' && artist?.trim()) params.set('author', artist.trim()); else params.delete('author'); parsed.hash = '/certificate?' + params.toString(); return parsed.toString(); } /** V3 uses signed headers and code=200, unlike the existing V2 provider. */ export class DepositProvider { constructor(private readonly environment: DepositEnvironment, private readonly appId: string, private readonly appKey: string) {} private async request(path: string, query: Record, body?: Record): Promise { const stamp = String(Date.now()); const url = new URL(path, DEPOSIT_ENDPOINTS[this.environment]); for (const [key, value] of Object.entries(query)) url.searchParams.set(key, value); // Do not log request headers, signed material, credentials, or evidence text. const response = await fetch(url, { method: body ? 'POST' : 'GET', redirect: 'error', signal: AbortSignal.timeout(25_000), headers: { 'Content-Type': 'application/json', 'ti-appid': this.appId, 'ti-timestamp': stamp, 'ti-signature': depositSignature(path, query, body || {}, stamp, this.appKey), }, ...(body ? { body: JSON.stringify(body) } : {}), }); if (!response.ok) throw new Error(`Deposit HTTP ${response.status}`); const result = await response.json() as any; if (!result || typeof result !== 'object') throw new Error('Invalid deposit response'); return result; } async submit(address: string, operateId: string, text: string): Promise { const result = await this.request('/v1/deposit/text/save', {}, { text, address, operateId, noDigest: false }); if (result.success === false && result.code !== undefined) throw new DepositRejected(`Deposit rejected (${result.code})`); if (Number(result.code) !== 200 || result.success !== true || result.data !== operateId) throw new Error('Deposit submission result uncertain'); } async query(address: string, operateId: string): Promise { const result = await this.request('/v1/deposit/query', { address, operateId }); if (Number(result.code) !== 200 || result.success !== true) throw new Error('Deposit query failed'); return result.data; } async certificate(address: string, operateId: string, evidenceText: string): Promise { const result = await this.request('/v1/deposit/certificate', { address, operateId }); // Pending/not-found is not grounds for resubmitting a deposit. if (Number(result.code) === 400 && result.success === false) return null; if (Number(result.code) !== 200 || result.success !== true) throw new Error('Certificate query failed'); const url = safeCertificateUrl(result.data, this.environment, address); if (!url) throw new Error('Invalid certificate URL'); const parsed = new URL(url); const params = new URLSearchParams(parsed.hash.slice('#/certificate?'.length)); if (params.get('digest') !== createHash('sha256').update(evidenceText, 'utf8').digest('hex')) { throw new Error('Certificate digest does not match the submitted evidence'); } if (params.get('type') !== 'TEXT') throw new Error('Unexpected certificate type'); // The provider returns partially unescaped text. Preserve &, #, +, % and Unicode // from our frozen evidence, rather than allowing them to become URL parameters. params.set('depositContent', evidenceText); parsed.hash = '/certificate?' + params.toString(); return parsed.toString(); } }