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

+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);
}