feat: 增加模板预览短期隔离上下文
This commit is contained in:
1 parent
b60174885e
commit
d38dbe02aa
8 files changed
+190
-22
No files matched your search
@@ -1,4 +1,4 @@
|
||||
import { useState } from "react";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { Alert, Collapse, List, Modal, Select, Tag, Typography } from "antd";
|
||||
import type { TemplatePackageVersion } from "@personal-brand/api-client";
|
||||
@@ -29,14 +29,29 @@ export function TemplatePackagePreviewModal({
|
||||
const [page, setPage] = useState("home");
|
||||
const [offeringId, setOfferingId] = useState<string>();
|
||||
const client = createApiClient();
|
||||
// 按 key 保存短期 token,避免 queryFn 引用自身 query 造成循环初始化。
|
||||
const sessionTokens = useRef(new Map<string, string>());
|
||||
const preview = useQuery({
|
||||
queryKey: ["admin-template-package-preview", version.id, industry],
|
||||
queryFn: () => client.previewAdminTemplatePackage(version.id, industry!),
|
||||
queryFn: () =>
|
||||
client.previewAdminTemplatePackage(
|
||||
version.id,
|
||||
industry!,
|
||||
sessionTokens.current.get(industry!),
|
||||
),
|
||||
enabled: Boolean(industry),
|
||||
retry: false,
|
||||
gcTime: 0,
|
||||
});
|
||||
const data = preview.data;
|
||||
useEffect(() => {
|
||||
if (preview.isError) {
|
||||
sessionTokens.current.delete(industry ?? "");
|
||||
}
|
||||
if (data && industry) {
|
||||
sessionTokens.current.set(industry, data.preview.session.token);
|
||||
}
|
||||
}, [data, industry, preview.isError]);
|
||||
return (
|
||||
<Modal
|
||||
title={`${version.displayName} · ${version.version} 版本预览`}
|
||||
|
||||
@@ -59,6 +59,7 @@ export class AdminTemplatePackageController {
|
||||
query.industry,
|
||||
subject,
|
||||
request.headers["x-request-id"]?.toString() ?? request.id,
|
||||
query.session,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Type } from "class-transformer";
|
||||
import { IsInt, IsNotEmpty, IsOptional, IsString, Max, Min } from "class-validator";
|
||||
import { IsInt, IsNotEmpty, IsOptional, IsString, Matches, Max, Min } from "class-validator";
|
||||
|
||||
export class ListTemplatePackagesQueryDto {
|
||||
@IsOptional()
|
||||
@@ -20,4 +20,10 @@ export class PreviewTemplatePackageQueryDto {
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
industry!: string;
|
||||
|
||||
// 短期 session token 是复用隔离预览数据的 capability,不是全局可重放凭据。
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@Matches("^[a-f0-9]{64}$")
|
||||
session?: string;
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { BadRequestException, ConflictException, Injectable } from "@nestjs/common";
|
||||
import { randomBytes } from "node:crypto";
|
||||
import {
|
||||
capabilityRegistry,
|
||||
getBrandTemplate,
|
||||
@@ -74,7 +75,95 @@ export class AdminTemplatePreviewService {
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly assets: AdminTemplatePreviewAssetsService,
|
||||
) {}
|
||||
async preview(id: string, industry: string, actorId: string, requestId?: string) {
|
||||
private readonly previewSessions = new Map<
|
||||
string,
|
||||
{
|
||||
versionId: string;
|
||||
industry: string;
|
||||
actorId: string;
|
||||
expiresAt: number;
|
||||
response: Awaited<ReturnType<AdminTemplatePreviewService["buildPreview"]>>;
|
||||
}
|
||||
>();
|
||||
|
||||
async preview(
|
||||
id: string,
|
||||
industry: string,
|
||||
actorId: string,
|
||||
requestId?: string,
|
||||
sessionToken?: string,
|
||||
) {
|
||||
if (sessionToken) {
|
||||
const session = this.previewSessions.get(sessionToken);
|
||||
if (!session || session.expiresAt <= Date.now()) {
|
||||
this.previewSessions.delete(sessionToken);
|
||||
throw new BadRequestException("预览 session 不存在或已过期,请重新创建预览");
|
||||
}
|
||||
if (
|
||||
session.actorId !== actorId ||
|
||||
session.versionId !== id ||
|
||||
session.industry !== industry
|
||||
) {
|
||||
throw new BadRequestException("预览 session 与版本、行业或管理员不匹配");
|
||||
}
|
||||
return {
|
||||
...session.response,
|
||||
preview: {
|
||||
...session.response.preview,
|
||||
session: {
|
||||
token: sessionToken,
|
||||
expiresAt: new Date(session.expiresAt).toISOString(),
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const projection = await this.buildPreview(id, industry);
|
||||
this.cleanupPreviewSessions();
|
||||
const token = randomBytes(32).toString("hex");
|
||||
const expiresAt = Date.now() + 15 * 60 * 1000;
|
||||
this.previewSessions.set(token, {
|
||||
versionId: projection.template.id,
|
||||
industry,
|
||||
actorId,
|
||||
expiresAt,
|
||||
response: projection,
|
||||
});
|
||||
while (this.previewSessions.size > 20) {
|
||||
const oldest = this.previewSessions.keys().next().value;
|
||||
if (!oldest) break;
|
||||
this.previewSessions.delete(oldest);
|
||||
}
|
||||
await this.prisma.templatePackageAuditLog.create({
|
||||
data: {
|
||||
templatePackageVersionId: projection.template.id,
|
||||
actorId,
|
||||
action: "previewed",
|
||||
...(requestId ? { requestId } : {}),
|
||||
metadata: {
|
||||
industry,
|
||||
contentChecksum: projection.template.contentChecksum,
|
||||
fixtureSource: projection.preview.fixtureSource,
|
||||
},
|
||||
},
|
||||
});
|
||||
return {
|
||||
...projection,
|
||||
preview: {
|
||||
...projection.preview,
|
||||
session: { token, expiresAt: new Date(expiresAt).toISOString() },
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
private cleanupPreviewSessions() {
|
||||
const now = Date.now();
|
||||
for (const [token, session] of this.previewSessions) {
|
||||
if (session.expiresAt <= now) this.previewSessions.delete(token);
|
||||
}
|
||||
}
|
||||
|
||||
private async buildPreview(id: string, industry: string) {
|
||||
const version = await this.prisma.templatePackageVersion.findUnique({ where: { id } });
|
||||
if (!version) throw new BadRequestException("模板版本不存在");
|
||||
if (version.status === "retired") throw new ConflictException("已撤回的模板版本不能创建新预览");
|
||||
@@ -199,19 +288,6 @@ export class AdminTemplatePreviewService {
|
||||
sample!,
|
||||
fixture?.brand,
|
||||
);
|
||||
await this.prisma.templatePackageAuditLog.create({
|
||||
data: {
|
||||
templatePackageVersionId: version.id,
|
||||
actorId,
|
||||
action: "previewed",
|
||||
...(requestId ? { requestId } : {}),
|
||||
metadata: {
|
||||
industry,
|
||||
contentChecksum: version.contentChecksum,
|
||||
fixtureSource: fixtureDeclared ? "previewFixture" : "legacy-sampleContent",
|
||||
},
|
||||
},
|
||||
});
|
||||
return {
|
||||
template: {
|
||||
id: version.id,
|
||||
|
||||
@@ -298,6 +298,58 @@ test("平台模板管理员可以按行业预览版本,且预览不写入品
|
||||
fixtureSource: "previewFixture",
|
||||
});
|
||||
assert.ok(event.actor.id);
|
||||
|
||||
// Preview session 只复用同一管理员、同一版本和行业的已构建投影;复用不产生第二条预览审计。
|
||||
assert.match(body.preview.session.token, /^[a-f0-9]{64}$/);
|
||||
const anotherTemplateAdmin = await prisma.adminUser.create({
|
||||
data: {
|
||||
username: `preview-session-${randomUUID()}`,
|
||||
passwordHash: "unused",
|
||||
displayName: "另一位模板管理员",
|
||||
platformTemplateRole: "template_admin",
|
||||
},
|
||||
});
|
||||
const anotherHeaders = {
|
||||
authorization: `Bearer ${signIdentity({
|
||||
subject: anotherTemplateAdmin.id,
|
||||
brandId,
|
||||
role: "admin",
|
||||
})}`,
|
||||
};
|
||||
try {
|
||||
const auditCount = await prisma.templatePackageAuditLog.count({
|
||||
where: { templatePackageVersionId: versionId, action: "previewed" },
|
||||
});
|
||||
const mismatchedActor = await request(
|
||||
`/admin/templates/${versionId}/preview?industry=personal&session=${body.preview.session.token}`,
|
||||
{ headers: anotherHeaders },
|
||||
);
|
||||
assert.equal(mismatchedActor.statusCode, 400, mismatchedActor.body);
|
||||
assert.match(JSON.parse(mismatchedActor.body).error.message, /不匹配/);
|
||||
const reused = await request(
|
||||
`/admin/templates/${versionId}/preview?industry=personal&session=${body.preview.session.token}`,
|
||||
{ headers },
|
||||
);
|
||||
assert.equal(reused.statusCode, 200, reused.body);
|
||||
const reusedBody = JSON.parse(reused.body);
|
||||
assert.equal(reusedBody.preview.session.token, body.preview.session.token);
|
||||
assert.deepEqual(reusedBody.workspace.brand, body.workspace.brand);
|
||||
assert.equal(
|
||||
await prisma.templatePackageAuditLog.count({
|
||||
where: { templatePackageVersionId: versionId, action: "previewed" },
|
||||
}),
|
||||
auditCount,
|
||||
);
|
||||
const unknownSession = await request(
|
||||
`/admin/templates/${versionId}/preview?industry=personal&session=${"0".repeat(64)}`,
|
||||
{ headers },
|
||||
);
|
||||
assert.equal(unknownSession.statusCode, 400, unknownSession.body);
|
||||
assert.match(JSON.parse(unknownSession.body).error.message, /不存在或已过期/);
|
||||
} finally {
|
||||
await prisma.adminUser.delete({ where: { id: anotherTemplateAdmin.id } });
|
||||
}
|
||||
|
||||
const stored = await prisma.templatePackageVersion.findUniqueOrThrow({
|
||||
where: { id: versionId },
|
||||
});
|
||||
|
||||
Reference in new issue
Block a user