refactor: 收口 Admin 会话与授权边界

This commit is contained in:
que01 committed 2026-10-19 10:13:13 +08:00
1 parent 0788480ce3
commit 4ef4be2071
67 files changed
+1890 -392

No files matched your search

@@ -1,23 +1,23 @@
{
"schemaVersion": 1,
"scope": "模板完成证据登记,保留命令、日志与产物哈希",
"generatedAt": "2026-10-19T01:15:00+08:00",
"generatedAt": "2026-10-19T02:30:00+08:00",
"templates": {
"acheng-campus-food": {
"real-manifest-interaction": {
"status": "passed",
"commands": [
"pnpm --filter @personal-brand/api test:integration",
"ADMIN_URL=http://127.0.0.1:3010 pnpm --filter @personal-brand/taro exec playwright test test/browser/admin-editor.spec.ts"
"ADMIN_URL=http://localhost:3005 pnpm --filter @personal-brand/taro exec playwright test test/browser/admin-editor.spec.ts"
],
"artifacts": [
{
"path": ".codex-tasks/template-audit-execution/raw/evidence-2026-10-18/api-integration.log",
"sha256": "f856baf44079516997ce8345fb843384fd4b47d5ca7009de49449d22e586ee7f"
"path": ".codex-tasks/template-audit-execution/raw/evidence-2026-10-19/api-integration.log",
"sha256": "75d40d84242c8be3218ddc00b520f44bea3e5accb75a7b170e2cc35959aba426"
},
{
"path": ".codex-tasks/template-audit-execution/raw/evidence-2026-10-18/admin-editor.log",
"sha256": "588b8e4372e91ddc58d7f2ba97111936469d5d3efa7d4c2f56b0356cc8d8541a"
"path": ".codex-tasks/template-audit-execution/raw/evidence-2026-10-19/admin-editor.log",
"sha256": "01323485f57007c7c932bc239ab07ad8147cfd3efef8eae885e524f90a93dd43"
}
],
"exitCode": 0
@@ -29,8 +29,8 @@
],
"artifacts": [
{
"path": ".codex-tasks/template-audit-execution/raw/evidence-2026-10-18/api-integration.log",
"sha256": "f856baf44079516997ce8345fb843384fd4b47d5ca7009de49449d22e586ee7f"
"path": ".codex-tasks/template-audit-execution/raw/evidence-2026-10-19/api-integration.log",
"sha256": "75d40d84242c8be3218ddc00b520f44bea3e5accb75a7b170e2cc35959aba426"
}
],
"exitCode": 0
@@ -38,24 +38,24 @@
"visual-reference": {
"status": "passed",
"commands": [
"TEMPLATE_PREVIEW_VISUAL_EVIDENCE=/home/que01/Project/persionalBrand/.codex-tasks/template-audit-execution/raw/visual-matrix-2026-10-18 ADMIN_URL=http://127.0.0.1:3010 pnpm --filter @personal-brand/taro exec playwright test test/browser/template-preview-media.spec.ts"
"TEMPLATE_PREVIEW_VISUAL_EVIDENCE=/home/que01/Project/persionalBrand/.codex-tasks/template-audit-execution/raw/visual-matrix-2026-10-19 ADMIN_URL=http://localhost:3005 pnpm --filter @personal-brand/taro exec playwright test test/browser/template-preview-media.spec.ts"
],
"artifacts": [
{
"path": ".codex-tasks/template-audit-execution/raw/evidence-2026-10-18/template-preview-media.log",
"sha256": "f8bc81dcf34094bc9bc430c5ef39fa919633ee58d21a6758cb2268bae8ba8125"
"path": ".codex-tasks/template-audit-execution/raw/evidence-2026-10-19/template-preview-media.log",
"sha256": "70cb23333a92751d8d711bbb9c9e0351b4b27c4b3bf9cf92fa74cfc6e70d8886"
},
{
"path": ".codex-tasks/template-audit-execution/raw/visual-matrix-2026-10-18/01-acheng-campus-food-food-320.png",
"sha256": "296fd872682a5474797bd2cfa7401e2fdf04904dfe1dcb0178d3057edd101666"
"path": ".codex-tasks/template-audit-execution/raw/visual-matrix-2026-10-19/01-acheng-campus-food-food-320.png",
"sha256": "8e8725895c61af3b77202d00a40a61c4e17d298ff9d2d47940a87565d8089329"
},
{
"path": ".codex-tasks/template-audit-execution/raw/visual-matrix-2026-10-18/01-acheng-campus-food-food-375.png",
"sha256": "6d51d0aae8828c0c85159fe764ab2cb7a0ab83de9d33a223406e920eb0dcc70d"
"path": ".codex-tasks/template-audit-execution/raw/visual-matrix-2026-10-19/01-acheng-campus-food-food-375.png",
"sha256": "4cfb078edea3b5223d7bd11899daeac67b4ccf84828f234a600b7429f3e3048f"
},
{
"path": ".codex-tasks/template-audit-execution/raw/visual-matrix-2026-10-18/01-acheng-campus-food-food-390.png",
"sha256": "cdb9cbbb078641866492e7d601253245fec6fa95dc8d917a550bfec5f9859a28"
"path": ".codex-tasks/template-audit-execution/raw/visual-matrix-2026-10-19/01-acheng-campus-food-food-390.png",
"sha256": "81113e44e82dc898a94d8755ff5ec8e248e4d5d0cb8eec7f100a694dc9d449da"
}
],
"exitCode": 0
@@ -63,33 +63,33 @@
"empty-error-branches": {
"status": "passed",
"commands": [
"TEMPLATE_PREVIEW_VISUAL_EVIDENCE=/home/que01/Project/persionalBrand/.codex-tasks/template-audit-execution/raw/visual-matrix-2026-10-18 ADMIN_URL=http://127.0.0.1:3010 pnpm --filter @personal-brand/taro exec playwright test test/browser/template-preview-media.spec.ts",
"ADMIN_URL=http://127.0.0.1:3010 pnpm --filter @personal-brand/taro exec playwright test test/browser/admin-editor.spec.ts"
"TEMPLATE_PREVIEW_VISUAL_EVIDENCE=/home/que01/Project/persionalBrand/.codex-tasks/template-audit-execution/raw/visual-matrix-2026-10-19 ADMIN_URL=http://localhost:3005 pnpm --filter @personal-brand/taro exec playwright test test/browser/template-preview-media.spec.ts",
"ADMIN_URL=http://localhost:3005 pnpm --filter @personal-brand/taro exec playwright test test/browser/admin-editor.spec.ts"
],
"artifacts": [
{
"path": ".codex-tasks/template-audit-execution/raw/evidence-2026-10-18/template-preview-media.log",
"sha256": "f8bc81dcf34094bc9bc430c5ef39fa919633ee58d21a6758cb2268bae8ba8125"
"path": ".codex-tasks/template-audit-execution/raw/evidence-2026-10-19/template-preview-media.log",
"sha256": "70cb23333a92751d8d711bbb9c9e0351b4b27c4b3bf9cf92fa74cfc6e70d8886"
},
{
"path": ".codex-tasks/template-audit-execution/raw/evidence-2026-10-18/admin-editor.log",
"sha256": "588b8e4372e91ddc58d7f2ba97111936469d5d3efa7d4c2f56b0356cc8d8541a"
"path": ".codex-tasks/template-audit-execution/raw/evidence-2026-10-19/admin-editor.log",
"sha256": "01323485f57007c7c932bc239ab07ad8147cfd3efef8eae885e524f90a93dd43"
},
{
"path": ".codex-tasks/template-audit-execution/raw/visual-matrix-2026-10-18/empty-01-acheng-campus-food-food.png",
"sha256": "c4abb911e0006f1749811d2161ddf78aa6cbee1910da5932209d2dd25cf1301c"
"path": ".codex-tasks/template-audit-execution/raw/visual-matrix-2026-10-19/empty-01-acheng-campus-food-food.png",
"sha256": "57360e276a98b1a2623114acb64bc3fc826f69a3cf9dfb961961f0fced5d90af"
},
{
"path": ".codex-tasks/template-audit-execution/raw/visual-matrix-2026-10-18/empty-02-atelier-solopreneur-personal.png",
"sha256": "19807439ca41c067185c7abc5f06d0e98749086fa35ef757db43066211d74f06"
"path": ".codex-tasks/template-audit-execution/raw/visual-matrix-2026-10-19/empty-02-atelier-solopreneur-personal.png",
"sha256": "32f6d6c2191da4aa23b4d27b2c89457db713aba46422eb7e7618f65676c70fd4"
},
{
"path": ".codex-tasks/template-audit-execution/raw/visual-matrix-2026-10-18/empty-03-linjing-editorial-personal.png",
"sha256": "890ef276bbc231ad7446c938e2767e8b37dba998e39143b50a9c21e13589854d"
"path": ".codex-tasks/template-audit-execution/raw/visual-matrix-2026-10-19/empty-03-linjing-editorial-personal.png",
"sha256": "433a469d71f7fbe3514ff5ca8faf642848f6d64ebe09a076b60a2d160e7e8305"
},
{
"path": ".codex-tasks/template-audit-execution/raw/visual-matrix-2026-10-18/empty-04-linjing-editorial-doors.png",
"sha256": "f0936ff7404fe5dfe5f047e9b84d0c7cbdd5434a4c75dfa9c3b0b169dda4b350"
"path": ".codex-tasks/template-audit-execution/raw/visual-matrix-2026-10-19/empty-04-linjing-editorial-doors.png",
"sha256": "5eaa90f39e05766c86bebd35598d9130b7548c34a77d82ce85d1ff8b3e5311c9"
}
],
"exitCode": 0
@@ -100,16 +100,16 @@
"status": "passed",
"commands": [
"pnpm --filter @personal-brand/api test:integration",
"ADMIN_URL=http://127.0.0.1:3010 pnpm --filter @personal-brand/taro exec playwright test test/browser/admin-editor.spec.ts"
"ADMIN_URL=http://localhost:3005 pnpm --filter @personal-brand/taro exec playwright test test/browser/admin-editor.spec.ts"
],
"artifacts": [
{
"path": ".codex-tasks/template-audit-execution/raw/evidence-2026-10-18/api-integration.log",
"sha256": "f856baf44079516997ce8345fb843384fd4b47d5ca7009de49449d22e586ee7f"
"path": ".codex-tasks/template-audit-execution/raw/evidence-2026-10-19/api-integration.log",
"sha256": "75d40d84242c8be3218ddc00b520f44bea3e5accb75a7b170e2cc35959aba426"
},
{
"path": ".codex-tasks/template-audit-execution/raw/evidence-2026-10-18/admin-editor.log",
"sha256": "588b8e4372e91ddc58d7f2ba97111936469d5d3efa7d4c2f56b0356cc8d8541a"
"path": ".codex-tasks/template-audit-execution/raw/evidence-2026-10-19/admin-editor.log",
"sha256": "01323485f57007c7c932bc239ab07ad8147cfd3efef8eae885e524f90a93dd43"
}
],
"exitCode": 0
@@ -121,8 +121,8 @@
],
"artifacts": [
{
"path": ".codex-tasks/template-audit-execution/raw/evidence-2026-10-18/api-integration.log",
"sha256": "f856baf44079516997ce8345fb843384fd4b47d5ca7009de49449d22e586ee7f"
"path": ".codex-tasks/template-audit-execution/raw/evidence-2026-10-19/api-integration.log",
"sha256": "75d40d84242c8be3218ddc00b520f44bea3e5accb75a7b170e2cc35959aba426"
}
],
"exitCode": 0
@@ -130,24 +130,24 @@
"visual-reference": {
"status": "passed",
"commands": [
"TEMPLATE_PREVIEW_VISUAL_EVIDENCE=/home/que01/Project/persionalBrand/.codex-tasks/template-audit-execution/raw/visual-matrix-2026-10-18 ADMIN_URL=http://127.0.0.1:3010 pnpm --filter @personal-brand/taro exec playwright test test/browser/template-preview-media.spec.ts"
"TEMPLATE_PREVIEW_VISUAL_EVIDENCE=/home/que01/Project/persionalBrand/.codex-tasks/template-audit-execution/raw/visual-matrix-2026-10-19 ADMIN_URL=http://localhost:3005 pnpm --filter @personal-brand/taro exec playwright test test/browser/template-preview-media.spec.ts"
],
"artifacts": [
{
"path": ".codex-tasks/template-audit-execution/raw/evidence-2026-10-18/template-preview-media.log",
"sha256": "f8bc81dcf34094bc9bc430c5ef39fa919633ee58d21a6758cb2268bae8ba8125"
"path": ".codex-tasks/template-audit-execution/raw/evidence-2026-10-19/template-preview-media.log",
"sha256": "70cb23333a92751d8d711bbb9c9e0351b4b27c4b3bf9cf92fa74cfc6e70d8886"
},
{
"path": ".codex-tasks/template-audit-execution/raw/visual-matrix-2026-10-18/02-atelier-solopreneur-personal-320.png",
"sha256": "bc86fd697e742cd3c8fb9581607e36917771d7783ed9e8f6adda667fcf998043"
"path": ".codex-tasks/template-audit-execution/raw/visual-matrix-2026-10-19/02-atelier-solopreneur-personal-320.png",
"sha256": "e55af9899393c7f9cfba9bb2b5c6ad6c447f90cf28dddd94da8feb6702fc8477"
},
{
"path": ".codex-tasks/template-audit-execution/raw/visual-matrix-2026-10-18/02-atelier-solopreneur-personal-375.png",
"sha256": "0c5d85656ebe7ca66896d8532fe15bc349f3f7581cfeb54fcc9626516d5e1b53"
"path": ".codex-tasks/template-audit-execution/raw/visual-matrix-2026-10-19/02-atelier-solopreneur-personal-375.png",
"sha256": "70d251ab829ebfc85dba7fd65ac423272af4af54b39f76d1bea9ebbe0f89bc2d"
},
{
"path": ".codex-tasks/template-audit-execution/raw/visual-matrix-2026-10-18/02-atelier-solopreneur-personal-390.png",
"sha256": "cfe3df22dc40f9f4a97d6b58f86f5947cd1c601c47895b0edc224c06f8a26b7e"
"path": ".codex-tasks/template-audit-execution/raw/visual-matrix-2026-10-19/02-atelier-solopreneur-personal-390.png",
"sha256": "a430e7c72f794d62f9f0248c52307b6f644ea5b6099ba6c8b929f365504c3b07"
}
],
"exitCode": 0
@@ -155,33 +155,33 @@
"empty-error-branches": {
"status": "passed",
"commands": [
"TEMPLATE_PREVIEW_VISUAL_EVIDENCE=/home/que01/Project/persionalBrand/.codex-tasks/template-audit-execution/raw/visual-matrix-2026-10-18 ADMIN_URL=http://127.0.0.1:3010 pnpm --filter @personal-brand/taro exec playwright test test/browser/template-preview-media.spec.ts",
"ADMIN_URL=http://127.0.0.1:3010 pnpm --filter @personal-brand/taro exec playwright test test/browser/admin-editor.spec.ts"
"TEMPLATE_PREVIEW_VISUAL_EVIDENCE=/home/que01/Project/persionalBrand/.codex-tasks/template-audit-execution/raw/visual-matrix-2026-10-19 ADMIN_URL=http://localhost:3005 pnpm --filter @personal-brand/taro exec playwright test test/browser/template-preview-media.spec.ts",
"ADMIN_URL=http://localhost:3005 pnpm --filter @personal-brand/taro exec playwright test test/browser/admin-editor.spec.ts"
],
"artifacts": [
{
"path": ".codex-tasks/template-audit-execution/raw/evidence-2026-10-18/template-preview-media.log",
"sha256": "f8bc81dcf34094bc9bc430c5ef39fa919633ee58d21a6758cb2268bae8ba8125"
"path": ".codex-tasks/template-audit-execution/raw/evidence-2026-10-19/template-preview-media.log",
"sha256": "70cb23333a92751d8d711bbb9c9e0351b4b27c4b3bf9cf92fa74cfc6e70d8886"
},
{
"path": ".codex-tasks/template-audit-execution/raw/evidence-2026-10-18/admin-editor.log",
"sha256": "588b8e4372e91ddc58d7f2ba97111936469d5d3efa7d4c2f56b0356cc8d8541a"
"path": ".codex-tasks/template-audit-execution/raw/evidence-2026-10-19/admin-editor.log",
"sha256": "01323485f57007c7c932bc239ab07ad8147cfd3efef8eae885e524f90a93dd43"
},
{
"path": ".codex-tasks/template-audit-execution/raw/visual-matrix-2026-10-18/empty-01-acheng-campus-food-food.png",
"sha256": "c4abb911e0006f1749811d2161ddf78aa6cbee1910da5932209d2dd25cf1301c"
"path": ".codex-tasks/template-audit-execution/raw/visual-matrix-2026-10-19/empty-01-acheng-campus-food-food.png",
"sha256": "57360e276a98b1a2623114acb64bc3fc826f69a3cf9dfb961961f0fced5d90af"
},
{
"path": ".codex-tasks/template-audit-execution/raw/visual-matrix-2026-10-18/empty-02-atelier-solopreneur-personal.png",
"sha256": "19807439ca41c067185c7abc5f06d0e98749086fa35ef757db43066211d74f06"
"path": ".codex-tasks/template-audit-execution/raw/visual-matrix-2026-10-19/empty-02-atelier-solopreneur-personal.png",
"sha256": "32f6d6c2191da4aa23b4d27b2c89457db713aba46422eb7e7618f65676c70fd4"
},
{
"path": ".codex-tasks/template-audit-execution/raw/visual-matrix-2026-10-18/empty-03-linjing-editorial-personal.png",
"sha256": "890ef276bbc231ad7446c938e2767e8b37dba998e39143b50a9c21e13589854d"
"path": ".codex-tasks/template-audit-execution/raw/visual-matrix-2026-10-19/empty-03-linjing-editorial-personal.png",
"sha256": "433a469d71f7fbe3514ff5ca8faf642848f6d64ebe09a076b60a2d160e7e8305"
},
{
"path": ".codex-tasks/template-audit-execution/raw/visual-matrix-2026-10-18/empty-04-linjing-editorial-doors.png",
"sha256": "f0936ff7404fe5dfe5f047e9b84d0c7cbdd5434a4c75dfa9c3b0b169dda4b350"
"path": ".codex-tasks/template-audit-execution/raw/visual-matrix-2026-10-19/empty-04-linjing-editorial-doors.png",
"sha256": "5eaa90f39e05766c86bebd35598d9130b7548c34a77d82ce85d1ff8b3e5311c9"
}
],
"exitCode": 0
@@ -192,16 +192,16 @@
"status": "passed",
"commands": [
"pnpm --filter @personal-brand/api test:integration",
"ADMIN_URL=http://127.0.0.1:3010 pnpm --filter @personal-brand/taro exec playwright test test/browser/admin-editor.spec.ts"
"ADMIN_URL=http://localhost:3005 pnpm --filter @personal-brand/taro exec playwright test test/browser/admin-editor.spec.ts"
],
"artifacts": [
{
"path": ".codex-tasks/template-audit-execution/raw/evidence-2026-10-18/api-integration.log",
"sha256": "f856baf44079516997ce8345fb843384fd4b47d5ca7009de49449d22e586ee7f"
"path": ".codex-tasks/template-audit-execution/raw/evidence-2026-10-19/api-integration.log",
"sha256": "75d40d84242c8be3218ddc00b520f44bea3e5accb75a7b170e2cc35959aba426"
},
{
"path": ".codex-tasks/template-audit-execution/raw/evidence-2026-10-18/admin-editor.log",
"sha256": "588b8e4372e91ddc58d7f2ba97111936469d5d3efa7d4c2f56b0356cc8d8541a"
"path": ".codex-tasks/template-audit-execution/raw/evidence-2026-10-19/admin-editor.log",
"sha256": "01323485f57007c7c932bc239ab07ad8147cfd3efef8eae885e524f90a93dd43"
}
],
"exitCode": 0
@@ -213,8 +213,8 @@
],
"artifacts": [
{
"path": ".codex-tasks/template-audit-execution/raw/evidence-2026-10-18/api-integration.log",
"sha256": "f856baf44079516997ce8345fb843384fd4b47d5ca7009de49449d22e586ee7f"
"path": ".codex-tasks/template-audit-execution/raw/evidence-2026-10-19/api-integration.log",
"sha256": "75d40d84242c8be3218ddc00b520f44bea3e5accb75a7b170e2cc35959aba426"
}
],
"exitCode": 0
@@ -222,36 +222,36 @@
"visual-reference": {
"status": "passed",
"commands": [
"TEMPLATE_PREVIEW_VISUAL_EVIDENCE=/home/que01/Project/persionalBrand/.codex-tasks/template-audit-execution/raw/visual-matrix-2026-10-18 ADMIN_URL=http://127.0.0.1:3010 pnpm --filter @personal-brand/taro exec playwright test test/browser/template-preview-media.spec.ts"
"TEMPLATE_PREVIEW_VISUAL_EVIDENCE=/home/que01/Project/persionalBrand/.codex-tasks/template-audit-execution/raw/visual-matrix-2026-10-19 ADMIN_URL=http://localhost:3005 pnpm --filter @personal-brand/taro exec playwright test test/browser/template-preview-media.spec.ts"
],
"artifacts": [
{
"path": ".codex-tasks/template-audit-execution/raw/evidence-2026-10-18/template-preview-media.log",
"sha256": "f8bc81dcf34094bc9bc430c5ef39fa919633ee58d21a6758cb2268bae8ba8125"
"path": ".codex-tasks/template-audit-execution/raw/evidence-2026-10-19/template-preview-media.log",
"sha256": "70cb23333a92751d8d711bbb9c9e0351b4b27c4b3bf9cf92fa74cfc6e70d8886"
},
{
"path": ".codex-tasks/template-audit-execution/raw/visual-matrix-2026-10-18/03-linjing-editorial-personal-320.png",
"sha256": "5185b355dfef3e7bd36019f9a549b6da74d5bed1ee93e8b8a1e2d0e153ef9cad"
"path": ".codex-tasks/template-audit-execution/raw/visual-matrix-2026-10-19/03-linjing-editorial-personal-320.png",
"sha256": "91ddbc9bd44476f55177320f241ba92dcedb80fb684aef525e0b25d5f7bbafc0"
},
{
"path": ".codex-tasks/template-audit-execution/raw/visual-matrix-2026-10-18/03-linjing-editorial-personal-375.png",
"sha256": "c0d87b677b3bd48460144d03646a791fac2ea004668346b5ee808ca1b4d02a89"
"path": ".codex-tasks/template-audit-execution/raw/visual-matrix-2026-10-19/03-linjing-editorial-personal-375.png",
"sha256": "6ead246000fb3039924c3451785d02facedf1d91dc39d37b567be427825ee2bf"
},
{
"path": ".codex-tasks/template-audit-execution/raw/visual-matrix-2026-10-18/03-linjing-editorial-personal-390.png",
"sha256": "3548b38659d59b1e3a8fff16a73bfa44b7eae6082b8f53688dfee6fe431257a7"
"path": ".codex-tasks/template-audit-execution/raw/visual-matrix-2026-10-19/03-linjing-editorial-personal-390.png",
"sha256": "46a2c912ec4d8ec0beaff9bd87fa0960b06dcdd52a341a6c487d5ecbb019b85a"
},
{
"path": ".codex-tasks/template-audit-execution/raw/visual-matrix-2026-10-18/04-linjing-editorial-doors-320.png",
"sha256": "2d3b5c678dba761126bd0f8c32ddb16f22075631951950cd115e92e9c8d736c6"
"path": ".codex-tasks/template-audit-execution/raw/visual-matrix-2026-10-19/04-linjing-editorial-doors-320.png",
"sha256": "024c48d7f72d5466dade9734bb52252ac929be8fe8f0003c33ce742263d515b5"
},
{
"path": ".codex-tasks/template-audit-execution/raw/visual-matrix-2026-10-18/04-linjing-editorial-doors-375.png",
"sha256": "b15bd96dba8b79873bf9c214cd9b8d7c3c3a418c1b9ff50be0fda8b132ec3f33"
"path": ".codex-tasks/template-audit-execution/raw/visual-matrix-2026-10-19/04-linjing-editorial-doors-375.png",
"sha256": "22649b1c9bb680b88a70be890a7e869fe807a3ce9da5fb162d4d832c0ead39c8"
},
{
"path": ".codex-tasks/template-audit-execution/raw/visual-matrix-2026-10-18/04-linjing-editorial-doors-390.png",
"sha256": "b17c4da052e3e501e2998121210f44c34f210bdb34b2bcdff516aaae86289ba3"
"path": ".codex-tasks/template-audit-execution/raw/visual-matrix-2026-10-19/04-linjing-editorial-doors-390.png",
"sha256": "a9fbee6a7e96c267d5960bc85061433ac3400971dcfe1ef35c1a6344313ce1ba"
}
],
"exitCode": 0
@@ -259,38 +259,38 @@
"empty-error-branches": {
"status": "passed",
"commands": [
"TEMPLATE_PREVIEW_VISUAL_EVIDENCE=/home/que01/Project/persionalBrand/.codex-tasks/template-audit-execution/raw/visual-matrix-2026-10-18 ADMIN_URL=http://127.0.0.1:3010 pnpm --filter @personal-brand/taro exec playwright test test/browser/template-preview-media.spec.ts",
"ADMIN_URL=http://127.0.0.1:3010 pnpm --filter @personal-brand/taro exec playwright test test/browser/admin-editor.spec.ts"
"TEMPLATE_PREVIEW_VISUAL_EVIDENCE=/home/que01/Project/persionalBrand/.codex-tasks/template-audit-execution/raw/visual-matrix-2026-10-19 ADMIN_URL=http://localhost:3005 pnpm --filter @personal-brand/taro exec playwright test test/browser/template-preview-media.spec.ts",
"ADMIN_URL=http://localhost:3005 pnpm --filter @personal-brand/taro exec playwright test test/browser/admin-editor.spec.ts"
],
"artifacts": [
{
"path": ".codex-tasks/template-audit-execution/raw/evidence-2026-10-18/template-preview-media.log",
"sha256": "f8bc81dcf34094bc9bc430c5ef39fa919633ee58d21a6758cb2268bae8ba8125"
"path": ".codex-tasks/template-audit-execution/raw/evidence-2026-10-19/template-preview-media.log",
"sha256": "70cb23333a92751d8d711bbb9c9e0351b4b27c4b3bf9cf92fa74cfc6e70d8886"
},
{
"path": ".codex-tasks/template-audit-execution/raw/evidence-2026-10-18/admin-editor.log",
"sha256": "588b8e4372e91ddc58d7f2ba97111936469d5d3efa7d4c2f56b0356cc8d8541a"
"path": ".codex-tasks/template-audit-execution/raw/evidence-2026-10-19/admin-editor.log",
"sha256": "01323485f57007c7c932bc239ab07ad8147cfd3efef8eae885e524f90a93dd43"
},
{
"path": ".codex-tasks/template-audit-execution/raw/visual-matrix-2026-10-18/empty-01-acheng-campus-food-food.png",
"sha256": "c4abb911e0006f1749811d2161ddf78aa6cbee1910da5932209d2dd25cf1301c"
"path": ".codex-tasks/template-audit-execution/raw/visual-matrix-2026-10-19/empty-01-acheng-campus-food-food.png",
"sha256": "57360e276a98b1a2623114acb64bc3fc826f69a3cf9dfb961961f0fced5d90af"
},
{
"path": ".codex-tasks/template-audit-execution/raw/visual-matrix-2026-10-18/empty-02-atelier-solopreneur-personal.png",
"sha256": "19807439ca41c067185c7abc5f06d0e98749086fa35ef757db43066211d74f06"
"path": ".codex-tasks/template-audit-execution/raw/visual-matrix-2026-10-19/empty-02-atelier-solopreneur-personal.png",
"sha256": "32f6d6c2191da4aa23b4d27b2c89457db713aba46422eb7e7618f65676c70fd4"
},
{
"path": ".codex-tasks/template-audit-execution/raw/visual-matrix-2026-10-18/empty-03-linjing-editorial-personal.png",
"sha256": "890ef276bbc231ad7446c938e2767e8b37dba998e39143b50a9c21e13589854d"
"path": ".codex-tasks/template-audit-execution/raw/visual-matrix-2026-10-19/empty-03-linjing-editorial-personal.png",
"sha256": "433a469d71f7fbe3514ff5ca8faf642848f6d64ebe09a076b60a2d160e7e8305"
},
{
"path": ".codex-tasks/template-audit-execution/raw/visual-matrix-2026-10-18/empty-04-linjing-editorial-doors.png",
"sha256": "f0936ff7404fe5dfe5f047e9b84d0c7cbdd5434a4c75dfa9c3b0b169dda4b350"
"path": ".codex-tasks/template-audit-execution/raw/visual-matrix-2026-10-19/empty-04-linjing-editorial-doors.png",
"sha256": "5eaa90f39e05766c86bebd35598d9130b7548c34a77d82ce85d1ff8b3e5311c9"
}
],
"exitCode": 0
}
}
},
"sourceTreeHash": "7c75d6c3fe05b9c09e1392deaa8114a18dedaa1074e0a9d9022e4ee757ae930e"
"sourceTreeHash": "616999880b203df896694cddf36c14ed8ed51eb24ee320850f80898b57503ad3"
}
@@ -0,0 +1,11 @@
Running 2 tests using 1 worker
(node:12847) Warning: The 'NO_COLOR' env is ignored due to the 'FORCE_COLOR' env being set.
(Use `node --trace-warnings ...` to show where the warning was created)
(node:12847) Warning: The 'NO_COLOR' env is ignored due to the 'FORCE_COLOR' env being set.
(Use `node --trace-warnings ...` to show where the warning was created)
✓ 1 test/browser/admin-editor.spec.ts:235:5 › Admin 按通用预览目标筛选字段并同步品牌草稿 (21.0s)
✓ 2 test/browser/admin-editor.spec.ts:654:5 › 林境模板支持首页和主理人区域点选 (22.2s)
2 passed (44.1s)
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,18 @@
Running 1 test using 1 worker
(node:12338) Warning: The 'NO_COLOR' env is ignored due to the 'FORCE_COLOR' env being set.
(Use `node --trace-warnings ...` to show where the warning was created)
(node:12338) Warning: The 'NO_COLOR' env is ignored due to the 'FORCE_COLOR' env being set.
(Use `node --trace-warnings ...` to show where the warning was created)
(node:12435) Warning: The 'NO_COLOR' env is ignored due to the 'FORCE_COLOR' env being set.
(Use `node --trace-warnings ...` to show where the warning was created)
(node:12543) Warning: The 'NO_COLOR' env is ignored due to the 'FORCE_COLOR' env being set.
(Use `node --trace-warnings ...` to show where the warning was created)
(node:12607) Warning: The 'NO_COLOR' env is ignored due to the 'FORCE_COLOR' env being set.
(Use `node --trace-warnings ...` to show where the warning was created)
(node:12662) Warning: The 'NO_COLOR' env is ignored due to the 'FORCE_COLOR' env being set.
(Use `node --trace-warnings ...` to show where the warning was created)
✓ 1 test/browser/template-preview-media.spec.ts:155:5 › 导入包预览矩阵展示身份、资源和完整媒体槽位 (9.1s)
1 passed (10.0s)
Binary file not shown.

After

Width:  |  Height:  |  Size: 75 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 80 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 62 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 56 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 66 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 63 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 96 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 108 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 107 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 69 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 78 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 75 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 74 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 68 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 104 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 89 KiB

+2 -2
View File
@@ -115,10 +115,10 @@ jobs:
node-version: 24
cache: pnpm
- run: pnpm install --frozen-lockfile
- run: pnpm --filter @personal-brand/taro build:h5
- run: TEMPLATE_KEY=acheng-campus-food pnpm --filter @personal-brand/taro build:h5
env:
TEMPLATE_KEY: ${{ matrix.template }}
- run: pnpm --filter @personal-brand/taro build:weapp
- run: TEMPLATE_KEY=acheng-campus-food pnpm --filter @personal-brand/taro build:weapp
env:
TEMPLATE_KEY: ${{ matrix.template }}
+1 -8
View File
@@ -12,7 +12,6 @@ import {
} from "@ant-design/icons";
import { useLocation, useNavigate } from "react-router-dom";
import { createApiClient } from "../lib/api.js";
import { saveAdminSession } from "../lib/auth-storage.js";
import { BrandMark } from "../components/BrandMark.js";
import { StatusTag } from "../components/StatusTag.js";
import {
@@ -58,13 +57,7 @@ export function Dashboard({
});
const switchBrand = async (brandId: string) => {
try {
const result = await createApiClient().switchAdminBrand(brandId);
saveAdminSession({
token: result.token,
role: result.role,
platformTemplateRole,
mustChangePassword: false,
});
await createApiClient().switchAdminBrand(brandId);
window.location.reload();
} catch (error) {
message.error(error instanceof Error ? error.message : "品牌切换失败");
+39 -19
View File
@@ -1,52 +1,72 @@
import React, { useState } from "react";
import type { AdminSession } from "@personal-brand/api-client";
import { ChangePassword, Login } from "../features/auth/AuthPages.js";
import { Dashboard } from "./Dashboard.js";
import { AdminRouter } from "./AdminRouter.js";
import { adminMessage as message } from "../components/AdminMessage.js";
import { createApiClient } from "../lib/api.js";
import { clearAdminSession, readAdminSession } from "../lib/auth-storage.js";
import { LoadingStack } from "../components/LoadingStack.js";
type SessionState = Omit<AdminSession, "authenticated">;
export function Root() {
const initialSession = readAdminSession();
const [loggedIn, setLoggedIn] = useState(initialSession.loggedIn);
const [role, setRole] = useState(initialSession.role);
const [platformTemplateRole, setPlatformTemplateRole] = useState(
initialSession.platformTemplateRole,
);
const [mustChangePassword, setMustChangePassword] = useState(initialSession.mustChangePassword);
const [session, setSession] = useState<SessionState | null>(null);
const [loading, setLoading] = useState(true);
React.useEffect(() => {
let active = true;
createApiClient()
.getAdminSession()
.then((current) => {
if (active) setSession(current);
})
.catch(() => {
if (active) setSession(null);
})
.finally(() => {
if (active) setLoading(false);
});
return () => {
active = false;
};
}, []);
React.useEffect(() => {
const expire = () => {
message.warning("登录状态已失效,请重新登录");
setLoggedIn(false);
setSession(null);
};
window.addEventListener("admin-auth-expired", expire);
return () => window.removeEventListener("admin-auth-expired", expire);
}, []);
const logout = async () => {
try {
await createApiClient().logoutAdmin();
} catch {
message.warning("已退出本地会话;服务端撤销请求未完成");
} finally {
clearAdminSession();
setLoggedIn(false);
setSession(null);
}
};
if (!loggedIn)
if (loading) return <LoadingStack />;
if (!session)
return (
<Login
onLogin={(session) => {
setRole(session.role);
setPlatformTemplateRole(session.platformTemplateRole);
setMustChangePassword(session.mustChangePassword);
setLoggedIn(true);
onLogin={(current) => {
setSession(current);
}}
/>
);
if (mustChangePassword) return <ChangePassword onComplete={() => setMustChangePassword(false)} />;
if (session.mustChangePassword) return <ChangePassword onComplete={() => setSession(null)} />;
return (
<AdminRouter>
<Dashboard onLogout={logout} role={role} platformTemplateRole={platformTemplateRole} />
<Dashboard
onLogout={logout}
role={session.role}
platformTemplateRole={session.platformTemplateRole}
/>
</AdminRouter>
);
}
+1 -5
View File
@@ -2,7 +2,6 @@ import { CloudUploadOutlined, DeleteOutlined, PictureOutlined } from "@ant-desig
import { Alert, Button, Image, Popconfirm, Spin, Upload, message } from "antd";
import { useEffect, useMemo, useState } from "react";
import { apiBaseUrl, authenticatedFetch, createApiClient } from "../lib/api.js";
import { readAdminToken } from "../lib/auth-storage.js";
interface ImageUrlFieldProps {
id?: string;
@@ -57,10 +56,7 @@ export function ImageUrlField({ id, value, onChange, placeholder, scope }: Image
: presign.uploadUrl;
const response = await authenticatedFetch(uploadUrl, {
method: "PUT",
headers: {
"content-type": file.type,
...(isLocalUpload ? { authorization: `Bearer ${readAdminToken() ?? ""}` } : {}),
},
headers: { "content-type": file.type },
body: file,
});
if (!response.ok) throw new Error(`upload failed: ${response.status}`);
+2 -12
View File
@@ -1,28 +1,19 @@
import { useState } from "react";
import { createApiClient } from "../../lib/api.js";
import { markAdminPasswordChanged, saveAdminSession } from "../../lib/auth-storage.js";
import { BrandMark } from "../../components/BrandMark.js";
import { adminMessage as message } from "../../components/AdminMessage.js";
import { AdminButton } from "../../components/AdminButton.js";
import { AdminCard } from "../../components/AdminCard.js";
import { AdminForm, AdminInput } from "../../components/AdminForm.js";
import type { AdminLoginSession } from "@personal-brand/api-client";
export function Login({
onLogin,
}: {
onLogin: (session: {
role: string;
mustChangePassword: boolean;
platformTemplateRole: "none" | "template_admin";
}) => void;
}) {
export function Login({ onLogin }: { onLogin: (session: AdminLoginSession) => void }) {
const [form] = AdminForm.useForm();
const [loading, setLoading] = useState(false);
async function submit(values: { username: string; password: string }) {
setLoading(true);
try {
const result = await createApiClient().loginAdmin(values.username, values.password);
saveAdminSession(result);
onLogin(result);
} catch (error) {
message.error(error instanceof Error ? error.message : "登录失败");
@@ -79,7 +70,6 @@ export function ChangePassword({ onComplete }: { onComplete: () => void }) {
setLoading(true);
try {
await createApiClient().changeAdminPassword(values.currentPassword, values.newPassword);
markAdminPasswordChanged();
message.success("密码已更新");
onComplete();
} catch (error) {
+4 -11
View File
@@ -1,23 +1,16 @@
import { ApiClient } from "@personal-brand/api-client";
import { clearAdminSession, readAdminToken } from "./auth-storage.js";
export const apiBaseUrl = import.meta.env.VITE_API_BASE_URL ?? "/api";
export async function authenticatedFetch(
input: RequestInfo | URL,
init?: RequestInit,
): Promise<Response> {
const response = await fetch(input, init);
if (response.status === 401) {
clearAdminSession();
window.dispatchEvent(new Event("admin-auth-expired"));
}
if (response.status === 401) window.dispatchEvent(new Event("admin-auth-expired"));
return response;
}
export function createApiClient(): ApiClient {
const token = readAdminToken();
return new ApiClient({
baseUrl: apiBaseUrl,
...(token ? { token } : {}),
fetcher: authenticatedFetch,
});
return new ApiClient({ baseUrl: apiBaseUrl, fetcher: authenticatedFetch });
}
-48
View File
@@ -1,48 +0,0 @@
export type StoredAdminSession = {
token: string;
role: string;
platformTemplateRole: "none" | "template_admin";
mustChangePassword: boolean;
};
const tokenKey = "adminToken";
const roleKey = "adminRole";
const platformRoleKey = "adminPlatformTemplateRole";
const mustChangePasswordKey = "adminMustChangePassword";
export function saveAdminSession(session: StoredAdminSession): void {
localStorage.setItem(tokenKey, session.token);
localStorage.setItem(roleKey, session.role);
localStorage.setItem(platformRoleKey, session.platformTemplateRole);
localStorage.setItem(mustChangePasswordKey, String(session.mustChangePassword));
}
export function readAdminToken(): string | null {
return localStorage.getItem(tokenKey);
}
export function readAdminSession(): {
loggedIn: boolean;
role: string;
platformTemplateRole: "none" | "template_admin";
mustChangePassword: boolean;
} {
return {
loggedIn: Boolean(localStorage.getItem(tokenKey)),
role: localStorage.getItem(roleKey) || "owner",
platformTemplateRole:
localStorage.getItem(platformRoleKey) === "template_admin" ? "template_admin" : "none",
mustChangePassword: localStorage.getItem(mustChangePasswordKey) === "true",
};
}
export function markAdminPasswordChanged(): void {
localStorage.setItem(mustChangePasswordKey, "false");
}
export function clearAdminSession(): void {
localStorage.removeItem(tokenKey);
localStorage.removeItem(roleKey);
localStorage.removeItem(platformRoleKey);
localStorage.removeItem(mustChangePasswordKey);
}
+1
View File
@@ -20,6 +20,7 @@
"dependencies": {
"@aws-sdk/client-s3": "^3.1149.0",
"@aws-sdk/s3-request-presigner": "^3.1149.0",
"@fastify/cookie": "^11.1.3",
"@fastify/multipart": "^10.1.3",
"@fastify/static": "^10.1.6",
"@nestjs/common": "^11.0.11",
+8 -1
View File
@@ -1,5 +1,6 @@
import { ForbiddenException, UnauthorizedException } from "@nestjs/common";
import type { FastifyRequest } from "fastify";
import { ADMIN_SESSION_COOKIE } from "./admin-session-cookie.js";
import { readIdentity } from "./auth.js";
export type AdminIdentity = {
@@ -9,8 +10,14 @@ export type AdminIdentity = {
tokenVersion: number;
};
export function readAdminToken(request: FastifyRequest): string | null {
const header = request.headers.authorization?.replace(/^Bearer\s+/i, "");
if (header) return header;
return request.cookies?.[ADMIN_SESSION_COOKIE] ?? null;
}
export function requireAdminIdentity(request: FastifyRequest): AdminIdentity {
const token = request.headers.authorization?.replace(/^Bearer\s+/i, "");
const token = readAdminToken(request);
if (!token) throw new UnauthorizedException("缺少管理员登录态");
let identity;
+32 -30
View File
@@ -1,16 +1,20 @@
import { ForbiddenException, Injectable, UnauthorizedException } from "@nestjs/common";
import type { FastifyRequest } from "fastify";
import { PrismaService } from "./prisma.service.js";
import { readAdminToken } from "./admin-access.identity.js";
import { readIdentity } from "./auth.js";
@Injectable()
export class AdminAccessService {
constructor(private readonly prisma: PrismaService) {}
async requireBrand(
request: FastifyRequest,
): Promise<{ subject: string; brandId: string; role: string }> {
const token = request.headers.authorization?.replace(/^Bearer\s+/i, "");
async requireToken(request: FastifyRequest): Promise<{
subject: string;
brandId: string;
mustChangePassword: boolean;
tokenVersion: number;
}> {
const token = readAdminToken(request);
if (!token) throw new UnauthorizedException("缺少管理员登录态");
let identity;
try {
@@ -21,17 +25,30 @@ export class AdminAccessService {
if (identity.role !== "admin") throw new ForbiddenException("无管理员权限");
const user = await this.prisma.adminUser.findUnique({
where: { id: identity.subject },
select: { mustChangePassword: true, isEnabled: true, tokenVersion: true },
select: { isEnabled: true, mustChangePassword: true, tokenVersion: true },
});
if (!user || identity.tokenVersion !== user.tokenVersion)
throw new UnauthorizedException("管理员登录态已失效,请重新登录");
if (!user.isEnabled || user.mustChangePassword)
if (!user.isEnabled) throw new ForbiddenException("管理员账号已停用");
return {
subject: identity.subject,
brandId: identity.brandId,
mustChangePassword: user.mustChangePassword,
tokenVersion: user.tokenVersion,
};
}
async requireBrand(
request: FastifyRequest,
): Promise<{ subject: string; brandId: string; role: string }> {
const access = await this.requireToken(request);
if (access.mustChangePassword)
throw new ForbiddenException("请先完成初始密码修改后再访问管理后台");
const membership = await this.prisma.brandMembership.findUnique({
where: { adminUserId_brandId: { adminUserId: identity.subject, brandId: identity.brandId } },
where: { adminUserId_brandId: { adminUserId: access.subject, brandId: access.brandId } },
});
if (!membership?.isEnabled) throw new ForbiddenException("管理员没有当前品牌权限");
return { subject: identity.subject, brandId: identity.brandId, role: membership.role };
return { subject: access.subject, brandId: access.brandId, role: membership.role };
}
async requireRole(request: FastifyRequest, allowedRoles: string[]): Promise<boolean> {
@@ -43,30 +60,15 @@ export class AdminAccessService {
}
async requireTemplateAdmin(request: FastifyRequest): Promise<{ subject: 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("无管理员权限");
const user = await this.prisma.adminUser.findUnique({
where: { id: identity.subject },
select: {
isEnabled: true,
mustChangePassword: true,
platformTemplateRole: true,
tokenVersion: true,
},
});
if (!user || identity.tokenVersion !== user.tokenVersion)
throw new UnauthorizedException("管理员登录态已失效,请重新登录");
if (!user.isEnabled || user.mustChangePassword)
const access = await this.requireToken(request);
if (access.mustChangePassword)
throw new ForbiddenException("请先完成初始密码修改后再访问管理后台");
const user = await this.prisma.adminUser.findUniqueOrThrow({
where: { id: access.subject },
select: { platformTemplateRole: true },
});
if (user.platformTemplateRole !== "template_admin")
throw new ForbiddenException("当前账号没有模板管理权限");
return { subject: identity.subject };
return { subject: access.subject };
}
}
+39
View File
@@ -0,0 +1,39 @@
import "reflect-metadata";
export const ADMIN_AUTH_METADATA = "admin-auth";
export type AdminAuthMetadata =
| { type: "public" }
| { type: "token" }
| { type: "brand" }
| { type: "roles"; roles: string[] }
| { type: "template-admin" };
function adminAuth(metadata: AdminAuthMetadata): ClassDecorator & MethodDecorator {
const decorator = ((
target: object,
propertyKey?: PropertyKey,
descriptor?: PropertyDescriptor,
) => {
// Nest 在 guard 中读取 handler function 的元数据;method decorator 必须写入 descriptor.value。
const metadataTarget =
propertyKey === undefined ? target : (descriptor?.value as object | undefined);
if (metadataTarget) {
Reflect.defineMetadata(ADMIN_AUTH_METADATA, metadata, metadataTarget);
}
}) as ClassDecorator & MethodDecorator;
return decorator;
}
export const AdminPublic = (): ClassDecorator & MethodDecorator => adminAuth({ type: "public" });
export const AdminTokenOnly = (): ClassDecorator & MethodDecorator => adminAuth({ type: "token" });
export const AdminBrand = (): ClassDecorator & MethodDecorator => adminAuth({ type: "brand" });
export const AdminRoles = (roles: string[]): ClassDecorator & MethodDecorator =>
adminAuth({ type: "roles", roles });
export const AdminTemplateAdmin = (): ClassDecorator & MethodDecorator =>
adminAuth({ type: "template-admin" });
+50 -11
View File
@@ -1,22 +1,30 @@
import { ForbiddenException, Injectable, UnauthorizedException } from "@nestjs/common";
import bcrypt from "bcryptjs";
import type { FastifyRequest } from "fastify";
import { AdminAccessService } from "./admin-access.service.js";
import { PrismaService } from "./prisma.service.js";
import { signIdentity } from "./auth.js";
export type AdminLoginSession = {
displayName: string;
role: string;
platformTemplateRole: "none" | "template_admin";
mustChangePassword: boolean;
};
export type AdminCurrentSession = AdminLoginSession & { authenticated: true };
@Injectable()
export class AdminAuthService {
constructor(private readonly prisma: PrismaService) {}
constructor(
private readonly prisma: PrismaService,
private readonly access: AdminAccessService,
) {}
async login(
username: string,
password: string,
): Promise<{
token: string;
displayName: string;
mustChangePassword: boolean;
role: string;
platformTemplateRole: string;
}> {
): Promise<{ session: AdminLoginSession; token: string }> {
const user = await this.prisma.adminUser.findUnique({ where: { username } });
if (!user || !user.isEnabled || !(await bcrypt.compare(password, user.passwordHash))) {
throw new UnauthorizedException("账号或密码错误");
@@ -31,16 +39,37 @@ export class AdminAuthService {
});
if (!membership) throw new ForbiddenException("管理员没有品牌权限,请先联系平台负责人分配");
return {
session: {
displayName: user.displayName,
mustChangePassword: user.mustChangePassword,
role: membership.role,
platformTemplateRole: user.platformTemplateRole,
},
token: signIdentity({
subject: user.id,
brandId: membership.brandId,
role: "admin",
tokenVersion: user.tokenVersion,
}),
};
}
async currentSession(request: FastifyRequest): Promise<AdminCurrentSession> {
const access = await this.access.requireBrand(request);
const user = await this.prisma.adminUser.findUniqueOrThrow({
where: { id: access.subject },
select: {
displayName: true,
mustChangePassword: true,
platformTemplateRole: true,
},
});
return {
authenticated: true,
displayName: user.displayName,
mustChangePassword: user.mustChangePassword,
role: membership.role,
platformTemplateRole: user.platformTemplateRole,
role: access.role,
};
}
@@ -55,20 +84,30 @@ export class AdminAuthService {
async changePassword(
userId: string,
brandId: string,
currentPassword: string,
newPassword: string,
): Promise<void> {
): Promise<{ token: string }> {
const user = await this.prisma.adminUser.findUnique({ where: { id: userId } });
if (!user?.isEnabled || !(await bcrypt.compare(currentPassword, user.passwordHash))) {
throw new UnauthorizedException("当前密码不正确");
}
await this.prisma.adminUser.update({
const updated = await this.prisma.adminUser.update({
where: { id: userId },
data: {
passwordHash: await bcrypt.hash(newPassword, 12),
mustChangePassword: false,
tokenVersion: { increment: 1 },
},
select: { tokenVersion: true },
});
return {
token: signIdentity({
subject: user.id,
brandId,
role: "admin",
tokenVersion: updated.tokenVersion,
}),
};
}
}
+28 -31
View File
@@ -1,43 +1,40 @@
import { Injectable } from "@nestjs/common";
import { Reflector } from "@nestjs/core";
import type { CanActivate, ExecutionContext } from "@nestjs/common";
import type { FastifyRequest } from "fastify";
import { ADMIN_AUTH_METADATA, type AdminAuthMetadata } from "./admin-auth.decorators.js";
import { AdminAccessService } from "./admin-access.service.js";
const PATH_METADATA = "path";
function metadataPath(target: object): string | undefined {
const value = Reflect.getMetadata(PATH_METADATA, target) as unknown;
return typeof value === "string" ? value : undefined;
}
@Injectable()
export class AdminMembershipGuard implements CanActivate {
constructor(private readonly access: AdminAccessService) {}
constructor(
private readonly access: AdminAccessService,
private readonly reflector: Reflector,
) {}
canActivate(context: ExecutionContext): Promise<boolean> {
async canActivate(context: ExecutionContext): Promise<boolean> {
const metadata = this.reflector.getAllAndOverride<AdminAuthMetadata | undefined>(
ADMIN_AUTH_METADATA,
[context.getHandler(), context.getClass()],
);
if (!metadata) return true;
const request = context.switchToHttp().getRequest<FastifyRequest>();
const handlerPath = metadataPath(context.getHandler());
const controllerPath = metadataPath(context.getClass());
const routePath = `${controllerPath ?? ""}/${handlerPath ?? ""}`.replace(/^\/+|\/+$/g, "");
if (routePath === "admin/session/login") return Promise.resolve(true);
if (routePath === "admin/session/change-password") return Promise.resolve(true);
if (!routePath.startsWith("admin/")) return Promise.resolve(true);
if (
routePath === "admin/templates" ||
routePath.startsWith("admin/templates/") ||
routePath === "admin/template-operations" ||
routePath.startsWith("admin/template-operations/")
) {
return this.access.requireTemplateAdmin(request).then(() => true);
switch (metadata.type) {
case "public":
return true;
case "token":
await this.access.requireToken(request);
return true;
case "roles":
await this.access.requireRole(request, metadata.roles);
return true;
case "template-admin":
await this.access.requireTemplateAdmin(request);
return true;
case "brand":
await this.access.requireBrand(request);
return true;
}
if (
/^admin\/workspace\/(install|capabilities(?:\/|$)|template(?:\/|$)|fields(?:\/|$))/.test(
routePath,
) ||
/^admin\/config\/visual-template(?:\/|$)/.test(routePath)
) {
return this.access.requireRole(request, ["owner", "admin", "platform-admin"]);
}
return this.access.requireBrand(request).then(() => true);
}
}
+23
View File
@@ -0,0 +1,23 @@
import type { FastifyReply } from "fastify";
export const ADMIN_SESSION_COOKIE = "admin_session";
const ADMIN_SESSION_MAX_AGE_SECONDS = 60 * 60 * 24 * 7;
export function setAdminSessionCookie(reply: FastifyReply, token: string): void {
reply.setCookie(ADMIN_SESSION_COOKIE, token, {
path: "/",
httpOnly: true,
sameSite: "strict",
secure: process.env.NODE_ENV === "production",
maxAge: ADMIN_SESSION_MAX_AGE_SECONDS,
});
}
export function clearAdminSessionCookie(reply: FastifyReply): void {
reply.clearCookie(ADMIN_SESSION_COOKIE, {
path: "/",
httpOnly: true,
sameSite: "strict",
secure: process.env.NODE_ENV === "production",
});
}
+3 -1
View File
@@ -2,6 +2,7 @@ import "reflect-metadata";
import { Module, ValidationPipe } from "@nestjs/common";
import { APP_GUARD } from "@nestjs/core";
import type { NestFastifyApplication } from "@nestjs/platform-fastify";
import cookiePlugin from "@fastify/cookie";
import { ApiExceptionFilter, RequestIdMiddleware } from "./http.js";
import { AdminMembershipGuard } from "./admin-membership.guard.js";
import { AdminModule } from "./modules/admin/admin.module.js";
@@ -28,13 +29,14 @@ import { WorkspaceModule } from "./modules/workspace/workspace.module.js";
})
export class AppModule {}
export function configureApp(app: NestFastifyApplication): void {
export async function configureApp(app: NestFastifyApplication): Promise<void> {
app.useGlobalPipes(
new ValidationPipe({ whitelist: true, forbidNonWhitelisted: true, transform: true }),
);
app.useGlobalFilters(new ApiExceptionFilter());
const apiPrefix = process.env.API_PREFIX?.replace(/^\/+|\/+$/g, "");
if (apiPrefix) app.setGlobalPrefix(apiPrefix);
await app.register(cookiePlugin);
app.use(new RequestIdMiddleware().use.bind(new RequestIdMiddleware()));
const corsOrigins = (process.env.CORS_ORIGINS ?? "")
.split(",")
+1 -1
View File
@@ -26,7 +26,7 @@ export async function createApp(): Promise<NestFastifyApplication> {
decorateReply: false,
});
}
configureApp(app);
await configureApp(app);
return app;
}
@@ -1,3 +1,4 @@
import { AdminBrand } from "../../admin-auth.decorators.js";
import {
Body,
Controller,
@@ -31,6 +32,7 @@ class AdminBookingQueryDto {
@IsOptional() @IsString() tagId?: string;
}
@AdminBrand()
@Controller("admin/bookings")
export class AdminBookingController {
constructor(private readonly bookings: BookingService) {}
@@ -1,3 +1,4 @@
import { AdminBrand } from "../../admin-auth.decorators.js";
import { Body, Controller, Delete, Get, Param, Patch, Post, Req } from "@nestjs/common";
import type { FastifyRequest } from "fastify";
import {
@@ -10,6 +11,7 @@ import { TemplateWorkspaceService } from "../../template-workspace.service.js";
import { requireAdminIdentity } from "../../admin-access.identity.js";
import { AdminBrandConfigService } from "./admin-brand-config.service.js";
@AdminBrand()
@Controller("admin/config")
export class AdminConfigController {
constructor(
@@ -1,8 +1,10 @@
import { AdminBrand } from "../../admin-auth.decorators.js";
import { Controller, Put, Query, Req } from "@nestjs/common";
import type { FastifyRequest } from "fastify";
import { AdminAccessService } from "../../admin-access.service.js";
import { AdminUploadService } from "./admin-upload.service.js";
@AdminBrand()
@Controller("admin/uploads")
export class AdminLocalUploadController {
constructor(
@@ -1,3 +1,4 @@
import { AdminBrand, AdminRoles } from "../../admin-auth.decorators.js";
import { Body, Controller, Get, Param, Patch, Post, Req } from "@nestjs/common";
import type { FastifyRequest } from "fastify";
import { AdminAccessService } from "../../admin-access.service.js";
@@ -13,6 +14,7 @@ import {
type AdminIdentity = { subject: string; brandId: string };
@AdminBrand()
@Controller("admin/miniapp-releases")
export class AdminMiniAppReleaseController {
constructor(
@@ -34,13 +36,13 @@ export class AdminMiniAppReleaseController {
return this.settingsService.get(identity.brandId);
}
@AdminRoles(["owner", "admin", "platform-admin"])
@Patch("settings")
async updateSettings(
@Req() request: FastifyRequest,
@Body() body: UpdateMiniAppSettingsDto & { privateKey?: string },
@Body() body: UpdateMiniAppSettingsDto,
): Promise<unknown> {
const identity = await this.identity(request);
await this.access.requireRole(request, ["owner", "admin", "platform-admin"]);
return this.settingsService.update(identity.brandId, body);
}
@@ -16,5 +16,6 @@ export class UpdateMiniAppSettingsDto {
build?: Record<string, unknown>;
@IsOptional()
@IsString()
privateKey?: string;
}
@@ -1,9 +1,11 @@
import { AdminBrand } from "../../admin-auth.decorators.js";
import { Controller, Get, Param, ParseIntPipe, Post, Body, Req } from "@nestjs/common";
import type { FastifyRequest } from "fastify";
import { AdminAccessService } from "../../admin-access.service.js";
import { BrandReleaseApiService } from "../../brand-release-api.service.js";
import { PublishBrandReleaseDto } from "../../release.dto.js";
@AdminBrand()
@Controller("admin/releases")
export class AdminReleaseController {
constructor(
@@ -1,3 +1,4 @@
import { AdminTemplateAdmin } from "../../admin-auth.decorators.js";
import { Controller, Get, Param, Post, Query, Req } from "@nestjs/common";
import type { FastifyRequest } from "fastify";
import { AdminAccessService } from "../../admin-access.service.js";
@@ -9,6 +10,7 @@ import { AdminTemplatePackageService } from "./admin-template-package.service.js
import { AdminTemplatePreviewService } from "./admin-template-preview.service.js";
@AdminTemplateAdmin()
@Controller("admin/templates")
export class AdminTemplatePackageController {
constructor(
@@ -1,9 +1,11 @@
import { AdminBrand } from "../../admin-auth.decorators.js";
import { Body, Controller, Get, Post, Req } from "@nestjs/common";
import type { FastifyRequest } from "fastify";
import { AdminAccessService } from "../../admin-access.service.js";
import { PresignUploadDto } from "./admin-upload.dto.js";
import { AdminUploadService } from "./admin-upload.service.js";
@AdminBrand()
@Controller("admin/uploads")
export class AdminUploadController {
constructor(
@@ -1,3 +1,4 @@
import { AdminTemplateAdmin } from "../../admin-auth.decorators.js";
import { Controller, Get, Query, Req } from "@nestjs/common";
import type { FastifyRequest } from "fastify";
import { Type } from "class-transformer";
@@ -14,6 +15,7 @@ class TemplateOperationMetricsQueryDto {
days = 30;
}
@AdminTemplateAdmin()
@Controller("admin/template-operations")
export class TemplateOperationMetricsController {
constructor(
@@ -1,11 +1,13 @@
import { Body, Controller, Post, Query, Req, UnauthorizedException } from "@nestjs/common";
import type { FastifyRequest } from "fastify";
import { Body, Controller, Get, Post, Query, Req, Res } from "@nestjs/common";
import type { FastifyReply, FastifyRequest } from "fastify";
import { WechatAuthService } from "../../wechat-auth.js";
import { AdminBrand, AdminPublic, AdminTokenOnly } from "../../admin-auth.decorators.js";
import { clearAdminSessionCookie, setAdminSessionCookie } from "../../admin-session-cookie.js";
import { AdminAuthService } from "../../admin-auth.service.js";
import { requireAdminIdentity } from "../../admin-access.identity.js";
import { AdminLoginDto, WechatLoginDto } from "../../admin-auth.dto.js";
import { CustomerSessionService } from "./customer-session.service.js";
import { ChangeAdminPasswordDto } from "../../admin.dto.js";
import { readIdentity } from "../../auth.js";
@Controller("customer/session")
export class CustomerSessionController {
@@ -28,37 +30,55 @@ export class CustomerSessionController {
export class AdminSessionController {
constructor(private readonly auth: AdminAuthService) {}
@AdminPublic()
@Post("login")
login(@Body() body: AdminLoginDto): Promise<{
token: string;
async login(
@Body() body: AdminLoginDto,
@Res({ passthrough: true }) reply: FastifyReply,
): Promise<{
displayName: string;
mustChangePassword: boolean;
role: string;
platformTemplateRole: string;
platformTemplateRole: "none" | "template_admin";
}> {
return this.auth.login(body.username, body.password);
const { session, token } = await this.auth.login(body.username, body.password);
setAdminSessionCookie(reply, token);
return session;
}
@AdminBrand()
@Get("current")
async current(@Req() request: FastifyRequest) {
return this.auth.currentSession(request);
}
@AdminTokenOnly()
@Post("logout")
async logout(@Req() request: FastifyRequest): Promise<{ loggedOut: true }> {
const token = request.headers.authorization?.replace(/^Bearer\s+/i, "");
if (!token) throw new UnauthorizedException("缺少管理员登录态");
const identity = readIdentity(token);
if (identity.role !== "admin") throw new UnauthorizedException("管理员登录态无效");
async logout(
@Req() request: FastifyRequest,
@Res({ passthrough: true }) reply: FastifyReply,
): Promise<{ loggedOut: true }> {
const identity = requireAdminIdentity(request);
await this.auth.logout(identity.subject);
clearAdminSessionCookie(reply);
return { loggedOut: true };
}
@AdminTokenOnly()
@Post("change-password")
async changePassword(
@Req() request: FastifyRequest,
@Body() body: ChangeAdminPasswordDto,
@Res({ passthrough: true }) reply: FastifyReply,
): Promise<{ changed: true }> {
const token = request.headers.authorization?.replace(/^Bearer\s+/i, "");
if (!token) throw new UnauthorizedException("缺少管理员登录态");
const identity = readIdentity(token);
if (identity.role !== "admin") throw new UnauthorizedException("管理员登录态无效");
await this.auth.changePassword(identity.subject, body.currentPassword, body.newPassword);
const identity = requireAdminIdentity(request);
const { token } = await this.auth.changePassword(
identity.subject,
identity.brandId,
body.currentPassword,
body.newPassword,
);
setAdminSessionCookie(reply, token);
return { changed: true };
}
}
@@ -1,41 +1,40 @@
import { Body, Controller, Get, Param, Patch, Post, Req } from "@nestjs/common";
import type { FastifyRequest } from "fastify";
import { AdminAccessService } from "../../admin-access.service.js";
import { AdminBrand, AdminRoles } from "../../admin-auth.decorators.js";
import { Body, Controller, Get, Param, Patch, Post, Req, Res } from "@nestjs/common";
import type { FastifyReply, FastifyRequest } from "fastify";
import { setAdminSessionCookie } from "../../admin-session-cookie.js";
import { requireAdminIdentity } from "../../admin-access.identity.js";
import { CreateBrandMemberDto, UpdateBrandMemberDto } from "../../admin.dto.js";
import { TenantService } from "./tenant.service.js";
@AdminBrand()
@Controller("admin/brands")
export class TenantController {
constructor(
private readonly access: AdminAccessService,
private readonly tenants: TenantService,
) {}
constructor(private readonly tenants: TenantService) {}
@AdminRoles(["owner", "admin", "platform-admin"])
@Get("members")
async listMembers(@Req() request: FastifyRequest): Promise<unknown> {
await this.access.requireRole(request, ["owner", "admin", "platform-admin"]);
const current = this.adminIdentity(request);
return this.tenants.listMembers(current.brandId);
}
@AdminRoles(["owner", "admin", "platform-admin"])
@Post("members")
async createMember(
@Req() request: FastifyRequest,
@Body() body: CreateBrandMemberDto,
): Promise<unknown> {
await this.access.requireRole(request, ["owner", "admin", "platform-admin"]);
const actor = this.adminIdentity(request);
return this.tenants.createMember(actor.brandId, body);
}
@AdminRoles(["owner", "admin", "platform-admin"])
@Patch("members/:id")
async updateMember(
@Req() request: FastifyRequest,
@Param("id") id: string,
@Body() body: UpdateBrandMemberDto,
): Promise<unknown> {
await this.access.requireRole(request, ["owner", "admin", "platform-admin"]);
const actor = this.adminIdentity(request);
return this.tenants.updateMember(actor.brandId, actor.subject, id, body);
}
@@ -50,9 +49,12 @@ export class TenantController {
async switchBrand(
@Req() request: FastifyRequest,
@Param("brandId") brandId: string,
): Promise<{ token: string; role: string; brand: unknown }> {
@Res({ passthrough: true }) reply: FastifyReply,
): Promise<{ role: string; brand: unknown }> {
const identity = this.adminIdentity(request);
return this.tenants.switchBrand(identity, brandId);
const result = await this.tenants.switchBrand(identity, brandId);
setAdminSessionCookie(reply, result.token);
return { role: result.role, brand: result.brand };
}
private adminIdentity(request: FastifyRequest) {
@@ -1,3 +1,4 @@
import { AdminBrand, AdminRoles } from "../../admin-auth.decorators.js";
import { Body, Controller, Get, Param, Patch, Post, Query, Req } from "@nestjs/common";
import type { FastifyRequest } from "fastify";
import {
@@ -9,6 +10,7 @@ import { requireAdminIdentity } from "../../admin-access.identity.js";
import { AdminSampleContentService } from "./admin-sample-content.service.js";
import { AdminWorkspaceCapabilitiesService } from "./admin-workspace-capabilities.service.js";
@AdminBrand()
@Controller("admin/workspace")
class AdminCapabilityController {
constructor(
@@ -16,6 +18,7 @@ class AdminCapabilityController {
private readonly sampleContentService: AdminSampleContentService,
) {}
@AdminRoles(["owner", "admin", "platform-admin"])
@Get("capabilities")
list(@Req() request: FastifyRequest): Promise<unknown> {
return this.capabilitiesService.list(requireAdminIdentity(request).brandId);
@@ -38,6 +41,7 @@ class AdminCapabilityController {
return this.sampleContentService.import(identity.brandId, identity.subject, body);
}
@AdminRoles(["owner", "admin", "platform-admin"])
@Patch("capabilities/:key")
update(
@Req() request: FastifyRequest,
@@ -1,3 +1,4 @@
import { AdminBrand, AdminRoles } from "../../admin-auth.decorators.js";
import { Body, Controller, Delete, Get, Param, Patch, Post, Req } from "@nestjs/common";
import type { FastifyRequest } from "fastify";
import {
@@ -10,10 +11,12 @@ import {
import { requireAdminIdentity } from "../../admin-access.identity.js";
import { AdminInquiryService } from "./admin-inquiry.service.js";
@AdminBrand()
@Controller("admin/workspace")
class AdminInquiryController {
constructor(private readonly inquiryService: AdminInquiryService) {}
@AdminRoles(["owner", "admin", "platform-admin"])
@Post("fields")
createField(
@Req() request: FastifyRequest,
@@ -22,6 +25,7 @@ class AdminInquiryController {
return this.inquiryService.createField(requireAdminIdentity(request).brandId, body);
}
@AdminRoles(["owner", "admin", "platform-admin"])
@Patch("fields/:id")
async updateField(
@Req() request: FastifyRequest,
@@ -31,6 +35,7 @@ class AdminInquiryController {
return this.inquiryService.updateField(requireAdminIdentity(request).brandId, id, body);
}
@AdminRoles(["owner", "admin", "platform-admin"])
@Delete("fields/:id")
async deleteField(@Req() request: FastifyRequest, @Param("id") id: string): Promise<unknown> {
return this.inquiryService.deleteField(requireAdminIdentity(request).brandId, id);
@@ -1,9 +1,11 @@
import { Body, Controller, Delete, Get, Param, Patch, Post, Req } from "@nestjs/common";
import type { FastifyRequest } from "fastify";
import { AdminBrand } from "../../admin-auth.decorators.js";
import { CreateOfferingDto, UpdateOfferingDto } from "../../admin.dto.js";
import { requireAdminIdentity } from "../../admin-access.identity.js";
import { AdminOfferingService } from "./admin-offering.service.js";
@AdminBrand()
@Controller("admin/workspace")
class AdminOfferingController {
constructor(private readonly offeringService: AdminOfferingService) {}
@@ -1,9 +1,11 @@
import { AdminBrand, AdminRoles } from "../../admin-auth.decorators.js";
import { Body, Controller, Get, Post, Req } from "@nestjs/common";
import type { FastifyRequest } from "fastify";
import { RollbackTemplateDto, UpgradeTemplateDto } from "../../admin.dto.js";
import { TemplateWorkspaceService } from "../../template-workspace.service.js";
import { requireAdminIdentity } from "../../admin-access.identity.js";
@AdminBrand()
@Controller("admin/workspace")
class AdminTemplateController {
constructor(private readonly templateWorkspace: TemplateWorkspaceService) {}
@@ -13,6 +15,7 @@ class AdminTemplateController {
return this.templateWorkspace.preview(requireAdminIdentity(request).brandId);
}
@AdminRoles(["owner", "admin", "platform-admin"])
@Post("template/upgrade")
async upgrade(
@Req() request: FastifyRequest,
@@ -23,6 +26,7 @@ class AdminTemplateController {
return this.templateWorkspace.upgrade(identity.brandId, body, identity.subject, requestId);
}
@AdminRoles(["owner", "admin", "platform-admin"])
@Post("template/rollback")
async rollback(
@Req() request: FastifyRequest,
@@ -1,3 +1,4 @@
import { AdminBrand, AdminRoles } from "../../admin-auth.decorators.js";
import { Controller, Get, Post, Body, Req } from "@nestjs/common";
import type { FastifyRequest } from "fastify";
import { InstallTemplateDto, SelectTemplateVersionDto } from "../../admin.dto.js";
@@ -5,6 +6,7 @@ import { TemplateWorkspaceService } from "../../template-workspace.service.js";
import { requireAdminIdentity } from "../../admin-access.identity.js";
import { AdminWorkspaceService } from "./admin-workspace.service.js";
@AdminBrand()
@Controller("admin/workspace")
class AdminWorkspacePreviewController {
constructor(
@@ -22,6 +24,7 @@ class AdminWorkspacePreviewController {
return this.workspaceService.getPreview(requireAdminIdentity(request).brandId);
}
@AdminRoles(["owner", "admin", "platform-admin"])
@Post("install")
async install(
@Req() request: FastifyRequest,
@@ -38,6 +41,7 @@ class AdminWorkspacePreviewController {
);
}
@AdminRoles(["owner", "admin", "platform-admin"])
@Post("template/select-version")
async selectVersion(
@Req() request: FastifyRequest,
+48 -42
View File
@@ -131,7 +131,7 @@ test("模板目录只允许平台模板管理员访问,并支持安全、幂
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
});
assert.equal(login.statusCode, 201);
const headers = { authorization: `Bearer ${JSON.parse(login.body).token}` };
const headers = { authorization: `Bearer ${sessionToken(login)}` };
const empty = await request("/admin/templates", { headers });
assert.equal(empty.statusCode, 200);
const baseline = JSON.parse(empty.body);
@@ -276,7 +276,7 @@ test("模板失败指标仅平台模板管理员可查,按窗口聚合且不
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
});
assert.equal(login.statusCode, 201);
const adminHeaders = { authorization: `Bearer ${JSON.parse(login.body).token}` };
const adminHeaders = { authorization: `Bearer ${sessionToken(login)}` };
const now = Date.now();
const recentRequestId = `metrics-${randomUUID()}`;
await prisma.templateOperationFailureEvent.createMany({
@@ -356,7 +356,7 @@ test("平台模板管理员可以按行业预览版本,且预览不写入品
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
});
assert.equal(login.statusCode, 201);
const headers = { authorization: `Bearer ${JSON.parse(login.body).token}` };
const headers = { authorization: `Bearer ${sessionToken(login)}` };
const invalidArchive = createTemplateArchive("atelier-solopreneur", (manifest) => {
manifest.previewFixture.personal.safety.submissions = "enabled";
});
@@ -700,7 +700,7 @@ test("miniapp release tasks are authorized, idempotent, and state checked", asyn
method: "POST",
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
});
const headers = { authorization: `Bearer ${JSON.parse(login.body).token}` };
const headers = { authorization: `Bearer ${sessionToken(login)}` };
const current = JSON.parse((await request("/admin/releases", { headers })).body).find(
(item) => item.status === "published",
);
@@ -846,7 +846,7 @@ test("miniapp release settings never expose or persist plaintext private keys",
method: "POST",
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
});
const headers = { authorization: `Bearer ${JSON.parse(login.body).token}` };
const headers = { authorization: `Bearer ${sessionToken(login)}` };
const { generateKeyPairSync } = await import("node:crypto");
const privateKey = generateKeyPairSync("rsa", {
modulusLength: 2048,
@@ -1390,7 +1390,7 @@ test("admin release lifecycle is authorized, brand-scoped, and versioned", async
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
});
assert.equal(login.statusCode, 201);
const adminToken = JSON.parse(login.body).token;
const adminToken = sessionToken(login);
const readiness = await request("/admin/releases/readiness", {
headers: { authorization: `Bearer ${adminToken}` },
});
@@ -1837,6 +1837,12 @@ function errorMessage(body) {
return parsed?.error?.message ?? parsed?.message ?? "";
}
function sessionToken(response) {
const cookie = response.cookies?.find((item) => item.name === "admin_session");
assert.ok(cookie, "admin session cookie missing");
return cookie.value;
}
async function request(url, options = {}) {
const { rawPayload, ...injectOptions } = options;
return app
@@ -1855,7 +1861,7 @@ async function publishReleaseForTests(note = "集成测试发布") {
method: "POST",
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
});
const token = JSON.parse(login.body).token;
const token = sessionToken(login);
return request("/admin/releases/publish", {
method: "POST",
headers: { authorization: `Bearer ${token}` },
@@ -1935,7 +1941,7 @@ test("visual template compatibility is enforced by catalog, preview, and version
method: "POST",
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
});
const token = JSON.parse(login.body).data?.token ?? JSON.parse(login.body).token;
const token = sessionToken(login);
const installation = await prisma.brandTemplateInstallation.findUniqueOrThrow({
where: { brandId },
});
@@ -1982,7 +1988,7 @@ test("industry template state has a single source of truth", async () => {
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
});
const headers = {
authorization: `Bearer ${JSON.parse(login.body).data?.token ?? JSON.parse(login.body).token}`,
authorization: `Bearer ${sessionToken(login)}`,
};
try {
@@ -2143,7 +2149,7 @@ test("admin can update declared capability status with authorization and audit",
method: "POST",
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
});
const token = JSON.parse(login.body).data?.token ?? JSON.parse(login.body).token;
const token = sessionToken(login);
const updated = await request("/admin/workspace/capabilities/inquiry", {
method: "PATCH",
headers: { authorization: `Bearer ${token}` },
@@ -2177,7 +2183,7 @@ test("editor membership can manage brand content but cannot change system settin
method: "POST",
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
});
const token = JSON.parse(login.body).data?.token ?? JSON.parse(login.body).token;
const token = sessionToken(login);
const identity = readIdentity(token);
const membership = await prisma.brandMembership.findUnique({
where: { adminUserId_brandId: { adminUserId: identity.subject, brandId } },
@@ -2212,7 +2218,7 @@ test("owner can manage brand members without removing the final owner", async ()
method: "POST",
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
});
const token = JSON.parse(login.body).data?.token ?? JSON.parse(login.body).token;
const token = sessionToken(login);
const identity = readIdentity(token);
const members = await request("/admin/brands/members", {
headers: { authorization: `Bearer ${token}` },
@@ -2257,7 +2263,7 @@ test("manually created member must change the initial password before normal use
method: "POST",
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
});
const ownerToken = JSON.parse(ownerLogin.body).token;
const ownerToken = sessionToken(ownerLogin);
const username = `first-login-${Date.now()}`;
const created = await request("/admin/brands/members", {
method: "POST",
@@ -2280,13 +2286,13 @@ test("manually created member must change the initial password before normal use
assert.equal(login.statusCode, 201);
assert.equal(JSON.parse(login.body).mustChangePassword, true);
const blocked = await request("/admin/brands/members", {
headers: { authorization: `Bearer ${JSON.parse(login.body).token}` },
headers: { authorization: `Bearer ${sessionToken(login)}` },
});
assert.equal(blocked.statusCode, 403);
assert.match(errorMessage(blocked.body), /初始密码/);
const changed = await request("/admin/session/change-password", {
method: "POST",
headers: { authorization: `Bearer ${JSON.parse(login.body).token}` },
headers: { authorization: `Bearer ${sessionToken(login)}` },
payload: { currentPassword: "initial-password-123", newPassword: "updated-password-123" },
});
assert.equal(changed.statusCode, 201);
@@ -2309,7 +2315,7 @@ test("admin can install optional quote capability without industry-specific bran
method: "POST",
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
});
const token = JSON.parse(login.body).token;
const token = sessionToken(login);
const response = await request("/admin/workspace/capabilities/quote-request", {
method: "PATCH",
headers: { authorization: `Bearer ${token}` },
@@ -2346,7 +2352,7 @@ test("admin capability list includes template defaults and brand overrides", asy
method: "POST",
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
});
const token = JSON.parse(login.body).data?.token ?? JSON.parse(login.body).token;
const token = sessionToken(login);
const defaults = await request("/admin/workspace/capabilities", {
headers: { authorization: `Bearer ${token}` },
});
@@ -2390,7 +2396,7 @@ test("installing another industry template is rejected without drifting brand id
method: "POST",
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
});
const token = JSON.parse(login.body).data?.token ?? JSON.parse(login.body).token;
const token = sessionToken(login);
const headers = { authorization: `Bearer ${token}` };
try {
// 品牌身份是 food;装 doors 属于「更换行业模板」,不在本版本范围内。
@@ -2442,7 +2448,7 @@ test("cross template requests are rejected without creating a drifted installati
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
});
const headers = {
authorization: `Bearer ${JSON.parse(login.body).data?.token ?? JSON.parse(login.body).token}`,
authorization: `Bearer ${sessionToken(login)}`,
};
try {
const rejected = await request("/admin/workspace/install", {
@@ -2507,7 +2513,7 @@ test("admin can preview and import sample content idempotently", async () => {
method: "POST",
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
});
const token = JSON.parse(login.body).data?.token ?? JSON.parse(login.body).token;
const token = sessionToken(login);
const headers = { authorization: `Bearer ${token}` };
const preview = await request(
`/admin/workspace/sample-content/preview?templatePackageVersionId=${packageVersionId}`,
@@ -2601,7 +2607,7 @@ test("template ledger install, upgrade preview, and rollback stay brand-scoped",
method: "POST",
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
});
const token = JSON.parse(login.body).data?.token ?? JSON.parse(login.body).token;
const token = sessionToken(login);
const before = await request("/admin/workspace");
assert.equal(before.statusCode, 401);
const customerAccess = await request("/admin/workspace", {
@@ -3053,7 +3059,7 @@ test("admin can customize workspace fields with brand isolation", async () => {
method: "POST",
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
});
const token = JSON.parse(login.body).data?.token ?? JSON.parse(login.body).token;
const token = sessionToken(login);
const workspace = await request("/admin/workspace", {
headers: { authorization: `Bearer ${token}` },
});
@@ -3098,7 +3104,7 @@ test("selected package version is reflected in public runtime workspace", async
method: "POST",
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
});
const token = JSON.parse(login.body).data?.token ?? JSON.parse(login.body).token;
const token = sessionToken(login);
const installation = await prisma.brandTemplateInstallation.findUniqueOrThrow({
where: { brandId },
});
@@ -3349,7 +3355,7 @@ test("admin can create and version an inquiry form", async () => {
method: "POST",
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
});
const token = JSON.parse(login.body).data?.token ?? JSON.parse(login.body).token;
const token = sessionToken(login);
const offering = await prisma.offering.findFirst({ where: { brandId, isEnabled: true } });
assert.ok(offering);
const created = await request("/admin/workspace/forms", {
@@ -3592,7 +3598,7 @@ test("admin workspace data stays inside the acting brand", async () => {
method: "POST",
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
});
const token = JSON.parse(login.body).data?.token ?? JSON.parse(login.body).token;
const token = sessionToken(login);
const actingBrandId = readIdentity(token).brandId;
const otherBrand = await prisma.brandProfile.findFirst({
where: { id: { not: actingBrandId } },
@@ -3604,7 +3610,7 @@ test("admin workspace data stays inside the acting brand", async () => {
headers: { authorization: `Bearer ${token}` },
});
assert.equal(switchResponse.statusCode, 201);
const switchedToken = JSON.parse(switchResponse.body).token;
const switchedToken = sessionToken(switchResponse);
assert.equal(readIdentity(switchedToken).brandId, otherBrand.id);
const workspace = await request("/admin/workspace", {
@@ -3631,7 +3637,7 @@ test("inquiry form offering link is validated against the brand", async () => {
method: "POST",
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
});
const token = JSON.parse(login.body).data?.token ?? JSON.parse(login.body).token;
const token = sessionToken(login);
const headers = { authorization: `Bearer ${token}` };
const offering = await prisma.offering.findFirst({ where: { brandId, isEnabled: true } });
assert.ok(offering);
@@ -3704,7 +3710,7 @@ test("release readiness explains a form whose offering was disabled", async () =
method: "POST",
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
});
const token = JSON.parse(login.body).data?.token ?? JSON.parse(login.body).token;
const token = sessionToken(login);
const headers = { authorization: `Bearer ${token}` };
const offering = await prisma.offering.findFirst({ where: { brandId, isEnabled: true } });
assert.ok(offering);
@@ -3741,7 +3747,7 @@ test("admin rejects invalid dynamic inquiry field definitions", async () => {
method: "POST",
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
});
const token = JSON.parse(login.body).data?.token ?? JSON.parse(login.body).token;
const token = sessionToken(login);
const invalid = await request("/admin/workspace/forms", {
method: "POST",
headers: { authorization: `Bearer ${token}` },
@@ -3758,7 +3764,7 @@ test("admin can manage offerings and public endpoint hides disabled offerings",
method: "POST",
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
});
const token = JSON.parse(login.body).data?.token ?? JSON.parse(login.body).token;
const token = sessionToken(login);
const invalidConfig = await request("/admin/workspace/offerings", {
method: "POST",
headers: { authorization: `Bearer ${token}` },
@@ -3836,7 +3842,7 @@ test("offering with an inquiry form cannot be deleted", async () => {
method: "POST",
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
});
const token = JSON.parse(login.body).data?.token ?? JSON.parse(login.body).token;
const token = sessionToken(login);
const offering = await prisma.offering.create({
data: { brandId, kind: "service", name: `保护测试-${Date.now()}`, description: "测试" },
});
@@ -3871,7 +3877,7 @@ test("seeded admin can log in and read protected booking resources", async () =>
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
});
assert.equal(login.statusCode, 201);
const token = JSON.parse(login.body).data?.token ?? JSON.parse(login.body).token;
const token = sessionToken(login);
assert.ok(token);
const count = await request("/admin/bookings/unread-count", {
@@ -3915,7 +3921,7 @@ test("admin logout revokes the current token", async () => {
payload: { username, password },
});
assert.equal(login.statusCode, 201, login.body);
const token = JSON.parse(login.body).token;
const token = sessionToken(login);
const headers = { authorization: `Bearer ${token}` };
const before = await request("/admin/bookings/unread-count", { headers });
assert.equal(before.statusCode, 200);
@@ -3984,7 +3990,7 @@ test("changing an admin password revokes existing admin tokens", async () => {
payload: { username, password: "initial-password-123" },
});
assert.equal(login.statusCode, 201, login.body);
const token = JSON.parse(login.body).token;
const token = sessionToken(login);
const headers = { authorization: `Bearer ${token}` };
const before = await request("/admin/bookings/unread-count", { headers });
assert.equal(before.statusCode, 200, before.body);
@@ -4008,7 +4014,7 @@ test("admin can list and switch only enabled brand memberships", async () => {
method: "POST",
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
});
const token = JSON.parse(login.body).data?.token ?? JSON.parse(login.body).token;
const token = sessionToken(login);
const brands = await request("/admin/brands", {
headers: { authorization: `Bearer ${token}` },
});
@@ -4030,7 +4036,7 @@ test("brand switching isolates admin configuration, offerings, and public worksp
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
});
assert.equal(login.statusCode, 201);
const defaultToken = JSON.parse(login.body).token;
const defaultToken = sessionToken(login);
const memberships = JSON.parse(
(
await request("/admin/brands", {
@@ -4046,7 +4052,7 @@ test("brand switching isolates admin configuration, offerings, and public worksp
headers: { authorization: `Bearer ${defaultToken}` },
});
assert.equal(switched.statusCode, 201);
const doorsToken = JSON.parse(switched.body).token;
const doorsToken = sessionToken(switched);
const [
defaultConfig,
@@ -4101,7 +4107,7 @@ test("disabled brand membership blocks existing admin token", async () => {
method: "POST",
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
});
const token = JSON.parse(login.body).data?.token ?? JSON.parse(login.body).token;
const token = sessionToken(login);
const admin = await prisma.adminUser.findUnique({ where: { username: "admin" } });
assert.ok(admin);
const membership = await prisma.brandMembership.findUnique({
@@ -4127,7 +4133,7 @@ test("admin can read and update brand and service configuration", async () => {
method: "POST",
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
});
const adminToken = JSON.parse(login.body).token;
const adminToken = sessionToken(login);
const removedAdminRoute = await request("/admin/config/services", {
headers: { authorization: `Bearer ${adminToken}` },
});
@@ -4242,7 +4248,7 @@ test("admin can update user-facing brand presentation without replacing other co
method: "POST",
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
});
const token = JSON.parse(login.body).data?.token ?? JSON.parse(login.body).token;
const token = sessionToken(login);
const brand = await prisma.brandProfile.findUnique({ where: { id: brandId } });
assert.ok(brand);
const originalConfig = brand.config;
@@ -4278,7 +4284,7 @@ test("admin can manage trust content", async () => {
method: "POST",
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
});
const token = JSON.parse(login.body).data?.token ?? JSON.parse(login.body).token;
const token = sessionToken(login);
assert.equal((await request("/admin/config/trust-content")).statusCode, 401);
assert.equal(
(
@@ -4530,7 +4536,7 @@ test("admin can advance booking status but cannot skip the state machine", async
method: "POST",
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
});
const adminToken = JSON.parse(login.body).token;
const adminToken = sessionToken(login);
const contacting = await request(`/admin/bookings/${booking.id}/status`, {
method: "POST",
headers: { authorization: `Bearer ${adminToken}` },
+2 -2
View File
@@ -25,8 +25,8 @@ API 地址通过 `API_BASE_URL` 设置,品牌通过 `BRAND_SLUG` 设置。H5
## 构建
```sh
pnpm --filter @personal-brand/taro build:h5
pnpm --filter @personal-brand/taro build:weapp
TEMPLATE_KEY=acheng-campus-food pnpm --filter @personal-brand/taro build:h5
TEMPLATE_KEY=acheng-campus-food pnpm --filter @personal-brand/taro build:weapp
TEMPLATE_KEY=linjing-editorial pnpm --filter @personal-brand/taro build:h5
TEMPLATE_KEY=linjing-editorial pnpm --filter @personal-brand/taro build:weapp
```
+1 -1
View File
@@ -81,7 +81,7 @@ function resolveTargets(envType, preview) {
if (process.env.MINIAPP_OUTPUT_ROOT)
return [path.resolve(taroRoot, process.env.MINIAPP_OUTPUT_ROOT)];
// 单模板构建默认使用餐饮试点;多模板预览必须显式 --preview。
const templateKey = process.env.TEMPLATE_KEY ?? "acheng-campus-food";
const templateKey = process.env.TEMPLATE_KEY;
if (!templateKey) throw new Error("TEMPLATE_KEY is required for non-preview masking");
return [path.join(taroRoot, "dist", templateKey, envType)];
}
+1
View File
@@ -1,6 +1,7 @@
{
"name": "@personal-brand/taro",
"private": true,
"type": "module",
"scripts": {
"dev:h5": "taro build --type h5 --watch",
"dev:preview": "PREVIEW_ALL_TEMPLATES=true taro build --type h5 --watch",
+38 -4
View File
@@ -235,6 +235,7 @@ runtimeWorkspace.trustItems.push(...additionalFoodTrust);
test("Admin 按通用预览目标筛选字段并同步品牌草稿", async ({ page }) => {
test.setTimeout(60000);
let rejectOfferingSave = false;
let sessionAuthenticated = false;
await page.setViewportSize({ width: 1920, height: 1000 });
await page.route("http://localhost:3001/public/workspace**", (route) =>
route.fulfill({ json: runtimeWorkspace }),
@@ -243,15 +244,31 @@ test("Admin 按通用预览目标筛选字段并同步品牌草稿", async ({ pa
const request = route.request();
const url = new URL(request.url());
url.pathname = url.pathname.replace(/^\/api/, "");
if (url.pathname === "/admin/session/login")
if (url.pathname === "/admin/session/current") {
if (!sessionAuthenticated) {
return route.fulfill({ status: 401, json: { error: { message: "未登录" } } });
}
return route.fulfill({
json: {
token: "fixture-token",
authenticated: true,
displayName: "测试管理员",
role: "owner",
mustChangePassword: false,
platformTemplateRole: "none",
},
});
}
if (url.pathname === "/admin/session/login") {
sessionAuthenticated = true;
return route.fulfill({
json: {
displayName: "测试管理员",
role: "owner",
mustChangePassword: false,
platformTemplateRole: "none",
},
});
}
if (url.pathname === "/admin/brands")
return route.fulfill({ json: [{ id: brand.id, role: "owner", brand }] });
if (url.pathname === "/admin/config/brand" && request.method() === "PATCH") {
@@ -636,6 +653,7 @@ test("Admin 按通用预览目标筛选字段并同步品牌草稿", async ({ pa
test("林境模板支持首页和主理人区域点选", async ({ page }) => {
test.setTimeout(60000);
let sessionAuthenticated = false;
await page.setViewportSize({ width: 1600, height: 900 });
const editorialBrand = {
...structuredClone(brand),
@@ -730,10 +748,26 @@ test("林境模板支持首页和主理人区域点选", async ({ page }) => {
await page.route("**/api/**", (route) => {
const url = new URL(route.request().url());
const path = url.pathname.replace(/^\/api/, "");
if (path === "/admin/session/login")
if (path === "/admin/session/current") {
if (!sessionAuthenticated) {
return route.fulfill({ status: 401, json: { error: { message: "未登录" } } });
}
return route.fulfill({
json: { token: "fixture-token", displayName: "测试管理员", role: "owner" },
json: {
authenticated: true,
displayName: "测试管理员",
role: "owner",
mustChangePassword: false,
platformTemplateRole: "none",
},
});
}
if (path === "/admin/session/login") {
sessionAuthenticated = true;
return route.fulfill({
json: { displayName: "测试管理员", role: "owner", mustChangePassword: false },
});
}
if (path === "/admin/brands")
return route.fulfill({
json: [{ id: editorialBrand.id, role: "owner", brand: editorialBrand }],
@@ -94,10 +94,11 @@ test("业务编辑弹窗预览列表与详情详情同一份内容", async ({ pa
await page.route("**/api/**", async (route) => {
const url = new URL(route.request().url());
const path = url.pathname.replace(/^\/api/, "");
if (path === "/admin/session/current")
return route.fulfill({ status: 401, json: { error: { message: "未登录" } } });
if (path === "/admin/session/login")
return route.fulfill({
json: {
token: "fixture-token",
displayName: "测试管理员",
role: "owner",
mustChangePassword: false,
@@ -57,9 +57,19 @@ test("模板管理可重试预览,并切换我的、详情和禁止提交的
),
);
await page.setViewportSize({ width: 1440, height: 1000 });
await page.addInitScript(() => {
localStorage.setItem("adminToken", "fixture-token");
localStorage.setItem("adminPlatformTemplateRole", "template_admin");
await page.route("**/api/**", (route) => {
const url = new URL(route.request().url());
if (url.pathname.endsWith("/admin/session/current"))
return route.fulfill({
json: {
authenticated: true,
displayName: "模板管理员",
role: "owner",
mustChangePassword: false,
platformTemplateRole: "template_admin",
},
});
return route.fulfill({ json: {} });
});
let attempts = 0;
const writes: string[] = [];
@@ -71,6 +81,16 @@ test("模板管理可重试预览,并切换我的、详情和禁止提交的
};
await page.route("**/api/**", async (route) => {
const url = new URL(route.request().url());
if (url.pathname.endsWith("/admin/session/current"))
return route.fulfill({
json: {
authenticated: true,
displayName: "模板管理员",
role: "owner",
mustChangePassword: false,
platformTemplateRole: "template_admin",
},
});
if (route.request().method() !== "GET") writes.push(url.pathname);
if (url.pathname.endsWith("/preview")) {
attempts++;
@@ -161,9 +161,19 @@ test("导入包预览矩阵展示身份、资源和完整媒体槽位", async ({
await test.step(`${mediaCase.packageKey}/${mediaCase.industry}`, async () => {
const { preview, version } = await buildPreviewFixture(mediaCase);
assert.ok(version);
await page.addInitScript(() => {
localStorage.setItem("adminToken", "fixture-token");
localStorage.setItem("adminPlatformTemplateRole", "template_admin");
await page.route("**/api/**", (route) => {
const url = new URL(route.request().url());
if (url.pathname.endsWith("/admin/session/current"))
return route.fulfill({
json: {
authenticated: true,
displayName: "模板管理员",
role: "owner",
mustChangePassword: false,
platformTemplateRole: "template_admin",
},
});
return route.fulfill({ json: {} });
});
const emptyPreview = structuredClone(preview);
emptyPreview.workspace.offerings = [];
@@ -175,6 +185,16 @@ test("导入包预览矩阵展示身份、资源和完整媒体槽位", async ({
const writes: string[] = [];
await page.route("**/api/**", async (route) => {
const url = new URL(route.request().url());
if (url.pathname.endsWith("/admin/session/current"))
return route.fulfill({
json: {
authenticated: true,
displayName: "模板管理员",
role: "owner",
mustChangePassword: false,
platformTemplateRole: "template_admin",
},
});
if (route.request().method() !== "GET") writes.push(url.pathname);
if (url.pathname.endsWith("/preview")) {
attempts += 1;
+33
View File
@@ -0,0 +1,33 @@
# 0032: Admin Session 使用 HttpOnly Cookie
## Context
Admin 前端此前把 access token 保存在 `localStorage`,并由 feature 代码注入 `Authorization` header。这导致 token 可被 XSS 读取、品牌切换 token 需要在前端流转,也让部分页面依赖本地登录态而非服务端会话。与此同时,Admin authorization 曾按 URL 字符串匹配,method-level 角色规则无法可靠覆盖 class-level 品牌 rule。
## Decision
- Admin access token 只通过 `admin_session` HttpOnly cookie 交付;浏览器端不再持久化或读取 Admin token。
- Admin API 继续接受 `Bearer` token,供集成测试、服务端调用和可审计工具使用。
- `AdminMembershipGuard` 只读取 decorator metadata:`AdminPublic`、`AdminBrand`、`AdminRoles`、`AdminTemplateAdmin`、`AdminTokenOnly`。不再匹配 route 字符串。
- method-level metadata 必须写入 Nest handler function,因此 method decorator 会覆盖 class-level metadata。
- 登录、品牌切换和修改密码都由 API 设置新 cookie;切换品牌和登录响应不再返回 Admin token。
- logout 只要求有效 Admin token,不额外要求当前品牌 membership,确保停用品牌成员仍可退出。
- Customer session 仍使用 token 响应,因为小程序宿主负责安全存储和请求注入。
## Alternatives
- 继续 localStorage:XSS 暴露面大,且本地状态容易与服务端 token version 漂移。
- 内存 token:刷新后丢失,需要重新登录,不能表达品牌切换后的当前会话。
- 继续按 route 字符串 guard:每新增 controller 都可能漏配,method-level 规则容易失效。
## Consequences
- Admin 前端跨站点调用必须允许 same-origin cookie;生产部署保持 Admin 与 API 同源或由网关代理。
- 测试必须把登录后的 token 从 cookie 提取,而不是从 response body 读取。
- Admin 登录/切换品牌/修改密码的 request/response contract 已同步更新到 API Client 和 OpenAPI。
- Guard 的 decorator metadata 目标是关键契约;错误写入 prototype property metadata 会让 class-level rule 覆盖 method rule,集成测试必须保留 editor 403 case。
- 新证据必须重新登记 `sourceTreeHash`,避免沿用旧代码的 template doctor 审计结果。
## Migration
一次性切换 Admin browser state 到 `/admin/session/current`;删除 `auth-storage`,不再添加兼容读取路径。已有未撤销 token 会随原 token version 过期策略继续失效。
+39 -10
View File
@@ -122,15 +122,30 @@ paths:
$ref: "#/components/schemas/AdminLogin"
responses:
"201":
description: Admin session token
description: Admin session created; the access token is set as an HttpOnly cookie
content:
application/json:
schema:
$ref: "#/components/schemas/AdminTokenResponse"
$ref: "#/components/schemas/AdminLoginSession"
/admin/session/current:
get:
operationId: getAdminSession
security:
- cookieAuth: []
- bearerAuth: []
responses:
"200":
description: Current admin session
content:
application/json:
schema:
$ref: "#/components/schemas/AdminSession"
/admin/session/logout:
post:
operationId: logoutAdmin
security: [bearerAuth: []]
security:
- cookieAuth: []
- bearerAuth: []
responses:
"201":
description: Admin session revoked
@@ -256,6 +271,10 @@ components:
bearerAuth:
type: http
scheme: bearer
cookieAuth:
type: apiKey
in: cookie
name: admin_session
parameters:
BookingId:
in: path
@@ -353,13 +372,23 @@ components:
required: [loggedOut]
properties:
loggedOut: { type: boolean, enum: [true] }
AdminTokenResponse:
allOf:
- $ref: "#/components/schemas/TokenResponse"
- type: object
required: [displayName]
properties:
displayName: { type: string }
AdminSession:
type: object
required: [authenticated, displayName, mustChangePassword, role, platformTemplateRole]
properties:
authenticated: { type: boolean, enum: [true] }
displayName: { type: string }
mustChangePassword: { type: boolean }
role: { type: string }
platformTemplateRole: { type: string, enum: [none, template_admin] }
AdminLoginSession:
type: object
required: [displayName, mustChangePassword, role, platformTemplateRole]
properties:
displayName: { type: string }
mustChangePassword: { type: boolean }
role: { type: string }
platformTemplateRole: { type: string, enum: [none, template_admin] }
UpdateBookingStatus:
type: object
required: [status]
+1 -1
View File
@@ -39,7 +39,7 @@
"test:deploy-verify": "node --test scripts/deploy/verify-release.test.mjs",
"test:deploy": "node --test scripts/deploy/*.test.mjs deploy/*.test.mjs",
"build:admin:preview": "PREVIEW_ALL_TEMPLATES=true API_BASE_URL=/api PREVIEW_PUBLIC_PATH=/template-preview/ pnpm --filter @personal-brand/taro build:preview && node scripts/package-template-preview.cjs && VITE_APP_BASE_PATH=/admin/ VITE_API_BASE_URL=/api pnpm --filter @personal-brand/admin build && node apps/taro/config/mask-taro.cjs admin",
"build:taro:food": "pnpm --filter @personal-brand/taro build:h5 && pnpm --filter @personal-brand/taro build:weapp",
"build:taro:food": "TEMPLATE_KEY=acheng-campus-food pnpm --filter @personal-brand/taro build:h5 && TEMPLATE_KEY=acheng-campus-food pnpm --filter @personal-brand/taro build:weapp",
"build:taro:linjing": "TEMPLATE_KEY=linjing-editorial pnpm --filter @personal-brand/taro build:h5 && TEMPLATE_KEY=linjing-editorial pnpm --filter @personal-brand/taro build:weapp",
"template:doctor": "node scripts/template-doctor.mjs",
"template:migration:audit": "pnpm --filter @personal-brand/api template:migration:audit",
+3
View File
@@ -45,6 +45,7 @@ export type {
TemplatePackagePreview,
TemplatePackageVersion,
} from "./resources/template.js";
export type { AdminLoginSession, AdminSession } from "./resources/session.js";
export type { TrustContent, TrustContentInput } from "./types/trust.js";
export type { PublicWorkspace } from "./types/workspace.js";
export { projectBrandAliases, projectTrustPresentation } from "@personal-brand/types";
@@ -156,6 +157,8 @@ export class ApiClient
) => this.resources.public.getCustomerInquirySubmission(...arguments_);
createCustomerSession = (...arguments_: Parameters<PublicMethods["createCustomerSession"]>) =>
this.resources.public.createCustomerSession(...arguments_);
getAdminSession = (...arguments_: Parameters<SessionMethods["getAdminSession"]>) =>
this.resources.session.getAdminSession(...arguments_);
loginAdmin = (...arguments_: Parameters<SessionMethods["loginAdmin"]>) =>
this.resources.session.loginAdmin(...arguments_);
changeAdminPassword = (...arguments_: Parameters<SessionMethods["changeAdminPassword"]>) =>
+1 -1
View File
@@ -15,7 +15,7 @@ export interface BrandMethods {
listAdminBrands(): Promise<AdminBrandMembership[]>;
switchAdminBrand(
brandId: string,
): Promise<{ token: string; role: string; brand: AdminBrandMembership["brand"] }>;
): Promise<{ role: string; brand: AdminBrandMembership["brand"] }>;
listAdminMembers(): Promise<AdminBrandMember[]>;
createAdminMember(body: {
username: string;
+13 -10
View File
@@ -1,16 +1,18 @@
import type { RequestFn } from "../client/request.js";
export type AdminSession = {
authenticated: true;
displayName: string;
mustChangePassword: boolean;
role: string;
platformTemplateRole: "none" | "template_admin";
};
export type AdminLoginSession = Omit<AdminSession, "authenticated">;
export interface SessionMethods {
loginAdmin(
username: string,
password: string,
): Promise<{
token: string;
displayName: string;
mustChangePassword: boolean;
role: string;
platformTemplateRole: "none" | "template_admin";
}>;
getAdminSession(): Promise<AdminSession>;
loginAdmin(username: string, password: string): Promise<AdminLoginSession>;
changeAdminPassword(currentPassword: string, newPassword: string): Promise<{ changed: true }>;
logoutAdmin(): Promise<{ loggedOut: true }>;
logoutCustomer(): Promise<{ loggedOut: true }>;
@@ -18,6 +20,7 @@ export interface SessionMethods {
export function sessionMethods({ request }: { request: RequestFn }): SessionMethods {
return {
getAdminSession: () => request("/admin/session/current"),
loginAdmin: (username, password) =>
request("/admin/session/login", { method: "POST", body: { username, password } }),
changeAdminPassword: (currentPassword, newPassword) =>
+23 -5
View File
@@ -43,7 +43,7 @@ overrides:
patchedDependencies:
'@jimp/core@0.16.13':
hash: e3gfmimxpqa7zt2vmxpy4rkhaq
hash: tmgzi2utshrw325qczfuqqr2oq
path: patches/@jimp__core@0.16.13.patch
miniprogram-ci@2.1.31:
hash: y4seosrw3qmysf77ad2tjzhu5e
@@ -120,6 +120,9 @@ importers:
'@aws-sdk/s3-request-presigner':
specifier: ^3.1149.0
version: 3.1149.0
'@fastify/cookie':
specifier: ^11.1.3
version: 11.1.3
'@fastify/multipart':
specifier: ^10.1.3
version: 10.1.3
@@ -2091,6 +2094,9 @@ packages:
'@fastify/busboy@3.2.3':
resolution: {integrity: sha512-fmo/IKgkenPzz3qTKG+sIUXdF/Kv83AkvvOXJHPTHJeKJbat8SsL1ihUaFaDotqoEl4UZ1Lf8Eb/3vK6eaWX2A==}
'@fastify/cookie@11.1.3':
resolution: {integrity: sha512-RBhlMNsmSG6C5KGiTkhSXBF75xIrUMSytDDBcpnVewhJ8XVYnJTu+SV6FYKXClIRsBuRjOfKbBSULvnPD3X/mg==}
'@fastify/cors@11.3.0':
resolution: {integrity: sha512-ggQGua+xHv1MvePbPr0v//xLYEsCXbWspquXCJS9Ot5YoRXq8J8ZWzHnxDBVnbtXosvistXo6LtNzOJswf64Fw==}
@@ -4739,6 +4745,10 @@ packages:
resolution: {integrity: sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==}
engines: {node: '>=18'}
cookie@2.0.1:
resolution: {integrity: sha512-yuToqVvRrj6pfDXREyQAAv8SkAEk/8GS3jQRTiUMm66TVtBYmqQeoEjL2Lmq8Rpo6271vH76InTChTitEAm65w==}
engines: {node: '>=22'}
copy-anything@2.0.6:
resolution: {integrity: sha512-1j20GZTsvKNkc4BY3NpMOM8tt///wY3FpIzozTOFO2ffuZcV61nojHXVKIy3WM+7ADCy5FVhdZYHYDdgTU0yJw==}
@@ -5525,6 +5535,7 @@ packages:
glob@10.2.6:
resolution: {integrity: sha512-U/rnDpXJGF414QQQZv5uVsabTVxMSwzS5CH0p3DRCIV6ownl4f7PzGnkGmvlum2wB+9RlJWJZ6ACU1INnBqiPA==}
engines: {node: '>=16 || 14 >=14.17'}
deprecated: Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me
hasBin: true
glob@13.0.6:
@@ -5533,11 +5544,11 @@ packages:
glob@7.1.2:
resolution: {integrity: sha512-MJTUg1kjuLeQCJ+ccE4Vpa6kKVXkPYJ2mOCQyUuKLcLQsdrMCpBPUi8qVE6+YuaJkozeA9NusTAw3hLr8Xe5EQ==}
deprecated: Glob versions prior to v9 are no longer supported
deprecated: Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me
glob@7.2.3:
resolution: {integrity: sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==}
deprecated: Glob versions prior to v9 are no longer supported
deprecated: Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me
global-modules@2.0.0:
resolution: {integrity: sha512-NGbfmJBp9x8IxyJSd1P+otYK8vonoJactOogrVfFRIAEY1ukil8RSKDz2Yo7wh1oihl51l/r6W4epkeKJHqL8A==}
@@ -10396,6 +10407,11 @@ snapshots:
'@fastify/busboy@3.2.3': {}
'@fastify/cookie@11.1.3':
dependencies:
cookie: 2.0.1
fastify-plugin: 6.0.0
'@fastify/cors@11.3.0':
dependencies:
fastify-plugin: 6.0.0
@@ -10514,7 +10530,7 @@ snapshots:
'@jimp/utils': 0.16.13
bmp-js: 0.1.0
'@jimp/core@0.16.13(patch_hash=e3gfmimxpqa7zt2vmxpy4rkhaq)':
'@jimp/core@0.16.13(patch_hash=tmgzi2utshrw325qczfuqqr2oq)':
dependencies:
'@babel/runtime': 7.26.10
'@jimp/utils': 0.16.13
@@ -10534,7 +10550,7 @@ snapshots:
'@jimp/custom@0.16.13':
dependencies:
'@babel/runtime': 7.26.10
'@jimp/core': 0.16.13(patch_hash=e3gfmimxpqa7zt2vmxpy4rkhaq)
'@jimp/core': 0.16.13(patch_hash=tmgzi2utshrw325qczfuqqr2oq)
transitivePeerDependencies:
- debug
- supports-color
@@ -13574,6 +13590,8 @@ snapshots:
cookie@1.1.1: {}
cookie@2.0.1: {}
copy-anything@2.0.6:
dependencies:
is-what: 3.14.1