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,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")