feat: 收口模板升级与阶段七持续回归

This commit is contained in:
que01 committed 2026-10-17 21:33:57 +08:00
1 parent ec16fff70e
commit 71c528de34
29 files changed
+1962 -304

No files matched your search

+365 -14
View File
@@ -145,6 +145,13 @@ test("模板目录只允许平台模板管理员访问,并支持安全、幂
assert.equal(listedBody.items.length, 1);
assert.equal(listedBody.items[0].status, "imported");
const versionId = listedBody.items[0].id;
const importedVersion = await prisma.templatePackageVersion.findUniqueOrThrow({
where: { id: versionId },
});
assert.ok(importedVersion.validationReport.files.length > 0);
assert.ok(
importedVersion.validationReport.files.every((file) => /^[a-f0-9]{64}$/.test(file.sha256)),
);
const publishMissing = await request(`/admin/templates/${versionId}/publish`, { method: "POST" });
assert.equal(publishMissing.statusCode, 401);
const publishCustomer = await request(`/admin/templates/${versionId}/publish`, {
@@ -183,6 +190,83 @@ test("模板目录只允许平台模板管理员访问,并支持安全、幂
assert.equal(JSON.parse(invalidRetire.body).changed, false);
});
test("模板失败指标仅平台模板管理员可查,按窗口聚合且不暴露操作内容", async () => {
const missing = await request("/admin/template-operations/failures");
assert.equal(missing.statusCode, 401);
const customer = await request("/admin/template-operations/failures", {
headers: { authorization: `Bearer ${customerToken}` },
});
assert.equal(customer.statusCode, 403);
const ordinaryUser = await prisma.adminUser.create({
data: {
username: `metrics-viewer-${randomUUID()}`,
passwordHash: "unused",
displayName: "普通管理员",
platformTemplateRole: "none",
mustChangePassword: false,
},
});
const headers = {
authorization: `Bearer ${signIdentity({ subject: ordinaryUser.id, brandId, role: "admin" })}`,
};
try {
const forbidden = await request("/admin/template-operations/failures", { headers });
assert.equal(forbidden.statusCode, 403);
} finally {
await prisma.adminUser.delete({ where: { id: ordinaryUser.id } });
}
const login = await request("/admin/session/login", {
method: "POST",
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
});
assert.equal(login.statusCode, 201);
const adminHeaders = { authorization: `Bearer ${JSON.parse(login.body).token}` };
const now = Date.now();
const recentRequestId = `metrics-${randomUUID()}`;
await prisma.templateOperationFailureEvent.createMany({
data: [
{
action: "preview",
resultCode: "HTTP_409",
requestId: recentRequestId,
actorId: "metrics-test-actor",
brandId,
packageKey: "metrics-test-package",
version: "1.0.0",
createdAt: new Date(now - 1000),
},
{
action: "preview",
resultCode: "HTTP_400",
createdAt: new Date(now - 2 * 24 * 60 * 60 * 1000),
},
{
action: "import",
resultCode: "HTTP_400",
createdAt: new Date(now - 200 * 24 * 60 * 60 * 1000),
},
],
});
const invalidWindow = await request("/admin/template-operations/failures?days=91", {
headers: adminHeaders,
});
assert.equal(invalidWindow.statusCode, 400);
const response = await request("/admin/template-operations/failures?days=1", {
headers: adminHeaders,
});
assert.equal(response.statusCode, 200, response.body);
const report = JSON.parse(response.body);
assert.equal(report.days, 1);
assert.equal(report.backfilled, false);
assert.equal(report.failures.find((item) => item.action === "preview").count, 1);
assert.equal(report.failures.find((item) => item.action === "import").count, 0);
assert.equal(report.failures.find((item) => item.action === "build").count, 0);
assert.equal(JSON.stringify(report).includes(recentRequestId), false);
assert.deepEqual(Object.keys(report.failures[0]).sort(), ["action", "count"]);
});
test("平台模板管理员可以按行业预览版本,且预览不写入品牌数据", async () => {
const missing = await request("/admin/templates/preview-version/preview?industry=personal");
assert.equal(missing.statusCode, 401);
@@ -2507,12 +2591,11 @@ test("template ledger install, upgrade preview, and rollback stay brand-scoped",
headers: { authorization: `Bearer ${customerToken}` },
});
assert.equal(customerAccess.statusCode, 403);
const currentTemplateKey = (
await prisma.brandProfile.findUniqueOrThrow({
where: { id: brandId },
select: { templateKey: true },
})
).templateKey;
const originalBrand = await prisma.brandProfile.findUniqueOrThrow({
where: { id: brandId },
select: { templateKey: true, config: true },
});
const currentTemplateKey = originalBrand.templateKey;
const crossTemplate = await request("/admin/workspace/install", {
method: "POST",
headers: { authorization: `Bearer ${token}` },
@@ -2533,6 +2616,12 @@ test("template ledger install, upgrade preview, and rollback stay brand-scoped",
true,
);
assert.equal(JSON.parse(installed.body).installation.configSnapshot.schemaVersion, "1.0");
const installedRecord = JSON.parse(installed.body).installation;
const createdVersionIds = [];
let historicalReleaseId;
let historicalFormId;
let historicalSubmissionId;
let historicalReleaseSnapshot;
try {
const previewUnauthorized = await request("/admin/workspace/template/preview");
assert.equal(previewUnauthorized.statusCode, 401);
@@ -2540,27 +2629,279 @@ test("template ledger install, upgrade preview, and rollback stay brand-scoped",
headers: { authorization: `Bearer ${token}` },
});
assert.equal(preview.statusCode, 200);
assert.equal(JSON.parse(preview.body).canUpgrade, false);
const rollbackUnauthorized = await request("/admin/workspace/template/rollback", {
method: "POST",
const admin = await prisma.adminUser.findUniqueOrThrow({ where: { username: "admin" } });
const latestExistingRelease = await prisma.brandRelease.findFirst({
where: { brandId },
orderBy: { version: "desc" },
});
assert.ok(
latestExistingRelease,
"integration fixture should have a published release snapshot",
);
historicalReleaseSnapshot = latestExistingRelease.snapshot;
const historicalRelease = await prisma.brandRelease.create({
data: {
brandId,
version: latestExistingRelease.version + 1,
snapshot: historicalReleaseSnapshot,
actorId: admin.id,
note: "Phase 6 历史快照回归",
},
});
historicalReleaseId = historicalRelease.id;
const historicalForm = await prisma.inquiryForm.create({
data: {
brandId,
name: "Phase 6 历史咨询表单",
fieldsSnapshot: [{ key: "message", label: "留言", type: "text", required: true }],
},
});
historicalFormId = historicalForm.id;
const historicalSubmission = await prisma.inquirySubmission.create({
data: {
brandId,
inquiryFormId: historicalForm.id,
customerSubject: "phase6-history-customer",
formVersion: 1,
fieldsSnapshot: historicalForm.fieldsSnapshot,
values: { message: "历史咨询内容" },
activeFields: ["message"],
},
});
historicalSubmissionId = historicalSubmission.id;
const packageKey = installedRecord.visualTemplateKey;
const packageVersion = `9.${Date.now()}.0`;
const initialPackageVersion = "1.0.0-phase6-test";
const templatePackage = await prisma.templatePackage.upsert({
where: { packageKey },
create: { packageKey },
update: {},
});
const initialPackageVersionRecord = await prisma.templatePackageVersion.create({
data: {
templatePackageId: templatePackage.id,
packageKey,
version: initialPackageVersion,
displayName: "集成测试基线包",
visualTemplateKey: packageKey,
status: "published",
manifestSnapshot: {
packageKey,
version: initialPackageVersion,
supportedIndustryTemplates: [currentTemplateKey],
requiredCapabilities: ["offerings"],
templateFields: [{ key: "founder", binding: "brand.config.founder", label: "主理人" }],
entrypoints: { home: "pages/index/index" },
assetSlots: [{ key: "brand.logo", binding: "brand.avatarUrl" }],
},
validationReport: {},
contentChecksum: `checksum-${initialPackageVersion}`,
archiveChecksum: `archive-${initialPackageVersion}`,
artifactPath: "/tmp/template-upgrade-initial-test",
importedById: admin.id,
},
});
createdVersionIds.push(initialPackageVersionRecord.id);
const originalConfig =
originalBrand.config && typeof originalBrand.config === "object" ? originalBrand.config : {};
const existingFounder = "升级前的品牌主理人";
await prisma.brandProfile.update({
where: { id: brandId },
data: { config: { ...originalConfig, founder: existingFounder } },
});
assert.equal(rollbackUnauthorized.statusCode, 401);
const installedRecord = JSON.parse(installed.body).installation;
await prisma.brandTemplateInstallation.update({
where: { id: installedRecord.id },
data: {
templateVersion: "2.0.0",
previousSnapshots: [installedRecord.configSnapshot],
templateVersion: initialPackageVersion,
templatePackageVersionId: initialPackageVersionRecord.id,
contentChecksum: initialPackageVersionRecord.contentChecksum,
configSnapshot: initialPackageVersionRecord.manifestSnapshot,
},
});
const packageVersionRecord = await prisma.templatePackageVersion.create({
data: {
templatePackageId: templatePackage.id,
packageKey,
version: packageVersion,
displayName: "集成测试升级包",
visualTemplateKey: packageKey,
status: "published",
manifestSnapshot: {
packageKey,
version: packageVersion,
supportedIndustryTemplates: [currentTemplateKey],
requiredCapabilities: [],
templateFields: [
{ key: "founder", binding: "brand.config.founder", label: "品牌主理人" },
],
entrypoints: { home: "pages/home/index", profile: "pages/profile/index" },
assetSlots: [
{ key: "brand.logo", binding: "brand.avatarUrl" },
{ key: "home.hero", binding: "brand.config.heroImage" },
],
},
validationReport: {},
contentChecksum: `checksum-${packageVersion}`,
archiveChecksum: `archive-${packageVersion}`,
artifactPath: "/tmp/template-upgrade-test",
importedById: admin.id,
},
});
createdVersionIds.push(packageVersionRecord.id);
const actionablePreview = await request("/admin/workspace/template/preview", {
headers: { authorization: `Bearer ${token}` },
});
const actionable = JSON.parse(actionablePreview.body);
assert.equal(actionable.canUpgrade, true);
assert.equal(actionable.targetPackageVersionId, packageVersionRecord.id);
assert.equal(actionable.changes.brandFields.available, false);
assert.equal(actionable.conflicts.length, 1);
assert.equal(actionable.conflicts[0].binding, "brand.config.founder");
assert.equal(actionable.changes.pages.added.length, 1);
assert.equal(actionable.changes.assets.slots.added.length, 1);
assert.deepEqual(actionable.changes.capabilities.removed, ["offerings"]);
assert.equal(actionable.changes.renderer.available, true);
assert.equal(actionable.changes.renderer.packageUpgradeChangesRenderer, false);
assert.equal(actionable.changes.assets.files.available, false);
const missingConfirm = await request("/admin/workspace/template/upgrade", {
method: "POST",
headers: { authorization: `Bearer ${token}` },
payload: {
templatePackageVersionId: packageVersionRecord.id,
expectedContentChecksum: packageVersionRecord.contentChecksum,
expectedCurrentVersion: actionable.currentVersion,
expectedCurrentPackageVersionId: actionable.currentPackageVersionId,
confirm: false,
preservedBindings: [],
},
});
assert.equal(missingConfirm.statusCode, 400);
const unresolvedConflict = await request("/admin/workspace/template/upgrade", {
method: "POST",
headers: { authorization: `Bearer ${token}` },
payload: {
templatePackageVersionId: packageVersionRecord.id,
expectedContentChecksum: packageVersionRecord.contentChecksum,
expectedCurrentVersion: actionable.currentVersion,
expectedCurrentPackageVersionId: actionable.currentPackageVersionId,
confirm: true,
preservedBindings: [],
},
});
assert.equal(unresolvedConflict.statusCode, 409);
const upgradePayload = {
templatePackageVersionId: packageVersionRecord.id,
expectedContentChecksum: packageVersionRecord.contentChecksum,
expectedCurrentVersion: actionable.currentVersion,
expectedCurrentPackageVersionId: actionable.currentPackageVersionId,
confirm: true,
preservedBindings: [{ key: "founder", binding: "brand.config.founder", action: "preserve" }],
};
const upgradeAttempts = await Promise.all(
[0, 1].map(() =>
request("/admin/workspace/template/upgrade", {
method: "POST",
headers: { authorization: `Bearer ${token}` },
payload: upgradePayload,
}),
),
);
assert.deepEqual(upgradeAttempts.map((item) => item.statusCode).sort(), [201, 409]);
const upgraded = upgradeAttempts.find((item) => item.statusCode === 201);
assert.ok(upgraded);
assert.equal(
JSON.parse(upgraded.body).installation.templatePackageVersionId,
packageVersionRecord.id,
);
assert.equal(
(await prisma.brandProfile.findUniqueOrThrow({ where: { id: brandId } })).config.founder,
existingFounder,
);
const retainedOldPackage = await prisma.templatePackageVersion.findUniqueOrThrow({
where: { id: initialPackageVersionRecord.id },
});
assert.equal(retainedOldPackage.contentChecksum, initialPackageVersionRecord.contentChecksum);
const retainedRelease = await prisma.brandRelease.findUniqueOrThrow({
where: { id: historicalReleaseId },
});
assert.deepEqual(retainedRelease.snapshot, historicalReleaseSnapshot);
assert.equal(
(await prisma.inquirySubmission.findUniqueOrThrow({ where: { id: historicalSubmissionId } }))
.values.message,
"历史咨询内容",
);
await prisma.$disconnect();
await prisma.$connect();
await app.close();
app = await createApp();
await app.init();
const afterApiRestart = await request("/admin/workspace/template/preview", {
headers: { authorization: `Bearer ${token}` },
});
assert.equal(afterApiRestart.statusCode, 200);
assert.equal(JSON.parse(afterApiRestart.body).currentPackageVersionId, packageVersionRecord.id);
const rollbackUnauthorized = await request("/admin/workspace/template/rollback", {
method: "POST",
payload: { expectedCurrentVersion: packageVersion, confirm: true },
});
assert.equal(rollbackUnauthorized.statusCode, 401);
const upgradeUnauthorized = await request("/admin/workspace/template/upgrade", {
method: "POST",
payload: {},
});
assert.equal(upgradeUnauthorized.statusCode, 401);
const upgradeForbidden = await request("/admin/workspace/template/upgrade", {
method: "POST",
headers: { authorization: `Bearer ${customerToken}` },
payload: {},
});
assert.equal(upgradeForbidden.statusCode, 403);
const upgradeInvalidDto = await request("/admin/workspace/template/upgrade", {
method: "POST",
headers: { authorization: `Bearer ${token}` },
payload: {},
});
assert.equal(upgradeInvalidDto.statusCode, 400);
const rollbackMissingConfirmation = await request("/admin/workspace/template/rollback", {
method: "POST",
headers: { authorization: `Bearer ${token}` },
payload: { expectedCurrentVersion: packageVersion, confirm: false },
});
assert.equal(rollbackMissingConfirmation.statusCode, 400);
const rollbackStaleVersion = await request("/admin/workspace/template/rollback", {
method: "POST",
headers: { authorization: `Bearer ${token}` },
payload: { expectedCurrentVersion: actionable.currentVersion, confirm: true },
});
assert.equal(rollbackStaleVersion.statusCode, 409);
const rollback = await request("/admin/workspace/template/rollback", {
method: "POST",
headers: { authorization: `Bearer ${token}` },
payload: { expectedCurrentVersion: packageVersion, confirm: true },
});
assert.equal(rollback.statusCode, 201);
assert.equal(JSON.parse(rollback.body).installation.templateVersion, "1.0.0");
assert.equal(JSON.parse(rollback.body).installation.templateVersion, initialPackageVersion);
assert.equal(
JSON.parse(rollback.body).installation.templatePackageVersionId,
initialPackageVersionRecord.id,
);
assert.equal(JSON.parse(rollback.body).installation.previousSnapshots.length, 0);
assert.match(JSON.parse(rollback.body).note, /配置基线/);
const operationAudit = await prisma.templatePackageAuditLog.findMany({
where: {
templatePackageVersionId: packageVersionRecord.id,
action: { in: ["brand_upgrade", "brand_rollback"] },
},
orderBy: { createdAt: "asc" },
});
assert.deepEqual(
operationAudit.map((item) => item.action),
["brand_upgrade", "brand_rollback"],
);
assert.equal(operationAudit[0].metadata.brandId, brandId);
assert.equal(operationAudit[0].metadata.contentChecksum, packageVersionRecord.contentChecksum);
assert.ok(operationAudit[0].requestId);
await prisma.templatePackageVersion.deleteMany({ where: { id: { in: createdVersionIds } } });
const workspace = await request("/admin/workspace", {
headers: { authorization: `Bearer ${token}` },
});
@@ -2603,8 +2944,18 @@ test("template ledger install, upgrade preview, and rollback stay brand-scoped",
});
assert.equal(conflict.statusCode, 400);
} finally {
if (historicalSubmissionId)
await prisma.inquirySubmission.deleteMany({ where: { id: historicalSubmissionId } });
if (historicalFormId) await prisma.inquiryForm.deleteMany({ where: { id: historicalFormId } });
if (historicalReleaseId)
await prisma.brandRelease.deleteMany({ where: { id: historicalReleaseId } });
await prisma.brandFieldDefinition.deleteMany({ where: { brandId } });
await prisma.brandTemplateInstallation.deleteMany({ where: { brandId } });
await prisma.templatePackageVersion.deleteMany({ where: { id: { in: createdVersionIds } } });
await prisma.brandProfile.update({
where: { id: brandId },
data: { templateKey: originalBrand.templateKey, config: originalBrand.config },
});
}
});
+53 -13
View File
@@ -1,7 +1,7 @@
import assert from "node:assert/strict";
import { execFileSync } from "node:child_process";
import { createHash } from "node:crypto";
import { mkdtempSync, readdirSync, readFileSync, rmSync } from "node:fs";
import { cpSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import os from "node:os";
import path from "node:path";
import { test } from "node:test";
@@ -24,17 +24,23 @@ interface Fixture {
function createTemplateFixture(packageKey: string): Fixture {
const root = mkdtempSync(path.join(os.tmpdir(), `template-preview-matrix-${packageKey}-`));
execFileSync(
process.execPath,
[
path.resolve(process.cwd(), "../../scripts/template-pack.cjs"),
"--template",
packageKey,
"--out",
root,
],
{ cwd: path.resolve(process.cwd(), "../.."), stdio: "ignore" },
);
try {
execFileSync(
process.execPath,
[
path.resolve(process.cwd(), "../../scripts/template-pack.cjs"),
"--template",
packageKey,
"--out",
root,
],
{ cwd: path.resolve(process.cwd(), "../.."), stdio: "pipe", encoding: "utf8" },
);
} catch (error) {
const details =
error instanceof Error && "stderr" in error ? String(error.stderr) : String(error);
throw new Error(`Could not package discovered template ${packageKey}: ${details}`);
}
const filename = readdirSync(root).find((item) => item.endsWith(".tar.gz"));
assert.ok(filename);
const archivePath = path.join(root, filename);
@@ -58,8 +64,42 @@ function createTemplateFixture(packageKey: string): Fixture {
};
}
function discoverTemplatePackages(packageRoot: string): string[] {
return readdirSync(packageRoot, { withFileTypes: true })
.filter(
(entry) =>
entry.isDirectory() &&
entry.name.startsWith("template-") &&
readdirSync(path.join(packageRoot, entry.name)).includes("template.json"),
)
.map((entry) => {
const manifest = JSON.parse(
readFileSync(path.join(packageRoot, entry.name, "template.json"), "utf8"),
) as TemplatePackageManifest;
return manifest.packageKey;
})
.sort();
}
test("template preview matrix discovers newly added package manifests", () => {
const packageRoot = mkdtempSync(path.join(os.tmpdir(), "template-discovery-matrix-"));
const source = path.resolve(process.cwd(), "../../packages/template-atelier-solopreneur");
const packageDirectory = path.join(packageRoot, "template-discovery-probe");
cpSync(source, packageDirectory, { recursive: true });
const manifestPath = path.join(packageDirectory, "template.json");
const manifest = JSON.parse(readFileSync(manifestPath, "utf8")) as TemplatePackageManifest;
writeFileSync(manifestPath, JSON.stringify({ ...manifest, packageKey: "discovery-probe" }));
try {
assert.deepEqual(discoverTemplatePackages(packageRoot), ["discovery-probe"]);
} finally {
rmSync(packageRoot, { recursive: true, force: true });
}
});
test("template preview matrix keeps every deployed package, industry, and version isolated", async () => {
const packageKeys = ["acheng-campus-food", "atelier-solopreneur", "linjing-editorial"];
const packageRoot = path.resolve(process.cwd(), "../../packages");
const packageKeys = discoverTemplatePackages(packageRoot);
assert.ok(packageKeys.length > 0, "at least one template package must be discovered");
const fixtures = packageKeys.map(createTemplateFixture);
let sequence = 0;
const versionFixture = (fixture: Fixture) => {