From b4e3e86dcd99c18081769c378d8b1d9278e2aeaf Mon Sep 17 00:00:00 2001 From: que01 Date: Fri, 23 Oct 2026 12:26:37 +0800 Subject: [PATCH 01/10] =?UTF-8?q?refactor:=20=E6=8B=86=E5=88=86=E6=A8=A1?= =?UTF-8?q?=E6=9D=BF=E5=B7=A5=E4=BD=9C=E5=8C=BA=E6=9C=8D=E5=8A=A1=E5=B9=B6?= =?UTF-8?q?=E7=BB=9F=E4=B8=80=E5=90=8E=E5=8F=B0=E8=AE=BF=E9=97=AE=E6=8E=A7?= =?UTF-8?q?=E5=88=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../raw/completion-evidence.json | 4 +- .../modules/admin/admin-booking.controller.ts | 74 ++--- .../modules/admin/admin-config.controller.ts | 12 +- apps/api/src/modules/infrastructure.module.ts | 12 +- apps/api/src/modules/tenant/tenant.service.ts | 10 +- .../workspace/admin-template.controller.ts | 16 +- .../admin-workspace-capabilities.service.ts | 8 +- .../admin-workspace-preview.controller.ts | 8 +- .../api/src/template/manifest-diff.helpers.ts | 114 ++++++++ apps/api/src/template/page-scheme.service.ts | 105 +++++++ .../template-installation.service.ts} | 273 +----------------- .../api/src/template/trust-content.service.ts | 69 +++++ apps/api/test/http.integration.test.js | 65 +++++ 13 files changed, 441 insertions(+), 329 deletions(-) create mode 100644 apps/api/src/template/manifest-diff.helpers.ts create mode 100644 apps/api/src/template/page-scheme.service.ts rename apps/api/src/{template-workspace.service.ts => template/template-installation.service.ts} (72%) create mode 100644 apps/api/src/template/trust-content.service.ts diff --git a/.codex-tasks/template-audit-execution/raw/completion-evidence.json b/.codex-tasks/template-audit-execution/raw/completion-evidence.json index 4aac64f..d1e30bc 100644 --- a/.codex-tasks/template-audit-execution/raw/completion-evidence.json +++ b/.codex-tasks/template-audit-execution/raw/completion-evidence.json @@ -1,7 +1,7 @@ { "schemaVersion": 1, "scope": "模板完成证据登记,保留命令、日志与产物哈希", - "generatedAt": "2026-10-21T08:37:34.818Z", + "generatedAt": "2026-10-23T04:26:41.081Z", "templates": { "acheng-campus-food": { "real-manifest-interaction": { @@ -256,5 +256,5 @@ } } }, - "sourceTreeHash": "ba35ee9629ec5aa84b9984139a4dbabc60fb576b1178f936eb8161eb905184e7" + "sourceTreeHash": "753ccedf803e63f14d8eaa3e8abcac074e274f3aed2f4f2facc3a66f8022af24" } diff --git a/apps/api/src/modules/admin/admin-booking.controller.ts b/apps/api/src/modules/admin/admin-booking.controller.ts index 2460a5e..0cff204 100644 --- a/apps/api/src/modules/admin/admin-booking.controller.ts +++ b/apps/api/src/modules/admin/admin-booking.controller.ts @@ -1,22 +1,12 @@ import { AdminBrand } from "../../admin-auth.decorators.js"; -import { - Body, - Controller, - ForbiddenException, - Get, - Param, - Post, - Query, - Req, - UnauthorizedException, -} from "@nestjs/common"; +import { Body, Controller, Get, Param, Post, Query, Req } from "@nestjs/common"; import { Transform } from "class-transformer"; import type { TransformFnParams } from "class-transformer"; import { BookingStatus } from "@prisma/client"; import { IsBoolean, IsEnum, IsOptional, IsString } from "class-validator"; import type { FastifyRequest } from "fastify"; +import { AdminAccessService } from "../../admin-access.service.js"; import { BookingService } from "../../booking.service.js"; -import { readIdentity } from "../../auth.js"; import { UpdateBookingStatusDto, UpdateBookingTagsDto, CreateTagDto } from "../../admin.dto.js"; class AdminBookingQueryDto { @@ -35,67 +25,67 @@ class AdminBookingQueryDto { @AdminBrand() @Controller("admin/bookings") export class AdminBookingController { - constructor(private readonly bookings: BookingService) {} + constructor( + private readonly access: AdminAccessService, + private readonly bookings: BookingService, + ) {} @Get() - list(@Req() request: FastifyRequest, @Query() query: AdminBookingQueryDto): Promise { - const brandId = this.requireAdmin(request); + async list( + @Req() request: FastifyRequest, + @Query() query: AdminBookingQueryDto, + ): Promise { + const { brandId } = await this.access.requireBrand(request); return this.bookings.listForAdmin(brandId, query); } @Get("unread-count") - unreadCount(@Req() request: FastifyRequest): Promise { - return this.bookings.unreadCountForAdmin(this.requireAdmin(request)); + async unreadCount(@Req() request: FastifyRequest): Promise { + const { brandId } = await this.access.requireBrand(request); + return this.bookings.unreadCountForAdmin(brandId); } @Get(":id") - detail(@Req() request: FastifyRequest, @Param("id") id: string): Promise { - return this.bookings.getForAdmin(this.requireAdmin(request), id); + async detail(@Req() request: FastifyRequest, @Param("id") id: string): Promise { + const { brandId } = await this.access.requireBrand(request); + return this.bookings.getForAdmin(brandId, id); } @Post(":id/status") - update( + async update( @Req() request: FastifyRequest, @Param("id") id: string, @Body() body: UpdateBookingStatusDto, ): Promise { - return this.bookings.updateStatus(this.requireAdmin(request), id, body.status, body.adminNote); + const { brandId } = await this.access.requireBrand(request); + return this.bookings.updateStatus(brandId, id, body.status, body.adminNote); } @Post(":id/read") - markRead(@Req() request: FastifyRequest, @Param("id") id: string): Promise { - return this.bookings.markRead(this.requireAdmin(request), id); + async markRead(@Req() request: FastifyRequest, @Param("id") id: string): Promise { + const { brandId } = await this.access.requireBrand(request); + return this.bookings.markRead(brandId, id); } @Post(":id/tags") - updateTags( + async updateTags( @Req() request: FastifyRequest, @Param("id") id: string, @Body() body: UpdateBookingTagsDto, ): Promise { - return this.bookings.updateTags(this.requireAdmin(request), id, body.tagIds); + const { brandId } = await this.access.requireBrand(request); + return this.bookings.updateTags(brandId, id, body.tagIds); } @Get("tags") - listTags(@Req() request: FastifyRequest): Promise { - return this.bookings.listTags(this.requireAdmin(request)); + async listTags(@Req() request: FastifyRequest): Promise { + const { brandId } = await this.access.requireBrand(request); + return this.bookings.listTags(brandId); } @Post("tags") - createTag(@Req() request: FastifyRequest, @Body() body: CreateTagDto): Promise { - return this.bookings.createTag(this.requireAdmin(request), body.name); - } - - private requireAdmin(request: FastifyRequest): string { - const token = request.headers.authorization?.replace(/^Bearer\s+/i, ""); - if (!token) throw new UnauthorizedException("缺少管理员登录态"); - let identity; - try { - identity = readIdentity(token); - } catch { - throw new UnauthorizedException("管理员登录态无效或已过期"); - } - if (identity.role !== "admin") throw new ForbiddenException("无管理员权限"); - return identity.brandId; + async createTag(@Req() request: FastifyRequest, @Body() body: CreateTagDto): Promise { + const { brandId } = await this.access.requireBrand(request); + return this.bookings.createTag(brandId, body.name); } } diff --git a/apps/api/src/modules/admin/admin-config.controller.ts b/apps/api/src/modules/admin/admin-config.controller.ts index 2980ee4..2bb229c 100644 --- a/apps/api/src/modules/admin/admin-config.controller.ts +++ b/apps/api/src/modules/admin/admin-config.controller.ts @@ -7,7 +7,7 @@ import { UpdateBrandPresentationDto, UpdateTrustContentDto, } from "../../admin.dto.js"; -import { TemplateWorkspaceService } from "../../template-workspace.service.js"; +import { TrustContentService } from "../../template/trust-content.service.js"; import { requireAdminIdentity } from "../../admin-access.identity.js"; import { AdminBrandConfigService } from "./admin-brand-config.service.js"; @@ -15,7 +15,7 @@ import { AdminBrandConfigService } from "./admin-brand-config.service.js"; @Controller("admin/config") export class AdminConfigController { constructor( - private readonly templateWorkspace: TemplateWorkspaceService, + private readonly trustContent: TrustContentService, private readonly brandConfig: AdminBrandConfigService, ) {} @Get("brand") @@ -42,7 +42,7 @@ export class AdminConfigController { @Get("trust-content") listTrustContent(@Req() request: FastifyRequest): Promise { const identity = requireAdminIdentity(request); - return this.templateWorkspace.listTrustContent(identity.brandId); + return this.trustContent.listTrustContent(identity.brandId); } @Post("trust-content") createTrustContent( @@ -50,7 +50,7 @@ export class AdminConfigController { @Body() body: CreateTrustContentDto, ): Promise { const identity = requireAdminIdentity(request); - return this.templateWorkspace.createTrustContent(identity.brandId, body); + return this.trustContent.createTrustContent(identity.brandId, body); } @Patch("trust-content/:id") updateTrustContent( @@ -59,7 +59,7 @@ export class AdminConfigController { @Body() body: UpdateTrustContentDto, ): Promise { const identity = requireAdminIdentity(request); - return this.templateWorkspace.updateTrustContent(identity.brandId, id, body); + return this.trustContent.updateTrustContent(identity.brandId, id, body); } @Delete("trust-content/:id") async deleteTrustContent( @@ -67,6 +67,6 @@ export class AdminConfigController { @Param("id") id: string, ): Promise { const identity = requireAdminIdentity(request); - return this.templateWorkspace.deleteTrustContent(identity.brandId, id); + return this.trustContent.deleteTrustContent(identity.brandId, id); } } diff --git a/apps/api/src/modules/infrastructure.module.ts b/apps/api/src/modules/infrastructure.module.ts index 0ba48e9..8402988 100644 --- a/apps/api/src/modules/infrastructure.module.ts +++ b/apps/api/src/modules/infrastructure.module.ts @@ -4,7 +4,9 @@ import { AdminMembershipGuard } from "../admin-membership.guard.js"; import { BrandReleaseApiService } from "../brand-release-api.service.js"; import { BrandReleaseService } from "../brand-release.service.js"; import { PrismaService } from "../prisma.service.js"; -import { TemplateWorkspaceService } from "../template-workspace.service.js"; +import { PageSchemeService } from "../template/page-scheme.service.js"; +import { TemplateInstallationService } from "../template/template-installation.service.js"; +import { TrustContentService } from "../template/trust-content.service.js"; import { WechatAuthService } from "../wechat-auth.js"; @Module({ @@ -15,7 +17,9 @@ import { WechatAuthService } from "../wechat-auth.js"; AdminMembershipGuard, BrandReleaseService, BrandReleaseApiService, - TemplateWorkspaceService, + PageSchemeService, + TemplateInstallationService, + TrustContentService, ], exports: [ PrismaService, @@ -24,7 +28,9 @@ import { WechatAuthService } from "../wechat-auth.js"; AdminMembershipGuard, BrandReleaseService, BrandReleaseApiService, - TemplateWorkspaceService, + PageSchemeService, + TemplateInstallationService, + TrustContentService, ], }) export class InfrastructureModule {} diff --git a/apps/api/src/modules/tenant/tenant.service.ts b/apps/api/src/modules/tenant/tenant.service.ts index 83e591a..8281a9b 100644 --- a/apps/api/src/modules/tenant/tenant.service.ts +++ b/apps/api/src/modules/tenant/tenant.service.ts @@ -14,7 +14,8 @@ import type { CreateBrandMemberDto, UpdateBrandMemberDto, } from "../../admin.dto.js"; -import { TemplateWorkspaceService } from "../../template-workspace.service.js"; +import { PageSchemeService } from "../../template/page-scheme.service.js"; +import { TemplateInstallationService } from "../../template/template-installation.service.js"; type AdminIdentity = { subject: string; brandId: string; tokenVersion?: number }; @@ -22,11 +23,12 @@ type AdminIdentity = { subject: string; brandId: string; tokenVersion?: number } export class TenantService { constructor( private readonly prisma: PrismaService, - private readonly templateWorkspace: TemplateWorkspaceService, + private readonly pageSchemes: PageSchemeService, + private readonly templateInstallations: TemplateInstallationService, ) {} async getCreationOptions() { - const catalog = await this.templateWorkspace.getPageSchemeCatalog(); + const catalog = await this.pageSchemes.getPageSchemeCatalog(); // 创建品牌只应从每个页面方案的最新已发布版本开始;旧版本仍可在页面方案页显式切换。 return { ...catalog, @@ -40,7 +42,7 @@ export class TenantService { const name = body.name.trim(); const slug = body.slug.trim(); if (!name || !slug) throw new BadRequestException("品牌名称和小程序地址标识不能为空"); - const packageVersion = await this.templateWorkspace.resolveInstallablePackageVersion( + const packageVersion = await this.templateInstallations.resolveInstallablePackageVersion( body.businessType, body.templatePackageVersionId, ); diff --git a/apps/api/src/modules/workspace/admin-template.controller.ts b/apps/api/src/modules/workspace/admin-template.controller.ts index 689ab86..70a72b7 100644 --- a/apps/api/src/modules/workspace/admin-template.controller.ts +++ b/apps/api/src/modules/workspace/admin-template.controller.ts @@ -2,24 +2,28 @@ import { AdminBrand, AdminRoles } from "../../admin-auth.decorators.js"; 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 { PageSchemeService } from "../../template/page-scheme.service.js"; +import { TemplateInstallationService } from "../../template/template-installation.service.js"; import { requireAdminIdentity } from "../../admin-access.identity.js"; @AdminBrand() @Controller("admin/workspace") class AdminTemplateController { - constructor(private readonly templateWorkspace: TemplateWorkspaceService) {} + constructor( + private readonly pageSchemes: PageSchemeService, + private readonly templateInstallations: TemplateInstallationService, + ) {} @AdminRoles(["owner", "admin", "platform-admin"]) @Get("template/options") options(@Req() request: FastifyRequest): Promise { - return this.templateWorkspace.getPageSchemeOptions(requireAdminIdentity(request).brandId); + return this.pageSchemes.getPageSchemeOptions(requireAdminIdentity(request).brandId); } @AdminRoles(["owner", "admin", "platform-admin"]) @Get("template/preview") preview(@Req() request: FastifyRequest): Promise { - return this.templateWorkspace.preview(requireAdminIdentity(request).brandId); + return this.templateInstallations.preview(requireAdminIdentity(request).brandId); } @AdminRoles(["owner", "admin", "platform-admin"]) @@ -30,7 +34,7 @@ class AdminTemplateController { ): Promise { const identity = requireAdminIdentity(request); const requestId = request.headers["x-request-id"]?.toString() ?? request.id; - return this.templateWorkspace.upgrade(identity.brandId, body, identity.subject, requestId); + return this.templateInstallations.upgrade(identity.brandId, body, identity.subject, requestId); } @AdminRoles(["owner", "admin", "platform-admin"]) @@ -41,7 +45,7 @@ class AdminTemplateController { ): Promise { const identity = requireAdminIdentity(request); const requestId = request.headers["x-request-id"]?.toString() ?? request.id; - return this.templateWorkspace.rollback(identity.brandId, identity.subject, body, requestId); + return this.templateInstallations.rollback(identity.brandId, identity.subject, body, requestId); } } diff --git a/apps/api/src/modules/workspace/admin-workspace-capabilities.service.ts b/apps/api/src/modules/workspace/admin-workspace-capabilities.service.ts index e4970bd..121dcba 100644 --- a/apps/api/src/modules/workspace/admin-workspace-capabilities.service.ts +++ b/apps/api/src/modules/workspace/admin-workspace-capabilities.service.ts @@ -8,19 +8,19 @@ import { validateCapabilityConfig, } from "@personal-brand/config"; import { PrismaService } from "../../prisma.service.js"; -import { TemplateWorkspaceService } from "../../template-workspace.service.js"; +import { TemplateInstallationService } from "../../template/template-installation.service.js"; import type { UpdateCapabilityInstallationDto } from "../../admin.dto.js"; @Injectable() export class AdminWorkspaceCapabilitiesService { constructor( private readonly prisma: PrismaService, - private readonly templateWorkspace: TemplateWorkspaceService, + private readonly templateInstallations: TemplateInstallationService, ) {} async list(brandId: string) { const [templateKey, installations] = await Promise.all([ - this.templateWorkspace.getEffectiveTemplateKey(brandId), + this.templateInstallations.getEffectiveTemplateKey(brandId), this.prisma.capabilityInstallation.findMany({ where: { brandId } }), ]); const installed = new Map(installations.map((item) => [item.capabilityKey, item])); @@ -54,7 +54,7 @@ export class AdminWorkspaceCapabilitiesService { body: UpdateCapabilityInstallationDto, ) { const template = getBrandTemplate( - await this.templateWorkspace.getEffectiveTemplateKey(brandId), + await this.templateInstallations.getEffectiveTemplateKey(brandId), ); if (!template?.capabilities.includes(key as never) && !(key in capabilityPlugins)) throw new BadRequestException("能力未被当前模板声明"); diff --git a/apps/api/src/modules/workspace/admin-workspace-preview.controller.ts b/apps/api/src/modules/workspace/admin-workspace-preview.controller.ts index ee729a6..631c94e 100644 --- a/apps/api/src/modules/workspace/admin-workspace-preview.controller.ts +++ b/apps/api/src/modules/workspace/admin-workspace-preview.controller.ts @@ -2,7 +2,7 @@ import { AdminBrand, AdminRoles } from "../../admin-auth.decorators.js"; import { Controller, Get, Post, Body, Req } from "@nestjs/common"; import type { FastifyRequest } from "fastify"; import { InstallTemplateDto, SelectTemplateVersionDto } from "../../admin.dto.js"; -import { TemplateWorkspaceService } from "../../template-workspace.service.js"; +import { TemplateInstallationService } from "../../template/template-installation.service.js"; import { requireAdminIdentity } from "../../admin-access.identity.js"; import { AdminWorkspaceService } from "./admin-workspace.service.js"; @@ -11,7 +11,7 @@ import { AdminWorkspaceService } from "./admin-workspace.service.js"; class AdminWorkspacePreviewController { constructor( private readonly workspaceService: AdminWorkspaceService, - private readonly templateWorkspace: TemplateWorkspaceService, + private readonly templateInstallations: TemplateInstallationService, ) {} @Get() @@ -32,7 +32,7 @@ class AdminWorkspacePreviewController { ): Promise { const identity = requireAdminIdentity(request); const requestId = request.headers["x-request-id"]?.toString() ?? request.id; - return this.templateWorkspace.install( + return this.templateInstallations.install( identity.brandId, body.templateKey, body.templatePackageVersionId, @@ -49,7 +49,7 @@ class AdminWorkspacePreviewController { ): Promise { const identity = requireAdminIdentity(request); const requestId = request.headers["x-request-id"]?.toString() ?? request.id; - return this.templateWorkspace.selectVersion( + return this.templateInstallations.selectVersion( identity.brandId, body, identity.subject, diff --git a/apps/api/src/template/manifest-diff.helpers.ts b/apps/api/src/template/manifest-diff.helpers.ts new file mode 100644 index 0000000..af879df --- /dev/null +++ b/apps/api/src/template/manifest-diff.helpers.ts @@ -0,0 +1,114 @@ +import type { TemplatePackageVersion } from "@prisma/client"; + +export function record(value: unknown): Record { + return value && typeof value === "object" && !Array.isArray(value) + ? (value as Record) + : {}; +} + +export function manifestRecords(value: unknown): Record[] { + return Array.isArray(value) + ? value.filter((item): item is Record => + Boolean(item && typeof item === "object" && !Array.isArray(item)), + ) + : []; +} + +export function stringList(value: unknown): string[] { + return Array.isArray(value) + ? value.filter((item): item is string => typeof item === "string") + : []; +} + +export function hasBindingValue(config: Record, binding: unknown): boolean { + if (typeof binding !== "string" || !binding.startsWith("brand.config.")) return false; + const value = binding + .slice("brand.config.".length) + .split(".") + .reduce((current, key) => record(current)[key], config); + return value !== undefined && value !== null && value !== ""; +} + +export function compareRecords(current: Record, target: Record) { + const currentKeys = Object.keys(current); + const targetKeys = Object.keys(target); + return { + added: targetKeys + .filter((key) => !(key in current)) + .map((key) => ({ key, target: target[key] })), + removed: currentKeys + .filter((key) => !(key in target)) + .map((key) => ({ key, current: current[key] })), + changed: targetKeys + .filter( + (key) => key in current && JSON.stringify(current[key]) !== JSON.stringify(target[key]), + ) + .map((key) => ({ key, current: current[key], target: target[key] })), + }; +} + +export function compareKeyedRecords( + current: Record[], + target: Record[], +) { + const currentByKey = new Map( + current + .filter((item) => typeof item.key === "string") + .map((item) => [item.key as string, item]), + ); + const targetByKey = new Map( + target.filter((item) => typeof item.key === "string").map((item) => [item.key as string, item]), + ); + return { + added: [...targetByKey].filter(([key]) => !currentByKey.has(key)).map(([, item]) => item), + removed: [...currentByKey].filter(([key]) => !targetByKey.has(key)).map(([, item]) => item), + changed: [...targetByKey].flatMap(([key, item]) => { + const previous = currentByKey.get(key); + return previous && JSON.stringify(previous) !== JSON.stringify(item) + ? [{ key, current: previous, target: item }] + : []; + }), + }; +} + +export function compareFiles( + current: Record[], + target: Record[], +) { + const currentByPath = new Map( + current + .filter((item) => typeof item.path === "string") + .map((item) => [item.path as string, item]), + ); + const targetByPath = new Map( + target + .filter((item) => typeof item.path === "string") + .map((item) => [item.path as string, item]), + ); + const available = currentByPath.size > 0 && targetByPath.size > 0; + return { + available, + ...(available + ? { + added: [...targetByPath] + .filter(([path]) => !currentByPath.has(path)) + .map(([, item]) => item), + removed: [...currentByPath] + .filter(([path]) => !targetByPath.has(path)) + .map(([, item]) => item), + changed: [...targetByPath].flatMap(([path, item]) => { + const previous = currentByPath.get(path); + return previous && previous.sha256 !== item.sha256 + ? [{ path, current: previous, target: item }] + : []; + }), + } + : { reason: "版本验证报告未包含完整文件清单" }), + }; +} + +export function readPackageFiles( + version: Pick, +): Record[] { + return manifestRecords(record(version.validationReport).files); +} diff --git a/apps/api/src/template/page-scheme.service.ts b/apps/api/src/template/page-scheme.service.ts new file mode 100644 index 0000000..c4a3126 --- /dev/null +++ b/apps/api/src/template/page-scheme.service.ts @@ -0,0 +1,105 @@ +import { BadRequestException, Injectable } from "@nestjs/common"; +import { + type BrandTemplateKey, + brandTemplateKeys, + getBrandTemplate, + getVisualTemplate, + getVisualTemplateManifest, + isVisualTemplateCompatible, + validateTemplatePackageManifest, +} from "@personal-brand/config"; +import { PrismaService } from "../prisma.service.js"; +import { compareTemplateVersions } from "../template-version-order.js"; +import { record } from "./manifest-diff.helpers.js"; + +@Injectable() +export class PageSchemeService { + constructor(private readonly prisma: PrismaService) {} + + async getPageSchemeCatalog() { + const versions = await this.prisma.templatePackageVersion.findMany({ + where: { status: "published" }, + orderBy: [{ importedAt: "desc" }, { createdAt: "desc" }], + }); + const candidates = versions.flatMap((version) => { + const manifest = record(version.manifestSnapshot); + const visualTemplateKey = manifest.visualTemplateKey; + if ( + manifest.packageKey !== version.packageKey || + manifest.version !== version.version || + typeof visualTemplateKey !== "string" || + visualTemplateKey !== version.packageKey + ) + return []; + const visualTemplate = getVisualTemplate(visualTemplateKey); + const visualManifest = getVisualTemplateManifest(visualTemplateKey); + if (!visualTemplate || !visualManifest) return []; + const supportedBusinessTypes = Array.isArray(manifest.supportedIndustryTemplates) + ? manifest.supportedIndustryTemplates.filter( + (value): value is BrandTemplateKey => + typeof value === "string" && + brandTemplateKeys.includes(value) && + Boolean(getBrandTemplate(value)), + ) + : []; + if ( + supportedBusinessTypes.length === 0 || + supportedBusinessTypes.some( + (businessType) => !isVisualTemplateCompatible(visualTemplate, businessType), + ) || + validateTemplatePackageManifest(manifest).length > 0 + ) + return []; + return [ + { + templatePackageVersionId: version.id, + packageKey: version.packageKey, + name: version.displayName, + description: visualManifest.description, + version: version.version, + supportedBusinessTypes, + }, + ]; + }); + const latestByPackage = new Map(); + for (const candidate of candidates) { + const latestVersion = latestByPackage.get(candidate.packageKey); + if (!latestVersion || compareTemplateVersions(candidate.version, latestVersion) > 0) { + latestByPackage.set(candidate.packageKey, candidate.version); + } + } + const pageSchemes = candidates.map(({ packageKey, ...candidate }) => ({ + ...candidate, + isLatestForPackage: latestByPackage.get(packageKey) === candidate.version, + })); + + return { + businesses: brandTemplateKeys.map((key) => { + const template = getBrandTemplate(key); + if (!template) throw new BadRequestException("业务类型配置不完整"); + return { key, name: template.name, description: template.description }; + }), + pageSchemes, + }; + } + + async getPageSchemeOptions(brandId: string) { + const brand = await this.prisma.brandProfile.findUnique({ + where: { id: brandId }, + select: { templateKey: true }, + }); + const template = brand ? getBrandTemplate(brand.templateKey) : undefined; + if (!brand || !template) throw new BadRequestException("品牌业务类型无效"); + const catalog = await this.getPageSchemeCatalog(); + return { + business: { + key: template.key, + name: template.name, + description: template.description, + }, + pageSchemes: catalog.pageSchemes.filter((scheme) => + scheme.supportedBusinessTypes.includes(template.key), + ), + }; + } +} diff --git a/apps/api/src/template-workspace.service.ts b/apps/api/src/template/template-installation.service.ts similarity index 72% rename from apps/api/src/template-workspace.service.ts rename to apps/api/src/template/template-installation.service.ts index 6da304e..a44663e 100644 --- a/apps/api/src/template-workspace.service.ts +++ b/apps/api/src/template/template-installation.service.ts @@ -3,7 +3,6 @@ import type { TemplatePackageVersion } from "@prisma/client"; import { Prisma } from "@prisma/client"; import { type BrandTemplateKey, - brandTemplateKeys, getBrandTemplate, getVisualTemplate, getVisualTemplateManifest, @@ -11,157 +10,25 @@ import { validateTemplatePackageManifest, } from "@personal-brand/config"; 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"; -import { compareTemplateVersions, latestTemplateVersion } from "./template-version-order.js"; +import type { RollbackTemplateDto, UpgradeTemplateDto } from "../admin.dto.js"; +import { PrismaService } from "../prisma.service.js"; +import { recordTemplateOperationFailure } from "../modules/admin/template-operation-failure.js"; +import { latestTemplateVersion } from "../template-version-order.js"; +import { + compareFiles, + compareKeyedRecords, + compareRecords, + hasBindingValue, + manifestRecords, + readPackageFiles, + record, + stringList, +} from "./manifest-diff.helpers.js"; @Injectable() -export class TemplateWorkspaceService { +export class TemplateInstallationService { constructor(private readonly prisma: PrismaService) {} - async getPageSchemeCatalog() { - const versions = await this.prisma.templatePackageVersion.findMany({ - where: { status: "published" }, - orderBy: [{ importedAt: "desc" }, { createdAt: "desc" }], - }); - const candidates = versions.flatMap((version) => { - const manifest = record(version.manifestSnapshot); - const visualTemplateKey = manifest.visualTemplateKey; - if ( - manifest.packageKey !== version.packageKey || - manifest.version !== version.version || - typeof visualTemplateKey !== "string" || - visualTemplateKey !== version.packageKey - ) - return []; - const visualTemplate = getVisualTemplate(visualTemplateKey); - const visualManifest = getVisualTemplateManifest(visualTemplateKey); - if (!visualTemplate || !visualManifest) return []; - const supportedBusinessTypes = Array.isArray(manifest.supportedIndustryTemplates) - ? manifest.supportedIndustryTemplates.filter( - (value): value is BrandTemplateKey => - typeof value === "string" && - brandTemplateKeys.includes(value) && - Boolean(getBrandTemplate(value)), - ) - : []; - if ( - supportedBusinessTypes.length === 0 || - supportedBusinessTypes.some( - (businessType) => !isVisualTemplateCompatible(visualTemplate, businessType), - ) || - validateTemplatePackageManifest(manifest).length > 0 - ) - return []; - return [ - { - templatePackageVersionId: version.id, - packageKey: version.packageKey, - name: version.displayName, - description: visualManifest.description, - version: version.version, - supportedBusinessTypes, - }, - ]; - }); - const latestByPackage = new Map(); - for (const candidate of candidates) { - const latestVersion = latestByPackage.get(candidate.packageKey); - if (!latestVersion || compareTemplateVersions(candidate.version, latestVersion) > 0) { - latestByPackage.set(candidate.packageKey, candidate.version); - } - } - const pageSchemes = candidates.map(({ packageKey, ...candidate }) => ({ - ...candidate, - isLatestForPackage: latestByPackage.get(packageKey) === candidate.version, - })); - - return { - businesses: brandTemplateKeys.map((key) => { - const template = getBrandTemplate(key); - if (!template) throw new BadRequestException("业务类型配置不完整"); - return { key, name: template.name, description: template.description }; - }), - pageSchemes, - }; - } - - async getPageSchemeOptions(brandId: string) { - const brand = await this.prisma.brandProfile.findUnique({ - where: { id: brandId }, - select: { templateKey: true }, - }); - const template = brand ? getBrandTemplate(brand.templateKey) : undefined; - if (!brand || !template) throw new BadRequestException("品牌业务类型无效"); - const catalog = await this.getPageSchemeCatalog(); - return { - business: { - key: template.key, - name: template.name, - description: template.description, - }, - pageSchemes: catalog.pageSchemes.filter((scheme) => - scheme.supportedBusinessTypes.includes(template.key), - ), - }; - } - - async getTrustContentTypes(brandId: string): Promise { - const installation = await this.prisma.brandTemplateInstallation.findUnique({ - where: { brandId }, - include: { templatePackageVersion: true }, - }); - if (!installation?.templatePackageVersion) - throw new BadRequestException("品牌没有锁定精确视觉模板包版本"); - const manifest = record( - installation.templatePackageVersion.manifestSnapshot, - ) as unknown as TemplatePackageManifest; - if (validateTemplatePackageManifest(manifest).length) - throw new BadRequestException("当前安装的模板包不符合统一模板契约"); - return manifest.trustContentTypes?.map((item) => item.type) ?? []; - } - async createTrustContent(brandId: string, body: CreateTrustContentDto) { - if (!(await this.getTrustContentTypes(brandId)).includes(body.type)) - throw new BadRequestException("当前模板不支持此信任内容类型"); - const { config, ...fields } = body; - return this.prisma.trustContent.create({ - data: { - ...fields, - brandId, - ...(config === undefined ? {} : { config: config as Prisma.InputJsonValue }), - }, - }); - } - async updateTrustContent(brandId: string, id: string, body: UpdateTrustContentDto) { - const item = await this.prisma.trustContent.findFirst({ where: { id, brandId } }); - if (!item) throw new BadRequestException("信任内容不存在"); - if (body.type !== undefined && !(await this.getTrustContentTypes(brandId)).includes(body.type)) - throw new BadRequestException("当前模板不支持此信任内容类型"); - const { config, ...fields } = body; - return this.prisma.trustContent.update({ - where: { id }, - data: { - ...fields, - ...(config === undefined ? {} : { config: config as Prisma.InputJsonValue }), - }, - }); - } - - listTrustContent(brandId: string) { - return this.prisma.trustContent.findMany({ - where: { brandId }, - orderBy: [{ type: "asc" }, { sortOrder: "asc" }], - }); - } - - async deleteTrustContent(brandId: string, id: string) { - const item = await this.prisma.trustContent.findFirst({ where: { id, brandId } }); - if (!item) throw new BadRequestException("信任内容不存在"); - await this.prisma.trustContent.delete({ where: { id } }); - return { deleted: true }; - } async getEffectiveTemplateKey(brandId: string): Promise { const [brand, installation] = await Promise.all([ this.prisma.brandProfile.findUnique({ @@ -759,113 +626,3 @@ export class TemplateWorkspaceService { }; } } - -function readPackageFiles( - version: Pick, -): Record[] { - return manifestRecords(record(version.validationReport).files); -} - -function record(value: unknown): Record { - return value && typeof value === "object" && !Array.isArray(value) - ? (value as Record) - : {}; -} - -function manifestRecords(value: unknown): Record[] { - return Array.isArray(value) - ? value.filter((item): item is Record => - Boolean(item && typeof item === "object" && !Array.isArray(item)), - ) - : []; -} - -function stringList(value: unknown): string[] { - return Array.isArray(value) - ? value.filter((item): item is string => typeof item === "string") - : []; -} - -function hasBindingValue(config: Record, binding: unknown): boolean { - if (typeof binding !== "string" || !binding.startsWith("brand.config.")) return false; - const value = binding - .slice("brand.config.".length) - .split(".") - .reduce((current, key) => record(current)[key], config); - return value !== undefined && value !== null && value !== ""; -} - -function compareRecords(current: Record, target: Record) { - const currentKeys = Object.keys(current); - const targetKeys = Object.keys(target); - return { - added: targetKeys - .filter((key) => !(key in current)) - .map((key) => ({ key, target: target[key] })), - removed: currentKeys - .filter((key) => !(key in target)) - .map((key) => ({ key, current: current[key] })), - changed: targetKeys - .filter( - (key) => key in current && JSON.stringify(current[key]) !== JSON.stringify(target[key]), - ) - .map((key) => ({ key, current: current[key], target: target[key] })), - }; -} - -function compareKeyedRecords( - current: Record[], - target: Record[], -) { - const currentByKey = new Map( - current - .filter((item) => typeof item.key === "string") - .map((item) => [item.key as string, item]), - ); - const targetByKey = new Map( - target.filter((item) => typeof item.key === "string").map((item) => [item.key as string, item]), - ); - return { - added: [...targetByKey].filter(([key]) => !currentByKey.has(key)).map(([, item]) => item), - removed: [...currentByKey].filter(([key]) => !targetByKey.has(key)).map(([, item]) => item), - changed: [...targetByKey].flatMap(([key, item]) => { - const previous = currentByKey.get(key); - return previous && JSON.stringify(previous) !== JSON.stringify(item) - ? [{ key, current: previous, target: item }] - : []; - }), - }; -} - -function compareFiles(current: Record[], target: Record[]) { - const currentByPath = new Map( - current - .filter((item) => typeof item.path === "string") - .map((item) => [item.path as string, item]), - ); - const targetByPath = new Map( - target - .filter((item) => typeof item.path === "string") - .map((item) => [item.path as string, item]), - ); - const available = currentByPath.size > 0 && targetByPath.size > 0; - return { - available, - ...(available - ? { - added: [...targetByPath] - .filter(([path]) => !currentByPath.has(path)) - .map(([, item]) => item), - removed: [...currentByPath] - .filter(([path]) => !targetByPath.has(path)) - .map(([, item]) => item), - changed: [...targetByPath].flatMap(([path, item]) => { - const previous = currentByPath.get(path); - return previous && previous.sha256 !== item.sha256 - ? [{ path, current: previous, target: item }] - : []; - }), - } - : { reason: "版本验证报告未包含完整文件清单" }), - }; -} diff --git a/apps/api/src/template/trust-content.service.ts b/apps/api/src/template/trust-content.service.ts new file mode 100644 index 0000000..20993e2 --- /dev/null +++ b/apps/api/src/template/trust-content.service.ts @@ -0,0 +1,69 @@ +import { BadRequestException, Injectable } from "@nestjs/common"; +import { Prisma } from "@prisma/client"; +import { validateTemplatePackageManifest } from "@personal-brand/config"; +import type { TemplatePackageManifest } from "@personal-brand/config"; +import type { CreateTrustContentDto, UpdateTrustContentDto } from "../admin.dto.js"; +import { PrismaService } from "../prisma.service.js"; +import { record } from "./manifest-diff.helpers.js"; + +@Injectable() +export class TrustContentService { + constructor(private readonly prisma: PrismaService) {} + + async getTrustContentTypes(brandId: string): Promise { + const installation = await this.prisma.brandTemplateInstallation.findUnique({ + where: { brandId }, + include: { templatePackageVersion: true }, + }); + if (!installation?.templatePackageVersion) + throw new BadRequestException("品牌没有锁定精确视觉模板包版本"); + const manifest = record( + installation.templatePackageVersion.manifestSnapshot, + ) as unknown as TemplatePackageManifest; + if (validateTemplatePackageManifest(manifest).length) + throw new BadRequestException("当前安装的模板包不符合统一模板契约"); + return manifest.trustContentTypes?.map((item) => item.type) ?? []; + } + + async createTrustContent(brandId: string, body: CreateTrustContentDto) { + if (!(await this.getTrustContentTypes(brandId)).includes(body.type)) + throw new BadRequestException("当前模板不支持此信任内容类型"); + const { config, ...fields } = body; + return this.prisma.trustContent.create({ + data: { + ...fields, + brandId, + ...(config === undefined ? {} : { config: config as Prisma.InputJsonValue }), + }, + }); + } + + async updateTrustContent(brandId: string, id: string, body: UpdateTrustContentDto) { + const item = await this.prisma.trustContent.findFirst({ where: { id, brandId } }); + if (!item) throw new BadRequestException("信任内容不存在"); + if (body.type !== undefined && !(await this.getTrustContentTypes(brandId)).includes(body.type)) + throw new BadRequestException("当前模板不支持此信任内容类型"); + const { config, ...fields } = body; + return this.prisma.trustContent.update({ + where: { id }, + data: { + ...fields, + ...(config === undefined ? {} : { config: config as Prisma.InputJsonValue }), + }, + }); + } + + listTrustContent(brandId: string) { + return this.prisma.trustContent.findMany({ + where: { brandId }, + orderBy: [{ type: "asc" }, { sortOrder: "asc" }], + }); + } + + async deleteTrustContent(brandId: string, id: string) { + const item = await this.prisma.trustContent.findFirst({ where: { id, brandId } }); + if (!item) throw new BadRequestException("信任内容不存在"); + await this.prisma.trustContent.delete({ where: { id } }); + return { deleted: true }; + } +} diff --git a/apps/api/test/http.integration.test.js b/apps/api/test/http.integration.test.js index f416cd6..7347bab 100644 --- a/apps/api/test/http.integration.test.js +++ b/apps/api/test/http.integration.test.js @@ -5123,6 +5123,71 @@ test("disabled brand membership blocks existing admin token", async () => { } }); +test("booking endpoints share the brand access policy", async () => { + const username = `booking-policy-${randomUUID()}`; + const password = "booking-policy-password-123"; + const user = await prisma.adminUser.create({ + data: { + username, + passwordHash: await bcrypt.hash(password, 12), + displayName: "预订策略测试管理员", + mustChangePassword: true, + }, + }); + const membership = await prisma.brandMembership.create({ + data: { brandId, adminUserId: user.id, role: "admin", isEnabled: true }, + }); + try { + const login = await request("/admin/session/login", { + method: "POST", + payload: { username, password }, + }); + assert.equal(login.statusCode, 201, login.body); + const headers = { authorization: `Bearer ${sessionToken(login)}` }; + const routes = [ + { method: "GET", url: "/admin/bookings" }, + { method: "GET", url: "/admin/bookings/unread-count" }, + { method: "GET", url: "/admin/bookings/tags" }, + { method: "POST", url: "/admin/bookings/tags", payload: { name: "策略测试标签" } }, + ]; + + // 初始密码未修改时,预订路由必须与其他后台路由一样被拒绝。 + for (const route of routes) { + const response = await request(route.url, { + method: route.method, + headers, + ...(route.payload ? { payload: route.payload } : {}), + }); + assert.equal(response.statusCode, 403, `${route.method} ${route.url}: ${response.body}`); + } + + // 品牌成员被停用后,同一 token 也不能再访问预订数据。 + await prisma.adminUser.update({ where: { id: user.id }, data: { mustChangePassword: false } }); + const changed = await request("/admin/session/login", { + method: "POST", + payload: { username, password }, + }); + assert.equal(changed.statusCode, 201, changed.body); + const activeHeaders = { authorization: `Bearer ${sessionToken(changed)}` }; + assert.equal((await request("/admin/bookings", { headers: activeHeaders })).statusCode, 200); + + await prisma.brandMembership.update({ + where: { id: membership.id }, + data: { isEnabled: false }, + }); + for (const route of routes) { + const response = await request(route.url, { + method: route.method, + headers: activeHeaders, + ...(route.payload ? { payload: route.payload } : {}), + }); + assert.equal(response.statusCode, 403, `${route.method} ${route.url}: ${response.body}`); + } + } finally { + await prisma.adminUser.delete({ where: { id: user.id } }); + } +}); + test("admin can read and update brand and service configuration", async () => { const login = await request("/admin/session/login", { method: "POST", -- 2.54.0 From 4d9c84defc44c80dde5e7ed1419ca7bc9ea06561 Mon Sep 17 00:00:00 2001 From: que01 Date: Fri, 23 Oct 2026 12:26:45 +0800 Subject: [PATCH 02/10] =?UTF-8?q?fix:=20=E7=94=9F=E4=BA=A7=E7=8E=AF?= =?UTF-8?q?=E5=A2=83=E6=8B=92=E7=BB=9D=E5=8D=A0=E4=BD=8D=20SESSION=5FSECRE?= =?UTF-8?q?T?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../raw/completion-evidence.json | 4 +- apps/api/src/auth.ts | 12 ++++++ apps/api/src/main.ts | 2 + apps/api/src/runtime-config.ts | 20 ++++++++++ apps/api/test/runtime-config.test.ts | 37 +++++++++++++++++++ 5 files changed, 73 insertions(+), 2 deletions(-) create mode 100644 apps/api/src/runtime-config.ts create mode 100644 apps/api/test/runtime-config.test.ts diff --git a/.codex-tasks/template-audit-execution/raw/completion-evidence.json b/.codex-tasks/template-audit-execution/raw/completion-evidence.json index d1e30bc..a9f736c 100644 --- a/.codex-tasks/template-audit-execution/raw/completion-evidence.json +++ b/.codex-tasks/template-audit-execution/raw/completion-evidence.json @@ -1,7 +1,7 @@ { "schemaVersion": 1, "scope": "模板完成证据登记,保留命令、日志与产物哈希", - "generatedAt": "2026-10-23T04:26:41.081Z", + "generatedAt": "2026-10-23T04:26:48.766Z", "templates": { "acheng-campus-food": { "real-manifest-interaction": { @@ -256,5 +256,5 @@ } } }, - "sourceTreeHash": "753ccedf803e63f14d8eaa3e8abcac074e274f3aed2f4f2facc3a66f8022af24" + "sourceTreeHash": "4a4f5161e6da114837458987d9574d5d09f0d89f1d53e88cd838fc9b31946c9b" } diff --git a/apps/api/src/auth.ts b/apps/api/src/auth.ts index b265502..87d1da1 100644 --- a/apps/api/src/auth.ts +++ b/apps/api/src/auth.ts @@ -1,5 +1,6 @@ import { UnauthorizedException } from "@nestjs/common"; import { createHmac, timingSafeEqual } from "node:crypto"; +import { isPlaceholderSecret } from "./runtime-config.js"; type Identity = { subject: string; @@ -9,9 +10,20 @@ type Identity = { exp: number; }; +let warnedAboutPlaceholderSecret = false; + function secret(): string { const value = process.env.SESSION_SECRET; if (!value || value.length < 32) throw new UnauthorizedException("服务端会话密钥未正确配置"); + if (isPlaceholderSecret(value)) { + // 生产环境已在启动时 fail fast;这里保留二次防线,避免绕过 createApp 的调用方签发弱 token。 + if (process.env.NODE_ENV === "production") + throw new UnauthorizedException("服务端会话密钥未正确配置"); + if (!warnedAboutPlaceholderSecret) { + warnedAboutPlaceholderSecret = true; + console.warn("[api] SESSION_SECRET 仍是示例占位符,仅可用于本地开发"); + } + } return value; } diff --git a/apps/api/src/main.ts b/apps/api/src/main.ts index e03cf13..f2fc647 100644 --- a/apps/api/src/main.ts +++ b/apps/api/src/main.ts @@ -6,8 +6,10 @@ import multipart from "@fastify/multipart"; import fastifyStatic from "@fastify/static"; import path from "node:path"; import { AppModule, configureApp } from "./app.module.js"; +import { assertProductionSecret } from "./runtime-config.js"; export async function createApp(): Promise { + assertProductionSecret(process.env.SESSION_SECRET); const app = await NestFactory.create(AppModule, new FastifyAdapter()); app .getHttpAdapter() diff --git a/apps/api/src/runtime-config.ts b/apps/api/src/runtime-config.ts new file mode 100644 index 0000000..46f0237 --- /dev/null +++ b/apps/api/src/runtime-config.ts @@ -0,0 +1,20 @@ +const PLACEHOLDER_PATTERN = /(replace-with|change-me|changeme|^your[-_ ]|example|placeholder)/i; + +/** 判断值是否仍是仓库示例中的占位符,而不是真实随机密钥。 */ +export function isPlaceholderSecret(value: string): boolean { + return PLACEHOLDER_PATTERN.test(value.trim()); +} + +/** + * 生产环境启动前的快速失败校验。 + * 本地开发允许占位符,避免示例 `.env` 阻塞调试;生产环境必须使用真实随机值。 + */ +export function assertProductionSecret( + value: string | undefined, + nodeEnv: string | undefined = process.env.NODE_ENV, +): void { + if (nodeEnv !== "production") return; + const secret = value?.trim() ?? ""; + if (secret.length < 32) throw new Error("SESSION_SECRET 必须是至少 32 位的随机值"); + if (isPlaceholderSecret(secret)) throw new Error("SESSION_SECRET 不能使用示例占位符"); +} diff --git a/apps/api/test/runtime-config.test.ts b/apps/api/test/runtime-config.test.ts new file mode 100644 index 0000000..eb455de --- /dev/null +++ b/apps/api/test/runtime-config.test.ts @@ -0,0 +1,37 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { assertProductionSecret, isPlaceholderSecret } from "../src/runtime-config.js"; + +test("production rejects missing or short session secrets", () => { + assert.throws(() => assertProductionSecret(undefined, "production"), /至少 32 位/); + assert.throws(() => assertProductionSecret("short-secret", "production"), /至少 32 位/); +}); + +test("production rejects example placeholder secrets", () => { + assert.throws( + () => assertProductionSecret("replace-with-at-least-32-random-characters", "production"), + /示例占位符/, + ); + assert.throws( + () => assertProductionSecret("change-me-now-1234567890-abcdefghij", "production"), + /示例占位符/, + ); +}); + +test("production accepts a strong random secret", () => { + assert.doesNotThrow(() => + assertProductionSecret("s3cure-Random-Value-0123456789-abcdefghij", "production"), + ); +}); + +test("development keeps working with the example placeholder", () => { + assert.doesNotThrow(() => + assertProductionSecret("replace-with-a-long-random-value", "development"), + ); +}); + +test("placeholder detection covers documented example values", () => { + assert.equal(isPlaceholderSecret("replace-with-a-long-random-value"), true); + assert.equal(isPlaceholderSecret(" YOur-secret-value "), true); + assert.equal(isPlaceholderSecret("s3cure-Random-Value-0123456789-abcdefghij"), false); +}); -- 2.54.0 From b190f2758a8dd5ca552f89678bb0202c68c31f6e Mon Sep 17 00:00:00 2001 From: que01 Date: Fri, 23 Oct 2026 12:26:53 +0800 Subject: [PATCH 03/10] =?UTF-8?q?docs:=20=E8=AE=B0=E5=BD=95=E5=90=8E?= =?UTF-8?q?=E5=8F=B0=E5=AE=A2=E6=88=B7=E7=AB=AF=E5=BC=82=E5=B8=B8=E4=B8=8A?= =?UTF-8?q?=E6=8A=A5=E9=99=90=E6=B5=81=E8=BE=B9=E7=95=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../adr/0035-admin-client-error-throttling.md | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 docs/adr/0035-admin-client-error-throttling.md diff --git a/docs/adr/0035-admin-client-error-throttling.md b/docs/adr/0035-admin-client-error-throttling.md new file mode 100644 index 0000000..66fc4c3 --- /dev/null +++ b/docs/adr/0035-admin-client-error-throttling.md @@ -0,0 +1,43 @@ +# 0035 Admin 客户端异常上报的进程内去重与限流 + +- 状态:已采纳 +- 日期:2026-10-23 + +## Context + +Admin 渲染异常上报 `POST /admin/client-errors` 需要防止两类问题: + +- 同一次渲染错误在多个组件或重试中重复上报,制造日志噪音。 +- 单账号在错误循环中高频上报,拖垮日志与请求处理。 + +当前生产为单实例 PM2(`deploy/ecosystem.config.cjs`),没有共享缓存或消息队列。引入 Redis 会增加部署依赖,而当前流量与实例数量都不需要。 + +## Decision + +1. 使用进程内 `Map` 完成两件事: + - 去重:`subject + errorId` 在 10 分钟内只记录一次。 + - 限流:同一 `subject` 每分钟最多 10 次,超出返回 429。 +2. 去重表最多 500 条,按插入顺序淘汰最旧记录;限流窗口每分钟清理。 +3. 该状态不持久化,进程重启后清零。 +4. 只有通过 `requireBrand` 认证的管理员才能上报,避免匿名刷量。 + +## Alternatives + +- 直接引入 Redis:增加部署与可用性依赖,当前单实例没有收益,推迟。 +- 不做限流:错误循环会持续写日志,并放大客户端重试,拒绝。 +- 记录到数据库:异常上报是诊断辅助数据,写入数据库会让故障时的数据库压力更大,拒绝。 + +## Consequences + +- 单实例下行为确定,无需额外基础设施。 +- 多实例部署时每个实例各自计数,实际限流值是 `实例数 × 10/分钟`,去重也只在本实例生效。 +- 进程重启会丢失去重窗口,可能重复记录少量错误。 + +## Migration plan + +1. 当前保持进程内实现,代码注释已说明单实例前提。 +2. 出现以下任一条件时迁移到共享存储(Redis 或数据库): + - API 扩展到多实例; + - 单账号错误上报量在正常故障场景下超过 10 次/分钟; + - 需要跨实例聚合错误统计。 +3. 迁移时保留当前接口与响应形状,仅替换存储实现,并补充并发与过期测试。 -- 2.54.0 From 00aeaa3cb1d6417920acd2eafc19dbeed3bae560 Mon Sep 17 00:00:00 2001 From: que01 Date: Fri, 23 Oct 2026 12:56:48 +0800 Subject: [PATCH 04/10] =?UTF-8?q?refactor:=20=E6=8B=86=E5=88=86=E5=90=8E?= =?UTF-8?q?=E5=8F=B0=E5=8F=AF=E8=A7=86=E5=8C=96=E7=BC=96=E8=BE=91=E5=99=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../raw/completion-evidence.json | 4 +- .../src/features/brand/PresentationEditor.tsx | 600 +----------------- .../brand/PresentationEditorInspector.tsx | 195 ++++++ .../brand/PresentationEditorPreview.tsx | 88 +++ .../brand/presentation-editor-controller.ts | 417 ++++++++++++ 5 files changed, 736 insertions(+), 568 deletions(-) create mode 100644 apps/admin/src/features/brand/PresentationEditorInspector.tsx create mode 100644 apps/admin/src/features/brand/PresentationEditorPreview.tsx create mode 100644 apps/admin/src/features/brand/presentation-editor-controller.ts diff --git a/.codex-tasks/template-audit-execution/raw/completion-evidence.json b/.codex-tasks/template-audit-execution/raw/completion-evidence.json index a9f736c..daec557 100644 --- a/.codex-tasks/template-audit-execution/raw/completion-evidence.json +++ b/.codex-tasks/template-audit-execution/raw/completion-evidence.json @@ -1,7 +1,7 @@ { "schemaVersion": 1, "scope": "模板完成证据登记,保留命令、日志与产物哈希", - "generatedAt": "2026-10-23T04:26:48.766Z", + "generatedAt": "2026-10-23T04:56:52.289Z", "templates": { "acheng-campus-food": { "real-manifest-interaction": { @@ -256,5 +256,5 @@ } } }, - "sourceTreeHash": "4a4f5161e6da114837458987d9574d5d09f0d89f1d53e88cd838fc9b31946c9b" + "sourceTreeHash": "503e7b49d4b7c34c3405cd3d89e58e624a30e4c4831997480ebd7d4359c34052" } diff --git a/apps/admin/src/features/brand/PresentationEditor.tsx b/apps/admin/src/features/brand/PresentationEditor.tsx index c9da99d..ffdea23 100644 --- a/apps/admin/src/features/brand/PresentationEditor.tsx +++ b/apps/admin/src/features/brand/PresentationEditor.tsx @@ -1,34 +1,15 @@ -import { Alert, Button, Grid, Select, Segmented, Space, Typography } from "antd"; -import { useQueryClient } from "@tanstack/react-query"; -import { useCallback, useEffect, useMemo, useState } from "react"; -import { useNavigate } from "react-router-dom"; -import type { AdminTemplateContent, RuntimeWorkspace } from "@personal-brand/api-client"; -import type { BrandProfile } from "@personal-brand/api-client"; +import { Alert, Grid, Segmented, Select, Space } from "antd"; +import type { + AdminTemplateContent, + BrandProfile, + RuntimeWorkspace, +} from "@personal-brand/api-client"; import { StatusTag } from "../../components/StatusTag.js"; -import { RecordContentEditor } from "../../components/RecordContentEditor.js"; -import { TemplatePreview } from "./TemplatePreview.js"; -import { InquiryPreviewEditor } from "./InquiryPreviewEditor.js"; -import { - resolvePreviewSelection, - previewTrustRecordId, - type PreviewSelection, - type PreviewTarget, -} from "./preview-selection.js"; -import { filterSectionsForPreviewTarget } from "../../lib/presentation/presentation-bindings.js"; import "./PresentationEditor.css"; -import { useEditorDraft } from "./use-editor-draft.js"; -import { - usePresentationRecordQueries, - useBrandPresentationSections, - useBrandSaveMutation, - useBrandPresentationForm, - useBrandPreviewDraft, -} from "./presentation-editor-state.js"; -import { useRecordPreview } from "./presentation-editor-record-preview.js"; -import type { RecordDraft } from "./presentation-editor-record-preview.js"; -import { pageTitle, previewTargetSource, trustSection } from "./presentation-editor-helpers.js"; -import { useDraftWorkspace } from "./use-draft-workspace.js"; -import { PresentationFormPanel } from "./PresentationFormPanel.js"; +import type { PreviewSelection } from "./preview-selection.js"; +import { usePresentationEditorController } from "./presentation-editor-controller.js"; +import { PresentationEditorInspector } from "./PresentationEditorInspector.js"; +import { PresentationEditorPreview } from "./PresentationEditorPreview.js"; interface PresentationEditorProps { templateContent: AdminTemplateContent | null | undefined; @@ -49,254 +30,14 @@ export function PresentationEditor({ error, initialSelection, }: PresentationEditorProps) { - const queryClient = useQueryClient(); - const navigate = useNavigate(); const breakpoints = Grid.useBreakpoint(); - const [activePage, setActivePage] = useState(); - const [selection, setSelection] = useState(initialSelection); - const [hasInitializedSelection, setHasInitializedSelection] = useState(Boolean(initialSelection)); - const [detailOfferingId, setDetailOfferingId] = useState(); - const [recordDraft, setRecordDraft] = useState(); - const [inquiryDraft, setInquiryDraft] = - useState(); - const [brandDirty, setBrandDirty] = useState(false); - const guardDraft = useEditorDraft(brandDirty || !!recordDraft || !!inquiryDraft); - const inquiryRuntime = previewWorkspace?.inquiryForms.find((item) => item.target === "brand"); - const sections = useBrandPresentationSections(templateContent); - const pageOptions = useMemo(() => { - const pages = new Map(); - for (const item of templateContent?.navigation ?? []) pages.set(item.page, item.label); - for (const section of templateContent?.admin.sections ?? []) { - const navigation = templateContent?.navigation.find((item) => item.page === section.page); - if (!pages.has(section.page)) - pages.set(section.page, navigation?.label ?? pageTitle(section.page)); - } - return [...pages].map(([value, label]) => ({ value, label })); - }, [templateContent]); - const selectedPage = pageOptions.some((item) => item.value === activePage) - ? activePage - : pageOptions[0]?.value; - const visibleSections = sections.filter((section) => section.page === selectedPage); - const recordSections = useMemo( - () => - (templateContent?.trustContentTypes ?? []) - .filter((item) => item.pages?.includes(selectedPage ?? "")) - .map((item) => trustSection(item, selectedPage ?? "home")), - [templateContent, selectedPage], - ); - const visibleTargets = useMemo( - () => - [...(templateContent?.admin.sections ?? []), ...recordSections] - .filter( - (section) => - section.page === selectedPage && - (selectedPage !== "detail" || section.target === "brand"), - ) - .flatMap((section) => - (section.previewTargets ?? []).map((target) => ({ - ...target, - page: section.page, - source: previewTargetSource(section, target.key), - ...(section.key.startsWith("trust:") ? { trustType: section.key.slice(6) } : {}), - })), - ) - .concat( - selectedPage === "inquiry" && inquiryRuntime - ? inquiryRuntime.fields.map((field) => ({ - key: `inquiry-field:${field.key}`, - label: field.label, - page: "inquiry", - source: "inquiry" as const, - })) - : [], - ), - [templateContent, selectedPage, recordSections, inquiryRuntime], - ); - const activeTarget = selection?.targetKey; - const selectedTarget = visibleTargets.find((target) => target.key === activeTarget); - const selectedSection = [...(templateContent?.admin.sections ?? []), ...recordSections].find( - (section) => - section.page === selectedPage && - section.previewTargets?.some((target) => target.key === selectedTarget?.key), - ); - const selectedRecordSource = - selectedTarget?.source === "offering" || selectedTarget?.source === "trust" - ? selectedTarget.source - : undefined; - const { offeringsQuery, trustQuery, selectedRecord } = usePresentationRecordQueries( - selectedRecordSource, - selection?.recordId, - ); - const editableSections = filterSectionsForPreviewTarget( - visibleSections.filter((section) => - section.fields.some((field) => field.binding.startsWith("brand.")), - ), - selectedTarget?.key, - ); - const recordSection = useMemo( - () => - selectedSection && selection?.targetKey - ? { - ...selectedSection, - fields: selectedSection.fields.filter( - (field) => field.previewTarget === selection.targetKey, - ), - } - : undefined, - [selectedSection, selection?.targetKey], - ); - const handleTargetSelected = useCallback( - (next?: PreviewSelection) => { - const select = () => - setSelection( - next - ? resolvePreviewSelection( - next.targetKey, - next.recordId, - visibleTargets, - selectedPage ?? "home", - ) - : undefined, - ); - if (recordDraft || inquiryDraft) - guardDraft(() => { - setInquiryDraft(undefined); - setRecordDraft(undefined); - select(); - }); - else select(); - }, - [visibleTargets, selectedPage, recordDraft, inquiryDraft, guardDraft], - ); - const relatedTargets = [ - ...(templateContent?.admin.sections ?? []) - .filter((section) => section.page === selectedPage && section.target !== "brand") - .map((section) => section.target), - ...((templateContent?.trustContentTypes ?? []).some((item) => - item.pages?.includes(selectedPage ?? ""), - ) - ? ["trust"] - : []), - ]; - const pageLinks = [...new Set(relatedTargets)].flatMap((target) => - target === "trust" - ? (templateContent?.trustContentTypes ?? []) - .filter((item) => item.pages?.includes(selectedPage ?? "")) - .map((item) => ({ - target: `trust:${item.type}`, - label: `编辑${item.label}`, - })) - : [ - { - target, - label: ( - { offering: "管理此页展示的业务内容", inquiry: "管理此页的咨询表单" } as Record< - string, - string - > - )[target], - }, - ], - ); - const relevantPageLinks = selectedSection - ? pageLinks.filter((item) => { - if (item.target.startsWith("trust:")) return selectedSection.target === "trust"; - return item.target === selectedSection.target; - }) - : pageLinks; - const formState = useBrandPresentationForm({ brand, config, sections }); - const { form, initialValues } = formState; - const save = useBrandSaveMutation({ - ...formState, - brand, - config, - sections, - queryClient, - onSaved: () => setBrandDirty(false), - }); - - useEffect(() => { - const initialPage = - typeof initialSelection === "object" && "page" in initialSelection - ? String(initialSelection.page) - : undefined; - if (initialPage) { - setActivePage( - pageOptions.some((item) => item.value === initialPage) - ? initialPage - : pageOptions[0]?.value, - ); - return; - } - if (!activePage && pageOptions.length) setActivePage(pageOptions[0]?.value); - }, [activePage, initialSelection, pageOptions]); - useEffect(() => { - if (hasInitializedSelection) return; - if (!pageOptions.length) return; - if (!initialSelection) return; - const requestedPage = - typeof initialSelection === "object" && "page" in initialSelection - ? String(initialSelection.page) - : undefined; - const resolvedPage = - requestedPage && pageOptions.some((item) => item.value === requestedPage) - ? requestedPage - : (pageOptions[0]?.value ?? "home"); - setSelection( - resolvePreviewSelection( - initialSelection.targetKey, - initialSelection.recordId, - visibleTargets, - resolvedPage, - ), - ); - setActivePage(resolvedPage); - setHasInitializedSelection(true); - }, [hasInitializedSelection, initialSelection, pageOptions, selectedPage, visibleTargets]); - useEffect(() => { - if (!initialSelection) setSelection(undefined); - }, [initialSelection, selectedPage, templateContent?.displayName]); - useEffect(() => { - if (!selection?.recordId) return; - const records = - selectedTarget?.source === "trust" - ? previewWorkspace?.trustItems - : previewWorkspace?.offerings; - if (records && !records.some((item) => item.id === selection.recordId)) setSelection(undefined); - }, [ - previewWorkspace?.offerings, - previewWorkspace?.trustItems, - selectedTarget?.source, - selection, - ]); - useEffect( - () => setRecordDraft(undefined), - [selection?.targetKey, selection?.recordId, selectedPage], - ); - const { previewBrand, handleValuesChange, resetPreview } = useBrandPreviewDraft({ - brand, - config, - sections, - form, - onDirty: () => setBrandDirty(true), - }); - const recordPreview = useRecordPreview({ recordDraft, selectedRecord, recordSection }); - useEffect(() => resetPreview(), [config, initialValues, resetPreview]); - const draftWorkspace = useDraftWorkspace({ - previewWorkspace, - previewBrand, - inquiryRuntime, - inquiryDraft, - recordDraft, - selectedRecord, - recordSection, - recordPreview, + const controller = usePresentationEditorController({ templateContent, + previewWorkspace, + config, + brand, + ...(initialSelection ? { initialSelection } : {}), }); - const selectedDetailOfferingId = - detailOfferingId && draftWorkspace?.offerings.some((item) => item.id === detailOfferingId) - ? detailOfferingId - : draftWorkspace?.offerings[0]?.id; return (
@@ -324,306 +65,33 @@ export function PresentationEditor({ {breakpoints.xs ? ( ({ - value: item.id, - label: item.name, - }))} - onChange={(value) => { - setDetailOfferingId(value); - setSelection(undefined); - }} - /> - ) : null} - - - -
-

- {selectedTarget?.label ?? pageTitle(selectedPage ?? "home")} -

- - {selectedPage === "detail" && !selectedTarget ? ( - { - void navigate("/admin/services"); - }} - > - 管理业务内容 - - } - /> - ) : activeTarget?.startsWith("inquiry-field:") && inquiryRuntime ? ( - item.key === inquiryRuntime.key) ?? - inquiryRuntime - } - fieldKey={activeTarget.slice("inquiry-field:".length)} - onDraft={setInquiryDraft} - onSaved={() => setInquiryDraft(undefined)} - /> - ) : selectedTarget?.composite ? ( - - {(selectedTarget.children ?? []).map((childKey) => { - const child = visibleTargets.find((item) => item.key === childKey); - if (!child) return null; - return ( - - ); - })} - - } - /> - ) : selectedRecordSource && selection?.recordId && selectedSection ? ( - selectedRecord ? ( - - setRecordDraft({ - source: selectedRecordSource, - id: selectedRecord.id, - values, - }) - } - onSaved={() => setRecordDraft(undefined)} - /> - ) : ( - { - if (selectedRecordSource === "offering") - void offeringsQuery.refetch(); - else void trustQuery.refetch(); - }} - > - 重试 - - ), - } - : {})} - /> - ) - ) : selectedRecordSource ? ( - - guardDraft(() => { - void navigate( - selectedRecordSource === "trust" - ? `/admin/trust?type=${encodeURIComponent(selectedTarget?.trustType ?? "")}` - : "/admin/services", - ); - }) - } - > - 配置此区域内容 - - } - /> - ) : !selectedTarget ? ( -
-

选择要编辑的区域

-

- 点击预览中的内容,或使用区域列表,查看并修改对应字段。 -

-
- ) : ( - save.mutate(values), - }} - onValuesChange={handleValuesChange} - /> - )} -
+ + ) : null} diff --git a/apps/admin/src/features/brand/PresentationEditorInspector.tsx b/apps/admin/src/features/brand/PresentationEditorInspector.tsx new file mode 100644 index 0000000..def7b6a --- /dev/null +++ b/apps/admin/src/features/brand/PresentationEditorInspector.tsx @@ -0,0 +1,195 @@ +import { Alert, Button, Space } from "antd"; +import { StatusTag } from "../../components/StatusTag.js"; +import { RecordContentEditor } from "../../components/RecordContentEditor.js"; +import { InquiryPreviewEditor } from "./InquiryPreviewEditor.js"; +import { PresentationFormPanel } from "./PresentationFormPanel.js"; +import { pageTitle } from "./presentation-editor-helpers.js"; +import type { PresentationEditorController } from "./presentation-editor-controller.js"; + +export function PresentationEditorInspector({ + controller, +}: { + controller: PresentationEditorController; +}) { + const { + selectedPage, + selectedTarget, + activeTarget, + selection, + selectedSection, + selectedRecordSource, + selectedRecord, + recordSection, + editableSections, + relevantPageLinks, + inquiryRuntime, + draftWorkspace, + form, + initialValues, + save, + offeringsQuery, + trustQuery, + recordDraft, + inquiryDraft, + brandDirty, + guardDraft, + } = controller; + const recordQuery = selectedRecordSource === "trust" ? trustQuery : offeringsQuery; + + return ( +
+

+ {selectedTarget?.label ?? pageTitle(selectedPage ?? "home")} +

+ + {selectedPage === "detail" && !selectedTarget ? ( + { + void controller.navigate("/admin/services"); + }} + > + 管理业务内容 + + } + /> + ) : activeTarget?.startsWith("inquiry-field:") && inquiryRuntime ? ( + item.key === inquiryRuntime.key) ?? + inquiryRuntime + } + fieldKey={activeTarget.slice("inquiry-field:".length)} + onDraft={controller.setInquiryDraft} + onSaved={() => controller.setInquiryDraft(undefined)} + /> + ) : selectedTarget?.composite ? ( + + {(selectedTarget.children ?? []).map((childKey) => { + const child = visibleTarget(childKey, controller); + if (!child) return null; + return ( + + ); + })} + + } + /> + ) : selectedRecordSource && selection?.recordId && selectedSection ? ( + selectedRecord ? ( + + controller.setRecordDraft({ + source: selectedRecordSource, + id: selectedRecord.id, + values, + }) + } + onSaved={() => controller.setRecordDraft(undefined)} + /> + ) : ( + void recordQuery.refetch()}> + 重试 + + ), + } + : {})} + /> + ) + ) : selectedRecordSource ? ( + + guardDraft(() => { + void controller.navigate( + selectedRecordSource === "trust" + ? `/admin/trust?type=${encodeURIComponent(selectedTarget?.trustType ?? "")}` + : "/admin/services", + ); + }) + } + > + 配置此区域内容 + + } + /> + ) : !selectedTarget ? ( +
+

选择要编辑的区域

+

+ 点击预览中的内容,或使用区域列表,查看并修改对应字段。 +

+
+ ) : ( + save.mutate(values), + }} + onValuesChange={controller.handleValuesChange} + /> + )} +
+ ); +} + +function visibleTarget(key: string, controller: PresentationEditorController) { + return controller.visibleTargets.find((item) => item.key === key); +} diff --git a/apps/admin/src/features/brand/PresentationEditorPreview.tsx b/apps/admin/src/features/brand/PresentationEditorPreview.tsx new file mode 100644 index 0000000..cda7516 --- /dev/null +++ b/apps/admin/src/features/brand/PresentationEditorPreview.tsx @@ -0,0 +1,88 @@ +import { Button, Select, Space, Typography } from "antd"; +import type { BrandProfile, RuntimeWorkspace } from "@personal-brand/api-client"; +import { TemplatePreview } from "./TemplatePreview.js"; +import type { PreviewSelection, PreviewTarget } from "./preview-selection.js"; + +interface PresentationEditorPreviewProps { + previewBrand: BrandProfile; + draftWorkspace?: RuntimeWorkspace | undefined; + selectedPage: string | undefined; + selectedDetailOfferingId: string | undefined; + activeTarget: string | undefined; + selection: PreviewSelection | undefined; + visibleTargets: PreviewTarget[]; + onSelectDetailOffering: (id: string) => void; + onTargetSelected: (next?: PreviewSelection) => void; + onSelectPreviewTarget: (target: PreviewTarget) => void; +} + +export function PresentationEditorPreview({ + previewBrand, + draftWorkspace, + selectedPage, + selectedDetailOfferingId, + activeTarget, + selection, + visibleTargets, + onSelectDetailOffering, + onTargetSelected, + onSelectPreviewTarget, +}: PresentationEditorPreviewProps) { + return ( + <> +
+

页面预览

+ {selectedPage === "detail" && draftWorkspace?.offerings.length ? ( +