feat: 追溯码客户端预览(TOTP式令牌保护,不激活不计数,可切换激活状态预览)
This commit is contained in:
@@ -0,0 +1,34 @@
|
||||
import { currentPreviewToken, isValidPreviewToken, PREVIEW_PERIOD_MS } from './preview-token.util';
|
||||
|
||||
describe('preview-token.util', () => {
|
||||
const secret = 'test-secret';
|
||||
const now = 1_800_000_000_000;
|
||||
|
||||
it('当前窗口令牌有效', () => {
|
||||
const token = currentPreviewToken(secret, now);
|
||||
expect(isValidPreviewToken(secret, token, now)).toBe(true);
|
||||
});
|
||||
|
||||
it('上一窗口令牌在宽限期内有效', () => {
|
||||
const prevToken = currentPreviewToken(secret, now - PREVIEW_PERIOD_MS);
|
||||
expect(prevToken).not.toBe(currentPreviewToken(secret, now));
|
||||
expect(isValidPreviewToken(secret, prevToken, now)).toBe(true);
|
||||
});
|
||||
|
||||
it('更早窗口令牌失效', () => {
|
||||
const oldToken = currentPreviewToken(secret, now - 2 * PREVIEW_PERIOD_MS);
|
||||
expect(isValidPreviewToken(secret, oldToken, now)).toBe(false);
|
||||
});
|
||||
|
||||
it('空/畸形/错误密钥令牌失效', () => {
|
||||
expect(isValidPreviewToken(secret, undefined, now)).toBe(false);
|
||||
expect(isValidPreviewToken(secret, '', now)).toBe(false);
|
||||
expect(isValidPreviewToken(secret, 'short', now)).toBe(false);
|
||||
expect(isValidPreviewToken(secret, currentPreviewToken('other-secret', now), now)).toBe(false);
|
||||
});
|
||||
|
||||
it('同窗口内令牌稳定,跨窗口轮换', () => {
|
||||
expect(currentPreviewToken(secret, now)).toBe(currentPreviewToken(secret, now + PREVIEW_PERIOD_MS - 1));
|
||||
expect(currentPreviewToken(secret, now)).not.toBe(currentPreviewToken(secret, now + PREVIEW_PERIOD_MS));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,28 @@
|
||||
import { createHmac, timingSafeEqual } from 'crypto';
|
||||
|
||||
// 追溯码预览令牌:类 TOTP 的时间窗口 HMAC 令牌。
|
||||
// 周期 10 分钟;校验时接受「当前窗口 + 上一窗口」,即令牌实际有效 10~20 分钟。
|
||||
// 无状态(不落库/不进 Redis),密钥复用 JWT_SECRET,后台随取随用、自动随时间轮换,
|
||||
// 防止预览地址被打印/转发后长期有效。
|
||||
export const PREVIEW_PERIOD_MS = 600_000;
|
||||
const TOKEN_HEX_LEN = 16;
|
||||
|
||||
function tokenForWindow(secret: string, window: number): string {
|
||||
return createHmac('sha256', secret).update(`preview:${window}`).digest('hex').slice(0, TOKEN_HEX_LEN);
|
||||
}
|
||||
|
||||
export function currentPreviewToken(secret: string, now = Date.now()): string {
|
||||
return tokenForWindow(secret, Math.floor(now / PREVIEW_PERIOD_MS));
|
||||
}
|
||||
|
||||
export function isValidPreviewToken(secret: string, token: string | undefined, now = Date.now()): boolean {
|
||||
if (!token || token.length !== TOKEN_HEX_LEN) return false;
|
||||
const window = Math.floor(now / PREVIEW_PERIOD_MS);
|
||||
const provided = Buffer.from(token, 'utf8');
|
||||
// 当前窗口 + 上一窗口(宽限期),常量时间比较防时序侧信道
|
||||
for (const w of [window, window - 1]) {
|
||||
const expected = Buffer.from(tokenForWindow(secret, w), 'utf8');
|
||||
if (provided.length === expected.length && timingSafeEqual(provided, expected)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -1,9 +1,11 @@
|
||||
import { Controller, Get, Param, Req, Res } from '@nestjs/common';
|
||||
import { Controller, Get, Param, Query, Req, Res } from '@nestjs/common';
|
||||
import { Request, Response } from 'express';
|
||||
import { ApiOperation, ApiTags } from '@nestjs/swagger';
|
||||
import { Throttle } from '@nestjs/throttler';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { Public } from '../common/decorators/public.decorator';
|
||||
import { extractIp } from '../common/utils/ua.util';
|
||||
import { isValidPreviewToken } from '../common/utils/preview-token.util';
|
||||
import { PublicTraceService } from './public-trace.service';
|
||||
import { SettingsService } from '../settings/settings.service';
|
||||
|
||||
@@ -13,6 +15,7 @@ export class PublicTraceController {
|
||||
constructor(
|
||||
private readonly service: PublicTraceService,
|
||||
private readonly settings: SettingsService,
|
||||
private readonly config: ConfigService,
|
||||
) {}
|
||||
|
||||
@Public()
|
||||
@@ -26,6 +29,22 @@ export class PublicTraceController {
|
||||
return this.service.trace(shortCode, { ip, userAgent });
|
||||
}
|
||||
|
||||
// 后台预览:凭时间令牌访问,零副作用(不激活/不计数/不写日志)。令牌过期返回 PREVIEW_EXPIRED。
|
||||
@Public()
|
||||
@Get('public/trace/:shortCode/preview')
|
||||
@Throttle({ default: { limit: 60, ttl: 60_000 } })
|
||||
@ApiOperation({ summary: 'C 端溯源预览(令牌保护,不激活不计数)' })
|
||||
preview(
|
||||
@Param('shortCode') shortCode: string,
|
||||
@Query('token') token?: string,
|
||||
@Query('state') state?: string,
|
||||
) {
|
||||
if (!isValidPreviewToken(this.config.get<string>('jwt.secret') || '', token)) {
|
||||
return { status: 'PREVIEW_EXPIRED' as const };
|
||||
}
|
||||
return this.service.preview(shortCode, state === 'active' ? 'active' : 'inactive');
|
||||
}
|
||||
|
||||
// 短链跳转:扫码打开 /t/:shortCode -> 重定向到 C 端溯源页(不在 /api 前缀下)
|
||||
@Public()
|
||||
@Get('t/:shortCode')
|
||||
|
||||
@@ -8,6 +8,13 @@ import { REDIS_CLIENT } from '../redis/redis.module';
|
||||
import { parseUserAgent } from '../common/utils/ua.util';
|
||||
|
||||
type TraceCodeWithRel = Prisma.TraceCodeGetPayload<{ include: { batch: true; artwork: true } }>;
|
||||
type ArtworkWithRel = Prisma.ArtworkGetPayload<{
|
||||
include: {
|
||||
template: { include: { fields: true } };
|
||||
traceNodes: true;
|
||||
certificates: true;
|
||||
};
|
||||
}>;
|
||||
|
||||
export interface TraceContext {
|
||||
ip: string;
|
||||
@@ -186,6 +193,81 @@ export class PublicTraceService {
|
||||
queryCount: updated.queryCount,
|
||||
firstActivatedAt: updated.firstActivatedAt,
|
||||
},
|
||||
...this.buildArtworkPayload(artwork, code, proof),
|
||||
};
|
||||
}
|
||||
|
||||
// 后台预览:与 trace() 相同的数据组装,但零副作用——不激活、不计数、不写查询日志。
|
||||
// state 决定防伪区块以「首次扫码」还是「重复访问」形态展示,antiCounterfeit 数值为演示占位/库中现值。
|
||||
async preview(shortCode: string, state: 'inactive' | 'active') {
|
||||
if (!TRACE_CODE_PATTERN.test(shortCode)) return { status: 'INVALID' as const };
|
||||
const id = await this.resolveId(shortCode);
|
||||
if (id === null) return { status: 'INVALID' as const };
|
||||
|
||||
const code = await this.prisma.traceCode.findUnique({
|
||||
where: { id },
|
||||
include: { batch: true, artwork: true },
|
||||
});
|
||||
if (!code) return { status: 'INVALID' as const };
|
||||
if (code.status === TraceCodeStatus.DISABLED) return { status: 'DISABLED' as const };
|
||||
if (code.status === TraceCodeStatus.ABNORMAL) return { status: 'ABNORMAL' as const };
|
||||
|
||||
const artwork = await this.prisma.artwork.findFirst({
|
||||
where: { id: code.artworkId, deletedAt: null },
|
||||
include: {
|
||||
template: { include: { fields: { orderBy: { sortOrder: 'asc' } } } },
|
||||
traceNodes: { orderBy: { sortOrder: 'asc' } },
|
||||
certificates: { orderBy: { id: 'asc' } },
|
||||
},
|
||||
});
|
||||
if (
|
||||
!artwork ||
|
||||
artwork.status === ArtworkStatus.DISABLED ||
|
||||
artwork.auditStatus !== AuditStatus.APPROVED
|
||||
) {
|
||||
return { status: 'INVALID' as const };
|
||||
}
|
||||
|
||||
const proof = await this.prisma.blockchainProof.findFirst({
|
||||
where: { traceCodeId: id, status: ProofStatus.ONCHAIN },
|
||||
orderBy: { id: 'desc' },
|
||||
});
|
||||
|
||||
const now = new Date();
|
||||
const firstQuery = state === 'inactive';
|
||||
return {
|
||||
status: 'OK' as const,
|
||||
preview: true,
|
||||
code: code.code,
|
||||
queriedAt: now,
|
||||
antiCounterfeit: firstQuery
|
||||
? { firstQuery: true, queryCount: 1, firstActivatedAt: now }
|
||||
: {
|
||||
firstQuery: false,
|
||||
queryCount: code.queryCount > 0 ? code.queryCount : 2,
|
||||
firstActivatedAt: code.firstActivatedAt ?? now,
|
||||
},
|
||||
...this.buildArtworkPayload(artwork, code, proof),
|
||||
};
|
||||
}
|
||||
|
||||
// trace/preview 共用的作品展示数据(作品信息 / 时间线 / 证书 / 区块链存证)
|
||||
private buildArtworkPayload(
|
||||
artwork: ArtworkWithRel,
|
||||
code: { outTime?: Date | null; outImages?: unknown },
|
||||
proof: {
|
||||
txHash: string | null;
|
||||
dataHash: string;
|
||||
blockHash: string | null;
|
||||
blockHeight: bigint | null;
|
||||
chainName: string | null;
|
||||
onchainAt: Date | null;
|
||||
explorerUrl: string | null;
|
||||
tokenId: bigint | null;
|
||||
contractAddress: string | null;
|
||||
} | null,
|
||||
) {
|
||||
return {
|
||||
artwork: {
|
||||
title: artwork.title,
|
||||
artist: artwork.artist,
|
||||
|
||||
@@ -62,6 +62,15 @@ export class SettingsController {
|
||||
return { userId, address, userKeyMasked: this.settingsService.maskSecretPublic(userKey) };
|
||||
}
|
||||
|
||||
@ApiBearerAuth()
|
||||
@Roles(RoleType.SUPER_ADMIN)
|
||||
@Post('tianhe/app-key/reveal')
|
||||
@ApiOperation({ summary: '查看天河链 App Key 掩码(仅返回掩码,不返回明文);用 POST 以便写入操作日志' })
|
||||
async revealTianheAppKey() {
|
||||
const all = await this.settingsService.getAllRaw();
|
||||
return { appKeyMasked: this.settingsService.maskSecretPublic(all.tianheAppKey || '') };
|
||||
}
|
||||
|
||||
@ApiBearerAuth()
|
||||
@Roles(RoleType.SUPER_ADMIN)
|
||||
@Post('tianhe/identity/reveal')
|
||||
|
||||
@@ -11,9 +11,12 @@ import {
|
||||
Res,
|
||||
} from '@nestjs/common';
|
||||
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { Response } from 'express';
|
||||
import { RoleType } from '@artveris/shared';
|
||||
import { TraceCodeService } from './trace-code.service';
|
||||
import { SettingsService } from '../settings/settings.service';
|
||||
import { currentPreviewToken, PREVIEW_PERIOD_MS } from '../common/utils/preview-token.util';
|
||||
import {
|
||||
BatchDeleteDto,
|
||||
BatchGroupDto,
|
||||
@@ -34,7 +37,23 @@ import { parseBigId } from '../common/utils/bigint.util';
|
||||
@ApiBearerAuth()
|
||||
@Controller()
|
||||
export class TraceCodeController {
|
||||
constructor(private readonly service: TraceCodeService) {}
|
||||
constructor(
|
||||
private readonly service: TraceCodeService,
|
||||
private readonly settings: SettingsService,
|
||||
private readonly config: ConfigService,
|
||||
) {}
|
||||
|
||||
// 预览令牌:类 TOTP,随时间自动轮换(当前+上一窗口有效)。后台点开预览页时随取随用,
|
||||
// 预览地址外泄后最长 2 个周期即失效,无法长期传播。
|
||||
@Get('trace-codes/preview-token')
|
||||
@ApiOperation({ summary: '获取 C 端预览令牌(自动轮换)' })
|
||||
async previewToken() {
|
||||
return {
|
||||
token: currentPreviewToken(this.config.get<string>('jwt.secret') || ''),
|
||||
clientBase: await this.settings.getClientBaseUrl(),
|
||||
periodMs: PREVIEW_PERIOD_MS,
|
||||
};
|
||||
}
|
||||
|
||||
@Post('trace-codes/batch')
|
||||
@Roles(RoleType.OPERATOR)
|
||||
|
||||
Reference in New Issue
Block a user