feat: 分离模板演示数据并校验预览资源

This commit is contained in:
que01 committed 2026-10-16 17:55:52 +08:00
1 parent 6edde5a8d6
commit b60174885e
31 files changed
+1785 -69

No files matched your search

@@ -48,10 +48,17 @@ export class AdminTemplatePackageController {
}
@Get(":id/preview")
preview(
async preview(
@Req() request: FastifyRequest,
@Param("id") id: string,
@Query() query: PreviewTemplatePackageQueryDto,
): ReturnType<AdminTemplatePreviewService["preview"]> {
return this.previews.preview(id, query.industry);
const { subject } = await this.access.requireTemplateAdmin(request);
return this.previews.preview(
id,
query.industry,
subject,
request.headers["x-request-id"]?.toString() ?? request.id,
);
}
}
@@ -5,6 +5,8 @@ import {
PayloadTooLargeException,
} from "@nestjs/common";
import { validateTemplatePackageManifest } from "@personal-brand/config";
import { validateTemplatePreviewFixtures } from "@personal-brand/validation";
import type { Prisma } from "@prisma/client";
import type { FastifyRequest } from "fastify";
import { createHash } from "node:crypto";
import { execFile } from "node:child_process";
@@ -24,6 +26,8 @@ type Manifest = {
version: string;
displayName: string;
visualTemplateKey?: string;
supportedIndustryTemplates?: string[];
previewFixture?: Prisma.InputJsonValue;
};
type ChecksumFile = {
@@ -419,6 +423,16 @@ export class AdminTemplatePackageService {
}
if (errors.length)
throw new BadRequestException(`template.json 不符合模板契约:${errors.join(";")}`);
if (manifest.previewFixture !== undefined) {
const issues = validateTemplatePreviewFixtures(
manifest.previewFixture,
manifest.supportedIndustryTemplates ?? [],
);
if (issues.length)
throw new BadRequestException(
`previewFixture 不符合预览契约:${issues.map((issue) => `${issue.path}: ${issue.message}`).join(";")}`,
);
}
if (
checksums.formatVersion !== "1" ||
checksums.packageKey !== manifest.packageKey ||
@@ -0,0 +1,104 @@
import { ConflictException, Injectable } from "@nestjs/common";
import { createHash } from "node:crypto";
import { execFile } from "node:child_process";
import { readFile, stat } from "node:fs/promises";
import { promisify } from "node:util";
const run = promisify(execFile);
const MAX_IMAGE_BYTES = 2 * 1024 * 1024;
const MAX_PREVIEW_BYTES = 8 * 1024 * 1024;
const digest = (content: Buffer) => createHash("sha256").update(content).digest("hex");
function imageMime(content: Buffer): string | undefined {
if (content.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])))
return "image/png";
if (content[0] === 255 && content[1] === 216 && content[2] === 255) return "image/jpeg";
if (["GIF87a", "GIF89a"].includes(content.subarray(0, 6).toString())) return "image/gif";
if (content.subarray(0, 4).toString() === "RIFF" && content.subarray(8, 12).toString() === "WEBP")
return "image/webp";
return undefined;
}
@Injectable()
export class AdminTemplatePreviewAssetsService {
async read(version: { artifactPath: string; archiveChecksum: string; contentChecksum: string }) {
const files: Record<string, { sha256: string; dataUrl: string }> = {};
const diagnostics: Array<{ code: string; severity: "warning"; message: string }> = [];
try {
// 只读取已通过导入门禁且摘要一致的 archive,不执行源码,也不解压到公开目录。
if ((await stat(version.artifactPath)).size > 50 * 1024 * 1024)
throw new Error("Archive size");
if (digest(await readFile(version.artifactPath)) !== version.archiveChecksum)
throw new Error("Archive checksum");
const { stdout: listing } = await run("tar", ["-tzf", version.artifactPath], {
maxBuffer: 4 * 1024 * 1024,
timeout: 10000,
});
const root = listing.split("\n")[0]?.split("/")[0];
if (!root || !/^[a-zA-Z0-9._-]+$/.test(root)) throw new Error("Archive root");
const readEntry = async (path: string, limit: number) => {
const result = await run("tar", ["-xOzf", version.artifactPath, "--", `${root}/${path}`], {
encoding: "buffer",
maxBuffer: limit,
timeout: 10000,
});
return result.stdout;
};
const checksums = JSON.parse(
(await readEntry("checksums.json", 2 * 1024 * 1024)).toString(),
) as {
contentChecksum: string;
files: Array<{ path: string; bytes: number; sha256: string }>;
};
if (checksums.contentChecksum !== version.contentChecksum || !Array.isArray(checksums.files))
throw new Error("Content checksum");
let totalBytes = 0;
let imageCount = 0;
for (const entry of checksums.files) {
if (
!/^miniapp\/assets\/(?:[a-zA-Z0-9_-]+\/)*[a-zA-Z0-9_.-]+\.(?:png|jpe?g|webp|gif)$/i.test(
entry.path,
)
)
continue;
const key = entry.path.slice("miniapp".length);
if (++imageCount > 128) {
diagnostics.push({
code: "PREVIEW_ASSET_COUNT",
severity: "warning",
message: "包内图片超过 128 个,请拆分或精简预览资源。",
});
break;
}
if (entry.bytes > MAX_IMAGE_BYTES || totalBytes + entry.bytes > MAX_PREVIEW_BYTES) {
diagnostics.push({
code: "PREVIEW_ASSET_LIMIT",
severity: "warning",
message: `资源 ${key} 超出预览体积限制,请缩小图片。`,
});
continue;
}
const content = await readEntry(entry.path, MAX_IMAGE_BYTES);
if (content.length !== entry.bytes || digest(content) !== entry.sha256)
throw new Error("Asset checksum");
const mime = imageMime(content);
if (!mime) {
diagnostics.push({
code: "PREVIEW_ASSET_TYPE",
severity: "warning",
message: `资源 ${key} 不是受支持的图片。`,
});
continue;
}
totalBytes += content.length;
files[key] = {
sha256: entry.sha256,
dataUrl: `data:${mime};base64,${content.toString("base64")}`,
};
}
return { files, diagnostics };
} catch {
throw new ConflictException("模板预览资源不可读取或摘要不一致,请检查已导入的模板包存储");
}
}
}
@@ -7,11 +7,16 @@ import {
getVisualTemplateManifest,
validateTemplatePackageManifest,
} from "@personal-brand/config";
import type { TemplatePackageManifest, TemplateSampleContent } from "@personal-brand/config";
import { validateFieldSnapshot } from "@personal-brand/validation";
import type {
TemplatePackageManifest,
TemplatePreviewFixture,
TemplateSampleContent,
} from "@personal-brand/config";
import { validateFieldSnapshot, validateTemplatePreviewFixture } from "@personal-brand/validation";
import type { BrandReleaseSnapshot } from "../../brand-release.service.js";
import { PrismaService } from "../../prisma.service.js";
import { assemblePublicWorkspace } from "../public/public-workspace.snapshot-assembler.js";
import { AdminTemplatePreviewAssetsService } from "./admin-template-preview-assets.service.js";
function record(value: unknown): Record<string, unknown> {
return value && typeof value === "object" && !Array.isArray(value)
@@ -45,6 +50,11 @@ function hasPreviewStructure(manifest: Record<string, unknown>): boolean {
) &&
records(manifest.navigation) &&
manifest.navigation.every((tab) => strings(tab, ["key", "label", "page"])) &&
records(manifest.assetSlots) &&
manifest.assetSlots.every(
(slot) =>
strings(slot, ["key", "label", "binding", "target"]) && typeof slot.required === "boolean",
) &&
records(record(manifest.admin).sections) &&
(record(manifest.admin).sections as Record<string, unknown>[]).every(
(section) => strings(section, ["key", "target"]) && fields(section.fields),
@@ -60,8 +70,11 @@ function hasPreviewStructure(manifest: Record<string, unknown>): boolean {
@Injectable()
export class AdminTemplatePreviewService {
constructor(private readonly prisma: PrismaService) {}
async preview(id: string, industry: string) {
constructor(
private readonly prisma: PrismaService,
private readonly assets: AdminTemplatePreviewAssetsService,
) {}
async preview(id: string, industry: string, actorId: string, requestId?: string) {
const version = await this.prisma.templatePackageVersion.findUnique({ where: { id } });
if (!version) throw new BadRequestException("模板版本不存在");
if (version.status === "retired") throw new ConflictException("已撤回的模板版本不能创建新预览");
@@ -119,12 +132,28 @@ export class AdminTemplatePreviewService {
) {
blockers.push("模板依赖的 capability 与所选行业不兼容");
}
if (blockers.length) throw new BadRequestException(`模板预览被阻断:${blockers.join(";")}`);
const sample = record(rawManifest.sampleContent)[industry] as TemplateSampleContent | undefined;
const fixtureDeclared = rawManifest.previewFixture !== undefined;
const fixture = record(rawManifest.previewFixture)[industry] as
TemplatePreviewFixture | undefined;
if (fixtureDeclared) {
const issues = validateTemplatePreviewFixture(fixture);
if (issues.length)
throw new BadRequestException(
`模板 previewFixture 不符合预览契约:${issues.map((issue) => `${issue.path}: ${issue.message}`).join(";")}`,
);
}
// 一旦包声明独立 fixture,缺失或无效时禁止偷偷回退到 bootstrap sample。
const sample = fixtureDeclared
? fixture!.content
: (record(rawManifest.sampleContent)[industry] as TemplateSampleContent | undefined);
const missingSampleSlots = this.missingSampleSlots(manifest, sample);
if (missingSampleSlots.length)
blockers.push(`preview sample 缺少必需数据:${missingSampleSlots.join("、")}`);
if (sample?.templateKey !== industry) blockers.push("sample 所属行业与所选行业不一致");
if (sample && !industryTemplate!.capabilities.some((key) => key === sample.capabilityKey))
blockers.push("preview sample 的咨询 capability 与所选行业不兼容");
if (!Array.isArray(sample?.fields) || validateFieldSnapshot(sample.fields).length)
blockers.push("sample 咨询字段不符合表单契约");
if (
@@ -151,11 +180,38 @@ export class AdminTemplatePreviewService {
)
)
blockers.push("sample 信任记录不符合模板声明");
for (const declaration of manifest.trustContentTypes ?? []) {
if (
declaration.required &&
!array(sample?.trustContent).some((item) => record(item).type === declaration.type)
)
blockers.push(`preview sample 缺少必需信任内容:${declaration.type}`);
}
if (blockers.length) {
throw new BadRequestException(`模板预览被阻断:${blockers.join(";")}`);
}
const workspace = this.buildSampleWorkspace(version.id, manifest, industryTemplate!, sample!);
const resources = await this.assets.read(version);
const workspace = this.buildSampleWorkspace(
version.id,
manifest,
industryTemplate!,
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,
@@ -185,6 +241,78 @@ export class AdminTemplatePreviewService {
requiredCapabilities,
missingSampleSlots: [],
},
preview: {
assetFiles: resources.files,
fixtureSource: fixtureDeclared
? ("previewFixture" as const)
: ("legacy-sampleContent" as const),
safety: {
submissions: "disabled" as const,
customerRecords: "disabled" as const,
contactActions: "disabled" as const,
},
diagnostics: [
...resources.diagnostics,
...(fixtureDeclared
? []
: [
{
code: "LEGACY_PREVIEW_SAMPLE",
severity: "warning" as const,
message: "该版本尚未提供独立预览数据,当前兼容使用品牌起始内容。",
},
]),
],
pages: Object.keys(manifest.entrypoints).map((page) => ({
key: page,
modules: manifest.admin.sections
.filter((section) => section.page === page)
.map((section) => ({
key: section.key,
title: section.title,
bindings: section.fields.map((field) => field.binding),
})),
})),
assets: manifest.assetSlots.map((slot) => {
const resolve = (source: Record<string, unknown>, path: string[]) =>
path.reduce<unknown>((value, key) => record(value)[key], source);
const sources =
slot.target === "brand"
? [record(workspace.brand)]
: slot.target === "offering"
? sample!.offerings
: sample!.trustContent;
const path = slot.binding.split(".").slice(1);
const values = sources.map((source) => resolve(record(source), path));
const populated = values.filter(
(value) => typeof value === "string" && value.trim().length > 0,
).length;
const verified = values.filter(
(value) => typeof value === "string" && Object.hasOwn(resources.files, value),
).length;
return {
key: slot.key,
label: slot.label,
binding: slot.binding,
required: slot.required,
populated,
total: sources.length,
status:
populated !== sources.length ||
!sources.length ||
values.some(
(value) =>
typeof value === "string" &&
value.startsWith("/assets/") &&
!Object.hasOwn(resources.files, value),
)
? ("missing" as const)
: verified === sources.length
? ("ready" as const)
: ("unverified" as const),
};
}),
},
workspace,
};
}
@@ -225,21 +353,22 @@ export class AdminTemplatePreviewService {
manifest: TemplatePackageManifest,
industryTemplate: NonNullable<ReturnType<typeof getBrandTemplate>>,
sample: TemplateSampleContent,
identity?: TemplatePreviewFixture["brand"],
) {
const brandConfig = record(sample.brandConfig);
const visualTemplateKey = manifest.visualTemplateKey;
const brand = {
id: `template-preview:${versionId}`,
slug: `template-preview-${manifest.packageKey}`,
name: `${manifest.displayName}示例品牌`,
name: identity?.name ?? `${manifest.displayName}示例品牌`,
templateKey: industryTemplate.key,
tagline: `${industryTemplate.name}模板示例`,
description: "这是模板预览数据,不属于任何真实品牌。",
avatarUrl: null,
coverUrl: null,
hours: "示例营业时间",
address: "示例服务范围",
deliveryNote: "预览模式不会提交咨询或创建客户记录。",
tagline: identity?.tagline ?? `${industryTemplate.name}模板示例`,
description: identity?.description ?? "这是模板预览数据,不属于任何真实品牌。",
avatarUrl: identity?.avatarUrl ?? null,
coverUrl: identity?.coverUrl ?? null,
hours: identity?.hours ?? "示例营业时间",
address: identity?.address ?? "示例服务范围",
deliveryNote: identity?.deliveryNote ?? "预览模式不会提交咨询或创建客户记录。",
contactPhone: null,
contactWechat: null,
config: { ...brandConfig, visualTemplateKey },
@@ -17,6 +17,7 @@ import { AdminTemplatePackageController } from "./admin-template-package.control
import { AdminTemplatePackageService } from "./admin-template-package.service.js";
import { AdminTemplatePreviewService } from "./admin-template-preview.service.js";
import { AdminTemplatePreviewAssetsService } from "./admin-template-preview-assets.service.js";
@Module({
imports: [InfrastructureModule, BookingModule],
@@ -38,6 +39,7 @@ import { AdminTemplatePreviewService } from "./admin-template-preview.service.js
AdminUploadService,
AdminTemplatePackageService,
AdminTemplatePreviewService,
AdminTemplatePreviewAssetsService,
],
})
export class AdminModule {}