feat: 支持消费者按实物点击生成天河链存证证书

This commit is contained in:
Nixevol
2026-09-20 01:40:04 +08:00
parent 3a6dfd7f24
commit f2d24dff0d
23 changed files with 810 additions and 23 deletions
+13
View File
@@ -73,6 +73,10 @@ const PRISMA_MODEL_BY_DELEGATE: Record<(typeof MODELS)[number], string> = {
systemSetting: 'SystemSetting',
};
const DATE_KEYS = new Set([
'certificateRequestedAt',
'certificateGeneratedAt',
'certificateNextCheck',
'certificateLeaseUntil',
'lastLoginAt',
'createdAt',
'updatedAt',
@@ -658,6 +662,15 @@ export class BackupService {
const rows = Array.isArray(db[model])
? db[model].map((row: unknown) => {
const revived = reviveRow(row as Record<string, any>) as Record<string, unknown>;
// A snapshot cannot prove that the original worker never sent this request.
// Restore unfinished certificates in query-only mode, never resubmit.
if (model === 'blockchainProof' && revived.certificateRequest &&
['PENDING', 'SUBMITTING', 'CHECKING', 'WAITING'].includes(String(revived.certificateState))) {
revived.certificateState = 'UNKNOWN';
revived.certificateLeaseToken = null;
revived.certificateLeaseUntil = null;
revived.certificateNextCheck = new Date();
}
return revived;
})
: [];
+4 -2
View File
@@ -7,12 +7,14 @@ import { AttestationService } from './attestation.service';
import { BlockchainController } from './blockchain.controller';
import { OnchainProcessor } from './onchain.processor';
import { OnchainRecoveryService } from './onchain-recovery.service';
import { DepositCertificateService } from './deposit-certificate.service';
import { DepositCertificateController } from './deposit-certificate.controller';
@Global()
@Module({
imports: [BullModule.registerQueue({ name: QUEUE_NAMES.ONCHAIN }), SettingsModule],
controllers: [BlockchainController],
providers: [BlockchainService, AttestationService, OnchainProcessor, OnchainRecoveryService],
controllers: [BlockchainController, DepositCertificateController],
providers: [BlockchainService, AttestationService, OnchainProcessor, OnchainRecoveryService, DepositCertificateService],
exports: [BlockchainService, AttestationService],
})
export class BlockchainModule {}
@@ -0,0 +1,19 @@
import { Controller, Get, Param, Post } from '@nestjs/common';
import { Throttle } from '@nestjs/throttler';
import { Public } from '../common/decorators/public.decorator';
import { DepositCertificateService } from './deposit-certificate.service';
@Controller('public/trace/:shortCode/certificate')
export class DepositCertificateController {
constructor(private readonly certificates: DepositCertificateService) {}
@Public()
@Get()
@Throttle({ default: { limit: 60, ttl: 60_000 } })
status(@Param('shortCode') shortCode: string) { return this.certificates.status(shortCode); }
@Public()
@Post()
@Throttle({ default: { limit: 5, ttl: 60_000 } })
request(@Param('shortCode') shortCode: string) { return this.certificates.request(shortCode); }
}
@@ -0,0 +1,93 @@
import { DepositCertificateService } from './deposit-certificate.service';
import { DepositProvider } from './deposit.provider';
const settings = {
certificateEnabled: 'true', certificateDailyLimit: '100', blockchainDriver: 'tianhe',
tianheEnv: 'test', tianheAppId: 'app', tianheAppKey: 'key', tianheWalletAddress: '0x' + 'a'.repeat(40),
};
function fixture(state = 'PENDING') {
const row: any = {
id: 1, traceCodeId: 1n, status: 'ONCHAIN', txHash: '0x' + 'c'.repeat(64), chainName: '天河链',
certificateState: state, certificateAttempts: 0, certificateLeaseUntil: null,
certificateRequest: { version: 1, environment: 'test', appId: 'app', address: settings.tianheWalletAddress, operateId: 'stable-op', text: 'frozen-evidence' },
};
const prisma = {
blockchainProof: {
updateMany: jest.fn().mockResolvedValue({ count: 1 }),
findUniqueOrThrow: jest.fn().mockResolvedValue(row),
},
traceCode: { findUnique: jest.fn().mockResolvedValue({ shortCode: '123456000001', status: 'ACTIVE', artwork: { status: 'ACTIVE', auditStatus: 'APPROVED' }, proofs: [row] }) },
$transaction: jest.fn(),
};
const config = { getAllRaw: jest.fn().mockResolvedValue(settings), get: jest.fn().mockResolvedValue('true') };
return { row, prisma, config, service: new DepositCertificateService(prisma as any, config as any) };
}
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(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 });
expect(config.getAllRaw).not.toHaveBeenCalled();
});
it('does not send when another worker owns the lease', async () => {
const { service, row, prisma } = fixture();
prisma.blockchainProof.updateMany.mockResolvedValue({ count: 0 });
const submit = jest.spyOn(DepositProvider.prototype, 'submit');
await service.process(row);
expect(submit).not.toHaveBeenCalled();
});
it('a submission timeout changes to query-only, preserving the exact operation id', async () => {
const { service, row, prisma } = fixture();
const submit = jest.spyOn(DepositProvider.prototype, 'submit').mockRejectedValue(new Error('timeout'));
await service.process(row);
expect(submit).toHaveBeenCalledWith(settings.tianheWalletAddress, 'stable-op', 'frozen-evidence');
expect(prisma.blockchainProof.updateMany.mock.calls[1][0].data.certificateState).toBe('WAITING');
row.certificateState = 'WAITING';
jest.spyOn(DepositProvider.prototype, 'query').mockResolvedValue({ operateId: 'stable-op', status: 2, createTime: '', txHash: '' });
const cert = jest.spyOn(DepositProvider.prototype, 'certificate');
await service.process(row);
expect(submit).toHaveBeenCalledTimes(1);
expect(cert).not.toHaveBeenCalled();
});
it('recovers a crashed SUBMITTING worker by querying, not resubmitting', async () => {
const { service, row } = fixture('SUBMITTING');
const submit = jest.spyOn(DepositProvider.prototype, 'submit');
const query = jest.spyOn(DepositProvider.prototype, 'query').mockResolvedValue({ status: 2 });
await service.process(row);
expect(submit).not.toHaveBeenCalled(); expect(query).toHaveBeenCalledWith(settings.tianheWalletAddress, 'stable-op');
});
it('stops before network calls if the wallet or environment changed', async () => {
const { service, row, config, prisma } = fixture();
config.getAllRaw.mockResolvedValue({ ...settings, tianheEnv: 'production' });
const submit = jest.spyOn(DepositProvider.prototype, 'submit');
await service.process(row);
expect(submit).not.toHaveBeenCalled();
expect(prisma.blockchainProof.updateMany.mock.calls[1][0].data.certificateState).toBe('UNKNOWN');
});
it('rejects inactive, disabled and unapproved items before creation', async () => {
const { service, prisma } = fixture('NONE');
prisma.traceCode.findUnique.mockResolvedValue({ status: 'INACTIVE' } as any);
await expect(service.request('123456000001')).rejects.toThrow();
expect(prisma.$transaction).not.toHaveBeenCalled();
});
it('uses an atomic NONE claim so a stale concurrent transaction cannot overwrite the request or consume quota', async () => {
const { service, prisma } = fixture('NONE');
const tx = {
systemSetting: { upsert: jest.fn(), update: jest.fn() },
$queryRaw: jest.fn().mockResolvedValue([{ value: '2026-09-20:1' }]),
blockchainProof: { updateMany: jest.fn().mockResolvedValue({ count: 0 }) },
};
prisma.$transaction.mockImplementation(async callback => callback(tx));
await service.request('123456000001');
expect(tx.blockchainProof.updateMany).toHaveBeenCalledWith(expect.objectContaining({ where: { id: 1, certificateState: 'NONE', status: 'ONCHAIN' } }));
expect(tx.systemSetting.update).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,195 @@
import { Injectable, Logger } from '@nestjs/common';
import { Interval } from '@nestjs/schedule';
import { ArtworkStatus, AuditStatus, BlockchainProof, Prisma, ProofStatus, TraceCodeStatus } from '@prisma/client';
import { randomBytes, randomUUID } from 'crypto';
import { ErrorCode, TRACE_CODE_PATTERN } from '@artveris/shared';
import { BusinessException } from '../common/exceptions/business.exception';
import { PrismaService } from '../prisma/prisma.service';
import { SettingsService } from '../settings/settings.service';
import { DepositEnvironment, DepositProvider, DepositRejected, safeCertificateUrl } from './deposit.provider';
interface CertificateRequest {
version: 1;
environment: DepositEnvironment;
appId: string;
address: string;
operateId: string;
text: string;
}
const ACTIVE_STATES = ['PENDING', 'SUBMITTING', 'WAITING', 'CHECKING'];
const MAX_CHECKS = 8;
@Injectable()
export class DepositCertificateService {
private readonly logger = new Logger(DepositCertificateService.name);
private running = false;
constructor(private readonly prisma: PrismaService, private readonly settings: SettingsService) {}
private async eligible(shortCode: string) {
if (!TRACE_CODE_PATTERN.test(shortCode)) throw new BusinessException(ErrorCode.NOT_FOUND, '追溯码不可用', 404);
const code = await this.prisma.traceCode.findUnique({
where: { shortCode }, include: { artwork: true, proofs: true },
});
const proof = code?.proofs[0];
if (!code || code.status !== TraceCodeStatus.ACTIVE || code.artwork.deletedAt ||
code.artwork.status !== ArtworkStatus.ACTIVE || code.artwork.auditStatus !== AuditStatus.APPROVED ||
!proof || proof.status !== ProofStatus.ONCHAIN || !proof.txHash || proof.chainName !== '天河链') {
throw new BusinessException(ErrorCode.NOT_FOUND, '当前实物暂不支持出证', 404);
}
return { code, proof };
}
private view(proof: BlockchainProof) {
const request = proof.certificateRequest as unknown as CertificateRequest | null;
const url = request && proof.certificateState === 'READY'
? safeCertificateUrl(proof.certificateUrl, request.environment, request.address) : null;
return {
status: proof.certificateState === 'READY' && !url ? 'FAILED' : proof.certificateState,
url, generatedAt: proof.certificateGeneratedAt,
};
}
/** No remote calls, writes, activation, or query-count changes. */
async status(shortCode: string) {
const { proof } = await this.eligible(shortCode);
return this.view(proof);
}
async request(shortCode: string) {
const { code, proof } = await this.eligible(shortCode);
if (proof.certificateState === 'READY') return this.view(proof);
const settings = await this.settings.getAllRaw();
if (settings.certificateEnabled === 'false') throw new BusinessException(ErrorCode.BAD_REQUEST, '证书生成暂时关闭');
if (proof.certificateState !== 'NONE') {
// An uncertain submission is never submitted again. User action only resumes queries.
if (proof.certificateState === 'UNKNOWN' && (!proof.certificateNextCheck || proof.certificateNextCheck <= new Date())) {
await this.prisma.blockchainProof.updateMany({
where: { id: proof.id, certificateState: 'UNKNOWN', certificateNextCheck: { lte: new Date() } },
data: { certificateState: 'WAITING', certificateAttempts: 0, certificateNextCheck: new Date() },
});
}
return this.view((await this.prisma.blockchainProof.findUniqueOrThrow({ where: { id: proof.id } })));
}
const environment = settings.tianheEnv as DepositEnvironment;
if (settings.blockchainDriver !== 'tianhe' || !['test', 'production'].includes(environment) ||
!settings.tianheAppId || !settings.tianheAppKey || !/^0x[0-9a-f]{40}$/i.test(settings.tianheWalletAddress || '')) {
throw new BusinessException(ErrorCode.BAD_REQUEST, '平台存证配置尚未就绪');
}
const now = new Date();
const request: CertificateRequest = {
version: 1, environment, appId: settings.tianheAppId, address: settings.tianheWalletAddress,
operateId: `avc${randomBytes(8).toString('hex')}`,
// The official TEXT certificate prints this verbatim; use readable labels.
text: [
`作品:${code.artwork.title}`,
`作者:${code.artwork.artist || '未填写'}`,
`档案编号:${code.artwork.archiveNo}`,
`实物追溯码:${code.shortCode}`,
`数字身份交易:${proof.txHash}`,
`证据记录时间:${now.toISOString()}`,
].join(';'),
};
// DB quota lock survives Redis restarts and serializes initial requests across workers.
// No credentials or network calls inside the transaction.
await this.prisma.$transaction(async tx => {
const quotaKey = 'certificateDailyQuota';
await tx.systemSetting.upsert({ where: { key: quotaKey }, create: { key: quotaKey, value: '' }, update: { key: quotaKey } });
const [quota] = await tx.$queryRaw<Array<{ value: string }>>`SELECT value FROM system_setting WHERE \`key\` = ${quotaKey} FOR UPDATE`;
// Use a conditional write, not a snapshot read: MySQL REPEATABLE READ can
// retain an older NONE snapshot while this transaction waited for the lock.
const claimed = await tx.blockchainProof.updateMany({ where: { id: proof.id, certificateState: 'NONE', status: ProofStatus.ONCHAIN }, data: {
certificateState: 'PENDING', certificateRequest: request as unknown as Prisma.InputJsonObject,
certificateRequestedAt: now, certificateNextCheck: now,
} });
if (!claimed.count) return;
const day = new Date(now.getTime() + 8 * 3600_000).toISOString().slice(0, 10);
const [quotaDay, quotaCount] = (quota?.value || '').split(':');
const count = quotaDay === day ? Number(quotaCount) || 0 : 0;
const limit = Math.min(10000, Math.max(0, Number(settings.certificateDailyLimit ?? '100') || 0));
if (count >= limit) throw new BusinessException(ErrorCode.TOO_MANY_REQUESTS, '今日证书生成数量已达上限,请稍后再试', 429);
await tx.systemSetting.update({ where: { key: quotaKey }, data: { value: `${day}:${count + 1}` } });
});
return this.view(await this.prisma.blockchainProof.findUniqueOrThrow({ where: { id: proof.id } }));
}
/** Persistent DB-backed work: only explicit requests enter PENDING. Restart-safe. */
@Interval(5000)
async tick() {
if (this.running) return;
this.running = true;
try {
if ((await this.settings.get('certificateEnabled')) === 'false') return;
const now = new Date();
const rows = await this.prisma.blockchainProof.findMany({
where: { certificateState: { in: ACTIVE_STATES }, certificateNextCheck: { lte: now },
OR: [{ certificateLeaseUntil: null }, { certificateLeaseUntil: { lt: now } }] },
orderBy: { certificateRequestedAt: 'asc' }, take: 5,
});
for (const row of rows) await this.process(row);
} catch {
this.logger.warn('Certificate worker unavailable; persisted requests will be checked again');
} finally { this.running = false; }
}
async process(row: BlockchainProof) {
const now = new Date();
const token = randomUUID();
const submit = row.certificateState === 'PENDING';
const claimed = await this.prisma.blockchainProof.updateMany({
where: { id: row.id, certificateState: row.certificateState,
certificateAttempts: row.certificateAttempts, certificateNextCheck: { lte: now },
OR: [{ certificateLeaseUntil: null }, { certificateLeaseUntil: { lt: now } }] },
data: { certificateState: submit ? 'SUBMITTING' : 'CHECKING', certificateLeaseToken: token,
certificateLeaseUntil: new Date(now.getTime() + 120_000) },
});
if (!claimed.count) return;
const finish = (data: Prisma.BlockchainProofUpdateManyMutationInput) => this.prisma.blockchainProof.updateMany({
where: { id: row.id, certificateLeaseToken: token },
data: { ...data, certificateLeaseUntil: null, certificateLeaseToken: null },
});
const attempts = row.certificateAttempts + 1;
let accepted = false;
try {
const request = row.certificateRequest as unknown as CertificateRequest;
const settings = await this.settings.getAllRaw();
if (!request || request.version !== 1 || settings.blockchainDriver !== 'tianhe' ||
settings.tianheEnv !== request.environment || settings.tianheAppId !== request.appId ||
settings.tianheWalletAddress !== request.address || !settings.tianheAppKey) {
await finish({ certificateState: 'UNKNOWN', certificateError: '存证环境或钱包已变更,请恢复原配置后继续查询', certificateNextCheck: now });
return;
}
const provider = new DepositProvider(request.environment, request.appId, settings.tianheAppKey);
if (submit) {
const current = await this.prisma.traceCode.findUnique({ where: { id: row.traceCodeId }, select: { shortCode: true } });
try { await this.eligible(current?.shortCode || ''); }
catch {
await finish({ certificateState: 'FAILED', certificateError: '实物当前状态不允许出证', certificateNextCheck: null });
return;
}
await provider.submit(request.address, request.operateId, request.text);
accepted = true;
await finish({ certificateState: 'WAITING', certificateError: null, certificateNextCheck: new Date(Date.now() + 5000) });
return;
}
// A crashed/timed-out SUBMITTING job also comes here, never back to submit().
const result = await provider.query(request.address, request.operateId);
const exists = result?.operateId === request.operateId && (Boolean(result?.createTime) || Boolean(result?.txHash));
const url = exists ? await provider.certificate(request.address, request.operateId, request.text) : null;
if (url) {
await finish({ certificateState: 'READY', certificateUrl: url, certificateGeneratedAt: new Date(),
certificateError: null, certificateNextCheck: null, certificateAttempts: attempts });
return;
}
await finish({ certificateState: attempts >= MAX_CHECKS ? 'UNKNOWN' : 'WAITING',
certificateAttempts: attempts, certificateError: '证书尚未就绪,后续仅查询原存证',
certificateNextCheck: new Date(Date.now() + 30_000) });
} catch (error) {
const rejected = submit && !accepted && error instanceof DepositRejected;
await finish({ certificateState: rejected ? 'FAILED' : attempts >= MAX_CHECKS ? 'UNKNOWN' : 'WAITING',
certificateAttempts: attempts, certificateError: rejected ? '存证提交被拒绝,请联系平台管理员' : '远端结果暂未确认,后续仅查询原存证',
certificateNextCheck: new Date(Date.now() + 30_000) });
}
}
}
@@ -0,0 +1,43 @@
import { depositSignature, DepositProvider, DepositRejected, safeCertificateUrl } from './deposit.provider';
import { createHash } from 'crypto';
describe('V3 deposit protocol', () => {
afterEach(() => jest.restoreAllMocks());
it('signs parameters deterministically with the V3 prefix convention', () => {
expect(depositSignature('/v1/deposit/query', { operateId: 'x', address: 'y' }, {}, '1000', 'secret'))
.toBe(depositSignature('/v1/deposit/query', { address: 'y', operateId: 'x' }, {}, '1000', 'secret'));
expect(depositSignature('/v1/deposit/query', { address: 'y' }, {}, '1000', 'secret'))
.not.toBe(depositSignature('/v1/deposit/query', {}, { address: 'y' }, '1000', 'secret'));
});
it('rejects foreign, wrong-environment and credential-bearing certificate URLs', () => {
const suffix = '#/certificate?address=abc&txHash=0x' + 'a'.repeat(64) + '&digest=' + 'b'.repeat(64);
expect(safeCertificateUrl('https://test.tichain.tianhecloud.com/' + suffix, 'test', 'abc')).toBeTruthy();
for (const base of ['https://evil.example/', 'https://tichain.tianhecloud.com/', 'https://user@test.tichain.tianhecloud.com/']) {
expect(safeCertificateUrl(base + suffix, 'test', 'abc')).toBeNull();
}
expect(safeCertificateUrl('https://test.tichain.tianhecloud.com/' + suffix, 'test', 'wrong')).toBeNull();
});
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', '证据'))
.rejects.toThrow('uncertain');
const [url, options] = fetcher.mock.calls[0];
expect(String(url)).toBe('https://test.api.tichain.tianhecloud.com/v1/deposit/text/save');
expect(JSON.stringify(options)).not.toContain('secret');
expect(options?.redirect).toBe('error');
});
it('distinguishes explicit rejection from uncertain transport failure', async () => {
jest.spyOn(global, 'fetch').mockResolvedValue({ ok: true, json: async () => ({ code: 400, success: false }) } as any);
await expect(new DepositProvider('test', 'app', 'key').submit('addr', 'op', 'test')).rejects.toBeInstanceOf(DepositRejected);
});
it('binds the returned certificate to the exact frozen evidence and preserves reserved characters', async () => {
const text = '作品:A&B + 100% #茶器';
const digest = createHash('sha256').update(text).digest('hex');
const value = 'https://test.tichain.tianhecloud.com/#/certificate?depositContent=broken&type=TEXT&address=addr&txHash=0x' + 'a'.repeat(64) + '&digest=' + digest;
jest.spyOn(global, 'fetch').mockResolvedValue({ ok: true, json: async () => ({ code: 200, success: true, data: value }) } as any);
const provider = new DepositProvider('test', 'app', 'key');
const result = await provider.certificate('addr', 'op', text);
expect(new URLSearchParams(new URL(result!).hash.split('?')[1]).get('depositContent')).toBe(text);
await expect(provider.certificate('addr', 'op', 'different evidence')).rejects.toThrow('digest');
});
});
@@ -0,0 +1,90 @@
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<string, unknown>, body: Record<string, unknown>, timestamp: string, key: string): string {
const params: Record<string, unknown> = { 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 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 {}
/** 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<string, string>, body?: Record<string, unknown>): Promise<any> {
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<void> {
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<any> {
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<string | null> {
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();
}
}
+12 -1
View File
@@ -1,4 +1,4 @@
import { Injectable, Logger } from '@nestjs/common';
import { BadRequestException, Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { createCipheriv, createDecipheriv, createHash, randomBytes } from 'crypto';
import { PrismaService } from '../prisma/prisma.service';
@@ -29,6 +29,8 @@ const EDITABLE_KEYS = [
'storageMigrationFingerprint',
'storageMigrationCopied',
'blockchainDriver',
'certificateEnabled',
'certificateDailyLimit',
'tianheEnv',
'tianheBaseUrl',
'tianheAppId',
@@ -89,6 +91,8 @@ export class SettingsService {
ossAccessKeySecret: this.config.get<string>('storage.oss.accessKeySecret') || '',
settingsEncryptionKey: this.config.get<string>('settingsEncryptionKey') || '',
blockchainDriver: this.config.get<string>('blockchain.driver') || 'mock',
certificateEnabled: 'true',
certificateDailyLimit: '100',
tianheEnv: 'test',
tianheBaseUrl: this.config.get<string>('blockchain.tianhe.baseUrl') || 'https://test.api.tichain.tianhecloud.com',
tianheAppId: this.config.get<string>('blockchain.tianhe.appId') || '',
@@ -142,6 +146,13 @@ export class SettingsService {
}
async updateAtomic(values: Record<string, string>): Promise<void> {
if (values.certificateEnabled !== undefined && !['true', 'false'].includes(String(values.certificateEnabled))) {
throw new BadRequestException('Invalid certificate switch');
}
if (values.certificateDailyLimit !== undefined &&
(!/^\d+$/.test(String(values.certificateDailyLimit)) || Number(values.certificateDailyLimit) > 10000)) {
throw new BadRequestException('Certificate daily limit must be between 0 and 10000');
}
const updates: Array<{ key: string; value: string }> = [];
for (const [key, value] of Object.entries(values)) {
if (!EDITABLE_KEYS.includes(key)) continue;