Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
172 changes: 170 additions & 2 deletions .github/workflows/deploy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -56,8 +56,6 @@ jobs:
- name: Build web
run: pnpm build:web

# 迁移不在这里跑:部署完成后由 setup 页 / 管理面「检查并升级数据库」触发同一套 runner。
#
# 版本号(§6.3):与前端页脚同源,由 scripts/build-info.mjs 在 CI 内从 git describe 现算
# (tag 形态 v<semver>-<提交数>-<短哈希>,无 tag 兜底 v1.0.0-<提交数>-<短哈希>)。
# APP_VERSION 非密钥,因此走 --var 注入、与 wrangler.toml 的 [vars] TABLE_PREFIX 并存;
Expand All @@ -75,3 +73,173 @@ jobs:
fi
pnpm exec wrangler deploy --secrets-file "$RUNNER_TEMP/secrets.json" \
--var "APP_VERSION:${APP_VERSION}"

# 数据库自动升级:Worker 部署成功后,由 CI 自动调用 /api/setup 执行增量迁移并校验账本。
- name: Run database migrations
env:
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
SETUP_SECRET: ${{ secrets.SETUP_SECRET }}
run: |
if [ -z "$CLOUDFLARE_API_TOKEN" ] || [ -z "$CLOUDFLARE_ACCOUNT_ID" ] || [ -z "$SETUP_SECRET" ]; then
echo "Missing required environment variables for database migration" >&2
exit 1
fi

WORKER_NAME=$(node -e '
import fs from "node:fs";
const toml = fs.readFileSync("worker/wrangler.toml", "utf8");
const m = toml.match(/^name\s*=\s*"([^"]+)"/m);
if (!m) { console.error("Missing name in worker/wrangler.toml"); process.exit(1); }
process.stdout.write(m[1]);
')
if [ -z "$WORKER_NAME" ]; then
echo "Failed to resolve worker name from worker/wrangler.toml" >&2
exit 1
fi

SUBDOMAIN_RES=$(curl -sS -X GET "https://api.cloudflare.com/client/v4/accounts/${CLOUDFLARE_ACCOUNT_ID}/workers/subdomain" \
-H "Authorization: Bearer ${CLOUDFLARE_API_TOKEN}" \
-H "Content-Type: application/json")
SUBDOMAIN=$(echo "$SUBDOMAIN_RES" | jq -r '.result.subdomain // empty')
if [ -z "$SUBDOMAIN" ]; then
echo "Failed to retrieve workers.dev subdomain: $(echo "$SUBDOMAIN_RES" | jq -c '.errors // .')" >&2
exit 1
fi

ROUTE_RES=$(curl -sS -X GET "https://api.cloudflare.com/client/v4/accounts/${CLOUDFLARE_ACCOUNT_ID}/workers/scripts/${WORKER_NAME}/subdomain" \
-H "Authorization: Bearer ${CLOUDFLARE_API_TOKEN}" \
-H "Content-Type: application/json")
ENABLED=$(echo "$ROUTE_RES" | jq -r '.result.enabled // false')
if [ "$ENABLED" != "true" ]; then
echo "workers.dev route is disabled for ${WORKER_NAME}, enabling..."
ENABLE_RES=$(curl -sS -X POST "https://api.cloudflare.com/client/v4/accounts/${CLOUDFLARE_ACCOUNT_ID}/workers/scripts/${WORKER_NAME}/subdomain" \
-H "Authorization: Bearer ${CLOUDFLARE_API_TOKEN}" \
-H "Content-Type: application/json" \
-d '{"enabled": true}')
ENABLE_SUCCESS=$(echo "$ENABLE_RES" | jq -r '.success // false')
if [ "$ENABLE_SUCCESS" != "true" ]; then
echo "Failed to enable workers.dev route for ${WORKER_NAME}: $(echo "$ENABLE_RES" | jq -c '.errors // .')" >&2
exit 1
fi
fi

APP_VERSION=$(node scripts/build-info.mjs --print)
if [ "${APP_VERSION##*-}" = "unknown" ]; then
echo "APP_VERSION 无法从 git describe 解析:${APP_VERSION}" >&2
exit 1
fi

DELAYS=(3 6 12 20)

verify_version() {
local PHASE="$1"
local VER_FILE
VER_FILE=$(mktemp)
local V_HTTP_STATUS=""
local V_VERSION=""
local V_OK=false

for V_ATTEMPT in 1 2 3 4 5; do
V_HTTP_STATUS=$(curl -sS -o "$VER_FILE" -w "%{http_code}" \
"https://${WORKER_NAME}.${SUBDOMAIN}.workers.dev/api/public?t=$(date +%s)" \
-H "Content-Type: application/json" 2>/dev/null) || V_HTTP_STATUS="000"

if [ "$V_HTTP_STATUS" = "200" ]; then
V_VERSION=$(jq -r '.version // empty' "$VER_FILE" 2>/dev/null || true)
echo "Version check (${PHASE}) attempt ${V_ATTEMPT}/5: served=${V_VERSION:-<none>}, expected=${APP_VERSION}"
if [ -n "$V_VERSION" ] && [ "$V_VERSION" = "$APP_VERSION" ]; then
V_OK=true
break
fi
else
echo "Version check (${PHASE}) attempt ${V_ATTEMPT}/5: HTTP ${V_HTTP_STATUS}" >&2
fi

if [ "$V_ATTEMPT" -lt 5 ]; then
sleep "${DELAYS[$((V_ATTEMPT - 1))]}"
fi
done

rm -f "$VER_FILE"
if [ "$V_OK" != "true" ]; then
echo "Version self-verification (${PHASE}) failed: /api/public never served ${APP_VERSION} (last served=${V_VERSION:-<none>}, HTTP ${V_HTTP_STATUS})" >&2
exit 1
fi
echo "Version self-verification (${PHASE}) passed: /api/public serving ${APP_VERSION}"
}

verify_version "pre-setup"

EXPECTED_MIGRATIONS=$(node -e '
import { registerHooks } from "node:module";
registerHooks({
resolve(specifier, context, nextResolve) {
try {
return nextResolve(specifier, context);
} catch (err) {
if (err.code === "ERR_MODULE_NOT_FOUND" && !specifier.endsWith(".ts")) {
return nextResolve(specifier + ".ts", context);
}
throw err;
}
}
});
const { getMigrations } = await import("./worker/src/lib/migrations.ts");
process.stdout.write(JSON.stringify(getMigrations("").map(m => m.name)));
')

RESP_FILE=$(mktemp)
HTTP_STATUS=$(curl -sS -o "$RESP_FILE" -w "%{http_code}" -X POST \
"https://${WORKER_NAME}.${SUBDOMAIN}.workers.dev/api/setup" \
-H "X-Setup-Secret: ${SETUP_SECRET}" \
-H "Content-Type: application/json" \
-d '' 2>/dev/null) || HTTP_STATUS="000"

if [ "$HTTP_STATUS" = "403" ]; then
echo "HTTP 403: Invalid setup secret" >&2
exit 1
fi
if [ "$HTTP_STATUS" != "200" ]; then
echo "HTTP ${HTTP_STATUS}: /api/setup failed: $(cat "$RESP_FILE" 2>/dev/null)" >&2
exit 1
fi

RESP_FILE="$RESP_FILE" EXPECTED_MIGRATIONS="$EXPECTED_MIGRATIONS" node -e '
import fs from "node:fs";
const expected = JSON.parse(process.env.EXPECTED_MIGRATIONS || "[]");
const resp = JSON.parse(fs.readFileSync(process.env.RESP_FILE, "utf8"));
if (resp.success !== true) {
console.error("Migration validation failed: response success is not true");
process.exit(1);
}
const migrations = resp.migrations || [];
const seen = new Set();
for (const m of migrations) {
if (m.status !== "applied" && m.status !== "skipped") {
console.error(`Migration validation failed: migration "${m.name}" has invalid status "${m.status}"`);
process.exit(1);
}
if (seen.has(m.name)) {
console.error(`Migration validation failed: duplicate migration "${m.name}" in response`);
process.exit(1);
}
seen.add(m.name);
}
const expectedSet = new Set(expected);
const actualSet = new Set(migrations.map(m => m.name));
const missing = expected.filter(n => !actualSet.has(n));
const extra = migrations.map(m => m.name).filter(n => !expectedSet.has(n));
if (missing.length > 0 || extra.length > 0) {
console.error(`Migration validation failed: set mismatch (missing: [${missing.join(", ")}], extra: [${extra.join(", ")}])`);
process.exit(1);
}
'

echo "Active table prefix: $(jq -r '.tablePrefix' "$RESP_FILE")"
echo "Migration ledger summary:"
jq -r '.migrations[] | " - \(.name): \(.status)"' "$RESP_FILE"

verify_version "post-setup"

rm -f "$RESP_FILE"
14 changes: 7 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

## 界面预览

以下截图取自系统界面(中文、亮色为主,另附暗色与移动端)。公开首页包含项目名、一句话说明与登录入口;登录后侧栏为响应式工作台,个人资料 / 系统管理 / 设置 / 关于从顶栏头像菜单进入;初始化页按数据库状态切换初始化、升级与已关闭三形态。
以下截图取自系统界面(中文、亮色为主,另附暗色与移动端)。公开首页包含项目名、一句话说明与登录入口;登录后侧栏为响应式工作台,个人资料 / 系统管理 / 设置 / 关于从顶栏头像菜单进入;初始化页仅用于首次初始化,已初始化后自动关闭。

<p align="center">
<img src=".github/assets/imgs/home.webp" alt="公开首页:项目名与一句话说明,下方是「登录」「注册」两个按钮,页脚显示构建版本号" width="960" />
Expand Down Expand Up @@ -46,12 +46,12 @@
- **项目身份单点**:`worker/src/config/project.ts` 集中管理展示名、仓库 / Worker 名、一句话说明与仓库地址;默认表前缀置于 `worker/src/config/defaults.json`,运行时与部署脚本共读。`pnpm check:identity` 扫描全仓,白名单外出现项目名 / slug 零残留。
- **表前缀三态**:未配置 → 默认前缀;配置自定义值 → 规范化后使用;显式空值(CI 保留字 `none`)→ 无前缀。生效前缀必须在初始化前定死,初始化后变更由 setup 前缀冲突守卫拦下(409)。
- **单一全量基线迁移**:单一全量基线 `schema_v1`(历史增量链路坍缩,一次建出最终形态),幂等、只进不退;账本表为 `_<生效前缀>schema_migrations`。生产库历史记录由执行器只读识别为已最新(跳过、不写库);`worker/src/db/schema.sql` 与 `worker/src/lib/schema.ts` 逐字同步并由测试锁死。
- **部署与升级解耦**:`deploy.yml` 只发 Worker、不跑迁移;结构变更必须等新版本部署完成(页脚 / 系统管理可见版本号)后再由管理员点「检查并升级数据库」。全新安装一步到位。
- **setup 双入口**:`/setup` 页(凭部署密钥)与系统管理「检查并升级数据库」(凭管理员会话)调用同一个迁移 runner;`POST /api/setup` 纯升级端点只跑迁移、不建用户,密钥走 `X-Setup-Secret` 请求头,按 IP 限流。UI 永不提供删表 / 清库入口。
- **部署自动升级**:`deploy.yml` 在 Worker 部署成功后自动调用 `/api/setup` 执行增量迁移并校验账本,数据库结构随部署自动升级,无需手动操作升级;全新安装一步到位。
- **初始化与迁移端点**:`/setup` 页仅用于首次初始化(凭部署密钥执行初始迁移并引导创建首个用户 / 管理员,无手动升级表单);`POST /api/setup` 纯升级端点供部署流水线自动调用及初始化使用,密钥走 `X-Setup-Secret` 请求头,按 IP 限流。UI 永不提供删表 / 清库入口。
- **多因子鉴权**:邮箱密码 + TOTP(密码步与验证码步分开呈现)+ Passkey(WebAuthn)+ 邮箱验证码第二因子;会话 Cookie 为 `HttpOnly` + `Secure` + `SameSite=Strict`,数据库只存令牌哈希;密码连续失败锁定账号,并设 IP 级限流。
- **注册与审核**:开放注册、默认需要管理员批准;首个注册用户自动成为管理员并直接批准。支持「注册需验证邮箱」开关。
- **现代前端体验**:响应式侧栏(SVG 菱形 Logo、宽度自由拖拽、收起为图标栏、本地持久化);亮 / 暗 / 自动三档主题;PWA 添加至主屏幕;中英双语(i18next,错误码驱动翻译);版本与构建信息自动生成注入。
- **系统管理**:邮件通道配置(SMTP / Resend)与测试邮件发送、注册与审核策略开关、用户管理(全量用户列表、行内审核批准 / 拒绝、操作菜单重置密码 / 封禁 / 提权 / 删除)、setup 页开关、数据库维护(回显生效前缀与迁移记录)。
- **系统管理**:邮件通道配置(SMTP / Resend)与测试邮件发送、注册与审核策略开关、用户管理(全量用户列表、行内审核批准 / 拒绝、操作菜单重置密码 / 封禁 / 提权 / 删除)、数据库维护(setup 页开关与生效表前缀展示)。
- **定时任务与 waker**:`[triggers] crons` 提供原生定时入口;接入 waker 仅需一把 `WAKER_SIGNING_KEY` Secret(未配走 Cron、配了 waker 验签接管),不设多余模式开关。
- **CI/CD 流水线**:`ci.yml`(lint / format / typecheck / build / test / 身份校验 / 部署 dry-run)、`deploy.yml`(push main 自动部署)、`tag.yml`(手动打语义化版本 tag)、`release.yml`(tag 触发 GitHub Release)。

Expand Down Expand Up @@ -118,7 +118,7 @@ openssl rand -base64 32 # SIGNING_SECRET

1. 打开 `/setup`,输入 `.dev.vars` 里的 `SETUP_SECRET`,点「初始化」:跑迁移,回显生效表前缀与迁移记录。
2. 点「注册首个用户」(或打开 `/register`)建账号:首个用户自动成为管理员并直接批准。
3. 之后 setup 页默认关闭;管理员可在「系统管理 → 数据库维护」重开页面或再次执行迁移。`/setup` 的「检查并升级」与 `POST /api/setup` 都只跑迁移,不会建用户、改密码或删数据。
3. 之后 setup 页默认关闭;管理员可在「系统管理 → 数据库维护」重开页面。后续数据库升级由部署流水线自动调用 `POST /api/setup` 执行增量迁移;`POST /api/setup` 纯升级端点只跑迁移,不会建用户、改密码或删数据。

初始化也可以直接用 curl(把 `<SETUP_SECRET>` 换成 `.dev.vars` 里的值,密钥只放请求头):

Expand Down Expand Up @@ -195,5 +195,5 @@ pnpm check:deploy # 先 build:web,再 wrangler deploy --dry-run(不联网
### 部署流程

1. 触发器:push main 触发自动部署。
2. `deploy.yml` 依次:安装依赖 → `materialize-secrets`(校验、写 secrets.json、解析 wrangler.toml)→ 构建前端 → `wrangler deploy --secrets-file`。
3. 部署本身不跑迁移。部署完成后打开 `/setup` 用部署密钥跑一次迁移(或由管理员在「系统管理 → 数据库维护」点「检查并升级数据库」)。
2. `deploy.yml` 依次:安装依赖 → `materialize-secrets`(校验、写 secrets.json、解析 wrangler.toml)→ 构建前端 → `wrangler deploy --secrets-file` → 自动调用 `POST /api/setup` 执行数据库增量迁移并校验账本。
3. 部署自动升级:Worker 部署成功后,`deploy.yml` 自动通过 workers.dev 路由调用 `POST /api/setup` 执行增量迁移并校验账本,无需管理员手动点击升级。新项目首次部署后打开 `/setup` 完成初始化并注册首个管理员。
8 changes: 2 additions & 6 deletions web/src/App.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -388,19 +388,15 @@ describe("路由与根门", () => {
expect(
await screen.findByRole("tab", { name: "数据库维护" })
).toHaveAttribute("data-state", "active")
expect(
screen.getByRole("button", { name: "检查并升级数据库" })
).toBeInTheDocument()
expect(await screen.findByText("开放初始化页面")).toBeInTheDocument()
view5.unmount()

// 旧址 /admin/maintenance 重定向到 /admin/database
const view6 = renderAt(routes, "/admin/maintenance")
expect(
await screen.findByRole("tab", { name: "数据库维护" })
).toHaveAttribute("data-state", "active")
expect(
screen.getByRole("button", { name: "检查并升级数据库" })
).toBeInTheDocument()
expect(await screen.findByText("开放初始化页面")).toBeInTheDocument()
view6.unmount()
})

Expand Down
9 changes: 1 addition & 8 deletions web/src/lib/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@ import type {
LoginResult,
Me,
MeUpdateInput,
MigrationResult,
PasskeySummary,
PublicInfo,
RegisterResult,
Expand Down Expand Up @@ -342,10 +341,6 @@ export const commentsApi = {

/* 系统管理 */

export interface AdminSetupResult extends SetupResult {
migrations: MigrationResult[]
}

export const adminApi = {
settings: () => request<AdminSettings>("/admin/settings"),

Expand Down Expand Up @@ -441,7 +436,5 @@ export const adminApi = {
request<AdminImportResult>("/admin/import", {
method: "POST",
body: input
}),

runSetup: () => request<AdminSetupResult>("/admin/setup", { method: "POST" })
})
}
10 changes: 1 addition & 9 deletions web/src/locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -152,12 +152,10 @@
"title": "Setup",
"checking": "Checking setup state…",
"initSubtitle": "Enter the deployment secret to initialize the database.",
"upgradeSubtitle": "Enter the deployment secret to check and upgrade the database.",
"closedTitle": "Setup page is closed",
"closedBody": "An admin can re-open it under System.",
"secret": "Deployment secret",
"submitInit": "Initialize",
"submitUpgrade": "Check and upgrade",
"doneTitle": "Database is ready",
"tablePrefix": "Effective table prefix",
"noPrefix": "No prefix",
Expand Down Expand Up @@ -369,13 +367,7 @@
"title": "Database",
"setupPage": "Open the setup page",
"setupPageHint": "This only gates the page; the endpoint still requires the deployment secret.",
"tablePrefix": "Effective table prefix",
"run": "Check and upgrade database",
"running": "Running…",
"done": "Migrations complete",
"migrations": "Migrations",
"applied": "Applied",
"skipped": "Skipped"
"tablePrefix": "Effective table prefix"
}
},
"comments": {
Expand Down
10 changes: 1 addition & 9 deletions web/src/locales/zh.json
Original file line number Diff line number Diff line change
Expand Up @@ -152,12 +152,10 @@
"title": "初始化",
"checking": "正在检查初始化状态…",
"initSubtitle": "输入部署密钥以初始化数据库。",
"upgradeSubtitle": "输入部署密钥以检查并升级数据库。",
"closedTitle": "初始化页面已关闭",
"closedBody": "管理员可在系统管理中重新开启。",
"secret": "部署密钥",
"submitInit": "初始化",
"submitUpgrade": "检查并升级",
"doneTitle": "数据库已就绪",
"tablePrefix": "生效表前缀",
"noPrefix": "无前缀",
Expand Down Expand Up @@ -369,13 +367,7 @@
"title": "数据库维护",
"setupPage": "开放初始化页面",
"setupPageHint": "只控制页面入口,接口仍需部署密钥。",
"tablePrefix": "生效表前缀",
"run": "检查并升级数据库",
"running": "正在执行…",
"done": "迁移完成",
"migrations": "迁移记录",
"applied": "已执行",
"skipped": "已跳过"
"tablePrefix": "生效表前缀"
}
},
"comments": {
Expand Down
Loading