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 },
|
||||
});
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
> 任务 ID:TMP-PLATFORM-001
|
||||
>
|
||||
> 状态:实施中,Phase 0/1/2 已完成,Phase 3 已接入版本预览、独立 fixture 和包内图片校验,隔离上下文与完整矩阵仍待验收
|
||||
> 状态:实施中,Phase 0/1/2 已完成,Phase 3 已接入版本预览、独立 fixture、包内图片校验和短期隔离 session;origin/CSP、CTA 导航、完整矩阵与最终视觉验收待完成
|
||||
>
|
||||
> 唯一任务入口:本文档
|
||||
>
|
||||
@@ -393,7 +393,7 @@ Phase 2 当前进度(2026-10-16):
|
||||
|
||||
### Phase 3:独立预览和模板管理页面
|
||||
|
||||
- [ ] 增加 preview session 或同等短期隔离上下文;
|
||||
- [x] 增加 preview session 或同等短期隔离上下文;
|
||||
- [ ] 按行业选择兼容组合,使用 preview fixture 通过真实 Runtime projection 渲染;
|
||||
- [ ] 页面展示模块顺序、字段来源、资源缺失、能力依赖和诊断;
|
||||
- [ ] 预览禁止真实咨询、客户记录、品牌发布和上传;
|
||||
@@ -427,6 +427,14 @@ Phase 3 独立 fixture 与资源进展(2026-10-16):
|
||||
- 自动化新增独立 fixture 与 bootstrap 解耦、无效安全策略导入拒绝、敏感身份字段拒绝、兼容来源标识、archive 漂移阻断及图片类型/体积/摘要故障回归。API HTTP integration `52/52`、upload `2/2`、API unit `51/51`、Client/Admin unit 各 `6/6`、真实包图片浏览器交互 `1/1` 通过;typecheck、Admin production build、变更范围 lint 和 `template:check` 通过。
|
||||
- 仍待推进:预览上下文与 origin/CSP 隔离、画布内 CTA 导航、跨模板/行业/版本完整矩阵和最终视觉验收。前述初版实现记录中的 fixture 与包内资源缺口由本段更新,其余阶段门禁不变。
|
||||
|
||||
Phase 3 短期隔离 session 进展(2026-10-16):
|
||||
|
||||
- 预览响应新增 `preview.session`;首次预览生成 64 位十六进制短期 token,有效期 15 分钟。`GET /admin/templates/:id/preview` 支持 `session` 查询参数,DTO 仅接受预期格式。
|
||||
- 服务端 session 只在 API 进程内存中保存已构建投影,上限 20 个并主动清理过期项;每次复用必须匹配同一平台模板管理员、版本 ID 和行业。因此 token 不是跨管理员可重放凭据,不同版本/行业/管理员不会串数据。
|
||||
- 带 session 的成功复用不重复读取 archive,也不重复写 `previewed` 审计;不存在、过期或绑定不匹配返回可操作的 `400`,管理员可重新创建预览。
|
||||
- Admin 预览按版本和行业保留短期 token 供失败重试复用;请求失败时删除对应 token,行业/版本选择和业务记录选择仍保留。
|
||||
- 自动化覆盖 session 成功复用、复用不新增审计、跨管理员拒绝、未知 token 拒绝、版本/行业绑定、shared client URL 和 Admin 重试上下文。本轮 API HTTP integration `52/52`、upload `2/2`、Client `6/6`、Admin unit `3/3` 和全仓 typecheck 通过;origin/CSP 隔离与最终矩阵验收仍待完成。
|
||||
|
||||
### Phase 4:品牌安装、bootstrap 和发布
|
||||
|
||||
- [ ] 区分行业安装和视觉包安装,保存精确版本与 checksum 快照;
|
||||
|
||||
@@ -16,7 +16,11 @@ export interface TemplateMethods {
|
||||
publishAdminTemplatePackage(id: string): Promise<TemplatePackageActionResult>;
|
||||
retireAdminTemplatePackage(id: string): Promise<TemplatePackageActionResult>;
|
||||
listAdminTemplatePackageAudit(id: string): Promise<TemplatePackageAuditEntry[]>;
|
||||
previewAdminTemplatePackage(id: string, industry: string): Promise<TemplatePackagePreview>;
|
||||
previewAdminTemplatePackage(
|
||||
id: string,
|
||||
industry: string,
|
||||
session?: string,
|
||||
): Promise<TemplatePackagePreview>;
|
||||
getPublicTemplate(key: BrandTemplateKey): Promise<BrandTemplateDefinition>;
|
||||
listPublicTemplates(): Promise<{
|
||||
industries: BrandTemplateDefinition[];
|
||||
@@ -137,6 +141,7 @@ export interface TemplatePackagePreview {
|
||||
assetFiles: Record<string, { sha256: string; dataUrl: string }>;
|
||||
fixtureSource: "previewFixture" | "legacy-sampleContent";
|
||||
safety: { submissions: "disabled"; customerRecords: "disabled"; contactActions: "disabled" };
|
||||
session: { token: string; expiresAt: string };
|
||||
diagnostics: Array<{ code: string; severity: "warning"; message: string }>;
|
||||
pages: Array<{
|
||||
key: string;
|
||||
@@ -224,9 +229,9 @@ export function templateMethods({ request }: { request: RequestFn }): TemplateMe
|
||||
request(`/admin/templates/${encodeURIComponent(id)}/retire`, { method: "POST" }),
|
||||
listAdminTemplatePackageAudit: (id) =>
|
||||
request(`/admin/templates/${encodeURIComponent(id)}/audit`),
|
||||
previewAdminTemplatePackage: (id, industry) =>
|
||||
previewAdminTemplatePackage: (id, industry, session) =>
|
||||
request(
|
||||
`/admin/templates/${encodeURIComponent(id)}/preview?industry=${encodeURIComponent(industry)}`,
|
||||
`/admin/templates/${encodeURIComponent(id)}/preview?industry=${encodeURIComponent(industry)}${session ? `&session=${encodeURIComponent(session)}` : ""}`,
|
||||
),
|
||||
getPublicTemplate: (key) => request(`/public/templates/${key}`),
|
||||
listPublicTemplates: () =>
|
||||
|
||||
@@ -116,6 +116,7 @@ test("模板目录客户端发送分页并支持版本发布和审计", async ()
|
||||
await client.publishAdminTemplatePackage("version/1");
|
||||
await client.listAdminTemplatePackageAudit("version/1");
|
||||
await client.previewAdminTemplatePackage("version/1", "personal & design");
|
||||
await client.previewAdminTemplatePackage("version/1", "personal & design", "1".repeat(64));
|
||||
assert.deepEqual(calls, [
|
||||
{ url: "http://api.test/admin/templates?page=2&pageSize=10", method: "GET" },
|
||||
{ url: "http://api.test/admin/templates/version%2F1/publish", method: "POST" },
|
||||
@@ -124,5 +125,9 @@ test("模板目录客户端发送分页并支持版本发布和审计", async ()
|
||||
url: "http://api.test/admin/templates/version%2F1/preview?industry=personal%20%26%20design",
|
||||
method: "GET",
|
||||
},
|
||||
{
|
||||
url: "http://api.test/admin/templates/version%2F1/preview?industry=personal%20%26%20design&session=1111111111111111111111111111111111111111111111111111111111111111",
|
||||
method: "GET",
|
||||
},
|
||||
]);
|
||||
});
|
||||
Reference in new issue
Block a user