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

@@ -3,12 +3,14 @@ import type { RuntimeWorkspace } from "@personal-brand/api-client";
import { Alert } from "antd";
import { resolveTemplateRenderer } from "./component-renderers.jsx";
import type { PreviewSelection, PreviewTarget } from "./preview-selection.js";
import { TemplatePreviewAssetsContext } from "./preview-assets.js";
import "./ComponentTemplatePreview.css";
type PreviewProps = {
workspace: RuntimeWorkspace;
page: string;
offeringId?: string;
assetFiles?: Record<string, { sha256: string; dataUrl: string }>;
selection?: PreviewSelection;
targets: PreviewTarget[];
onTargetSelected: (selection?: PreviewSelection) => void;
@@ -21,6 +23,7 @@ export function ComponentTemplatePreview({
workspace,
page,
offeringId,
assetFiles,
selection,
targets,
onTargetSelected,
@@ -232,7 +235,9 @@ export function ComponentTemplatePreview({
}}
>
<div ref={canvas} className="component-template-preview__canvas">
<Renderer workspace={workspace} page={page} {...(offeringId ? { offeringId } : {})} />
<TemplatePreviewAssetsContext.Provider value={assetFiles}>
<Renderer workspace={workspace} page={page} {...(offeringId ? { offeringId } : {})} />
</TemplatePreviewAssetsContext.Provider>
<div
ref={overlay}
className={`component-template-preview__overlay-host ${
@@ -0,0 +1,5 @@
import { createContext } from "react";
export const TemplatePreviewAssetsContext = createContext<
Record<string, { sha256: string; dataUrl: string }> | undefined
>(undefined);
@@ -1,4 +1,5 @@
import React from "react";
import { TemplatePreviewAssetsContext } from "./preview-assets.js";
export const TemplateAssetContext = React.createContext("");
const templateAssets = import.meta.glob("../../../../../packages/template-*/miniapp/assets/**/*", {
@@ -99,10 +100,14 @@ export function Checkbox({ value, checked }) {
export const Label = element("label");
export const Image = React.forwardRef(({ mode, src, style, ...props }, ref) => {
const key = React.useContext(TemplateAssetContext);
const assets = React.useContext(TemplatePreviewAssetsContext);
return React.createElement("img", {
...props,
ref,
src: resolveImageSource(src, key),
src:
assets && typeof src === "string" && src.startsWith("/assets/")
? assets[src]?.dataUrl
: resolveImageSource(src, key),
style: { objectFit: mode === "aspectFit" ? "contain" : "cover", ...style },
});
});
@@ -249,8 +249,12 @@ export function TemplateManagementPage() {
renderItem={(item) => (
<List.Item>
<List.Item.Meta
title={`${item.action} · ${item.actor.displayName}`}
description={`${item.fromStatus ?? "-"} -> ${item.toStatus ?? "-"} · ${new Date(item.createdAt).toLocaleString()}`}
title={`${item.action === "previewed" ? "预览模板" : item.action} · ${item.actor.displayName}`}
description={
item.action === "previewed"
? `行业 ${typeof item.metadata?.industry === "string" ? item.metadata.industry : "-"} · ${new Date(item.createdAt).toLocaleString()}`
: `${item.fromStatus ?? "-"} -> ${item.toStatus ?? "-"} · ${new Date(item.createdAt).toLocaleString()}`
}
/>
</List.Item>
)}
@@ -260,7 +264,12 @@ export function TemplateManagementPage() {
{previewVersion ? (
<TemplatePackagePreviewModal
version={previewVersion}
onClose={() => setPreviewVersion(null)}
onClose={() => {
setPreviewVersion(null);
void queryClient.invalidateQueries({
queryKey: ["admin-template-package-audit", previewVersion.id],
});
}}
/>
) : null}
</div>
@@ -1,6 +1,6 @@
import { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { Alert, Modal, Select, Typography } from "antd";
import { Alert, Collapse, List, Modal, Select, Tag, Typography } from "antd";
import type { TemplatePackageVersion } from "@personal-brand/api-client";
import { createApiClient } from "../../lib/api.js";
import { QueryState } from "../../components/QueryState.js";
@@ -76,6 +76,20 @@ export function TemplatePackagePreviewModal({
>
{data ? (
<>
{data.preview.diagnostics.map((diagnostic) => (
<Alert
key={diagnostic.code}
type="warning"
showIcon
message={diagnostic.message}
/>
))}
<Typography.Text type="secondary">
演示数据:
{data.preview.fixtureSource === "previewFixture"
? "独立预览内容"
: "兼容起始内容"}
</Typography.Text>
<Typography.Paragraph type="secondary">
{data.industry.name} · Runtime {data.compatibility.runtimeContract} · renderer{" "}
{data.compatibility.renderer.key}@{data.compatibility.renderer.version}
@@ -103,9 +117,65 @@ export function TemplatePackagePreviewModal({
onChange={setOfferingId}
/>
) : null}
<Collapse
items={[
{
key: "modules",
label: "页面模块与字段来源",
children: (
<List
dataSource={
data.preview.pages.find((item) => item.key === page)?.modules ?? []
}
locale={{ emptyText: "此页面由 Runtime 提供,不包含模板编辑模块" }}
renderItem={(item) => (
<List.Item>
<div>
<Typography.Text strong>{item.title}</Typography.Text>
<Typography.Paragraph type="secondary">
{item.bindings.join("、")}
</Typography.Paragraph>
</div>
</List.Item>
)}
/>
),
},
{
key: "assets",
label: "资源诊断",
children: (
<List
dataSource={data.preview.assets}
locale={{ emptyText: "模板未声明资源槽位" }}
renderItem={(item) => (
<List.Item>
<div>
{item.label}{" "}
<Tag color={item.status === "missing" ? "warning" : "default"}>
{item.status === "missing"
? "内容缺失"
: item.status === "ready"
? "包内资源已验证"
: "可用性待验证"}
</Tag>
{item.required ? "必需" : "可选"} · 已配置 {item.populated}/
{item.total}
<Typography.Paragraph type="secondary">
{item.binding}
</Typography.Paragraph>
</div>
</List.Item>
)}
/>
),
},
]}
/>
<ComponentTemplatePreview
key={`${version.id}:${industry}:${page}`}
workspace={data.workspace}
assetFiles={data.preview.assetFiles}
page={page}
{...((offeringId ?? data.workspace.offerings[0]?.id)
? { offeringId: offeringId ?? data.workspace.offerings[0]!.id }
@@ -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 {}
+170 -20
View File
@@ -1,7 +1,7 @@
import assert from "node:assert/strict";
import { randomUUID } from "node:crypto";
import { createHash, randomUUID } from "node:crypto";
import { execFileSync } from "node:child_process";
import { mkdtempSync, readFileSync, readdirSync } from "node:fs";
import { mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
import os from "node:os";
import path from "node:path";
import { after, before, test } from "node:test";
@@ -41,22 +41,50 @@ function multipartArchive(archive) {
};
}
function createTemplateArchive(template = "acheng-campus-food") {
function createTemplateArchive(template = "acheng-campus-food", mutateManifest) {
const output = mkdtempSync(path.join(os.tmpdir(), "personal-brand-template-pack-"));
execFileSync(
process.execPath,
[
path.resolve(process.cwd(), "../../scripts/template-pack.cjs"),
"--template",
template,
"--out",
output,
],
{ cwd: path.resolve(process.cwd(), "../.."), stdio: "ignore" },
);
const filename = readdirSync(output).find((item) => item.endsWith(".tar.gz"));
assert.ok(filename);
return readFileSync(path.join(output, filename));
try {
execFileSync(
process.execPath,
[
path.resolve(process.cwd(), "../../scripts/template-pack.cjs"),
"--template",
template,
"--out",
output,
],
{ cwd: path.resolve(process.cwd(), "../.."), stdio: "ignore" },
);
const filename = readdirSync(output).find((item) => item.endsWith(".tar.gz"));
assert.ok(filename);
if (mutateManifest) {
const packageName = filename.slice(0, -7);
const directory = path.join(output, packageName);
const manifestPath = path.join(directory, "template.json");
const manifest = JSON.parse(readFileSync(manifestPath, "utf8"));
mutateManifest(manifest);
const content = Buffer.from(JSON.stringify(manifest));
writeFileSync(manifestPath, content);
const checksumPath = path.join(directory, "checksums.json");
const checksums = JSON.parse(readFileSync(checksumPath, "utf8"));
const entry = checksums.files.find((item) => item.path === "template.json");
entry.bytes = content.length;
entry.sha256 = createHash("sha256").update(content).digest("hex");
const canonicalEntries = checksums.files.map((item) => ({
bytes: item.bytes,
path: item.path,
sha256: item.sha256,
}));
checksums.contentChecksum = createHash("sha256")
.update(JSON.stringify(canonicalEntries))
.digest("hex");
writeFileSync(checksumPath, JSON.stringify(checksums));
execFileSync("tar", ["-czf", path.join(output, filename), "-C", output, packageName]);
}
return readFileSync(path.join(output, filename));
} finally {
rmSync(output, { recursive: true, force: true });
}
}
test("模板目录只允许平台模板管理员访问,并支持安全、幂等导入", async () => {
@@ -190,6 +218,19 @@ test("平台模板管理员可以按行业预览版本,且预览不写入品
});
assert.equal(login.statusCode, 201);
const headers = { authorization: `Bearer ${JSON.parse(login.body).token}` };
const invalidArchive = createTemplateArchive("atelier-solopreneur", (manifest) => {
manifest.previewFixture.personal.safety.submissions = "enabled";
});
const invalidMultipart = multipartArchive(invalidArchive);
const versionCount = await prisma.templatePackageVersion.count();
const rejectedImport = await request("/admin/templates/import", {
method: "POST",
headers: { ...headers, ...invalidMultipart.headers },
rawPayload: invalidMultipart.payload,
});
assert.equal(rejectedImport.statusCode, 400, rejectedImport.body);
assert.match(JSON.parse(rejectedImport.body).error.message, /previewFixture/);
assert.equal(await prisma.templatePackageVersion.count(), versionCount);
const archive = createTemplateArchive("atelier-solopreneur");
const multipart = multipartArchive(archive);
const imported = await request("/admin/templates/import", {
@@ -213,7 +254,7 @@ test("平台模板管理员可以按行业预览版本,且预览不写入品
]);
const before = await businessCounts();
const preview = await request(`/admin/templates/${versionId}/preview?industry=personal`, {
headers,
headers: { ...headers, "x-request-id": "independent-template-preview" },
});
assert.equal(preview.statusCode, 200, preview.body);
const body = JSON.parse(preview.body);
@@ -226,11 +267,85 @@ test("平台模板管理员可以按行业预览版本,且预览不写入品
assert.equal(body.workspace.brand.config.visualTemplateKey, "atelier-solopreneur");
assert.equal(body.template.pages.includes("profile"), true);
assert.equal(body.template.pages.includes("inquiry"), true);
assert.equal(body.preview.fixtureSource, "previewFixture");
assert.equal(body.workspace.brand.name, "独立工坊 · 演示品牌");
assert.equal(body.workspace.brand.founder, "林予 · 示例主理人");
assert.equal(body.workspace.brand.contactPhone, null);
assert.equal(body.preview.safety.submissions, "disabled");
assert.ok(body.preview.pages.find((page) => page.key === "home").modules.length > 0);
assert.ok(
body.preview.assets.some(
(asset) => asset.binding === "brand.avatarUrl" && asset.status === "missing",
),
);
assert.ok(
body.preview.assets.some(
(asset) => asset.binding === "offering.coverUrl" && asset.status === "ready",
),
);
assert.match(
body.preview.assetFiles["/assets/cases/campus.jpg"].dataUrl,
/^data:image\/jpeg;base64,/,
);
assert.match(body.preview.assetFiles["/assets/cases/campus.jpg"].sha256, /^[a-f0-9]{64}$/);
const previewAudit = await request(`/admin/templates/${versionId}/audit`, { headers });
assert.equal(previewAudit.statusCode, 200);
const event = JSON.parse(previewAudit.body).find((entry) => entry.action === "previewed");
assert.equal(event.requestId, "independent-template-preview");
assert.deepEqual(event.metadata, {
industry: "personal",
contentChecksum: body.template.contentChecksum,
fixtureSource: "previewFixture",
});
assert.ok(event.actor.id);
const stored = await prisma.templatePackageVersion.findUniqueOrThrow({
where: { id: versionId },
});
const failures = [
[{ ...stored.manifestSnapshot, sampleContent: {} }, /缺少必需数据/],
[{ ...stored.manifestSnapshot, previewFixture: {} }, /previewFixture/],
[{ ...stored.manifestSnapshot, previewFixture: { personal: null } }, /previewFixture/],
[
{
...stored.manifestSnapshot,
previewFixture: {
personal: {
...stored.manifestSnapshot.previewFixture.personal,
safety: { submissions: "enabled" },
},
},
},
/previewFixture/,
],
[
{
...stored.manifestSnapshot,
previewFixture: {
personal: {
...stored.manifestSnapshot.previewFixture.personal,
brand: {
...stored.manifestSnapshot.previewFixture.personal.brand,
contactPhone: "13800000000",
},
},
},
},
/previewFixture/,
],
[
{
...stored.manifestSnapshot,
previewFixture: {
personal: {
...stored.manifestSnapshot.previewFixture.personal,
content: {
...stored.manifestSnapshot.previewFixture.personal.content,
templateKey: "food",
},
},
},
},
/所属行业/,
],
[{ ...stored.manifestSnapshot, requiredCapabilities: ["unknown"] }, /未注册的 capability/],
[{ ...stored.manifestSnapshot, visualTemplateKey: "unknown" }, /renderer/],
[{ ...stored.manifestSnapshot, runtimeContract: "9.0" }, /契约/],
@@ -241,6 +356,41 @@ test("平台模板管理员可以按行业预览版本,且预览不写入品
[{ ...stored.manifestSnapshot, admin: { sections: [{ fields: [null] }] } }, /契约/],
];
try {
await prisma.templatePackageVersion.update({
where: { id: versionId },
data: { archiveChecksum: "0".repeat(64) },
});
const corrupt = await request(`/admin/templates/${versionId}/preview?industry=personal`, {
headers,
});
assert.equal(corrupt.statusCode, 409, corrupt.body);
assert.match(JSON.parse(corrupt.body).error.message, /摘要不一致/);
await prisma.templatePackageVersion.update({
where: { id: versionId },
data: { archiveChecksum: stored.archiveChecksum },
});
// 独立演示内容不依赖 bootstrap;旧包则显式标明兼容来源。
await prisma.templatePackageVersion.update({
where: { id: versionId },
data: { manifestSnapshot: { ...stored.manifestSnapshot, sampleContent: {} } },
});
const independent = await request(`/admin/templates/${versionId}/preview?industry=personal`, {
headers,
});
assert.equal(independent.statusCode, 200, independent.body);
assert.equal(JSON.parse(independent.body).workspace.brand.founder, "林予 · 示例主理人");
const legacyManifest = { ...stored.manifestSnapshot };
delete legacyManifest.previewFixture;
await prisma.templatePackageVersion.update({
where: { id: versionId },
data: { manifestSnapshot: legacyManifest },
});
const legacy = await request(`/admin/templates/${versionId}/preview?industry=personal`, {
headers,
});
assert.equal(legacy.statusCode, 200, legacy.body);
assert.equal(JSON.parse(legacy.body).preview.fixtureSource, "legacy-sampleContent");
assert.equal(JSON.parse(legacy.body).preview.diagnostics[0].code, "LEGACY_PREVIEW_SAMPLE");
for (const [manifestSnapshot, reason] of failures) {
await prisma.templatePackageVersion.update({
where: { id: versionId },
@@ -255,7 +405,7 @@ test("平台模板管理员可以按行业预览版本,且预览不写入品
} finally {
await prisma.templatePackageVersion.update({
where: { id: versionId },
data: { manifestSnapshot: stored.manifestSnapshot },
data: { manifestSnapshot: stored.manifestSnapshot, archiveChecksum: stored.archiveChecksum },
});
}
const noIndustry = await request(`/admin/templates/${versionId}/preview`, { headers });
@@ -0,0 +1,72 @@
import assert from "node:assert/strict";
import { execFileSync } from "node:child_process";
import { createHash } from "node:crypto";
import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import os from "node:os";
import path from "node:path";
import { test } from "node:test";
import "reflect-metadata";
import { ConflictException } from "@nestjs/common";
import { AdminTemplatePreviewAssetsService } from "../src/modules/admin/admin-template-preview-assets.service.js";
const digest = (value: Buffer | string) => createHash("sha256").update(value).digest("hex");
function archiveFixture(corruptImage = false) {
const root = mkdtempSync(path.join(os.tmpdir(), "template-preview-assets-"));
const directory = path.join(root, "fixture");
mkdirSync(path.join(directory, "miniapp/assets"), { recursive: true });
const png = readFileSync(
"../../packages/template-atelier-solopreneur/miniapp/assets/tab/home.png",
);
const contents: Record<string, Buffer> = {
"miniapp/assets/icon.png": png,
"miniapp/assets/bad.jpg": Buffer.from("This is not an image"),
"miniapp/assets/large.png": Buffer.alloc(2 * 1024 * 1024 + 1),
"miniapp/assets/script.svg": Buffer.from("<svg onload='alert(1)'/>"),
};
const files = Object.entries(contents).map(([file, content]) => {
writeFileSync(path.join(directory, file), content);
return {
bytes: content.length,
path: file,
sha256: corruptImage ? "0".repeat(64) : digest(content),
};
});
const contentChecksum = digest(JSON.stringify(files));
writeFileSync(path.join(directory, "checksums.json"), JSON.stringify({ contentChecksum, files }));
const artifactPath = path.join(root, "fixture.tar.gz");
execFileSync("tar", ["-czf", artifactPath, "-C", root, "fixture"]);
return {
root,
version: { artifactPath, contentChecksum, archiveChecksum: digest(readFileSync(artifactPath)) },
};
}
test("preview resources verify raster content and diagnose invalid or oversized assets", async () => {
const fixture = archiveFixture();
try {
const result = await new AdminTemplatePreviewAssetsService().read(fixture.version);
assert.deepEqual(Object.keys(result.files), ["/assets/icon.png"]);
assert.match(result.files["/assets/icon.png"]!.dataUrl, /^data:image\/png;base64,/);
assert.deepEqual(
result.diagnostics.map((item) => item.code),
["PREVIEW_ASSET_TYPE", "PREVIEW_ASSET_LIMIT"],
);
} finally {
rmSync(fixture.root, { recursive: true, force: true });
}
});
test("preview resources reject image checksum drift and unavailable archives", async () => {
const fixture = archiveFixture(true);
try {
const service = new AdminTemplatePreviewAssetsService();
await assert.rejects(service.read(fixture.version), ConflictException);
await assert.rejects(
service.read({ ...fixture.version, artifactPath: path.join(fixture.root, "missing.tar.gz") }),
ConflictException,
);
} finally {
rmSync(fixture.root, { recursive: true, force: true });
}
});
@@ -30,11 +30,25 @@ test("模板管理可重试预览,并切换我的、详情和禁止提交的
`
import 'reflect-metadata';
import { AdminTemplatePreviewService } from './dist/modules/admin/admin-template-preview.service.js';
import { AdminTemplatePreviewAssetsService } from './dist/modules/admin/admin-template-preview-assets.service.js';
import { execFileSync } from 'node:child_process';
import { createHash } from 'node:crypto';
import { mkdtempSync, readdirSync, readFileSync, rmSync } from 'node:fs';
import os from 'node:os';
import path from 'node:path';
let input = '';
for await (const chunk of process.stdin) input += chunk;
const version = JSON.parse(input);
const service = new AdminTemplatePreviewService({ templatePackageVersion: { findUnique: async () => version } });
process.stdout.write(JSON.stringify(await service.preview(version.id, 'personal')));
const temporary = mkdtempSync(path.join(os.tmpdir(), 'template-preview-browser-'));
try {
execFileSync(process.execPath, ['../../scripts/template-pack.cjs', '--template', version.packageKey, '--out', temporary], { stdio: 'ignore' });
const archive = readdirSync(temporary).find((file) => file.endsWith('.tar.gz'));
version.artifactPath = path.join(temporary, archive);
version.archiveChecksum = createHash('sha256').update(readFileSync(version.artifactPath)).digest('hex');
version.contentChecksum = JSON.parse(readFileSync(path.join(temporary, archive.slice(0, -7), 'checksums.json'), 'utf8')).contentChecksum;
const service = new AdminTemplatePreviewService({ templatePackageVersion: { findUnique: async () => version }, templatePackageAuditLog: { create: async () => ({}) } }, new AdminTemplatePreviewAssetsService());
process.stdout.write(JSON.stringify(await service.preview(version.id, 'personal', 'browser-fixture-admin')));
} finally { rmSync(temporary, { recursive: true, force: true }); }
`,
],
{ cwd: path.resolve("../api"), input: JSON.stringify(version), encoding: "utf8" },
@@ -70,8 +84,12 @@ test("模板管理可重试预览,并切换我的、详情和禁止提交的
await expect(modal.getByText("预览测试失败,请重试")).toBeVisible();
await modal.getByRole("button", { name: /重试/ }).click();
await expect(modal.locator(".atelier-founder-name")).toHaveText(
manifest.sampleContent.personal.brandConfig.founder,
manifest.previewFixture.personal.content.brandConfig.founder,
);
await expect(modal.getByText("演示数据:独立预览内容")).toBeVisible();
await modal.getByText("资源诊断", { exact: true }).click();
await expect(modal.getByText("内容缺失", { exact: true }).first()).toBeVisible();
await expect(modal.getByText("包内资源已验证", { exact: true }).first()).toBeVisible();
const choosePage = async (label: string) => {
await modal.getByLabel("预览页面").click();
await page.locator(".ant-select-item-option-content").getByText(label, { exact: true }).click();
@@ -80,8 +98,13 @@ test("模板管理可重试预览,并切换我的、详情和禁止提交的
await expect(modal.locator(".component-template-preview")).toContainText("我的咨询记录");
await choosePage("业务详情");
await expect(modal.locator(".component-template-preview")).toContainText(
manifest.sampleContent.personal.offerings[0].name,
manifest.previewFixture.personal.content.offerings[0].name,
);
const caseImage = modal.locator('.component-template-preview img[src^="data:image/"]').first();
await expect(caseImage).toBeVisible();
await expect
.poll(() => caseImage.evaluate((image: HTMLImageElement) => image.naturalWidth))
.toBeGreaterThan(0);
await choosePage("咨询表单");
await expect(modal.locator(".inquiry-form")).toBeVisible();
await expect(modal.locator(".inquiry-form button").last()).toBeDisabled();