Compare commits
44
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1e1d4d0326 | ||
|
|
92227e1311 | ||
|
|
e75c524343 | ||
|
|
1a4f71996a | ||
|
|
a2fa6c3c31 | ||
|
|
015947f8fb | ||
|
|
072a1037ac | ||
|
|
447c224fce | ||
|
|
f2fc1e0810 | ||
|
|
12a3bf2f3b | ||
|
|
ca6d1712bd | ||
|
|
e7ef0b3ce5 | ||
|
|
b82aa12875 | ||
|
|
b43b6f2785 | ||
|
|
965dd10219 | ||
|
|
371689484e | ||
|
|
d923b8cea9 | ||
|
|
a1b29cedee | ||
|
|
34504c0b44 | ||
|
|
3af5611da5 | ||
|
|
2fe108d66a | ||
|
|
4cd3749806 | ||
|
|
00aeaa3cb1 | ||
|
|
b190f2758a | ||
|
|
4d9c84defc | ||
|
|
b4e3e86dcd | ||
|
|
5051839986 | ||
|
|
84522a8908 | ||
|
|
18bcdbeb00 | ||
|
|
040504774d | ||
|
|
1001c43af6 | ||
|
|
121148f6cf | ||
|
|
a08a2f0f98 | ||
|
|
669d4a7de6 | ||
|
|
ec0cf78d69 | ||
|
|
658c94a4e9 | ||
|
|
261a33a5ca | ||
|
|
f28332f49a | ||
|
|
c33c9cbd63 | ||
|
|
b742fc70b5 | ||
|
|
6bd91d5ee8 | ||
|
|
cdc7b407bc | ||
|
|
9bfa4bb736 | ||
|
|
c04ab1ef60 |
No files matched your search
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"schemaVersion": 1,
|
"schemaVersion": 1,
|
||||||
"scope": "模板完成证据登记,保留命令、日志与产物哈希",
|
"scope": "模板完成证据登记,保留命令、日志与产物哈希",
|
||||||
"generatedAt": "2026-10-21T04:17:12.186Z",
|
"generatedAt": "2026-10-23T11:27:49.824Z",
|
||||||
"templates": {
|
"templates": {
|
||||||
"acheng-campus-food": {
|
"acheng-campus-food": {
|
||||||
"real-manifest-interaction": {
|
"real-manifest-interaction": {
|
||||||
@@ -256,5 +256,5 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"sourceTreeHash": "4331e0ff7919e4cc1d44de321c1c1d47e7f1858098d575dea7b21553aaeba284"
|
"sourceTreeHash": "1dbd5f3a24cc1f86925b4bcd05c99b45cc00d6a39dabe2302ad07ba7f763c79c"
|
||||||
}
|
}
|
||||||
@@ -9,6 +9,8 @@ API_PREFIX=
|
|||||||
CORS_ORIGINS=http://localhost:3000
|
CORS_ORIGINS=http://localhost:3000
|
||||||
ADMIN_PORT=3000
|
ADMIN_PORT=3000
|
||||||
SESSION_SECRET=replace-with-a-long-random-value
|
SESSION_SECRET=replace-with-a-long-random-value
|
||||||
|
# 单实例使用 memory;多实例部署改用 postgres 并先执行数据库迁移
|
||||||
|
CLIENT_ERROR_THROTTLE_STORE=memory
|
||||||
DEFAULT_BRAND_ID=00000000-0000-0000-0000-000000000001
|
DEFAULT_BRAND_ID=00000000-0000-0000-0000-000000000001
|
||||||
TEMPLATE_ARTIFACT_ROOT=/var/lib/personal-brand/template-artifacts
|
TEMPLATE_ARTIFACT_ROOT=/var/lib/personal-brand/template-artifacts
|
||||||
SEED_ADMIN_PASSWORD=change-me-now-123
|
SEED_ADMIN_PASSWORD=change-me-now-123
|
||||||
|
|||||||
@@ -6,6 +6,8 @@ POSTGRES_PORT=5432
|
|||||||
|
|
||||||
DATABASE_URL=postgresql://personal_brand:replace-with-a-long-database-password@127.0.0.1:5432/personal_brand?schema=public
|
DATABASE_URL=postgresql://personal_brand:replace-with-a-long-database-password@127.0.0.1:5432/personal_brand?schema=public
|
||||||
SESSION_SECRET=replace-with-at-least-32-random-characters
|
SESSION_SECRET=replace-with-at-least-32-random-characters
|
||||||
|
# 单实例使用 memory;多实例部署改用 postgres 并先执行数据库迁移
|
||||||
|
CLIENT_ERROR_THROTTLE_STORE=memory
|
||||||
DEFAULT_BRAND_ID=00000000-0000-0000-0000-000000000001
|
DEFAULT_BRAND_ID=00000000-0000-0000-0000-000000000001
|
||||||
SEED_ADMIN_PASSWORD=replace-with-a-one-time-initial-password
|
SEED_ADMIN_PASSWORD=replace-with-a-one-time-initial-password
|
||||||
SEED_MODE=skip
|
SEED_MODE=skip
|
||||||
@@ -14,6 +16,12 @@ API_PORT=3001
|
|||||||
API_PREFIX=
|
API_PREFIX=
|
||||||
CORS_ORIGINS=
|
CORS_ORIGINS=
|
||||||
|
|
||||||
|
# 发布备份保留 7 份;定时备份默认保留 14 天
|
||||||
|
BACKUP_RETENTION_DAYS=14
|
||||||
|
# 可选:配置 rsync 目标后,每次定时备份会额外复制一份到异地
|
||||||
|
# 需要预先为 ubuntu 用户配置 SSH key;未配置时备份只保留在本机
|
||||||
|
# BACKUP_OFFSITE_TARGET=backup@example-host:/srv/personal-brand-backups/
|
||||||
|
|
||||||
LOCAL_MEDIA_ROOT=/home/ubuntu/persional-brand/media
|
LOCAL_MEDIA_ROOT=/home/ubuntu/persional-brand/media
|
||||||
LOCAL_MEDIA_BASE_URL=/media
|
LOCAL_MEDIA_BASE_URL=/media
|
||||||
OBJECT_STORAGE_ENDPOINT=
|
OBJECT_STORAGE_ENDPOINT=
|
||||||
@@ -23,6 +31,8 @@ OBJECT_STORAGE_ACCESS_KEY=
|
|||||||
OBJECT_STORAGE_SECRET_KEY=
|
OBJECT_STORAGE_SECRET_KEY=
|
||||||
OBJECT_STORAGE_REGION=us-east-1
|
OBJECT_STORAGE_REGION=us-east-1
|
||||||
|
|
||||||
|
# 访客微信登录配置,与后台「小程序上传配置」相互独立:
|
||||||
|
# AppID 必须与上传配置一致;AppSecret 只放在服务器环境变量中
|
||||||
WECHAT_APP_ID=
|
WECHAT_APP_ID=
|
||||||
WECHAT_APP_SECRET=
|
WECHAT_APP_SECRET=
|
||||||
|
|
||||||
|
|||||||
+96
-17
@@ -3,7 +3,13 @@ name: CI
|
|||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
branches: [main]
|
branches: [main]
|
||||||
|
# 纯文档提交不占用 runner;需要状态时用 workflow_dispatch 手动触发。
|
||||||
|
paths-ignore:
|
||||||
|
- "**.md"
|
||||||
|
# PR 不设置 paths-ignore:branch protection 的 required checks 必须始终上报,
|
||||||
|
# 否则纯文档 PR 会永远等不到状态检查而无法合并。
|
||||||
pull_request:
|
pull_request:
|
||||||
|
workflow_dispatch:
|
||||||
|
|
||||||
concurrency:
|
concurrency:
|
||||||
group: ci-${{ github.ref }}
|
group: ci-${{ github.ref }}
|
||||||
@@ -12,6 +18,8 @@ concurrency:
|
|||||||
env:
|
env:
|
||||||
NODE_VERSION: "24"
|
NODE_VERSION: "24"
|
||||||
PNPM_VERSION: "9.15.0"
|
PNPM_VERSION: "9.15.0"
|
||||||
|
# runner 任务容器把该路径 bind mount 到宿主机共享 store,避免每个 job 重复下载依赖。
|
||||||
|
npm_config_store_dir: /workspace/.pnpm-store
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
static:
|
static:
|
||||||
@@ -20,16 +28,32 @@ jobs:
|
|||||||
timeout-minutes: 40
|
timeout-minutes: 40
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
- uses: pnpm/action-setup@v4
|
- name: Verify preinstalled toolchain
|
||||||
|
# 任务镜像已内置 Node 与 pnpm;不在这里下载 Node,避免 nodejs.org 慢连接拖死整个 job。
|
||||||
|
run: |
|
||||||
|
actual_node="$(node -p 'process.versions.node')"
|
||||||
|
actual_pnpm="$(pnpm --version)"
|
||||||
|
test "${actual_node%%.*}" = "$NODE_VERSION" || { echo "expected Node $NODE_VERSION.x, got $actual_node" >&2; exit 1; }
|
||||||
|
test "$actual_pnpm" = "$PNPM_VERSION" || { echo "expected pnpm $PNPM_VERSION, got $actual_pnpm" >&2; exit 1; }
|
||||||
|
- name: Restore Prisma engine cache
|
||||||
|
uses: actions/cache@v4
|
||||||
with:
|
with:
|
||||||
version: ${{ env.PNPM_VERSION }}
|
path: ~/.cache/prisma
|
||||||
- uses: actions/setup-node@v4
|
key: prisma-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('pnpm-lock.yaml') }}
|
||||||
|
restore-keys: |
|
||||||
|
prisma-${{ runner.os }}-${{ runner.arch }}-
|
||||||
|
- name: Restore Turbo cache
|
||||||
|
uses: actions/cache@v4
|
||||||
with:
|
with:
|
||||||
node-version: ${{ env.NODE_VERSION }}
|
path: .turbo/cache
|
||||||
cache: pnpm
|
key: turbo-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('pnpm-lock.yaml') }}-${{ github.sha }}
|
||||||
|
restore-keys: |
|
||||||
|
turbo-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('pnpm-lock.yaml') }}-
|
||||||
|
turbo-${{ runner.os }}-${{ runner.arch }}-
|
||||||
- run: pnpm install --frozen-lockfile
|
- run: pnpm install --frozen-lockfile
|
||||||
- run: pnpm check
|
- run: pnpm check
|
||||||
- run: pnpm test:api-routes
|
- run: pnpm test:api-routes
|
||||||
|
- run: pnpm test:deploy
|
||||||
- run: pnpm validate:templates
|
- run: pnpm validate:templates
|
||||||
- run: pnpm template:compatibility
|
- run: pnpm template:compatibility
|
||||||
- run: pnpm --filter @personal-brand/api exec tsx --test test/template-preview-matrix.test.ts
|
- run: pnpm --filter @personal-brand/api exec tsx --test test/template-preview-matrix.test.ts
|
||||||
@@ -43,23 +67,71 @@ jobs:
|
|||||||
needs: [static]
|
needs: [static]
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
- uses: pnpm/action-setup@v4
|
- name: Verify preinstalled toolchain
|
||||||
|
# 任务镜像已内置 Node 与 pnpm;不在这里下载 Node,避免 nodejs.org 慢连接拖死整个 job。
|
||||||
|
run: |
|
||||||
|
actual_node="$(node -p 'process.versions.node')"
|
||||||
|
actual_pnpm="$(pnpm --version)"
|
||||||
|
test "${actual_node%%.*}" = "$NODE_VERSION" || { echo "expected Node $NODE_VERSION.x, got $actual_node" >&2; exit 1; }
|
||||||
|
test "$actual_pnpm" = "$PNPM_VERSION" || { echo "expected pnpm $PNPM_VERSION, got $actual_pnpm" >&2; exit 1; }
|
||||||
|
- name: Restore Prisma engine cache
|
||||||
|
uses: actions/cache@v4
|
||||||
with:
|
with:
|
||||||
version: ${{ env.PNPM_VERSION }}
|
path: ~/.cache/prisma
|
||||||
- uses: actions/setup-node@v4
|
key: prisma-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('pnpm-lock.yaml') }}
|
||||||
|
restore-keys: |
|
||||||
|
prisma-${{ runner.os }}-${{ runner.arch }}-
|
||||||
|
- name: Restore Turbo cache
|
||||||
|
uses: actions/cache@v4
|
||||||
with:
|
with:
|
||||||
node-version: ${{ env.NODE_VERSION }}
|
path: .turbo/cache
|
||||||
cache: pnpm
|
key: turbo-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('pnpm-lock.yaml') }}-${{ github.sha }}
|
||||||
|
restore-keys: |
|
||||||
|
turbo-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('pnpm-lock.yaml') }}-
|
||||||
|
turbo-${{ runner.os }}-${{ runner.arch }}-
|
||||||
- run: pnpm install --frozen-lockfile
|
- run: pnpm install --frozen-lockfile
|
||||||
- run: pnpm build
|
- run: pnpm build
|
||||||
- run: pnpm build:admin:preview
|
- run: pnpm build:admin:preview
|
||||||
- run: pnpm validate:template-release
|
- run: pnpm validate:template-release
|
||||||
|
|
||||||
|
browser-smoke:
|
||||||
|
name: Browser smoke
|
||||||
|
# 只在 PR 和手动触发时运行,避免 main 合并后重复消耗共享生产 runner。
|
||||||
|
if: github.event_name == 'pull_request' || github.event_name == 'workflow_dispatch'
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
timeout-minutes: 30
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- name: Verify preinstalled toolchain
|
||||||
|
# 任务镜像已内置 Node 与 pnpm;不在这里下载 Node,避免 nodejs.org 慢连接拖死整个 job。
|
||||||
|
run: |
|
||||||
|
actual_node="$(node -p 'process.versions.node')"
|
||||||
|
actual_pnpm="$(pnpm --version)"
|
||||||
|
test "${actual_node%%.*}" = "$NODE_VERSION" || { echo "expected Node $NODE_VERSION.x, got $actual_node" >&2; exit 1; }
|
||||||
|
test "$actual_pnpm" = "$PNPM_VERSION" || { echo "expected pnpm $PNPM_VERSION, got $actual_pnpm" >&2; exit 1; }
|
||||||
|
- name: Restore Prisma engine cache
|
||||||
|
uses: actions/cache@v4
|
||||||
|
with:
|
||||||
|
path: ~/.cache/prisma
|
||||||
|
key: prisma-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('pnpm-lock.yaml') }}
|
||||||
|
restore-keys: |
|
||||||
|
prisma-${{ runner.os }}-${{ runner.arch }}-
|
||||||
|
- run: pnpm install --frozen-lockfile
|
||||||
|
- name: Cache Playwright browsers
|
||||||
|
uses: actions/cache@v4
|
||||||
|
with:
|
||||||
|
path: ~/.cache/ms-playwright
|
||||||
|
key: playwright-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('pnpm-lock.yaml') }}
|
||||||
|
- name: Install Chromium
|
||||||
|
# 系统依赖与同版本 Chromium 已预装在 personal-brand-ci:node24 中;这里只做版本兜底。
|
||||||
|
run: pnpm --filter @personal-brand/taro exec playwright install chromium
|
||||||
|
- name: Run PR browser smoke
|
||||||
|
run: pnpm test:browser:smoke
|
||||||
|
|
||||||
api:
|
api:
|
||||||
name: API integration
|
name: API integration
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
timeout-minutes: 45
|
timeout-minutes: 45
|
||||||
needs: [static]
|
|
||||||
services:
|
services:
|
||||||
postgres:
|
postgres:
|
||||||
image: postgres:16-alpine
|
image: postgres:16-alpine
|
||||||
@@ -79,13 +151,20 @@ jobs:
|
|||||||
SEED_ADMIN_PASSWORD: ci-integration-admin-password
|
SEED_ADMIN_PASSWORD: ci-integration-admin-password
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
- uses: pnpm/action-setup@v4
|
- name: Verify preinstalled toolchain
|
||||||
|
# 任务镜像已内置 Node 与 pnpm;不在这里下载 Node,避免 nodejs.org 慢连接拖死整个 job。
|
||||||
|
run: |
|
||||||
|
actual_node="$(node -p 'process.versions.node')"
|
||||||
|
actual_pnpm="$(pnpm --version)"
|
||||||
|
test "${actual_node%%.*}" = "$NODE_VERSION" || { echo "expected Node $NODE_VERSION.x, got $actual_node" >&2; exit 1; }
|
||||||
|
test "$actual_pnpm" = "$PNPM_VERSION" || { echo "expected pnpm $PNPM_VERSION, got $actual_pnpm" >&2; exit 1; }
|
||||||
|
- name: Restore Prisma engine cache
|
||||||
|
uses: actions/cache@v4
|
||||||
with:
|
with:
|
||||||
version: ${{ env.PNPM_VERSION }}
|
path: ~/.cache/prisma
|
||||||
- uses: actions/setup-node@v4
|
key: prisma-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('pnpm-lock.yaml') }}
|
||||||
with:
|
restore-keys: |
|
||||||
node-version: ${{ env.NODE_VERSION }}
|
prisma-${{ runner.os }}-${{ runner.arch }}-
|
||||||
cache: pnpm
|
|
||||||
- run: pnpm install --frozen-lockfile
|
- run: pnpm install --frozen-lockfile
|
||||||
- name: Prepare API test env
|
- name: Prepare API test env
|
||||||
working-directory: apps/api
|
working-directory: apps/api
|
||||||
|
|||||||
Executable
+6
@@ -0,0 +1,6 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
# 提交前让模板完成证据的源码哈希跟随当前工作树,避免额外的 chore 提交。
|
||||||
|
set -e
|
||||||
|
[ -f scripts/template-evidence-refresh.mjs ] || exit 0
|
||||||
|
command -v node >/dev/null 2>&1 || exit 0
|
||||||
|
node scripts/template-evidence-refresh.mjs --stage
|
||||||
@@ -24,6 +24,9 @@ media/
|
|||||||
|
|
||||||
**/.swc/
|
**/.swc/
|
||||||
.codex-tasks/
|
.codex-tasks/
|
||||||
|
!.codex-tasks/template-audit-execution/
|
||||||
|
!.codex-tasks/template-audit-execution/raw/
|
||||||
|
!.codex-tasks/template-audit-execution/raw/completion-evidence.json
|
||||||
docker-compose.override.yml
|
docker-compose.override.yml
|
||||||
.env.production
|
.env.production
|
||||||
|
|
||||||
|
|||||||
+8
-3
@@ -27,6 +27,7 @@ ADR 0033 已落地:
|
|||||||
- Taro Runtime、Admin 组件预览、真实 manifest 驱动编辑、草稿/发布隔离。
|
- Taro Runtime、Admin 组件预览、真实 manifest 驱动编辑、草稿/发布隔离。
|
||||||
- 发布备注为可选字段;空备注不会写入数据库,也不影响发布、回滚和公开内容。
|
- 发布备注为可选字段;空备注不会写入数据库,也不影响发布、回滚和公开内容。
|
||||||
- 依赖 override 的运行时兼容性通过 `miniprogram-ci` / Jimp / image-size / uuid smoke test 守卫。
|
- 依赖 override 的运行时兼容性通过 `miniprogram-ci` / Jimp / image-size / uuid smoke test 守卫。
|
||||||
|
- Gitea Actions CI 已在 `oracle_arm` 自托管 runner 上落地,`static` / `build` / `api` 三个 job 已完整通过(run 21);详见 `docs/ci.md`。
|
||||||
- 小程序构建、上传任务状态机、attempt lease 和失败记录。
|
- 小程序构建、上传任务状态机、attempt lease 和失败记录。
|
||||||
- Admin/Customer token version:修改 admin 密码或调用 logout 后旧 token 立即失效;无 membership 的账号不会自动获得 owner 权限。
|
- Admin/Customer token version:修改 admin 密码或调用 logout 后旧 token 立即失效;无 membership 的账号不会自动获得 owner 权限。
|
||||||
- `visualPresentation` 已进入唯一 `template.json` 契约,旧手写 visual manifest 优先路径已删除。
|
- `visualPresentation` 已进入唯一 `template.json` 契约,旧手写 visual manifest 优先路径已删除。
|
||||||
@@ -36,10 +37,10 @@ ADR 0033 已落地:
|
|||||||
当前生产 release:
|
当前生产 release:
|
||||||
|
|
||||||
```text
|
```text
|
||||||
20261021034700-adcaa12970af
|
20261023100112-a2fa6c3c3140
|
||||||
```
|
```
|
||||||
|
|
||||||
该 release 由提交 `adcaa12` 构建,包含后台渲染异常上报(`POST /admin/client-errors`,含去重与限流)、Admin 列表接口运行时响应契约校验,以及前序 release 的创建品牌与页面方案交互修复、Admin 渲染错误边界和异常数据容忍。部署后已完成公开路由健康检查,并确认未登录调用异常上报接口返回 `401 HTTP_401`,说明新接口已进入生产路由。
|
该 release 由提交 `a2fa6c3` 构建,新增生产数据库每日定时备份、备份可读性校验、发布/定时备份保留策略、`backup-timer` 与 `backup-age-hours` 部署状态门禁。部署后已手动触发一次 `personal-brand-backup.service`,生成 `scheduled-20261023T100426Z-1029929.dump`,并通过 `pg_restore -l` 校验可读。
|
||||||
|
|
||||||
生产健康检查:
|
生产健康检查:
|
||||||
|
|
||||||
@@ -48,7 +49,11 @@ api=online
|
|||||||
pm2-autostart=enabled
|
pm2-autostart=enabled
|
||||||
admin=active
|
admin=active
|
||||||
database=running
|
database=running
|
||||||
backups=7
|
backups=8
|
||||||
|
latest-backup=2026-10-23 10:04:27 +0000 scheduled-20261023T100426Z-1029929.dump
|
||||||
|
backup-timer=active
|
||||||
|
backup-age-hours=0
|
||||||
|
backup-temp-files=0
|
||||||
/admin/ 200
|
/admin/ 200
|
||||||
/template-preview/ 200
|
/template-preview/ 200
|
||||||
/api/health 200
|
/api/health 200
|
||||||
|
|||||||
@@ -28,8 +28,9 @@ export function InquiryPreviewEditor({
|
|||||||
const record = query.data?.find((item) => item.id === runtime.key);
|
const record = query.data?.find((item) => item.id === runtime.key);
|
||||||
const field = runtime.fields.find((item) => item.key === fieldKey);
|
const field = runtime.fields.find((item) => item.key === fieldKey);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (field) form.setFieldsValue({ ...field });
|
if (!record || !field) return;
|
||||||
}, [fieldKey, runtime.key, form]);
|
form.setFieldsValue({ ...field });
|
||||||
|
}, [field, fieldKey, form, record, runtime.key]);
|
||||||
const update = (values: Record<string, unknown>) =>
|
const update = (values: Record<string, unknown>) =>
|
||||||
runtime.fields.map((item) => (item.key === fieldKey ? { ...item, ...values } : item));
|
runtime.fields.map((item) => (item.key === fieldKey ? { ...item, ...values } : item));
|
||||||
const save = useMutation({
|
const save = useMutation({
|
||||||
|
|||||||
@@ -1,34 +1,15 @@
|
|||||||
import { Alert, Button, Grid, Select, Segmented, Space, Typography } from "antd";
|
import { Alert, Grid, Segmented, Select, Space } from "antd";
|
||||||
import { useQueryClient } from "@tanstack/react-query";
|
import type {
|
||||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
AdminTemplateContent,
|
||||||
import { useNavigate } from "react-router-dom";
|
BrandProfile,
|
||||||
import type { AdminTemplateContent, RuntimeWorkspace } from "@personal-brand/api-client";
|
RuntimeWorkspace,
|
||||||
import type { BrandProfile } from "@personal-brand/api-client";
|
} from "@personal-brand/api-client";
|
||||||
import { StatusTag } from "../../components/StatusTag.js";
|
import { StatusTag } from "../../components/StatusTag.js";
|
||||||
import { RecordContentEditor } from "../../components/RecordContentEditor.js";
|
|
||||||
import { TemplatePreview } from "./TemplatePreview.js";
|
|
||||||
import { InquiryPreviewEditor } from "./InquiryPreviewEditor.js";
|
|
||||||
import {
|
|
||||||
resolvePreviewSelection,
|
|
||||||
previewTrustRecordId,
|
|
||||||
type PreviewSelection,
|
|
||||||
type PreviewTarget,
|
|
||||||
} from "./preview-selection.js";
|
|
||||||
import { filterSectionsForPreviewTarget } from "../../lib/presentation/presentation-bindings.js";
|
|
||||||
import "./PresentationEditor.css";
|
import "./PresentationEditor.css";
|
||||||
import { useEditorDraft } from "./use-editor-draft.js";
|
import type { PreviewSelection } from "./preview-selection.js";
|
||||||
import {
|
import { usePresentationEditorController } from "./presentation-editor-controller.js";
|
||||||
usePresentationRecordQueries,
|
import { PresentationEditorInspector } from "./PresentationEditorInspector.js";
|
||||||
useBrandPresentationSections,
|
import { PresentationEditorPreview } from "./PresentationEditorPreview.js";
|
||||||
useBrandSaveMutation,
|
|
||||||
useBrandPresentationForm,
|
|
||||||
useBrandPreviewDraft,
|
|
||||||
} from "./presentation-editor-state.js";
|
|
||||||
import { useRecordPreview } from "./presentation-editor-record-preview.js";
|
|
||||||
import type { RecordDraft } from "./presentation-editor-record-preview.js";
|
|
||||||
import { pageTitle, previewTargetSource, trustSection } from "./presentation-editor-helpers.js";
|
|
||||||
import { useDraftWorkspace } from "./use-draft-workspace.js";
|
|
||||||
import { PresentationFormPanel } from "./PresentationFormPanel.js";
|
|
||||||
|
|
||||||
interface PresentationEditorProps {
|
interface PresentationEditorProps {
|
||||||
templateContent: AdminTemplateContent | null | undefined;
|
templateContent: AdminTemplateContent | null | undefined;
|
||||||
@@ -49,254 +30,14 @@ export function PresentationEditor({
|
|||||||
error,
|
error,
|
||||||
initialSelection,
|
initialSelection,
|
||||||
}: PresentationEditorProps) {
|
}: PresentationEditorProps) {
|
||||||
const queryClient = useQueryClient();
|
|
||||||
const navigate = useNavigate();
|
|
||||||
const breakpoints = Grid.useBreakpoint();
|
const breakpoints = Grid.useBreakpoint();
|
||||||
const [activePage, setActivePage] = useState<string>();
|
const controller = usePresentationEditorController({
|
||||||
const [selection, setSelection] = useState<PreviewSelection | undefined>(initialSelection);
|
|
||||||
const [hasInitializedSelection, setHasInitializedSelection] = useState(Boolean(initialSelection));
|
|
||||||
const [detailOfferingId, setDetailOfferingId] = useState<string>();
|
|
||||||
const [recordDraft, setRecordDraft] = useState<RecordDraft>();
|
|
||||||
const [inquiryDraft, setInquiryDraft] =
|
|
||||||
useState<RuntimeWorkspace["inquiryForms"][number]["fields"]>();
|
|
||||||
const [brandDirty, setBrandDirty] = useState(false);
|
|
||||||
const guardDraft = useEditorDraft(brandDirty || !!recordDraft || !!inquiryDraft);
|
|
||||||
const inquiryRuntime = previewWorkspace?.inquiryForms.find((item) => item.target === "brand");
|
|
||||||
const sections = useBrandPresentationSections(templateContent);
|
|
||||||
const pageOptions = useMemo(() => {
|
|
||||||
const pages = new Map<string, string>();
|
|
||||||
for (const item of templateContent?.navigation ?? []) pages.set(item.page, item.label);
|
|
||||||
for (const section of templateContent?.admin.sections ?? []) {
|
|
||||||
const navigation = templateContent?.navigation.find((item) => item.page === section.page);
|
|
||||||
if (!pages.has(section.page))
|
|
||||||
pages.set(section.page, navigation?.label ?? pageTitle(section.page));
|
|
||||||
}
|
|
||||||
return [...pages].map(([value, label]) => ({ value, label }));
|
|
||||||
}, [templateContent]);
|
|
||||||
const selectedPage = pageOptions.some((item) => item.value === activePage)
|
|
||||||
? activePage
|
|
||||||
: pageOptions[0]?.value;
|
|
||||||
const visibleSections = sections.filter((section) => section.page === selectedPage);
|
|
||||||
const recordSections = useMemo(
|
|
||||||
() =>
|
|
||||||
(templateContent?.trustContentTypes ?? [])
|
|
||||||
.filter((item) => item.pages?.includes(selectedPage ?? ""))
|
|
||||||
.map((item) => trustSection(item, selectedPage ?? "home")),
|
|
||||||
[templateContent, selectedPage],
|
|
||||||
);
|
|
||||||
const visibleTargets = useMemo<PreviewTarget[]>(
|
|
||||||
() =>
|
|
||||||
[...(templateContent?.admin.sections ?? []), ...recordSections]
|
|
||||||
.filter(
|
|
||||||
(section) =>
|
|
||||||
section.page === selectedPage &&
|
|
||||||
(selectedPage !== "detail" || section.target === "brand"),
|
|
||||||
)
|
|
||||||
.flatMap((section) =>
|
|
||||||
(section.previewTargets ?? []).map((target) => ({
|
|
||||||
...target,
|
|
||||||
page: section.page,
|
|
||||||
source: previewTargetSource(section, target.key),
|
|
||||||
...(section.key.startsWith("trust:") ? { trustType: section.key.slice(6) } : {}),
|
|
||||||
})),
|
|
||||||
)
|
|
||||||
.concat(
|
|
||||||
selectedPage === "inquiry" && inquiryRuntime
|
|
||||||
? inquiryRuntime.fields.map((field) => ({
|
|
||||||
key: `inquiry-field:${field.key}`,
|
|
||||||
label: field.label,
|
|
||||||
page: "inquiry",
|
|
||||||
source: "inquiry" as const,
|
|
||||||
}))
|
|
||||||
: [],
|
|
||||||
),
|
|
||||||
[templateContent, selectedPage, recordSections, inquiryRuntime],
|
|
||||||
);
|
|
||||||
const activeTarget = selection?.targetKey;
|
|
||||||
const selectedTarget = visibleTargets.find((target) => target.key === activeTarget);
|
|
||||||
const selectedSection = [...(templateContent?.admin.sections ?? []), ...recordSections].find(
|
|
||||||
(section) =>
|
|
||||||
section.page === selectedPage &&
|
|
||||||
section.previewTargets?.some((target) => target.key === selectedTarget?.key),
|
|
||||||
);
|
|
||||||
const selectedRecordSource =
|
|
||||||
selectedTarget?.source === "offering" || selectedTarget?.source === "trust"
|
|
||||||
? selectedTarget.source
|
|
||||||
: undefined;
|
|
||||||
const { offeringsQuery, trustQuery, selectedRecord } = usePresentationRecordQueries(
|
|
||||||
selectedRecordSource,
|
|
||||||
selection?.recordId,
|
|
||||||
);
|
|
||||||
const editableSections = filterSectionsForPreviewTarget(
|
|
||||||
visibleSections.filter((section) =>
|
|
||||||
section.fields.some((field) => field.binding.startsWith("brand.")),
|
|
||||||
),
|
|
||||||
selectedTarget?.key,
|
|
||||||
);
|
|
||||||
const recordSection = useMemo(
|
|
||||||
() =>
|
|
||||||
selectedSection && selection?.targetKey
|
|
||||||
? {
|
|
||||||
...selectedSection,
|
|
||||||
fields: selectedSection.fields.filter(
|
|
||||||
(field) => field.previewTarget === selection.targetKey,
|
|
||||||
),
|
|
||||||
}
|
|
||||||
: undefined,
|
|
||||||
[selectedSection, selection?.targetKey],
|
|
||||||
);
|
|
||||||
const handleTargetSelected = useCallback(
|
|
||||||
(next?: PreviewSelection) => {
|
|
||||||
const select = () =>
|
|
||||||
setSelection(
|
|
||||||
next
|
|
||||||
? resolvePreviewSelection(
|
|
||||||
next.targetKey,
|
|
||||||
next.recordId,
|
|
||||||
visibleTargets,
|
|
||||||
selectedPage ?? "home",
|
|
||||||
)
|
|
||||||
: undefined,
|
|
||||||
);
|
|
||||||
if (recordDraft || inquiryDraft)
|
|
||||||
guardDraft(() => {
|
|
||||||
setInquiryDraft(undefined);
|
|
||||||
setRecordDraft(undefined);
|
|
||||||
select();
|
|
||||||
});
|
|
||||||
else select();
|
|
||||||
},
|
|
||||||
[visibleTargets, selectedPage, recordDraft, inquiryDraft, guardDraft],
|
|
||||||
);
|
|
||||||
const relatedTargets = [
|
|
||||||
...(templateContent?.admin.sections ?? [])
|
|
||||||
.filter((section) => section.page === selectedPage && section.target !== "brand")
|
|
||||||
.map((section) => section.target),
|
|
||||||
...((templateContent?.trustContentTypes ?? []).some((item) =>
|
|
||||||
item.pages?.includes(selectedPage ?? ""),
|
|
||||||
)
|
|
||||||
? ["trust"]
|
|
||||||
: []),
|
|
||||||
];
|
|
||||||
const pageLinks = [...new Set(relatedTargets)].flatMap((target) =>
|
|
||||||
target === "trust"
|
|
||||||
? (templateContent?.trustContentTypes ?? [])
|
|
||||||
.filter((item) => item.pages?.includes(selectedPage ?? ""))
|
|
||||||
.map((item) => ({
|
|
||||||
target: `trust:${item.type}`,
|
|
||||||
label: `编辑${item.label}`,
|
|
||||||
}))
|
|
||||||
: [
|
|
||||||
{
|
|
||||||
target,
|
|
||||||
label: (
|
|
||||||
{ offering: "管理此页展示的业务内容", inquiry: "管理此页的咨询表单" } as Record<
|
|
||||||
string,
|
|
||||||
string
|
|
||||||
>
|
|
||||||
)[target],
|
|
||||||
},
|
|
||||||
],
|
|
||||||
);
|
|
||||||
const relevantPageLinks = selectedSection
|
|
||||||
? pageLinks.filter((item) => {
|
|
||||||
if (item.target.startsWith("trust:")) return selectedSection.target === "trust";
|
|
||||||
return item.target === selectedSection.target;
|
|
||||||
})
|
|
||||||
: pageLinks;
|
|
||||||
const formState = useBrandPresentationForm({ brand, config, sections });
|
|
||||||
const { form, initialValues } = formState;
|
|
||||||
const save = useBrandSaveMutation({
|
|
||||||
...formState,
|
|
||||||
brand,
|
|
||||||
config,
|
|
||||||
sections,
|
|
||||||
queryClient,
|
|
||||||
onSaved: () => setBrandDirty(false),
|
|
||||||
});
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
const initialPage =
|
|
||||||
typeof initialSelection === "object" && "page" in initialSelection
|
|
||||||
? String(initialSelection.page)
|
|
||||||
: undefined;
|
|
||||||
if (initialPage) {
|
|
||||||
setActivePage(
|
|
||||||
pageOptions.some((item) => item.value === initialPage)
|
|
||||||
? initialPage
|
|
||||||
: pageOptions[0]?.value,
|
|
||||||
);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (!activePage && pageOptions.length) setActivePage(pageOptions[0]?.value);
|
|
||||||
}, [activePage, initialSelection, pageOptions]);
|
|
||||||
useEffect(() => {
|
|
||||||
if (hasInitializedSelection) return;
|
|
||||||
if (!pageOptions.length) return;
|
|
||||||
if (!initialSelection) return;
|
|
||||||
const requestedPage =
|
|
||||||
typeof initialSelection === "object" && "page" in initialSelection
|
|
||||||
? String(initialSelection.page)
|
|
||||||
: undefined;
|
|
||||||
const resolvedPage =
|
|
||||||
requestedPage && pageOptions.some((item) => item.value === requestedPage)
|
|
||||||
? requestedPage
|
|
||||||
: (pageOptions[0]?.value ?? "home");
|
|
||||||
setSelection(
|
|
||||||
resolvePreviewSelection(
|
|
||||||
initialSelection.targetKey,
|
|
||||||
initialSelection.recordId,
|
|
||||||
visibleTargets,
|
|
||||||
resolvedPage,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
setActivePage(resolvedPage);
|
|
||||||
setHasInitializedSelection(true);
|
|
||||||
}, [hasInitializedSelection, initialSelection, pageOptions, selectedPage, visibleTargets]);
|
|
||||||
useEffect(() => {
|
|
||||||
if (!initialSelection) setSelection(undefined);
|
|
||||||
}, [initialSelection, selectedPage, templateContent?.displayName]);
|
|
||||||
useEffect(() => {
|
|
||||||
if (!selection?.recordId) return;
|
|
||||||
const records =
|
|
||||||
selectedTarget?.source === "trust"
|
|
||||||
? previewWorkspace?.trustItems
|
|
||||||
: previewWorkspace?.offerings;
|
|
||||||
if (records && !records.some((item) => item.id === selection.recordId)) setSelection(undefined);
|
|
||||||
}, [
|
|
||||||
previewWorkspace?.offerings,
|
|
||||||
previewWorkspace?.trustItems,
|
|
||||||
selectedTarget?.source,
|
|
||||||
selection,
|
|
||||||
]);
|
|
||||||
useEffect(
|
|
||||||
() => setRecordDraft(undefined),
|
|
||||||
[selection?.targetKey, selection?.recordId, selectedPage],
|
|
||||||
);
|
|
||||||
const { previewBrand, handleValuesChange, resetPreview } = useBrandPreviewDraft({
|
|
||||||
brand,
|
|
||||||
config,
|
|
||||||
sections,
|
|
||||||
form,
|
|
||||||
onDirty: () => setBrandDirty(true),
|
|
||||||
});
|
|
||||||
const recordPreview = useRecordPreview({ recordDraft, selectedRecord, recordSection });
|
|
||||||
useEffect(() => resetPreview(), [config, initialValues, resetPreview]);
|
|
||||||
const draftWorkspace = useDraftWorkspace({
|
|
||||||
previewWorkspace,
|
|
||||||
previewBrand,
|
|
||||||
inquiryRuntime,
|
|
||||||
inquiryDraft,
|
|
||||||
recordDraft,
|
|
||||||
selectedRecord,
|
|
||||||
recordSection,
|
|
||||||
recordPreview,
|
|
||||||
templateContent,
|
templateContent,
|
||||||
|
previewWorkspace,
|
||||||
|
config,
|
||||||
|
brand,
|
||||||
|
...(initialSelection ? { initialSelection } : {}),
|
||||||
});
|
});
|
||||||
const selectedDetailOfferingId =
|
|
||||||
detailOfferingId && draftWorkspace?.offerings.some((item) => item.id === detailOfferingId)
|
|
||||||
? detailOfferingId
|
|
||||||
: draftWorkspace?.offerings[0]?.id;
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<section className="presentation-editor" aria-labelledby="presentation-editor-title">
|
<section className="presentation-editor" aria-labelledby="presentation-editor-title">
|
||||||
@@ -324,306 +65,33 @@ export function PresentationEditor({
|
|||||||
{breakpoints.xs ? (
|
{breakpoints.xs ? (
|
||||||
<Select
|
<Select
|
||||||
aria-label="选择小程序页面"
|
aria-label="选择小程序页面"
|
||||||
value={selectedPage}
|
value={controller.selectedPage ?? null}
|
||||||
options={pageOptions}
|
options={controller.pageOptions}
|
||||||
onChange={(value) =>
|
onChange={controller.selectPage}
|
||||||
guardDraft(() => {
|
|
||||||
setBrandDirty(false);
|
|
||||||
form.setFieldsValue(initialValues);
|
|
||||||
resetPreview();
|
|
||||||
setRecordDraft(undefined);
|
|
||||||
setInquiryDraft(undefined);
|
|
||||||
setActivePage(value);
|
|
||||||
})
|
|
||||||
}
|
|
||||||
className="admin-field-w-2xl"
|
className="admin-field-w-2xl"
|
||||||
/>
|
/>
|
||||||
) : (
|
) : (
|
||||||
<Segmented
|
<Segmented
|
||||||
value={selectedPage}
|
value={controller.selectedPage ?? null}
|
||||||
options={pageOptions}
|
options={controller.pageOptions}
|
||||||
onChange={(value) =>
|
onChange={(value) => controller.selectPage(String(value))}
|
||||||
guardDraft(() => {
|
|
||||||
setBrandDirty(false);
|
|
||||||
form.setFieldsValue(initialValues);
|
|
||||||
resetPreview();
|
|
||||||
setRecordDraft(undefined);
|
|
||||||
setInquiryDraft(undefined);
|
|
||||||
setActivePage(String(value));
|
|
||||||
})
|
|
||||||
}
|
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
</Space>
|
</Space>
|
||||||
<div className="presentation-editor__workspace">
|
<div className="presentation-editor__workspace">
|
||||||
<div className="presentation-editor__preview">
|
<PresentationEditorPreview
|
||||||
<h3 className="admin-section-title admin-flush">页面预览</h3>
|
previewBrand={controller.previewBrand}
|
||||||
{selectedPage === "detail" && draftWorkspace?.offerings.length ? (
|
draftWorkspace={controller.draftWorkspace}
|
||||||
<Select
|
selectedPage={controller.selectedPage}
|
||||||
aria-label="选择详情页业务内容"
|
selectedDetailOfferingId={controller.selectedDetailOfferingId}
|
||||||
className="admin-block admin-offset-bottom-sm"
|
activeTarget={controller.activeTarget}
|
||||||
value={selectedDetailOfferingId}
|
selection={controller.selection}
|
||||||
options={draftWorkspace.offerings.map((item) => ({
|
visibleTargets={controller.visibleTargets}
|
||||||
value: item.id,
|
onSelectDetailOffering={controller.selectDetailOffering}
|
||||||
label: item.name,
|
onTargetSelected={controller.handleTargetSelected}
|
||||||
}))}
|
onSelectPreviewTarget={controller.selectPreviewTarget}
|
||||||
onChange={(value) => {
|
/>
|
||||||
setDetailOfferingId(value);
|
<PresentationEditorInspector controller={controller} />
|
||||||
setSelection(undefined);
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
) : null}
|
|
||||||
<TemplatePreview
|
|
||||||
brand={previewBrand}
|
|
||||||
{...(draftWorkspace ? { workspace: draftWorkspace } : {})}
|
|
||||||
page={selectedPage ?? "home"}
|
|
||||||
{...(selectedPage === "detail" && selectedDetailOfferingId
|
|
||||||
? { offeringId: selectedDetailOfferingId }
|
|
||||||
: {})}
|
|
||||||
{...(activeTarget ? { targetKey: activeTarget } : {})}
|
|
||||||
{...(selection ? { selection } : {})}
|
|
||||||
targets={visibleTargets}
|
|
||||||
onTargetSelected={handleTargetSelected}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<aside className="presentation-editor__outline" aria-label="页面区域">
|
|
||||||
<h3 className="admin-section-title admin-flush">页面区域</h3>
|
|
||||||
<p className="admin-section-description">选择区域,编辑对应内容</p>
|
|
||||||
{visibleTargets.length ? (
|
|
||||||
<Space className="presentation-editor__regions admin-offset-top" wrap>
|
|
||||||
{visibleTargets.map((target) => (
|
|
||||||
<Button
|
|
||||||
key={target.key}
|
|
||||||
className={
|
|
||||||
visibleTargets.some((parent) => parent.children?.includes(target.key))
|
|
||||||
? "is-child-region"
|
|
||||||
: ""
|
|
||||||
}
|
|
||||||
aria-pressed={activeTarget === target.key}
|
|
||||||
type={activeTarget === target.key ? "primary" : "default"}
|
|
||||||
onClick={() => {
|
|
||||||
const recordId =
|
|
||||||
target.source === "offering"
|
|
||||||
? selectedPage === "detail"
|
|
||||||
? selectedDetailOfferingId
|
|
||||||
: draftWorkspace?.offerings[0]?.id
|
|
||||||
: target.source === "trust"
|
|
||||||
? previewTrustRecordId(
|
|
||||||
draftWorkspace?.trustItems ?? [],
|
|
||||||
target.trustType,
|
|
||||||
)
|
|
||||||
: undefined;
|
|
||||||
handleTargetSelected({
|
|
||||||
targetKey: target.key,
|
|
||||||
...(recordId ? { recordId } : {}),
|
|
||||||
});
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{target.label}
|
|
||||||
</Button>
|
|
||||||
))}
|
|
||||||
</Space>
|
|
||||||
) : null}
|
|
||||||
{!visibleTargets.length ? (
|
|
||||||
<Typography.Text type="secondary">此页为动态预览</Typography.Text>
|
|
||||||
) : null}
|
|
||||||
</aside>
|
|
||||||
<div className="presentation-editor__inspector">
|
|
||||||
<h3 className="admin-section-title admin-flush">
|
|
||||||
{selectedTarget?.label ?? pageTitle(selectedPage ?? "home")}
|
|
||||||
</h3>
|
|
||||||
<StatusTag
|
|
||||||
tone={
|
|
||||||
save.isError
|
|
||||||
? "error"
|
|
||||||
: save.isPending || brandDirty || recordDraft || inquiryDraft
|
|
||||||
? "warning"
|
|
||||||
: "neutral"
|
|
||||||
}
|
|
||||||
label={
|
|
||||||
save.isPending
|
|
||||||
? "正在保存"
|
|
||||||
: save.isError
|
|
||||||
? "保存失败,请重试"
|
|
||||||
: brandDirty || recordDraft || inquiryDraft
|
|
||||||
? "有未保存修改"
|
|
||||||
: "草稿已同步"
|
|
||||||
}
|
|
||||||
/>
|
|
||||||
{selectedPage === "detail" && !selectedTarget ? (
|
|
||||||
<Alert
|
|
||||||
type="info"
|
|
||||||
showIcon
|
|
||||||
title="详情页由所选业务内容动态生成"
|
|
||||||
description="选择业务内容预览详情,记录内容在业务提供项中维护;公共标题和按钮文案可从左侧区域列表配置,对全部详情生效。"
|
|
||||||
action={
|
|
||||||
<Button
|
|
||||||
onClick={() => {
|
|
||||||
void navigate("/admin/services");
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
管理业务内容
|
|
||||||
</Button>
|
|
||||||
}
|
|
||||||
/>
|
|
||||||
) : activeTarget?.startsWith("inquiry-field:") && inquiryRuntime ? (
|
|
||||||
<InquiryPreviewEditor
|
|
||||||
runtime={
|
|
||||||
draftWorkspace?.inquiryForms.find((item) => item.key === inquiryRuntime.key) ??
|
|
||||||
inquiryRuntime
|
|
||||||
}
|
|
||||||
fieldKey={activeTarget.slice("inquiry-field:".length)}
|
|
||||||
onDraft={setInquiryDraft}
|
|
||||||
onSaved={() => setInquiryDraft(undefined)}
|
|
||||||
/>
|
|
||||||
) : selectedTarget?.composite ? (
|
|
||||||
<Alert
|
|
||||||
type="info"
|
|
||||||
showIcon
|
|
||||||
title="这是一个组合区域"
|
|
||||||
description={
|
|
||||||
<Space wrap>
|
|
||||||
{(selectedTarget.children ?? []).map((childKey) => {
|
|
||||||
const child = visibleTargets.find((item) => item.key === childKey);
|
|
||||||
if (!child) return null;
|
|
||||||
return (
|
|
||||||
<Button
|
|
||||||
key={child.key}
|
|
||||||
onClick={() => {
|
|
||||||
const recordId =
|
|
||||||
child.source === "offering"
|
|
||||||
? selectedPage === "detail"
|
|
||||||
? selectedDetailOfferingId
|
|
||||||
: draftWorkspace?.offerings[0]?.id
|
|
||||||
: child.source === "trust"
|
|
||||||
? previewTrustRecordId(
|
|
||||||
draftWorkspace?.trustItems ?? [],
|
|
||||||
child.trustType,
|
|
||||||
)
|
|
||||||
: undefined;
|
|
||||||
handleTargetSelected({
|
|
||||||
targetKey: child.key,
|
|
||||||
...(recordId ? { recordId } : {}),
|
|
||||||
});
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
编辑{child.label}
|
|
||||||
</Button>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</Space>
|
|
||||||
}
|
|
||||||
/>
|
|
||||||
) : selectedRecordSource && selection?.recordId && selectedSection ? (
|
|
||||||
selectedRecord ? (
|
|
||||||
<RecordContentEditor
|
|
||||||
key={`${selectedRecordSource}:${selectedRecord.id}:${selectedSection.key}`}
|
|
||||||
source={selectedRecordSource}
|
|
||||||
record={selectedRecord}
|
|
||||||
section={recordSection!}
|
|
||||||
context="visual"
|
|
||||||
onDraft={(values) =>
|
|
||||||
setRecordDraft({
|
|
||||||
source: selectedRecordSource,
|
|
||||||
id: selectedRecord.id,
|
|
||||||
values,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
onSaved={() => setRecordDraft(undefined)}
|
|
||||||
/>
|
|
||||||
) : (
|
|
||||||
<Alert
|
|
||||||
type={
|
|
||||||
(
|
|
||||||
selectedRecordSource === "offering"
|
|
||||||
? offeringsQuery.isError
|
|
||||||
: trustQuery.isError
|
|
||||||
)
|
|
||||||
? "error"
|
|
||||||
: "info"
|
|
||||||
}
|
|
||||||
title={
|
|
||||||
(
|
|
||||||
selectedRecordSource === "offering"
|
|
||||||
? offeringsQuery.isError
|
|
||||||
: trustQuery.isError
|
|
||||||
)
|
|
||||||
? "内容读取失败"
|
|
||||||
: (
|
|
||||||
selectedRecordSource === "offering"
|
|
||||||
? offeringsQuery.isSuccess
|
|
||||||
: trustQuery.isSuccess
|
|
||||||
)
|
|
||||||
? "对应内容已不存在,请重新选择页面中的区域"
|
|
||||||
: "正在读取对应内容"
|
|
||||||
}
|
|
||||||
{...((
|
|
||||||
selectedRecordSource === "offering"
|
|
||||||
? offeringsQuery.isError
|
|
||||||
: trustQuery.isError
|
|
||||||
)
|
|
||||||
? {
|
|
||||||
action: (
|
|
||||||
<Button
|
|
||||||
size="small"
|
|
||||||
onClick={() => {
|
|
||||||
if (selectedRecordSource === "offering")
|
|
||||||
void offeringsQuery.refetch();
|
|
||||||
else void trustQuery.refetch();
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
重试
|
|
||||||
</Button>
|
|
||||||
),
|
|
||||||
}
|
|
||||||
: {})}
|
|
||||||
/>
|
|
||||||
)
|
|
||||||
) : selectedRecordSource ? (
|
|
||||||
<Alert
|
|
||||||
type="info"
|
|
||||||
showIcon
|
|
||||||
title="此区域尚未配置内容"
|
|
||||||
description="创建并启用对应内容后,即可在预览中点选编辑。"
|
|
||||||
action={
|
|
||||||
<Button
|
|
||||||
onClick={() =>
|
|
||||||
guardDraft(() => {
|
|
||||||
void navigate(
|
|
||||||
selectedRecordSource === "trust"
|
|
||||||
? `/admin/trust?type=${encodeURIComponent(selectedTarget?.trustType ?? "")}`
|
|
||||||
: "/admin/services",
|
|
||||||
);
|
|
||||||
})
|
|
||||||
}
|
|
||||||
>
|
|
||||||
配置此区域内容
|
|
||||||
</Button>
|
|
||||||
}
|
|
||||||
/>
|
|
||||||
) : !selectedTarget ? (
|
|
||||||
<div className="presentation-editor__empty">
|
|
||||||
<h3 className="admin-subhead">选择要编辑的区域</h3>
|
|
||||||
<p className="admin-section-description">
|
|
||||||
点击预览中的内容,或使用区域列表,查看并修改对应字段。
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<PresentationFormPanel
|
|
||||||
form={form}
|
|
||||||
initialValues={initialValues}
|
|
||||||
editableSections={editableSections}
|
|
||||||
relevantPageLinks={relevantPageLinks}
|
|
||||||
selectedTarget={selectedTarget}
|
|
||||||
save={{
|
|
||||||
error: save.error,
|
|
||||||
isPending: save.isPending,
|
|
||||||
mutate: (values) => save.mutate(values),
|
|
||||||
}}
|
|
||||||
onValuesChange={handleValuesChange}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
</>
|
</>
|
||||||
) : null}
|
) : null}
|
||||||
|
|||||||
@@ -0,0 +1,196 @@
|
|||||||
|
import { Alert, Button, Space } from "antd";
|
||||||
|
import { StatusTag } from "../../components/StatusTag.js";
|
||||||
|
import { RecordContentEditor } from "../../components/RecordContentEditor.js";
|
||||||
|
import { InquiryPreviewEditor } from "./InquiryPreviewEditor.js";
|
||||||
|
import { PresentationFormPanel } from "./PresentationFormPanel.js";
|
||||||
|
import { pageTitle } from "./presentation-editor-helpers.js";
|
||||||
|
import type { PresentationEditorController } from "./presentation-editor-controller.js";
|
||||||
|
|
||||||
|
export function PresentationEditorInspector({
|
||||||
|
controller,
|
||||||
|
}: {
|
||||||
|
controller: PresentationEditorController;
|
||||||
|
}) {
|
||||||
|
const {
|
||||||
|
selectedPage,
|
||||||
|
selectedTarget,
|
||||||
|
activeTarget,
|
||||||
|
selection,
|
||||||
|
selectedSection,
|
||||||
|
selectedRecordSource,
|
||||||
|
selectedRecord,
|
||||||
|
recordSection,
|
||||||
|
editableSections,
|
||||||
|
relevantPageLinks,
|
||||||
|
inquiryRuntime,
|
||||||
|
draftWorkspace,
|
||||||
|
form,
|
||||||
|
initialValues,
|
||||||
|
save,
|
||||||
|
offeringsQuery,
|
||||||
|
trustQuery,
|
||||||
|
recordDraft,
|
||||||
|
inquiryDraft,
|
||||||
|
brandDirty,
|
||||||
|
guardDraft,
|
||||||
|
} = controller;
|
||||||
|
const recordQuery = selectedRecordSource === "trust" ? trustQuery : offeringsQuery;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="presentation-editor__inspector">
|
||||||
|
<h3 className="admin-section-title admin-flush">
|
||||||
|
{selectedTarget?.label ?? pageTitle(selectedPage ?? "home")}
|
||||||
|
</h3>
|
||||||
|
<StatusTag
|
||||||
|
tone={
|
||||||
|
save.isError
|
||||||
|
? "error"
|
||||||
|
: save.isPending || brandDirty || recordDraft || inquiryDraft
|
||||||
|
? "warning"
|
||||||
|
: "neutral"
|
||||||
|
}
|
||||||
|
label={
|
||||||
|
save.isPending
|
||||||
|
? "正在保存"
|
||||||
|
: save.isError
|
||||||
|
? "保存失败,请重试"
|
||||||
|
: brandDirty || recordDraft || inquiryDraft
|
||||||
|
? "有未保存修改"
|
||||||
|
: "草稿已同步"
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
{selectedPage === "detail" && !selectedTarget ? (
|
||||||
|
<Alert
|
||||||
|
type="info"
|
||||||
|
showIcon
|
||||||
|
title="详情页由所选业务内容动态生成"
|
||||||
|
description="选择业务内容预览详情,记录内容在业务提供项中维护;公共标题和按钮文案可从左侧区域列表配置,对全部详情生效。"
|
||||||
|
action={
|
||||||
|
<Button
|
||||||
|
onClick={() => {
|
||||||
|
void controller.navigate("/admin/services");
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
管理业务内容
|
||||||
|
</Button>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
) : activeTarget?.startsWith("inquiry-field:") && inquiryRuntime ? (
|
||||||
|
<InquiryPreviewEditor
|
||||||
|
runtime={
|
||||||
|
draftWorkspace?.inquiryForms.find((item) => item.key === inquiryRuntime.key) ??
|
||||||
|
inquiryRuntime
|
||||||
|
}
|
||||||
|
fieldKey={activeTarget.slice("inquiry-field:".length)}
|
||||||
|
onDraft={controller.setInquiryDraft}
|
||||||
|
onSaved={() => controller.setInquiryDraft(undefined)}
|
||||||
|
/>
|
||||||
|
) : selectedTarget?.composite ? (
|
||||||
|
<Alert
|
||||||
|
type="info"
|
||||||
|
showIcon
|
||||||
|
title="这是一个组合区域"
|
||||||
|
description={
|
||||||
|
<Space wrap>
|
||||||
|
{(selectedTarget.children ?? []).map((childKey) => {
|
||||||
|
const child = visibleTarget(childKey, controller);
|
||||||
|
if (!child) return null;
|
||||||
|
return (
|
||||||
|
<Button key={child.key} onClick={() => controller.selectPreviewTarget(child)}>
|
||||||
|
编辑{child.label}
|
||||||
|
</Button>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</Space>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
) : selectedRecordSource && selection?.recordId && selectedSection ? (
|
||||||
|
selectedRecord ? (
|
||||||
|
<RecordContentEditor
|
||||||
|
key={`${selectedRecordSource}:${selectedRecord.id}:${selectedSection.key}`}
|
||||||
|
source={selectedRecordSource}
|
||||||
|
record={selectedRecord}
|
||||||
|
section={recordSection!}
|
||||||
|
context="visual"
|
||||||
|
onDraft={(values) =>
|
||||||
|
controller.setRecordDraft({
|
||||||
|
source: selectedRecordSource,
|
||||||
|
id: selectedRecord.id,
|
||||||
|
values,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
onSaved={() => controller.setRecordDraft(undefined)}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<Alert
|
||||||
|
type={recordQuery.isError ? "error" : "info"}
|
||||||
|
title={
|
||||||
|
recordQuery.isError
|
||||||
|
? "内容读取失败"
|
||||||
|
: recordQuery.isSuccess
|
||||||
|
? "对应内容已不存在,请重新选择页面中的区域"
|
||||||
|
: "正在读取对应内容"
|
||||||
|
}
|
||||||
|
{...(recordQuery.isError
|
||||||
|
? {
|
||||||
|
action: (
|
||||||
|
<Button size="small" onClick={() => void recordQuery.refetch()}>
|
||||||
|
重试
|
||||||
|
</Button>
|
||||||
|
),
|
||||||
|
}
|
||||||
|
: {})}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
) : selectedRecordSource ? (
|
||||||
|
<Alert
|
||||||
|
type="info"
|
||||||
|
showIcon
|
||||||
|
title="此区域尚未配置内容"
|
||||||
|
description="创建并启用对应内容后,即可在预览中点选编辑。"
|
||||||
|
action={
|
||||||
|
<Button
|
||||||
|
onClick={() =>
|
||||||
|
guardDraft(() => {
|
||||||
|
void controller.navigate(
|
||||||
|
selectedRecordSource === "trust"
|
||||||
|
? `/admin/trust?type=${encodeURIComponent(selectedTarget?.trustType ?? "")}`
|
||||||
|
: "/admin/services",
|
||||||
|
);
|
||||||
|
})
|
||||||
|
}
|
||||||
|
>
|
||||||
|
配置此区域内容
|
||||||
|
</Button>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
) : !selectedTarget ? (
|
||||||
|
<div className="presentation-editor__empty">
|
||||||
|
<h3 className="admin-subhead">选择要编辑的区域</h3>
|
||||||
|
<p className="admin-section-description">
|
||||||
|
点击预览中的内容,或使用区域列表,查看并修改对应字段。
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<PresentationFormPanel
|
||||||
|
key={`${selectedPage}:${selectedTarget.key}`}
|
||||||
|
form={form}
|
||||||
|
initialValues={initialValues}
|
||||||
|
editableSections={editableSections}
|
||||||
|
relevantPageLinks={relevantPageLinks}
|
||||||
|
selectedTarget={selectedTarget}
|
||||||
|
save={{
|
||||||
|
error: save.error,
|
||||||
|
isPending: save.isPending,
|
||||||
|
mutate: (values) => save.mutate(values),
|
||||||
|
}}
|
||||||
|
onValuesChange={controller.handleValuesChange}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function visibleTarget(key: string, controller: PresentationEditorController) {
|
||||||
|
return controller.visibleTargets.find((item) => item.key === key);
|
||||||
|
}
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
import { Button, Select, Space, Typography } from "antd";
|
||||||
|
import type { BrandProfile, RuntimeWorkspace } from "@personal-brand/api-client";
|
||||||
|
import { TemplatePreview } from "./TemplatePreview.js";
|
||||||
|
import type { PreviewSelection, PreviewTarget } from "./preview-selection.js";
|
||||||
|
|
||||||
|
interface PresentationEditorPreviewProps {
|
||||||
|
previewBrand: BrandProfile;
|
||||||
|
draftWorkspace?: RuntimeWorkspace | undefined;
|
||||||
|
selectedPage: string | undefined;
|
||||||
|
selectedDetailOfferingId: string | undefined;
|
||||||
|
activeTarget: string | undefined;
|
||||||
|
selection: PreviewSelection | undefined;
|
||||||
|
visibleTargets: PreviewTarget[];
|
||||||
|
onSelectDetailOffering: (id: string) => void;
|
||||||
|
onTargetSelected: (next?: PreviewSelection) => void;
|
||||||
|
onSelectPreviewTarget: (target: PreviewTarget) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function PresentationEditorPreview({
|
||||||
|
previewBrand,
|
||||||
|
draftWorkspace,
|
||||||
|
selectedPage,
|
||||||
|
selectedDetailOfferingId,
|
||||||
|
activeTarget,
|
||||||
|
selection,
|
||||||
|
visibleTargets,
|
||||||
|
onSelectDetailOffering,
|
||||||
|
onTargetSelected,
|
||||||
|
onSelectPreviewTarget,
|
||||||
|
}: PresentationEditorPreviewProps) {
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<div className="presentation-editor__preview">
|
||||||
|
<h3 className="admin-section-title admin-flush">页面预览</h3>
|
||||||
|
{selectedPage === "detail" && draftWorkspace?.offerings.length ? (
|
||||||
|
<Select
|
||||||
|
aria-label="选择详情页业务内容"
|
||||||
|
className="admin-block admin-offset-bottom-sm"
|
||||||
|
value={selectedDetailOfferingId ?? null}
|
||||||
|
options={draftWorkspace.offerings.map((item) => ({
|
||||||
|
value: item.id,
|
||||||
|
label: item.name,
|
||||||
|
}))}
|
||||||
|
onChange={onSelectDetailOffering}
|
||||||
|
/>
|
||||||
|
) : null}
|
||||||
|
<TemplatePreview
|
||||||
|
brand={previewBrand}
|
||||||
|
{...(draftWorkspace ? { workspace: draftWorkspace } : {})}
|
||||||
|
page={selectedPage ?? "home"}
|
||||||
|
{...(selectedPage === "detail" && selectedDetailOfferingId
|
||||||
|
? { offeringId: selectedDetailOfferingId }
|
||||||
|
: {})}
|
||||||
|
{...(activeTarget ? { targetKey: activeTarget } : {})}
|
||||||
|
{...(selection ? { selection } : {})}
|
||||||
|
targets={visibleTargets}
|
||||||
|
onTargetSelected={onTargetSelected}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<aside className="presentation-editor__outline" aria-label="页面区域">
|
||||||
|
<h3 className="admin-section-title admin-flush">页面区域</h3>
|
||||||
|
<p className="admin-section-description">选择区域,编辑对应内容</p>
|
||||||
|
{visibleTargets.length ? (
|
||||||
|
<Space className="presentation-editor__regions admin-offset-top" wrap>
|
||||||
|
{visibleTargets.map((target) => (
|
||||||
|
<Button
|
||||||
|
key={target.key}
|
||||||
|
className={
|
||||||
|
visibleTargets.some((parent) => parent.children?.includes(target.key))
|
||||||
|
? "is-child-region"
|
||||||
|
: ""
|
||||||
|
}
|
||||||
|
aria-pressed={activeTarget === target.key}
|
||||||
|
type={activeTarget === target.key ? "primary" : "default"}
|
||||||
|
onClick={() => onSelectPreviewTarget(target)}
|
||||||
|
>
|
||||||
|
{target.label}
|
||||||
|
</Button>
|
||||||
|
))}
|
||||||
|
</Space>
|
||||||
|
) : null}
|
||||||
|
{!visibleTargets.length ? (
|
||||||
|
<Typography.Text type="secondary">此页为动态预览</Typography.Text>
|
||||||
|
) : null}
|
||||||
|
</aside>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -146,7 +146,7 @@ export function TemplatePreview({
|
|||||||
<>
|
<>
|
||||||
{!ready && !error ? (
|
{!ready && !error ? (
|
||||||
<div className="template-preview__loading">
|
<div className="template-preview__loading">
|
||||||
<Spin tip="正在加载页面预览" />
|
<Spin description="正在加载页面预览" />
|
||||||
</div>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
{error ? (
|
{error ? (
|
||||||
|
|||||||
@@ -0,0 +1,416 @@
|
|||||||
|
import { useQueryClient } from "@tanstack/react-query";
|
||||||
|
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||||
|
import { useNavigate, type NavigateFunction } from "react-router-dom";
|
||||||
|
import type {
|
||||||
|
AdminTemplateContent,
|
||||||
|
BrandProfile,
|
||||||
|
Offering,
|
||||||
|
RuntimeWorkspace,
|
||||||
|
TemplateAdminSection,
|
||||||
|
TrustContent,
|
||||||
|
} from "@personal-brand/api-client";
|
||||||
|
import type { FormInstance } from "antd";
|
||||||
|
import { filterSectionsForPreviewTarget } from "../../lib/presentation/presentation-bindings.js";
|
||||||
|
import type { PresentationValues } from "../../lib/presentation/presentation-bindings.js";
|
||||||
|
import {
|
||||||
|
resolvePreviewSelection,
|
||||||
|
previewTrustRecordId,
|
||||||
|
type PreviewSelection,
|
||||||
|
type PreviewTarget,
|
||||||
|
} from "./preview-selection.js";
|
||||||
|
import { useEditorDraft } from "./use-editor-draft.js";
|
||||||
|
import {
|
||||||
|
useBrandPresentationForm,
|
||||||
|
useBrandPresentationSections,
|
||||||
|
useBrandPreviewDraft,
|
||||||
|
useBrandSaveMutation,
|
||||||
|
usePresentationRecordQueries,
|
||||||
|
} from "./presentation-editor-state.js";
|
||||||
|
import { useRecordPreview, type RecordDraft } from "./presentation-editor-record-preview.js";
|
||||||
|
import { pageTitle, previewTargetSource, trustSection } from "./presentation-editor-helpers.js";
|
||||||
|
import { useDraftWorkspace } from "./use-draft-workspace.js";
|
||||||
|
|
||||||
|
export interface PresentationEditorControllerInput {
|
||||||
|
templateContent: AdminTemplateContent | null | undefined;
|
||||||
|
previewWorkspace?: RuntimeWorkspace | undefined;
|
||||||
|
config: Record<string, unknown> | null | undefined;
|
||||||
|
brand: BrandProfile;
|
||||||
|
initialSelection?: PreviewSelection;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PresentationRecordQuery {
|
||||||
|
isError: boolean;
|
||||||
|
isSuccess: boolean;
|
||||||
|
refetch: () => unknown;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PresentationEditorController {
|
||||||
|
pageOptions: { value: string; label: string }[];
|
||||||
|
selectedPage: string | undefined;
|
||||||
|
visibleTargets: PreviewTarget[];
|
||||||
|
selectedTarget: PreviewTarget | undefined;
|
||||||
|
selectedSection: TemplateAdminSection | undefined;
|
||||||
|
selectedRecordSource: "offering" | "trust" | undefined;
|
||||||
|
selectedRecord: Offering | TrustContent | undefined;
|
||||||
|
recordSection: TemplateAdminSection | undefined;
|
||||||
|
editableSections: TemplateAdminSection[];
|
||||||
|
relevantPageLinks: { target: string; label: string | undefined }[];
|
||||||
|
inquiryRuntime: RuntimeWorkspace["inquiryForms"][number] | undefined;
|
||||||
|
draftWorkspace: RuntimeWorkspace | undefined;
|
||||||
|
previewBrand: BrandProfile;
|
||||||
|
selectedDetailOfferingId: string | undefined;
|
||||||
|
form: FormInstance<PresentationValues>;
|
||||||
|
initialValues: PresentationValues;
|
||||||
|
save: {
|
||||||
|
error: unknown;
|
||||||
|
isError: boolean;
|
||||||
|
isPending: boolean;
|
||||||
|
mutate: (values: PresentationValues) => void;
|
||||||
|
};
|
||||||
|
offeringsQuery: PresentationRecordQuery;
|
||||||
|
trustQuery: PresentationRecordQuery;
|
||||||
|
recordDraft: RecordDraft | undefined;
|
||||||
|
inquiryDraft: RuntimeWorkspace["inquiryForms"][number]["fields"] | undefined;
|
||||||
|
brandDirty: boolean;
|
||||||
|
selection: PreviewSelection | undefined;
|
||||||
|
activeTarget: string | undefined;
|
||||||
|
guardDraft: (action: () => void) => void;
|
||||||
|
selectPage: (page: string) => void;
|
||||||
|
selectDetailOffering: (id: string) => void;
|
||||||
|
selectPreviewTarget: (target: PreviewTarget) => void;
|
||||||
|
handleTargetSelected: (next?: PreviewSelection) => void;
|
||||||
|
setRecordDraft: (draft: RecordDraft | undefined) => void;
|
||||||
|
setInquiryDraft: (fields: RuntimeWorkspace["inquiryForms"][number]["fields"] | undefined) => void;
|
||||||
|
handleValuesChange: (changed: PresentationValues, allValues: PresentationValues) => void;
|
||||||
|
navigate: NavigateFunction;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* PresentationEditor 的状态与派生数据集中在此处。
|
||||||
|
* 视图组件只负责渲染,避免页面组件继续膨胀。
|
||||||
|
*/
|
||||||
|
export function usePresentationEditorController({
|
||||||
|
templateContent,
|
||||||
|
previewWorkspace,
|
||||||
|
config,
|
||||||
|
brand,
|
||||||
|
initialSelection,
|
||||||
|
}: PresentationEditorControllerInput): PresentationEditorController {
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
const navigate = useNavigate();
|
||||||
|
const [activePage, setActivePage] = useState<string>();
|
||||||
|
const [selection, setSelection] = useState<PreviewSelection | undefined>(initialSelection);
|
||||||
|
const [hasInitializedSelection, setHasInitializedSelection] = useState(Boolean(initialSelection));
|
||||||
|
const [detailOfferingId, setDetailOfferingId] = useState<string>();
|
||||||
|
const [recordDraft, setRecordDraft] = useState<RecordDraft>();
|
||||||
|
const [inquiryDraft, setInquiryDraft] =
|
||||||
|
useState<RuntimeWorkspace["inquiryForms"][number]["fields"]>();
|
||||||
|
const [brandDirty, setBrandDirty] = useState(false);
|
||||||
|
const guardDraft = useEditorDraft(brandDirty || !!recordDraft || !!inquiryDraft);
|
||||||
|
const inquiryRuntime = previewWorkspace?.inquiryForms.find((item) => item.target === "brand");
|
||||||
|
const sections = useBrandPresentationSections(templateContent);
|
||||||
|
const pageOptions = useMemo(() => {
|
||||||
|
const pages = new Map<string, string>();
|
||||||
|
for (const item of templateContent?.navigation ?? []) pages.set(item.page, item.label);
|
||||||
|
for (const section of templateContent?.admin.sections ?? []) {
|
||||||
|
const navigation = templateContent?.navigation.find((item) => item.page === section.page);
|
||||||
|
if (!pages.has(section.page))
|
||||||
|
pages.set(section.page, navigation?.label ?? pageTitle(section.page));
|
||||||
|
}
|
||||||
|
return [...pages].map(([value, label]) => ({ value, label }));
|
||||||
|
}, [templateContent]);
|
||||||
|
const selectedPage = pageOptions.some((item) => item.value === activePage)
|
||||||
|
? activePage
|
||||||
|
: pageOptions[0]?.value;
|
||||||
|
const visibleSections = sections.filter((section) => section.page === selectedPage);
|
||||||
|
const recordSections = useMemo(
|
||||||
|
() =>
|
||||||
|
(templateContent?.trustContentTypes ?? [])
|
||||||
|
.filter((item) => item.pages?.includes(selectedPage ?? ""))
|
||||||
|
.map((item) => trustSection(item, selectedPage ?? "home")),
|
||||||
|
[templateContent, selectedPage],
|
||||||
|
);
|
||||||
|
const visibleTargets = useMemo<PreviewTarget[]>(
|
||||||
|
() =>
|
||||||
|
[...(templateContent?.admin.sections ?? []), ...recordSections]
|
||||||
|
.filter(
|
||||||
|
(section) =>
|
||||||
|
section.page === selectedPage &&
|
||||||
|
(selectedPage !== "detail" || section.target === "brand"),
|
||||||
|
)
|
||||||
|
.flatMap((section) =>
|
||||||
|
(section.previewTargets ?? []).map((target) => ({
|
||||||
|
...target,
|
||||||
|
page: section.page,
|
||||||
|
source: previewTargetSource(section, target.key),
|
||||||
|
...(section.key.startsWith("trust:") ? { trustType: section.key.slice(6) } : {}),
|
||||||
|
})),
|
||||||
|
)
|
||||||
|
.concat(
|
||||||
|
selectedPage === "inquiry" && inquiryRuntime
|
||||||
|
? inquiryRuntime.fields.map((field) => ({
|
||||||
|
key: `inquiry-field:${field.key}`,
|
||||||
|
label: field.label,
|
||||||
|
page: "inquiry",
|
||||||
|
source: "inquiry" as const,
|
||||||
|
}))
|
||||||
|
: [],
|
||||||
|
),
|
||||||
|
[templateContent, selectedPage, recordSections, inquiryRuntime],
|
||||||
|
);
|
||||||
|
const activeTarget = selection?.targetKey;
|
||||||
|
const selectedTarget = visibleTargets.find((target) => target.key === activeTarget);
|
||||||
|
const selectedSection = [...(templateContent?.admin.sections ?? []), ...recordSections].find(
|
||||||
|
(section) =>
|
||||||
|
section.page === selectedPage &&
|
||||||
|
section.previewTargets?.some((target) => target.key === selectedTarget?.key),
|
||||||
|
);
|
||||||
|
const selectedRecordSource =
|
||||||
|
selectedTarget?.source === "offering" || selectedTarget?.source === "trust"
|
||||||
|
? selectedTarget.source
|
||||||
|
: undefined;
|
||||||
|
const { offeringsQuery, trustQuery, selectedRecord } = usePresentationRecordQueries(
|
||||||
|
selectedRecordSource,
|
||||||
|
selection?.recordId,
|
||||||
|
);
|
||||||
|
const editableSections = filterSectionsForPreviewTarget(
|
||||||
|
visibleSections.filter((section) =>
|
||||||
|
section.fields.some((field) => field.binding.startsWith("brand.")),
|
||||||
|
),
|
||||||
|
selectedTarget?.key,
|
||||||
|
);
|
||||||
|
const recordSection = useMemo(
|
||||||
|
() =>
|
||||||
|
selectedSection && selection?.targetKey
|
||||||
|
? {
|
||||||
|
...selectedSection,
|
||||||
|
fields: selectedSection.fields.filter(
|
||||||
|
(field) => field.previewTarget === selection.targetKey,
|
||||||
|
),
|
||||||
|
}
|
||||||
|
: undefined,
|
||||||
|
[selectedSection, selection?.targetKey],
|
||||||
|
);
|
||||||
|
const handleTargetSelected = useCallback(
|
||||||
|
(next?: PreviewSelection) => {
|
||||||
|
const select = () =>
|
||||||
|
setSelection(
|
||||||
|
next
|
||||||
|
? resolvePreviewSelection(
|
||||||
|
next.targetKey,
|
||||||
|
next.recordId,
|
||||||
|
visibleTargets,
|
||||||
|
selectedPage ?? "home",
|
||||||
|
)
|
||||||
|
: undefined,
|
||||||
|
);
|
||||||
|
if (recordDraft || inquiryDraft)
|
||||||
|
guardDraft(() => {
|
||||||
|
setInquiryDraft(undefined);
|
||||||
|
setRecordDraft(undefined);
|
||||||
|
select();
|
||||||
|
});
|
||||||
|
else select();
|
||||||
|
},
|
||||||
|
[visibleTargets, selectedPage, recordDraft, inquiryDraft, guardDraft],
|
||||||
|
);
|
||||||
|
const relatedTargets = [
|
||||||
|
...(templateContent?.admin.sections ?? [])
|
||||||
|
.filter((section) => section.page === selectedPage && section.target !== "brand")
|
||||||
|
.map((section) => section.target),
|
||||||
|
...((templateContent?.trustContentTypes ?? []).some((item) =>
|
||||||
|
item.pages?.includes(selectedPage ?? ""),
|
||||||
|
)
|
||||||
|
? ["trust"]
|
||||||
|
: []),
|
||||||
|
];
|
||||||
|
const pageLinks = [...new Set(relatedTargets)].flatMap((target) =>
|
||||||
|
target === "trust"
|
||||||
|
? (templateContent?.trustContentTypes ?? [])
|
||||||
|
.filter((item) => item.pages?.includes(selectedPage ?? ""))
|
||||||
|
.map((item) => ({
|
||||||
|
target: `trust:${item.type}`,
|
||||||
|
label: `编辑${item.label}`,
|
||||||
|
}))
|
||||||
|
: [
|
||||||
|
{
|
||||||
|
target,
|
||||||
|
label: (
|
||||||
|
{ offering: "管理此页展示的业务内容", inquiry: "管理此页的咨询表单" } as Record<
|
||||||
|
string,
|
||||||
|
string
|
||||||
|
>
|
||||||
|
)[target],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
);
|
||||||
|
const relevantPageLinks = selectedSection
|
||||||
|
? pageLinks.filter((item) => {
|
||||||
|
if (item.target.startsWith("trust:")) return selectedSection.target === "trust";
|
||||||
|
return item.target === selectedSection.target;
|
||||||
|
})
|
||||||
|
: pageLinks;
|
||||||
|
const formState = useBrandPresentationForm({ brand, config, sections });
|
||||||
|
const { form, initialValues } = formState;
|
||||||
|
const save = useBrandSaveMutation({
|
||||||
|
...formState,
|
||||||
|
brand,
|
||||||
|
config,
|
||||||
|
sections,
|
||||||
|
queryClient,
|
||||||
|
onSaved: () => setBrandDirty(false),
|
||||||
|
});
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const initialPage =
|
||||||
|
typeof initialSelection === "object" && "page" in initialSelection
|
||||||
|
? String(initialSelection.page)
|
||||||
|
: undefined;
|
||||||
|
if (initialPage) {
|
||||||
|
setActivePage(
|
||||||
|
pageOptions.some((item) => item.value === initialPage)
|
||||||
|
? initialPage
|
||||||
|
: pageOptions[0]?.value,
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!activePage && pageOptions.length) setActivePage(pageOptions[0]?.value);
|
||||||
|
}, [activePage, initialSelection, pageOptions]);
|
||||||
|
useEffect(() => {
|
||||||
|
if (hasInitializedSelection) return;
|
||||||
|
if (!pageOptions.length) return;
|
||||||
|
if (!initialSelection) return;
|
||||||
|
const requestedPage =
|
||||||
|
typeof initialSelection === "object" && "page" in initialSelection
|
||||||
|
? String(initialSelection.page)
|
||||||
|
: undefined;
|
||||||
|
const resolvedPage =
|
||||||
|
requestedPage && pageOptions.some((item) => item.value === requestedPage)
|
||||||
|
? requestedPage
|
||||||
|
: (pageOptions[0]?.value ?? "home");
|
||||||
|
setSelection(
|
||||||
|
resolvePreviewSelection(
|
||||||
|
initialSelection.targetKey,
|
||||||
|
initialSelection.recordId,
|
||||||
|
visibleTargets,
|
||||||
|
resolvedPage,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
setActivePage(resolvedPage);
|
||||||
|
setHasInitializedSelection(true);
|
||||||
|
}, [hasInitializedSelection, initialSelection, pageOptions, selectedPage, visibleTargets]);
|
||||||
|
useEffect(() => {
|
||||||
|
if (!initialSelection) setSelection(undefined);
|
||||||
|
}, [initialSelection, selectedPage, templateContent?.displayName]);
|
||||||
|
useEffect(() => {
|
||||||
|
if (!selection?.recordId) return;
|
||||||
|
const records =
|
||||||
|
selectedTarget?.source === "trust"
|
||||||
|
? previewWorkspace?.trustItems
|
||||||
|
: previewWorkspace?.offerings;
|
||||||
|
if (records && !records.some((item) => item.id === selection.recordId)) setSelection(undefined);
|
||||||
|
}, [
|
||||||
|
previewWorkspace?.offerings,
|
||||||
|
previewWorkspace?.trustItems,
|
||||||
|
selectedTarget?.source,
|
||||||
|
selection,
|
||||||
|
]);
|
||||||
|
useEffect(
|
||||||
|
() => setRecordDraft(undefined),
|
||||||
|
[selection?.targetKey, selection?.recordId, selectedPage],
|
||||||
|
);
|
||||||
|
const { previewBrand, handleValuesChange, resetPreview } = useBrandPreviewDraft({
|
||||||
|
brand,
|
||||||
|
config,
|
||||||
|
sections,
|
||||||
|
form,
|
||||||
|
onDirty: () => setBrandDirty(true),
|
||||||
|
});
|
||||||
|
const recordPreview = useRecordPreview({ recordDraft, selectedRecord, recordSection });
|
||||||
|
useEffect(() => resetPreview(), [config, initialValues, resetPreview]);
|
||||||
|
const draftWorkspace = useDraftWorkspace({
|
||||||
|
previewWorkspace,
|
||||||
|
previewBrand,
|
||||||
|
inquiryRuntime,
|
||||||
|
inquiryDraft,
|
||||||
|
recordDraft,
|
||||||
|
selectedRecord,
|
||||||
|
recordSection,
|
||||||
|
recordPreview,
|
||||||
|
templateContent,
|
||||||
|
});
|
||||||
|
const selectedDetailOfferingId =
|
||||||
|
detailOfferingId && draftWorkspace?.offerings.some((item) => item.id === detailOfferingId)
|
||||||
|
? detailOfferingId
|
||||||
|
: draftWorkspace?.offerings[0]?.id;
|
||||||
|
|
||||||
|
const selectPage = useCallback(
|
||||||
|
(page: string) => {
|
||||||
|
guardDraft(() => {
|
||||||
|
setBrandDirty(false);
|
||||||
|
resetPreview();
|
||||||
|
setRecordDraft(undefined);
|
||||||
|
setInquiryDraft(undefined);
|
||||||
|
setActivePage(page);
|
||||||
|
});
|
||||||
|
},
|
||||||
|
[guardDraft, resetPreview],
|
||||||
|
);
|
||||||
|
const selectDetailOffering = useCallback((id: string) => {
|
||||||
|
setDetailOfferingId(id);
|
||||||
|
setSelection(undefined);
|
||||||
|
}, []);
|
||||||
|
const selectPreviewTarget = useCallback(
|
||||||
|
(target: PreviewTarget) => {
|
||||||
|
const recordId =
|
||||||
|
target.source === "offering"
|
||||||
|
? selectedPage === "detail"
|
||||||
|
? selectedDetailOfferingId
|
||||||
|
: draftWorkspace?.offerings[0]?.id
|
||||||
|
: target.source === "trust"
|
||||||
|
? previewTrustRecordId(draftWorkspace?.trustItems ?? [], target.trustType)
|
||||||
|
: undefined;
|
||||||
|
handleTargetSelected({
|
||||||
|
targetKey: target.key,
|
||||||
|
...(recordId ? { recordId } : {}),
|
||||||
|
});
|
||||||
|
},
|
||||||
|
[handleTargetSelected, selectedPage, selectedDetailOfferingId, draftWorkspace],
|
||||||
|
);
|
||||||
|
|
||||||
|
return {
|
||||||
|
pageOptions,
|
||||||
|
selectedPage,
|
||||||
|
visibleTargets,
|
||||||
|
selectedTarget,
|
||||||
|
selectedSection,
|
||||||
|
selectedRecordSource,
|
||||||
|
selectedRecord,
|
||||||
|
recordSection,
|
||||||
|
editableSections,
|
||||||
|
relevantPageLinks,
|
||||||
|
inquiryRuntime,
|
||||||
|
draftWorkspace,
|
||||||
|
previewBrand,
|
||||||
|
selectedDetailOfferingId,
|
||||||
|
form,
|
||||||
|
initialValues,
|
||||||
|
save,
|
||||||
|
offeringsQuery,
|
||||||
|
trustQuery,
|
||||||
|
recordDraft,
|
||||||
|
inquiryDraft,
|
||||||
|
brandDirty,
|
||||||
|
selection,
|
||||||
|
activeTarget,
|
||||||
|
guardDraft,
|
||||||
|
selectPage,
|
||||||
|
selectDetailOffering,
|
||||||
|
selectPreviewTarget,
|
||||||
|
handleTargetSelected,
|
||||||
|
setRecordDraft,
|
||||||
|
setInquiryDraft,
|
||||||
|
handleValuesChange,
|
||||||
|
navigate,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -89,7 +89,6 @@ export function useBrandPresentationForm({
|
|||||||
return values;
|
return values;
|
||||||
}, [brand, config, sections]);
|
}, [brand, config, sections]);
|
||||||
|
|
||||||
useEffect(() => form.setFieldsValue(initialValues), [form, initialValues]);
|
|
||||||
return { form, initialValues };
|
return { form, initialValues };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -27,7 +27,21 @@ const element = (tag) =>
|
|||||||
|
|
||||||
export const View = element("div");
|
export const View = element("div");
|
||||||
export const Text = element("span");
|
export const Text = element("span");
|
||||||
export const Button = element("button");
|
export const Button = React.forwardRef(
|
||||||
|
({ children, className, style, onClick, loading, ...props }, ref) =>
|
||||||
|
React.createElement(
|
||||||
|
"button",
|
||||||
|
{
|
||||||
|
...props,
|
||||||
|
ref,
|
||||||
|
className,
|
||||||
|
style,
|
||||||
|
onClick,
|
||||||
|
...(loading ? { "aria-busy": "true" } : {}),
|
||||||
|
},
|
||||||
|
children,
|
||||||
|
),
|
||||||
|
);
|
||||||
export const Input = React.forwardRef(({ onInput, ...props }, ref) =>
|
export const Input = React.forwardRef(({ onInput, ...props }, ref) =>
|
||||||
React.createElement("input", {
|
React.createElement("input", {
|
||||||
...props,
|
...props,
|
||||||
@@ -101,16 +115,18 @@ export const Label = element("label");
|
|||||||
export const Image = React.forwardRef(({ mode, src, style, ...props }, ref) => {
|
export const Image = React.forwardRef(({ mode, src, style, ...props }, ref) => {
|
||||||
const key = React.useContext(TemplateAssetContext);
|
const key = React.useContext(TemplateAssetContext);
|
||||||
const assets = React.useContext(TemplatePreviewAssetsContext);
|
const assets = React.useContext(TemplatePreviewAssetsContext);
|
||||||
|
const normalizedSrc = typeof src === "string" ? src.trim() : "";
|
||||||
|
if (!normalizedSrc) return null;
|
||||||
return React.createElement("img", {
|
return React.createElement("img", {
|
||||||
...props,
|
...props,
|
||||||
ref,
|
ref,
|
||||||
src:
|
src:
|
||||||
assets && typeof src === "string" && src.startsWith("/assets/")
|
assets && normalizedSrc.startsWith("/assets/")
|
||||||
? // 导入包资源以 /assets 开头;本地多模板预览的 renderer 可能额外携带包 key 前缀。
|
? // 导入包资源以 /assets 开头;本地多模板预览的 renderer 可能额外携带包 key 前缀。
|
||||||
(assets[src]?.dataUrl ??
|
(assets[normalizedSrc]?.dataUrl ??
|
||||||
assets[src.replace(`/assets/${key}/`, "/assets/")]?.dataUrl ??
|
assets[normalizedSrc.replace(`/assets/${key}/`, "/assets/")]?.dataUrl ??
|
||||||
src)
|
normalizedSrc)
|
||||||
: resolveImageSource(src, key),
|
: resolveImageSource(normalizedSrc, key),
|
||||||
style: { objectFit: mode === "aspectFit" ? "contain" : "cover", ...style },
|
style: { objectFit: mode === "aspectFit" ? "contain" : "cover", ...style },
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -9,7 +9,7 @@
|
|||||||
"lint": "eslint .",
|
"lint": "eslint .",
|
||||||
"typecheck": "tsc -p tsconfig.json --noEmit",
|
"typecheck": "tsc -p tsconfig.json --noEmit",
|
||||||
"test": "tsx --test test/**/*.test.ts",
|
"test": "tsx --test test/**/*.test.ts",
|
||||||
"test:integration": "pnpm build && node --env-file=.env test/template-contract-migration.integration.mjs && node --env-file=.env test/run-integration.cjs && pnpm --filter @personal-brand/api exec tsx --test test/http.upload.test.js",
|
"test:integration": "pnpm --workspace-root exec turbo run build --filter=@personal-brand/api... && node --env-file=.env test/template-contract-migration.integration.mjs && node --env-file=.env test/run-integration.cjs && pnpm --filter @personal-brand/api exec tsx --test test/http.upload.test.js",
|
||||||
"clean": "rimraf dist",
|
"clean": "rimraf dist",
|
||||||
"start": "node dist/main.js",
|
"start": "node dist/main.js",
|
||||||
"db:generate": "prisma generate",
|
"db:generate": "prisma generate",
|
||||||
|
|||||||
@@ -0,0 +1,28 @@
|
|||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "ClientErrorThrottleWindow" (
|
||||||
|
"subject" TEXT NOT NULL,
|
||||||
|
"windowStart" TIMESTAMP(3) NOT NULL,
|
||||||
|
"count" INTEGER NOT NULL,
|
||||||
|
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "ClientErrorThrottleWindow_pkey" PRIMARY KEY ("subject")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "ClientErrorDedupe" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"subject" TEXT NOT NULL,
|
||||||
|
"errorId" TEXT NOT NULL,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "ClientErrorDedupe_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "ClientErrorThrottleWindow_windowStart_idx" ON "ClientErrorThrottleWindow"("windowStart");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "ClientErrorDedupe_subject_errorId_key" ON "ClientErrorDedupe"("subject", "errorId");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "ClientErrorDedupe_createdAt_idx" ON "ClientErrorDedupe"("createdAt");
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
generator client {
|
generator client {
|
||||||
provider = "prisma-client-js"
|
provider = "prisma-client-js"
|
||||||
binaryTargets = ["linux-musl-openssl-3.0.x", "debian-openssl-3.0.x"]
|
binaryTargets = ["linux-musl-openssl-3.0.x", "debian-openssl-3.0.x", "linux-arm64-openssl-3.0.x"]
|
||||||
}
|
}
|
||||||
|
|
||||||
datasource db {
|
datasource db {
|
||||||
@@ -468,6 +468,25 @@ model AdminUser {
|
|||||||
templateAuditLogs TemplatePackageAuditLog[] @relation("TemplatePackageAuditActor")
|
templateAuditLogs TemplatePackageAuditLog[] @relation("TemplatePackageAuditActor")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
model ClientErrorThrottleWindow {
|
||||||
|
subject String @id
|
||||||
|
windowStart DateTime
|
||||||
|
count Int
|
||||||
|
updatedAt DateTime @updatedAt
|
||||||
|
|
||||||
|
@@index([windowStart])
|
||||||
|
}
|
||||||
|
|
||||||
|
model ClientErrorDedupe {
|
||||||
|
id String @id @default(uuid())
|
||||||
|
subject String
|
||||||
|
errorId String
|
||||||
|
createdAt DateTime @default(now())
|
||||||
|
|
||||||
|
@@unique([subject, errorId])
|
||||||
|
@@index([createdAt])
|
||||||
|
}
|
||||||
|
|
||||||
model TemplatePackage {
|
model TemplatePackage {
|
||||||
id String @id @default(uuid())
|
id String @id @default(uuid())
|
||||||
packageKey String @unique
|
packageKey String @unique
|
||||||
|
|||||||
@@ -4,16 +4,36 @@ import { PrismaService } from "./prisma.service.js";
|
|||||||
import { readAdminToken } from "./admin-access.identity.js";
|
import { readAdminToken } from "./admin-access.identity.js";
|
||||||
import { readIdentity } from "./auth.js";
|
import { readIdentity } from "./auth.js";
|
||||||
|
|
||||||
|
type TokenAccess = {
|
||||||
|
subject: string;
|
||||||
|
brandId: string;
|
||||||
|
mustChangePassword: boolean;
|
||||||
|
tokenVersion: number;
|
||||||
|
platformTemplateRole: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
type BrandAccess = { subject: string; brandId: string; role: string };
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class AdminAccessService {
|
export class AdminAccessService {
|
||||||
|
/**
|
||||||
|
* 同一 HTTP 请求内 Guard 和 Controller 都会调用访问校验。
|
||||||
|
* 用 WeakMap 按请求缓存结果,既避免重复查询,也不会把权限状态跨请求缓存。
|
||||||
|
*/
|
||||||
|
private readonly tokenAccess = new WeakMap<FastifyRequest, Promise<TokenAccess>>();
|
||||||
|
private readonly brandAccess = new WeakMap<FastifyRequest, Promise<BrandAccess>>();
|
||||||
|
|
||||||
constructor(private readonly prisma: PrismaService) {}
|
constructor(private readonly prisma: PrismaService) {}
|
||||||
|
|
||||||
async requireToken(request: FastifyRequest): Promise<{
|
requireToken(request: FastifyRequest): Promise<TokenAccess> {
|
||||||
subject: string;
|
const cached = this.tokenAccess.get(request);
|
||||||
brandId: string;
|
if (cached) return cached;
|
||||||
mustChangePassword: boolean;
|
const pending = this.resolveToken(request);
|
||||||
tokenVersion: number;
|
this.tokenAccess.set(request, pending);
|
||||||
}> {
|
return pending;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async resolveToken(request: FastifyRequest): Promise<TokenAccess> {
|
||||||
const token = readAdminToken(request);
|
const token = readAdminToken(request);
|
||||||
if (!token) throw new UnauthorizedException("缺少管理员登录态");
|
if (!token) throw new UnauthorizedException("缺少管理员登录态");
|
||||||
let identity;
|
let identity;
|
||||||
@@ -25,7 +45,12 @@ export class AdminAccessService {
|
|||||||
if (identity.role !== "admin") throw new ForbiddenException("无管理员权限");
|
if (identity.role !== "admin") throw new ForbiddenException("无管理员权限");
|
||||||
const user = await this.prisma.adminUser.findUnique({
|
const user = await this.prisma.adminUser.findUnique({
|
||||||
where: { id: identity.subject },
|
where: { id: identity.subject },
|
||||||
select: { isEnabled: true, mustChangePassword: true, tokenVersion: true },
|
select: {
|
||||||
|
isEnabled: true,
|
||||||
|
mustChangePassword: true,
|
||||||
|
tokenVersion: true,
|
||||||
|
platformTemplateRole: true,
|
||||||
|
},
|
||||||
});
|
});
|
||||||
if (!user || identity.tokenVersion !== user.tokenVersion)
|
if (!user || identity.tokenVersion !== user.tokenVersion)
|
||||||
throw new UnauthorizedException("管理员登录态已失效,请重新登录");
|
throw new UnauthorizedException("管理员登录态已失效,请重新登录");
|
||||||
@@ -35,12 +60,19 @@ export class AdminAccessService {
|
|||||||
brandId: identity.brandId,
|
brandId: identity.brandId,
|
||||||
mustChangePassword: user.mustChangePassword,
|
mustChangePassword: user.mustChangePassword,
|
||||||
tokenVersion: user.tokenVersion,
|
tokenVersion: user.tokenVersion,
|
||||||
|
platformTemplateRole: user.platformTemplateRole,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
async requireBrand(
|
requireBrand(request: FastifyRequest): Promise<BrandAccess> {
|
||||||
request: FastifyRequest,
|
const cached = this.brandAccess.get(request);
|
||||||
): Promise<{ subject: string; brandId: string; role: string }> {
|
if (cached) return cached;
|
||||||
|
const pending = this.resolveBrand(request);
|
||||||
|
this.brandAccess.set(request, pending);
|
||||||
|
return pending;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async resolveBrand(request: FastifyRequest): Promise<BrandAccess> {
|
||||||
const access = await this.requireToken(request);
|
const access = await this.requireToken(request);
|
||||||
if (access.mustChangePassword)
|
if (access.mustChangePassword)
|
||||||
throw new ForbiddenException("请先完成初始密码修改后再访问管理后台");
|
throw new ForbiddenException("请先完成初始密码修改后再访问管理后台");
|
||||||
@@ -63,11 +95,7 @@ export class AdminAccessService {
|
|||||||
const access = await this.requireToken(request);
|
const access = await this.requireToken(request);
|
||||||
if (access.mustChangePassword)
|
if (access.mustChangePassword)
|
||||||
throw new ForbiddenException("请先完成初始密码修改后再访问管理后台");
|
throw new ForbiddenException("请先完成初始密码修改后再访问管理后台");
|
||||||
const user = await this.prisma.adminUser.findUniqueOrThrow({
|
if (access.platformTemplateRole !== "template_admin")
|
||||||
where: { id: access.subject },
|
|
||||||
select: { platformTemplateRole: true },
|
|
||||||
});
|
|
||||||
if (user.platformTemplateRole !== "template_admin")
|
|
||||||
throw new ForbiddenException("当前账号没有模板管理权限");
|
throw new ForbiddenException("当前账号没有模板管理权限");
|
||||||
return { subject: access.subject };
|
return { subject: access.subject };
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { UnauthorizedException } from "@nestjs/common";
|
import { UnauthorizedException } from "@nestjs/common";
|
||||||
import { createHmac, timingSafeEqual } from "node:crypto";
|
import { createHmac, timingSafeEqual } from "node:crypto";
|
||||||
|
import { isPlaceholderSecret } from "./runtime-config.js";
|
||||||
|
|
||||||
type Identity = {
|
type Identity = {
|
||||||
subject: string;
|
subject: string;
|
||||||
@@ -9,9 +10,20 @@ type Identity = {
|
|||||||
exp: number;
|
exp: number;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
let warnedAboutPlaceholderSecret = false;
|
||||||
|
|
||||||
function secret(): string {
|
function secret(): string {
|
||||||
const value = process.env.SESSION_SECRET;
|
const value = process.env.SESSION_SECRET;
|
||||||
if (!value || value.length < 32) throw new UnauthorizedException("服务端会话密钥未正确配置");
|
if (!value || value.length < 32) throw new UnauthorizedException("服务端会话密钥未正确配置");
|
||||||
|
if (isPlaceholderSecret(value)) {
|
||||||
|
// 生产环境已在启动时 fail fast;这里保留二次防线,避免绕过 createApp 的调用方签发弱 token。
|
||||||
|
if (process.env.NODE_ENV === "production")
|
||||||
|
throw new UnauthorizedException("服务端会话密钥未正确配置");
|
||||||
|
if (!warnedAboutPlaceholderSecret) {
|
||||||
|
warnedAboutPlaceholderSecret = true;
|
||||||
|
console.warn("[api] SESSION_SECRET 仍是示例占位符,仅可用于本地开发");
|
||||||
|
}
|
||||||
|
}
|
||||||
return value;
|
return value;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -6,8 +6,10 @@ import multipart from "@fastify/multipart";
|
|||||||
import fastifyStatic from "@fastify/static";
|
import fastifyStatic from "@fastify/static";
|
||||||
import path from "node:path";
|
import path from "node:path";
|
||||||
import { AppModule, configureApp } from "./app.module.js";
|
import { AppModule, configureApp } from "./app.module.js";
|
||||||
|
import { assertProductionSecret } from "./runtime-config.js";
|
||||||
|
|
||||||
export async function createApp(): Promise<NestFastifyApplication> {
|
export async function createApp(): Promise<NestFastifyApplication> {
|
||||||
|
assertProductionSecret(process.env.SESSION_SECRET);
|
||||||
const app = await NestFactory.create<NestFastifyApplication>(AppModule, new FastifyAdapter());
|
const app = await NestFactory.create<NestFastifyApplication>(AppModule, new FastifyAdapter());
|
||||||
app
|
app
|
||||||
.getHttpAdapter()
|
.getHttpAdapter()
|
||||||
|
|||||||
@@ -1,22 +1,12 @@
|
|||||||
import { AdminBrand } from "../../admin-auth.decorators.js";
|
import { AdminBrand } from "../../admin-auth.decorators.js";
|
||||||
import {
|
import { Body, Controller, Get, Param, Post, Query, Req } from "@nestjs/common";
|
||||||
Body,
|
|
||||||
Controller,
|
|
||||||
ForbiddenException,
|
|
||||||
Get,
|
|
||||||
Param,
|
|
||||||
Post,
|
|
||||||
Query,
|
|
||||||
Req,
|
|
||||||
UnauthorizedException,
|
|
||||||
} from "@nestjs/common";
|
|
||||||
import { Transform } from "class-transformer";
|
import { Transform } from "class-transformer";
|
||||||
import type { TransformFnParams } from "class-transformer";
|
import type { TransformFnParams } from "class-transformer";
|
||||||
import { BookingStatus } from "@prisma/client";
|
import { BookingStatus } from "@prisma/client";
|
||||||
import { IsBoolean, IsEnum, IsOptional, IsString } from "class-validator";
|
import { IsBoolean, IsEnum, IsOptional, IsString } from "class-validator";
|
||||||
import type { FastifyRequest } from "fastify";
|
import type { FastifyRequest } from "fastify";
|
||||||
|
import { AdminAccessService } from "../../admin-access.service.js";
|
||||||
import { BookingService } from "../../booking.service.js";
|
import { BookingService } from "../../booking.service.js";
|
||||||
import { readIdentity } from "../../auth.js";
|
|
||||||
import { UpdateBookingStatusDto, UpdateBookingTagsDto, CreateTagDto } from "../../admin.dto.js";
|
import { UpdateBookingStatusDto, UpdateBookingTagsDto, CreateTagDto } from "../../admin.dto.js";
|
||||||
|
|
||||||
class AdminBookingQueryDto {
|
class AdminBookingQueryDto {
|
||||||
@@ -35,67 +25,67 @@ class AdminBookingQueryDto {
|
|||||||
@AdminBrand()
|
@AdminBrand()
|
||||||
@Controller("admin/bookings")
|
@Controller("admin/bookings")
|
||||||
export class AdminBookingController {
|
export class AdminBookingController {
|
||||||
constructor(private readonly bookings: BookingService) {}
|
constructor(
|
||||||
|
private readonly access: AdminAccessService,
|
||||||
|
private readonly bookings: BookingService,
|
||||||
|
) {}
|
||||||
|
|
||||||
@Get()
|
@Get()
|
||||||
list(@Req() request: FastifyRequest, @Query() query: AdminBookingQueryDto): Promise<unknown> {
|
async list(
|
||||||
const brandId = this.requireAdmin(request);
|
@Req() request: FastifyRequest,
|
||||||
|
@Query() query: AdminBookingQueryDto,
|
||||||
|
): Promise<unknown> {
|
||||||
|
const { brandId } = await this.access.requireBrand(request);
|
||||||
return this.bookings.listForAdmin(brandId, query);
|
return this.bookings.listForAdmin(brandId, query);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Get("unread-count")
|
@Get("unread-count")
|
||||||
unreadCount(@Req() request: FastifyRequest): Promise<unknown> {
|
async unreadCount(@Req() request: FastifyRequest): Promise<unknown> {
|
||||||
return this.bookings.unreadCountForAdmin(this.requireAdmin(request));
|
const { brandId } = await this.access.requireBrand(request);
|
||||||
|
return this.bookings.unreadCountForAdmin(brandId);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Get(":id")
|
@Get(":id")
|
||||||
detail(@Req() request: FastifyRequest, @Param("id") id: string): Promise<unknown> {
|
async detail(@Req() request: FastifyRequest, @Param("id") id: string): Promise<unknown> {
|
||||||
return this.bookings.getForAdmin(this.requireAdmin(request), id);
|
const { brandId } = await this.access.requireBrand(request);
|
||||||
|
return this.bookings.getForAdmin(brandId, id);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Post(":id/status")
|
@Post(":id/status")
|
||||||
update(
|
async update(
|
||||||
@Req() request: FastifyRequest,
|
@Req() request: FastifyRequest,
|
||||||
@Param("id") id: string,
|
@Param("id") id: string,
|
||||||
@Body() body: UpdateBookingStatusDto,
|
@Body() body: UpdateBookingStatusDto,
|
||||||
): Promise<unknown> {
|
): Promise<unknown> {
|
||||||
return this.bookings.updateStatus(this.requireAdmin(request), id, body.status, body.adminNote);
|
const { brandId } = await this.access.requireBrand(request);
|
||||||
|
return this.bookings.updateStatus(brandId, id, body.status, body.adminNote);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Post(":id/read")
|
@Post(":id/read")
|
||||||
markRead(@Req() request: FastifyRequest, @Param("id") id: string): Promise<unknown> {
|
async markRead(@Req() request: FastifyRequest, @Param("id") id: string): Promise<unknown> {
|
||||||
return this.bookings.markRead(this.requireAdmin(request), id);
|
const { brandId } = await this.access.requireBrand(request);
|
||||||
|
return this.bookings.markRead(brandId, id);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Post(":id/tags")
|
@Post(":id/tags")
|
||||||
updateTags(
|
async updateTags(
|
||||||
@Req() request: FastifyRequest,
|
@Req() request: FastifyRequest,
|
||||||
@Param("id") id: string,
|
@Param("id") id: string,
|
||||||
@Body() body: UpdateBookingTagsDto,
|
@Body() body: UpdateBookingTagsDto,
|
||||||
): Promise<unknown> {
|
): Promise<unknown> {
|
||||||
return this.bookings.updateTags(this.requireAdmin(request), id, body.tagIds);
|
const { brandId } = await this.access.requireBrand(request);
|
||||||
|
return this.bookings.updateTags(brandId, id, body.tagIds);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Get("tags")
|
@Get("tags")
|
||||||
listTags(@Req() request: FastifyRequest): Promise<unknown> {
|
async listTags(@Req() request: FastifyRequest): Promise<unknown> {
|
||||||
return this.bookings.listTags(this.requireAdmin(request));
|
const { brandId } = await this.access.requireBrand(request);
|
||||||
|
return this.bookings.listTags(brandId);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Post("tags")
|
@Post("tags")
|
||||||
createTag(@Req() request: FastifyRequest, @Body() body: CreateTagDto): Promise<unknown> {
|
async createTag(@Req() request: FastifyRequest, @Body() body: CreateTagDto): Promise<unknown> {
|
||||||
return this.bookings.createTag(this.requireAdmin(request), body.name);
|
const { brandId } = await this.access.requireBrand(request);
|
||||||
}
|
return this.bookings.createTag(brandId, body.name);
|
||||||
|
|
||||||
private requireAdmin(request: FastifyRequest): string {
|
|
||||||
const token = request.headers.authorization?.replace(/^Bearer\s+/i, "");
|
|
||||||
if (!token) throw new UnauthorizedException("缺少管理员登录态");
|
|
||||||
let identity;
|
|
||||||
try {
|
|
||||||
identity = readIdentity(token);
|
|
||||||
} catch {
|
|
||||||
throw new UnauthorizedException("管理员登录态无效或已过期");
|
|
||||||
}
|
|
||||||
if (identity.role !== "admin") throw new ForbiddenException("无管理员权限");
|
|
||||||
return identity.brandId;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,9 +1,9 @@
|
|||||||
import { HttpException, Injectable } from "@nestjs/common";
|
import { Inject, Injectable } from "@nestjs/common";
|
||||||
|
import {
|
||||||
|
CLIENT_ERROR_THROTTLE_STORE,
|
||||||
|
type ClientErrorThrottleStore,
|
||||||
|
} from "./client-error-throttle.store.js";
|
||||||
|
|
||||||
const RATE_WINDOW_MS = 60_000;
|
|
||||||
const RATE_LIMIT = 10;
|
|
||||||
const DEDUPE_TTL_MS = 10 * 60_000;
|
|
||||||
const DEDUPE_CAPACITY = 500;
|
|
||||||
const LOG_STACK_LIMIT = 4000;
|
const LOG_STACK_LIMIT = 4000;
|
||||||
|
|
||||||
export interface ClientErrorReport {
|
export interface ClientErrorReport {
|
||||||
@@ -22,27 +22,16 @@ export interface ClientErrorReceipt {
|
|||||||
duplicate: boolean;
|
duplicate: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* 后台渲染异常去重与限流。
|
|
||||||
* 当前生产为单实例 PM2,因此使用进程内窗口;扩成多实例前需要换成共享存储。
|
|
||||||
*/
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class AdminClientErrorService {
|
export class AdminClientErrorService {
|
||||||
private readonly recentErrorIds = new Map<string, number>();
|
constructor(
|
||||||
private readonly windows = new Map<string, number[]>();
|
@Inject(CLIENT_ERROR_THROTTLE_STORE)
|
||||||
|
private readonly throttle: ClientErrorThrottleStore,
|
||||||
|
) {}
|
||||||
|
|
||||||
record(report: ClientErrorReport): ClientErrorReceipt {
|
async record(report: ClientErrorReport): Promise<ClientErrorReceipt> {
|
||||||
const now = Date.now();
|
const result = await this.throttle.record(report);
|
||||||
this.prune(now);
|
if (result.duplicate) return { received: true, duplicate: true };
|
||||||
|
|
||||||
const dedupeKey = `${report.subject}:${report.errorId}`;
|
|
||||||
if (this.recentErrorIds.has(dedupeKey)) {
|
|
||||||
return { received: true, duplicate: true };
|
|
||||||
}
|
|
||||||
|
|
||||||
this.assertWithinRate(report.subject, now);
|
|
||||||
this.recentErrorIds.set(dedupeKey, now);
|
|
||||||
this.trimDedupe();
|
|
||||||
|
|
||||||
console.error("admin client error", {
|
console.error("admin client error", {
|
||||||
errorId: report.errorId,
|
errorId: report.errorId,
|
||||||
@@ -57,35 +46,4 @@ export class AdminClientErrorService {
|
|||||||
|
|
||||||
return { received: true, duplicate: false };
|
return { received: true, duplicate: false };
|
||||||
}
|
}
|
||||||
|
|
||||||
private assertWithinRate(subject: string, now: number): void {
|
|
||||||
const recent = (this.windows.get(subject) ?? []).filter(
|
|
||||||
(timestamp) => now - timestamp < RATE_WINDOW_MS,
|
|
||||||
);
|
|
||||||
if (recent.length >= RATE_LIMIT) {
|
|
||||||
this.windows.set(subject, recent);
|
|
||||||
throw new HttpException("客户端错误上报过于频繁,请稍后再试", 429);
|
|
||||||
}
|
|
||||||
recent.push(now);
|
|
||||||
this.windows.set(subject, recent);
|
|
||||||
}
|
|
||||||
|
|
||||||
private prune(now: number): void {
|
|
||||||
for (const [key, timestamp] of this.recentErrorIds) {
|
|
||||||
if (now - timestamp >= DEDUPE_TTL_MS) this.recentErrorIds.delete(key);
|
|
||||||
}
|
|
||||||
for (const [subject, timestamps] of this.windows) {
|
|
||||||
const recent = timestamps.filter((timestamp) => now - timestamp < RATE_WINDOW_MS);
|
|
||||||
if (recent.length === 0) this.windows.delete(subject);
|
|
||||||
else this.windows.set(subject, recent);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private trimDedupe(): void {
|
|
||||||
while (this.recentErrorIds.size > DEDUPE_CAPACITY) {
|
|
||||||
const oldest = this.recentErrorIds.keys().next();
|
|
||||||
if (oldest.done) return;
|
|
||||||
this.recentErrorIds.delete(oldest.value);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -7,7 +7,7 @@ import {
|
|||||||
UpdateBrandPresentationDto,
|
UpdateBrandPresentationDto,
|
||||||
UpdateTrustContentDto,
|
UpdateTrustContentDto,
|
||||||
} from "../../admin.dto.js";
|
} from "../../admin.dto.js";
|
||||||
import { TemplateWorkspaceService } from "../../template-workspace.service.js";
|
import { TrustContentService } from "../../template/trust-content.service.js";
|
||||||
import { requireAdminIdentity } from "../../admin-access.identity.js";
|
import { requireAdminIdentity } from "../../admin-access.identity.js";
|
||||||
import { AdminBrandConfigService } from "./admin-brand-config.service.js";
|
import { AdminBrandConfigService } from "./admin-brand-config.service.js";
|
||||||
|
|
||||||
@@ -15,7 +15,7 @@ import { AdminBrandConfigService } from "./admin-brand-config.service.js";
|
|||||||
@Controller("admin/config")
|
@Controller("admin/config")
|
||||||
export class AdminConfigController {
|
export class AdminConfigController {
|
||||||
constructor(
|
constructor(
|
||||||
private readonly templateWorkspace: TemplateWorkspaceService,
|
private readonly trustContent: TrustContentService,
|
||||||
private readonly brandConfig: AdminBrandConfigService,
|
private readonly brandConfig: AdminBrandConfigService,
|
||||||
) {}
|
) {}
|
||||||
@Get("brand")
|
@Get("brand")
|
||||||
@@ -42,7 +42,7 @@ export class AdminConfigController {
|
|||||||
@Get("trust-content")
|
@Get("trust-content")
|
||||||
listTrustContent(@Req() request: FastifyRequest): Promise<unknown> {
|
listTrustContent(@Req() request: FastifyRequest): Promise<unknown> {
|
||||||
const identity = requireAdminIdentity(request);
|
const identity = requireAdminIdentity(request);
|
||||||
return this.templateWorkspace.listTrustContent(identity.brandId);
|
return this.trustContent.listTrustContent(identity.brandId);
|
||||||
}
|
}
|
||||||
@Post("trust-content")
|
@Post("trust-content")
|
||||||
createTrustContent(
|
createTrustContent(
|
||||||
@@ -50,7 +50,7 @@ export class AdminConfigController {
|
|||||||
@Body() body: CreateTrustContentDto,
|
@Body() body: CreateTrustContentDto,
|
||||||
): Promise<unknown> {
|
): Promise<unknown> {
|
||||||
const identity = requireAdminIdentity(request);
|
const identity = requireAdminIdentity(request);
|
||||||
return this.templateWorkspace.createTrustContent(identity.brandId, body);
|
return this.trustContent.createTrustContent(identity.brandId, body);
|
||||||
}
|
}
|
||||||
@Patch("trust-content/:id")
|
@Patch("trust-content/:id")
|
||||||
updateTrustContent(
|
updateTrustContent(
|
||||||
@@ -59,7 +59,7 @@ export class AdminConfigController {
|
|||||||
@Body() body: UpdateTrustContentDto,
|
@Body() body: UpdateTrustContentDto,
|
||||||
): Promise<unknown> {
|
): Promise<unknown> {
|
||||||
const identity = requireAdminIdentity(request);
|
const identity = requireAdminIdentity(request);
|
||||||
return this.templateWorkspace.updateTrustContent(identity.brandId, id, body);
|
return this.trustContent.updateTrustContent(identity.brandId, id, body);
|
||||||
}
|
}
|
||||||
@Delete("trust-content/:id")
|
@Delete("trust-content/:id")
|
||||||
async deleteTrustContent(
|
async deleteTrustContent(
|
||||||
@@ -67,6 +67,6 @@ export class AdminConfigController {
|
|||||||
@Param("id") id: string,
|
@Param("id") id: string,
|
||||||
): Promise<unknown> {
|
): Promise<unknown> {
|
||||||
const identity = requireAdminIdentity(request);
|
const identity = requireAdminIdentity(request);
|
||||||
return this.templateWorkspace.deleteTrustContent(identity.brandId, id);
|
return this.trustContent.deleteTrustContent(identity.brandId, id);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -4,6 +4,9 @@ import { InfrastructureModule } from "../infrastructure.module.js";
|
|||||||
import { AdminBookingController } from "./admin-booking.controller.js";
|
import { AdminBookingController } from "./admin-booking.controller.js";
|
||||||
import { AdminClientErrorController } from "./admin-client-error.controller.js";
|
import { AdminClientErrorController } from "./admin-client-error.controller.js";
|
||||||
import { AdminClientErrorService } from "./admin-client-error.service.js";
|
import { AdminClientErrorService } from "./admin-client-error.service.js";
|
||||||
|
import { createClientErrorThrottleStore } from "./client-error-throttle.factory.js";
|
||||||
|
import { CLIENT_ERROR_THROTTLE_STORE } from "./client-error-throttle.store.js";
|
||||||
|
import { PrismaService } from "../../prisma.service.js";
|
||||||
import { AdminBrandConfigService } from "./admin-brand-config.service.js";
|
import { AdminBrandConfigService } from "./admin-brand-config.service.js";
|
||||||
import { AdminConfigController } from "./admin-config.controller.js";
|
import { AdminConfigController } from "./admin-config.controller.js";
|
||||||
import { AdminLocalUploadController } from "./admin-local-upload.controller.js";
|
import { AdminLocalUploadController } from "./admin-local-upload.controller.js";
|
||||||
@@ -47,6 +50,11 @@ import { AdminTemplatePreviewAssetsService } from "./admin-template-preview-asse
|
|||||||
AdminTemplatePreviewService,
|
AdminTemplatePreviewService,
|
||||||
AdminTemplatePreviewAssetsService,
|
AdminTemplatePreviewAssetsService,
|
||||||
TemplateOperationMetricsService,
|
TemplateOperationMetricsService,
|
||||||
|
{
|
||||||
|
provide: CLIENT_ERROR_THROTTLE_STORE,
|
||||||
|
useFactory: (prisma: PrismaService) => createClientErrorThrottleStore(prisma),
|
||||||
|
inject: [PrismaService],
|
||||||
|
},
|
||||||
AdminClientErrorService,
|
AdminClientErrorService,
|
||||||
],
|
],
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -0,0 +1,20 @@
|
|||||||
|
import type { PrismaService } from "../../prisma.service.js";
|
||||||
|
import { PostgresClientErrorThrottleStore } from "./client-error-throttle.postgres.store.js";
|
||||||
|
import {
|
||||||
|
MemoryClientErrorThrottleStore,
|
||||||
|
type ClientErrorThrottleStore,
|
||||||
|
} from "./client-error-throttle.store.js";
|
||||||
|
|
||||||
|
export function createClientErrorThrottleStore(
|
||||||
|
prisma: PrismaService,
|
||||||
|
mode = process.env.CLIENT_ERROR_THROTTLE_STORE ?? "memory",
|
||||||
|
): ClientErrorThrottleStore {
|
||||||
|
switch (mode) {
|
||||||
|
case "memory":
|
||||||
|
return new MemoryClientErrorThrottleStore();
|
||||||
|
case "postgres":
|
||||||
|
return new PostgresClientErrorThrottleStore(prisma);
|
||||||
|
default:
|
||||||
|
throw new Error(`Unsupported CLIENT_ERROR_THROTTLE_STORE: ${mode}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,94 @@
|
|||||||
|
import { randomUUID } from "node:crypto";
|
||||||
|
import { HttpException } from "@nestjs/common";
|
||||||
|
import { Prisma } from "@prisma/client";
|
||||||
|
import type { PrismaService } from "../../prisma.service.js";
|
||||||
|
import {
|
||||||
|
CLIENT_ERROR_DEDUPE_TTL_MS,
|
||||||
|
CLIENT_ERROR_RATE_LIMIT,
|
||||||
|
CLIENT_ERROR_RATE_WINDOW_MS,
|
||||||
|
type ClientErrorThrottleReport,
|
||||||
|
type ClientErrorThrottleResult,
|
||||||
|
type ClientErrorThrottleStore,
|
||||||
|
} from "./client-error-throttle.store.js";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 多实例部署使用的共享存储实现。
|
||||||
|
* 去重与限流在同一事务中执行:限流拒绝时不会留下已去重标记。
|
||||||
|
*/
|
||||||
|
export class PostgresClientErrorThrottleStore implements ClientErrorThrottleStore {
|
||||||
|
private lastCleanupAt = 0;
|
||||||
|
|
||||||
|
constructor(private readonly prisma: PrismaService) {}
|
||||||
|
|
||||||
|
async record(
|
||||||
|
report: ClientErrorThrottleReport,
|
||||||
|
now = Date.now(),
|
||||||
|
): Promise<ClientErrorThrottleResult> {
|
||||||
|
const cutoff = new Date(now - CLIENT_ERROR_DEDUPE_TTL_MS);
|
||||||
|
const windowStart = new Date(
|
||||||
|
Math.floor(now / CLIENT_ERROR_RATE_WINDOW_MS) * CLIENT_ERROR_RATE_WINDOW_MS,
|
||||||
|
);
|
||||||
|
const recordedAt = new Date(now);
|
||||||
|
let duplicate = false;
|
||||||
|
|
||||||
|
await this.prisma.$transaction(async (transaction) => {
|
||||||
|
const inserted = await transaction.$queryRaw<Array<{ id: string }>>(Prisma.sql`
|
||||||
|
INSERT INTO "ClientErrorDedupe" ("id", "subject", "errorId", "createdAt")
|
||||||
|
VALUES (${randomUUID()}, ${report.subject}, ${report.errorId}, ${recordedAt})
|
||||||
|
ON CONFLICT ("subject", "errorId") DO UPDATE SET
|
||||||
|
"createdAt" = EXCLUDED."createdAt"
|
||||||
|
WHERE "ClientErrorDedupe"."createdAt" < ${cutoff}
|
||||||
|
RETURNING "id"
|
||||||
|
`);
|
||||||
|
if (!inserted.length) {
|
||||||
|
duplicate = true;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const rows = await transaction.$queryRaw<Array<{ count: number }>>(Prisma.sql`
|
||||||
|
INSERT INTO "ClientErrorThrottleWindow" ("subject", "windowStart", "count", "updatedAt")
|
||||||
|
VALUES (${report.subject}, ${windowStart}, 1, ${recordedAt})
|
||||||
|
ON CONFLICT ("subject") DO UPDATE SET
|
||||||
|
"count" = CASE
|
||||||
|
WHEN EXCLUDED."windowStart" > "ClientErrorThrottleWindow"."windowStart"
|
||||||
|
THEN 1
|
||||||
|
WHEN EXCLUDED."windowStart" = "ClientErrorThrottleWindow"."windowStart"
|
||||||
|
THEN LEAST("ClientErrorThrottleWindow"."count" + 1, ${CLIENT_ERROR_RATE_LIMIT + 1})
|
||||||
|
ELSE "ClientErrorThrottleWindow"."count"
|
||||||
|
END,
|
||||||
|
"windowStart" = GREATEST(
|
||||||
|
"ClientErrorThrottleWindow"."windowStart",
|
||||||
|
EXCLUDED."windowStart"
|
||||||
|
),
|
||||||
|
"updatedAt" = EXCLUDED."updatedAt"
|
||||||
|
RETURNING "count"
|
||||||
|
`);
|
||||||
|
if (Number(rows[0]?.count ?? 1) > CLIENT_ERROR_RATE_LIMIT) {
|
||||||
|
throw new HttpException("客户端错误上报过于频繁,请稍后再试", 429);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
await this.cleanupIfNeeded(cutoff, windowStart, now);
|
||||||
|
return { duplicate };
|
||||||
|
}
|
||||||
|
|
||||||
|
private async cleanupIfNeeded(cutoff: Date, windowStart: Date, now: number): Promise<void> {
|
||||||
|
if (now - this.lastCleanupAt < CLIENT_ERROR_RATE_WINDOW_MS) return;
|
||||||
|
this.lastCleanupAt = now;
|
||||||
|
try {
|
||||||
|
await Promise.all([
|
||||||
|
this.prisma.clientErrorDedupe.deleteMany({ where: { createdAt: { lt: cutoff } } }),
|
||||||
|
this.prisma.clientErrorThrottleWindow.deleteMany({
|
||||||
|
where: {
|
||||||
|
windowStart: {
|
||||||
|
lt: new Date(windowStart.getTime() - CLIENT_ERROR_RATE_WINDOW_MS),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
]);
|
||||||
|
} catch (error) {
|
||||||
|
// 清理失败不能影响诊断上报本身,下一分钟会再次尝试。
|
||||||
|
console.warn("[api] client error throttle cleanup failed", error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
import { HttpException } from "@nestjs/common";
|
||||||
|
|
||||||
|
export const CLIENT_ERROR_RATE_WINDOW_MS = 60_000;
|
||||||
|
export const CLIENT_ERROR_RATE_LIMIT = 10;
|
||||||
|
export const CLIENT_ERROR_DEDUPE_TTL_MS = 10 * 60_000;
|
||||||
|
export const CLIENT_ERROR_DEDUPE_CAPACITY = 500;
|
||||||
|
export const CLIENT_ERROR_THROTTLE_STORE = Symbol("CLIENT_ERROR_THROTTLE_STORE");
|
||||||
|
|
||||||
|
export interface ClientErrorThrottleReport {
|
||||||
|
subject: string;
|
||||||
|
errorId: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ClientErrorThrottleResult {
|
||||||
|
duplicate: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ClientErrorThrottleStore {
|
||||||
|
record(report: ClientErrorThrottleReport, now?: number): Promise<ClientErrorThrottleResult>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 单实例部署使用的进程内实现;多实例必须切换为共享存储。 */
|
||||||
|
export class MemoryClientErrorThrottleStore implements ClientErrorThrottleStore {
|
||||||
|
private readonly recentErrorIds = new Map<string, number>();
|
||||||
|
private readonly windows = new Map<string, number[]>();
|
||||||
|
|
||||||
|
record(report: ClientErrorThrottleReport, now = Date.now()): Promise<ClientErrorThrottleResult> {
|
||||||
|
this.prune(now);
|
||||||
|
|
||||||
|
const dedupeKey = `${report.subject}:${report.errorId}`;
|
||||||
|
if (this.recentErrorIds.has(dedupeKey)) return Promise.resolve({ duplicate: true });
|
||||||
|
|
||||||
|
this.assertWithinRate(report.subject, now);
|
||||||
|
this.recentErrorIds.set(dedupeKey, now);
|
||||||
|
this.trimDedupe();
|
||||||
|
return Promise.resolve({ duplicate: false });
|
||||||
|
}
|
||||||
|
|
||||||
|
private assertWithinRate(subject: string, now: number): void {
|
||||||
|
const recent = (this.windows.get(subject) ?? []).filter(
|
||||||
|
(timestamp) => now - timestamp < CLIENT_ERROR_RATE_WINDOW_MS,
|
||||||
|
);
|
||||||
|
if (recent.length >= CLIENT_ERROR_RATE_LIMIT) {
|
||||||
|
this.windows.set(subject, recent);
|
||||||
|
throw new HttpException("客户端错误上报过于频繁,请稍后再试", 429);
|
||||||
|
}
|
||||||
|
recent.push(now);
|
||||||
|
this.windows.set(subject, recent);
|
||||||
|
}
|
||||||
|
|
||||||
|
private prune(now: number): void {
|
||||||
|
for (const [key, timestamp] of this.recentErrorIds) {
|
||||||
|
if (now - timestamp >= CLIENT_ERROR_DEDUPE_TTL_MS) this.recentErrorIds.delete(key);
|
||||||
|
}
|
||||||
|
for (const [subject, timestamps] of this.windows) {
|
||||||
|
const recent = timestamps.filter(
|
||||||
|
(timestamp) => now - timestamp < CLIENT_ERROR_RATE_WINDOW_MS,
|
||||||
|
);
|
||||||
|
if (recent.length === 0) this.windows.delete(subject);
|
||||||
|
else this.windows.set(subject, recent);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private trimDedupe(): void {
|
||||||
|
while (this.recentErrorIds.size > CLIENT_ERROR_DEDUPE_CAPACITY) {
|
||||||
|
const oldest = this.recentErrorIds.keys().next();
|
||||||
|
if (oldest.done) return;
|
||||||
|
this.recentErrorIds.delete(oldest.value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,7 +4,9 @@ import { AdminMembershipGuard } from "../admin-membership.guard.js";
|
|||||||
import { BrandReleaseApiService } from "../brand-release-api.service.js";
|
import { BrandReleaseApiService } from "../brand-release-api.service.js";
|
||||||
import { BrandReleaseService } from "../brand-release.service.js";
|
import { BrandReleaseService } from "../brand-release.service.js";
|
||||||
import { PrismaService } from "../prisma.service.js";
|
import { PrismaService } from "../prisma.service.js";
|
||||||
import { TemplateWorkspaceService } from "../template-workspace.service.js";
|
import { PageSchemeService } from "../template/page-scheme.service.js";
|
||||||
|
import { TemplateInstallationService } from "../template/template-installation.service.js";
|
||||||
|
import { TrustContentService } from "../template/trust-content.service.js";
|
||||||
import { WechatAuthService } from "../wechat-auth.js";
|
import { WechatAuthService } from "../wechat-auth.js";
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
@@ -15,7 +17,9 @@ import { WechatAuthService } from "../wechat-auth.js";
|
|||||||
AdminMembershipGuard,
|
AdminMembershipGuard,
|
||||||
BrandReleaseService,
|
BrandReleaseService,
|
||||||
BrandReleaseApiService,
|
BrandReleaseApiService,
|
||||||
TemplateWorkspaceService,
|
PageSchemeService,
|
||||||
|
TemplateInstallationService,
|
||||||
|
TrustContentService,
|
||||||
],
|
],
|
||||||
exports: [
|
exports: [
|
||||||
PrismaService,
|
PrismaService,
|
||||||
@@ -24,7 +28,9 @@ import { WechatAuthService } from "../wechat-auth.js";
|
|||||||
AdminMembershipGuard,
|
AdminMembershipGuard,
|
||||||
BrandReleaseService,
|
BrandReleaseService,
|
||||||
BrandReleaseApiService,
|
BrandReleaseApiService,
|
||||||
TemplateWorkspaceService,
|
PageSchemeService,
|
||||||
|
TemplateInstallationService,
|
||||||
|
TrustContentService,
|
||||||
],
|
],
|
||||||
})
|
})
|
||||||
export class InfrastructureModule {}
|
export class InfrastructureModule {}
|
||||||
@@ -14,7 +14,8 @@ import type {
|
|||||||
CreateBrandMemberDto,
|
CreateBrandMemberDto,
|
||||||
UpdateBrandMemberDto,
|
UpdateBrandMemberDto,
|
||||||
} from "../../admin.dto.js";
|
} from "../../admin.dto.js";
|
||||||
import { TemplateWorkspaceService } from "../../template-workspace.service.js";
|
import { PageSchemeService } from "../../template/page-scheme.service.js";
|
||||||
|
import { TemplateInstallationService } from "../../template/template-installation.service.js";
|
||||||
|
|
||||||
type AdminIdentity = { subject: string; brandId: string; tokenVersion?: number };
|
type AdminIdentity = { subject: string; brandId: string; tokenVersion?: number };
|
||||||
|
|
||||||
@@ -22,11 +23,12 @@ type AdminIdentity = { subject: string; brandId: string; tokenVersion?: number }
|
|||||||
export class TenantService {
|
export class TenantService {
|
||||||
constructor(
|
constructor(
|
||||||
private readonly prisma: PrismaService,
|
private readonly prisma: PrismaService,
|
||||||
private readonly templateWorkspace: TemplateWorkspaceService,
|
private readonly pageSchemes: PageSchemeService,
|
||||||
|
private readonly templateInstallations: TemplateInstallationService,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
async getCreationOptions() {
|
async getCreationOptions() {
|
||||||
const catalog = await this.templateWorkspace.getPageSchemeCatalog();
|
const catalog = await this.pageSchemes.getPageSchemeCatalog();
|
||||||
// 创建品牌只应从每个页面方案的最新已发布版本开始;旧版本仍可在页面方案页显式切换。
|
// 创建品牌只应从每个页面方案的最新已发布版本开始;旧版本仍可在页面方案页显式切换。
|
||||||
return {
|
return {
|
||||||
...catalog,
|
...catalog,
|
||||||
@@ -40,7 +42,7 @@ export class TenantService {
|
|||||||
const name = body.name.trim();
|
const name = body.name.trim();
|
||||||
const slug = body.slug.trim();
|
const slug = body.slug.trim();
|
||||||
if (!name || !slug) throw new BadRequestException("品牌名称和小程序地址标识不能为空");
|
if (!name || !slug) throw new BadRequestException("品牌名称和小程序地址标识不能为空");
|
||||||
const packageVersion = await this.templateWorkspace.resolveInstallablePackageVersion(
|
const packageVersion = await this.templateInstallations.resolveInstallablePackageVersion(
|
||||||
body.businessType,
|
body.businessType,
|
||||||
body.templatePackageVersionId,
|
body.templatePackageVersionId,
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -2,24 +2,28 @@ import { AdminBrand, AdminRoles } from "../../admin-auth.decorators.js";
|
|||||||
import { Body, Controller, Get, Post, Req } from "@nestjs/common";
|
import { Body, Controller, Get, Post, Req } from "@nestjs/common";
|
||||||
import type { FastifyRequest } from "fastify";
|
import type { FastifyRequest } from "fastify";
|
||||||
import { RollbackTemplateDto, UpgradeTemplateDto } from "../../admin.dto.js";
|
import { RollbackTemplateDto, UpgradeTemplateDto } from "../../admin.dto.js";
|
||||||
import { TemplateWorkspaceService } from "../../template-workspace.service.js";
|
import { PageSchemeService } from "../../template/page-scheme.service.js";
|
||||||
|
import { TemplateInstallationService } from "../../template/template-installation.service.js";
|
||||||
import { requireAdminIdentity } from "../../admin-access.identity.js";
|
import { requireAdminIdentity } from "../../admin-access.identity.js";
|
||||||
|
|
||||||
@AdminBrand()
|
@AdminBrand()
|
||||||
@Controller("admin/workspace")
|
@Controller("admin/workspace")
|
||||||
class AdminTemplateController {
|
class AdminTemplateController {
|
||||||
constructor(private readonly templateWorkspace: TemplateWorkspaceService) {}
|
constructor(
|
||||||
|
private readonly pageSchemes: PageSchemeService,
|
||||||
|
private readonly templateInstallations: TemplateInstallationService,
|
||||||
|
) {}
|
||||||
|
|
||||||
@AdminRoles(["owner", "admin", "platform-admin"])
|
@AdminRoles(["owner", "admin", "platform-admin"])
|
||||||
@Get("template/options")
|
@Get("template/options")
|
||||||
options(@Req() request: FastifyRequest): Promise<unknown> {
|
options(@Req() request: FastifyRequest): Promise<unknown> {
|
||||||
return this.templateWorkspace.getPageSchemeOptions(requireAdminIdentity(request).brandId);
|
return this.pageSchemes.getPageSchemeOptions(requireAdminIdentity(request).brandId);
|
||||||
}
|
}
|
||||||
|
|
||||||
@AdminRoles(["owner", "admin", "platform-admin"])
|
@AdminRoles(["owner", "admin", "platform-admin"])
|
||||||
@Get("template/preview")
|
@Get("template/preview")
|
||||||
preview(@Req() request: FastifyRequest): Promise<unknown> {
|
preview(@Req() request: FastifyRequest): Promise<unknown> {
|
||||||
return this.templateWorkspace.preview(requireAdminIdentity(request).brandId);
|
return this.templateInstallations.preview(requireAdminIdentity(request).brandId);
|
||||||
}
|
}
|
||||||
|
|
||||||
@AdminRoles(["owner", "admin", "platform-admin"])
|
@AdminRoles(["owner", "admin", "platform-admin"])
|
||||||
@@ -30,7 +34,7 @@ class AdminTemplateController {
|
|||||||
): Promise<unknown> {
|
): Promise<unknown> {
|
||||||
const identity = requireAdminIdentity(request);
|
const identity = requireAdminIdentity(request);
|
||||||
const requestId = request.headers["x-request-id"]?.toString() ?? request.id;
|
const requestId = request.headers["x-request-id"]?.toString() ?? request.id;
|
||||||
return this.templateWorkspace.upgrade(identity.brandId, body, identity.subject, requestId);
|
return this.templateInstallations.upgrade(identity.brandId, body, identity.subject, requestId);
|
||||||
}
|
}
|
||||||
|
|
||||||
@AdminRoles(["owner", "admin", "platform-admin"])
|
@AdminRoles(["owner", "admin", "platform-admin"])
|
||||||
@@ -41,7 +45,7 @@ class AdminTemplateController {
|
|||||||
): Promise<unknown> {
|
): Promise<unknown> {
|
||||||
const identity = requireAdminIdentity(request);
|
const identity = requireAdminIdentity(request);
|
||||||
const requestId = request.headers["x-request-id"]?.toString() ?? request.id;
|
const requestId = request.headers["x-request-id"]?.toString() ?? request.id;
|
||||||
return this.templateWorkspace.rollback(identity.brandId, identity.subject, body, requestId);
|
return this.templateInstallations.rollback(identity.brandId, identity.subject, body, requestId);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -8,19 +8,19 @@ import {
|
|||||||
validateCapabilityConfig,
|
validateCapabilityConfig,
|
||||||
} from "@personal-brand/config";
|
} from "@personal-brand/config";
|
||||||
import { PrismaService } from "../../prisma.service.js";
|
import { PrismaService } from "../../prisma.service.js";
|
||||||
import { TemplateWorkspaceService } from "../../template-workspace.service.js";
|
import { TemplateInstallationService } from "../../template/template-installation.service.js";
|
||||||
import type { UpdateCapabilityInstallationDto } from "../../admin.dto.js";
|
import type { UpdateCapabilityInstallationDto } from "../../admin.dto.js";
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class AdminWorkspaceCapabilitiesService {
|
export class AdminWorkspaceCapabilitiesService {
|
||||||
constructor(
|
constructor(
|
||||||
private readonly prisma: PrismaService,
|
private readonly prisma: PrismaService,
|
||||||
private readonly templateWorkspace: TemplateWorkspaceService,
|
private readonly templateInstallations: TemplateInstallationService,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
async list(brandId: string) {
|
async list(brandId: string) {
|
||||||
const [templateKey, installations] = await Promise.all([
|
const [templateKey, installations] = await Promise.all([
|
||||||
this.templateWorkspace.getEffectiveTemplateKey(brandId),
|
this.templateInstallations.getEffectiveTemplateKey(brandId),
|
||||||
this.prisma.capabilityInstallation.findMany({ where: { brandId } }),
|
this.prisma.capabilityInstallation.findMany({ where: { brandId } }),
|
||||||
]);
|
]);
|
||||||
const installed = new Map(installations.map((item) => [item.capabilityKey, item]));
|
const installed = new Map(installations.map((item) => [item.capabilityKey, item]));
|
||||||
@@ -54,7 +54,7 @@ export class AdminWorkspaceCapabilitiesService {
|
|||||||
body: UpdateCapabilityInstallationDto,
|
body: UpdateCapabilityInstallationDto,
|
||||||
) {
|
) {
|
||||||
const template = getBrandTemplate(
|
const template = getBrandTemplate(
|
||||||
await this.templateWorkspace.getEffectiveTemplateKey(brandId),
|
await this.templateInstallations.getEffectiveTemplateKey(brandId),
|
||||||
);
|
);
|
||||||
if (!template?.capabilities.includes(key as never) && !(key in capabilityPlugins))
|
if (!template?.capabilities.includes(key as never) && !(key in capabilityPlugins))
|
||||||
throw new BadRequestException("能力未被当前模板声明");
|
throw new BadRequestException("能力未被当前模板声明");
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import { AdminBrand, AdminRoles } from "../../admin-auth.decorators.js";
|
|||||||
import { Controller, Get, Post, Body, Req } from "@nestjs/common";
|
import { Controller, Get, Post, Body, Req } from "@nestjs/common";
|
||||||
import type { FastifyRequest } from "fastify";
|
import type { FastifyRequest } from "fastify";
|
||||||
import { InstallTemplateDto, SelectTemplateVersionDto } from "../../admin.dto.js";
|
import { InstallTemplateDto, SelectTemplateVersionDto } from "../../admin.dto.js";
|
||||||
import { TemplateWorkspaceService } from "../../template-workspace.service.js";
|
import { TemplateInstallationService } from "../../template/template-installation.service.js";
|
||||||
import { requireAdminIdentity } from "../../admin-access.identity.js";
|
import { requireAdminIdentity } from "../../admin-access.identity.js";
|
||||||
import { AdminWorkspaceService } from "./admin-workspace.service.js";
|
import { AdminWorkspaceService } from "./admin-workspace.service.js";
|
||||||
|
|
||||||
@@ -11,7 +11,7 @@ import { AdminWorkspaceService } from "./admin-workspace.service.js";
|
|||||||
class AdminWorkspacePreviewController {
|
class AdminWorkspacePreviewController {
|
||||||
constructor(
|
constructor(
|
||||||
private readonly workspaceService: AdminWorkspaceService,
|
private readonly workspaceService: AdminWorkspaceService,
|
||||||
private readonly templateWorkspace: TemplateWorkspaceService,
|
private readonly templateInstallations: TemplateInstallationService,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
@Get()
|
@Get()
|
||||||
@@ -32,7 +32,7 @@ class AdminWorkspacePreviewController {
|
|||||||
): Promise<unknown> {
|
): Promise<unknown> {
|
||||||
const identity = requireAdminIdentity(request);
|
const identity = requireAdminIdentity(request);
|
||||||
const requestId = request.headers["x-request-id"]?.toString() ?? request.id;
|
const requestId = request.headers["x-request-id"]?.toString() ?? request.id;
|
||||||
return this.templateWorkspace.install(
|
return this.templateInstallations.install(
|
||||||
identity.brandId,
|
identity.brandId,
|
||||||
body.templateKey,
|
body.templateKey,
|
||||||
body.templatePackageVersionId,
|
body.templatePackageVersionId,
|
||||||
@@ -49,7 +49,7 @@ class AdminWorkspacePreviewController {
|
|||||||
): Promise<unknown> {
|
): Promise<unknown> {
|
||||||
const identity = requireAdminIdentity(request);
|
const identity = requireAdminIdentity(request);
|
||||||
const requestId = request.headers["x-request-id"]?.toString() ?? request.id;
|
const requestId = request.headers["x-request-id"]?.toString() ?? request.id;
|
||||||
return this.templateWorkspace.selectVersion(
|
return this.templateInstallations.selectVersion(
|
||||||
identity.brandId,
|
identity.brandId,
|
||||||
body,
|
body,
|
||||||
identity.subject,
|
identity.subject,
|
||||||
|
|||||||
@@ -0,0 +1,20 @@
|
|||||||
|
const PLACEHOLDER_PATTERN = /(replace-with|change-me|changeme|^your[-_ ]|example|placeholder)/i;
|
||||||
|
|
||||||
|
/** 判断值是否仍是仓库示例中的占位符,而不是真实随机密钥。 */
|
||||||
|
export function isPlaceholderSecret(value: string): boolean {
|
||||||
|
return PLACEHOLDER_PATTERN.test(value.trim());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 生产环境启动前的快速失败校验。
|
||||||
|
* 本地开发允许占位符,避免示例 `.env` 阻塞调试;生产环境必须使用真实随机值。
|
||||||
|
*/
|
||||||
|
export function assertProductionSecret(
|
||||||
|
value: string | undefined,
|
||||||
|
nodeEnv: string | undefined = process.env.NODE_ENV,
|
||||||
|
): void {
|
||||||
|
if (nodeEnv !== "production") return;
|
||||||
|
const secret = value?.trim() ?? "";
|
||||||
|
if (secret.length < 32) throw new Error("SESSION_SECRET 必须是至少 32 位的随机值");
|
||||||
|
if (isPlaceholderSecret(secret)) throw new Error("SESSION_SECRET 不能使用示例占位符");
|
||||||
|
}
|
||||||
@@ -0,0 +1,114 @@
|
|||||||
|
import type { TemplatePackageVersion } from "@prisma/client";
|
||||||
|
|
||||||
|
export function record(value: unknown): Record<string, unknown> {
|
||||||
|
return value && typeof value === "object" && !Array.isArray(value)
|
||||||
|
? (value as Record<string, unknown>)
|
||||||
|
: {};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function manifestRecords(value: unknown): Record<string, unknown>[] {
|
||||||
|
return Array.isArray(value)
|
||||||
|
? value.filter((item): item is Record<string, unknown> =>
|
||||||
|
Boolean(item && typeof item === "object" && !Array.isArray(item)),
|
||||||
|
)
|
||||||
|
: [];
|
||||||
|
}
|
||||||
|
|
||||||
|
export function stringList(value: unknown): string[] {
|
||||||
|
return Array.isArray(value)
|
||||||
|
? value.filter((item): item is string => typeof item === "string")
|
||||||
|
: [];
|
||||||
|
}
|
||||||
|
|
||||||
|
export function hasBindingValue(config: Record<string, unknown>, binding: unknown): boolean {
|
||||||
|
if (typeof binding !== "string" || !binding.startsWith("brand.config.")) return false;
|
||||||
|
const value = binding
|
||||||
|
.slice("brand.config.".length)
|
||||||
|
.split(".")
|
||||||
|
.reduce<unknown>((current, key) => record(current)[key], config);
|
||||||
|
return value !== undefined && value !== null && value !== "";
|
||||||
|
}
|
||||||
|
|
||||||
|
export function compareRecords(current: Record<string, unknown>, target: Record<string, unknown>) {
|
||||||
|
const currentKeys = Object.keys(current);
|
||||||
|
const targetKeys = Object.keys(target);
|
||||||
|
return {
|
||||||
|
added: targetKeys
|
||||||
|
.filter((key) => !(key in current))
|
||||||
|
.map((key) => ({ key, target: target[key] })),
|
||||||
|
removed: currentKeys
|
||||||
|
.filter((key) => !(key in target))
|
||||||
|
.map((key) => ({ key, current: current[key] })),
|
||||||
|
changed: targetKeys
|
||||||
|
.filter(
|
||||||
|
(key) => key in current && JSON.stringify(current[key]) !== JSON.stringify(target[key]),
|
||||||
|
)
|
||||||
|
.map((key) => ({ key, current: current[key], target: target[key] })),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function compareKeyedRecords(
|
||||||
|
current: Record<string, unknown>[],
|
||||||
|
target: Record<string, unknown>[],
|
||||||
|
) {
|
||||||
|
const currentByKey = new Map(
|
||||||
|
current
|
||||||
|
.filter((item) => typeof item.key === "string")
|
||||||
|
.map((item) => [item.key as string, item]),
|
||||||
|
);
|
||||||
|
const targetByKey = new Map(
|
||||||
|
target.filter((item) => typeof item.key === "string").map((item) => [item.key as string, item]),
|
||||||
|
);
|
||||||
|
return {
|
||||||
|
added: [...targetByKey].filter(([key]) => !currentByKey.has(key)).map(([, item]) => item),
|
||||||
|
removed: [...currentByKey].filter(([key]) => !targetByKey.has(key)).map(([, item]) => item),
|
||||||
|
changed: [...targetByKey].flatMap(([key, item]) => {
|
||||||
|
const previous = currentByKey.get(key);
|
||||||
|
return previous && JSON.stringify(previous) !== JSON.stringify(item)
|
||||||
|
? [{ key, current: previous, target: item }]
|
||||||
|
: [];
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function compareFiles(
|
||||||
|
current: Record<string, unknown>[],
|
||||||
|
target: Record<string, unknown>[],
|
||||||
|
) {
|
||||||
|
const currentByPath = new Map(
|
||||||
|
current
|
||||||
|
.filter((item) => typeof item.path === "string")
|
||||||
|
.map((item) => [item.path as string, item]),
|
||||||
|
);
|
||||||
|
const targetByPath = new Map(
|
||||||
|
target
|
||||||
|
.filter((item) => typeof item.path === "string")
|
||||||
|
.map((item) => [item.path as string, item]),
|
||||||
|
);
|
||||||
|
const available = currentByPath.size > 0 && targetByPath.size > 0;
|
||||||
|
return {
|
||||||
|
available,
|
||||||
|
...(available
|
||||||
|
? {
|
||||||
|
added: [...targetByPath]
|
||||||
|
.filter(([path]) => !currentByPath.has(path))
|
||||||
|
.map(([, item]) => item),
|
||||||
|
removed: [...currentByPath]
|
||||||
|
.filter(([path]) => !targetByPath.has(path))
|
||||||
|
.map(([, item]) => item),
|
||||||
|
changed: [...targetByPath].flatMap(([path, item]) => {
|
||||||
|
const previous = currentByPath.get(path);
|
||||||
|
return previous && previous.sha256 !== item.sha256
|
||||||
|
? [{ path, current: previous, target: item }]
|
||||||
|
: [];
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
: { reason: "版本验证报告未包含完整文件清单" }),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function readPackageFiles(
|
||||||
|
version: Pick<TemplatePackageVersion, "validationReport">,
|
||||||
|
): Record<string, unknown>[] {
|
||||||
|
return manifestRecords(record(version.validationReport).files);
|
||||||
|
}
|
||||||
@@ -0,0 +1,105 @@
|
|||||||
|
import { BadRequestException, Injectable } from "@nestjs/common";
|
||||||
|
import {
|
||||||
|
type BrandTemplateKey,
|
||||||
|
brandTemplateKeys,
|
||||||
|
getBrandTemplate,
|
||||||
|
getVisualTemplate,
|
||||||
|
getVisualTemplateManifest,
|
||||||
|
isVisualTemplateCompatible,
|
||||||
|
validateTemplatePackageManifest,
|
||||||
|
} from "@personal-brand/config";
|
||||||
|
import { PrismaService } from "../prisma.service.js";
|
||||||
|
import { compareTemplateVersions } from "../template-version-order.js";
|
||||||
|
import { record } from "./manifest-diff.helpers.js";
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class PageSchemeService {
|
||||||
|
constructor(private readonly prisma: PrismaService) {}
|
||||||
|
|
||||||
|
async getPageSchemeCatalog() {
|
||||||
|
const versions = await this.prisma.templatePackageVersion.findMany({
|
||||||
|
where: { status: "published" },
|
||||||
|
orderBy: [{ importedAt: "desc" }, { createdAt: "desc" }],
|
||||||
|
});
|
||||||
|
const candidates = versions.flatMap((version) => {
|
||||||
|
const manifest = record(version.manifestSnapshot);
|
||||||
|
const visualTemplateKey = manifest.visualTemplateKey;
|
||||||
|
if (
|
||||||
|
manifest.packageKey !== version.packageKey ||
|
||||||
|
manifest.version !== version.version ||
|
||||||
|
typeof visualTemplateKey !== "string" ||
|
||||||
|
visualTemplateKey !== version.packageKey
|
||||||
|
)
|
||||||
|
return [];
|
||||||
|
const visualTemplate = getVisualTemplate(visualTemplateKey);
|
||||||
|
const visualManifest = getVisualTemplateManifest(visualTemplateKey);
|
||||||
|
if (!visualTemplate || !visualManifest) return [];
|
||||||
|
const supportedBusinessTypes = Array.isArray(manifest.supportedIndustryTemplates)
|
||||||
|
? manifest.supportedIndustryTemplates.filter(
|
||||||
|
(value): value is BrandTemplateKey =>
|
||||||
|
typeof value === "string" &&
|
||||||
|
brandTemplateKeys.includes(value) &&
|
||||||
|
Boolean(getBrandTemplate(value)),
|
||||||
|
)
|
||||||
|
: [];
|
||||||
|
if (
|
||||||
|
supportedBusinessTypes.length === 0 ||
|
||||||
|
supportedBusinessTypes.some(
|
||||||
|
(businessType) => !isVisualTemplateCompatible(visualTemplate, businessType),
|
||||||
|
) ||
|
||||||
|
validateTemplatePackageManifest(manifest).length > 0
|
||||||
|
)
|
||||||
|
return [];
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
templatePackageVersionId: version.id,
|
||||||
|
packageKey: version.packageKey,
|
||||||
|
name: version.displayName,
|
||||||
|
description: visualManifest.description,
|
||||||
|
version: version.version,
|
||||||
|
supportedBusinessTypes,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
});
|
||||||
|
const latestByPackage = new Map<string, string>();
|
||||||
|
for (const candidate of candidates) {
|
||||||
|
const latestVersion = latestByPackage.get(candidate.packageKey);
|
||||||
|
if (!latestVersion || compareTemplateVersions(candidate.version, latestVersion) > 0) {
|
||||||
|
latestByPackage.set(candidate.packageKey, candidate.version);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const pageSchemes = candidates.map(({ packageKey, ...candidate }) => ({
|
||||||
|
...candidate,
|
||||||
|
isLatestForPackage: latestByPackage.get(packageKey) === candidate.version,
|
||||||
|
}));
|
||||||
|
|
||||||
|
return {
|
||||||
|
businesses: brandTemplateKeys.map((key) => {
|
||||||
|
const template = getBrandTemplate(key);
|
||||||
|
if (!template) throw new BadRequestException("业务类型配置不完整");
|
||||||
|
return { key, name: template.name, description: template.description };
|
||||||
|
}),
|
||||||
|
pageSchemes,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async getPageSchemeOptions(brandId: string) {
|
||||||
|
const brand = await this.prisma.brandProfile.findUnique({
|
||||||
|
where: { id: brandId },
|
||||||
|
select: { templateKey: true },
|
||||||
|
});
|
||||||
|
const template = brand ? getBrandTemplate(brand.templateKey) : undefined;
|
||||||
|
if (!brand || !template) throw new BadRequestException("品牌业务类型无效");
|
||||||
|
const catalog = await this.getPageSchemeCatalog();
|
||||||
|
return {
|
||||||
|
business: {
|
||||||
|
key: template.key,
|
||||||
|
name: template.name,
|
||||||
|
description: template.description,
|
||||||
|
},
|
||||||
|
pageSchemes: catalog.pageSchemes.filter((scheme) =>
|
||||||
|
scheme.supportedBusinessTypes.includes(template.key),
|
||||||
|
),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
+15
-258
@@ -3,7 +3,6 @@ import type { TemplatePackageVersion } from "@prisma/client";
|
|||||||
import { Prisma } from "@prisma/client";
|
import { Prisma } from "@prisma/client";
|
||||||
import {
|
import {
|
||||||
type BrandTemplateKey,
|
type BrandTemplateKey,
|
||||||
brandTemplateKeys,
|
|
||||||
getBrandTemplate,
|
getBrandTemplate,
|
||||||
getVisualTemplate,
|
getVisualTemplate,
|
||||||
getVisualTemplateManifest,
|
getVisualTemplateManifest,
|
||||||
@@ -11,157 +10,25 @@ import {
|
|||||||
validateTemplatePackageManifest,
|
validateTemplatePackageManifest,
|
||||||
} from "@personal-brand/config";
|
} from "@personal-brand/config";
|
||||||
import type { TemplatePackageManifest } from "@personal-brand/config";
|
import type { TemplatePackageManifest } from "@personal-brand/config";
|
||||||
import type { CreateTrustContentDto, UpdateTrustContentDto } from "./admin.dto.js";
|
import type { RollbackTemplateDto, UpgradeTemplateDto } from "../admin.dto.js";
|
||||||
import type { RollbackTemplateDto, UpgradeTemplateDto } from "./admin.dto.js";
|
import { PrismaService } from "../prisma.service.js";
|
||||||
import { PrismaService } from "./prisma.service.js";
|
import { recordTemplateOperationFailure } from "../modules/admin/template-operation-failure.js";
|
||||||
import { recordTemplateOperationFailure } from "./modules/admin/template-operation-failure.js";
|
import { latestTemplateVersion } from "../template-version-order.js";
|
||||||
import { compareTemplateVersions, latestTemplateVersion } from "./template-version-order.js";
|
import {
|
||||||
|
compareFiles,
|
||||||
|
compareKeyedRecords,
|
||||||
|
compareRecords,
|
||||||
|
hasBindingValue,
|
||||||
|
manifestRecords,
|
||||||
|
readPackageFiles,
|
||||||
|
record,
|
||||||
|
stringList,
|
||||||
|
} from "./manifest-diff.helpers.js";
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class TemplateWorkspaceService {
|
export class TemplateInstallationService {
|
||||||
constructor(private readonly prisma: PrismaService) {}
|
constructor(private readonly prisma: PrismaService) {}
|
||||||
|
|
||||||
async getPageSchemeCatalog() {
|
|
||||||
const versions = await this.prisma.templatePackageVersion.findMany({
|
|
||||||
where: { status: "published" },
|
|
||||||
orderBy: [{ importedAt: "desc" }, { createdAt: "desc" }],
|
|
||||||
});
|
|
||||||
const candidates = versions.flatMap((version) => {
|
|
||||||
const manifest = record(version.manifestSnapshot);
|
|
||||||
const visualTemplateKey = manifest.visualTemplateKey;
|
|
||||||
if (
|
|
||||||
manifest.packageKey !== version.packageKey ||
|
|
||||||
manifest.version !== version.version ||
|
|
||||||
typeof visualTemplateKey !== "string" ||
|
|
||||||
visualTemplateKey !== version.packageKey
|
|
||||||
)
|
|
||||||
return [];
|
|
||||||
const visualTemplate = getVisualTemplate(visualTemplateKey);
|
|
||||||
const visualManifest = getVisualTemplateManifest(visualTemplateKey);
|
|
||||||
if (!visualTemplate || !visualManifest) return [];
|
|
||||||
const supportedBusinessTypes = Array.isArray(manifest.supportedIndustryTemplates)
|
|
||||||
? manifest.supportedIndustryTemplates.filter(
|
|
||||||
(value): value is BrandTemplateKey =>
|
|
||||||
typeof value === "string" &&
|
|
||||||
brandTemplateKeys.includes(value) &&
|
|
||||||
Boolean(getBrandTemplate(value)),
|
|
||||||
)
|
|
||||||
: [];
|
|
||||||
if (
|
|
||||||
supportedBusinessTypes.length === 0 ||
|
|
||||||
supportedBusinessTypes.some(
|
|
||||||
(businessType) => !isVisualTemplateCompatible(visualTemplate, businessType),
|
|
||||||
) ||
|
|
||||||
validateTemplatePackageManifest(manifest).length > 0
|
|
||||||
)
|
|
||||||
return [];
|
|
||||||
return [
|
|
||||||
{
|
|
||||||
templatePackageVersionId: version.id,
|
|
||||||
packageKey: version.packageKey,
|
|
||||||
name: version.displayName,
|
|
||||||
description: visualManifest.description,
|
|
||||||
version: version.version,
|
|
||||||
supportedBusinessTypes,
|
|
||||||
},
|
|
||||||
];
|
|
||||||
});
|
|
||||||
const latestByPackage = new Map<string, string>();
|
|
||||||
for (const candidate of candidates) {
|
|
||||||
const latestVersion = latestByPackage.get(candidate.packageKey);
|
|
||||||
if (!latestVersion || compareTemplateVersions(candidate.version, latestVersion) > 0) {
|
|
||||||
latestByPackage.set(candidate.packageKey, candidate.version);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
const pageSchemes = candidates.map(({ packageKey, ...candidate }) => ({
|
|
||||||
...candidate,
|
|
||||||
isLatestForPackage: latestByPackage.get(packageKey) === candidate.version,
|
|
||||||
}));
|
|
||||||
|
|
||||||
return {
|
|
||||||
businesses: brandTemplateKeys.map((key) => {
|
|
||||||
const template = getBrandTemplate(key);
|
|
||||||
if (!template) throw new BadRequestException("业务类型配置不完整");
|
|
||||||
return { key, name: template.name, description: template.description };
|
|
||||||
}),
|
|
||||||
pageSchemes,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
async getPageSchemeOptions(brandId: string) {
|
|
||||||
const brand = await this.prisma.brandProfile.findUnique({
|
|
||||||
where: { id: brandId },
|
|
||||||
select: { templateKey: true },
|
|
||||||
});
|
|
||||||
const template = brand ? getBrandTemplate(brand.templateKey) : undefined;
|
|
||||||
if (!brand || !template) throw new BadRequestException("品牌业务类型无效");
|
|
||||||
const catalog = await this.getPageSchemeCatalog();
|
|
||||||
return {
|
|
||||||
business: {
|
|
||||||
key: template.key,
|
|
||||||
name: template.name,
|
|
||||||
description: template.description,
|
|
||||||
},
|
|
||||||
pageSchemes: catalog.pageSchemes.filter((scheme) =>
|
|
||||||
scheme.supportedBusinessTypes.includes(template.key),
|
|
||||||
),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
async getTrustContentTypes(brandId: string): Promise<string[]> {
|
|
||||||
const installation = await this.prisma.brandTemplateInstallation.findUnique({
|
|
||||||
where: { brandId },
|
|
||||||
include: { templatePackageVersion: true },
|
|
||||||
});
|
|
||||||
if (!installation?.templatePackageVersion)
|
|
||||||
throw new BadRequestException("品牌没有锁定精确视觉模板包版本");
|
|
||||||
const manifest = record(
|
|
||||||
installation.templatePackageVersion.manifestSnapshot,
|
|
||||||
) as unknown as TemplatePackageManifest;
|
|
||||||
if (validateTemplatePackageManifest(manifest).length)
|
|
||||||
throw new BadRequestException("当前安装的模板包不符合统一模板契约");
|
|
||||||
return manifest.trustContentTypes?.map((item) => item.type) ?? [];
|
|
||||||
}
|
|
||||||
async createTrustContent(brandId: string, body: CreateTrustContentDto) {
|
|
||||||
if (!(await this.getTrustContentTypes(brandId)).includes(body.type))
|
|
||||||
throw new BadRequestException("当前模板不支持此信任内容类型");
|
|
||||||
const { config, ...fields } = body;
|
|
||||||
return this.prisma.trustContent.create({
|
|
||||||
data: {
|
|
||||||
...fields,
|
|
||||||
brandId,
|
|
||||||
...(config === undefined ? {} : { config: config as Prisma.InputJsonValue }),
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
|
||||||
async updateTrustContent(brandId: string, id: string, body: UpdateTrustContentDto) {
|
|
||||||
const item = await this.prisma.trustContent.findFirst({ where: { id, brandId } });
|
|
||||||
if (!item) throw new BadRequestException("信任内容不存在");
|
|
||||||
if (body.type !== undefined && !(await this.getTrustContentTypes(brandId)).includes(body.type))
|
|
||||||
throw new BadRequestException("当前模板不支持此信任内容类型");
|
|
||||||
const { config, ...fields } = body;
|
|
||||||
return this.prisma.trustContent.update({
|
|
||||||
where: { id },
|
|
||||||
data: {
|
|
||||||
...fields,
|
|
||||||
...(config === undefined ? {} : { config: config as Prisma.InputJsonValue }),
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
listTrustContent(brandId: string) {
|
|
||||||
return this.prisma.trustContent.findMany({
|
|
||||||
where: { brandId },
|
|
||||||
orderBy: [{ type: "asc" }, { sortOrder: "asc" }],
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
async deleteTrustContent(brandId: string, id: string) {
|
|
||||||
const item = await this.prisma.trustContent.findFirst({ where: { id, brandId } });
|
|
||||||
if (!item) throw new BadRequestException("信任内容不存在");
|
|
||||||
await this.prisma.trustContent.delete({ where: { id } });
|
|
||||||
return { deleted: true };
|
|
||||||
}
|
|
||||||
async getEffectiveTemplateKey(brandId: string): Promise<BrandTemplateKey> {
|
async getEffectiveTemplateKey(brandId: string): Promise<BrandTemplateKey> {
|
||||||
const [brand, installation] = await Promise.all([
|
const [brand, installation] = await Promise.all([
|
||||||
this.prisma.brandProfile.findUnique({
|
this.prisma.brandProfile.findUnique({
|
||||||
@@ -759,113 +626,3 @@ export class TemplateWorkspaceService {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function readPackageFiles(
|
|
||||||
version: Pick<TemplatePackageVersion, "validationReport">,
|
|
||||||
): Record<string, unknown>[] {
|
|
||||||
return manifestRecords(record(version.validationReport).files);
|
|
||||||
}
|
|
||||||
|
|
||||||
function record(value: unknown): Record<string, unknown> {
|
|
||||||
return value && typeof value === "object" && !Array.isArray(value)
|
|
||||||
? (value as Record<string, unknown>)
|
|
||||||
: {};
|
|
||||||
}
|
|
||||||
|
|
||||||
function manifestRecords(value: unknown): Record<string, unknown>[] {
|
|
||||||
return Array.isArray(value)
|
|
||||||
? value.filter((item): item is Record<string, unknown> =>
|
|
||||||
Boolean(item && typeof item === "object" && !Array.isArray(item)),
|
|
||||||
)
|
|
||||||
: [];
|
|
||||||
}
|
|
||||||
|
|
||||||
function stringList(value: unknown): string[] {
|
|
||||||
return Array.isArray(value)
|
|
||||||
? value.filter((item): item is string => typeof item === "string")
|
|
||||||
: [];
|
|
||||||
}
|
|
||||||
|
|
||||||
function hasBindingValue(config: Record<string, unknown>, binding: unknown): boolean {
|
|
||||||
if (typeof binding !== "string" || !binding.startsWith("brand.config.")) return false;
|
|
||||||
const value = binding
|
|
||||||
.slice("brand.config.".length)
|
|
||||||
.split(".")
|
|
||||||
.reduce<unknown>((current, key) => record(current)[key], config);
|
|
||||||
return value !== undefined && value !== null && value !== "";
|
|
||||||
}
|
|
||||||
|
|
||||||
function compareRecords(current: Record<string, unknown>, target: Record<string, unknown>) {
|
|
||||||
const currentKeys = Object.keys(current);
|
|
||||||
const targetKeys = Object.keys(target);
|
|
||||||
return {
|
|
||||||
added: targetKeys
|
|
||||||
.filter((key) => !(key in current))
|
|
||||||
.map((key) => ({ key, target: target[key] })),
|
|
||||||
removed: currentKeys
|
|
||||||
.filter((key) => !(key in target))
|
|
||||||
.map((key) => ({ key, current: current[key] })),
|
|
||||||
changed: targetKeys
|
|
||||||
.filter(
|
|
||||||
(key) => key in current && JSON.stringify(current[key]) !== JSON.stringify(target[key]),
|
|
||||||
)
|
|
||||||
.map((key) => ({ key, current: current[key], target: target[key] })),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function compareKeyedRecords(
|
|
||||||
current: Record<string, unknown>[],
|
|
||||||
target: Record<string, unknown>[],
|
|
||||||
) {
|
|
||||||
const currentByKey = new Map(
|
|
||||||
current
|
|
||||||
.filter((item) => typeof item.key === "string")
|
|
||||||
.map((item) => [item.key as string, item]),
|
|
||||||
);
|
|
||||||
const targetByKey = new Map(
|
|
||||||
target.filter((item) => typeof item.key === "string").map((item) => [item.key as string, item]),
|
|
||||||
);
|
|
||||||
return {
|
|
||||||
added: [...targetByKey].filter(([key]) => !currentByKey.has(key)).map(([, item]) => item),
|
|
||||||
removed: [...currentByKey].filter(([key]) => !targetByKey.has(key)).map(([, item]) => item),
|
|
||||||
changed: [...targetByKey].flatMap(([key, item]) => {
|
|
||||||
const previous = currentByKey.get(key);
|
|
||||||
return previous && JSON.stringify(previous) !== JSON.stringify(item)
|
|
||||||
? [{ key, current: previous, target: item }]
|
|
||||||
: [];
|
|
||||||
}),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function compareFiles(current: Record<string, unknown>[], target: Record<string, unknown>[]) {
|
|
||||||
const currentByPath = new Map(
|
|
||||||
current
|
|
||||||
.filter((item) => typeof item.path === "string")
|
|
||||||
.map((item) => [item.path as string, item]),
|
|
||||||
);
|
|
||||||
const targetByPath = new Map(
|
|
||||||
target
|
|
||||||
.filter((item) => typeof item.path === "string")
|
|
||||||
.map((item) => [item.path as string, item]),
|
|
||||||
);
|
|
||||||
const available = currentByPath.size > 0 && targetByPath.size > 0;
|
|
||||||
return {
|
|
||||||
available,
|
|
||||||
...(available
|
|
||||||
? {
|
|
||||||
added: [...targetByPath]
|
|
||||||
.filter(([path]) => !currentByPath.has(path))
|
|
||||||
.map(([, item]) => item),
|
|
||||||
removed: [...currentByPath]
|
|
||||||
.filter(([path]) => !targetByPath.has(path))
|
|
||||||
.map(([, item]) => item),
|
|
||||||
changed: [...targetByPath].flatMap(([path, item]) => {
|
|
||||||
const previous = currentByPath.get(path);
|
|
||||||
return previous && previous.sha256 !== item.sha256
|
|
||||||
? [{ path, current: previous, target: item }]
|
|
||||||
: [];
|
|
||||||
}),
|
|
||||||
}
|
|
||||||
: { reason: "版本验证报告未包含完整文件清单" }),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
import { BadRequestException, Injectable } from "@nestjs/common";
|
||||||
|
import { Prisma } from "@prisma/client";
|
||||||
|
import { validateTemplatePackageManifest } from "@personal-brand/config";
|
||||||
|
import type { TemplatePackageManifest } from "@personal-brand/config";
|
||||||
|
import type { CreateTrustContentDto, UpdateTrustContentDto } from "../admin.dto.js";
|
||||||
|
import { PrismaService } from "../prisma.service.js";
|
||||||
|
import { record } from "./manifest-diff.helpers.js";
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class TrustContentService {
|
||||||
|
constructor(private readonly prisma: PrismaService) {}
|
||||||
|
|
||||||
|
async getTrustContentTypes(brandId: string): Promise<string[]> {
|
||||||
|
const installation = await this.prisma.brandTemplateInstallation.findUnique({
|
||||||
|
where: { brandId },
|
||||||
|
include: { templatePackageVersion: true },
|
||||||
|
});
|
||||||
|
if (!installation?.templatePackageVersion)
|
||||||
|
throw new BadRequestException("品牌没有锁定精确视觉模板包版本");
|
||||||
|
const manifest = record(
|
||||||
|
installation.templatePackageVersion.manifestSnapshot,
|
||||||
|
) as unknown as TemplatePackageManifest;
|
||||||
|
if (validateTemplatePackageManifest(manifest).length)
|
||||||
|
throw new BadRequestException("当前安装的模板包不符合统一模板契约");
|
||||||
|
return manifest.trustContentTypes?.map((item) => item.type) ?? [];
|
||||||
|
}
|
||||||
|
|
||||||
|
async createTrustContent(brandId: string, body: CreateTrustContentDto) {
|
||||||
|
if (!(await this.getTrustContentTypes(brandId)).includes(body.type))
|
||||||
|
throw new BadRequestException("当前模板不支持此信任内容类型");
|
||||||
|
const { config, ...fields } = body;
|
||||||
|
return this.prisma.trustContent.create({
|
||||||
|
data: {
|
||||||
|
...fields,
|
||||||
|
brandId,
|
||||||
|
...(config === undefined ? {} : { config: config as Prisma.InputJsonValue }),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async updateTrustContent(brandId: string, id: string, body: UpdateTrustContentDto) {
|
||||||
|
const item = await this.prisma.trustContent.findFirst({ where: { id, brandId } });
|
||||||
|
if (!item) throw new BadRequestException("信任内容不存在");
|
||||||
|
if (body.type !== undefined && !(await this.getTrustContentTypes(brandId)).includes(body.type))
|
||||||
|
throw new BadRequestException("当前模板不支持此信任内容类型");
|
||||||
|
const { config, ...fields } = body;
|
||||||
|
return this.prisma.trustContent.update({
|
||||||
|
where: { id },
|
||||||
|
data: {
|
||||||
|
...fields,
|
||||||
|
...(config === undefined ? {} : { config: config as Prisma.InputJsonValue }),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
listTrustContent(brandId: string) {
|
||||||
|
return this.prisma.trustContent.findMany({
|
||||||
|
where: { brandId },
|
||||||
|
orderBy: [{ type: "asc" }, { sortOrder: "asc" }],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async deleteTrustContent(brandId: string, id: string) {
|
||||||
|
const item = await this.prisma.trustContent.findFirst({ where: { id, brandId } });
|
||||||
|
if (!item) throw new BadRequestException("信任内容不存在");
|
||||||
|
await this.prisma.trustContent.delete({ where: { id } });
|
||||||
|
return { deleted: true };
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
import assert from "node:assert/strict";
|
||||||
|
import test from "node:test";
|
||||||
|
import { ForbiddenException } from "@nestjs/common";
|
||||||
|
import { AdminAccessService } from "../src/admin-access.service.js";
|
||||||
|
import { signIdentity } from "../src/auth.js";
|
||||||
|
|
||||||
|
process.env.SESSION_SECRET = "admin-access-service-test-secret-1234567890";
|
||||||
|
|
||||||
|
type RequestFixture = {
|
||||||
|
headers: { authorization: string };
|
||||||
|
};
|
||||||
|
|
||||||
|
function requestFixture(subject = "admin-1", brandId = "brand-1"): RequestFixture {
|
||||||
|
return {
|
||||||
|
headers: {
|
||||||
|
authorization: `Bearer ${signIdentity({ subject, brandId, role: "admin" })}`,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function accessFixture() {
|
||||||
|
const calls = { adminUser: 0, membership: 0 };
|
||||||
|
const prisma = {
|
||||||
|
adminUser: {
|
||||||
|
findUnique: async () => {
|
||||||
|
calls.adminUser += 1;
|
||||||
|
return {
|
||||||
|
isEnabled: true,
|
||||||
|
mustChangePassword: false,
|
||||||
|
tokenVersion: 0,
|
||||||
|
platformTemplateRole: "none",
|
||||||
|
};
|
||||||
|
},
|
||||||
|
},
|
||||||
|
brandMembership: {
|
||||||
|
findUnique: async () => {
|
||||||
|
calls.membership += 1;
|
||||||
|
return { role: "owner", isEnabled: true };
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
return { calls, prisma };
|
||||||
|
}
|
||||||
|
|
||||||
|
test("同一请求内 Guard 与 Controller 复用访问校验结果", async () => {
|
||||||
|
const { calls, prisma } = accessFixture();
|
||||||
|
const service = new AdminAccessService(prisma as never);
|
||||||
|
const request = requestFixture();
|
||||||
|
|
||||||
|
const [guardResult, controllerResult] = await Promise.all([
|
||||||
|
service.requireBrand(request as never),
|
||||||
|
service.requireBrand(request as never),
|
||||||
|
]);
|
||||||
|
assert.deepEqual(guardResult, controllerResult);
|
||||||
|
await service.requireRole(request as never, ["owner"]);
|
||||||
|
await assert.rejects(
|
||||||
|
service.requireTemplateAdmin(request as never),
|
||||||
|
(error: unknown) => error instanceof ForbiddenException,
|
||||||
|
);
|
||||||
|
|
||||||
|
assert.equal(calls.adminUser, 1);
|
||||||
|
assert.equal(calls.membership, 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("不同请求之间不共享访问校验缓存", async () => {
|
||||||
|
const { calls, prisma } = accessFixture();
|
||||||
|
const service = new AdminAccessService(prisma as never);
|
||||||
|
|
||||||
|
await service.requireBrand(requestFixture("admin-1") as never);
|
||||||
|
await service.requireBrand(requestFixture("admin-2") as never);
|
||||||
|
|
||||||
|
assert.equal(calls.adminUser, 2);
|
||||||
|
assert.equal(calls.membership, 2);
|
||||||
|
});
|
||||||
@@ -2,6 +2,7 @@ import assert from "node:assert/strict";
|
|||||||
import { test } from "node:test";
|
import { test } from "node:test";
|
||||||
import { HttpException } from "@nestjs/common";
|
import { HttpException } from "@nestjs/common";
|
||||||
import { AdminClientErrorService } from "../src/modules/admin/admin-client-error.service.js";
|
import { AdminClientErrorService } from "../src/modules/admin/admin-client-error.service.js";
|
||||||
|
import { MemoryClientErrorThrottleStore } from "../src/modules/admin/client-error-throttle.store.js";
|
||||||
|
|
||||||
function report(errorId: string, subject = "admin:user-1") {
|
function report(errorId: string, subject = "admin:user-1") {
|
||||||
return {
|
return {
|
||||||
@@ -15,40 +16,42 @@ function report(errorId: string, subject = "admin:user-1") {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
test("首次上报记录,相同 errorId 在窗口内按管理员去重", () => {
|
function service() {
|
||||||
const service = new AdminClientErrorService();
|
return new AdminClientErrorService(new MemoryClientErrorThrottleStore());
|
||||||
assert.deepEqual(service.record(report("admin-error-1")), {
|
}
|
||||||
|
|
||||||
|
test("首次上报记录,相同 errorId 在窗口内按管理员去重", async () => {
|
||||||
|
const errors = service();
|
||||||
|
assert.deepEqual(await errors.record(report("admin-error-1")), {
|
||||||
received: true,
|
received: true,
|
||||||
duplicate: false,
|
duplicate: false,
|
||||||
});
|
});
|
||||||
assert.deepEqual(service.record(report("admin-error-1")), {
|
assert.deepEqual(await errors.record(report("admin-error-1")), {
|
||||||
received: true,
|
received: true,
|
||||||
duplicate: true,
|
duplicate: true,
|
||||||
});
|
});
|
||||||
// 不同管理员使用相同 errorId 时互不影响
|
// 不同管理员使用相同 errorId 时互不影响
|
||||||
assert.deepEqual(service.record(report("admin-error-1", "admin:user-2")), {
|
assert.deepEqual(await errors.record(report("admin-error-1", "admin:user-2")), {
|
||||||
received: true,
|
received: true,
|
||||||
duplicate: false,
|
duplicate: false,
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
test("同一管理员 60 秒内最多接受 10 条不同错误", () => {
|
test("同一管理员 60 秒内最多接受 10 条不同错误", async () => {
|
||||||
const service = new AdminClientErrorService();
|
const errors = service();
|
||||||
for (let index = 0; index < 10; index += 1) {
|
for (let index = 0; index < 10; index += 1) {
|
||||||
assert.deepEqual(service.record(report(`admin-rate-${index}`)), {
|
assert.deepEqual(await errors.record(report(`admin-rate-${index}`)), {
|
||||||
received: true,
|
received: true,
|
||||||
duplicate: false,
|
duplicate: false,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
try {
|
await assert.rejects(errors.record(report("admin-rate-overflow")), (error) => {
|
||||||
service.record(report("admin-rate-overflow"));
|
|
||||||
assert.fail("应当触发限流");
|
|
||||||
} catch (error) {
|
|
||||||
assert.ok(error instanceof HttpException);
|
assert.ok(error instanceof HttpException);
|
||||||
assert.equal(error.getStatus(), 429);
|
assert.equal(error.getStatus(), 429);
|
||||||
}
|
return true;
|
||||||
|
});
|
||||||
// 另一个管理员不受影响
|
// 另一个管理员不受影响
|
||||||
assert.deepEqual(service.record(report("admin-rate-other", "admin:user-2")), {
|
assert.deepEqual(await errors.record(report("admin-rate-other", "admin:user-2")), {
|
||||||
received: true,
|
received: true,
|
||||||
duplicate: false,
|
duplicate: false,
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,24 @@
|
|||||||
|
import assert from "node:assert/strict";
|
||||||
|
import { test } from "node:test";
|
||||||
|
import { createClientErrorThrottleStore } from "../src/modules/admin/client-error-throttle.factory.js";
|
||||||
|
import { PostgresClientErrorThrottleStore } from "../src/modules/admin/client-error-throttle.postgres.store.js";
|
||||||
|
import { MemoryClientErrorThrottleStore } from "../src/modules/admin/client-error-throttle.store.js";
|
||||||
|
|
||||||
|
const prisma = {} as never;
|
||||||
|
|
||||||
|
test("默认使用进程内存储", () => {
|
||||||
|
const store = createClientErrorThrottleStore(prisma, "memory");
|
||||||
|
assert.ok(store instanceof MemoryClientErrorThrottleStore);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("多实例可切换为 Postgres 共享存储", () => {
|
||||||
|
const store = createClientErrorThrottleStore(prisma, "postgres");
|
||||||
|
assert.ok(store instanceof PostgresClientErrorThrottleStore);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("未知存储模式在启动时快速失败", () => {
|
||||||
|
assert.throws(
|
||||||
|
() => createClientErrorThrottleStore(prisma, "redis"),
|
||||||
|
/Unsupported CLIENT_ERROR_THROTTLE_STORE/,
|
||||||
|
);
|
||||||
|
});
|
||||||
@@ -12,6 +12,11 @@ import { createApp } from "../dist/main.js";
|
|||||||
import { readIdentity, signIdentity } from "../dist/auth.js";
|
import { readIdentity, signIdentity } from "../dist/auth.js";
|
||||||
import { WechatAuthService } from "../dist/wechat-auth.js";
|
import { WechatAuthService } from "../dist/wechat-auth.js";
|
||||||
import { AdminMiniAppReleaseService } from "../dist/modules/admin/admin-miniapp-release.service.js";
|
import { AdminMiniAppReleaseService } from "../dist/modules/admin/admin-miniapp-release.service.js";
|
||||||
|
import { PostgresClientErrorThrottleStore } from "../dist/modules/admin/client-error-throttle.postgres.store.js";
|
||||||
|
import {
|
||||||
|
CLIENT_ERROR_DEDUPE_TTL_MS,
|
||||||
|
CLIENT_ERROR_RATE_WINDOW_MS,
|
||||||
|
} from "../dist/modules/admin/client-error-throttle.store.js";
|
||||||
|
|
||||||
let app;
|
let app;
|
||||||
const prisma = new PrismaClient();
|
const prisma = new PrismaClient();
|
||||||
@@ -1928,6 +1933,88 @@ test("admin client error reports are authenticated, validated, and deduplicated"
|
|||||||
assert.equal(invalid.statusCode, 400);
|
assert.equal(invalid.statusCode, 400);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("postgres client error store deduplicates and rate limits across instances", async () => {
|
||||||
|
const storeA = new PostgresClientErrorThrottleStore(prisma);
|
||||||
|
const storeB = new PostgresClientErrorThrottleStore(prisma);
|
||||||
|
const subjectPrefix = `pg-client-error-${randomUUID()}`;
|
||||||
|
const dedupeSubject = `${subjectPrefix}-dedupe`;
|
||||||
|
const concurrentSubject = `${subjectPrefix}-concurrent`;
|
||||||
|
const rateSubject = `${subjectPrefix}-rate`;
|
||||||
|
const lateSubject = `${subjectPrefix}-late`;
|
||||||
|
const now = Date.now();
|
||||||
|
try {
|
||||||
|
assert.deepEqual(await storeA.record({ subject: dedupeSubject, errorId: "same" }, now), {
|
||||||
|
duplicate: false,
|
||||||
|
});
|
||||||
|
assert.deepEqual(await storeB.record({ subject: dedupeSubject, errorId: "same" }, now), {
|
||||||
|
duplicate: true,
|
||||||
|
});
|
||||||
|
assert.deepEqual(
|
||||||
|
await storeB.record(
|
||||||
|
{ subject: dedupeSubject, errorId: "same" },
|
||||||
|
now + CLIENT_ERROR_DEDUPE_TTL_MS + 1_000,
|
||||||
|
),
|
||||||
|
{ duplicate: false },
|
||||||
|
);
|
||||||
|
|
||||||
|
const concurrent = await Promise.all(
|
||||||
|
Array.from({ length: 6 }, (_, index) =>
|
||||||
|
(index % 2 === 0 ? storeA : storeB).record(
|
||||||
|
{ subject: concurrentSubject, errorId: "concurrent-same" },
|
||||||
|
now,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
assert.equal(concurrent.filter((result) => !result.duplicate).length, 1);
|
||||||
|
|
||||||
|
for (let index = 0; index < 10; index += 1) {
|
||||||
|
const store = index % 2 === 0 ? storeA : storeB;
|
||||||
|
assert.deepEqual(
|
||||||
|
await store.record({ subject: rateSubject, errorId: `rate-${index}` }, now),
|
||||||
|
{ duplicate: false },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
await assert.rejects(
|
||||||
|
storeB.record({ subject: rateSubject, errorId: "rate-overflow" }, now),
|
||||||
|
(error) => error.getStatus?.() === 429,
|
||||||
|
);
|
||||||
|
assert.deepEqual(
|
||||||
|
await storeA.record(
|
||||||
|
{ subject: rateSubject, errorId: "rate-next-window" },
|
||||||
|
now + CLIENT_ERROR_RATE_WINDOW_MS,
|
||||||
|
),
|
||||||
|
{ duplicate: false },
|
||||||
|
);
|
||||||
|
|
||||||
|
// 旧窗口的迟到请求不得把窗口指针回拨,否则会额外放行一整窗口。
|
||||||
|
await storeA.record(
|
||||||
|
{ subject: lateSubject, errorId: "late-first" },
|
||||||
|
now + CLIENT_ERROR_RATE_WINDOW_MS,
|
||||||
|
);
|
||||||
|
await storeB.record({ subject: lateSubject, errorId: "late-old" }, now);
|
||||||
|
for (let index = 0; index < 9; index += 1) {
|
||||||
|
assert.deepEqual(
|
||||||
|
await storeA.record(
|
||||||
|
{ subject: lateSubject, errorId: `late-next-${index}` },
|
||||||
|
now + CLIENT_ERROR_RATE_WINDOW_MS,
|
||||||
|
),
|
||||||
|
{ duplicate: false },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
await assert.rejects(
|
||||||
|
storeB.record(
|
||||||
|
{ subject: lateSubject, errorId: "late-overflow" },
|
||||||
|
now + CLIENT_ERROR_RATE_WINDOW_MS,
|
||||||
|
),
|
||||||
|
(error) => error.getStatus?.() === 429,
|
||||||
|
);
|
||||||
|
} finally {
|
||||||
|
const subjects = [dedupeSubject, concurrentSubject, rateSubject, lateSubject];
|
||||||
|
await prisma.clientErrorDedupe.deleteMany({ where: { subject: { in: subjects } } });
|
||||||
|
await prisma.clientErrorThrottleWindow.deleteMany({ where: { subject: { in: subjects } } });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
async function assertProtectedRouteBoundary(url, options = {}) {
|
async function assertProtectedRouteBoundary(url, options = {}) {
|
||||||
const { method = "GET", payload, forbiddenRole = "customer", headers = {} } = options;
|
const { method = "GET", payload, forbiddenRole = "customer", headers = {} } = options;
|
||||||
const requestOptions = payload === undefined ? { method, headers } : { method, headers, payload };
|
const requestOptions = payload === undefined ? { method, headers } : { method, headers, payload };
|
||||||
@@ -5123,6 +5210,71 @@ test("disabled brand membership blocks existing admin token", async () => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("booking endpoints share the brand access policy", async () => {
|
||||||
|
const username = `booking-policy-${randomUUID()}`;
|
||||||
|
const password = "booking-policy-password-123";
|
||||||
|
const user = await prisma.adminUser.create({
|
||||||
|
data: {
|
||||||
|
username,
|
||||||
|
passwordHash: await bcrypt.hash(password, 12),
|
||||||
|
displayName: "预订策略测试管理员",
|
||||||
|
mustChangePassword: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const membership = await prisma.brandMembership.create({
|
||||||
|
data: { brandId, adminUserId: user.id, role: "admin", isEnabled: true },
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
const login = await request("/admin/session/login", {
|
||||||
|
method: "POST",
|
||||||
|
payload: { username, password },
|
||||||
|
});
|
||||||
|
assert.equal(login.statusCode, 201, login.body);
|
||||||
|
const headers = { authorization: `Bearer ${sessionToken(login)}` };
|
||||||
|
const routes = [
|
||||||
|
{ method: "GET", url: "/admin/bookings" },
|
||||||
|
{ method: "GET", url: "/admin/bookings/unread-count" },
|
||||||
|
{ method: "GET", url: "/admin/bookings/tags" },
|
||||||
|
{ method: "POST", url: "/admin/bookings/tags", payload: { name: "策略测试标签" } },
|
||||||
|
];
|
||||||
|
|
||||||
|
// 初始密码未修改时,预订路由必须与其他后台路由一样被拒绝。
|
||||||
|
for (const route of routes) {
|
||||||
|
const response = await request(route.url, {
|
||||||
|
method: route.method,
|
||||||
|
headers,
|
||||||
|
...(route.payload ? { payload: route.payload } : {}),
|
||||||
|
});
|
||||||
|
assert.equal(response.statusCode, 403, `${route.method} ${route.url}: ${response.body}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 品牌成员被停用后,同一 token 也不能再访问预订数据。
|
||||||
|
await prisma.adminUser.update({ where: { id: user.id }, data: { mustChangePassword: false } });
|
||||||
|
const changed = await request("/admin/session/login", {
|
||||||
|
method: "POST",
|
||||||
|
payload: { username, password },
|
||||||
|
});
|
||||||
|
assert.equal(changed.statusCode, 201, changed.body);
|
||||||
|
const activeHeaders = { authorization: `Bearer ${sessionToken(changed)}` };
|
||||||
|
assert.equal((await request("/admin/bookings", { headers: activeHeaders })).statusCode, 200);
|
||||||
|
|
||||||
|
await prisma.brandMembership.update({
|
||||||
|
where: { id: membership.id },
|
||||||
|
data: { isEnabled: false },
|
||||||
|
});
|
||||||
|
for (const route of routes) {
|
||||||
|
const response = await request(route.url, {
|
||||||
|
method: route.method,
|
||||||
|
headers: activeHeaders,
|
||||||
|
...(route.payload ? { payload: route.payload } : {}),
|
||||||
|
});
|
||||||
|
assert.equal(response.statusCode, 403, `${route.method} ${route.url}: ${response.body}`);
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
await prisma.adminUser.delete({ where: { id: user.id } });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
test("admin can read and update brand and service configuration", async () => {
|
test("admin can read and update brand and service configuration", async () => {
|
||||||
const login = await request("/admin/session/login", {
|
const login = await request("/admin/session/login", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
|
|||||||
@@ -0,0 +1,37 @@
|
|||||||
|
import assert from "node:assert/strict";
|
||||||
|
import { test } from "node:test";
|
||||||
|
import { assertProductionSecret, isPlaceholderSecret } from "../src/runtime-config.js";
|
||||||
|
|
||||||
|
test("production rejects missing or short session secrets", () => {
|
||||||
|
assert.throws(() => assertProductionSecret(undefined, "production"), /至少 32 位/);
|
||||||
|
assert.throws(() => assertProductionSecret("short-secret", "production"), /至少 32 位/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("production rejects example placeholder secrets", () => {
|
||||||
|
assert.throws(
|
||||||
|
() => assertProductionSecret("replace-with-at-least-32-random-characters", "production"),
|
||||||
|
/示例占位符/,
|
||||||
|
);
|
||||||
|
assert.throws(
|
||||||
|
() => assertProductionSecret("change-me-now-1234567890-abcdefghij", "production"),
|
||||||
|
/示例占位符/,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("production accepts a strong random secret", () => {
|
||||||
|
assert.doesNotThrow(() =>
|
||||||
|
assertProductionSecret("s3cure-Random-Value-0123456789-abcdefghij", "production"),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("development keeps working with the example placeholder", () => {
|
||||||
|
assert.doesNotThrow(() =>
|
||||||
|
assertProductionSecret("replace-with-a-long-random-value", "development"),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("placeholder detection covers documented example values", () => {
|
||||||
|
assert.equal(isPlaceholderSecret("replace-with-a-long-random-value"), true);
|
||||||
|
assert.equal(isPlaceholderSecret(" YOur-secret-value "), true);
|
||||||
|
assert.equal(isPlaceholderSecret("s3cure-Random-Value-0123456789-abcdefghij"), false);
|
||||||
|
});
|
||||||
@@ -45,7 +45,6 @@ async function main() {
|
|||||||
.filter((entry) => entry.isDirectory() && entry.name !== targetMigration)
|
.filter((entry) => entry.isDirectory() && entry.name !== targetMigration)
|
||||||
.map((entry) => entry.name)
|
.map((entry) => entry.name)
|
||||||
.sort();
|
.sort();
|
||||||
assert.equal(migrationDirs.at(-1), "20261019100000_remove_brand_profile_defaults");
|
|
||||||
await admin.$executeRawUnsafe(`CREATE SCHEMA "${schema}"`);
|
await admin.$executeRawUnsafe(`CREATE SCHEMA "${schema}"`);
|
||||||
createdSchema = true;
|
createdSchema = true;
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,7 @@
|
|||||||
|
{
|
||||||
|
"$schema": "https://turbo.build/schema.json",
|
||||||
|
"extends": ["//"],
|
||||||
|
"tasks": {
|
||||||
|
"lint": { "dependsOn": ["build", "^build"] }
|
||||||
|
}
|
||||||
|
}
|
||||||
+35
-1
@@ -61,7 +61,41 @@ pnpm --filter @personal-brand/taro test
|
|||||||
pnpm --filter @personal-brand/taro test:browser
|
pnpm --filter @personal-brand/taro test:browser
|
||||||
```
|
```
|
||||||
|
|
||||||
浏览器测试需要先启动 API 和餐饮 H5 预览。`PREVIEW_URL` 指定预览地址,`CHROMIUM_PATH` 指定本机 Chromium;测试只读取开发库,模拟错误响应用于失败路径,不写入真实数据。
|
完整浏览器回归需要同时启动四类服务,缺一会产生误导性的失败:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
# 1. API(3001)。CORS 必须放行 Admin 与两个 H5 预览来源,否则浏览器报 Failed to fetch。
|
||||||
|
CORS_ORIGINS=http://localhost:3002,http://localhost:3003,http://localhost:3005 \
|
||||||
|
pnpm --filter @personal-brand/api dev
|
||||||
|
|
||||||
|
# 2. Admin(3005)。dev server 会把 /api 代理到 3001;静态 preview 没有该代理。
|
||||||
|
ADMIN_PORT=3005 pnpm --filter @personal-brand/admin dev
|
||||||
|
|
||||||
|
# 3. 餐饮 H5(3002)
|
||||||
|
TEMPLATE_KEY=acheng-campus-food PREVIEW_PORT=3002 pnpm --filter @personal-brand/taro dev:h5
|
||||||
|
|
||||||
|
# 4. 林境 H5(3003)
|
||||||
|
TEMPLATE_KEY=linjing-editorial PREVIEW_PORT=3003 pnpm --filter @personal-brand/taro dev:h5
|
||||||
|
```
|
||||||
|
|
||||||
|
然后执行:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
ADMIN_URL=http://127.0.0.1:3005 PREVIEW_URL=http://127.0.0.1:3002 \
|
||||||
|
pnpm --filter @personal-brand/taro test:browser
|
||||||
|
```
|
||||||
|
|
||||||
|
`PREVIEW_URL` 指定餐饮预览地址,林境用例固定访问 `http://localhost:3003`,`CHROMIUM_PATH` 可指定本机 Chromium。测试只读取开发库,模拟错误响应用于失败路径,不写入真实数据。
|
||||||
|
|
||||||
|
当前 Taro 4.3 的 `dev:h5` watch 模式在本地会持续增长直至 OOM,而一次性构建正常。遇到该问题时改用 `TEMPLATE_KEY=<key> pnpm --filter @personal-brand/taro build:h5`,再通过静态服务器托管 `dist/<key>/h5`;静态托管同样需要把对应来源加入 `CORS_ORIGINS`。
|
||||||
|
|
||||||
|
PR 和本地可用轻量 smoke 验证 Admin 会话与创建品牌流程:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
pnpm test:browser:smoke
|
||||||
|
```
|
||||||
|
|
||||||
|
该命令会自动构建 Admin 并启动静态预览;完整浏览器回归仍使用 `pnpm --filter @personal-brand/taro test:browser`。
|
||||||
|
|
||||||
## 回滚与切换
|
## 回滚与切换
|
||||||
|
|
||||||
|
|||||||
@@ -11,7 +11,8 @@
|
|||||||
"typecheck": "tsc --noEmit",
|
"typecheck": "tsc --noEmit",
|
||||||
"lint": "pnpm --workspace-root exec eslint apps/taro/src apps/taro/config \"packages/template-*/taro/**/*.{ts,tsx}\"",
|
"lint": "pnpm --workspace-root exec eslint apps/taro/src apps/taro/config \"packages/template-*/taro/**/*.{ts,tsx}\"",
|
||||||
"test": "node --experimental-strip-types --test test/*.test.mjs",
|
"test": "node --experimental-strip-types --test test/*.test.mjs",
|
||||||
"test:browser": "playwright test"
|
"test:browser": "playwright test",
|
||||||
|
"test:browser:smoke": "playwright test -c playwright.smoke.config.ts"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@personal-brand/types": "workspace:*",
|
"@personal-brand/types": "workspace:*",
|
||||||
|
|||||||
@@ -0,0 +1,28 @@
|
|||||||
|
import { defineConfig } from "@playwright/test";
|
||||||
|
|
||||||
|
const adminOrigin = process.env.ADMIN_URL || "http://127.0.0.1:3005";
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
testDir: "./test/browser",
|
||||||
|
// PR smoke 只覆盖最容易影响所有后台操作的会话与品牌创建流程。
|
||||||
|
testMatch: ["admin-session.spec.ts", "brand-creation-and-page-scheme.spec.ts"],
|
||||||
|
timeout: 30000,
|
||||||
|
fullyParallel: false,
|
||||||
|
workers: 1,
|
||||||
|
use: {
|
||||||
|
viewport: { width: 1440, height: 1000 },
|
||||||
|
screenshot: "only-on-failure",
|
||||||
|
trace: "retain-on-failure",
|
||||||
|
launchOptions: { args: ["--no-sandbox"] },
|
||||||
|
},
|
||||||
|
reporter: [["list"]],
|
||||||
|
outputDir: "../../.codex-tasks/browser-smoke/raw",
|
||||||
|
webServer: {
|
||||||
|
// 使用已构建的 Admin 静态产物,避免在 CI 中额外启动 API 或 Vite 开发代理。
|
||||||
|
command:
|
||||||
|
"pnpm --dir ../../apps/admin exec vite preview --host 127.0.0.1 --port 3005 --strictPort",
|
||||||
|
url: `${adminOrigin}/admin/brands/new`,
|
||||||
|
reuseExistingServer: !process.env.CI,
|
||||||
|
timeout: 60000,
|
||||||
|
},
|
||||||
|
});
|
||||||
@@ -88,6 +88,27 @@ async function verifyCanvasTargets(page: Page, manifest: any, pageKey: string) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const adminOrigin = process.env.ADMIN_URL || "http://localhost:3005";
|
const adminOrigin = process.env.ADMIN_URL || "http://localhost:3005";
|
||||||
|
const consoleWarnings = new WeakMap<Page, string[]>();
|
||||||
|
|
||||||
|
test.beforeEach(({ page }) => {
|
||||||
|
const warnings: string[] = [];
|
||||||
|
consoleWarnings.set(page, warnings);
|
||||||
|
page.on("console", (message) => {
|
||||||
|
const text = message.text();
|
||||||
|
const isWarning =
|
||||||
|
message.type() === "warning" ||
|
||||||
|
(message.type() === "error" &&
|
||||||
|
(text.startsWith("Warning:") ||
|
||||||
|
text.includes("non-boolean attribute") ||
|
||||||
|
text.includes("empty string")));
|
||||||
|
if (isWarning) warnings.push(text);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test.afterEach(({ page }) => {
|
||||||
|
expect(consoleWarnings.get(page) ?? []).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
const brand = {
|
const brand = {
|
||||||
id: "brand-fixture",
|
id: "brand-fixture",
|
||||||
slug: "preview-fixture",
|
slug: "preview-fixture",
|
||||||
@@ -712,6 +733,9 @@ test("林境模板支持首页和主理人区域点选", async ({ page }) => {
|
|||||||
title: "专业资历",
|
title: "专业资历",
|
||||||
summary: "建筑与门系统经验",
|
summary: "建筑与门系统经验",
|
||||||
content: "持续服务私宅项目",
|
content: "持续服务私宅项目",
|
||||||
|
sortOrder: 0,
|
||||||
|
isPublished: true,
|
||||||
|
coverUrl: null,
|
||||||
config: {
|
config: {
|
||||||
pillars: editorialPillars,
|
pillars: editorialPillars,
|
||||||
serviceFlow: editorialFlow,
|
serviceFlow: editorialFlow,
|
||||||
|
|||||||
@@ -1,7 +1,28 @@
|
|||||||
import fs from "node:fs";
|
import fs from "node:fs";
|
||||||
import { test, expect } from "@playwright/test";
|
import { test, expect, type Page } from "@playwright/test";
|
||||||
|
|
||||||
const adminOrigin = process.env.ADMIN_URL || "http://localhost:3005";
|
const adminOrigin = process.env.ADMIN_URL || "http://localhost:3005";
|
||||||
|
const consoleWarnings = new WeakMap<Page, string[]>();
|
||||||
|
|
||||||
|
test.beforeEach(({ page }) => {
|
||||||
|
const warnings: string[] = [];
|
||||||
|
consoleWarnings.set(page, warnings);
|
||||||
|
page.on("console", (message) => {
|
||||||
|
const text = message.text();
|
||||||
|
const isWarning =
|
||||||
|
message.type() === "warning" ||
|
||||||
|
(message.type() === "error" &&
|
||||||
|
(text.startsWith("Warning:") ||
|
||||||
|
text.includes("non-boolean attribute") ||
|
||||||
|
text.includes("empty string")));
|
||||||
|
if (isWarning) warnings.push(text);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test.afterEach(({ page }) => {
|
||||||
|
expect(consoleWarnings.get(page) ?? []).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
const templateContent = JSON.parse(
|
const templateContent = JSON.parse(
|
||||||
fs.readFileSync("../../packages/template-acheng-campus-food/template.json", "utf8"),
|
fs.readFileSync("../../packages/template-acheng-campus-food/template.json", "utf8"),
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -11,13 +11,17 @@ const manifest = JSON.parse(
|
|||||||
);
|
);
|
||||||
const version = {
|
const version = {
|
||||||
id: "preview-browser-version",
|
id: "preview-browser-version",
|
||||||
|
templatePackageId: "preview-browser-package",
|
||||||
packageKey: manifest.packageKey,
|
packageKey: manifest.packageKey,
|
||||||
version: manifest.version,
|
version: manifest.version,
|
||||||
displayName: manifest.displayName,
|
displayName: manifest.displayName,
|
||||||
status: "imported",
|
status: "imported",
|
||||||
contentChecksum: "fixture-checksum",
|
contentChecksum: "fixture-checksum",
|
||||||
|
archiveChecksum: "fixture-archive-checksum",
|
||||||
|
importedAt: "2026-10-21T00:00:00.000Z",
|
||||||
|
updatedAt: "2026-10-21T00:00:00.000Z",
|
||||||
manifestSnapshot: manifest,
|
manifestSnapshot: manifest,
|
||||||
importedBy: { displayName: "模板管理员" },
|
importedBy: { id: "template-admin", username: "admin", displayName: "模板管理员" },
|
||||||
validationReport: {},
|
validationReport: {},
|
||||||
manifestSummary: { supportedIndustryTemplates: manifest.supportedIndustryTemplates },
|
manifestSummary: { supportedIndustryTemplates: manifest.supportedIndustryTemplates },
|
||||||
};
|
};
|
||||||
@@ -103,6 +107,16 @@ test("模板管理可重试预览,并切换我的、详情和禁止提交的
|
|||||||
}
|
}
|
||||||
if (url.pathname.endsWith("/admin/templates"))
|
if (url.pathname.endsWith("/admin/templates"))
|
||||||
return route.fulfill({ json: { items: [version], page: 1, pageSize: 20, total: 1 } });
|
return route.fulfill({ json: { items: [version], page: 1, pageSize: 20, total: 1 } });
|
||||||
|
if (url.pathname.endsWith("/admin/template-operations/failures"))
|
||||||
|
return route.fulfill({
|
||||||
|
json: {
|
||||||
|
since: "2026-09-21T00:00:00.000Z",
|
||||||
|
until: "2026-10-21T00:00:00.000Z",
|
||||||
|
days: 30,
|
||||||
|
backfilled: true,
|
||||||
|
failures: [],
|
||||||
|
},
|
||||||
|
});
|
||||||
if (url.pathname.endsWith("/admin/brands")) return route.fulfill({ json: [] });
|
if (url.pathname.endsWith("/admin/brands")) return route.fulfill({ json: [] });
|
||||||
return route.fulfill({ json: { name: "测试工作区" } });
|
return route.fulfill({ json: { name: "测试工作区" } });
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -18,12 +18,15 @@ type PackedChecksums = {
|
|||||||
|
|
||||||
type PreviewVersion = {
|
type PreviewVersion = {
|
||||||
id: string;
|
id: string;
|
||||||
|
templatePackageId: string;
|
||||||
packageKey: string;
|
packageKey: string;
|
||||||
version: string;
|
version: string;
|
||||||
displayName: string;
|
displayName: string;
|
||||||
status: "imported";
|
status: "imported";
|
||||||
manifestSnapshot: PackedManifest;
|
manifestSnapshot: PackedManifest;
|
||||||
importedBy: { displayName: string };
|
importedBy: { id: string; username: string; displayName: string };
|
||||||
|
importedAt: string;
|
||||||
|
updatedAt: string;
|
||||||
validationReport: Record<string, unknown>;
|
validationReport: Record<string, unknown>;
|
||||||
manifestSummary: { supportedIndustryTemplates: string[] };
|
manifestSummary: { supportedIndustryTemplates: string[] };
|
||||||
artifactPath: string;
|
artifactPath: string;
|
||||||
@@ -88,12 +91,15 @@ async function buildPreviewFixture(mediaCase: MediaCase) {
|
|||||||
const archivePath = path.join(temporary, archive);
|
const archivePath = path.join(temporary, archive);
|
||||||
const version: PreviewVersion = {
|
const version: PreviewVersion = {
|
||||||
id: `preview-media-${mediaCase.packageKey}-${mediaCase.industry}`,
|
id: `preview-media-${mediaCase.packageKey}-${mediaCase.industry}`,
|
||||||
|
templatePackageId: `preview-media-package-${mediaCase.packageKey}`,
|
||||||
packageKey: manifest.packageKey,
|
packageKey: manifest.packageKey,
|
||||||
version: manifest.version,
|
version: manifest.version,
|
||||||
displayName: manifest.displayName,
|
displayName: manifest.displayName,
|
||||||
status: "imported",
|
status: "imported",
|
||||||
manifestSnapshot: manifest,
|
manifestSnapshot: manifest,
|
||||||
importedBy: { displayName: "模板管理员" },
|
importedBy: { id: "template-admin", username: "admin", displayName: "模板管理员" },
|
||||||
|
importedAt: "2026-10-21T00:00:00.000Z",
|
||||||
|
updatedAt: "2026-10-21T00:00:00.000Z",
|
||||||
validationReport: {},
|
validationReport: {},
|
||||||
manifestSummary: { supportedIndustryTemplates: manifest.supportedIndustryTemplates },
|
manifestSummary: { supportedIndustryTemplates: manifest.supportedIndustryTemplates },
|
||||||
artifactPath: archivePath,
|
artifactPath: archivePath,
|
||||||
@@ -216,6 +222,16 @@ test("导入包预览矩阵展示身份、资源和完整媒体槽位", async ({
|
|||||||
total: 1,
|
total: 1,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
if (url.pathname.endsWith("/admin/template-operations/failures"))
|
||||||
|
return route.fulfill({
|
||||||
|
json: {
|
||||||
|
since: "2026-09-21T00:00:00.000Z",
|
||||||
|
until: "2026-10-21T00:00:00.000Z",
|
||||||
|
days: 30,
|
||||||
|
backfilled: true,
|
||||||
|
failures: [],
|
||||||
|
},
|
||||||
|
});
|
||||||
if (url.pathname.endsWith("/admin/brands")) return route.fulfill({ json: [] });
|
if (url.pathname.endsWith("/admin/brands")) return route.fulfill({ json: [] });
|
||||||
return route.fulfill({ json: { name: "测试工作区" } });
|
return route.fulfill({ json: { name: "测试工作区" } });
|
||||||
});
|
});
|
||||||
|
|||||||
+6
-1
@@ -18,7 +18,12 @@ RUN pnpm --filter @personal-brand/config build
|
|||||||
RUN pnpm --filter @personal-brand/types build
|
RUN pnpm --filter @personal-brand/types build
|
||||||
RUN pnpm --filter @personal-brand/validation build
|
RUN pnpm --filter @personal-brand/validation build
|
||||||
RUN pnpm --filter @personal-brand/api-client build
|
RUN pnpm --filter @personal-brand/api-client build
|
||||||
RUN pnpm add -w @tarojs/binding-linux-arm64-gnu@4.3.0
|
ARG TARGETARCH
|
||||||
|
RUN case "${TARGETARCH:-$(uname -m)}" in \
|
||||||
|
arm64 | aarch64) pnpm add -w @tarojs/binding-linux-arm64-gnu@4.3.0 ;; \
|
||||||
|
amd64 | x86_64) pnpm add -w @tarojs/binding-linux-x64-gnu@4.3.0 ;; \
|
||||||
|
*) echo "unsupported TARGETARCH: ${TARGETARCH:-$(uname -m)}" >&2; exit 1 ;; \
|
||||||
|
esac
|
||||||
RUN pnpm build:admin:preview
|
RUN pnpm build:admin:preview
|
||||||
|
|
||||||
FROM alpine:latest AS runtime
|
FROM alpine:latest AS runtime
|
||||||
|
|||||||
@@ -0,0 +1,53 @@
|
|||||||
|
import { mkdir, rm } from "node:fs/promises";
|
||||||
|
import path from "node:path";
|
||||||
|
import { spawnSync } from "node:child_process";
|
||||||
|
import {
|
||||||
|
backupPostgresDatabase,
|
||||||
|
pruneBackups,
|
||||||
|
scheduledBackupName,
|
||||||
|
verifyPostgresBackup,
|
||||||
|
} from "./database-backup.mjs";
|
||||||
|
|
||||||
|
const root = process.env.DEPLOY_ROOT;
|
||||||
|
if (!root || !path.isAbsolute(root)) throw new Error("DEPLOY_ROOT must be absolute");
|
||||||
|
process.loadEnvFile(path.join(root, "shared/.env.production"));
|
||||||
|
|
||||||
|
const container = process.env.POSTGRES_CONTAINER;
|
||||||
|
if (!container || !/^[a-zA-Z0-9_.-]+$/.test(container)) {
|
||||||
|
throw new Error("POSTGRES_CONTAINER is required");
|
||||||
|
}
|
||||||
|
const retentionDays = Number(process.env.BACKUP_RETENTION_DAYS ?? "14");
|
||||||
|
if (!Number.isInteger(retentionDays) || retentionDays < 1) {
|
||||||
|
throw new Error("BACKUP_RETENTION_DAYS must be a positive integer");
|
||||||
|
}
|
||||||
|
|
||||||
|
const directory = path.join(root, "shared/backups");
|
||||||
|
await mkdir(directory, { recursive: true });
|
||||||
|
const destination = path.join(directory, scheduledBackupName());
|
||||||
|
|
||||||
|
await backupPostgresDatabase({ container, destination });
|
||||||
|
try {
|
||||||
|
await verifyPostgresBackup({ container, file: destination });
|
||||||
|
} catch (error) {
|
||||||
|
await rm(destination, { force: true });
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
await pruneBackups(directory, { retentionDays });
|
||||||
|
|
||||||
|
const offsiteTarget = process.env.BACKUP_OFFSITE_TARGET?.trim();
|
||||||
|
if (offsiteTarget) {
|
||||||
|
if (
|
||||||
|
!/^[a-zA-Z0-9_.@:/-]+$/.test(offsiteTarget) ||
|
||||||
|
offsiteTarget.startsWith("-") ||
|
||||||
|
offsiteTarget.includes("..")
|
||||||
|
) {
|
||||||
|
throw new Error("BACKUP_OFFSITE_TARGET contains unsupported characters");
|
||||||
|
}
|
||||||
|
const result = spawnSync("rsync", ["-a", "--partial", destination, offsiteTarget], {
|
||||||
|
stdio: "inherit",
|
||||||
|
env: process.env,
|
||||||
|
});
|
||||||
|
if (result.status !== 0) throw new Error("Offsite backup copy failed");
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(`scheduled backup written: ${destination}`);
|
||||||
@@ -0,0 +1,138 @@
|
|||||||
|
import { createReadStream, createWriteStream } from "node:fs";
|
||||||
|
import { readdir, rename, rm, stat } from "node:fs/promises";
|
||||||
|
import path from "node:path";
|
||||||
|
import { spawn, spawnSync } from "node:child_process";
|
||||||
|
|
||||||
|
const DAY_MS = 24 * 60 * 60 * 1000;
|
||||||
|
const SCHEDULED_BACKUP = /^scheduled-\d{8}T\d{6}Z-\d+\.dump$/;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 定时备份文件名包含 UTC 秒级时间和进程号,避免同一秒内重复执行时覆盖已有备份。
|
||||||
|
*/
|
||||||
|
export function scheduledBackupName(date = new Date(), pid = process.pid) {
|
||||||
|
const stamp = date
|
||||||
|
.toISOString()
|
||||||
|
.replace(/[-:]/g, "")
|
||||||
|
.replace(/\.\d{3}Z$/, "Z");
|
||||||
|
if (!/^\d{8}T\d{6}Z$/.test(stamp)) throw new Error("Invalid backup timestamp");
|
||||||
|
return `scheduled-${stamp}-${pid}.dump`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 保留策略:
|
||||||
|
* - 发布前备份按文件名保留最近 7 份,保持原有发布回滚能力;
|
||||||
|
* - 定时备份按修改时间保留最近 retentionDays 天;
|
||||||
|
* - 同名临时文件由 pruneBackups 统一清理。
|
||||||
|
*/
|
||||||
|
export function selectExpiredBackups(
|
||||||
|
entries,
|
||||||
|
{ now = Date.now(), retentionDays = 14, keepReleaseBackups = 7 } = {},
|
||||||
|
) {
|
||||||
|
if (!Number.isInteger(retentionDays) || retentionDays < 1) {
|
||||||
|
throw new Error("retentionDays must be a positive integer");
|
||||||
|
}
|
||||||
|
if (!Number.isInteger(keepReleaseBackups) || keepReleaseBackups < 1) {
|
||||||
|
throw new Error("keepReleaseBackups must be a positive integer");
|
||||||
|
}
|
||||||
|
|
||||||
|
const cutoff = now - retentionDays * DAY_MS;
|
||||||
|
const expired = [];
|
||||||
|
const releaseBackups = entries
|
||||||
|
.filter((entry) => entry.name.endsWith(".dump") && !SCHEDULED_BACKUP.test(entry.name))
|
||||||
|
.sort((left, right) => right.name.localeCompare(left.name));
|
||||||
|
|
||||||
|
for (const entry of releaseBackups.slice(keepReleaseBackups)) expired.push(entry.name);
|
||||||
|
for (const entry of entries) {
|
||||||
|
if (SCHEDULED_BACKUP.test(entry.name) && entry.mtimeMs < cutoff) expired.push(entry.name);
|
||||||
|
}
|
||||||
|
|
||||||
|
return [...new Set(expired)];
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function backupPostgresDatabase({
|
||||||
|
container,
|
||||||
|
destination,
|
||||||
|
docker = "docker",
|
||||||
|
env = process.env,
|
||||||
|
}) {
|
||||||
|
const temporary = destination + ".tmp";
|
||||||
|
const child = spawn(
|
||||||
|
docker,
|
||||||
|
["exec", container, "sh", "-c", 'exec pg_dump -Fc -U "$POSTGRES_USER" -d "$POSTGRES_DB"'],
|
||||||
|
{ stdio: ["ignore", "pipe", "inherit"], env },
|
||||||
|
);
|
||||||
|
const output = createWriteStream(temporary, { flags: "wx", mode: 0o600 });
|
||||||
|
child.stdout.pipe(output);
|
||||||
|
try {
|
||||||
|
await Promise.all([
|
||||||
|
new Promise((resolve, reject) => {
|
||||||
|
child.on("error", reject);
|
||||||
|
child.on("exit", (code) =>
|
||||||
|
code === 0 ? resolve() : reject(new Error("Database backup failed")),
|
||||||
|
);
|
||||||
|
}),
|
||||||
|
new Promise((resolve, reject) => {
|
||||||
|
output.on("finish", resolve);
|
||||||
|
output.on("error", reject);
|
||||||
|
}),
|
||||||
|
]);
|
||||||
|
await rename(temporary, destination);
|
||||||
|
} catch (error) {
|
||||||
|
child.kill("SIGTERM");
|
||||||
|
output.destroy();
|
||||||
|
await rm(temporary, { force: true });
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function verifyPostgresBackup({
|
||||||
|
container,
|
||||||
|
file,
|
||||||
|
docker = "docker",
|
||||||
|
env = process.env,
|
||||||
|
}) {
|
||||||
|
const child = spawn(docker, ["exec", "-i", container, "pg_restore", "-l"], {
|
||||||
|
stdio: ["pipe", "ignore", "pipe"],
|
||||||
|
env,
|
||||||
|
});
|
||||||
|
const input = createReadStream(file);
|
||||||
|
let stderr = "";
|
||||||
|
child.stderr.setEncoding("utf8");
|
||||||
|
child.stderr.on("data", (chunk) => {
|
||||||
|
stderr += chunk;
|
||||||
|
});
|
||||||
|
input.pipe(child.stdin);
|
||||||
|
|
||||||
|
try {
|
||||||
|
await new Promise((resolve, reject) => {
|
||||||
|
child.on("error", reject);
|
||||||
|
input.on("error", reject);
|
||||||
|
child.stdin.on("error", (error) => {
|
||||||
|
if (error.code !== "EPIPE") reject(error);
|
||||||
|
});
|
||||||
|
child.on("exit", (code) => {
|
||||||
|
if (code === 0) resolve();
|
||||||
|
else reject(new Error(`Backup is not readable: ${stderr.trim() || "pg_restore failed"}`));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
input.destroy();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function pruneBackups(directory, options = {}) {
|
||||||
|
const entries = await readdir(directory);
|
||||||
|
const withStats = [];
|
||||||
|
for (const name of entries) {
|
||||||
|
const info = await stat(path.join(directory, name));
|
||||||
|
if (!info.isFile()) continue;
|
||||||
|
withStats.push({ name, mtimeMs: info.mtimeMs });
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const name of selectExpiredBackups(withStats, options)) {
|
||||||
|
await rm(path.join(directory, name));
|
||||||
|
}
|
||||||
|
for (const name of entries) {
|
||||||
|
if (name.endsWith(".dump.tmp")) await rm(path.join(directory, name), { force: true });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,132 @@
|
|||||||
|
import assert from "node:assert/strict";
|
||||||
|
import { chmod, mkdtemp, readFile, rm, stat, utimes, writeFile } from "node:fs/promises";
|
||||||
|
import os from "node:os";
|
||||||
|
import path from "node:path";
|
||||||
|
import test from "node:test";
|
||||||
|
import {
|
||||||
|
backupPostgresDatabase,
|
||||||
|
pruneBackups,
|
||||||
|
scheduledBackupName,
|
||||||
|
selectExpiredBackups,
|
||||||
|
verifyPostgresBackup,
|
||||||
|
} from "./database-backup.mjs";
|
||||||
|
|
||||||
|
test("定时备份文件名使用 UTC 时间和进程号", () => {
|
||||||
|
assert.equal(
|
||||||
|
scheduledBackupName(new Date("2026-10-23T09:45:00.123Z"), 42),
|
||||||
|
"scheduled-20261023T094500Z-42.dump",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("发布备份只保留最近 7 份,定时备份按保留天数清理", () => {
|
||||||
|
const now = Date.parse("2026-10-23T12:00:00Z");
|
||||||
|
const day = 24 * 60 * 60 * 1000;
|
||||||
|
const entries = [
|
||||||
|
...Array.from({ length: 8 }, (_, index) => ({
|
||||||
|
name: `2026100${index + 1}000000-release${index}.dump`,
|
||||||
|
mtimeMs: now,
|
||||||
|
})),
|
||||||
|
{ name: "scheduled-20261001T000000Z-1.dump", mtimeMs: now - 30 * day },
|
||||||
|
{ name: "scheduled-20261020T000000Z-2.dump", mtimeMs: now - 3 * day },
|
||||||
|
];
|
||||||
|
|
||||||
|
assert.deepEqual(selectExpiredBackups(entries, { now, retentionDays: 14 }), [
|
||||||
|
"20261001000000-release0.dump",
|
||||||
|
"scheduled-20261001T000000Z-1.dump",
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("非法保留天数会被拒绝", () => {
|
||||||
|
assert.throws(() => selectExpiredBackups([], { retentionDays: 0 }), /positive integer/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("pruneBackups 删除过期备份和残留临时文件", async () => {
|
||||||
|
const directory = await mkdtemp(path.join(os.tmpdir(), "personal-brand-backup-"));
|
||||||
|
const old = path.join(directory, "scheduled-20260101T000000Z-1.dump");
|
||||||
|
const current = path.join(directory, "scheduled-20261023T000000Z-2.dump");
|
||||||
|
const temporary = path.join(directory, "scheduled-20261023T000000Z-3.dump.tmp");
|
||||||
|
try {
|
||||||
|
await writeFile(old, "old");
|
||||||
|
await writeFile(current, "current");
|
||||||
|
await writeFile(temporary, "partial");
|
||||||
|
const oldTime = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
|
||||||
|
await utimes(old, oldTime, oldTime);
|
||||||
|
|
||||||
|
await pruneBackups(directory, { retentionDays: 14 });
|
||||||
|
|
||||||
|
await assert.rejects(stat(old), { code: "ENOENT" });
|
||||||
|
await assert.rejects(stat(temporary), { code: "ENOENT" });
|
||||||
|
assert.equal((await stat(current)).size, 7);
|
||||||
|
} finally {
|
||||||
|
await rm(directory, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
async function writeFakeDocker(directory, body) {
|
||||||
|
const file = path.join(directory, "docker");
|
||||||
|
await writeFile(file, "#!/bin/sh\n" + body, { mode: 0o755 });
|
||||||
|
await chmod(file, 0o755);
|
||||||
|
return file;
|
||||||
|
}
|
||||||
|
|
||||||
|
test("备份写入权限受限的 dump 文件并清理临时文件", async () => {
|
||||||
|
const directory = await mkdtemp(path.join(os.tmpdir(), "personal-brand-dump-"));
|
||||||
|
const destination = path.join(directory, "release.dump");
|
||||||
|
try {
|
||||||
|
const docker = await writeFakeDocker(directory, "printf 'dump-bytes'\n");
|
||||||
|
await backupPostgresDatabase({ container: "postgres", destination, docker });
|
||||||
|
|
||||||
|
assert.equal(await readFile(destination, "utf8"), "dump-bytes");
|
||||||
|
assert.equal((await stat(destination)).mode & 0o777, 0o600);
|
||||||
|
await assert.rejects(stat(destination + ".tmp"), { code: "ENOENT" });
|
||||||
|
} finally {
|
||||||
|
await rm(directory, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("pg_dump 失败时删除半成品备份", async () => {
|
||||||
|
const directory = await mkdtemp(path.join(os.tmpdir(), "personal-brand-dump-"));
|
||||||
|
const destination = path.join(directory, "release.dump");
|
||||||
|
try {
|
||||||
|
const docker = await writeFakeDocker(directory, "printf 'partial'; exit 1\n");
|
||||||
|
await assert.rejects(
|
||||||
|
backupPostgresDatabase({ container: "postgres", destination, docker }),
|
||||||
|
/Database backup failed/,
|
||||||
|
);
|
||||||
|
|
||||||
|
await assert.rejects(stat(destination), { code: "ENOENT" });
|
||||||
|
await assert.rejects(stat(destination + ".tmp"), { code: "ENOENT" });
|
||||||
|
} finally {
|
||||||
|
await rm(directory, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("备份可被 pg_restore 读取校验", async () => {
|
||||||
|
const directory = await mkdtemp(path.join(os.tmpdir(), "personal-brand-verify-"));
|
||||||
|
const file = path.join(directory, "release.dump");
|
||||||
|
try {
|
||||||
|
await writeFile(file, "dump-bytes");
|
||||||
|
const docker = await writeFakeDocker(directory, "cat >/dev/null; exit 0\n");
|
||||||
|
await verifyPostgresBackup({ container: "postgres", file, docker });
|
||||||
|
} finally {
|
||||||
|
await rm(directory, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("pg_restore 校验失败时报告不可读", async () => {
|
||||||
|
const directory = await mkdtemp(path.join(os.tmpdir(), "personal-brand-verify-"));
|
||||||
|
const file = path.join(directory, "release.dump");
|
||||||
|
try {
|
||||||
|
await writeFile(file, "broken");
|
||||||
|
const docker = await writeFakeDocker(
|
||||||
|
directory,
|
||||||
|
"cat >/dev/null; echo 'invalid header' >&2; exit 1\n",
|
||||||
|
);
|
||||||
|
await assert.rejects(
|
||||||
|
verifyPostgresBackup({ container: "postgres", file, docker }),
|
||||||
|
/invalid header/,
|
||||||
|
);
|
||||||
|
} finally {
|
||||||
|
await rm(directory, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -6,6 +6,8 @@ module.exports = {
|
|||||||
apps: [
|
apps: [
|
||||||
{
|
{
|
||||||
name: "personal-brand-api",
|
name: "personal-brand-api",
|
||||||
|
instances: 1,
|
||||||
|
exec_mode: "fork",
|
||||||
cwd: path.join(root, "current/apps/api"),
|
cwd: path.join(root, "current/apps/api"),
|
||||||
script: "dist/main.js",
|
script: "dist/main.js",
|
||||||
interpreter: process.execPath,
|
interpreter: process.execPath,
|
||||||
|
|||||||
@@ -0,0 +1,13 @@
|
|||||||
|
import assert from "node:assert/strict";
|
||||||
|
import test from "node:test";
|
||||||
|
import { createRequire } from "node:module";
|
||||||
|
|
||||||
|
process.env.DEPLOY_ROOT = "/srv/personal-brand";
|
||||||
|
const require = createRequire(import.meta.url);
|
||||||
|
const config = require("./ecosystem.config.cjs");
|
||||||
|
|
||||||
|
test("异常上报使用进程内存储时 PM2 必须保持单实例", () => {
|
||||||
|
assert.equal(config.apps.length, 1);
|
||||||
|
assert.equal(config.apps[0].instances, 1);
|
||||||
|
assert.equal(config.apps[0].exec_mode, "fork");
|
||||||
|
});
|
||||||
+41
-65
@@ -1,4 +1,3 @@
|
|||||||
import { createWriteStream } from "node:fs";
|
|
||||||
import {
|
import {
|
||||||
copyFile,
|
copyFile,
|
||||||
cp,
|
cp,
|
||||||
@@ -14,8 +13,10 @@ import {
|
|||||||
writeFile,
|
writeFile,
|
||||||
} from "node:fs/promises";
|
} from "node:fs/promises";
|
||||||
import path from "node:path";
|
import path from "node:path";
|
||||||
import { spawn, spawnSync } from "node:child_process";
|
import { spawnSync } from "node:child_process";
|
||||||
import { checkPackage } from "../scripts/deploy/check-package.mjs";
|
import { checkPackage } from "../scripts/deploy/check-package.mjs";
|
||||||
|
import { assertReleaseEnvironment } from "./release-environment.mjs";
|
||||||
|
import { backupPostgresDatabase, pruneBackups, verifyPostgresBackup } from "./database-backup.mjs";
|
||||||
|
|
||||||
const root = process.env.DEPLOY_ROOT;
|
const root = process.env.DEPLOY_ROOT;
|
||||||
if (!root || !path.isAbsolute(root)) throw new Error("DEPLOY_ROOT must be absolute");
|
if (!root || !path.isAbsolute(root)) throw new Error("DEPLOY_ROOT must be absolute");
|
||||||
@@ -28,20 +29,7 @@ if (!postgresContainer || !/^[a-zA-Z0-9_.-]+$/.test(postgresContainer)) {
|
|||||||
throw new Error("POSTGRES_CONTAINER is required for the database backup");
|
throw new Error("POSTGRES_CONTAINER is required for the database backup");
|
||||||
}
|
}
|
||||||
if (Number(process.versions.node.split(".")[0]) !== 24) throw new Error("Node.js 24 is required");
|
if (Number(process.versions.node.split(".")[0]) !== 24) throw new Error("Node.js 24 is required");
|
||||||
if (
|
const databaseUrl = assertReleaseEnvironment(process.env);
|
||||||
process.env.NODE_ENV !== "production" ||
|
|
||||||
!process.env.DATABASE_URL ||
|
|
||||||
!process.env.SESSION_SECRET ||
|
|
||||||
process.env.SESSION_SECRET.length < 32 ||
|
|
||||||
!process.env.DEFAULT_BRAND_ID ||
|
|
||||||
!process.env.LOCAL_MEDIA_ROOT
|
|
||||||
) {
|
|
||||||
throw new Error("Production environment is missing required values");
|
|
||||||
}
|
|
||||||
if (!path.isAbsolute(process.env.LOCAL_MEDIA_ROOT))
|
|
||||||
throw new Error("LOCAL_MEDIA_ROOT must be absolute");
|
|
||||||
if (process.env.API_PREFIX) throw new Error("API_PREFIX must be empty when Traefik strips /api");
|
|
||||||
const databaseUrl = new URL(process.env.DATABASE_URL);
|
|
||||||
const privateDatabaseHost = /^(10\.|192\.168\.|172\.(1[6-9]|2\d|3[0-1])\.)/.test(
|
const privateDatabaseHost = /^(10\.|192\.168\.|172\.(1[6-9]|2\d|3[0-1])\.)/.test(
|
||||||
databaseUrl.hostname,
|
databaseUrl.hostname,
|
||||||
);
|
);
|
||||||
@@ -110,6 +98,37 @@ async function installPm2Service() {
|
|||||||
run("systemctl", ["--user", "enable", pm2ServiceName]);
|
run("systemctl", ["--user", "enable", pm2ServiceName]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const backupTimerName = "personal-brand-backup.timer";
|
||||||
|
|
||||||
|
async function installBackupTimer(release) {
|
||||||
|
const directory = path.dirname(adminServiceFile);
|
||||||
|
const serviceFile = path.join(directory, "personal-brand-backup.service");
|
||||||
|
const timerFile = path.join(directory, backupTimerName);
|
||||||
|
await mkdir(directory, { recursive: true });
|
||||||
|
// 定时任务从 shared 读取稳定副本;发布回滚后 current 变了,备份任务仍然可用。
|
||||||
|
await copyFile(
|
||||||
|
path.join(release, "deploy/backup-db.mjs"),
|
||||||
|
path.join(root, "shared/backup-db.mjs"),
|
||||||
|
);
|
||||||
|
await copyFile(
|
||||||
|
path.join(release, "deploy/database-backup.mjs"),
|
||||||
|
path.join(root, "shared/database-backup.mjs"),
|
||||||
|
);
|
||||||
|
await writeFile(
|
||||||
|
serviceFile,
|
||||||
|
`[Unit]\nDescription=Personal Brand daily database backup\nAfter=network-online.target\nWants=network-online.target\n\n[Service]\nType=oneshot\nEnvironment=DEPLOY_ROOT=${root}\nEnvironment=HOME=${process.env.HOME ?? "/home/ubuntu"}\nEnvironment=PATH=${process.env.PATH}\nExecStart=${process.execPath} ${root}/shared/backup-db.mjs\n`,
|
||||||
|
{ mode: 0o644 },
|
||||||
|
);
|
||||||
|
await writeFile(
|
||||||
|
timerFile,
|
||||||
|
`[Unit]\nDescription=Daily Personal Brand database backup\n\n[Timer]\nOnCalendar=*-*-* 03:30:00\nPersistent=true\nRandomizedDelaySec=10m\n\n[Install]\nWantedBy=timers.target\n`,
|
||||||
|
{ mode: 0o644 },
|
||||||
|
);
|
||||||
|
run("systemctl", ["--user", "daemon-reload"]);
|
||||||
|
run("systemctl", ["--user", "enable", "--now", backupTimerName]);
|
||||||
|
run("systemctl", ["--user", "restart", backupTimerName]);
|
||||||
|
}
|
||||||
|
|
||||||
async function waitForAdminHealth() {
|
async function waitForAdminHealth() {
|
||||||
const url = "http://127.0.0.1:" + (process.env.ADMIN_STATIC_PORT ?? "3010") + "/admin/";
|
const url = "http://127.0.0.1:" + (process.env.ADMIN_STATIC_PORT ?? "3010") + "/admin/";
|
||||||
for (let attempt = 0; attempt < 20; attempt++) {
|
for (let attempt = 0; attempt < 20; attempt++) {
|
||||||
@@ -146,53 +165,6 @@ async function switchCurrent(target) {
|
|||||||
await rename(temporary, current);
|
await rename(temporary, current);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function backupDatabase(destination) {
|
|
||||||
const temporary = destination + ".tmp";
|
|
||||||
const child = spawn(
|
|
||||||
"docker",
|
|
||||||
[
|
|
||||||
"exec",
|
|
||||||
postgresContainer,
|
|
||||||
"sh",
|
|
||||||
"-c",
|
|
||||||
'exec pg_dump -Fc -U "$POSTGRES_USER" -d "$POSTGRES_DB"',
|
|
||||||
],
|
|
||||||
{ stdio: ["ignore", "pipe", "inherit"] },
|
|
||||||
);
|
|
||||||
const output = createWriteStream(temporary, { flags: "wx", mode: 0o600 });
|
|
||||||
child.stdout.pipe(output);
|
|
||||||
try {
|
|
||||||
await Promise.all([
|
|
||||||
new Promise((resolve, reject) => {
|
|
||||||
child.on("error", reject);
|
|
||||||
child.on("exit", (code) =>
|
|
||||||
code === 0 ? resolve() : reject(new Error("Database backup failed")),
|
|
||||||
);
|
|
||||||
}),
|
|
||||||
new Promise((resolve, reject) => {
|
|
||||||
output.on("finish", resolve);
|
|
||||||
output.on("error", reject);
|
|
||||||
}),
|
|
||||||
]);
|
|
||||||
await rename(temporary, destination);
|
|
||||||
} catch (error) {
|
|
||||||
await rm(temporary, { force: true });
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function pruneBackups(directory) {
|
|
||||||
const backups = (await readdir(directory, { withFileTypes: true }))
|
|
||||||
.filter((entry) => entry.isFile() && entry.name.endsWith(".dump"))
|
|
||||||
.map((entry) => entry.name)
|
|
||||||
.sort()
|
|
||||||
.reverse();
|
|
||||||
for (const backup of backups.slice(7)) await rm(path.join(directory, backup));
|
|
||||||
for (const entry of await readdir(directory)) {
|
|
||||||
if (entry.endsWith(".dump.tmp")) await rm(path.join(directory, entry), { force: true });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function pruneReleases(directory, currentRelease, previousRelease) {
|
async function pruneReleases(directory, currentRelease, previousRelease) {
|
||||||
const releases = (await readdir(directory, { withFileTypes: true }))
|
const releases = (await readdir(directory, { withFileTypes: true }))
|
||||||
.filter((entry) => entry.isDirectory())
|
.filter((entry) => entry.isDirectory())
|
||||||
@@ -379,8 +351,11 @@ try {
|
|||||||
release,
|
release,
|
||||||
);
|
);
|
||||||
run("pnpm", ["--filter", "@personal-brand/api", "exec", "prisma", "generate"], release);
|
run("pnpm", ["--filter", "@personal-brand/api", "exec", "prisma", "generate"], release);
|
||||||
await backupDatabase(path.join(root, "shared/backups", manifest.version + ".dump"));
|
const backupDirectory = path.join(root, "shared/backups");
|
||||||
await pruneBackups(path.join(root, "shared/backups"));
|
const releaseBackup = path.join(backupDirectory, manifest.version + ".dump");
|
||||||
|
await backupPostgresDatabase({ container: postgresContainer, destination: releaseBackup });
|
||||||
|
await verifyPostgresBackup({ container: postgresContainer, file: releaseBackup });
|
||||||
|
await pruneBackups(backupDirectory);
|
||||||
// 旧数据的模板包声明必须先收敛,migration 才能安全地删除兼容字段。
|
// 旧数据的模板包声明必须先收敛,migration 才能安全地删除兼容字段。
|
||||||
run(process.execPath, ["deploy/prepare-template-contract.mjs", ".", "--apply"], release);
|
run(process.execPath, ["deploy/prepare-template-contract.mjs", ".", "--apply"], release);
|
||||||
run("pnpm", ["--filter", "@personal-brand/api", "exec", "prisma", "migrate", "deploy"], release);
|
run("pnpm", ["--filter", "@personal-brand/api", "exec", "prisma", "migrate", "deploy"], release);
|
||||||
@@ -402,6 +377,7 @@ try {
|
|||||||
await writeFile(path.join(root, "shared/previous-release"), previous + "\n");
|
await writeFile(path.join(root, "shared/previous-release"), previous + "\n");
|
||||||
run("pm2", ["save"]);
|
run("pm2", ["save"]);
|
||||||
await pruneReleases(path.join(root, "releases"), release, previous);
|
await pruneReleases(path.join(root, "releases"), release, previous);
|
||||||
|
await installBackupTimer(release);
|
||||||
console.log("release installed: " + manifest.version);
|
console.log("release installed: " + manifest.version);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (routeUpdated) {
|
if (routeUpdated) {
|
||||||
|
|||||||
@@ -0,0 +1,41 @@
|
|||||||
|
import path from "node:path";
|
||||||
|
|
||||||
|
const PLACEHOLDER_PATTERN = /(replace-with|change-me|changeme|^your[-_ ]|example|placeholder)/i;
|
||||||
|
|
||||||
|
/** 判断值是否仍是示例占位符,而不是真实随机密钥。 */
|
||||||
|
export function isPlaceholderSecret(value) {
|
||||||
|
return PLACEHOLDER_PATTERN.test(value.trim());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 切流前校验共享生产环境文件。
|
||||||
|
* 除必填项外,必须拒绝示例密钥,避免上线后才在 API 启动时失败。
|
||||||
|
*/
|
||||||
|
export function assertReleaseEnvironment(environment) {
|
||||||
|
if (
|
||||||
|
environment.NODE_ENV !== "production" ||
|
||||||
|
!environment.DATABASE_URL ||
|
||||||
|
!environment.SESSION_SECRET ||
|
||||||
|
!environment.DEFAULT_BRAND_ID ||
|
||||||
|
!environment.LOCAL_MEDIA_ROOT
|
||||||
|
) {
|
||||||
|
throw new Error("Production environment is missing required values");
|
||||||
|
}
|
||||||
|
if (environment.SESSION_SECRET.trim().length < 32) {
|
||||||
|
throw new Error("SESSION_SECRET must contain at least 32 characters");
|
||||||
|
}
|
||||||
|
if (isPlaceholderSecret(environment.SESSION_SECRET)) {
|
||||||
|
throw new Error("SESSION_SECRET must not use an example placeholder");
|
||||||
|
}
|
||||||
|
if (!path.isAbsolute(environment.LOCAL_MEDIA_ROOT)) {
|
||||||
|
throw new Error("LOCAL_MEDIA_ROOT must be absolute");
|
||||||
|
}
|
||||||
|
if (environment.API_PREFIX) {
|
||||||
|
throw new Error("API_PREFIX must be empty when Traefik strips /api");
|
||||||
|
}
|
||||||
|
const throttleStore = environment.CLIENT_ERROR_THROTTLE_STORE ?? "memory";
|
||||||
|
if (!["memory", "postgres"].includes(throttleStore)) {
|
||||||
|
throw new Error("CLIENT_ERROR_THROTTLE_STORE must be memory or postgres");
|
||||||
|
}
|
||||||
|
return new URL(environment.DATABASE_URL);
|
||||||
|
}
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
import assert from "node:assert/strict";
|
||||||
|
import test from "node:test";
|
||||||
|
import { assertReleaseEnvironment } from "./release-environment.mjs";
|
||||||
|
|
||||||
|
const validEnvironment = {
|
||||||
|
NODE_ENV: "production",
|
||||||
|
DATABASE_URL: "postgresql://user:password@127.0.0.1:5432/personal_brand",
|
||||||
|
SESSION_SECRET: "Zx9vQ2mK7pL4rT8wY3nB6cF1hJ5sD0gA",
|
||||||
|
DEFAULT_BRAND_ID: "brand-1",
|
||||||
|
LOCAL_MEDIA_ROOT: "/srv/personal-brand/media",
|
||||||
|
};
|
||||||
|
|
||||||
|
test("生产环境校验接受真实随机密钥", () => {
|
||||||
|
const databaseUrl = assertReleaseEnvironment(validEnvironment);
|
||||||
|
assert.equal(databaseUrl.hostname, "127.0.0.1");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("生产环境校验拒绝示例占位密钥", () => {
|
||||||
|
assert.throws(
|
||||||
|
() =>
|
||||||
|
assertReleaseEnvironment({
|
||||||
|
...validEnvironment,
|
||||||
|
SESSION_SECRET: "replace-with-at-least-32-random-characters",
|
||||||
|
}),
|
||||||
|
/must not use an example placeholder/,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("生产环境校验拒绝过短密钥", () => {
|
||||||
|
assert.throws(
|
||||||
|
() => assertReleaseEnvironment({ ...validEnvironment, SESSION_SECRET: "short-secret" }),
|
||||||
|
/at least 32 characters/,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("生产环境校验拒绝缺失的必填项", () => {
|
||||||
|
assert.throws(
|
||||||
|
() => assertReleaseEnvironment({ ...validEnvironment, DEFAULT_BRAND_ID: "" }),
|
||||||
|
/missing required values/,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("生产环境校验拒绝 Traefik 之外的 API 前缀", () => {
|
||||||
|
assert.throws(
|
||||||
|
() => assertReleaseEnvironment({ ...validEnvironment, API_PREFIX: "/api" }),
|
||||||
|
/API_PREFIX must be empty/,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("生产环境校验拒绝未知的异常限流存储", () => {
|
||||||
|
assert.throws(
|
||||||
|
() => assertReleaseEnvironment({ ...validEnvironment, CLIENT_ERROR_THROTTLE_STORE: "redis" }),
|
||||||
|
/CLIENT_ERROR_THROTTLE_STORE must be memory or postgres/,
|
||||||
|
);
|
||||||
|
});
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
# 本地 CI 任务容器基础镜像:Node 24 + pnpm + Playwright 运行依赖。
|
||||||
|
# 构建(在仓库根目录执行):
|
||||||
|
# docker build -f deploy/runner/Dockerfile -t personal-brand-ci:node24 .
|
||||||
|
# Playwright 版本需与 apps/taro/package.json 保持一致;升级 Playwright 后重建本镜像。
|
||||||
|
FROM node:24-bookworm
|
||||||
|
|
||||||
|
ARG PNPM_VERSION=9.15.0
|
||||||
|
ARG PLAYWRIGHT_VERSION=1.58.2
|
||||||
|
# 必须与 pnpm-lock.yaml 中解析出的 Prisma 版本一致;升级 Prisma 后同步修改并重建镜像。
|
||||||
|
ARG PRISMA_VERSION=6.19.3
|
||||||
|
|
||||||
|
ENV PNPM_HOME=/usr/local/share/pnpm
|
||||||
|
ENV PATH=${PNPM_HOME}:${PATH}
|
||||||
|
|
||||||
|
RUN apt-get update \
|
||||||
|
&& apt-get install -y --no-install-recommends jq unzip \
|
||||||
|
&& rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
|
RUN corepack enable \
|
||||||
|
&& corepack prepare pnpm@${PNPM_VERSION} --activate \
|
||||||
|
&& pnpm --version
|
||||||
|
|
||||||
|
# 预装 Chromium 的系统依赖和浏览器本体,避免每个 job 重复执行 apt 与下载。
|
||||||
|
RUN npx --yes playwright@${PLAYWRIGHT_VERSION} install --with-deps chromium \
|
||||||
|
&& rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
|
# 预热 Prisma engines 到 /root/.cache/prisma。CI job 每次都是新容器,若不预热,
|
||||||
|
# 每个 job 的 prisma generate 都会重新访问 binaries.prisma.sh,网络抖动会直接拖垮 CI。
|
||||||
|
COPY apps/api/prisma/schema.prisma /tmp/prisma-warmup/schema.prisma
|
||||||
|
RUN printf '%s\n' '{"name":"prisma-warmup","private":true}' > /tmp/prisma-warmup/package.json \
|
||||||
|
&& cd /tmp/prisma-warmup \
|
||||||
|
&& DATABASE_URL=postgresql://warmup:warmup@127.0.0.1:5432/warmup npx --yes prisma@${PRISMA_VERSION} generate --schema schema.prisma \
|
||||||
|
&& rm -rf /tmp/prisma-warmup /root/.npm
|
||||||
|
|
||||||
|
WORKDIR /workspace
|
||||||
Executable
+157
@@ -0,0 +1,157 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# 在 CI 主机上安装并注册 Gitea Actions runner(Ubuntu/arm64 或 amd64)。
|
||||||
|
#
|
||||||
|
# 用法(在 runner 主机上、仓库之外执行):
|
||||||
|
# GITEA_URL=https://git.example.com RUNNER_TOKEN=xxx ./deploy/runner/install-runner.sh
|
||||||
|
# DRY_RUN=1 ... ./deploy/runner/install-runner.sh # 只打印将执行的命令
|
||||||
|
#
|
||||||
|
# 需要的环境变量:
|
||||||
|
# GITEA_URL Gitea 站点地址
|
||||||
|
# RUNNER_TOKEN 仓库 Settings → Actions → Runners 里生成的注册 token
|
||||||
|
# 可选:
|
||||||
|
# RUNNER_NAME runner 名称,默认取 hostname
|
||||||
|
# RUNNER_LABELS 默认 ubuntu-latest
|
||||||
|
# RUNNER_VERSION 默认 5.2.0
|
||||||
|
# RUNNER_ROOT 默认 $HOME/gitea-runner
|
||||||
|
# RUNNER_CAPACITY 默认 1,按 runner 主机资源设置并发数
|
||||||
|
# RUNNER_CONTAINER_OPTIONS 默认 "--cpus=1.5 --memory=4g"
|
||||||
|
# RUNNER_PNPM_STORE 宿主机 pnpm store 目录,默认 $RUNNER_ROOT/pnpm-store
|
||||||
|
# RUNNER_IMAGE 任务容器镜像,默认 node:24-bookworm;本地预构建镜像可传 personal-brand-ci:node24
|
||||||
|
# CACHE_PORT 默认 8193
|
||||||
|
# RUNNER_CACHE_HOST 默认 172.17.0.1(Docker 默认 bridge 网关)
|
||||||
|
# SKIP_LINGER 默认 0;设为 1 时不尝试用 sudo 开启 linger
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
GITEA_URL=${GITEA_URL:?需要设置 GITEA_URL}
|
||||||
|
RUNNER_TOKEN=${RUNNER_TOKEN:?需要设置 RUNNER_TOKEN}
|
||||||
|
RUNNER_NAME=${RUNNER_NAME:-$(hostname -s)}
|
||||||
|
RUNNER_LABELS=${RUNNER_LABELS:-ubuntu-latest}
|
||||||
|
RUNNER_VERSION=${RUNNER_VERSION:-5.2.0}
|
||||||
|
RUNNER_ROOT=${RUNNER_ROOT:-$HOME/gitea-runner}
|
||||||
|
RUNNER_CAPACITY=${RUNNER_CAPACITY:-1}
|
||||||
|
RUNNER_CONTAINER_OPTIONS=${RUNNER_CONTAINER_OPTIONS:-"--cpus=1.5 --memory=4g"}
|
||||||
|
RUNNER_PNPM_STORE=${RUNNER_PNPM_STORE:-$RUNNER_ROOT/pnpm-store}
|
||||||
|
RUNNER_IMAGE=${RUNNER_IMAGE:-node:24-bookworm}
|
||||||
|
CACHE_PORT=${CACHE_PORT:-8193}
|
||||||
|
RUNNER_CACHE_HOST=${RUNNER_CACHE_HOST:-172.17.0.1}
|
||||||
|
CACHE_DIR=${CACHE_DIR:-$RUNNER_ROOT/cache-data}
|
||||||
|
SKIP_LINGER=${SKIP_LINGER:-0}
|
||||||
|
DRY_RUN=${DRY_RUN:-0}
|
||||||
|
|
||||||
|
if [ "$DRY_RUN" != "1" ]; then
|
||||||
|
command -v docker >/dev/null 2>&1 || { echo "缺少 docker,请先安装并启动 Docker" >&2; exit 1; }
|
||||||
|
command -v systemctl >/dev/null 2>&1 || { echo "缺少 systemd,当前脚本只支持 systemd 主机" >&2; exit 1; }
|
||||||
|
fi
|
||||||
|
|
||||||
|
case "$(uname -m)" in
|
||||||
|
aarch64 | arm64) ARCH=arm64 ;;
|
||||||
|
x86_64 | amd64) ARCH=amd64 ;;
|
||||||
|
*) echo "不支持的架构: $(uname -m)" >&2; exit 1 ;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
run() {
|
||||||
|
if [ "$DRY_RUN" = "1" ]; then
|
||||||
|
echo "+ ${*//$RUNNER_TOKEN/***}"
|
||||||
|
else
|
||||||
|
"$@"
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
archive="gitea-runner-${RUNNER_VERSION}-linux-${ARCH}.xz"
|
||||||
|
base="https://dl.gitea.com/gitea-runner/${RUNNER_VERSION}"
|
||||||
|
|
||||||
|
run mkdir -p "$RUNNER_ROOT" "$CACHE_DIR" "$RUNNER_PNPM_STORE"
|
||||||
|
if [ ! -x "$RUNNER_ROOT/gitea-runner-${RUNNER_VERSION}-linux-${ARCH}" ]; then
|
||||||
|
run curl -fsSL -o "$RUNNER_ROOT/$archive" "$base/$archive"
|
||||||
|
run curl -fsSL -o "$RUNNER_ROOT/$archive.sha256" "$base/$archive.sha256"
|
||||||
|
run env -C "$RUNNER_ROOT" sha256sum -c "$archive.sha256"
|
||||||
|
run xz -d -f "$RUNNER_ROOT/$archive"
|
||||||
|
fi
|
||||||
|
run chmod +x "$RUNNER_ROOT/gitea-runner-${RUNNER_VERSION}-linux-${ARCH}"
|
||||||
|
|
||||||
|
# 把 pnpm store 挂到所有任务容器的固定路径;workflow 通过 npm_config_store_dir 指向它。
|
||||||
|
case " $RUNNER_CONTAINER_OPTIONS " in
|
||||||
|
*"/workspace/.pnpm-store"*) ;;
|
||||||
|
*) RUNNER_CONTAINER_OPTIONS="$RUNNER_CONTAINER_OPTIONS --volume=${RUNNER_PNPM_STORE}:/workspace/.pnpm-store" ;;
|
||||||
|
esac
|
||||||
|
run ln -sf "gitea-runner-${RUNNER_VERSION}-linux-${ARCH}" "$RUNNER_ROOT/gitea-runner"
|
||||||
|
|
||||||
|
label_specs() {
|
||||||
|
printf '%s\n' "$RUNNER_LABELS" | tr ',' '\n' | sed "s|^\(.*\)$|\1:docker://${RUNNER_IMAGE}|"
|
||||||
|
}
|
||||||
|
|
||||||
|
if [ ! -f "$RUNNER_ROOT/.runner" ]; then
|
||||||
|
run env -C "$RUNNER_ROOT" ./gitea-runner register \
|
||||||
|
--no-interactive \
|
||||||
|
--instance "$GITEA_URL" \
|
||||||
|
--token "$RUNNER_TOKEN" \
|
||||||
|
--name "$RUNNER_NAME" \
|
||||||
|
--labels "$(label_specs | paste -sd, -)"
|
||||||
|
fi
|
||||||
|
if [ -f "$RUNNER_ROOT/.runner" ]; then
|
||||||
|
run chmod 600 "$RUNNER_ROOT/.runner"
|
||||||
|
fi
|
||||||
|
|
||||||
|
run tee "$RUNNER_ROOT/config.yaml" >/dev/null <<CONFIG
|
||||||
|
log:
|
||||||
|
level: debug
|
||||||
|
runner:
|
||||||
|
file: .runner
|
||||||
|
capacity: ${RUNNER_CAPACITY}
|
||||||
|
timeout: 2h
|
||||||
|
fetch_timeout: 10s
|
||||||
|
fetch_interval: 2s
|
||||||
|
labels:
|
||||||
|
$(label_specs | sed 's|^| - "|; s|$|"|')
|
||||||
|
cache:
|
||||||
|
enabled: true
|
||||||
|
dir: ${CACHE_DIR}
|
||||||
|
host: ${RUNNER_CACHE_HOST}
|
||||||
|
port: ${CACHE_PORT}
|
||||||
|
container:
|
||||||
|
options: "${RUNNER_CONTAINER_OPTIONS}"
|
||||||
|
valid_volumes:
|
||||||
|
- ${RUNNER_PNPM_STORE}
|
||||||
|
docker_host: "-"
|
||||||
|
CONFIG
|
||||||
|
|
||||||
|
run mkdir -p "$HOME/.config/systemd/user"
|
||||||
|
run tee "$HOME/.config/systemd/user/gitea-runner.service" >/dev/null <<UNIT
|
||||||
|
[Unit]
|
||||||
|
Description=Gitea Actions Runner (${RUNNER_NAME})
|
||||||
|
After=network-online.target
|
||||||
|
Wants=network-online.target
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
WorkingDirectory=${RUNNER_ROOT}
|
||||||
|
ExecStart=${RUNNER_ROOT}/gitea-runner daemon -c ${RUNNER_ROOT}/config.yaml
|
||||||
|
Restart=always
|
||||||
|
RestartSec=5
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=default.target
|
||||||
|
UNIT
|
||||||
|
|
||||||
|
# 用户级 systemd 服务默认在最后一个会话退出后停止;开启 linger 才能在重启后自动拉起 runner。
|
||||||
|
if [ "$SKIP_LINGER" != "1" ] && command -v loginctl >/dev/null 2>&1; then
|
||||||
|
linger=$(loginctl show-user "$USER" -p Linger --value 2>/dev/null || true)
|
||||||
|
if [ "$linger" != "yes" ]; then
|
||||||
|
run sudo loginctl enable-linger "$USER"
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
run systemctl --user daemon-reload
|
||||||
|
run systemctl --user enable --now gitea-runner.service
|
||||||
|
|
||||||
|
# 任务容器经 Docker bridge 访问 runner 内置 cache server,ufw 默认 INPUT DROP 会拦截。
|
||||||
|
# Gitea Actions 会给每个 job 建独立 bridge(实测 192.168.x),因此三个私网段都要放行。
|
||||||
|
if command -v ufw >/dev/null 2>&1; then
|
||||||
|
for cidr in 172.16.0.0/12 192.168.0.0/16 10.0.0.0/8; do
|
||||||
|
run sudo ufw allow from "$cidr" to any port "$CACHE_PORT" proto tcp comment "gitea actions cache"
|
||||||
|
done
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo
|
||||||
|
echo "runner 已安装:$RUNNER_ROOT"
|
||||||
|
echo "检查状态:systemctl --user status gitea-runner.service"
|
||||||
|
echo "检查 linger:loginctl show-user \"$USER\" -p Linger"
|
||||||
|
echo "检查日志:journalctl --user -u gitea-runner -n 100 --no-pager"
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
# 0035 Admin 客户端异常上报的去重与限流
|
||||||
|
|
||||||
|
- 状态:已采纳
|
||||||
|
- 日期:2026-10-23
|
||||||
|
|
||||||
|
## Context
|
||||||
|
|
||||||
|
Admin 渲染异常上报 `POST /admin/client-errors` 需要防止两类问题:
|
||||||
|
|
||||||
|
- 同一次渲染错误在多个组件或重试中重复上报,制造日志噪音。
|
||||||
|
- 单账号在错误循环中高频上报,拖垮日志与请求处理。
|
||||||
|
|
||||||
|
生产 PM2 当前保持单实例(`deploy/ecosystem.config.cjs`),因此默认不需要额外基础设施。但当 API 扩展为多实例时,进程内窗口会让实际限流值按实例数放大,跨实例去重也会失效。
|
||||||
|
|
||||||
|
## Decision
|
||||||
|
|
||||||
|
1. 提供两种 `ClientErrorThrottleStore` 实现,由 `CLIENT_ERROR_THROTTLE_STORE` 选择:
|
||||||
|
- `memory`(默认):适合当前单实例 PM2,使用进程内 `Map`。
|
||||||
|
- `postgres`:适合多实例,使用数据库共享去重与限流状态。
|
||||||
|
2. 两种实现使用一致语义:
|
||||||
|
- 去重:`subject + errorId` 在 10 分钟内只接受一次。
|
||||||
|
- 限流:同一 `subject` 每分钟最多接受 10 条不同错误,超出返回 429。
|
||||||
|
3. Postgres 实现使用两张表:
|
||||||
|
- `ClientErrorDedupe` 通过 `(subject, errorId)` 唯一约束去重,并用条件 UPSERT 刷新过期记录。
|
||||||
|
- `ClientErrorThrottleWindow` 按 `subject` 单行保存当前窗口,使用原子 UPSERT 累加计数。
|
||||||
|
- 去重与限流在同一事务内完成,限流拒绝会回滚去重标记,避免客户端重试同一 `errorId` 时被误判为已记录。
|
||||||
|
4. 过期去重记录与旧限流窗口每分钟最多清理一次,清理失败只记录警告,不影响诊断上报。
|
||||||
|
5. 只有通过 `requireBrand` 认证的管理员才能上报,避免匿名刷量。未知的 `CLIENT_ERROR_THROTTLE_STORE` 值必须在启动时失败。
|
||||||
|
|
||||||
|
## Alternatives
|
||||||
|
|
||||||
|
- 只保留进程内实现:多实例下计数与去重不准确,拒绝作为唯一方案。
|
||||||
|
- 直接引入 Redis:增加部署与可用性依赖;当已经有 Postgres 时,数据库方案成本更低。
|
||||||
|
- 不做限流:错误循环会持续写日志,并放大客户端重试,拒绝。
|
||||||
|
- 把错误详情写入数据库:异常上报是诊断辅助数据,故障时不应继续给数据库增加业务写入压力;数据库只保存短期限流状态。
|
||||||
|
|
||||||
|
## Consequences
|
||||||
|
|
||||||
|
- 默认 `memory` 模式保持现有单实例部署的零额外依赖和低延迟。
|
||||||
|
- 多实例部署必须显式设置 `CLIENT_ERROR_THROTTLE_STORE=postgres`;只把 PM2 调成 cluster 模式而不切换存储,会重新引入按实例放大的问题。
|
||||||
|
- Postgres 模式每个接受的上报会增加少量事务写入,但只有已被放行的错误才会进入日志记录路径。
|
||||||
|
- 进程重启会清空 `memory` 模式的状态;`postgres` 模式在重启后仍能保持窗口。
|
||||||
|
- `memory` 模式使用滑动窗口;`postgres` 模式按自然分钟切分,边界附近可能出现短时双倍突发。这是诊断上报可接受的取舍。
|
||||||
|
|
||||||
|
## Migration plan
|
||||||
|
|
||||||
|
1. 当前单实例 PM2 继续使用默认 `memory` 模式。
|
||||||
|
2. 扩展 API 实例数前,先执行 `20261023130000_add_client_error_throttle` 迁移,并设置 `CLIENT_ERROR_THROTTLE_STORE=postgres`。
|
||||||
|
3. 验证多实例下同一 `errorId` 只记录一次,且单账号跨实例超过 10 条/分钟返回 429。
|
||||||
|
4. 如需 Redis 或消息队列,保留 `ClientErrorThrottleStore` 接口与响应形状,仅替换工厂实现并补充并发与过期测试。
|
||||||
+96
-8
@@ -1,20 +1,23 @@
|
|||||||
# CI(Gitea Actions)
|
# CI(Gitea Actions)
|
||||||
|
|
||||||
远端仓库是 Gitea,CI 由 `.gitea/workflows/ci.yml` 定义,运行在 `oracle_arm` 主机上的 self-hosted runner。
|
远端仓库是 Gitea,CI 由 `.gitea/workflows/ci.yml` 定义,运行在本地工作站 `Elitebook` 上的 self-hosted runner(x86_64、Docker、双并发)。旧的 `oracle_arm` runner 已停止并禁用,避免两个 runner 争抢 `ubuntu-latest` 标签。
|
||||||
|
|
||||||
## Runner
|
## Runner
|
||||||
|
|
||||||
- 程序:`gitea-runner` v5.2.0(linux/arm64),位于 `/home/ubuntu/gitea-runner`
|
安装与运维步骤见 `docs/runner-setup.md`(`deploy/runner/install-runner.sh` 可复现整套配置)。
|
||||||
|
|
||||||
|
- 程序:`gitea-runner` v5.2.0(linux/amd64),位于 `~/gitea-runner`
|
||||||
- 服务:systemd user unit `gitea-runner.service`
|
- 服务:systemd user unit `gitea-runner.service`
|
||||||
- 标签:`ubuntu-latest`、`oracle-arm`
|
- 标签:`ubuntu-latest`、`local-x64`
|
||||||
- 执行模式:Docker,单并发,任务容器限制 `--cpus=1.5 --memory=4g`
|
- 执行模式:Docker,双并发,任务容器限制 `--cpus=4 --memory=8g`
|
||||||
|
- 任务镜像:`personal-brand-ci:node24`(预装 pnpm 与 Playwright 依赖,见 `deploy/runner/Dockerfile`)
|
||||||
- 作用域:仅 `que01/persionalBrand` 仓库
|
- 作用域:仅 `que01/persionalBrand` 仓库
|
||||||
|
|
||||||
查看状态:
|
查看状态:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
ssh oracle_arm 'systemctl --user status gitea-runner.service'
|
systemctl --user status gitea-runner.service
|
||||||
ssh oracle_arm 'journalctl --user -u gitea-runner -n 100 --no-pager'
|
journalctl --user -u gitea-runner -n 100 --no-pager
|
||||||
```
|
```
|
||||||
|
|
||||||
## 当前门禁
|
## 当前门禁
|
||||||
@@ -22,9 +25,94 @@ ssh oracle_arm 'journalctl --user -u gitea-runner -n 100 --no-pager'
|
|||||||
- `static`:格式、lint、typecheck、模板检查、路由与模板 preview 覆盖
|
- `static`:格式、lint、typecheck、模板检查、路由与模板 preview 覆盖
|
||||||
- `build`:生产构建、Admin preview 构建、模板 release 校验
|
- `build`:生产构建、Admin preview 构建、模板 release 校验
|
||||||
- `api`:PostgreSQL service container 上的 API integration
|
- `api`:PostgreSQL service container 上的 API integration
|
||||||
|
- `browser-smoke`:PR 和手动触发时执行会话恢复、创建品牌与页面方案 smoke;只在 PR 和 `workflow_dispatch` 运行,main 合并后不重复执行
|
||||||
|
|
||||||
浏览器回归仍作为发布前本地门禁执行,避免在 2 核生产主机上运行 Playwright 抢占资源。
|
完整浏览器回归仍作为发布前本地门禁执行,避免在共享开发机上运行过重的 Playwright 套件。PR smoke 只跑两条关键流程,并使用已构建的 Admin 静态产物与 mocked API。
|
||||||
|
|
||||||
## 注意
|
## 注意
|
||||||
|
|
||||||
Runner 与生产 API 共用 `oracle_arm` 主机。任务容器已限制 CPU 与内存;如果 CI 期间生产延迟明显,应暂停 runner 或迁移到独立主机。
|
Runner 与本地开发工作共用 `Elitebook` 主机,不再与生产 API 共用资源。任务容器限制 4 CPU / 8 GB、并发 2;本地机器关机或休眠时 CI 会排队,required checks 不会自动完成。
|
||||||
|
|
||||||
|
## 工具链与外部下载
|
||||||
|
|
||||||
|
任务镜像 `personal-brand-ci:node24` 已内置 Node 24 和 pnpm 9.15.0;workflow 不再调用 `actions/setup-node` 或 `pnpm/action-setup`,而是在每个 job 开头执行 `Verify preinstalled toolchain`。这样不会因为 nodejs.org 下载缓慢或中断而把 job 卡到超时。
|
||||||
|
|
||||||
|
Prisma engines 在构建镜像时预热到 `/root/.cache/prisma`,job 内 `pnpm install` 触发的 `prisma generate` 直接命中缓存,不再访问 `binaries.prisma.sh`。workflow 仍用 `actions/cache` 缓存该目录,作为更换镜像或镜像未预热时的兜底。升级 Prisma 后必须同步 `deploy/runner/Dockerfile` 的 `PRISMA_VERSION` 并重建镜像。
|
||||||
|
|
||||||
|
## 缓存
|
||||||
|
|
||||||
|
Runner 内置 cache server(`cache.host=172.17.0.1`、`cache.port=8193`、`cache.dir=~/gitea-runner/cache-data`),供 `actions/cache` 使用(Turbo 缓存等)。
|
||||||
|
|
||||||
|
pnpm 依赖不再走 actions/cache:宿主机 `~/gitea-runner/pnpm-store` 被 bind mount 到任务容器的 `/workspace/.pnpm-store`,workflow 的 `npm_config_store_dir` 指向该路径。同一轮 CI 里的 static、build、api、browser-smoke 共享一份 store,`pnpm install` 只做链接/校验,不再重复下载 1600+ 个包。
|
||||||
|
|
||||||
|
如果 runner 主机启用了 `ufw`,任务容器到 cache server 的流量会被 `INPUT DROP` 拦截,需要显式放行 Docker 使用的三个私网网段;本地工作站未启用 `ufw`,无需配置:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
sudo ufw allow from 172.16.0.0/12 to any port 8193 proto tcp comment "gitea actions cache"
|
||||||
|
sudo ufw allow from 192.168.0.0/16 to any port 8193 proto tcp comment "gitea actions cache"
|
||||||
|
sudo ufw allow from 10.0.0.0/8 to any port 8193 proto tcp comment "gitea actions cache"
|
||||||
|
```
|
||||||
|
|
||||||
|
注意 Gitea Actions 会为每个 job 建立自己的 bridge 网络(实测网关为 `192.168.80.1`),不只是默认的 `172.17.0.1`;只放行 `172.16.0.0/12` 仍然会超时。
|
||||||
|
|
||||||
|
未放行时表现为 `Failed to GetCacheEntryDownloadURL ... ETIMEDOUT`,每个 job 会额外空等数分钟,且缓存永远不会命中。验证方式是在 job 容器内直接请求缓存端口:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker exec <job-container> node -e 'fetch("http://172.17.0.1:8193/").then(r=>console.log(r.status))'
|
||||||
|
```
|
||||||
|
|
||||||
|
返回 `404` 表示连通(该端口不提供根路径),超时表示仍被拦截。
|
||||||
|
|
||||||
|
Runner 日志级别保持 `debug`:`info` 级别不会记录各 step 的 `Success - Main ...` 与告警,排障时只能依赖 Gitea 页面。
|
||||||
|
|
||||||
|
## 迁移前基线(`oracle_arm`)
|
||||||
|
|
||||||
|
| 项 | 值 |
|
||||||
|
| ---------------- | ----------------------------- |
|
||||||
|
| run | `21`(`run_number=21`) |
|
||||||
|
| commit | `c33c9cb` |
|
||||||
|
| Static checks | 05:03:54 → 05:15:42 UTC,通过 |
|
||||||
|
| Production build | 05:15:47 → 05:27:27 UTC,通过 |
|
||||||
|
| API integration | 05:27:32 → 05:37:16 UTC,通过 |
|
||||||
|
|
||||||
|
单并发下整轮约 33 分钟;三个 job 串行执行,主要耗时在 `pnpm install` 与构建。
|
||||||
|
|
||||||
|
该轮次全部告警均来自缓存后端不可达(`ETIMEDOUT`),已按上一节修复。
|
||||||
|
|
||||||
|
修复后的对照数据(run `22`,commit `261a33a`;run `23` 的 static 为 5.7 分钟):
|
||||||
|
|
||||||
|
| job | 修复前耗时 | 修复后耗时 |
|
||||||
|
| ---------------- | ---------- | --------------------------------------------------------- |
|
||||||
|
| Static checks | 11.8 min | 11.7 min(该 job 在放行规则生效前启动,仍走缓存超时路径) |
|
||||||
|
| Production build | 11.7 min | 7.6 min |
|
||||||
|
| API integration | 9.7 min | 3.8 min |
|
||||||
|
|
||||||
|
缓存内容为 pnpm store,首次落盘约 1.1 GB,位于 `~/gitea-runner/pnpm-store`(共享 bind mount)。
|
||||||
|
|
||||||
|
## 触发范围
|
||||||
|
|
||||||
|
- `push` 到 `main` 时忽略纯文档改动(`**.md`),避免为文档提交跑完整 CI。
|
||||||
|
- `pull_request` 不设置 `paths-ignore`。branch protection 要求的 status check 必须每次都上报,否则纯文档 PR 会一直停在「等待检查」而无法合并。
|
||||||
|
- 需要给纯文档提交补一次状态时,用 `workflow_dispatch` 手动触发。
|
||||||
|
|
||||||
|
模板完成证据的源码哈希已同步收敛,文档、CI 配置和部署脚本改动不再使证据失效;模板、renderer、Admin 模板编辑器、品牌内容 API 等会影响交付的源码改动仍会更新哈希。`pre-commit` 会按 Git index 重算并暂存证据,不再需要单独的 `chore: 更新模板完成证据源码哈希` 提交。注意:`pre-commit` 只在该仓库执行过 `pnpm install`(触发 `prepare` 设置 `core.hooksPath`)后生效。
|
||||||
|
|
||||||
|
## 分支保护
|
||||||
|
|
||||||
|
`main` 由 Gitea branch protection 保护,规则为:
|
||||||
|
|
||||||
|
- 禁止直接 push 和 force push,所有改动走分支 + Pull Request。
|
||||||
|
- 必须通过 `CI / *` 状态检查(覆盖 `Static checks`、`Production build`、`API integration` 及其后续新增 job)。
|
||||||
|
- `required_approvals = 0`:当前是单人维护,不强制他人审批,但 CI 必须全绿。
|
||||||
|
|
||||||
|
仓库管理员如需紧急放行,应临时调整保护规则并在事后恢复,不要长期用管理员权限绕过检查。规则可通过 `PATCH /api/v1/repos/que01/persionalBrand/branch_protections/main` 复现:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"enable_push": false,
|
||||||
|
"enable_force_push": false,
|
||||||
|
"enable_status_check": true,
|
||||||
|
"status_check_contexts": ["CI / *"],
|
||||||
|
"required_approvals": 0
|
||||||
|
}
|
||||||
|
```
|
||||||
+28
-2
@@ -30,9 +30,33 @@ DEPLOY_TARGET=oracle_arm PUBLIC_BASE_URL=https://wechat.app.que01.top pnpm deplo
|
|||||||
pnpm deploy:status
|
pnpm deploy:status
|
||||||
```
|
```
|
||||||
|
|
||||||
数据库备份自动保留最近 7 份;备份归档在状态检查中通过 `pg_restore -l` 校验可读性。备份失败会清理未完成的临时文件,不自动删除数据库数据。发布成功后保留当前版本、上一版本和最近 5 个发布目录。状态检查同时报告 PM2 自启、磁盘空间、备份时间/可读性及发布目录数量。
|
数据库备份分两类:
|
||||||
|
|
||||||
备份当前仍在同一台 VPS 上,不等同于灾难恢复副本。应将 `shared/backups/*.dump` 定期复制到独立主机或对象存储,并至少每季度在隔离数据库执行一次恢复演练;不得在生产数据库上测试恢复。整机重启演练需在维护窗口执行,确认 Admin、API、PostgreSQL 和公网路由恢复后再结束维护。
|
- 发布备份:每次 `pnpm deploy:release` 在 migration 前创建,按版本名保留最近 7 份。
|
||||||
|
- 定时备份:由 user-level `personal-brand-backup.timer` 每天 03:30(VPS 本地时区)执行,写入 `shared/backups/scheduled-*.dump`,默认保留 14 天。
|
||||||
|
|
||||||
|
定时任务的脚本副本位于 `shared/backup-db.mjs` 和 `shared/database-backup.mjs`,不依赖当前 release 目录,回滚后仍可运行。每次备份先用 `pg_dump -Fc` 写入临时文件,再用 `pg_restore -l` 校验;校验失败会删除损坏文件并让本次任务失败。备份失败会清理未完成的临时文件,不自动删除数据库数据。发布成功后保留当前版本、上一版本和最近 5 个发布目录。
|
||||||
|
|
||||||
|
状态检查会验证备份定时器处于 active、最新备份不超过 36 小时(可用 `BACKUP_MAX_AGE_HOURS` 调整),并通过 `pg_restore -l` 校验可读性。状态检查同时报告 PM2 自启、磁盘空间、备份时间和发布目录数量。
|
||||||
|
|
||||||
|
如需异地副本,在 `shared/.env.production` 配置 `BACKUP_OFFSITE_TARGET`(`rsync` 目标,例如 `backup@example-host:/srv/personal-brand-backups/`),并为 `ubuntu` 用户预先配置 SSH key。未配置时备份只保留在同一台 VPS 上,不等同于灾难恢复副本。至少每季度应在隔离数据库执行一次恢复演练,不得在生产数据库上测试恢复;整机重启演练需在维护窗口执行,确认 Admin、API、PostgreSQL 和公网路由恢复后再结束维护。
|
||||||
|
|
||||||
|
## 微信登录配置
|
||||||
|
|
||||||
|
后台「小程序上传配置」中的 AppID 和上传私钥只用于构建、上传小程序代码,不等于访客登录配置。体验版或正式版调用 `wx.login` 后,API 还需要以下两个环境变量才能通过微信 `jscode2session` 换取 OpenID:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
WECHAT_APP_ID=wxd75d946d6978d183
|
||||||
|
WECHAT_APP_SECRET=<小程序 AppSecret>
|
||||||
|
```
|
||||||
|
|
||||||
|
两项写入 `shared/.env.production`,不要提交到仓库。`WECHAT_APP_ID` 必须与后台上传配置中的 AppID 一致;不一致时微信会返回 `40029` 或 `40163`。修改后重启 API:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
pm2 restart personal-brand-api
|
||||||
|
```
|
||||||
|
|
||||||
|
API 通过 `node --env-file=shared/.env.production` 启动,重启后会读取新值。`pnpm deploy:status` 会检查两项是否非空;缺失时状态检查失败。
|
||||||
|
|
||||||
## Nginx 反向代理
|
## Nginx 反向代理
|
||||||
|
|
||||||
@@ -88,6 +112,8 @@ SEED_ADMIN_PASSWORD=<first-boot-admin-password>
|
|||||||
|
|
||||||
`DATABASE_URL` 使用最小权限数据库账号。`SESSION_SECRET` 不能复用示例值或开发值。`DEFAULT_BRAND_ID` 供未携带 `brandSlug` 的公共请求使用,缺失时 API 返回 503,不会回退到硬编码品牌。
|
`DATABASE_URL` 使用最小权限数据库账号。`SESSION_SECRET` 不能复用示例值或开发值。`DEFAULT_BRAND_ID` 供未携带 `brandSlug` 的公共请求使用,缺失时 API 返回 503,不会回退到硬编码品牌。
|
||||||
|
|
||||||
|
`CLIENT_ERROR_THROTTLE_STORE` 默认为 `memory`,与当前 PM2 单实例模式匹配。扩展到多实例前必须先执行数据库迁移并改为 `postgres`,否则每个实例会各自限流与去重,实际阈值会被实例数量放大。
|
||||||
|
|
||||||
`CORS_ORIGINS` 默认为空并关闭跨域访问;只有 Admin 或预览应用从其他 origin 调用 API 时,才配置逗号分隔的 HTTPS origin allow-list。
|
`CORS_ORIGINS` 默认为空并关闭跨域访问;只有 Admin 或预览应用从其他 origin 调用 API 时,才配置逗号分隔的 HTTPS origin allow-list。
|
||||||
|
|
||||||
本次部署会为管理员账号引入 `tokenVersion`。既有 admin token 会因缺少当前版本号而失效,管理员需要重新登录;之后修改密码会立即撤销同一账号的旧 token。媒体上传使用 S3 兼容对象存储和预签名直传,生产环境必须配置独立的 `OBJECT_STORAGE_PUBLIC_URL`、最小权限访问密钥和专用 bucket。微信相关变量只在启用对应能力时配置,同样不能提交真实凭据。
|
本次部署会为管理员账号引入 `tokenVersion`。既有 admin token 会因缺少当前版本号而失效,管理员需要重新登录;之后修改密码会立即撤销同一账号的旧 token。媒体上传使用 S3 兼容对象存储和预签名直传,生产环境必须配置独立的 `OBJECT_STORAGE_PUBLIC_URL`、最小权限访问密钥和专用 bucket。微信相关变量只在启用对应能力时配置,同样不能提交真实凭据。
|
||||||
|
|||||||
@@ -0,0 +1,92 @@
|
|||||||
|
# CI Runner 安装与运维
|
||||||
|
|
||||||
|
CI 跑在自托管 Gitea Actions runner 上。当前使用本地工作站 `Elitebook`(x86_64、12 核、30 GB,Docker 容器执行),旧的 `oracle_arm` runner 已停止并禁用。本文件记录可复现的安装步骤,避免换机器时重新摸索。
|
||||||
|
|
||||||
|
## 一次性准备
|
||||||
|
|
||||||
|
1. 在 Gitea 仓库 Settings → Actions → Runners 里创建注册 token(只对单个仓库或整个实例生效)。
|
||||||
|
2. 目标主机需要:Docker、`curl`、`xz`、systemd;Node 不需要(任务容器自带)。`ufw` 和 `sudo` 仅在需要配置防火墙或 linger 时使用。
|
||||||
|
|
||||||
|
## 安装
|
||||||
|
|
||||||
|
把仓库里的脚本拷到目标主机后执行:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
GITEA_URL=https://git.example.com \
|
||||||
|
RUNNER_TOKEN=<注册 token> \
|
||||||
|
RUNNER_NAME=elitebook-local \
|
||||||
|
RUNNER_LABELS=ubuntu-latest,local-x64 \
|
||||||
|
RUNNER_CAPACITY=2 \
|
||||||
|
RUNNER_CONTAINER_OPTIONS='--cpus=4 --memory=8g' \
|
||||||
|
RUNNER_IMAGE=personal-brand-ci:node24 \
|
||||||
|
RUNNER_PNPM_STORE=$HOME/gitea-runner/pnpm-store \
|
||||||
|
SKIP_LINGER=1 \
|
||||||
|
./install-runner.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
加 `DRY_RUN=1` 可先看它准备执行哪些命令(token 会被替换成 `***`)。
|
||||||
|
|
||||||
|
脚本做的事:
|
||||||
|
|
||||||
|
1. 按架构下载 `gitea-runner-<version>-linux-<arch>`,校验 `.sha256` 后解压到 `~/gitea-runner`。
|
||||||
|
2. 用 `--no-interactive` 注册,写出 `.runner`(已存在则跳过,可重复执行)。
|
||||||
|
3. 生成 `config.yaml`:按 `RUNNER_CAPACITY` 设置并发,使用 `RUNNER_IMAGE`(默认 `node:24-bookworm`)作为任务容器镜像,内置 cache server 监听 `172.17.0.1:8193`,并按 `RUNNER_CONTAINER_OPTIONS` 限制任务容器资源。
|
||||||
|
4. 把 `RUNNER_PNPM_STORE`(默认 `~/gitea-runner/pnpm-store`)bind mount 到任务容器的 `/workspace/.pnpm-store`;workflow 通过 `npm_config_store_dir` 指向同一路径,所有 job 复用这份 pnpm store,避免重复下载依赖。
|
||||||
|
5. 为下载的 runner 二进制补上可执行权限,避免归档解压后出现 `Permission denied`。
|
||||||
|
6. 装 systemd user unit `gitea-runner.service`,执行 `loginctl enable-linger` 后 `enable --now`。
|
||||||
|
7. 放行任务容器到 cache 端口的 ufw 规则。
|
||||||
|
|
||||||
|
## 专用 CI 镜像
|
||||||
|
|
||||||
|
`browser-smoke` 需要 Chromium 及其系统库。为避免每个 job 重复执行 `playwright install --with-deps`,本机使用预构建镜像:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker build -f deploy/runner/Dockerfile -t personal-brand-ci:node24 .
|
||||||
|
```
|
||||||
|
|
||||||
|
镜像包含 Node 24、pnpm 9.15.0、git/curl/jq/unzip,以及 Playwright 1.58.2 的 Chromium、headless shell、FFmpeg 和系统依赖;构建时还会预热 Prisma engines 到 `/root/.cache/prisma`。构建产物是本机 amd64 镜像(约 3 GB),不推送到 registry。
|
||||||
|
|
||||||
|
workflow 不再使用 `actions/setup-node` 或 `pnpm/action-setup`,而是直接校验镜像内置的 Node/pnpm 版本。因此替换 `RUNNER_IMAGE` 时必须保证镜像内已有 Node 24 和 pnpm 9.15.0,否则 job 会在 `Verify preinstalled toolchain` 步骤失败。
|
||||||
|
|
||||||
|
`apps/taro/package.json` 升级 Playwright 后,同步修改 `deploy/runner/Dockerfile` 的 `PLAYWRIGHT_VERSION`;升级 Prisma 后,同步修改 `PRISMA_VERSION`。然后重建镜像并重启 runner:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker build -f deploy/runner/Dockerfile -t personal-brand-ci:node24 .
|
||||||
|
systemctl --user restart gitea-runner.service
|
||||||
|
```
|
||||||
|
|
||||||
|
镜像只在当前主机存在;换 runner 主机时需要重新构建。若在 ARM 主机构建,镜像会按该主机架构原生构建,不需要额外参数。
|
||||||
|
|
||||||
|
## 为什么 ufw 要放行三个网段
|
||||||
|
|
||||||
|
任务容器访问宿主机的 cache server 走 Docker bridge,`ufw` 默认 `INPUT DROP` 会直接丢包。Gitea Actions 每个 job 会新建独立 bridge(实测 `192.168.x`),默认 `docker0` 又是 `172.17.x`,所以需要 `172.16.0.0/12`、`192.168.0.0/16`、`10.0.0.0/8` 三条规则。只放行其中一条的后果是缓存恢复/保存各空等数分钟并最终超时。
|
||||||
|
|
||||||
|
## 日常检查
|
||||||
|
|
||||||
|
```bash
|
||||||
|
systemctl --user status gitea-runner.service
|
||||||
|
journalctl --user -u gitea-runner -n 100 --no-pager
|
||||||
|
du -sh ~/gitea-runner/cache-data ~/gitea-runner/pnpm-store
|
||||||
|
```
|
||||||
|
|
||||||
|
`pnpm-store` 会持续增长。确认没有 job 运行时,可以执行 `pnpm store prune` 清理未被引用的包(在任意任务容器里对 `/workspace/.pnpm-store` 执行,或直接删除旧目录后让下一次 job 重新填充)。
|
||||||
|
|
||||||
|
`pnpm deploy:status` 只检查 VPS 服务、备份和公网路由,不再把 CI runner 当作生产健康条件。runner 已迁到本地工作站,脚本会额外打印非阻断的 `ci-runner-local=`,也可以直接用上面的 `systemctl --user status gitea-runner.service` 检查。
|
||||||
|
|
||||||
|
## 排障
|
||||||
|
|
||||||
|
| 现象 | 先查什么 |
|
||||||
|
| ----------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- |
|
||||||
|
| push 后 CI 一直 queued 不启动 | runner 服务是否 active;Gitea 仓库 Runners 页面是否显示 online |
|
||||||
|
| 日志出现 `Failed to GetCacheEntryDownloadURL ... ETIMEDOUT` | ufw 是否放行三个私网段;`docker exec <job-container> node -e 'fetch("http://172.17.0.1:8193/")'` 应返回 404 |
|
||||||
|
| 一轮 CI 突然变慢 | 缓存是否命中;宿主机负载与磁盘余量 |
|
||||||
|
| 本机开发明显变慢 | 是否同时运行 build/api job;用 `docker stats` 检查任务容器资源 |
|
||||||
|
| 重启后 runner 没起来 | `loginctl show-user "$USER" -p Linger` 应为 `Linger=yes`;否则执行 `sudo loginctl enable-linger "$USER"` |
|
||||||
|
|
||||||
|
## 约束
|
||||||
|
|
||||||
|
- 本地 runner 使用 `capacity: 2`,每个任务容器限制 `4 CPU / 8 GB`;按宿主资源调整,不要超过实际可用内存。
|
||||||
|
- `~/gitea-runner/pnpm-store` 是所有 job 共享的 pnpm store。不要删除正在被 job 使用的 store;换 runner 主机时整目录拷贝或重新预热即可。
|
||||||
|
- 本地 runner 关机或休眠时,required checks 会保持 queued。需要开机自启时执行 `sudo loginctl enable-linger "$USER"`,否则用户会话退出后服务会停止。
|
||||||
|
- 日志级别保持 `debug`:`info` 级别不记录各 step 的结果行,排障时等于没有日志。
|
||||||
|
- 完整浏览器回归不进入定时或 main 推送 CI;PR 只运行轻量 browser smoke(见 `docs/ci.md`),完整套件仍在发布前执行。
|
||||||
@@ -30,7 +30,7 @@ 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 仍会让命令失败。
|
已逐条完成源码审阅的 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` 证据;每类证据必须包含实际命令、`exitCode=0`、日志或截图产物及其 SHA-256。registry 还必须记录 source tree hash;doctor 会计算当前仓库源码树(排除 `.codex-tasks/` 证据目录)的 hash,并在不匹配时拒绝完成态。doctor 会校验证据覆盖全部模板、产物存在且哈希一致。全部通过时 `completionStatus=complete`;证据文件缺失时保持 `unverified`;登记不完整或哈希不匹配时对应模板为 `incomplete` 并让命令失败。
|
完成证据登记在 `.codex-tasks/template-audit-execution/raw/completion-evidence.json`。每套模板必须提供 `real-manifest-interaction`、`save-reload-publish-isolation`、`visual-reference`、`empty-error-branches` 四类 `passed` 证据;每类证据必须包含实际命令、`exitCode=0`、日志或截图产物及其 SHA-256。registry 还必须记录 source tree hash;doctor 会计算当前仓库源码树的 hash,并在不匹配时拒绝完成态。哈希范围只包含会影响模板交付的源码:排除 `.codex-tasks/`、`.gitea/`、`deploy/`、`scripts/deploy/` 以及除 `docs/template-completion-rules.md` 之外的全部 markdown。改文档、改 CI 或改部署脚本不再让已完成证据失效,改模板、renderer、诊断器或本文件仍然会。doctor 会校验证据覆盖全部模板、产物存在且哈希一致。全部通过时 `completionStatus=complete`;证据文件缺失时保持 `unverified`;登记不完整或哈希不匹配时对应模板为 `incomplete` 并让命令失败。
|
||||||
|
|
||||||
AST 解析可追踪 workspace.brand、presentation、object 和局部别名。动态路径、跨组件和间接映射等未知情况标为 review,不能猜测为通过。诊断器包含正反故障注入测试。
|
AST 解析可追踪 workspace.brand、presentation、object 和局部别名。动态路径、跨组件和间接映射等未知情况标为 review,不能猜测为通过。诊断器包含正反故障注入测试。
|
||||||
|
|
||||||
@@ -94,3 +94,9 @@ Taro 小程序构建默认会把 CSS 中的 HTML 标签选择器重写为 `.h5-<
|
|||||||
4. 原生控件必查:显示类型、宽度、高度令牌、文字垂直居中、点击命中、安全区和底部遮挡。
|
4. 原生控件必查:显示类型、宽度、高度令牌、文字垂直居中、点击命中、安全区和底部遮挡。
|
||||||
5. 真机必查:request/media 合法域名、登录、拨号、复制、滚动、字体缩放和 iPhone 底部安全区。
|
5. 真机必查:request/media 合法域名、登录、拨号、复制、滚动、字体缩放和 iPhone 底部安全区。
|
||||||
6. 修复方式先查共享 reset、令牌和 Taro 运行时,再改模板局部样式;同类问题必须补产物契约测试或视觉清单项,不允许只改单个模板的单个按钮。
|
6. 修复方式先查共享 reset、令牌和 Taro 运行时,再改模板局部样式;同类问题必须补产物契约测试或视觉清单项,不允许只改单个模板的单个按钮。
|
||||||
|
|
||||||
|
## 证据哈希维护
|
||||||
|
|
||||||
|
`git config core.hooksPath .githooks` 由 `pnpm install` 的 `prepare` 自动设置,`.githooks/pre-commit` 会在提交前调用 `node scripts/template-evidence-refresh.mjs --stage`,把最新的 `sourceTreeHash` 合并进同一个提交。不要再用「先提交业务改动、再提交 `chore: 更新模板完成证据源码哈希`」的两段式流程:那会让真正的改动永远拿不到绿色 CI。
|
||||||
|
|
||||||
|
需要手动重算时执行 `pnpm evidence:refresh`;加 `--stage` 会同时 `git add -f` 已跟踪的证据文件。
|
||||||
@@ -8,6 +8,8 @@
|
|||||||
>
|
>
|
||||||
> 架构决策:ADR 0029:模板管理、导入与分发边界
|
> 架构决策:ADR 0029:模板管理、导入与分发边界
|
||||||
|
|
||||||
|
> 状态校正(2026-10-23):当前 `pnpm template:doctor` 对 `acheng-campus-food`、`atelier-solopreneur`、`linjing-editorial` 均返回 `staticStatus=pass`、`completionStatus=complete`、`unresolvedIssues=0`。下方 2026-10-17/18 记录中的 `unverified` 是历史证据,不代表当前状态。该报告只证明自动化证据齐全,不替代 Phase 8 的真实品牌操作、微信外部验证和运营审阅。
|
||||||
|
|
||||||
本文档把模板从本地开发、导出、线上导入、校验、预览、安装到小程序发布的完整工作固化为一个可追踪任务。后续代码、迁移、接口、后台页面、测试证据和已知缺口都必须回到本文登记。本文描述的是目标和实施门禁;没有对应代码、测试和运行证据的条目不能标记为完成。
|
本文档把模板从本地开发、导出、线上导入、校验、预览、安装到小程序发布的完整工作固化为一个可追踪任务。后续代码、迁移、接口、后台页面、测试证据和已知缺口都必须回到本文登记。本文描述的是目标和实施门禁;没有对应代码、测试和运行证据的条目不能标记为完成。
|
||||||
|
|
||||||
## 1. 背景和目标
|
## 1. 背景和目标
|
||||||
|
|||||||
@@ -75,4 +75,4 @@ Admin 直接复用 Taro renderer,模板原始 CSS 按 750 设计宽度转换
|
|||||||
|
|
||||||
## 本轮边界
|
## 本轮边界
|
||||||
|
|
||||||
本次先制定计划,功能实施尚未开始。聚焦内容编辑,不做任意拖拽布局或 HTML 入库。保留模板视觉和 H5 回退;不重置数据库或 seed,必要结构调整先制定兼容迁移。
|
截至 2026-10-23,`.codex-tasks/visual-editor-closure/SUBTASKS.csv` 中的 5 个子任务均已标记 `DONE`;本文保留为实现范围、验收标准和后续回归依据,当前状态以该 CSV 和实际验证记录为准。本轮仍聚焦内容编辑,不做任意拖拽布局或 HTML 入库。保留模板视觉和 H5 回退;不重置数据库或 seed,必要结构调整先制定兼容迁移。
|
||||||
+4
-1
@@ -14,6 +14,8 @@
|
|||||||
"format": "prettier --write .",
|
"format": "prettier --write .",
|
||||||
"format:check": "prettier --check .",
|
"format:check": "prettier --check .",
|
||||||
"check": "pnpm format:check && pnpm lint && pnpm typecheck && pnpm template:check",
|
"check": "pnpm format:check && pnpm lint && pnpm typecheck && pnpm template:check",
|
||||||
|
"prepare": "git config core.hooksPath .githooks || true",
|
||||||
|
"evidence:refresh": "node scripts/template-evidence-refresh.mjs",
|
||||||
"db:migrate": "pnpm --filter @personal-brand/api db:migrate",
|
"db:migrate": "pnpm --filter @personal-brand/api db:migrate",
|
||||||
"db:seed": "pnpm --filter @personal-brand/api db:seed",
|
"db:seed": "pnpm --filter @personal-brand/api db:seed",
|
||||||
"test:api-client": "pnpm --filter @personal-brand/api exec tsx --test ../../packages/api-client/test/**/*.test.ts",
|
"test:api-client": "pnpm --filter @personal-brand/api exec tsx --test ../../packages/api-client/test/**/*.test.ts",
|
||||||
@@ -48,7 +50,8 @@
|
|||||||
"check:local-media": "node scripts/check-local-media.mjs",
|
"check:local-media": "node scripts/check-local-media.mjs",
|
||||||
"test:template-doctor": "node --test scripts/test/template-doctor.test.mjs",
|
"test:template-doctor": "node --test scripts/test/template-doctor.test.mjs",
|
||||||
"build:taro:atelier": "TEMPLATE_KEY=atelier-solopreneur pnpm --filter @personal-brand/taro build:h5 && TEMPLATE_KEY=atelier-solopreneur pnpm --filter @personal-brand/taro build:weapp",
|
"build:taro:atelier": "TEMPLATE_KEY=atelier-solopreneur pnpm --filter @personal-brand/taro build:h5 && TEMPLATE_KEY=atelier-solopreneur pnpm --filter @personal-brand/taro build:weapp",
|
||||||
"build:taro:all": "pnpm build:taro:food && pnpm build:taro:linjing && pnpm build:taro:atelier"
|
"build:taro:all": "pnpm build:taro:food && pnpm build:taro:linjing && pnpm build:taro:atelier",
|
||||||
|
"test:browser:smoke": "pnpm --filter @personal-brand/types build && pnpm --filter @personal-brand/admin build && pnpm --filter @personal-brand/taro test:browser:smoke"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@eslint/js": "^9.17.0",
|
"@eslint/js": "^9.17.0",
|
||||||
|
|||||||
+69
-33
@@ -1,9 +1,10 @@
|
|||||||
import path from "node:path";
|
import path from "node:path";
|
||||||
import { spawnSync } from "node:child_process";
|
import { spawnSync } from "node:child_process";
|
||||||
import { fileURLToPath } from "node:url";
|
import { fileURLToPath, pathToFileURL } from "node:url";
|
||||||
|
|
||||||
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../..");
|
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../..");
|
||||||
const target = process.env.DEPLOY_TARGET ?? "oracle_arm";
|
const target = process.env.DEPLOY_TARGET ?? "oracle_arm";
|
||||||
|
const deployRoot = process.env.DEPLOY_ROOT ?? "/home/ubuntu/persional-brand";
|
||||||
const publicBaseUrl = (process.env.PUBLIC_BASE_URL ?? "https://wechat.app.que01.top").replace(
|
const publicBaseUrl = (process.env.PUBLIC_BASE_URL ?? "https://wechat.app.que01.top").replace(
|
||||||
/\/$/,
|
/\/$/,
|
||||||
"",
|
"",
|
||||||
@@ -15,43 +16,78 @@ function run(command, args) {
|
|||||||
process.stdout.write(result.stdout);
|
process.stdout.write(result.stdout);
|
||||||
}
|
}
|
||||||
|
|
||||||
run("ssh", [
|
// ssh 会把多个参数用空格拼成一个字符串交给远端 shell,整段脚本必须先整体加引号,
|
||||||
target,
|
// 否则 `bash -lc set -euo pipefail; ...` 只会执行 `set`,其余命令落到远端登录 shell。
|
||||||
"bash",
|
function shellQuote(value) {
|
||||||
"-lc",
|
return "'" + value.replace(/'/g, "'\\''") + "'";
|
||||||
[
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 生产状态检查只覆盖 VPS 上的服务和公网路由。
|
||||||
|
* CI runner 已迁到本地工作站,不能再把远端 gitea-runner.service 当成生产健康条件。
|
||||||
|
*/
|
||||||
|
export function buildRemoteStatusScript({ deployRoot: rootPath = deployRoot } = {}) {
|
||||||
|
if (!/^\/[a-zA-Z0-9_./-]+$/.test(rootPath)) throw new Error("Invalid deployment root");
|
||||||
|
|
||||||
|
return [
|
||||||
"set -euo pipefail",
|
"set -euo pipefail",
|
||||||
'source "$HOME/.nvm/nvm.sh"',
|
'source "$HOME/.nvm/nvm.sh"',
|
||||||
"export DEPLOY_ROOT=/home/ubuntu/persional-brand",
|
`export DEPLOY_ROOT=${shellQuote(rootPath)}`,
|
||||||
'printf "current=%s\\n" "$(readlink /home/ubuntu/persional-brand/current)"',
|
'printf "current=%s\\n" "$(readlink "$DEPLOY_ROOT/current")"',
|
||||||
'printf "api="; test "$(pm2 pid personal-brand-api)" != "0"; echo online',
|
'printf "api="; test "$(pm2 pid personal-brand-api)" != "0"; echo online',
|
||||||
'printf "pm2-autostart="; systemctl --user is-enabled personal-brand-pm2.service',
|
'printf "pm2-autostart="; systemctl --user is-enabled personal-brand-pm2.service',
|
||||||
'printf "admin="; systemctl --user is-active personal-brand-admin-static.service',
|
'printf "admin="; systemctl --user is-active personal-brand-admin-static.service',
|
||||||
'printf "database="; docker inspect -f "{{.State.Status}}" personal-brand-postgres-1',
|
'printf "database="; docker inspect -f "{{.State.Status}}" personal-brand-postgres-1',
|
||||||
'printf "backups="; find /home/ubuntu/persional-brand/shared/backups -maxdepth 1 -name "*.dump" | wc -l',
|
'printf "backups="; find "$DEPLOY_ROOT/shared/backups" -maxdepth 1 -name "*.dump" | wc -l',
|
||||||
'printf "latest-backup="; newest=$(find /home/ubuntu/persional-brand/shared/backups -maxdepth 1 -type f -name "*.dump" -printf "%T@ %p\\n" | sort -nr | head -1 | cut -d" " -f2-); test -n "$newest"; stat -c "%y %s bytes" "$newest"; docker exec -i personal-brand-postgres-1 pg_restore -l < "$newest" >/dev/null; echo readable',
|
'printf "latest-backup="; newest=$(find "$DEPLOY_ROOT/shared/backups" -maxdepth 1 -type f -name "*.dump" -printf "%T@ %p\\n" | sort -nr | head -1 | cut -d" " -f2-); test -n "$newest"; stat -c "%y %s bytes" "$newest"; docker exec -i personal-brand-postgres-1 pg_restore -l < "$newest" >/dev/null; echo readable',
|
||||||
'printf "backup-temp-files="; find /home/ubuntu/persional-brand/shared/backups -maxdepth 1 -type f -name "*.tmp" | wc -l',
|
'printf "backup-timer="; systemctl --user is-active personal-brand-backup.timer',
|
||||||
'printf "disk="; df -h / | awk "NR==2 {print \\$5 \" used, \" \\$4 \" free\"}"',
|
'printf "backup-age-hours="; newest=$(find "$DEPLOY_ROOT/shared/backups" -maxdepth 1 -type f -name "*.dump" -printf "%T@ %p\\n" | sort -nr | head -1 | cut -d" " -f2-); age=$(( ( $(date +%s) - $(stat -c %Y "$newest") ) / 3600 )); echo "$age"; test "$age" -le "${BACKUP_MAX_AGE_HOURS:-36}"',
|
||||||
'printf "release-count="; find /home/ubuntu/persional-brand/releases -mindepth 1 -maxdepth 1 -type d | wc -l',
|
'printf "backup-temp-files="; find "$DEPLOY_ROOT/shared/backups" -maxdepth 1 -type f -name "*.tmp" | wc -l',
|
||||||
].join("; "),
|
'printf "wechat-login="; if grep -q "^WECHAT_APP_ID=." "$DEPLOY_ROOT/shared/.env.production" && grep -q "^WECHAT_APP_SECRET=." "$DEPLOY_ROOT/shared/.env.production"; then echo configured; else echo missing; exit 1; fi',
|
||||||
]);
|
'printf "disk="; df -h / | awk \'NR==2 {print $5 " used, " $4 " free"}\'',
|
||||||
|
'printf "release-count="; find "$DEPLOY_ROOT/releases" -mindepth 1 -maxdepth 1 -type d | wc -l',
|
||||||
|
].join("; ");
|
||||||
|
}
|
||||||
|
|
||||||
for (const route of [
|
/**
|
||||||
"/admin/",
|
* CI runner 与生产状态是两件事。这里只做本地提示,runner 不活跃不应阻断部署状态检查。
|
||||||
"/template-preview/",
|
*/
|
||||||
"/api/health",
|
function printLocalRunnerStatus() {
|
||||||
"/media/seed/food-package-02.jpg",
|
const result = spawnSync("systemctl", ["--user", "is-active", "gitea-runner.service"], {
|
||||||
]) {
|
encoding: "utf8",
|
||||||
run("curl", [
|
});
|
||||||
"--fail",
|
const state = (result.stdout || "").trim();
|
||||||
"--silent",
|
process.stdout.write(`ci-runner-local=${state || "unknown"}\n`);
|
||||||
"--show-error",
|
}
|
||||||
"--max-time",
|
|
||||||
"10",
|
function main() {
|
||||||
"-o",
|
if (!/^[a-zA-Z0-9_.@:-]+$/.test(target)) throw new Error("Invalid deployment SSH target");
|
||||||
"/dev/null",
|
if (!/^\/[a-zA-Z0-9_./-]+$/.test(deployRoot)) throw new Error("Invalid deployment root");
|
||||||
"-w",
|
|
||||||
route + " %{http_code}\\n",
|
run("ssh", [target, "bash -lc " + shellQuote(buildRemoteStatusScript())]);
|
||||||
publicBaseUrl + route,
|
printLocalRunnerStatus();
|
||||||
]);
|
|
||||||
|
for (const route of [
|
||||||
|
"/admin/",
|
||||||
|
"/template-preview/",
|
||||||
|
"/api/health",
|
||||||
|
"/media/seed/food-package-02.jpg",
|
||||||
|
]) {
|
||||||
|
run("curl", [
|
||||||
|
"--fail",
|
||||||
|
"--silent",
|
||||||
|
"--show-error",
|
||||||
|
"--max-time",
|
||||||
|
"10",
|
||||||
|
"-o",
|
||||||
|
"/dev/null",
|
||||||
|
"-w",
|
||||||
|
route + " %{http_code}\\n",
|
||||||
|
publicBaseUrl + route,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
|
||||||
|
main();
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
import assert from "node:assert/strict";
|
||||||
|
import { spawnSync } from "node:child_process";
|
||||||
|
import test from "node:test";
|
||||||
|
import { buildRemoteStatusScript } from "./status.mjs";
|
||||||
|
|
||||||
|
test("生产状态脚本不再要求 VPS 上运行 CI runner", () => {
|
||||||
|
const script = buildRemoteStatusScript();
|
||||||
|
|
||||||
|
assert.doesNotMatch(script, /gitea-runner/);
|
||||||
|
assert.match(script, /pm2 pid personal-brand-api/);
|
||||||
|
assert.match(script, /pg_restore -l/);
|
||||||
|
assert.match(script, /personal-brand-backup\.timer/);
|
||||||
|
assert.match(script, /backup-age-hours/);
|
||||||
|
assert.match(script, /BACKUP_MAX_AGE_HOURS/);
|
||||||
|
assert.match(script, /wechat-login/);
|
||||||
|
assert.match(script, /WECHAT_APP_SECRET/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("生产状态脚本语法有效", () => {
|
||||||
|
const result = spawnSync("bash", ["-n"], {
|
||||||
|
input: buildRemoteStatusScript(),
|
||||||
|
encoding: "utf8",
|
||||||
|
});
|
||||||
|
|
||||||
|
assert.equal(result.status, 0, result.stderr);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("生产状态脚本使用调用方指定的部署目录", () => {
|
||||||
|
const script = buildRemoteStatusScript({ deployRoot: "/srv/personal-brand" });
|
||||||
|
|
||||||
|
assert.match(script, /DEPLOY_ROOT='\/srv\/personal-brand'/);
|
||||||
|
assert.match(script, /"\$DEPLOY_ROOT\/current"/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("非法部署目录会被拒绝", () => {
|
||||||
|
assert.throws(() => buildRemoteStatusScript({ deployRoot: "/srv/personal brand" }), /Invalid/);
|
||||||
|
});
|
||||||
@@ -431,32 +431,56 @@ function walkRepositoryFiles(root, directory = root) {
|
|||||||
return files;
|
return files;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function sourceTreeHash(root) {
|
const EVIDENCE_SCOPE_IGNORED_PREFIXES = [".codex-tasks/", ".gitea/", "deploy/", "scripts/deploy/"];
|
||||||
|
const EVIDENCE_SCOPE_IGNORED_EXTENSIONS = [".md", ".mdx"];
|
||||||
|
const EVIDENCE_SCOPE_ALWAYS_INCLUDED = ["docs/template-completion-rules.md"];
|
||||||
|
|
||||||
|
// 证据哈希只覆盖会影响模板交付的源码:文档、CI 配置和部署脚本的改动不使证据失效。
|
||||||
|
export function isEvidenceSourcePath(relativePath) {
|
||||||
|
const normalized = relativePath.split(path.sep).join("/");
|
||||||
|
if (EVIDENCE_SCOPE_ALWAYS_INCLUDED.includes(normalized)) return true;
|
||||||
|
if (EVIDENCE_SCOPE_IGNORED_PREFIXES.some((prefix) => normalized.startsWith(prefix))) return false;
|
||||||
|
return !EVIDENCE_SCOPE_IGNORED_EXTENSIONS.some((extension) => normalized.endsWith(extension));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function sourceTreeHash(root, options = {}) {
|
||||||
const rootPath = path.resolve(root);
|
const rootPath = path.resolve(root);
|
||||||
|
const { staged = false } = options;
|
||||||
let files;
|
let files;
|
||||||
|
let readContent;
|
||||||
if (fs.existsSync(path.join(rootPath, ".git"))) {
|
if (fs.existsSync(path.join(rootPath, ".git"))) {
|
||||||
const output = execFileSync(
|
// 只统计已跟踪文件:未纳入版本控制的文件不属于任何一次可复现的交付。
|
||||||
"git",
|
// staged 模式从 Git index 读取内容,供 pre-commit 使用,避免部分暂存时把
|
||||||
["ls-files", "-z", "--cached", "--others", "--exclude-standard"],
|
// 工作区里的未提交改动算进提交对应的证据哈希。
|
||||||
{ cwd: rootPath, maxBuffer: 64 * 1024 * 1024 },
|
const output = execFileSync("git", ["ls-files", "-z", "--cached"], {
|
||||||
);
|
cwd: rootPath,
|
||||||
|
maxBuffer: 64 * 1024 * 1024,
|
||||||
|
});
|
||||||
files = output
|
files = output
|
||||||
.toString("utf8")
|
.toString("utf8")
|
||||||
.split("\0")
|
.split("\0")
|
||||||
.filter((file) => file && !file.startsWith(".codex-tasks/"))
|
.filter((file) => file && isEvidenceSourcePath(file))
|
||||||
.map((file) => path.join(rootPath, file))
|
.map((file) => path.join(rootPath, file));
|
||||||
.filter((file) => fs.existsSync(file) && fs.statSync(file).isFile());
|
if (!staged) files = files.filter((file) => fs.existsSync(file) && fs.statSync(file).isFile());
|
||||||
|
readContent = staged
|
||||||
|
? (file) =>
|
||||||
|
execFileSync("git", ["show", ":" + path.relative(rootPath, file)], {
|
||||||
|
cwd: rootPath,
|
||||||
|
maxBuffer: 64 * 1024 * 1024,
|
||||||
|
})
|
||||||
|
: (file) => fs.readFileSync(file);
|
||||||
} else {
|
} else {
|
||||||
files = walkRepositoryFiles(rootPath).filter(
|
files = walkRepositoryFiles(rootPath).filter((file) =>
|
||||||
(file) => !path.relative(rootPath, file).startsWith(".codex-tasks/"),
|
isEvidenceSourcePath(path.relative(rootPath, file)),
|
||||||
);
|
);
|
||||||
|
readContent = (file) => fs.readFileSync(file);
|
||||||
}
|
}
|
||||||
files.sort();
|
files.sort();
|
||||||
const hash = crypto.createHash("sha256");
|
const hash = crypto.createHash("sha256");
|
||||||
for (const file of files) {
|
for (const file of files) {
|
||||||
hash.update(path.relative(rootPath, file));
|
hash.update(path.relative(rootPath, file));
|
||||||
hash.update("\0");
|
hash.update("\0");
|
||||||
hash.update(fs.readFileSync(file));
|
hash.update(readContent(file));
|
||||||
hash.update("\0");
|
hash.update("\0");
|
||||||
}
|
}
|
||||||
return hash.digest("hex");
|
return hash.digest("hex");
|
||||||
|
|||||||
Executable
+32
@@ -0,0 +1,32 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
import fs from "node:fs";
|
||||||
|
import path from "node:path";
|
||||||
|
import { execFileSync } from "node:child_process";
|
||||||
|
import { sourceTreeHash } from "./lib/template-doctor.mjs";
|
||||||
|
|
||||||
|
const REGISTRY = path.join(
|
||||||
|
".codex-tasks",
|
||||||
|
"template-audit-execution",
|
||||||
|
"raw",
|
||||||
|
"completion-evidence.json",
|
||||||
|
);
|
||||||
|
const shouldStage = process.argv.includes("--stage");
|
||||||
|
|
||||||
|
if (!fs.existsSync(REGISTRY)) {
|
||||||
|
console.log(`template evidence: ${REGISTRY} 不存在,跳过`);
|
||||||
|
process.exit(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
const registry = JSON.parse(fs.readFileSync(REGISTRY, "utf8"));
|
||||||
|
const nextHash = sourceTreeHash(process.cwd(), { staged: shouldStage });
|
||||||
|
if (registry.sourceTreeHash === nextHash) {
|
||||||
|
console.log("template evidence: 源码哈希已是最新");
|
||||||
|
process.exit(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
registry.sourceTreeHash = nextHash;
|
||||||
|
registry.generatedAt = new Date().toISOString();
|
||||||
|
fs.writeFileSync(REGISTRY, JSON.stringify(registry, null, 2) + "\n");
|
||||||
|
console.log(`template evidence: sourceTreeHash 更新为 ${nextHash}`);
|
||||||
|
|
||||||
|
if (shouldStage) execFileSync("git", ["add", "-f", REGISTRY], { stdio: "inherit" });
|
||||||
@@ -9,6 +9,7 @@ import {
|
|||||||
applyCompletionEvidence,
|
applyCompletionEvidence,
|
||||||
applyManualReview,
|
applyManualReview,
|
||||||
diagnoseTemplate,
|
diagnoseTemplate,
|
||||||
|
isEvidenceSourcePath,
|
||||||
sourceTreeHash,
|
sourceTreeHash,
|
||||||
} from "../lib/template-doctor.mjs";
|
} from "../lib/template-doctor.mjs";
|
||||||
|
|
||||||
@@ -78,6 +79,67 @@ test("CLI 自动发现全部模板,问题退出 1,未知模板退出 2", ()
|
|||||||
assert.equal(missing.status, 2);
|
assert.equal(missing.status, 2);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("证据哈希范围排除文档、CI 与部署脚本,保留模板交付相关源码", () => {
|
||||||
|
assert.equal(isEvidenceSourcePath("docs/ci.md"), false);
|
||||||
|
assert.equal(isEvidenceSourcePath("PROJECT_STATUS.md"), false);
|
||||||
|
assert.equal(isEvidenceSourcePath(".gitea/workflows/ci.yml"), false);
|
||||||
|
assert.equal(isEvidenceSourcePath("deploy/install-release.mjs"), false);
|
||||||
|
assert.equal(isEvidenceSourcePath("scripts/deploy/status.mjs"), false);
|
||||||
|
assert.equal(isEvidenceSourcePath(".codex-tasks/template-audit-execution/raw/a.json"), false);
|
||||||
|
assert.equal(isEvidenceSourcePath("docs/template-completion-rules.md"), true);
|
||||||
|
assert.equal(isEvidenceSourcePath("apps/api/src/main.ts"), true);
|
||||||
|
assert.equal(isEvidenceSourcePath("packages/template-linjing-editorial/template.json"), true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("文档改动不改变证据哈希,源码改动仍然改变", () => {
|
||||||
|
const root = fs.mkdtempSync(path.join(os.tmpdir(), "template-doctor-scope-"));
|
||||||
|
try {
|
||||||
|
fs.mkdirSync(path.join(root, "docs"), { recursive: true });
|
||||||
|
fs.writeFileSync(path.join(root, "app.ts"), "export const value = 1;\n");
|
||||||
|
const baseline = sourceTreeHash(root);
|
||||||
|
|
||||||
|
fs.writeFileSync(path.join(root, "PROJECT_STATUS.md"), "状态更新\n");
|
||||||
|
fs.writeFileSync(path.join(root, "docs", "ci.md"), "文档更新\n");
|
||||||
|
assert.equal(sourceTreeHash(root), baseline);
|
||||||
|
|
||||||
|
fs.writeFileSync(path.join(root, "docs", "template-completion-rules.md"), "规则更新\n");
|
||||||
|
assert.notEqual(sourceTreeHash(root), baseline);
|
||||||
|
|
||||||
|
fs.writeFileSync(path.join(root, "app.ts"), "export const value = 2;\n");
|
||||||
|
assert.notEqual(sourceTreeHash(root), baseline);
|
||||||
|
} finally {
|
||||||
|
fs.rmSync(root, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("pre-commit 证据哈希按暂存区计算,不受部分暂存和未跟踪文件影响", () => {
|
||||||
|
const root = fs.mkdtempSync(path.join(os.tmpdir(), "template-doctor-staged-"));
|
||||||
|
const git = (...args) => {
|
||||||
|
const result = spawnSync("git", args, { cwd: root, encoding: "utf8" });
|
||||||
|
assert.equal(result.status, 0, result.stderr);
|
||||||
|
return result.stdout;
|
||||||
|
};
|
||||||
|
try {
|
||||||
|
git("init", "-q");
|
||||||
|
fs.writeFileSync(path.join(root, "app.ts"), "export const value = 1;\n");
|
||||||
|
git("add", "app.ts");
|
||||||
|
const stagedBaseline = sourceTreeHash(root, { staged: true });
|
||||||
|
|
||||||
|
fs.writeFileSync(path.join(root, "app.ts"), "export const value = 2;\n");
|
||||||
|
fs.writeFileSync(path.join(root, "untracked.ts"), "export const draft = true;\n");
|
||||||
|
const stagedWithUnstagedEdits = sourceTreeHash(root, { staged: true });
|
||||||
|
assert.equal(stagedWithUnstagedEdits, stagedBaseline);
|
||||||
|
assert.notEqual(sourceTreeHash(root), stagedBaseline);
|
||||||
|
|
||||||
|
git("-c", "user.name=test", "-c", "user.email=test@example.com", "commit", "-qm", "one");
|
||||||
|
git("checkout", "--", "app.ts");
|
||||||
|
assert.equal(sourceTreeHash(root), stagedBaseline);
|
||||||
|
assert.equal(sourceTreeHash(root, { staged: true }), stagedBaseline);
|
||||||
|
} finally {
|
||||||
|
fs.rmSync(root, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
test("完成证据登记必须覆盖全部要求并校验产物哈希", () => {
|
test("完成证据登记必须覆盖全部要求并校验产物哈希", () => {
|
||||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), "template-doctor-evidence-"));
|
const root = fs.mkdtempSync(path.join(os.tmpdir(), "template-doctor-evidence-"));
|
||||||
const artifactPath = path.join(root, "integration.log");
|
const artifactPath = path.join(root, "integration.log");
|
||||||
|
|||||||
Reference in new issue
Block a user