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
5 changes: 2 additions & 3 deletions .github/workflows/deploy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -48,9 +48,8 @@ jobs:
TABLE_PREFIX: ${{ vars.TABLE_PREFIX }}
run: node scripts/materialize-secrets.mjs

# The worker `deploy` script runs `pnpm codegen` first: schema.generated.ts
# is generated from schema.sql and not committed, so it must be regenerated
# before every wrangler deploy.
# Deploy Worker (schema migrations are applied by the Worker itself on
# setup / first read — see worker/src/lib/migrations-runner.ts).
- name: Deploy Worker
working-directory: worker
env:
Expand Down
1 change: 0 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ dist
.wrangler
*.local
.DS_Store
worker/src/db/schema.generated.ts
.dev.vars
*.tsbuildinfo
web/dist
Expand Down
26 changes: 25 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,31 @@ pnpm lint && pnpm format:check

## 初始化(setup)

线上首次部署、库中无账号时开放 setup:`POST /api/auth/setup`(header `X-Setup-Secret`)创建唯一所有者账号,创建后 setup 永久关闭,不设注册接口。
线上首次部署、库中无账号时开放 setup:`POST /api/auth/setup`(header `X-Setup-Secret`)创建唯一所有者账号,创建后 setup 永久关闭,不设注册接口。响应在 `{ success, user, tablePrefix }` 之外附 `migrations: [{ name, status }]`(`applied` / `skipped`)。

## 数据库迁移账本(schema ledger)

schema 的唯一可信源是 `worker/src/lib/migrations.ts` 的 `getMigrations(prefix)` 迁移列表,执行由 `worker/src/lib/migrations-runner.ts` 的 `runMigrations(env)` 完成(setup 路由与读路径 `ensureSchema` 共用同一个 runner)。原 `worker/src/db/schema.sql` + `gen-schema.mjs` codegen 已删除,不再有第二份 schema 定义。

**账本表名**:`_` + 前缀核 + `_schema_migrations`,前缀核即生效 `TABLE_PREFIX` 去掉尾部下划线(大小写原值保留):

| 生效前缀 | 账本表 |
| ------------ | --------------------------- |
| `nav_` | `_nav_schema_migrations` |
| `app_` | `_app_schema_migrations` |
| `abc123` | `_abc123_schema_migrations` |
| 空(`none`) | `_schema_migrations` |

表名只由 `migrationsTable(prefix)` 一处生成,不散落拼接。表结构 `name TEXT PRIMARY KEY, applied_at INTEGER NOT NULL DEFAULT (unixepoch())`。

**`schema_v1` 塌缩说明**:nav v1 上线时是裸建表(`CREATE TABLE IF NOT EXISTS` 逐次重放),没有版本历史;本次改造把当前全部 schema(表、索引、`setup_completed` 种子)整体塌缩为一条 `schema_v1`。存量库首次跑 runner 时 `schema_v1` 因 `IF NOT EXISTS` 直接成功并被记账,不需要数据迁移。

**runner 语义**:解析生效前缀 → 防静默切换冲突探测(库中已按其他前缀初始化过就报错,绝不再建第二套)→ 建账本表 → 读取已应用集合 → 按序执行未记录项、成功后立即写一行 → 首个失败即停、报错、失败项不落账、后续不执行。前缀冲突时 setup 返回 409 `{ error: "table prefix conflict", detail }`。

**今后迁移著述规则**:
1. 已合并的迁移名字与 SQL **不可修改**,只能在列表末尾追加(`schema_v2`、`schema_v3`…)。
2. 迁移必须向后兼容、只增不毁:只加表 / 索引 / 列,不删、不改名、不重写存量数据。
3. 破坏性变更须另行立规格(含删表重初始化清单),不走常规迁移。

## API 契约

Expand Down
3 changes: 1 addition & 2 deletions biome.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,7 @@
"!**/.wrangler",
"!**/web/public",
"!**/web/dist",
"!**/worker/.wrangler",
"!**/worker/src/db/schema.generated.ts"
"!**/worker/.wrangler"
]
},
"formatter": {
Expand Down
16 changes: 8 additions & 8 deletions docs/api-contract.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,14 +61,14 @@

## 鉴权(/api/auth/*)

| 方法 | 路径 | 说明 |
| ---- | ---------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| GET | `/api/auth/setup` | `{"enabled":true}` 表示可创建所有者 |
| POST | `/api/auth/setup` | header `X-Setup-Secret`;body `{username, password}`(password ≥ 8)→ 201 并下发会话;已有账号 → 403 |
| POST | `/api/auth/login` | body `{username, password}` → `{success, user}`;若已启用 TOTP → `{requires2fa:true, tempToken}`;失败 401 `{"error":"invalid credentials","remainingAttempts":N}`;连续失败 5 次锁定 15 分钟 → 429 |
| POST | `/api/auth/2fa/verify` | body `{tempToken, code}`(TOTP 6 位)→ 200 并下发会话;错误码 401 |
| POST | `/api/auth/logout` | 吊销当前会话 |
| GET | `/api/auth/session` | 会话探测:`{"authenticated":true,"userId":…}`;未登录 401 JSON |
| 方法 | 路径 | 说明 |
| ---- | ---------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| GET | `/api/auth/setup` | `{"enabled":true}` 表示可创建所有者 |
| POST | `/api/auth/setup` | header `X-Setup-Secret`;body `{username, password}`(password ≥ 8)→ 201 并下发会话,附 `tablePrefix` 与 `migrations:[{name,status}]`(账本迁移结果);已有账号 → 403;表前缀冲突 → 409 `{"error":"table prefix conflict"}` |
| POST | `/api/auth/login` | body `{username, password}` → `{success, user}`;若已启用 TOTP → `{requires2fa:true, tempToken}`;失败 401 `{"error":"invalid credentials","remainingAttempts":N}`;连续失败 5 次锁定 15 分钟 → 429 |
| POST | `/api/auth/2fa/verify` | body `{tempToken, code}`(TOTP 6 位)→ 200 并下发会话;错误码 401 |
| POST | `/api/auth/logout` | 吊销当前会话 |
| GET | `/api/auth/session` | 会话探测:`{"authenticated":true,"userId":…}`;未登录 401 JSON |

Passkey(WebAuthn,/api/auth/passkey/*,@simplewebauthn/server v14):

Expand Down
11 changes: 5 additions & 6 deletions worker/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,11 @@
"private": true,
"type": "module",
"scripts": {
"codegen": "node scripts/gen-schema.mjs",
"dev": "pnpm codegen && wrangler dev",
"build": "pnpm codegen && tsc --noEmit",
"typecheck": "pnpm codegen && tsc --noEmit",
"test": "pnpm codegen && vitest run",
"deploy": "pnpm codegen && wrangler deploy"
"dev": "wrangler dev",
"build": "tsc --noEmit",
"typecheck": "tsc --noEmit",
"test": "vitest run",
"deploy": "wrangler deploy"
},
"dependencies": {
"@simplewebauthn/server": "^14.0.0",
Expand Down
19 changes: 0 additions & 19 deletions worker/scripts/gen-schema.mjs

This file was deleted.

113 changes: 0 additions & 113 deletions worker/src/db/schema.sql

This file was deleted.

13 changes: 0 additions & 13 deletions worker/src/db/sql.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,5 @@
// Shared SQL helpers.

export function splitStatements(sql: string): string[] {
return sql
.split(";")
.map((s) => s.trim())
.filter((s) => s.length > 0);
}

export async function runScript(db: D1Database, sql: string): Promise<void> {
for (const stmt of splitStatements(sql)) {
await db.prepare(stmt).run();
}
}

export function nowIso(): string {
return new Date().toISOString();
}
25 changes: 10 additions & 15 deletions worker/src/lib/migrate.ts
Original file line number Diff line number Diff line change
@@ -1,34 +1,29 @@
import { getTablePrefix, type Env } from "../types";
import { countUsers } from "../db/queries/users";
import { runMigrations, type RunMigrationsResult } from "./migrations-runner";

// Per-isolate flag: after the first successful run in this Worker isolate the
// schema is guaranteed to exist for the isolate's lifetime, so read paths skip
// the DDL replay entirely (D1 tables persist across requests).
// the ledger replay entirely (D1 tables persist across requests).
let schemaReady = false;
import { runScript } from "../db/sql";
// Schema source of truth: src/db/schema.sql. It is loaded through a generated
// module so both the Worker build and the test runner can import it plainly.
import { SCHEMA_SQL } from "../db/schema.generated";

/**
* Applies the D1 schema. Idempotent by construction: every statement in
* schema.sql uses IF NOT EXISTS / OR IGNORE, so re-running on an empty or an
* already-initialized database succeeds (acceptance: "空库迁移可重复执行成功").
* Applies pending migrations and marks the isolate schema-ready. Returns the
* per-migration ledger outcome so setup can report what was applied/skipped.
* Idempotent: recorded migrations are skipped, so re-running is cheap.
*/
export async function runMigrations(env: Env): Promise<{ applied: boolean }> {
const prefix = getTablePrefix(env);
const resolved = SCHEMA_SQL.replace(/\{prefix\}/g, prefix);
await runScript(env.DB, resolved);
export async function applyMigrations(env: Env): Promise<RunMigrationsResult> {
const result = await runMigrations(env);
schemaReady = true;
return { applied: true };
return result;
}

/**
* Read-surface guard: ensures the schema exists at most once per isolate.
* Runs the idempotent DDL on first request, then only a cheap COUNT probe.
* Runs the ledgered migrations on first request, then only a cheap COUNT probe.
*/
export async function ensureSchema(env: Env): Promise<void> {
if (schemaReady) return;
await runMigrations(env);
await applyMigrations(env);
await countUsers(env.DB, getTablePrefix(env));
}
Loading
Loading