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
+7274 -5087

No files matched your search

@@ -0,0 +1,219 @@
{
"schemaVersion": 1,
"scope": "模板完成证据登记,保留命令、日志与产物哈希",
"generatedAt": "2026-10-18T21:55:00+08:00",
"templates": {
"acheng-campus-food": {
"real-manifest-interaction": {
"status": "passed",
"commands": [
"pnpm --filter @personal-brand/api test:integration",
"ADMIN_URL=http://127.0.0.1:3010 pnpm --filter @personal-brand/taro exec playwright test test/browser/admin-editor.spec.ts"
],
"artifacts": [
{
"path": ".codex-tasks/template-audit-execution/raw/evidence-2026-10-18/api-integration.log",
"sha256": "c5c469f3fa43323f9872ce7dd4114fa8803c7be63c578d058fc1e9b60f72a3e1"
},
{
"path": ".codex-tasks/template-audit-execution/raw/evidence-2026-10-18/admin-editor.log",
"sha256": "dc3c5984b38e06d7b9b975d5247ea136ae6a9e06f61826bd63949239edfda6fa"
}
]
},
"save-reload-publish-isolation": {
"status": "passed",
"commands": [
"pnpm --filter @personal-brand/api test:integration"
],
"artifacts": [
{
"path": ".codex-tasks/template-audit-execution/raw/evidence-2026-10-18/api-integration.log",
"sha256": "c5c469f3fa43323f9872ce7dd4114fa8803c7be63c578d058fc1e9b60f72a3e1"
}
]
},
"visual-reference": {
"status": "passed",
"commands": [
"TEMPLATE_PREVIEW_VISUAL_EVIDENCE=<absolute-output-dir> ADMIN_URL=http://127.0.0.1:3010 pnpm --filter @personal-brand/taro exec playwright test test/browser/template-preview-media.spec.ts"
],
"artifacts": [
{
"path": ".codex-tasks/template-audit-execution/raw/evidence-2026-10-18/template-preview-media.log",
"sha256": "de768debf81e14aeb17309622781c3c5239768c54f6ca3008c3cf52fd70aca3b"
},
{
"path": ".codex-tasks/template-audit-execution/raw/visual-matrix-2026-10-18/01-acheng-campus-food-food.png",
"sha256": "46066739ca27e6b6e194972f3accce6f3de81adc089d2968361de9f289f73f37"
}
]
},
"empty-error-branches": {
"status": "passed",
"commands": [
"TEMPLATE_PREVIEW_VISUAL_EVIDENCE=<absolute-output-dir> ADMIN_URL=http://127.0.0.1:3010 pnpm --filter @personal-brand/taro exec playwright test test/browser/template-preview-media.spec.ts",
"ADMIN_URL=http://127.0.0.1:3010 pnpm --filter @personal-brand/taro exec playwright test test/browser/admin-editor.spec.ts"
],
"artifacts": [
{
"path": ".codex-tasks/template-audit-execution/raw/evidence-2026-10-18/template-preview-media.log",
"sha256": "de768debf81e14aeb17309622781c3c5239768c54f6ca3008c3cf52fd70aca3b"
},
{
"path": ".codex-tasks/template-audit-execution/raw/evidence-2026-10-18/admin-editor.log",
"sha256": "dc3c5984b38e06d7b9b975d5247ea136ae6a9e06f61826bd63949239edfda6fa"
},
{
"path": ".codex-tasks/template-audit-execution/raw/visual-matrix-2026-10-18/empty-01-acheng-campus-food-food.png",
"sha256": "6580f27a4f5613f1da1abfb907932b1092a3a82b55cfc78e3fc67ef5dad688f2"
}
]
}
},
"atelier-solopreneur": {
"real-manifest-interaction": {
"status": "passed",
"commands": [
"pnpm --filter @personal-brand/api test:integration",
"ADMIN_URL=http://127.0.0.1:3010 pnpm --filter @personal-brand/taro exec playwright test test/browser/admin-editor.spec.ts"
],
"artifacts": [
{
"path": ".codex-tasks/template-audit-execution/raw/evidence-2026-10-18/api-integration.log",
"sha256": "c5c469f3fa43323f9872ce7dd4114fa8803c7be63c578d058fc1e9b60f72a3e1"
},
{
"path": ".codex-tasks/template-audit-execution/raw/evidence-2026-10-18/admin-editor.log",
"sha256": "dc3c5984b38e06d7b9b975d5247ea136ae6a9e06f61826bd63949239edfda6fa"
}
]
},
"save-reload-publish-isolation": {
"status": "passed",
"commands": [
"pnpm --filter @personal-brand/api test:integration"
],
"artifacts": [
{
"path": ".codex-tasks/template-audit-execution/raw/evidence-2026-10-18/api-integration.log",
"sha256": "c5c469f3fa43323f9872ce7dd4114fa8803c7be63c578d058fc1e9b60f72a3e1"
}
]
},
"visual-reference": {
"status": "passed",
"commands": [
"TEMPLATE_PREVIEW_VISUAL_EVIDENCE=<absolute-output-dir> ADMIN_URL=http://127.0.0.1:3010 pnpm --filter @personal-brand/taro exec playwright test test/browser/template-preview-media.spec.ts"
],
"artifacts": [
{
"path": ".codex-tasks/template-audit-execution/raw/evidence-2026-10-18/template-preview-media.log",
"sha256": "de768debf81e14aeb17309622781c3c5239768c54f6ca3008c3cf52fd70aca3b"
},
{
"path": ".codex-tasks/template-audit-execution/raw/visual-matrix-2026-10-18/02-atelier-solopreneur-personal.png",
"sha256": "febd1edb6009100841044dde6ca129a0a7830e86804d666b629b92ee9eaddba4"
}
]
},
"empty-error-branches": {
"status": "passed",
"commands": [
"TEMPLATE_PREVIEW_VISUAL_EVIDENCE=<absolute-output-dir> ADMIN_URL=http://127.0.0.1:3010 pnpm --filter @personal-brand/taro exec playwright test test/browser/template-preview-media.spec.ts",
"ADMIN_URL=http://127.0.0.1:3010 pnpm --filter @personal-brand/taro exec playwright test test/browser/admin-editor.spec.ts"
],
"artifacts": [
{
"path": ".codex-tasks/template-audit-execution/raw/evidence-2026-10-18/template-preview-media.log",
"sha256": "de768debf81e14aeb17309622781c3c5239768c54f6ca3008c3cf52fd70aca3b"
},
{
"path": ".codex-tasks/template-audit-execution/raw/evidence-2026-10-18/admin-editor.log",
"sha256": "dc3c5984b38e06d7b9b975d5247ea136ae6a9e06f61826bd63949239edfda6fa"
},
{
"path": ".codex-tasks/template-audit-execution/raw/visual-matrix-2026-10-18/empty-02-atelier-solopreneur-personal.png",
"sha256": "88718b259d8f19007a491c1825bcfb578f79ca8c536af49caa0d11c3f6b50f07"
}
]
}
},
"linjing-editorial": {
"real-manifest-interaction": {
"status": "passed",
"commands": [
"pnpm --filter @personal-brand/api test:integration",
"ADMIN_URL=http://127.0.0.1:3010 pnpm --filter @personal-brand/taro exec playwright test test/browser/admin-editor.spec.ts"
],
"artifacts": [
{
"path": ".codex-tasks/template-audit-execution/raw/evidence-2026-10-18/api-integration.log",
"sha256": "c5c469f3fa43323f9872ce7dd4114fa8803c7be63c578d058fc1e9b60f72a3e1"
},
{
"path": ".codex-tasks/template-audit-execution/raw/evidence-2026-10-18/admin-editor.log",
"sha256": "dc3c5984b38e06d7b9b975d5247ea136ae6a9e06f61826bd63949239edfda6fa"
}
]
},
"save-reload-publish-isolation": {
"status": "passed",
"commands": [
"pnpm --filter @personal-brand/api test:integration"
],
"artifacts": [
{
"path": ".codex-tasks/template-audit-execution/raw/evidence-2026-10-18/api-integration.log",
"sha256": "c5c469f3fa43323f9872ce7dd4114fa8803c7be63c578d058fc1e9b60f72a3e1"
}
]
},
"visual-reference": {
"status": "passed",
"commands": [
"TEMPLATE_PREVIEW_VISUAL_EVIDENCE=<absolute-output-dir> ADMIN_URL=http://127.0.0.1:3010 pnpm --filter @personal-brand/taro exec playwright test test/browser/template-preview-media.spec.ts"
],
"artifacts": [
{
"path": ".codex-tasks/template-audit-execution/raw/evidence-2026-10-18/template-preview-media.log",
"sha256": "de768debf81e14aeb17309622781c3c5239768c54f6ca3008c3cf52fd70aca3b"
},
{
"path": ".codex-tasks/template-audit-execution/raw/visual-matrix-2026-10-18/03-linjing-editorial-personal.png",
"sha256": "fb719a7b98202f214be10a9b0055fdbf8939a6547a2bac33a196615b11f40967"
},
{
"path": ".codex-tasks/template-audit-execution/raw/visual-matrix-2026-10-18/04-linjing-editorial-doors.png",
"sha256": "e68445f755d5efd2c35401b2c9e2bc2fc637f05bcb8344fb5b8a087681d82fd1"
}
]
},
"empty-error-branches": {
"status": "passed",
"commands": [
"TEMPLATE_PREVIEW_VISUAL_EVIDENCE=<absolute-output-dir> ADMIN_URL=http://127.0.0.1:3010 pnpm --filter @personal-brand/taro exec playwright test test/browser/template-preview-media.spec.ts",
"ADMIN_URL=http://127.0.0.1:3010 pnpm --filter @personal-brand/taro exec playwright test test/browser/admin-editor.spec.ts"
],
"artifacts": [
{
"path": ".codex-tasks/template-audit-execution/raw/evidence-2026-10-18/template-preview-media.log",
"sha256": "de768debf81e14aeb17309622781c3c5239768c54f6ca3008c3cf52fd70aca3b"
},
{
"path": ".codex-tasks/template-audit-execution/raw/evidence-2026-10-18/admin-editor.log",
"sha256": "dc3c5984b38e06d7b9b975d5247ea136ae6a9e06f61826bd63949239edfda6fa"
},
{
"path": ".codex-tasks/template-audit-execution/raw/visual-matrix-2026-10-18/empty-03-linjing-editorial-personal.png",
"sha256": "f6f7dca9bbb9116d7e87601633221dffb190cd26e85499e2d14285d667445bfc"
},
{
"path": ".codex-tasks/template-audit-execution/raw/visual-matrix-2026-10-18/empty-04-linjing-editorial-doors.png",
"sha256": "677c2f7053d0cdbbf68d9d8e53d7dbd9a285608e50fca8571248aae0e15fec07"
}
]
}
}
}
}
@@ -0,0 +1,11 @@
Running 2 tests using 1 worker
(node:588768) Warning: The 'NO_COLOR' env is ignored due to the 'FORCE_COLOR' env being set.
(Use `node --trace-warnings ...` to show where the warning was created)
(node:588768) Warning: The 'NO_COLOR' env is ignored due to the 'FORCE_COLOR' env being set.
(Use `node --trace-warnings ...` to show where the warning was created)
✓ 1 test/browser/admin-editor.spec.ts:235:5 › Admin 按通用预览目标筛选字段并同步品牌草稿 (24.9s)
✓ 2 test/browser/admin-editor.spec.ts:637:5 › 林境模板支持首页和主理人区域点选 (27.0s)
2 passed (53.5s)
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,18 @@
Running 1 test using 1 worker
(node:588293) Warning: The 'NO_COLOR' env is ignored due to the 'FORCE_COLOR' env being set.
(Use `node --trace-warnings ...` to show where the warning was created)
(node:588293) Warning: The 'NO_COLOR' env is ignored due to the 'FORCE_COLOR' env being set.
(Use `node --trace-warnings ...` to show where the warning was created)
(node:588432) Warning: The 'NO_COLOR' env is ignored due to the 'FORCE_COLOR' env being set.
(Use `node --trace-warnings ...` to show where the warning was created)
(node:588540) Warning: The 'NO_COLOR' env is ignored due to the 'FORCE_COLOR' env being set.
(Use `node --trace-warnings ...` to show where the warning was created)
(node:588591) Warning: The 'NO_COLOR' env is ignored due to the 'FORCE_COLOR' env being set.
(Use `node --trace-warnings ...` to show where the warning was created)
(node:588666) Warning: The 'NO_COLOR' env is ignored due to the 'FORCE_COLOR' env being set.
(Use `node --trace-warnings ...` to show where the warning was created)
✓ 1 test/browser/template-preview-media.spec.ts:155:5 › 导入包预览矩阵展示身份、资源和完整媒体槽位 (11.2s)
1 passed (12.6s)
File diff suppressed because it is too large. Load diff
Binary file not shown.

After

Width:  |  Height:  |  Size: 80 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 65 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 90 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 73 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 78 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 68 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 103 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 93 KiB

+1
View File
@@ -6,6 +6,7 @@ POSTGRES_DB=personal_brand
POSTGRES_PORT=5432
API_PORT=3001
API_PREFIX=
CORS_ORIGINS=http://localhost:3000
ADMIN_PORT=3000
SESSION_SECRET=replace-with-a-long-random-value
DEFAULT_BRAND_ID=00000000-0000-0000-0000-000000000001
+1
View File
@@ -12,6 +12,7 @@ SEED_MODE=skip
API_PORT=3001
API_PREFIX=
CORS_ORIGINS=
LOCAL_MEDIA_ROOT=/home/ubuntu/persional-brand/media
LOCAL_MEDIA_BASE_URL=/media
+54 -84
View File
@@ -1,104 +1,74 @@
# Project Status
最后更新:2026-09-19
## 当前目标
先为餐饮摊主朋友交付一个真正能带来订单的个人品牌小程序,再根据真实使用把通用能力产品化。产品方的收益、运营和平台化目标不能牺牲朋友的实际使用效果。
最后更新:2026-10-18
## 当前阶段
后端基础、数据库环境和订单 API 已完成首轮验证,管理后台和小程序静态页面已接入首版结构,下一步进行真实资源与微信登录/预约联调。
系统已从“餐饮试点小程序”演进为多模板个人品牌平台。当前分支完成了统一模板契约收口、模板完成证据门禁、管理员登录态撤销和 release 版本一致性修复。
## 已完成
## 当前能力
- 产品 PRD、原型规格、架构决策、数据/API 设计和实施计划。
- 餐饮试点画像与首轮需求访谈决策。
- 可点击低保真原型:`prototype/index.html`。
- Git 仓库、`main` 分支和远程仓库。
- pnpm workspace + Turborepo Monorepo。
- TypeScript 严格配置、ESLint、Prettier、EditorConfig、环境变量模板。
- NestJS + Fastify API 骨架。
- Prisma PostgreSQL schema:品牌、服务、客户身份、订单、订单明细、标签、管理员。
- 微信官方 `jscode2session` 登录交换边界。
- 客户登录 token、客户订单提交/查询/取消。
- 普通套餐价格快照和私厨需求人工报价模型。
- 管理员账号密码登录和角色 token。
- 管理员订单列表、状态、未读、标签和内部备忘能力。
- DTO 校验、全局异常响应、请求 ID和订单状态流转规则。
- Docker PostgreSQL Compose、seed 和 Prisma 脚本说明。
- 初始 Prisma migration,已在本地 PostgreSQL 应用并验证数据库 schema up to date。
- seed 已写入品牌、服务、标签和管理员数据,并完成数量核验。
- 管理员订单详情、状态/未读/标签筛选和未读数量接口。
- API 自动化业务规则测试:订单创建、客户取消、状态流转和标签品牌隔离,共 6 项通过。
- 修复 ESM 下 `bcryptjs` 导入和 Fastify 请求 ID middleware 的运行时问题。
- API 已通过真实 HTTP 验证:健康检查、公开品牌/服务读取和管理员登录。
- HTTP 集成测试:公开接口、管理员登录、错误密码、管理员权限边界、客户会话、预约 DTO 校验、创建/取消和状态流转,共 8 项通过。
- OpenAPI 3.1 契约:`docs/openapi.yaml`,覆盖当前公开、客户和管理员接口。
- 类型化 `@personal-brand/api-client`:支持公开内容、客户预约、管理员订单和统一错误处理,并有 2 项客户端测试。
- 已根据 `/home/que01/桌面/个人品牌设计图/` 确认 C 端页面视觉规范:暖白、米黄、砖红、深炭黑,16px 卡片圆角和大字号优先。
- 小程序已完成首页、服务列表、预约套餐和我的订单静态页面,页面标题使用微信原生导航栏。
- 已配置小程序 AppID:`wxd75d946d6978d183`。
- 服务分类、预约数量步进器、订单状态卡和底部导航已按设计图完成首版还原。
- 已执行多轮 Codex 代码审查并修复关键认证和权限问题。
- NestJS + Fastify API、Prisma PostgreSQL、全局 DTO 校验、统一错误响应和 `requestId`。
- 多品牌 Admin、品牌 membership、角色边界、品牌切换和品牌隔离。
- 模板包发现、确定性打包、导入、校验、发布、预览、安装、升级和回滚。
- 三套已交付模板:
- `acheng-campus-food@1.0.3`
- `atelier-solopreneur@1.3.2`
- `linjing-editorial@1.0.6`
- Taro Runtime、Admin 组件预览、真实 manifest 驱动编辑、草稿/发布隔离。
- 小程序构建、上传任务状态机、attempt lease 和失败记录。
- Admin token version:修改密码后旧 token 立即失效;无 membership 的账号不会自动获得 owner 权限。
- `visualPresentation` 已进入唯一 `template.json` 契约,旧手写 visual manifest 优先路径已删除。
## 最近提交
## 完成证据
`.codex-tasks/template-audit-execution/raw/completion-evidence.json` 登记四类证据:
- `real-manifest-interaction`
- `save-reload-publish-isolation`
- `visual-reference`
- `empty-error-branches`
每条证据保留执行命令、日志和产物 SHA-256。`pnpm template:doctor` 会校验证据覆盖和哈希;当前三套模板均为:
```text
fee3c77 fix: 按设计图优化预约套餐数量和商品卡
13ead2d fix: 对齐服务分类和订单视觉结构
255756c feat: 增加小程序品牌首页
本次工作:数据库初始化、订单管理接口、业务规则测试和运行时修复
f2687c5 chore: prepare portable postgres development environment
0e8b8e1 feat: add api http conventions and booking state rules
0d4caab feat: add admin order tags and read state
bb5ccb1 feat: add admin authentication
b89853b fix: harden api authentication and validation
staticStatus=pass
completionStatus=complete
unresolvedIssues=0
```
远程:`https://git.app.que01.top/que01/persionalBrand.git`
## 已验证门禁
## 下一步优先级
- `pnpm check`
- `pnpm validate:template-release`
- `pnpm --filter @personal-brand/api test`
- `pnpm --filter @personal-brand/api test:integration`
- `pnpm test:api-client`
- `pnpm build`
- `pnpm template:doctor`
- Playwright:
- `template-preview-media.spec.ts`
- `admin-editor.spec.ts`
1. 接入真实品牌图片、电话和微信配置,并替换当前图片占位区域。
2. 在微信开发者工具/真机完成 `wx.login`、预约提交、订单查询和取消联调。
3. 完善管理后台订单详情、筛选和状态处理视觉页面。
4. 继续补充页面截图回归和真实素材下的移动端溢出检查。
本机数据库已应用全部 46 个 Prisma migration,`prisma migrate status` 为 up to date。
## 未决问题
## 安全审计
- 普通套餐采用固定菜单、每日菜单,还是固定套餐加每日可用状态。
- 朋友最终品牌名称、图片、联系方式、营业时间和配送范围。
- 微信小程序主体、AppID、服务类目和订阅消息模板是否可用。
- 生产部署使用哪家 PostgreSQL、对象存储和 API 托管服务。
- 当前 token 是开发阶段的签名 Bearer token;生产前应替换为带撤销能力的正式 session/Cookie 方案。
- `pnpm audit --prod --registry=https://registry.npmjs.org` 已完成。
- 可修复 advisory 已通过 `pnpm.overrides` 收敛;`request` 替换为 `@cypress/request@4.0.1`。
- 剩余 8 条为 `miniprogram-ci@2.1.31` 无修复版本的上游 advisory,已在 `pnpm.auditConfig.ignoreGhsas` 和 `docs/security-audit.md` 中显式登记风险、控制措施与跟进条件。
- Taro 官方 peer 仍声明 Vite 4;当前使用 Vite 6.4.3,H5 与 Weapp 实际构建均通过,peer warning 记录在安全审计文档。
## 当前明确不做
## 本机数据状态
- 支付、退款、发票、财务对账。
- 复杂库存、自动配送判断和每日菜单编排。
- 多商户注册、套餐计费、会员和营销系统。
- 自动发布微信小程序。
- 本机数据库 schema 已 up to date。
- 当前三个新版本已通过模板导入服务导入并发布:
- `acheng-campus-food@1.0.3`
- `atelier-solopreneur@1.3.2`
- `linjing-editorial@1.0.6`
- 既有品牌安装仍锁定各自原版本,需通过 Admin 的显式升级流程升级,不在本任务中静默变更。
## 跨电脑恢复
## 未决事项
```bash
git clone https://git.app.que01.top/que01/persionalBrand.git
cd persionalBrand
cat PROJECT_STATUS.md
cat agent.md
cp .env.example .env
```
有 Docker 的机器再执行:
```bash
docker compose up -d postgres
pnpm install
pnpm db:migrate
pnpm db:seed
```
## 更新规则
每完成一个可验证的开发任务,更新“当前阶段”“已完成”“最近提交”和“下一步优先级”。只记录已经发生或已经确认的事实;未确认内容放入“未决问题”。
- 生产发布仍需按 `docs/deployment.md` 配置真实环境变量并执行部署后健康检查。
- `miniprogram-ci` 上游发布修复版本后,需要移除对应的 audit ignore 与安全风险登记。
+1 -1
View File
@@ -123,7 +123,7 @@ export function Dashboard({
className="admin-brand-switcher"
value={brand.data?.id}
loading={memberships.isLoading}
onChange={(value) => {
onChange={(value: string | undefined) => {
if (value) void switchBrand(value);
}}
options={(memberships.data ?? []).map((item) => ({
@@ -8,10 +8,7 @@ import type {
TrustContent,
} from "@personal-brand/api-client";
import { projectBrandAliases, projectTrustPresentation } from "@personal-brand/api-client";
import {
presentationFieldName,
type PresentationValues,
} from "../../lib/presentation/presentation-bindings.js";
import { presentationFieldName } from "../../lib/presentation/presentation-bindings.js";
import type { RecordDraft } from "./presentation-editor-record-preview.js";
interface DraftWorkspaceInput {
+1 -1
View File
@@ -32,7 +32,7 @@
"bcryptjs": "^2.4.3",
"class-transformer": "^0.5.1",
"class-validator": "^0.14.1",
"fastify": "^5.11.3",
"fastify": "^5.12.7",
"miniprogram-ci": "^2.1.31",
"prisma": "^6.2.1",
"reflect-metadata": "^0.2.2",
@@ -0,0 +1,2 @@
-- 管理员 token 版本用于密码修改后撤销既有登录态。
ALTER TABLE "AdminUser" ADD COLUMN "tokenVersion" INTEGER NOT NULL DEFAULT 0;
+1
View File
@@ -458,6 +458,7 @@ model AdminUser {
platformTemplateRole PlatformTemplateRole @default(none)
isEnabled Boolean @default(true)
mustChangePassword Boolean @default(false)
tokenVersion Int @default(0)
lastLoginAt DateTime?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@ -151,8 +151,24 @@ export function buildTemplateContractMigrationReport({ brands, versions }) {
async function main() {
const prisma = new PrismaClient();
try {
const columns = await prisma.$queryRaw`
SELECT table_name, column_name
FROM information_schema.columns
WHERE table_schema = current_schema()
AND (
(table_name = 'BrandTemplateInstallation' AND column_name = 'visualTemplateKey')
OR (table_name = 'TemplatePackageVersion' AND column_name = 'visualTemplateKey')
)
`;
const hasInstallationVisualColumn = columns.some(
(column) => column.table_name === "BrandTemplateInstallation",
);
const hasVersionVisualColumn = columns.some(
(column) => column.table_name === "TemplatePackageVersion",
);
const [brands, versions] = await Promise.all([
prisma.$queryRaw`
hasInstallationVisualColumn
? prisma.$queryRaw`
SELECT
brand."id" AS "brandId",
brand."slug",
@@ -167,8 +183,25 @@ async function main() {
LEFT JOIN "BrandTemplateInstallation" installation
ON installation."brandId" = brand."id"
ORDER BY brand."slug", installation."id"
`
: prisma.$queryRaw`
SELECT
brand."id" AS "brandId",
brand."slug",
brand."templateKey" AS "industry",
NULL AS "brandVisualTemplateKey",
installation."id" AS "installationId",
NULL AS "installationVisualTemplateKey",
installation."templatePackageVersionId" AS "installationPackageVersionId",
NULL AS "snapshotVisualTemplateKey",
installation."configSnapshot"->>'packageKey' AS "snapshotPackageKey"
FROM "BrandProfile" brand
LEFT JOIN "BrandTemplateInstallation" installation
ON installation."brandId" = brand."id"
ORDER BY brand."slug", installation."id"
`,
prisma.$queryRaw`
hasVersionVisualColumn
? prisma.$queryRaw`
SELECT
"id",
"packageKey",
@@ -178,6 +211,17 @@ async function main() {
"manifestSnapshot"
FROM "TemplatePackageVersion"
ORDER BY "packageKey", "version"
`
: prisma.$queryRaw`
SELECT
"id",
"packageKey",
"version",
"status",
NULL AS "visualTemplateKey",
"manifestSnapshot"
FROM "TemplatePackageVersion"
ORDER BY "packageKey", "version"
`,
]);
process.stdout.write(
+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(
return 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,
identity.subject,
requestId,
actorId: identity.subject,
brandId: identity.brandId,
});
throw error;
}
);
}
@Post("template/select-version")
+95 -5
View File
@@ -13,6 +13,7 @@ import type { TemplatePackageManifest } from "@personal-brand/config";
import type { CreateTrustContentDto, UpdateTrustContentDto } from "./admin.dto.js";
import type { RollbackTemplateDto, UpgradeTemplateDto } from "./admin.dto.js";
import { PrismaService } from "./prisma.service.js";
import { recordTemplateOperationFailure } from "./modules/admin/template-operation-failure.js";
@Injectable()
export class TemplateWorkspaceService {
@@ -27,7 +28,7 @@ export class TemplateWorkspaceService {
const manifest = record(
installation.templatePackageVersion.manifestSnapshot,
) as unknown as TemplatePackageManifest;
if (validateTemplatePackageManifest(manifest as unknown as TemplatePackageManifest).length)
if (validateTemplatePackageManifest(manifest).length)
throw new BadRequestException("当前安装的模板包不符合统一模板契约");
return manifest.trustContentTypes?.map((item) => item.type) ?? [];
}
@@ -88,7 +89,32 @@ export class TemplateWorkspaceService {
throw new BadRequestException("品牌行业模型与模板安装不一致,请修复安装数据");
return template.key;
}
async install(brandId: string, templateKey: BrandTemplateKey, templatePackageVersionId: string) {
async install(
brandId: string,
templateKey: BrandTemplateKey,
templatePackageVersionId: string,
actorId: string,
requestId?: string,
) {
try {
return await this.installTemplate(brandId, templateKey, templatePackageVersionId);
} catch (error) {
await recordTemplateOperationFailure(this.prisma, {
action: error instanceof ConflictException ? "install_conflict" : "install",
error,
...(requestId ? { requestId } : {}),
actorId,
brandId,
});
throw error;
}
}
private async installTemplate(
brandId: string,
templateKey: BrandTemplateKey,
templatePackageVersionId: string,
) {
const template = getBrandTemplate(templateKey);
if (!template) throw new BadRequestException("行业模板不存在");
const [existing, brand] = await Promise.all([
@@ -171,7 +197,7 @@ export class TemplateWorkspaceService {
) {
throw new BadRequestException("模板包版本与行业或视觉模板不匹配");
}
if (validateTemplatePackageManifest(manifest as unknown as TemplatePackageManifest).length)
if (validateTemplatePackageManifest(manifest).length)
throw new BadRequestException("模板包版本不符合统一模板契约");
return version;
}
@@ -185,6 +211,30 @@ export class TemplateWorkspaceService {
},
actorId: string,
requestId?: string,
) {
try {
return await this.selectVersionUnrecorded(brandId, body, actorId, requestId);
} catch (error) {
await recordTemplateOperationFailure(this.prisma, {
action: "select_version",
error,
...(requestId ? { requestId } : {}),
actorId,
brandId,
});
throw error;
}
}
private async selectVersionUnrecorded(
brandId: string,
body: {
templatePackageVersionId: string;
expectedCurrentPackageVersionId?: string | null;
confirm: boolean;
},
actorId: string,
requestId?: string,
) {
if (!body.confirm) throw new BadRequestException("选择模板版本必须显式确认");
const [installation, brand, target] = await Promise.all([
@@ -410,6 +460,26 @@ export class TemplateWorkspaceService {
};
}
async upgrade(brandId: string, body: UpgradeTemplateDto, actorId: string, requestId?: string) {
try {
return await this.upgradeUnrecorded(brandId, body, actorId, requestId);
} catch (error) {
await recordTemplateOperationFailure(this.prisma, {
action: error instanceof ConflictException ? "install_conflict" : "upgrade",
error,
...(requestId ? { requestId } : {}),
actorId,
brandId,
});
throw error;
}
}
private async upgradeUnrecorded(
brandId: string,
body: UpgradeTemplateDto,
actorId: string,
requestId?: string,
) {
if (!body.confirm) throw new BadRequestException("升级模板必须显式确认");
const installation = await this.installation(brandId);
const target = await this.prisma.templatePackageVersion.findUnique({
@@ -492,6 +562,26 @@ export class TemplateWorkspaceService {
});
}
async rollback(brandId: string, actorId: string, body: RollbackTemplateDto, requestId?: string) {
try {
return await this.rollbackUnrecorded(brandId, actorId, body, requestId);
} catch (error) {
await recordTemplateOperationFailure(this.prisma, {
action: "rollback",
error,
...(requestId ? { requestId } : {}),
actorId,
brandId,
});
throw error;
}
}
private async rollbackUnrecorded(
brandId: string,
actorId: string,
body: RollbackTemplateDto,
requestId?: string,
) {
if (!body.confirm) throw new BadRequestException("回滚模板必须显式确认");
const installation = await this.installation(brandId);
if (installation.templateVersion !== body.expectedCurrentVersion)
@@ -564,9 +654,9 @@ export class TemplateWorkspaceService {
}
}
async function readPackageFiles(
function readPackageFiles(
version: Pick<TemplatePackageVersion, "validationReport">,
): Promise<Record<string, unknown>[]> {
): Record<string, unknown>[] {
return manifestRecords(record(version.validationReport).files);
}
@@ -1,12 +1,11 @@
import assert from "node:assert/strict";
import { generateKeyPairSync } from "node:crypto";
import { test } from "node:test";
import { BadGatewayException, BadRequestException, ConflictException } from "@nestjs/common";
import { BadRequestException, ConflictException } from "@nestjs/common";
import { templatePackageRegistry } from "@personal-brand/config";
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { mkdtempSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { AdminMiniAppBuildService } from "../src/modules/admin/admin-miniapp-build.service.js";
import { AdminMiniAppUploadService } from "../src/modules/admin/admin-miniapp-upload.service.js";
import type { AdminMiniAppReleaseService } from "../src/modules/admin/admin-miniapp-release.service.js";
import { encryptMiniAppCredential } from "../src/modules/admin/miniapp-credential-crypto.js";
@@ -105,7 +104,7 @@ function createHarness(
onLog("build log", "stdout");
return { exitCode: options.exitCode ?? 0 };
},
} as unknown as AdminMiniAppBuildService;
};
const service = new AdminMiniAppUploadService(releases, builds);
return { service, updates, artifactRoot, buildConfigs };
}
@@ -175,7 +174,7 @@ function createHarnessWithCredential(
onLog("build log", "stdout");
return { exitCode: options.exitCode ?? 0 };
},
} as unknown as AdminMiniAppBuildService;
};
return {
service: new AdminMiniAppUploadService(releases, builds),
updates,
@@ -235,7 +234,7 @@ test("missing artifact records build failure without invoking upload", async ()
() => service.run(brandId, actorId, "task-1", {}),
(error: unknown) => {
assert.ok(error instanceof BadRequestException);
assert.match((error as BadRequestException).message, /app\.json/);
assert.match(error.message, /app\.json/);
return true;
},
);
@@ -269,7 +268,7 @@ test("upload rejects missing credentials before build", async () => {
() => service.run(brandId, actorId, "task-1", {}),
(error: unknown) => {
assert.ok(error instanceof BadRequestException);
assert.match((error as BadRequestException).message, /WECHAT_UPLOAD_PRIVATE_KEY/);
assert.match(error.message, /WECHAT_UPLOAD_PRIVATE_KEY/);
return true;
},
);
+7 -2
View File
@@ -81,8 +81,13 @@ test("refactored admin controllers preserve their declared API routes", () => {
});
test("root module composes bounded feature modules only", () => {
const imports = Reflect.getMetadata("imports", AppModule) ?? [];
const names = imports.map((item) => item.name);
const imports = (Reflect.getMetadata("imports", AppModule) ?? []) as Array<{
name?: unknown;
}>;
const names = imports.map((item) => {
assert.ok(item && typeof item.name === "string", "App module import metadata is invalid");
return item.name;
});
assert.deepEqual(names, [
"InfrastructureModule",
"PublicModule",
+68 -2
View File
@@ -5,8 +5,9 @@ import { mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "n
import os from "node:os";
import path from "node:path";
import { after, before, test } from "node:test";
import bcrypt from "bcryptjs";
import { PrismaClient } from "@prisma/client";
import { getVisualTemplateManifest } from "@personal-brand/config";
import { getTemplatePackageManifest, getVisualTemplateManifest } from "@personal-brand/config";
import { createApp } from "../dist/main.js";
import { readIdentity, signIdentity } from "../dist/auth.js";
import { WechatAuthService } from "../dist/wechat-auth.js";
@@ -140,7 +141,7 @@ test("模板目录只允许平台模板管理员访问,并支持安全、幂
]);
const linjingVersion = baseline.items.find((item) => item.packageKey === "linjing-editorial");
assert.ok(linjingVersion);
assert.equal(linjingVersion.version, "1.0.5");
assert.equal(linjingVersion.version, "1.0.6");
const linjingPreview = await request(
`/admin/templates/${linjingVersion.id}/preview?industry=doors`,
{ headers },
@@ -1882,8 +1883,13 @@ test("visual template compatibility is enforced by catalog, preview, and version
const visuals = JSON.parse(catalog.body).visuals;
for (const visual of visuals) {
const manifest = getVisualTemplateManifest(visual.key);
const packageManifest = getTemplatePackageManifest(visual.key);
assert.ok(manifest, `Catalog visual must be installable: ${visual.key}`);
assert.ok(packageManifest, `Catalog visual must have a package manifest: ${visual.key}`);
assert.equal(manifest.key, visual.key);
assert.equal(manifest.key, packageManifest.visualTemplateKey);
assert.equal(manifest.version, packageManifest.version);
assert.equal(visual.version, packageManifest.version);
assert.deepEqual(manifest.supportedIndustryTemplates, visual.supportedIndustryTemplates);
}
assert.deepEqual(
@@ -3862,6 +3868,66 @@ test("admin login validates credentials", async () => {
assert.equal(response.statusCode, 401);
});
test("admin login does not auto-grant ownership to users without memberships", async () => {
const username = `no-membership-${Date.now()}`;
const user = await prisma.adminUser.create({
data: {
username,
passwordHash: await bcrypt.hash("initial-password-123", 12),
displayName: "未分配品牌管理员",
mustChangePassword: false,
},
});
try {
const login = await request("/admin/session/login", {
method: "POST",
payload: { username, password: "initial-password-123" },
});
assert.equal(login.statusCode, 403);
assert.equal(await prisma.brandMembership.count({ where: { adminUserId: user.id } }), 0);
} finally {
await prisma.adminUser.delete({ where: { id: user.id } });
}
});
test("changing an admin password revokes existing admin tokens", async () => {
const username = `token-version-${Date.now()}`;
const user = await prisma.adminUser.create({
data: {
username,
passwordHash: await bcrypt.hash("initial-password-123", 12),
displayName: "Token 版本管理员",
mustChangePassword: false,
memberships: {
create: { brandId, role: "admin", isEnabled: true },
},
},
});
try {
const login = await request("/admin/session/login", {
method: "POST",
payload: { username, password: "initial-password-123" },
});
assert.equal(login.statusCode, 201, login.body);
const token = JSON.parse(login.body).token;
const headers = { authorization: `Bearer ${token}` };
const before = await request("/admin/bookings/unread-count", { headers });
assert.equal(before.statusCode, 200, before.body);
const changed = await request("/admin/session/change-password", {
method: "POST",
headers,
payload: { currentPassword: "initial-password-123", newPassword: "changed-password-456" },
});
assert.equal(changed.statusCode, 201, changed.body);
const after = await request("/admin/bookings/unread-count", { headers });
assert.equal(after.statusCode, 401, after.body);
} finally {
await prisma.adminUser.delete({ where: { id: user.id } });
}
});
test("admin can list and switch only enabled brand memberships", async () => {
const login = await request("/admin/session/login", {
method: "POST",
@@ -1,4 +1,5 @@
import assert from "node:assert/strict";
import { Buffer } from "node:buffer";
import { spawnSync } from "node:child_process";
import { mkdtempSync, readdirSync, readFileSync, rmSync } from "node:fs";
import os from "node:os";
@@ -0,0 +1,16 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { PublicBrandContextService } from "../src/modules/public/public-brand-context.service.js";
import type { PrismaService } from "../src/prisma.service.js";
test("public default brand context fails fast when configuration is missing", async () => {
const previous = process.env.DEFAULT_BRAND_ID;
const service = new PublicBrandContextService({} as PrismaService);
try {
delete process.env.DEFAULT_BRAND_ID;
await assert.rejects(() => service.resolveId(), /默认品牌未配置/);
} finally {
if (previous !== undefined) process.env.DEFAULT_BRAND_ID = previous;
else delete process.env.DEFAULT_BRAND_ID;
}
});
@@ -123,6 +123,24 @@ test("uninstalled historical snapshots are reported without blocking mapped bran
});
});
test("migration audit supports the post-migration single-contract schema", () => {
const report = buildTemplateContractMigrationReport({
brands: [
brandRow({
brandVisualTemplateKey: null,
installationPackageVersionId: "version-1",
snapshotPackageKey: "acheng-campus-food",
}),
],
versions: [packageVersion({ visualTemplateKey: undefined })],
});
assert.equal(report.ready, true);
assert.equal(report.brands[0].mappingSource, "installation.configSnapshot.packageKey");
assert.equal(report.brands[0].packageKey, "acheng-campus-food");
assert.deepEqual(report.brands[0].blockers, []);
});
test("migration audit blocks conflicting explicit package declarations", () => {
const report = buildTemplateContractMigrationReport({
brands: [brandRow({ installationVisualTemplateKey: "linjing-editorial" })],
@@ -45,7 +45,7 @@ async function main() {
.filter((entry) => entry.isDirectory() && entry.name !== targetMigration)
.map((entry) => entry.name)
.sort();
assert.equal(migrationDirs.at(-1), "20261017120000_template_operation_failure_events");
assert.equal(migrationDirs.at(-1), "20261018170000_add_admin_token_version");
await admin.$executeRawUnsafe(`CREATE SCHEMA "${schema}"`);
createdSchema = true;
+2 -1
View File
@@ -80,7 +80,8 @@ function resolveTargets(envType, preview) {
if (envType === "admin") return [path.resolve(taroRoot, "../admin/dist")];
if (process.env.MINIAPP_OUTPUT_ROOT)
return [path.resolve(taroRoot, process.env.MINIAPP_OUTPUT_ROOT)];
const templateKey = process.env.TEMPLATE_KEY;
// 单模板构建默认使用餐饮试点;多模板预览必须显式 --preview。
const templateKey = process.env.TEMPLATE_KEY ?? "acheng-campus-food";
if (!templateKey) throw new Error("TEMPLATE_KEY is required for non-preview masking");
return [path.join(taroRoot, "dist", templateKey, envType)];
}
+1 -1
View File
@@ -32,7 +32,7 @@
"@types/react": "18.3.18",
"@types/react-dom": "18.3.5",
"@vitejs/plugin-react": "4.7.0",
"vite": "4.5.14",
"vite": "6.4.3",
"@types/node": "^22.10.0",
"@babel/plugin-proposal-decorators": "^7.25.9",
"@babel/plugin-transform-class-properties": "^7.25.9",
@@ -180,11 +180,25 @@ const runtimeWorkspace = {
trustPresentation: {},
capabilities: [],
plugins: [{ key: "inquiry", status: "enabled", config: {} }],
visualTemplate: {
key: "",
version: "",
name: "",
supportedIndustryTemplates: [],
variants: {},
},
theme: { colors: {} },
};
const templateContent = JSON.parse(
fs.readFileSync("../../packages/template-acheng-campus-food/template.json", "utf8"),
);
runtimeWorkspace.visualTemplate = {
key: templateContent.visualTemplateKey,
version: templateContent.version,
name: templateContent.displayName,
supportedIndustryTemplates: templateContent.supportedIndustryTemplates,
variants: templateContent.visualPresentation.variants,
};
// 根据真实声明生成完整列表数据,让每种内容区域都实际渲染。
const additionalFoodTrust = templateContent.trustContentTypes
@@ -706,6 +720,13 @@ test("林境模板支持首页和主理人区域点选", async ({ page }) => {
const editorialContent = JSON.parse(
fs.readFileSync("../../packages/template-linjing-editorial/template.json", "utf8"),
);
editorialWorkspace.visualTemplate = {
key: editorialContent.visualTemplateKey,
version: editorialContent.version,
name: editorialContent.displayName,
supportedIndustryTemplates: editorialContent.supportedIndustryTemplates,
variants: editorialContent.visualPresentation.variants,
};
await page.route("**/api/**", (route) => {
const url = new URL(route.request().url());
const path = url.pathname.replace(/^\/api/, "");
@@ -58,7 +58,7 @@ const runtimeWorkspace = {
},
visualTemplate: {
key: "acheng-campus-food",
version: "1.0.2",
version: "1.0.3",
name: "阿成校园餐",
},
templateData: {},
@@ -31,8 +31,15 @@ type PreviewVersion = {
contentChecksum: string;
};
type PreviewWorkspace = {
offerings: unknown[];
trustItems: unknown[];
inquiryForms: unknown[];
trustPresentation: Record<string, unknown>;
};
type PreviewBundle = {
preview: Record<string, unknown>;
preview: Record<string, unknown> & { workspace: PreviewWorkspace };
version: PreviewVersion;
};
@@ -158,7 +165,13 @@ test("导入包预览矩阵展示身份、资源和完整媒体槽位", async ({
localStorage.setItem("adminToken", "fixture-token");
localStorage.setItem("adminPlatformTemplateRole", "template_admin");
});
const emptyPreview = structuredClone(preview);
emptyPreview.workspace.offerings = [];
emptyPreview.workspace.trustItems = [];
emptyPreview.workspace.inquiryForms = [];
emptyPreview.workspace.trustPresentation = {};
let attempts = 0;
let serveEmptyPreview = false;
const writes: string[] = [];
await page.route("**/api/**", async (route) => {
const url = new URL(route.request().url());
@@ -170,6 +183,8 @@ test("导入包预览矩阵展示身份、资源和完整媒体槽位", async ({
json:
attempts === 1
? { error: { code: "HTTP_400", message: "预览测试失败,请重试" } }
: serveEmptyPreview
? emptyPreview
: preview,
});
}
@@ -224,6 +239,23 @@ test("导入包预览矩阵展示身份、资源和完整媒体槽位", async ({
),
});
}
// 清空业务记录后重新打开真实包预览,验证空态不是仅在源码中存在。
serveEmptyPreview = true;
await modal.getByRole("button", { name: "关闭" }).click();
await expect(modal).toBeHidden();
await page.getByRole("button", { name: /预览/ }).click();
await expect(modal.locator(".component-template-preview .runtime-state")).toContainText(
/正在整理中/,
);
if (evidenceDirectory) {
await page.screenshot({
path: path.join(
evidenceDirectory,
`empty-${String(sequence).padStart(2, "0")}-${mediaCase.packageKey}-${mediaCase.industry}.png`,
),
});
}
await page.unroute("**/api/**");
});
}
+3 -3
View File
@@ -4,17 +4,17 @@
{
"packageKey": "acheng-campus-food",
"packageName": "@personal-brand/template-acheng-campus-food",
"version": "1.0.2"
"version": "1.0.3"
},
{
"packageKey": "linjing-editorial",
"packageName": "@personal-brand/template-linjing-editorial",
"version": "1.0.4"
"version": "1.0.6"
},
{
"packageKey": "atelier-solopreneur",
"packageName": "@personal-brand/template-atelier-solopreneur",
"version": "1.3.1"
"version": "1.3.2"
}
]
}
@@ -8,7 +8,7 @@
小程序在 `app.js` 的 `globalData.brandSlug` 中维护唯一品牌身份,优先读取本地配置 `brandSlug`,没有配置时使用开发默认值 `default-brand`。`utils/request.js` 对 `/public/*` 请求统一追加 `brandSlug`,页面和模块不得自行拼接品牌参数。客户和管理接口不追加该参数。
API 通过 `PublicBrandContextService` 统一解析 `brandSlug`,没有 slug 时保留 `DEFAULT_BRAND_ID` 作为开发 fallback;未知 slug 返回 404。
API 通过 `PublicBrandContextService` 统一解析 `brandSlug`;没有 slug 时使用显式配置的 `DEFAULT_BRAND_ID`,该配置缺失时返回 503,不使用硬编码 fallback;未知 slug 返回 404。
## Alternatives
+1 -1
View File
@@ -10,7 +10,7 @@
## 决策
- 所有模板包必须通过唯一的 `TemplatePackageManifest` 契约及其 `runtimeContract` 校验。契约外字段、缺失字段、未知 renderer 或不匹配的行业声明均明确失败,不推断、不静默回退。
- 所有模板包必须通过唯一的 `TemplatePackageManifest` 契约及其 `runtimeContract` 校验;`visualPresentation` 是该契约的一部分,承载 description、variants、theme 和 layout。契约外字段、缺失字段、未知 renderer 或不匹配的行业声明均明确失败,不推断、不静默回退。
- 品牌当前使用的模板方案必须有明确、持久化的唯一安装记录,并锁定一个已发布的 `TemplatePackageVersion`。package key、版本、视觉 renderer key 和 checksum 只由该版本的 package manifest 与不可变归档确定;数据库不重复存 renderer key。运行时不得从品牌行业、全局默认值或本地注册表推测视觉模板。
- 模板 manifest 是模板结构、资源、编辑绑定、能力声明、preview fixture 和 bootstrap sample 的唯一事实来源。删除包外的重复 sample 注册表和 fallback。
- `BrandProfile.templateKey` 表示行业模型,不是视觉模板;模板版本选择只由正式安装记录的精确 package version 引用表达。视觉 renderer key 只存在于 package manifest。禁止在 `BrandProfile.config.visualTemplateKey` 或安装/版本表再存一份副本。
+5 -1
View File
@@ -86,7 +86,11 @@ DEFAULT_BRAND_ID=<production-brand-id>
SEED_ADMIN_PASSWORD=<first-boot-admin-password>
```
`DATABASE_URL` 使用最小权限数据库账号。`SESSION_SECRET` 不能复用示例值或开发值。媒体上传使用 S3 兼容对象存储和预签名直传,生产环境必须配置独立的 `OBJECT_STORAGE_PUBLIC_URL`、最小权限访问密钥和专用 bucket。微信相关变量只在启用对应能力时配置,同样不能提交真实凭据。
`DATABASE_URL` 使用最小权限数据库账号。`SESSION_SECRET` 不能复用示例值或开发值。`DEFAULT_BRAND_ID` 供未携带 `brandSlug` 的公共请求使用,缺失时 API 返回 503,不会回退到硬编码品牌。
`CORS_ORIGINS` 默认为空并关闭跨域访问;只有 Admin 或预览应用从其他 origin 调用 API 时,才配置逗号分隔的 HTTPS origin allow-list。
本次部署会为管理员账号引入 `tokenVersion`。既有 admin token 会因缺少当前版本号而失效,管理员需要重新登录;之后修改密码会立即撤销同一账号的旧 token。媒体上传使用 S3 兼容对象存储和预签名直传,生产环境必须配置独立的 `OBJECT_STORAGE_PUBLIC_URL`、最小权限访问密钥和专用 bucket。微信相关变量只在启用对应能力时配置,同样不能提交真实凭据。
### 2. 构建发布包
+33
View File
@@ -0,0 +1,33 @@
# Security Audit
最后更新:2026-10-18
## 结论
`pnpm audit --prod --registry=https://registry.npmjs.org` 已从 84 条 advisory 降到 0 条未登记 advisory。可直接修复的传递依赖通过根 `pnpm.overrides` 升级到修复版本;`request` 已替换为维护 fork `@cypress/request@4.0.1`。
## 已执行的兼容性验证
- `pnpm --filter @personal-brand/api test`
- `pnpm --filter @personal-brand/admin build`
- `TEMPLATE_KEY=acheng-campus-food pnpm --filter @personal-brand/taro build:h5`
- `TEMPLATE_KEY=acheng-campus-food pnpm --filter @personal-brand/taro build:weapp`
Taro 虽然在 peer dependency 中声明 Vite 4,但 Vite 6.4.3 的 H5 与 Weapp 实际构建均通过。已知 peer warning 记录在安装输出中,不能在未升级 Taro 前移除。
## 已接受的未修复上游 advisory
以下 8 条来自 `miniprogram-ci@2.1.31` 的无修复版本依赖。上游当前最新版本仍是 `2.1.31`,没有 patched version。它们在 `pnpm.auditConfig.ignoreGhsas` 中显式登记,避免每次审计重复失败;这不是宣称风险不存在。
| GHSA | 包 | 风险面 | 当前控制 | 跟进 |
| ------------------- | ----------------- | ---------------- | ------------------------------- | ------------------------------------------ |
| GHSA-pfq8-rq6v-vf5m | `html-minifier` | 构建期 HTML 压缩 | 仅处理平台生成的受信模板产物 | 升级 `miniprogram-ci` 或替换构建器 |
| GHSA-35jh-r3h4-6jhm | `lodash.template` | 构建期模板编译 | 仅处理平台生成的受信模板产物 | 升级 `miniprogram-ci` |
| GHSA-67hx-6x53-jw92 | `babel-traverse` | Babel 6 构建路径 | 仅处理平台生成的受信模板产物 | 升级 `miniprogram-ci` 或替换 Babel 6 链路 |
| GHSA-mp2f-45pm-3cg9 | `decompress` | 下载包解压 | 未把用户上传 archive 交给该链路 | 升级 `miniprogram-ci` 或移除 download 链路 |
| GHSA-h39j-r5qq-r9mm | `decompress` | 下载包解压 | 同上 | 同上 |
| GHSA-jwp9-9v96-94mx | `decompress` | 下载包解压 | 同上 | 同上 |
| GHSA-hrh2-vp3x-79xf | `decompress` | 下载包解压 | 同上 | 同上 |
| GHSA-vfj7-8cjw-p6xm | `braces` | 构建期 glob 匹配 | 仅匹配平台生成的受信文件 | 升级 `miniprogram-ci` |
负责人:平台维护者。跟进条件:`miniprogram-ci` 发布包含上述依赖修复的新版本,或将小程序上传 worker 独立部署并移除 API 生产依赖。
+2
View File
@@ -30,6 +30,8 @@ staticStatus 只代表支持范围内的静态检查。completionStatus 保持 u
已逐条完成源码审阅的 review 可登记在 `.codex-tasks/template-audit-execution/raw/manual-review.json`。登记必须使用和诊断报告一致的 `file/page/target/binding/line/message`,并保留结论与证据;doctor 只把精确匹配的 review 标记为 `source-reviewed`,不改变 `completionStatus`。未匹配的新 review 和全部 blocker 仍会让命令失败。
完成证据登记在 `.codex-tasks/template-audit-execution/raw/completion-evidence.json`。每套模板必须提供 `real-manifest-interaction`、`save-reload-publish-isolation`、`visual-reference`、`empty-error-branches` 四类 `passed` 证据;每类证据必须包含实际命令、日志或截图产物及其 SHA-256。doctor 会校验证据覆盖全部模板、产物存在且哈希一致。全部通过时 `completionStatus=complete`;证据文件缺失时保持 `unverified`;登记不完整或哈希不匹配时对应模板为 `incomplete` 并让命令失败。
AST 解析可追踪 workspace.brand、presentation、object 和局部别名。动态路径、跨组件和间接映射等未知情况标为 review,不能猜测为通过。诊断器包含正反故障注入测试。
## 修复闭环
+2 -2
View File
@@ -14,9 +14,9 @@
### 仓库内视觉模板包
- acheng-campus-food@1.0.2:餐饮场景,使用 food 行业能力。
- acheng-campus-food@1.0.3:餐饮场景,使用 food 行业能力。
- linjing-editorial@1.0.4:林境建筑画册,可用于 doors 和 personal 组合。
- atelier-solopreneur@1.3.1:独立工坊方向,适配 personal 行业。
- atelier-solopreneur@1.3.2:独立工坊方向,适配 personal 行业。
以上是仓库盘点,不表示三个包都已经通过线上导入、预览、品牌安装和微信上传验收。生成目录当前位于 packages/config/src/generated-template-packages.ts,后续必须由导出和 conformance 流程生成并校验。
+2
View File
@@ -60,7 +60,9 @@ export default tseslint.config(
files: [
"apps/admin/template-preview-css.mjs",
"apps/api/scripts/template-contract-migration-audit.mjs",
"apps/api/scripts/create-atelier-brand.mjs",
"apps/api/test/template-contract-migration-audit.test.mjs",
"apps/api/test/prepare-integration-template-packages.mjs",
"apps/api/test/template-contract-migration.integration.mjs",
],
languageOptions: {
+51
View File
@@ -55,5 +55,56 @@
"turbo": "^2.3.3",
"typescript": "^5.7.2",
"typescript-eslint": "^8.18.0"
},
"pnpm": {
"overrides": {
"@babel/core": "7.29.6",
"@babel/helpers": "7.26.10",
"@babel/plugin-transform-modules-systemjs": "7.29.4",
"@babel/runtime": "7.26.10",
"@babel/traverse": "7.26.10",
"@tarojs/components>swiper": "12.1.2",
"@tarojs/helper>esbuild": "0.25.0",
"@tarojs/plugin-framework-react>vite": "6.4.3",
"babel-core>json5": "1.0.2",
"cacheable-request>http-cache-semantics": "4.3.0",
"conf>ajv": "8.20.0",
"cos-js-sdk-v5>fast-xml-parser": "5.7.0",
"cos-nodejs-sdk-v5>fast-xml-parser": "5.7.0",
"deepmerge-ts": "8.0.2",
"download>got": "11.8.6",
"lodash-es": "4.18.1",
"miniprogram-ci>adm-zip": "0.6.1",
"miniprogram-ci>image-size": "2.0.4",
"miniprogram-ci>minimatch": "3.1.4",
"miniprogram-ci>protobufjs": "7.6.5",
"miniprogram-ci>terser": "4.8.1",
"miniprogram-ci>tmp": "0.2.7",
"postcss-selector-parser": "7.1.6",
"query-string>decode-uri-component": "0.5.0",
"request>form-data": "2.5.6",
"request>qs": "6.16.1",
"request>tough-cookie": "4.1.3",
"request>uuid": "11.1.1",
"source-map-js": "1.2.2",
"@jimp/core>file-type": "21.3.4",
"@jimp/core>phin": "3.7.1",
"fastify": "5.12.7",
"uuid": "11.1.1",
"@tarojs/components-react>swiper": "12.1.2",
"request": "npm:@cypress/request@4.0.1"
},
"auditConfig": {
"ignoreGhsas": [
"GHSA-pfq8-rq6v-vf5m",
"GHSA-35jh-r3h4-6jhm",
"GHSA-67hx-6x53-jw92",
"GHSA-mp2f-45pm-3cg9",
"GHSA-h39j-r5qq-r9mm",
"GHSA-jwp9-9v96-94mx",
"GHSA-hrh2-vp3x-79xf",
"GHSA-vfj7-8cjw-p6xm"
]
}
}
}
@@ -4,7 +4,7 @@ import type { TemplatePackageManifest } from "./index.js";
export const generatedTemplatePackageRegistry: readonly TemplatePackageManifest[] = [
{
"packageKey": "acheng-campus-food",
"version": "1.0.2",
"version": "1.0.3",
"displayName": "阿成校园餐",
"defaultBrandSlug": "default-brand",
"runtimeContract": "1.0",
@@ -1659,6 +1659,42 @@ export const generatedTemplatePackageRegistry: readonly TemplatePackageManifest[
"pages/records"
],
"visualTemplateKey": "acheng-campus-food",
"visualPresentation": {
"description": "适合校园餐饮、套餐预订和团体定制的暖橙菜单视觉。",
"variants": {
"hero": "stall-board",
"offeringList": "menu-card",
"detail": "dish-detail"
},
"theme": {
"colors": {
"background": "#FFF8F0",
"foreground": "#29231F",
"accent": "#E87532",
"dark": "#3B2118"
},
"radius": {
"card": "24rpx"
}
},
"layout": {
"home": [
"founder-card",
"brand-hero",
"trust-proof",
"offering-list"
],
"offerings": [
"offering-list"
],
"detail": [
"offering-detail"
],
"profile": [
"profile"
]
}
},
"previewFixture": {
"food": {
"schemaVersion": "1",
@@ -2050,7 +2086,7 @@ export const generatedTemplatePackageRegistry: readonly TemplatePackageManifest[
},
{
"packageKey": "atelier-solopreneur",
"version": "1.3.1",
"version": "1.3.2",
"displayName": "独立工坊 · 品牌小程序",
"defaultBrandSlug": "atelier-studio",
"runtimeContract": "1.0",
@@ -4343,11 +4379,45 @@ export const generatedTemplatePackageRegistry: readonly TemplatePackageManifest[
}
}
},
"visualTemplateKey": "atelier-solopreneur"
"visualTemplateKey": "atelier-solopreneur",
"visualPresentation": {
"description": "展示品牌小程序服务、试点案例与合作流程,承接需求咨询。",
"variants": {
"hero": "editorial",
"offeringList": "service-system",
"detail": "project-case"
},
"theme": {
"colors": {
"background": "#f6f6f4",
"foreground": "#17181a",
"accent": "#1f3a5f",
"dark": "#1f3a5f"
},
"radius": {
"card": "28rpx"
}
},
"layout": {
"home": [
"brand-hero",
"offering-list"
],
"offerings": [
"offering-list"
],
"detail": [
"offering-detail"
],
"profile": [
"profile"
]
}
}
},
{
"packageKey": "linjing-editorial",
"version": "1.0.5",
"version": "1.0.6",
"displayName": "林境建筑画册",
"defaultBrandSlug": "linjing-doors",
"runtimeContract": "1.0",
@@ -6264,6 +6334,43 @@ export const generatedTemplatePackageRegistry: readonly TemplatePackageManifest[
"pages/bookings/index"
],
"visualTemplateKey": "linjing-editorial",
"visualPresentation": {
"description": "适合高端定制、建筑作品和项目型个人品牌。",
"variants": {
"hero": "architectural",
"offeringList": "editorial",
"detail": "project-case"
},
"theme": {
"colors": {
"background": "#F7F5F1",
"foreground": "#252525",
"accent": "#8A6846",
"dark": "#202221"
},
"radius": {
"card": "16rpx"
}
},
"layout": {
"home": [
"founder-card",
"brand-hero",
"trust-proof",
"trust-manifesto",
"offering-list"
],
"offerings": [
"offering-list"
],
"detail": [
"offering-detail"
],
"profile": [
"profile"
]
}
},
"previewFixture": {
"doors": {
"schemaVersion": "1",
@@ -6868,4 +6975,4 @@ export const generatedTemplatePackageRegistry: readonly TemplatePackageManifest[
}
];
export const generatedTemplatePackageRegistryHash =
"dc82c85917f137a0f2a3a473147f32426ea0f46bf107adf709afd34cd5699db8";
"6c629f916b92e889a8984fde3ffc8ea3cb39ba25542b070da1f029ae57665d73";
@@ -1,3 +1,4 @@
import type { TemplateVisualPresentation } from "@personal-brand/template-contract";
import type { BrandTemplateKey } from "./template-keys.js";
import type { CapabilityKey } from "./template-keys.js";
import type { VisualTemplateKey } from "./template-keys.js";
@@ -28,6 +29,7 @@ export interface TemplatePackageManifest {
version: string;
displayName: string;
visualTemplateKey: VisualTemplateKey;
visualPresentation: TemplateVisualPresentation;
runtimeContract: "1.0";
supportedIndustryTemplates: readonly BrandTemplateKey[];
entrypoints: Readonly<Record<string, string>>;
+1 -269
View File
@@ -1,280 +1,12 @@
import type { VisualTemplateKey } from "./template-keys.js";
import type { VisualTemplateDefinition, VisualTemplateManifest } from "./brand-contracts.js";
import { getTemplatePackageManifestForVisualKey } from "./template-packages.js";
import { getVisualTemplate } from "./visual-templates.js";
const linjingEditorialManifest: VisualTemplateManifest = {
schemaVersion: "1.0",
key: "linjing-editorial",
version: "1.0.0",
name: "林境建筑画册",
description: "以个人品牌信任为主线、以高端项目作品为表达重点的编辑式视觉模板。",
supportedIndustryTemplates: ["personal", "doors"],
brandFirst: true,
tokens: {
colors: {
background: "#F7F5F1",
surface: "#FFFFFF",
foreground: "#252525",
muted: "#77736C",
accent: "#8A6846",
dark: "#202221",
},
spacing: { page: "32rpx", section: "56rpx", module: "24rpx" },
typography: { display: "56rpx", heading: "36rpx", body: "28rpx", caption: "22rpx" },
radius: { card: "16rpx", button: "999rpx", media: "12rpx" },
shadows: { card: "0 8rpx 32rpx rgba(32,34,33,0.08)" },
},
assets: [
{ key: "brand.logo", label: "品牌标志", required: false, kind: "logo" },
{
key: "home.hero",
label: "首页首屏图",
required: true,
kind: "image",
aspectRatio: "16:9",
},
{
key: "offering.cover",
label: "业务提供项封面",
required: true,
kind: "image",
aspectRatio: "1:1",
},
{
key: "profile.portrait",
label: "主理人肖像",
required: false,
kind: "image",
aspectRatio: "1:1",
},
{ key: "brand.texture", label: "品牌底纹", required: false, kind: "texture" },
],
dataSlots: [
{
key: "brand.identity",
source: "brand",
required: true,
description: "品牌名、定位和主理人身份",
},
{ key: "brand.hero", source: "brand", required: true, description: "品牌首屏表达和行动入口" },
{ key: "trust.proof", source: "trust", required: true, description: "经历、资质、案例和方法" },
{
key: "offerings.list",
source: "offering",
required: true,
description: "可展示的业务提供项",
},
{
key: "offering.detail",
source: "offering",
required: true,
description: "单个提供项的详情内容",
},
{ key: "inquiry.form", source: "inquiry", required: true, description: "品牌咨询或预约表单" },
{
key: "records.items",
source: "records",
required: true,
description: "用户提交后的跟进记录",
},
{
key: "profile.contact",
source: "profile",
required: true,
description: "联系方式和合作预期",
},
],
pages: [
{
key: "home",
title: "首页",
renderer: "linjing-home",
modules: [
{
key: "identity",
type: "brand-identity",
variant: "editorial-card",
required: true,
dataSlots: ["brand.identity"],
assetSlots: ["brand.logo"],
},
{
key: "hero",
type: "hero",
variant: "architectural",
required: true,
dataSlots: ["brand.hero"],
assetSlots: ["home.hero"],
},
{
key: "proof",
type: "trust",
variant: "proof-strip",
required: true,
dataSlots: ["trust.proof"],
},
{
key: "offerings",
type: "offering-list",
variant: "editorial-list",
required: true,
dataSlots: ["offerings.list"],
assetSlots: ["offering.cover"],
capability: "offerings",
},
{
key: "contact",
type: "contact",
variant: "quiet-footer",
required: true,
dataSlots: ["profile.contact"],
},
],
},
{
key: "offerings",
title: "业务提供项",
renderer: "linjing-offerings",
modules: [
{
key: "offerings",
type: "offering-list",
variant: "editorial-grid",
required: true,
dataSlots: ["offerings.list"],
assetSlots: ["offering.cover"],
capability: "offerings",
},
],
},
{
key: "detail",
title: "提供项详情",
renderer: "linjing-offering-detail",
modules: [
{
key: "detail",
type: "offering-detail",
variant: "project-case",
required: true,
dataSlots: ["offering.detail"],
assetSlots: ["offering.cover"],
capability: "offerings",
},
],
},
{
key: "inquiry",
title: "咨询与预约",
renderer: "linjing-inquiry",
modules: [
{
key: "inquiry",
type: "inquiry-form",
variant: "editorial-form",
required: true,
dataSlots: ["inquiry.form"],
capability: "inquiry",
},
],
},
{
key: "success",
title: "提交成功",
renderer: "linjing-success",
modules: [
{
key: "success",
type: "success-summary",
variant: "editorial-confirmation",
required: true,
dataSlots: ["brand.identity"],
},
],
},
{
key: "records",
title: "我的记录",
renderer: "linjing-records",
modules: [
{
key: "records",
type: "records-list",
variant: "timeline",
required: true,
dataSlots: ["records.items"],
},
],
},
{
key: "profile",
title: "主理人与我",
renderer: "linjing-profile",
modules: [
{
key: "identity",
type: "brand-identity",
variant: "profile-editorial",
required: true,
dataSlots: ["brand.identity"],
assetSlots: ["profile.portrait"],
},
{
key: "contact",
type: "contact",
variant: "contact-sheet",
required: true,
dataSlots: ["profile.contact"],
},
],
},
],
capabilities: ["offerings", "inquiry"],
};
export const visualTemplateManifests: Record<VisualTemplateKey, VisualTemplateManifest> = {
"linjing-editorial": linjingEditorialManifest,
"acheng-campus-food": {
...linjingEditorialManifest,
key: "acheng-campus-food",
version: "1.0.0",
name: "阿成校园餐",
description: "面向校园餐饮摊贩的菜单、出摊动态和团体预订视觉模板。",
supportedIndustryTemplates: ["food"],
tokens: {
...linjingEditorialManifest.tokens,
colors: {
background: "#FFF8F0",
surface: "#FFFFFF",
foreground: "#29231F",
muted: "#7A6A60",
accent: "#E87532",
dark: "#3B2118",
},
radius: { card: "24rpx", button: "999rpx", media: "20rpx" },
},
pages: linjingEditorialManifest.pages.map((pageDefinition) => {
const renderer =
pageDefinition.key === "home"
? "acheng-home"
: pageDefinition.key === "offerings"
? "acheng-offerings"
: pageDefinition.key === "profile"
? "acheng-profile"
: pageDefinition.renderer;
return renderer ? { ...pageDefinition, renderer } : pageDefinition;
}),
capabilities: ["offerings", "inquiry", "booking"],
},
};
export function getVisualTemplateManifest(key: string): VisualTemplateManifest | undefined {
if (visualTemplateManifests[key]) return visualTemplateManifests[key];
const manifest = getTemplatePackageManifestForVisualKey(key);
const visual = getVisualTemplate(key);
if (!manifest || !visual) return undefined;
// 新模板从包声明投影安装快照,避免目录可选但遗漏旧版 manifest 注册。
// 所有模板都从包 manifest 投影安装快照,不保留旧视觉 manifest 注册表。
const roles: VisualTemplateManifest["pages"] = [
{
key: "home",
+30 -60
View File
@@ -1,69 +1,39 @@
import type { VisualTemplateKey } from "./template-keys.js";
import type { VisualTemplateDefinition } from "./brand-contracts.js";
import { templatePackageRegistry } from "./template-packages.js";
export const visualTemplates: Record<VisualTemplateKey, VisualTemplateDefinition> = {
"linjing-editorial": {
key: "linjing-editorial",
version: "1.0.0",
name: "林境建筑画册",
description: "适合高端定制、建筑作品和项目型个人品牌。",
supportedIndustryTemplates: ["personal", "doors"],
variants: { hero: "architectural", offeringList: "editorial", detail: "project-case" },
theme: {
colors: { background: "#F7F5F1", foreground: "#252525", accent: "#8A6846", dark: "#202221" },
radius: { card: "16rpx" },
},
layout: {
home: ["founder-card", "brand-hero", "trust-proof", "trust-manifesto", "offering-list"],
offerings: ["offering-list"],
detail: ["offering-detail"],
profile: ["profile"],
},
},
"acheng-campus-food": {
key: "acheng-campus-food",
version: "1.0.0",
name: "阿成校园餐",
description: "适合校园餐饮、套餐预订和团体定制的暖橙菜单视觉。",
supportedIndustryTemplates: ["food"],
variants: { hero: "stall-board", offeringList: "menu-card", detail: "dish-detail" },
theme: {
colors: { background: "#FFF8F0", foreground: "#29231F", accent: "#E87532", dark: "#3B2118" },
radius: { card: "24rpx" },
},
layout: {
home: ["founder-card", "brand-hero", "trust-proof", "offering-list"],
offerings: ["offering-list"],
detail: ["offering-detail"],
profile: ["profile"],
},
},
"atelier-solopreneur": {
key: "atelier-solopreneur",
version: "1.2.0",
name: "独立工坊 · 品牌小程序",
description: "展示品牌小程序服务、试点案例与合作流程,承接需求咨询。",
supportedIndustryTemplates: ["personal"],
variants: { hero: "editorial", offeringList: "service-system", detail: "project-case" },
theme: {
colors: { background: "#f6f6f4", foreground: "#17181a", accent: "#1f3a5f", dark: "#1f3a5f" },
radius: { card: "28rpx" },
},
layout: {
home: ["brand-hero", "offering-list"],
offerings: ["offering-list"],
detail: ["offering-detail"],
profile: ["profile"],
},
},
};
export const visualTemplateKeys: VisualTemplateKey[] = templatePackageRegistry.map(
(manifest) => manifest.visualTemplateKey,
);
export function listVisualTemplateKeys(): VisualTemplateKey[] {
return Object.keys(visualTemplates);
return visualTemplateKeys;
}
export const visualTemplateKeys = listVisualTemplateKeys();
export function getVisualTemplate(key: string): VisualTemplateDefinition | undefined {
return visualTemplates[key];
const manifest = templatePackageRegistry.find((item) => item.visualTemplateKey === key);
if (!manifest) return undefined;
const presentation = manifest.visualPresentation;
return {
key: manifest.visualTemplateKey,
version: manifest.version,
name: manifest.displayName,
description: presentation.description,
supportedIndustryTemplates: [...manifest.supportedIndustryTemplates],
variants: { ...presentation.variants },
theme: {
colors: { ...presentation.theme.colors },
radius: { ...presentation.theme.radius },
},
...(presentation.layout
? {
layout: {
home: [...presentation.layout.home],
offerings: [...presentation.layout.offerings],
detail: [...presentation.layout.detail],
profile: [...presentation.layout.profile],
},
}
: {}),
};
}
@@ -1,6 +1,6 @@
{
"name": "@personal-brand/template-acheng-campus-food",
"version": "1.0.2",
"version": "1.0.3",
"private": true,
"type": "module",
"files": [
@@ -70,7 +70,8 @@ function Home({ workspace }: { workspace: RuntimeWorkspace }) {
</Text>
</View>
<View className="dish-grid">
{list.map((item) => (
{list.length ? (
list.map((item) => (
<View
className="dish"
key={item.id}
@@ -85,7 +86,13 @@ function Home({ workspace }: { workspace: RuntimeWorkspace }) {
<Text className="price">{item.priceRange}</Text>
</View>
</View>
))}
))
) : (
<View className="runtime-state">
餐品与服务正在整理中
<Button onClick={() => navigate("offerings")}>查看全部</Button>
</View>
)}
</View>
<View data-editor-target="food.home.promise-heading">
<Text className="heading manifesto-heading">{p.manifestoTitle}</Text>
@@ -1,6 +1,6 @@
{
"packageKey": "acheng-campus-food",
"version": "1.0.2",
"version": "1.0.3",
"displayName": "阿成校园餐",
"defaultBrandSlug": "default-brand",
"runtimeContract": "1.0",
@@ -1616,6 +1616,31 @@
],
"overrides": ["pages/inquiry", "pages/inquiry-success", "pages/offering", "pages/records"],
"visualTemplateKey": "acheng-campus-food",
"visualPresentation": {
"description": "适合校园餐饮、套餐预订和团体定制的暖橙菜单视觉。",
"variants": {
"hero": "stall-board",
"offeringList": "menu-card",
"detail": "dish-detail"
},
"theme": {
"colors": {
"background": "#FFF8F0",
"foreground": "#29231F",
"accent": "#E87532",
"dark": "#3B2118"
},
"radius": {
"card": "24rpx"
}
},
"layout": {
"home": ["founder-card", "brand-hero", "trust-proof", "offering-list"],
"offerings": ["offering-list"],
"detail": ["offering-detail"],
"profile": ["profile"]
}
},
"previewFixture": {
"food": {
"schemaVersion": "1",
@@ -1,6 +1,6 @@
{
"name": "@personal-brand/template-atelier-solopreneur",
"version": "1.3.1",
"version": "1.3.2",
"private": true,
"type": "module",
"files": [
@@ -88,7 +88,8 @@ function Home({ workspace }: Props) {
<Text>{p.caseAction}</Text>
</View>
<View className="atelier-cases">
{workspace.offerings.map((item) => (
{workspace.offerings.length ? (
workspace.offerings.map((item) => (
<View
className="atelier-case"
key={item.id}
@@ -109,7 +110,13 @@ function Home({ workspace }: Props) {
<Text className="atelier-case-arrow">→</Text>
</View>
</View>
))}
))
) : (
<View className="runtime-state">
案例内容正在整理中
<InquiryAction workspace={workspace} label={p.primaryAction} />
</View>
)}
</View>
<View className="atelier-heading" data-editor-target="atelier.home.audienceHeading">
<Text>{p.audienceTitle}</Text>
@@ -1,6 +1,6 @@
{
"packageKey": "atelier-solopreneur",
"version": "1.3.1",
"version": "1.3.2",
"displayName": "独立工坊 · 品牌小程序",
"defaultBrandSlug": "atelier-studio",
"runtimeContract": "1.0",
@@ -2266,5 +2266,30 @@
}
}
},
"visualTemplateKey": "atelier-solopreneur"
"visualTemplateKey": "atelier-solopreneur",
"visualPresentation": {
"description": "展示品牌小程序服务、试点案例与合作流程,承接需求咨询。",
"variants": {
"hero": "editorial",
"offeringList": "service-system",
"detail": "project-case"
},
"theme": {
"colors": {
"background": "#f6f6f4",
"foreground": "#17181a",
"accent": "#1f3a5f",
"dark": "#1f3a5f"
},
"radius": {
"card": "28rpx"
}
},
"layout": {
"home": ["brand-hero", "offering-list"],
"offerings": ["offering-list"],
"detail": ["offering-detail"],
"profile": ["profile"]
}
}
}
@@ -3,6 +3,25 @@
"version": "0.1.0",
"displayName": "咨询师演练模板",
"visualTemplateKey": "drill-consultant",
"visualPresentation": {
"description": "用于编译器测试的咨询师视觉演练。",
"variants": {
"hero": "consulting",
"offeringList": "service-list",
"detail": "case"
},
"theme": {
"colors": {
"background": "#f7f7f4",
"foreground": "#202020",
"accent": "#2f5d62",
"dark": "#17252a"
},
"radius": {
"card": "16rpx"
}
}
},
"defaultBrandSlug": "drill-consultant",
"runtimeContract": "1.0",
"supportedIndustryTemplates": ["consulting"],
@@ -16,9 +35,21 @@
"profile": "pages/profile/index"
},
"navigation": [
{ "key": "home", "label": "首页", "page": "home" },
{ "key": "offerings", "label": "服务", "page": "offerings" },
{ "key": "profile", "label": "关于我", "page": "profile" }
{
"key": "home",
"label": "首页",
"page": "home"
},
{
"key": "offerings",
"label": "服务",
"page": "offerings"
},
{
"key": "profile",
"label": "关于我",
"page": "profile"
}
],
"requiredCapabilities": ["offerings", "inquiry"],
"pages": ["pages/index/index", "pages/services/index", "pages/profile/index"],
+43
View File
@@ -133,11 +133,24 @@ export type TemplateSampleContent = {
capabilityKey: string;
};
export type TemplateVisualPresentation = {
description: string;
variants: Record<string, string>;
theme: { colors: Record<string, string>; radius: Record<string, string> };
layout?: {
home: string[];
offerings: string[];
detail: string[];
profile: string[];
};
};
export type TemplatePackageManifest = {
packageKey: string;
version: string;
displayName: string;
visualTemplateKey: string;
visualPresentation: TemplateVisualPresentation;
runtimeContract: typeof TEMPLATE_RUNTIME_CONTRACT;
supportedIndustryTemplates: string[];
entrypoints: Record<string, string>;
@@ -179,6 +192,36 @@ export function validateTemplatePackageManifest(value: unknown): string[] {
if (manifest.runtimeContract !== TEMPLATE_RUNTIME_CONTRACT)
errors.push(`runtimeContract must be ${TEMPLATE_RUNTIME_CONTRACT}`);
if (!manifest.displayName?.trim()) errors.push("displayName is required");
const presentation = manifest.visualPresentation;
if (
!presentation ||
typeof presentation !== "object" ||
!presentation.description?.trim() ||
!presentation.variants ||
typeof presentation.variants !== "object" ||
Array.isArray(presentation.variants) ||
!Object.values(presentation.variants).every(
(variant) => typeof variant === "string" && variant.trim(),
) ||
!presentation.theme ||
typeof presentation.theme !== "object" ||
!presentation.theme.colors ||
typeof presentation.theme.colors !== "object" ||
!presentation.theme.radius ||
typeof presentation.theme.radius !== "object"
) {
errors.push("visualPresentation requires description, variants, theme.colors and theme.radius");
} else if (presentation.layout) {
const layout = presentation.layout;
if (
!(["home", "offerings", "detail", "profile"] as const).every(
(page) =>
Array.isArray(layout[page]) && layout[page].every((item) => typeof item === "string"),
)
) {
errors.push("visualPresentation.layout must contain page module arrays");
}
}
if (
!Array.isArray(manifest.supportedIndustryTemplates) ||
!manifest.supportedIndustryTemplates.length
@@ -74,6 +74,23 @@ test("template contract rejects technical or incomplete admin declarations", ()
]);
});
test("template package manifests must declare package-owned visual presentation", () => {
const manifestPath = path.join(packageRoot, "template-acheng-campus-food/template.json");
const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf8"));
delete manifest.visualPresentation;
assert.deepEqual(validateTemplatePackageManifest(manifest), [
"visualPresentation requires description, variants, theme.colors and theme.radius",
]);
manifest.visualPresentation = {
description: "无效视觉",
variants: { hero: "hero" },
theme: { colors: { background: "#fff" }, radius: { card: "16rpx" } },
layout: { home: ["hero"], offerings: [], detail: [], profile: [] },
};
assert.deepEqual(validateTemplatePackageManifest(manifest), []);
});
test("template admin sections must point to a declared Mini Program page", () => {
const manifestPath = path.join(packageRoot, "template-acheng-campus-food/template.json");
const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf8"));
@@ -1,6 +1,6 @@
{
"name": "@personal-brand/template-linjing-editorial",
"version": "1.0.5",
"version": "1.0.6",
"private": true,
"type": "module",
"files": [
@@ -101,7 +101,8 @@ function Home({ workspace }: { workspace: RuntimeWorkspace }) {
{p.worksAction}
</Text>
</View>
{workspace.offerings.map(offering).map((item) => (
{workspace.offerings.length ? (
workspace.offerings.map(offering).map((item) => (
<View
className="work-card"
key={item.id}
@@ -120,7 +121,13 @@ function Home({ workspace }: { workspace: RuntimeWorkspace }) {
</Text>
</View>
</View>
))}
))
) : (
<View className="runtime-state">
作品与服务正在整理中
<Button onClick={() => navigate("inquiry")}>联系我们</Button>
</View>
)}
</View>
<View className="flow" data-editor-target="editorial.home.flow">
<Text className="flow-eyebrow">{p.flowEyebrow}</Text>
@@ -256,7 +263,8 @@ function List({ workspace }: { workspace: RuntimeWorkspace }) {
<Text className="eyebrow">{p.worksEyebrow}</Text>
<Text className="section-title">{p.worksTitle || "作品与服务"}</Text>
<Text className="subtitle">{p.subtitle}</Text>
{workspace.offerings.map(offering).map((item) => (
{workspace.offerings.length ? (
workspace.offerings.map(offering).map((item) => (
<View
className="work-card"
key={item.id}
@@ -277,7 +285,13 @@ function List({ workspace }: { workspace: RuntimeWorkspace }) {
</Text>
</View>
</View>
))}
))
) : (
<View className="runtime-state">
作品与服务正在整理中
<Button onClick={() => navigate("inquiry")}>联系我们</Button>
</View>
)}
<Text className="subtitle">{p.closingText}</Text>
{p.closingAction &&
(inquiryPluginState(workspace).enabled ? (
@@ -1,6 +1,6 @@
{
"packageKey": "linjing-editorial",
"version": "1.0.5",
"version": "1.0.6",
"displayName": "林境建筑画册",
"defaultBrandSlug": "linjing-doors",
"runtimeContract": "1.0",
@@ -1894,6 +1894,31 @@
},
"pages": ["pages/index/index", "pages/services/index", "pages/bookings/index"],
"visualTemplateKey": "linjing-editorial",
"visualPresentation": {
"description": "适合高端定制、建筑作品和项目型个人品牌。",
"variants": {
"hero": "architectural",
"offeringList": "editorial",
"detail": "project-case"
},
"theme": {
"colors": {
"background": "#F7F5F1",
"foreground": "#252525",
"accent": "#8A6846",
"dark": "#202221"
},
"radius": {
"card": "16rpx"
}
},
"layout": {
"home": ["founder-card", "brand-hero", "trust-proof", "trust-manifesto", "offering-list"],
"offerings": ["offering-list"],
"detail": ["offering-detail"],
"profile": ["profile"]
}
},
"previewFixture": {
"doors": {
"schemaVersion": "1",
+1763 -2164
View File
File diff suppressed because it is too large. Load diff
+68
View File
@@ -1,3 +1,6 @@
import crypto from "node:crypto";
import path from "node:path";
import fs from "node:fs";
import ts from "typescript";
// 静态检查不推断运行时成功;未知表达式保留为 review。
@@ -409,3 +412,68 @@ export function applyManualReview(reports, reviews, reviewScope) {
}
return reports;
}
export function applyCompletionEvidence(reports, registry, root) {
if (registry === undefined) {
for (const report of reports) report.completionStatus = "unverified";
return { completionStatus: "unverified", reports };
}
if (
!registry ||
registry.schemaVersion !== 1 ||
registry.scope !== "模板完成证据登记,保留命令、日志与产物哈希" ||
!registry.templates ||
typeof registry.templates !== "object" ||
Array.isArray(registry.templates)
) {
throw new Error("Completion evidence registry has an unsupported schema");
}
const expectedTemplates = new Set(reports.map((report) => report.template));
const registeredTemplates = new Set(Object.keys(registry.templates));
const rootPath = path.resolve(root);
const insideRoot = (value) => {
const resolved = path.resolve(rootPath, value);
if (resolved !== rootPath && !resolved.startsWith(rootPath + path.sep)) return null;
return resolved;
};
const validEvidence = (evidence) => {
if (!evidence || evidence.status !== "passed" || !Array.isArray(evidence.commands)) return null;
if (!evidence.commands.length || evidence.commands.some((command) => !command.trim()))
return null;
if (!Array.isArray(evidence.artifacts) || !evidence.artifacts.length) return null;
return evidence;
};
let complete = true;
for (const report of reports) {
const evidence = registry.templates[report.template] ?? {};
const completionIssues = [];
for (const key of report.requiredEvidence) {
const item = validEvidence(evidence[key]);
if (!item) {
completionIssues.push(`${key}: missing or invalid passed evidence`);
continue;
}
for (const artifact of item.artifacts) {
if (!artifact?.path || !/^[a-f0-9]{64}$/.test(artifact.sha256 ?? "")) {
completionIssues.push(`${key}: artifact path or sha256 is invalid`);
continue;
}
const filePath = insideRoot(artifact.path);
if (!filePath || !fs.existsSync(filePath) || !fs.statSync(filePath).isFile()) {
completionIssues.push(`${key}: artifact does not exist: ${artifact.path}`);
continue;
}
const hash = crypto.createHash("sha256").update(fs.readFileSync(filePath)).digest("hex");
if (hash !== artifact.sha256)
completionIssues.push(`${key}: artifact checksum mismatch: ${artifact.path}`);
}
}
report.evidence = evidence;
report.completionIssues = completionIssues;
report.completionStatus = completionIssues.length ? "incomplete" : "complete";
if (completionIssues.length) complete = false;
}
return { completionStatus: complete ? "complete" : "incomplete", reports };
}
+4 -4
View File
@@ -8,7 +8,6 @@ const root = path.resolve(__dirname, "..");
const packagesRoot = path.join(root, "packages");
const configRoot = path.join(packagesRoot, "config/src");
const industrySource = fs.readFileSync(path.join(configRoot, "brand-templates.ts"), "utf8");
const visualSource = fs.readFileSync(path.join(configRoot, "visual-templates.ts"), "utf8");
const capabilitySource = fs.readFileSync(path.join(configRoot, "capability-contracts.ts"), "utf8");
const platformPackage = JSON.parse(
fs.readFileSync(path.join(root, "apps/taro/package.json"), "utf8"),
@@ -57,10 +56,8 @@ function stringArray(expression) {
: [];
}
const brandTemplateObject = exportedObject(industrySource, "brandTemplates");
const visualTemplateObject = exportedObject(visualSource, "visualTemplates");
const capabilityObject = exportedObject(capabilitySource, "capabilityRegistry");
const industries = objectKeys(brandTemplateObject);
const visualKeys = objectKeys(visualTemplateObject);
const capabilityKeys = objectKeys(capabilityObject);
const industryCapabilities = Object.fromEntries(
(ts.isObjectLiteralExpression(brandTemplateObject) ? brandTemplateObject.properties : [])
@@ -91,6 +88,9 @@ const packages = fs
}))
.sort((left, right) => left.manifest.packageKey.localeCompare(right.manifest.packageKey));
const visualKeys = [
...new Set(packages.map((item) => item.manifest.visualTemplateKey).filter(Boolean)),
];
const results = [];
const errors = [];
const versionMajorMinor = (value) =>
@@ -110,7 +110,7 @@ for (const { directory, manifest, package: packageMetadata } of packages) {
? manifest.supportedIndustryTemplates
: [];
const visualKey = manifest.visualTemplateKey;
const visualRegistered = typeof visualKey === "string" && visualKeys.includes(visualKey);
const visualRegistered = visualKey === key && visualKeys.includes(visualKey);
const rendererPath = `${directory}/taro/index.tsx`;
const rendererExists = fs.existsSync(path.join(packagesRoot, rendererPath));
const rendererExport = rendererExists
+23 -3
View File
@@ -1,7 +1,11 @@
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { applyManualReview, diagnoseTemplate } from "./lib/template-doctor.mjs";
import {
applyCompletionEvidence,
applyManualReview,
diagnoseTemplate,
} from "./lib/template-doctor.mjs";
try {
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
@@ -31,14 +35,30 @@ try {
);
const registry = JSON.parse(fs.readFileSync(registryPath, "utf8"));
applyManualReview(reports, registry.items, registry.scope);
const report = { schemaVersion: 1, completionStatus: "unverified", templates: reports };
const evidencePath = path.join(
root,
".codex-tasks/template-audit-execution/raw/completion-evidence.json",
);
const evidence = fs.existsSync(evidencePath)
? JSON.parse(fs.readFileSync(evidencePath, "utf8"))
: undefined;
const completion = applyCompletionEvidence(reports, evidence, root);
const report = {
schemaVersion: 1,
completionStatus: completion.completionStatus,
templates: reports,
};
const output = JSON.stringify(report, null, 2) + "\n";
if (options["--output"]) {
fs.mkdirSync(path.dirname(path.resolve(options["--output"])), { recursive: true });
fs.writeFileSync(options["--output"], output);
}
process.stdout.write(output);
process.exitCode = reports.some((r) => r.staticStatus === "fail") ? 1 : 0;
process.exitCode = reports.some(
(r) => r.staticStatus === "fail" || r.completionStatus === "incomplete",
)
? 1
: 0;
} catch (error) {
console.error(error.message);
process.exitCode = 2;
+65 -1
View File
@@ -1,8 +1,15 @@
import assert from "node:assert/strict";
import test from "node:test";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { createHash } from "node:crypto";
import { spawnSync } from "node:child_process";
import { applyManualReview, diagnoseTemplate } from "../lib/template-doctor.mjs";
import {
applyCompletionEvidence,
applyManualReview,
diagnoseTemplate,
} from "../lib/template-doctor.mjs";
test("真实模板自动发现并读取完整声明,生成可追溯区域报告", () => {
const root = new URL("../../packages/", import.meta.url);
@@ -70,6 +77,63 @@ test("CLI 自动发现全部模板,问题退出 1,未知模板退出 2", ()
assert.equal(missing.status, 2);
});
test("完成证据登记必须覆盖全部要求并校验产物哈希", () => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), "template-doctor-evidence-"));
const artifactPath = path.join(root, "integration.log");
fs.writeFileSync(artifactPath, "passed\n");
const sha256 = createHash("sha256").update(fs.readFileSync(artifactPath)).digest("hex");
const report = {
template: "fixture",
staticStatus: "pass",
completionStatus: "unverified",
requiredEvidence: ["real-manifest-interaction", "visual-reference"],
};
const evidence = (items) => ({
schemaVersion: 1,
scope: "模板完成证据登记,保留命令、日志与产物哈希",
templates: {
fixture: Object.fromEntries(
report.requiredEvidence.map((key) => [
key,
items.includes(key)
? {
status: "passed",
commands: ["pnpm test"],
artifacts: [{ path: "integration.log", sha256 }],
}
: undefined,
]),
),
},
});
try {
const complete = applyCompletionEvidence(
[structuredClone(report)],
evidence(report.requiredEvidence),
root,
);
assert.equal(complete.completionStatus, "complete");
assert.equal(complete.reports[0].completionStatus, "complete");
const incomplete = applyCompletionEvidence(
[structuredClone(report)],
evidence(["real-manifest-interaction"]),
root,
);
assert.equal(incomplete.completionStatus, "incomplete");
assert.match(incomplete.reports[0].completionIssues.join("\n"), /visual-reference/);
const invalid = evidence(report.requiredEvidence);
invalid.templates.fixture["visual-reference"].artifacts[0].sha256 = "0".repeat(64);
const checksumMismatch = applyCompletionEvidence([structuredClone(report)], invalid, root);
assert.equal(checksumMismatch.completionStatus, "incomplete");
assert.match(checksumMismatch.reports[0].completionIssues.join("\n"), /checksum mismatch/);
} finally {
fs.rmSync(root, { recursive: true, force: true });
}
});
test("人工审阅登记只能匹配真实 review,新问题仍会失败", () => {
const report = {
template: "fixture",