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 -1
View File
@@ -32,7 +32,7 @@
"bcryptjs": "^2.4.3",
"class-transformer": "^0.5.1",
"class-validator": "^0.14.1",
"fastify": "^5.11.3",
"fastify": "^5.12.7",
"miniprogram-ci": "^2.1.31",
"prisma": "^6.2.1",
"reflect-metadata": "^0.2.2",
@@ -0,0 +1,2 @@
-- 管理员 token 版本用于密码修改后撤销既有登录态。
ALTER TABLE "AdminUser" ADD COLUMN "tokenVersion" INTEGER NOT NULL DEFAULT 0;
+1
View File
@@ -458,6 +458,7 @@ model AdminUser {
platformTemplateRole PlatformTemplateRole @default(none)
isEnabled Boolean @default(true)
mustChangePassword Boolean @default(false)
tokenVersion Int @default(0)
lastLoginAt DateTime?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@ -151,34 +151,78 @@ export function buildTemplateContractMigrationReport({ brands, versions }) {
async function main() {
const prisma = new PrismaClient();
try {
const columns = await prisma.$queryRaw`
SELECT table_name, column_name
FROM information_schema.columns
WHERE table_schema = current_schema()
AND (
(table_name = 'BrandTemplateInstallation' AND column_name = 'visualTemplateKey')
OR (table_name = 'TemplatePackageVersion' AND column_name = 'visualTemplateKey')
)
`;
const hasInstallationVisualColumn = columns.some(
(column) => column.table_name === "BrandTemplateInstallation",
);
const hasVersionVisualColumn = columns.some(
(column) => column.table_name === "TemplatePackageVersion",
);
const [brands, versions] = await Promise.all([
prisma.$queryRaw`
SELECT
brand."id" AS "brandId",
brand."slug",
brand."templateKey" AS "industry",
brand."config"->>'visualTemplateKey' AS "brandVisualTemplateKey",
installation."id" AS "installationId",
installation."visualTemplateKey" AS "installationVisualTemplateKey",
installation."templatePackageVersionId" AS "installationPackageVersionId",
installation."configSnapshot"->>'visualTemplateKey' AS "snapshotVisualTemplateKey",
installation."configSnapshot"->>'packageKey' AS "snapshotPackageKey"
FROM "BrandProfile" brand
LEFT JOIN "BrandTemplateInstallation" installation
ON installation."brandId" = brand."id"
ORDER BY brand."slug", installation."id"
`,
prisma.$queryRaw`
SELECT
"id",
"packageKey",
"version",
"status",
"visualTemplateKey",
"manifestSnapshot"
FROM "TemplatePackageVersion"
ORDER BY "packageKey", "version"
`,
hasInstallationVisualColumn
? prisma.$queryRaw`
SELECT
brand."id" AS "brandId",
brand."slug",
brand."templateKey" AS "industry",
brand."config"->>'visualTemplateKey' AS "brandVisualTemplateKey",
installation."id" AS "installationId",
installation."visualTemplateKey" AS "installationVisualTemplateKey",
installation."templatePackageVersionId" AS "installationPackageVersionId",
installation."configSnapshot"->>'visualTemplateKey' AS "snapshotVisualTemplateKey",
installation."configSnapshot"->>'packageKey' AS "snapshotPackageKey"
FROM "BrandProfile" brand
LEFT JOIN "BrandTemplateInstallation" installation
ON installation."brandId" = brand."id"
ORDER BY brand."slug", installation."id"
`
: prisma.$queryRaw`
SELECT
brand."id" AS "brandId",
brand."slug",
brand."templateKey" AS "industry",
NULL AS "brandVisualTemplateKey",
installation."id" AS "installationId",
NULL AS "installationVisualTemplateKey",
installation."templatePackageVersionId" AS "installationPackageVersionId",
NULL AS "snapshotVisualTemplateKey",
installation."configSnapshot"->>'packageKey' AS "snapshotPackageKey"
FROM "BrandProfile" brand
LEFT JOIN "BrandTemplateInstallation" installation
ON installation."brandId" = brand."id"
ORDER BY brand."slug", installation."id"
`,
hasVersionVisualColumn
? prisma.$queryRaw`
SELECT
"id",
"packageKey",
"version",
"status",
"visualTemplateKey",
"manifestSnapshot"
FROM "TemplatePackageVersion"
ORDER BY "packageKey", "version"
`
: prisma.$queryRaw`
SELECT
"id",
"packageKey",
"version",
"status",
NULL AS "visualTemplateKey",
"manifestSnapshot"
FROM "TemplatePackageVersion"
ORDER BY "packageKey", "version"
`,
]);
process.stdout.write(
`${JSON.stringify(buildTemplateContractMigrationReport({ brands, versions }), null, 2)}\n`,
+13 -4
View File
@@ -21,9 +21,11 @@ export class AdminAccessService {
if (identity.role !== "admin") throw new ForbiddenException("无管理员权限");
const user = await this.prisma.adminUser.findUnique({
where: { id: identity.subject },
select: { mustChangePassword: true, isEnabled: true },
select: { mustChangePassword: true, isEnabled: true, tokenVersion: true },
});
if (!user?.isEnabled || user.mustChangePassword)
if (!user || identity.tokenVersion !== user.tokenVersion)
throw new UnauthorizedException("管理员登录态已失效,请重新登录");
if (!user.isEnabled || user.mustChangePassword)
throw new ForbiddenException("请先完成初始密码修改后再访问管理后台");
const membership = await this.prisma.brandMembership.findUnique({
where: { adminUserId_brandId: { adminUserId: identity.subject, brandId: identity.brandId } },
@@ -52,9 +54,16 @@ export class AdminAccessService {
if (identity.role !== "admin") throw new ForbiddenException("无管理员权限");
const user = await this.prisma.adminUser.findUnique({
where: { id: identity.subject },
select: { isEnabled: true, mustChangePassword: true, platformTemplateRole: true },
select: {
isEnabled: true,
mustChangePassword: true,
platformTemplateRole: true,
tokenVersion: true,
},
});
if (!user?.isEnabled || user.mustChangePassword)
if (!user || identity.tokenVersion !== user.tokenVersion)
throw new UnauthorizedException("管理员登录态已失效,请重新登录");
if (!user.isEnabled || user.mustChangePassword)
throw new ForbiddenException("请先完成初始密码修改后再访问管理后台");
if (user.platformTemplateRole !== "template_admin")
throw new ForbiddenException("当前账号没有模板管理权限");
+11 -14
View File
@@ -1,4 +1,4 @@
import { Injectable, UnauthorizedException } from "@nestjs/common";
import { ForbiddenException, Injectable, UnauthorizedException } from "@nestjs/common";
import bcrypt from "bcryptjs";
import { PrismaService } from "./prisma.service.js";
import { signIdentity } from "./auth.js";
@@ -29,24 +29,17 @@ export class AdminAuthService {
where: { adminUserId: user.id, isEnabled: true },
orderBy: { createdAt: "asc" },
});
const activeMembership =
membership ??
(await this.prisma.brandMembership.create({
data: {
adminUserId: user.id,
brandId: process.env.DEFAULT_BRAND_ID ?? "00000000-0000-0000-0000-000000000001",
role: "owner",
},
}));
if (!membership) throw new ForbiddenException("管理员没有品牌权限,请先联系平台负责人分配");
return {
token: signIdentity({
subject: user.id,
brandId: activeMembership.brandId,
brandId: membership.brandId,
role: "admin",
tokenVersion: user.tokenVersion,
}),
displayName: user.displayName,
mustChangePassword: user.mustChangePassword,
role: activeMembership.role,
role: membership.role,
platformTemplateRole: user.platformTemplateRole,
};
}
@@ -57,12 +50,16 @@ export class AdminAuthService {
newPassword: string,
): Promise<void> {
const user = await this.prisma.adminUser.findUnique({ where: { id: userId } });
if (!user || !(await bcrypt.compare(currentPassword, user.passwordHash))) {
if (!user?.isEnabled || !(await bcrypt.compare(currentPassword, user.passwordHash))) {
throw new UnauthorizedException("当前密码不正确");
}
await this.prisma.adminUser.update({
where: { id: userId },
data: { passwordHash: await bcrypt.hash(newPassword, 12), mustChangePassword: false },
data: {
passwordHash: await bcrypt.hash(newPassword, 12),
mustChangePassword: false,
tokenVersion: { increment: 1 },
},
});
}
}
+7 -2
View File
@@ -5,14 +5,19 @@ import { AdminAccessService } from "./admin-access.service.js";
const PATH_METADATA = "path";
function metadataPath(target: object): string | undefined {
const value = Reflect.getMetadata(PATH_METADATA, target) as unknown;
return typeof value === "string" ? value : undefined;
}
@Injectable()
export class AdminMembershipGuard implements CanActivate {
constructor(private readonly access: AdminAccessService) {}
canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest<FastifyRequest>();
const handlerPath = Reflect.getMetadata(PATH_METADATA, context.getHandler());
const controllerPath = Reflect.getMetadata(PATH_METADATA, context.getClass());
const handlerPath = metadataPath(context.getHandler());
const controllerPath = metadataPath(context.getClass());
const routePath = `${controllerPath ?? ""}/${handlerPath ?? ""}`.replace(/^\/+|\/+$/g, "");
if (routePath === "admin/session/login") return Promise.resolve(true);
if (routePath === "admin/session/change-password") return Promise.resolve(true);
+10 -1
View File
@@ -36,5 +36,14 @@ export function configureApp(app: NestFastifyApplication): void {
const apiPrefix = process.env.API_PREFIX?.replace(/^\/+|\/+$/g, "");
if (apiPrefix) app.setGlobalPrefix(apiPrefix);
app.use(new RequestIdMiddleware().use.bind(new RequestIdMiddleware()));
app.enableCors();
const corsOrigins = (process.env.CORS_ORIGINS ?? "")
.split(",")
.map((origin) => origin.trim())
.filter(Boolean);
app.enableCors({
origin: corsOrigins.length > 0 ? corsOrigins : false,
methods: ["GET", "POST", "PATCH", "PUT", "DELETE", "OPTIONS"],
allowedHeaders: ["Authorization", "Content-Type", "X-Request-Id"],
credentials: false,
});
}
+12 -2
View File
@@ -1,7 +1,13 @@
import { UnauthorizedException } from "@nestjs/common";
import { createHmac, timingSafeEqual } from "node:crypto";
type Identity = { subject: string; brandId: string; role: "customer" | "admin"; exp: number };
type Identity = {
subject: string;
brandId: string;
role: "customer" | "admin";
tokenVersion?: number;
exp: number;
};
function secret(): string {
const value = process.env.SESSION_SECRET;
@@ -14,7 +20,11 @@ export function signIdentity(
ttlSeconds = 60 * 60 * 24 * 7,
): string {
const payload = Buffer.from(
JSON.stringify({ ...identity, exp: Math.floor(Date.now() / 1000) + ttlSeconds }),
JSON.stringify({
...identity,
tokenVersion: identity.tokenVersion ?? 0,
exp: Math.floor(Date.now() / 1000) + ttlSeconds,
}),
).toString("base64url");
const signature = createHmac("sha256", secret()).update(payload).digest("base64url");
return `${payload}.${signature}`;
@@ -1,5 +1,4 @@
import {
BadRequestException,
Body,
Controller,
Delete,
@@ -30,8 +29,7 @@ export class AdminConfigController {
private readonly templateWorkspace: TemplateWorkspaceService,
private readonly brandConfig: AdminBrandConfigService,
) {}
private brandId(request?: FastifyRequest): string {
if (!request) return process.env.DEFAULT_BRAND_ID ?? "00000000-0000-0000-0000-000000000001";
private brandId(request: FastifyRequest): string {
const token = request.headers.authorization?.replace(/^Bearer\s+/i, "");
if (!token) throw new UnauthorizedException("缺少管理员登录态");
const identity = readIdentity(token);
@@ -12,11 +12,7 @@ import {
AdminMiniAppReleaseService,
miniAppAttemptLeaseMs,
} from "./admin-miniapp-release.service.js";
import {
miniappReleaseOutputRoot,
miniappReleaseProjectPath,
miniappTaroOutputRoot,
} from "./miniapp-artifact.js";
import { miniappReleaseProjectPath, miniappTaroOutputRoot } from "./miniapp-artifact.js";
import { miniappApiBaseUrl, weappAppId } from "./miniapp-build-config.js";
import { buildingStaleMs, isStaleBuilding } from "./miniapp-build-status.js";
import { decryptMiniAppCredential } from "./miniapp-credential-crypto.js";
@@ -90,12 +86,6 @@ export class AdminMiniAppUploadService {
if (!canReuseArtifact) {
const buildAttempt = await this.releases.acquireAttempt(brandId, actorId, taskId, "build");
const outputRoot = miniappReleaseOutputRoot(
brand.slug ?? brandId,
templateKey,
templateManifest.version,
buildAttempt.id,
);
projectPath = miniappReleaseProjectPath(
brand.slug ?? brandId,
templateKey,
@@ -432,7 +432,7 @@ export class AdminTemplatePackageService {
throw new BadRequestException("package.json version 与 template.json version 不一致");
let errors: string[];
try {
errors = validateTemplatePackageManifest(manifest as never);
errors = validateTemplatePackageManifest(manifest);
} catch {
throw new BadRequestException("template.json 不符合模板契约");
}
@@ -245,7 +245,7 @@ export class AdminTemplatePreviewService {
throw new BadRequestException(
`模板 previewFixture 不符合预览契约:${fixtureIssues.map((issue) => `${issue.path}: ${issue.message}`).join(";")}`,
);
const sample = fixture!.content as TemplateSampleContent;
const sample = fixture!.content;
const missingSampleSlots = this.missingSampleSlots(manifest, sample);
if (missingSampleSlots.length)
blockers.push(`preview sample 缺少必需数据:${missingSampleSlots.join("、")}`);
@@ -294,7 +294,7 @@ export class AdminTemplatePreviewService {
version.id,
manifest,
industryTemplate!,
sample!,
sample,
fixture?.brand,
);
return {
@@ -352,8 +352,8 @@ export class AdminTemplatePreviewService {
slot.target === "brand"
? [record(workspace.brand)]
: slot.target === "offering"
? sample!.offerings
: sample!.trustContent;
? sample.offerings
: sample.trustContent;
const path = slot.binding.split(".").slice(1);
const values = sources.map((source) => resolve(record(source), path));
const populated = values.filter(
@@ -1,5 +1,5 @@
import { HttpException } from "@nestjs/common";
import { PrismaService } from "../../prisma.service.js";
import type { PrismaService } from "../../prisma.service.js";
export async function recordTemplateOperationFailure(
prisma: PrismaService,
@@ -3,7 +3,6 @@ import {
Controller,
ForbiddenException,
Get,
NotFoundException,
Param,
Post,
Req,
@@ -1,14 +1,16 @@
import { Injectable, NotFoundException } from "@nestjs/common";
import { Injectable, NotFoundException, ServiceUnavailableException } from "@nestjs/common";
import { PrismaService } from "../../prisma.service.js";
const FALLBACK_BRAND_ID = "00000000-0000-0000-0000-000000000001";
@Injectable()
export class PublicBrandContextService {
constructor(private readonly prisma: PrismaService) {}
async resolveId(brandSlug?: string): Promise<string> {
if (!brandSlug) return process.env.DEFAULT_BRAND_ID ?? FALLBACK_BRAND_ID;
if (!brandSlug) {
const defaultBrandId = process.env.DEFAULT_BRAND_ID;
if (!defaultBrandId) throw new ServiceUnavailableException("默认品牌未配置");
return defaultBrandId;
}
const brand = await this.prisma.brandProfile.findUnique({
where: { slug: brandSlug },
select: { id: true },
@@ -1,11 +1,4 @@
import {
BadRequestException,
Controller,
Get,
NotFoundException,
Param,
Query,
} from "@nestjs/common";
import { Controller, Get, NotFoundException, Param, Query } from "@nestjs/common";
import { PublicBrandContextService } from "./public-brand-context.service.js";
import { BrandReleaseService } from "../../brand-release.service.js";
@@ -107,7 +107,12 @@ export class TenantService {
});
if (!membership) throw new ForbiddenException("没有该品牌的管理权限");
return {
token: signIdentity({ subject: identity.subject, brandId, role: "admin" }),
token: signIdentity({
subject: identity.subject,
brandId,
role: "admin",
tokenVersion: identity.tokenVersion ?? 0,
}),
brand: membership.brand,
};
}
@@ -6,6 +6,7 @@ export type AdminIdentity = {
subject: string;
brandId: string;
role: "admin";
tokenVersion: number;
};
export function requireAdminIdentity(request: FastifyRequest): AdminIdentity {
@@ -9,7 +9,6 @@ import {
} from "@personal-brand/config";
import { validateFieldSnapshot } from "@personal-brand/validation";
import { PrismaService } from "../../prisma.service.js";
import { TemplateWorkspaceService } from "../../template-workspace.service.js";
type BootstrapSource = {
kind: "package_version";
@@ -74,10 +73,7 @@ function asJson(value: unknown): Prisma.InputJsonValue {
@Injectable()
export class AdminSampleContentService {
constructor(
private readonly prisma: PrismaService,
_templateWorkspace: TemplateWorkspaceService,
) {}
constructor(private readonly prisma: PrismaService) {}
async preview(brandId: string, query?: { templatePackageVersionId?: string }) {
const { brand, source, visualTemplateKey } = await this.resolveSource(
@@ -222,10 +218,10 @@ export class AdminSampleContentService {
await tx.templateBootstrapImport.create({
data: {
brandId,
templatePackageVersionId: source.version!.id,
packageKey: source.version!.packageKey,
packageVersion: source.version!.version,
contentChecksum: source.version!.contentChecksum,
templatePackageVersionId: source.version.id,
packageKey: source.version.packageKey,
packageVersion: source.version.version,
contentChecksum: source.version.contentChecksum,
actorId,
strategy: "missing_only",
status: "imported",
@@ -294,7 +290,9 @@ export class AdminSampleContentService {
throw new BadRequestException("sampleContent 行业与品牌不匹配");
const fieldIssues = validateFieldSnapshot(source.sample.fields);
if (fieldIssues.length)
throw new BadRequestException(`bootstrap 表单字段无效:${fieldIssues.join(";")}`);
throw new BadRequestException(
`bootstrap 表单字段无效:${fieldIssues.map((issue) => `${issue.path}: ${issue.message}`).join(";")}`,
);
return { brand, source, visualTemplateKey };
}
@@ -2,16 +2,11 @@ import { Body, Controller, Get, Post, Req } from "@nestjs/common";
import type { FastifyRequest } from "fastify";
import { RollbackTemplateDto, UpgradeTemplateDto } from "../../admin.dto.js";
import { TemplateWorkspaceService } from "../../template-workspace.service.js";
import { PrismaService } from "../../prisma.service.js";
import { recordTemplateOperationFailure } from "../admin/template-operation-failure.js";
import { requireAdminIdentity } from "./admin-access.identity.js";
@Controller("admin/workspace")
class AdminTemplateController {
constructor(
private readonly templateWorkspace: TemplateWorkspaceService,
private readonly prisma: PrismaService,
) {}
constructor(private readonly templateWorkspace: TemplateWorkspaceService) {}
@Get("template/preview")
preview(@Req() request: FastifyRequest): Promise<unknown> {
@@ -25,26 +20,7 @@ class AdminTemplateController {
): Promise<unknown> {
const identity = requireAdminIdentity(request);
const requestId = request.headers["x-request-id"]?.toString() ?? request.id;
try {
return await this.templateWorkspace.upgrade(
identity.brandId,
body,
identity.subject,
requestId,
);
} catch (error) {
await recordTemplateOperationFailure(this.prisma, {
action:
error instanceof Error && error.name.includes("Conflict")
? "install_conflict"
: "upgrade",
error,
requestId,
actorId: identity.subject,
brandId: identity.brandId,
});
throw error;
}
return this.templateWorkspace.upgrade(identity.brandId, body, identity.subject, requestId);
}
@Post("template/rollback")
@@ -54,23 +30,7 @@ class AdminTemplateController {
): Promise<unknown> {
const identity = requireAdminIdentity(request);
const requestId = request.headers["x-request-id"]?.toString() ?? request.id;
try {
return await this.templateWorkspace.rollback(
identity.brandId,
identity.subject,
body,
requestId,
);
} catch (error) {
await recordTemplateOperationFailure(this.prisma, {
action: "rollback",
error,
requestId,
actorId: identity.subject,
brandId: identity.brandId,
});
throw error;
}
return this.templateWorkspace.rollback(identity.brandId, identity.subject, body, requestId);
}
}
@@ -4,15 +4,12 @@ import { InstallTemplateDto, SelectTemplateVersionDto } from "../../admin.dto.js
import { TemplateWorkspaceService } from "../../template-workspace.service.js";
import { requireAdminIdentity } from "./admin-access.identity.js";
import { AdminWorkspaceService } from "./admin-workspace.service.js";
import { PrismaService } from "../../prisma.service.js";
import { recordTemplateOperationFailure } from "../admin/template-operation-failure.js";
@Controller("admin/workspace")
class AdminWorkspacePreviewController {
constructor(
private readonly workspaceService: AdminWorkspaceService,
private readonly templateWorkspace: TemplateWorkspaceService,
private readonly prisma: PrismaService,
) {}
@Get()
@@ -32,25 +29,13 @@ class AdminWorkspacePreviewController {
): Promise<unknown> {
const identity = requireAdminIdentity(request);
const requestId = request.headers["x-request-id"]?.toString() ?? request.id;
try {
return await this.templateWorkspace.install(
identity.brandId,
body.templateKey,
body.templatePackageVersionId,
);
} catch (error) {
await recordTemplateOperationFailure(this.prisma, {
action:
error instanceof Error && error.name.includes("Conflict")
? "install_conflict"
: "install",
error,
requestId,
actorId: identity.subject,
brandId: identity.brandId,
});
throw error;
}
return this.templateWorkspace.install(
identity.brandId,
body.templateKey,
body.templatePackageVersionId,
identity.subject,
requestId,
);
}
@Post("template/select-version")
+95 -5
View File
@@ -13,6 +13,7 @@ import type { TemplatePackageManifest } from "@personal-brand/config";
import type { CreateTrustContentDto, UpdateTrustContentDto } from "./admin.dto.js";
import type { RollbackTemplateDto, UpgradeTemplateDto } from "./admin.dto.js";
import { PrismaService } from "./prisma.service.js";
import { recordTemplateOperationFailure } from "./modules/admin/template-operation-failure.js";
@Injectable()
export class TemplateWorkspaceService {
@@ -27,7 +28,7 @@ export class TemplateWorkspaceService {
const manifest = record(
installation.templatePackageVersion.manifestSnapshot,
) as unknown as TemplatePackageManifest;
if (validateTemplatePackageManifest(manifest as unknown as TemplatePackageManifest).length)
if (validateTemplatePackageManifest(manifest).length)
throw new BadRequestException("当前安装的模板包不符合统一模板契约");
return manifest.trustContentTypes?.map((item) => item.type) ?? [];
}
@@ -88,7 +89,32 @@ export class TemplateWorkspaceService {
throw new BadRequestException("品牌行业模型与模板安装不一致,请修复安装数据");
return template.key;
}
async install(brandId: string, templateKey: BrandTemplateKey, templatePackageVersionId: string) {
async install(
brandId: string,
templateKey: BrandTemplateKey,
templatePackageVersionId: string,
actorId: string,
requestId?: string,
) {
try {
return await this.installTemplate(brandId, templateKey, templatePackageVersionId);
} catch (error) {
await recordTemplateOperationFailure(this.prisma, {
action: error instanceof ConflictException ? "install_conflict" : "install",
error,
...(requestId ? { requestId } : {}),
actorId,
brandId,
});
throw error;
}
}
private async installTemplate(
brandId: string,
templateKey: BrandTemplateKey,
templatePackageVersionId: string,
) {
const template = getBrandTemplate(templateKey);
if (!template) throw new BadRequestException("行业模板不存在");
const [existing, brand] = await Promise.all([
@@ -171,7 +197,7 @@ export class TemplateWorkspaceService {
) {
throw new BadRequestException("模板包版本与行业或视觉模板不匹配");
}
if (validateTemplatePackageManifest(manifest as unknown as TemplatePackageManifest).length)
if (validateTemplatePackageManifest(manifest).length)
throw new BadRequestException("模板包版本不符合统一模板契约");
return version;
}
@@ -185,6 +211,30 @@ export class TemplateWorkspaceService {
},
actorId: string,
requestId?: string,
) {
try {
return await this.selectVersionUnrecorded(brandId, body, actorId, requestId);
} catch (error) {
await recordTemplateOperationFailure(this.prisma, {
action: "select_version",
error,
...(requestId ? { requestId } : {}),
actorId,
brandId,
});
throw error;
}
}
private async selectVersionUnrecorded(
brandId: string,
body: {
templatePackageVersionId: string;
expectedCurrentPackageVersionId?: string | null;
confirm: boolean;
},
actorId: string,
requestId?: string,
) {
if (!body.confirm) throw new BadRequestException("选择模板版本必须显式确认");
const [installation, brand, target] = await Promise.all([
@@ -410,6 +460,26 @@ export class TemplateWorkspaceService {
};
}
async upgrade(brandId: string, body: UpgradeTemplateDto, actorId: string, requestId?: string) {
try {
return await this.upgradeUnrecorded(brandId, body, actorId, requestId);
} catch (error) {
await recordTemplateOperationFailure(this.prisma, {
action: error instanceof ConflictException ? "install_conflict" : "upgrade",
error,
...(requestId ? { requestId } : {}),
actorId,
brandId,
});
throw error;
}
}
private async upgradeUnrecorded(
brandId: string,
body: UpgradeTemplateDto,
actorId: string,
requestId?: string,
) {
if (!body.confirm) throw new BadRequestException("升级模板必须显式确认");
const installation = await this.installation(brandId);
const target = await this.prisma.templatePackageVersion.findUnique({
@@ -492,6 +562,26 @@ export class TemplateWorkspaceService {
});
}
async rollback(brandId: string, actorId: string, body: RollbackTemplateDto, requestId?: string) {
try {
return await this.rollbackUnrecorded(brandId, actorId, body, requestId);
} catch (error) {
await recordTemplateOperationFailure(this.prisma, {
action: "rollback",
error,
...(requestId ? { requestId } : {}),
actorId,
brandId,
});
throw error;
}
}
private async rollbackUnrecorded(
brandId: string,
actorId: string,
body: RollbackTemplateDto,
requestId?: string,
) {
if (!body.confirm) throw new BadRequestException("回滚模板必须显式确认");
const installation = await this.installation(brandId);
if (installation.templateVersion !== body.expectedCurrentVersion)
@@ -564,9 +654,9 @@ export class TemplateWorkspaceService {
}
}
async function readPackageFiles(
function readPackageFiles(
version: Pick<TemplatePackageVersion, "validationReport">,
): Promise<Record<string, unknown>[]> {
): Record<string, unknown>[] {
return manifestRecords(record(version.validationReport).files);
}
@@ -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;