fix: 收口模板契约与安全门禁

统一模板包 visual 契约并补齐完成证据;修复 release 版本一致性、管理员 token 撤销、CORS 与默认品牌配置;收敛依赖安全风险并完成全量回归验证。
This commit is contained in:
que01 committed 2026-10-18 22:05:31 +08:00
1 parent 456171aa85
commit 4f0b50c7f1
84 files changed
+7367 -5180

No files matched your search

@@ -1,12 +1,11 @@
import assert from "node:assert/strict";
import { generateKeyPairSync } from "node:crypto";
import { test } from "node:test";
import { BadGatewayException, BadRequestException, ConflictException } from "@nestjs/common";
import { BadRequestException, ConflictException } from "@nestjs/common";
import { templatePackageRegistry } from "@personal-brand/config";
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { mkdtempSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { AdminMiniAppBuildService } from "../src/modules/admin/admin-miniapp-build.service.js";
import { AdminMiniAppUploadService } from "../src/modules/admin/admin-miniapp-upload.service.js";
import type { AdminMiniAppReleaseService } from "../src/modules/admin/admin-miniapp-release.service.js";
import { encryptMiniAppCredential } from "../src/modules/admin/miniapp-credential-crypto.js";
@@ -105,7 +104,7 @@ function createHarness(
onLog("build log", "stdout");
return { exitCode: options.exitCode ?? 0 };
},
} as unknown as AdminMiniAppBuildService;
};
const service = new AdminMiniAppUploadService(releases, builds);
return { service, updates, artifactRoot, buildConfigs };
}
@@ -175,7 +174,7 @@ function createHarnessWithCredential(
onLog("build log", "stdout");
return { exitCode: options.exitCode ?? 0 };
},
} as unknown as AdminMiniAppBuildService;
};
return {
service: new AdminMiniAppUploadService(releases, builds),
updates,
@@ -235,7 +234,7 @@ test("missing artifact records build failure without invoking upload", async ()
() => service.run(brandId, actorId, "task-1", {}),
(error: unknown) => {
assert.ok(error instanceof BadRequestException);
assert.match((error as BadRequestException).message, /app\.json/);
assert.match(error.message, /app\.json/);
return true;
},
);
@@ -269,7 +268,7 @@ test("upload rejects missing credentials before build", async () => {
() => service.run(brandId, actorId, "task-1", {}),
(error: unknown) => {
assert.ok(error instanceof BadRequestException);
assert.match((error as BadRequestException).message, /WECHAT_UPLOAD_PRIVATE_KEY/);
assert.match(error.message, /WECHAT_UPLOAD_PRIVATE_KEY/);
return true;
},
);
+7 -2
View File
@@ -81,8 +81,13 @@ test("refactored admin controllers preserve their declared API routes", () => {
});
test("root module composes bounded feature modules only", () => {
const imports = Reflect.getMetadata("imports", AppModule) ?? [];
const names = imports.map((item) => item.name);
const imports = (Reflect.getMetadata("imports", AppModule) ?? []) as Array<{
name?: unknown;
}>;
const names = imports.map((item) => {
assert.ok(item && typeof item.name === "string", "App module import metadata is invalid");
return item.name;
});
assert.deepEqual(names, [
"InfrastructureModule",
"PublicModule",
+68 -2
View File
@@ -5,8 +5,9 @@ import { mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "n
import os from "node:os";
import path from "node:path";
import { after, before, test } from "node:test";
import bcrypt from "bcryptjs";
import { PrismaClient } from "@prisma/client";
import { getVisualTemplateManifest } from "@personal-brand/config";
import { getTemplatePackageManifest, getVisualTemplateManifest } from "@personal-brand/config";
import { createApp } from "../dist/main.js";
import { readIdentity, signIdentity } from "../dist/auth.js";
import { WechatAuthService } from "../dist/wechat-auth.js";
@@ -140,7 +141,7 @@ test("模板目录只允许平台模板管理员访问,并支持安全、幂
]);
const linjingVersion = baseline.items.find((item) => item.packageKey === "linjing-editorial");
assert.ok(linjingVersion);
assert.equal(linjingVersion.version, "1.0.5");
assert.equal(linjingVersion.version, "1.0.6");
const linjingPreview = await request(
`/admin/templates/${linjingVersion.id}/preview?industry=doors`,
{ headers },
@@ -1882,8 +1883,13 @@ test("visual template compatibility is enforced by catalog, preview, and version
const visuals = JSON.parse(catalog.body).visuals;
for (const visual of visuals) {
const manifest = getVisualTemplateManifest(visual.key);
const packageManifest = getTemplatePackageManifest(visual.key);
assert.ok(manifest, `Catalog visual must be installable: ${visual.key}`);
assert.ok(packageManifest, `Catalog visual must have a package manifest: ${visual.key}`);
assert.equal(manifest.key, visual.key);
assert.equal(manifest.key, packageManifest.visualTemplateKey);
assert.equal(manifest.version, packageManifest.version);
assert.equal(visual.version, packageManifest.version);
assert.deepEqual(manifest.supportedIndustryTemplates, visual.supportedIndustryTemplates);
}
assert.deepEqual(
@@ -3862,6 +3868,66 @@ test("admin login validates credentials", async () => {
assert.equal(response.statusCode, 401);
});
test("admin login does not auto-grant ownership to users without memberships", async () => {
const username = `no-membership-${Date.now()}`;
const user = await prisma.adminUser.create({
data: {
username,
passwordHash: await bcrypt.hash("initial-password-123", 12),
displayName: "未分配品牌管理员",
mustChangePassword: false,
},
});
try {
const login = await request("/admin/session/login", {
method: "POST",
payload: { username, password: "initial-password-123" },
});
assert.equal(login.statusCode, 403);
assert.equal(await prisma.brandMembership.count({ where: { adminUserId: user.id } }), 0);
} finally {
await prisma.adminUser.delete({ where: { id: user.id } });
}
});
test("changing an admin password revokes existing admin tokens", async () => {
const username = `token-version-${Date.now()}`;
const user = await prisma.adminUser.create({
data: {
username,
passwordHash: await bcrypt.hash("initial-password-123", 12),
displayName: "Token 版本管理员",
mustChangePassword: false,
memberships: {
create: { brandId, role: "admin", isEnabled: true },
},
},
});
try {
const login = await request("/admin/session/login", {
method: "POST",
payload: { username, password: "initial-password-123" },
});
assert.equal(login.statusCode, 201, login.body);
const token = JSON.parse(login.body).token;
const headers = { authorization: `Bearer ${token}` };
const before = await request("/admin/bookings/unread-count", { headers });
assert.equal(before.statusCode, 200, before.body);
const changed = await request("/admin/session/change-password", {
method: "POST",
headers,
payload: { currentPassword: "initial-password-123", newPassword: "changed-password-456" },
});
assert.equal(changed.statusCode, 201, changed.body);
const after = await request("/admin/bookings/unread-count", { headers });
assert.equal(after.statusCode, 401, after.body);
} finally {
await prisma.adminUser.delete({ where: { id: user.id } });
}
});
test("admin can list and switch only enabled brand memberships", async () => {
const login = await request("/admin/session/login", {
method: "POST",
@@ -1,4 +1,5 @@
import assert from "node:assert/strict";
import { Buffer } from "node:buffer";
import { spawnSync } from "node:child_process";
import { mkdtempSync, readdirSync, readFileSync, rmSync } from "node:fs";
import os from "node:os";
@@ -0,0 +1,16 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { PublicBrandContextService } from "../src/modules/public/public-brand-context.service.js";
import type { PrismaService } from "../src/prisma.service.js";
test("public default brand context fails fast when configuration is missing", async () => {
const previous = process.env.DEFAULT_BRAND_ID;
const service = new PublicBrandContextService({} as PrismaService);
try {
delete process.env.DEFAULT_BRAND_ID;
await assert.rejects(() => service.resolveId(), /默认品牌未配置/);
} finally {
if (previous !== undefined) process.env.DEFAULT_BRAND_ID = previous;
else delete process.env.DEFAULT_BRAND_ID;
}
});
@@ -123,6 +123,24 @@ test("uninstalled historical snapshots are reported without blocking mapped bran
});
});
test("migration audit supports the post-migration single-contract schema", () => {
const report = buildTemplateContractMigrationReport({
brands: [
brandRow({
brandVisualTemplateKey: null,
installationPackageVersionId: "version-1",
snapshotPackageKey: "acheng-campus-food",
}),
],
versions: [packageVersion({ visualTemplateKey: undefined })],
});
assert.equal(report.ready, true);
assert.equal(report.brands[0].mappingSource, "installation.configSnapshot.packageKey");
assert.equal(report.brands[0].packageKey, "acheng-campus-food");
assert.deepEqual(report.brands[0].blockers, []);
});
test("migration audit blocks conflicting explicit package declarations", () => {
const report = buildTemplateContractMigrationReport({
brands: [brandRow({ installationVisualTemplateKey: "linjing-editorial" })],
@@ -45,7 +45,7 @@ async function main() {
.filter((entry) => entry.isDirectory() && entry.name !== targetMigration)
.map((entry) => entry.name)
.sort();
assert.equal(migrationDirs.at(-1), "20261017120000_template_operation_failure_events");
assert.equal(migrationDirs.at(-1), "20261018170000_add_admin_token_version");
await admin.$executeRawUnsafe(`CREATE SCHEMA "${schema}"`);
createdSchema = true;