feat: 客户页面改为站内查看存证和证书

This commit is contained in:
Nixevol
2026-11-15 12:15:04 +08:00
parent 6669722c00
commit 2955efb278
15 changed files with 253 additions and 70 deletions
@@ -26,15 +26,20 @@ describe('Consumer certificate lifecycle', () => {
afterEach(() => jest.restoreAllMocks());
it('GET only reads persisted state and never starts a job or calls Tianhe', async () => {
const { service, prisma, config } = fixture('NONE');
expect(await service.status('123456000001')).toMatchObject({ status: 'NONE', url: null });
expect(await service.status('123456000001')).toMatchObject({ status: 'NONE', certificate: null });
expect(prisma.blockchainProof.updateMany).not.toHaveBeenCalled();
expect(prisma.$transaction).not.toHaveBeenCalled();
expect(config.getAllRaw).not.toHaveBeenCalled();
});
it('returns an existing shared certificate without consulting credentials or submitting', async () => {
const { service, row, config } = fixture('READY');
row.certificateUrl = 'https://test.tichain.tianhecloud.com/#/certificate?address=' + settings.tianheWalletAddress + '&txHash=0x' + 'a'.repeat(64) + '&digest=' + 'b'.repeat(64);
expect(await service.request('123456000001')).toMatchObject({ status: 'READY', url: row.certificateUrl });
row.certificateUrl = 'https://test.tichain.tianhecloud.com/#/certificate?address=' + settings.tianheWalletAddress + '&txHash=0x' + 'a'.repeat(64) + '&digest=' + 'b'.repeat(64) + '&createTime=1789844077000';
const result = await service.request('123456000001');
expect(result).toMatchObject({
status: 'READY',
certificate: { text: 'frozen-evidence', digest: 'b'.repeat(64), txHash: '0x' + 'a'.repeat(64), author: settings.tianheWalletAddress, createdAt: '2026-09-19T18:54:37.000Z' },
});
expect(JSON.stringify(result)).not.toContain('tianhecloud');
expect(config.getAllRaw).not.toHaveBeenCalled();
});
it('does not send when another worker owns the lease', async () => {
@@ -6,7 +6,7 @@ import { DEFAULT_CERTIFICATE_TEXT_TEMPLATE, ErrorCode, renderCertificateText, TR
import { BusinessException } from '../common/exceptions/business.exception';
import { PrismaService } from '../prisma/prisma.service';
import { SettingsService } from '../settings/settings.service';
import { certificateAuthorUrl, DepositEnvironment, DepositProvider, DepositRejected, safeCertificateUrl } from './deposit.provider';
import { DepositEnvironment, DepositProvider, DepositRejected, presentStoredCertificate } from './deposit.provider';
interface CertificateRequest {
version: 1;
@@ -43,12 +43,13 @@ export class DepositCertificateService {
private async view(proof: BlockchainProof, artist?: string | null) {
const request = proof.certificateRequest as unknown as CertificateRequest | null;
const url = request && proof.certificateState === 'READY'
? safeCertificateUrl(proof.certificateUrl, request.environment, request.address) : null;
const certificate = request && proof.certificateState === 'READY'
? presentStoredCertificate(proof.certificateUrl, request.environment, request.address, request.text, await this.settings.get('certificateAuthorMode'), artist)
: null;
return {
status: proof.certificateState === 'READY' && !url ? 'FAILED' : proof.certificateState,
url: url ? certificateAuthorUrl(url, await this.settings.get('certificateAuthorMode'), artist) : null,
status: proof.certificateState === 'READY' && !certificate ? 'FAILED' : proof.certificateState,
generatedAt: proof.certificateGeneratedAt,
certificate,
};
}
@@ -1,4 +1,4 @@
import { certificateAuthorUrl, depositSignature, DepositProvider, DepositRejected, safeCertificateUrl } from './deposit.provider';
import { certificateAuthorUrl, depositSignature, DepositProvider, DepositRejected, presentStoredCertificate, safeCertificateUrl } from './deposit.provider';
import { createHash } from 'crypto';
describe('V3 deposit protocol', () => {
@@ -28,6 +28,16 @@ describe('V3 deposit protocol', () => {
}
expect(safeCertificateUrl('https://test.tichain.tianhecloud.com/' + suffix, 'test', 'wrong')).toBeNull();
});
it('presents stored certificate fields without the Tianhe page address', () => {
const address = '0x' + 'a'.repeat(40);
const txHash = '0x' + 'c'.repeat(64);
const digest = 'd'.repeat(64);
const stored = `https://tichain.tianhecloud.com/#/certificate?address=${address}&txHash=${txHash}&digest=${digest}&createTime=1789867663000`;
const view = presentStoredCertificate(stored, 'production', address, '十二生肖莲花手工杯', 'ARTWORK_ARTIST', '黄志伟');
expect(view).toEqual({ text: '十二生肖莲花手工杯', digest, txHash, author: '黄志伟', createdAt: '2026-09-20T01:27:43.000Z' });
expect(JSON.stringify(view)).not.toContain('tianhecloud');
expect(presentStoredCertificate(stored, 'production', address, '十二生肖莲花手工杯', 'WALLET', '黄志伟')?.author).toBe(address);
});
it('uses signed headers, does not expose keys in URL/body and rejects ambiguous acceptance', async () => {
const fetcher = jest.spyOn(global, 'fetch').mockResolvedValue({ ok: true, json: async () => ({ code: 200, success: true, data: 'different-id' }) } as any);
await expect(new DepositProvider('test', 'app', 'secret').submit('address', 'op', '证据'))
@@ -14,6 +14,26 @@ export function depositSignature(path: string, query: Record<string, unknown>, b
return createHash('sha256').update(json + timestamp + key, 'utf8').digest('hex');
}
export interface StoredCertificateView {
text: string;
digest: string;
txHash: string;
author: string;
createdAt: 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 {
@@ -96,8 +96,7 @@ function createHarness(options: {
set: jest.fn().mockResolvedValue('OK'),
};
const storage = { getUrl: jest.fn((key: string) => `/uploads/${key}`) };
const settings = { getAllRaw: jest.fn().mockResolvedValue({}) };
const service = new PublicTraceService(prisma as any, storage as any, settings as any, redis as any);
const service = new PublicTraceService(prisma as any, storage as any, redis as any);
return { service, prisma };
}
@@ -15,10 +15,8 @@ import {
} from '@artveris/shared';
import { PrismaService } from '../prisma/prisma.service';
import { StorageService } from '../storage/storage.service';
import { SettingsService } from '../settings/settings.service';
import { REDIS_CLIENT } from '../redis/redis.module';
import { parseUserAgent } from '../common/utils/ua.util';
import { buildTianheExplorerTxUrl } from '../blockchain/tianhe.provider';
type TraceCodeWithRel = Prisma.TraceCodeGetPayload<{ include: { batch: true; artwork: true } }>;
type ArtworkWithRel = Prisma.ArtworkGetPayload<{
@@ -45,7 +43,6 @@ export class PublicTraceService {
constructor(
private readonly prisma: PrismaService,
private readonly storage: StorageService,
private readonly settings: SettingsService,
@Inject(REDIS_CLIENT) private readonly redis: Redis,
) {}
@@ -271,8 +268,6 @@ export class PublicTraceService {
const result = firstActivate ? QueryResult.FIRST_ACTIVATE : QueryResult.REPEAT;
await this.writeLog(id, artwork.id, shortCode, result, ctx, { ...code, ...updated });
const explorerUrl = await this.resolveExplorerUrl(proof);
return {
status: 'OK' as const,
queriedAt: now,
@@ -281,7 +276,7 @@ export class PublicTraceService {
queryCount: updated.queryCount,
firstActivatedAt: updated.firstActivatedAt,
},
...this.buildArtworkPayload(artwork, code, proof, explorerUrl),
...this.buildArtworkPayload(artwork, code, proof),
};
}
@@ -329,7 +324,6 @@ export class PublicTraceService {
const now = new Date();
const firstQuery = state === 'inactive';
const explorerUrl = await this.resolveExplorerUrl(proof);
return {
status: 'OK' as const,
preview: true,
@@ -341,7 +335,7 @@ export class PublicTraceService {
queryCount: code.queryCount > 0 ? code.queryCount : 2,
firstActivatedAt: code.firstActivatedAt ?? now,
},
...this.buildArtworkPayload(artwork, code, proof, explorerUrl),
...this.buildArtworkPayload(artwork, code, proof),
};
}
@@ -362,13 +356,11 @@ export class PublicTraceService {
blockHeight: bigint | null;
chainName: string | null;
onchainAt: Date | null;
explorerUrl: string | null;
contractAddress: string | null;
status: string;
failureReason: string | null;
submittedAt: Date | null;
} | null,
explorerUrl: string | null,
) {
return {
artwork: {
@@ -414,7 +406,6 @@ export class PublicTraceService {
blockHeight: proof.blockHeight,
chainName: proof.chainName,
onchainAt: proof.onchainAt,
explorerUrl,
contractAddress: proof.contractAddress,
submittedAt: proof.submittedAt,
failureReason: this.publicFailureReason(proof.status, proof.failureReason),
@@ -471,18 +462,6 @@ export class PublicTraceService {
};
}
private async resolveExplorerUrl(
proof: { txHash: string | null; chainName: string | null; explorerUrl: string | null } | null,
): Promise<string | null> {
const tianheProof =
proof?.chainName === '天河链' ||
/tianhe|tichain/i.test(proof?.chainName || '') ||
/tianhecloud\.com/i.test(proof?.explorerUrl || '');
if (!proof?.txHash || !tianheProof) return proof?.explorerUrl ?? null;
const settings = await this.settings.getAllRaw();
return buildTianheExplorerTxUrl(settings.tianheBaseUrl || '', proof.txHash, settings.tianheEnv);
}
private buildFields(
fields: Array<{ fieldKey: string; label: string; type: string }>,
dynamic: unknown,