diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index 823721b..50a6b84 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -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: diff --git a/.gitignore b/.gitignore index 76857a1..abefe00 100644 --- a/.gitignore +++ b/.gitignore @@ -3,7 +3,6 @@ dist .wrangler *.local .DS_Store -worker/src/db/schema.generated.ts .dev.vars *.tsbuildinfo web/dist diff --git a/README.md b/README.md index 1338322..3d2052c 100644 --- a/README.md +++ b/README.md @@ -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 契约 diff --git a/biome.json b/biome.json index c4d316e..fda7e42 100644 --- a/biome.json +++ b/biome.json @@ -8,8 +8,7 @@ "!**/.wrangler", "!**/web/public", "!**/web/dist", - "!**/worker/.wrangler", - "!**/worker/src/db/schema.generated.ts" + "!**/worker/.wrangler" ] }, "formatter": { diff --git a/docs/api-contract.md b/docs/api-contract.md index 986bed2..f25c4e5 100644 --- a/docs/api-contract.md +++ b/docs/api-contract.md @@ -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): diff --git a/worker/package.json b/worker/package.json index 3739ac4..69bf0e2 100644 --- a/worker/package.json +++ b/worker/package.json @@ -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", diff --git a/worker/scripts/gen-schema.mjs b/worker/scripts/gen-schema.mjs deleted file mode 100644 index 583803f..0000000 --- a/worker/scripts/gen-schema.mjs +++ /dev/null @@ -1,19 +0,0 @@ -#!/usr/bin/env node -// Generates src/db/schema.generated.ts from src/db/schema.sql so the schema can -// be imported as a plain string in both the Worker build and the test runner. -// Run via `pnpm --filter worker codegen` (also invoked before typecheck/test). -import { readFileSync, writeFileSync } from "node:fs"; -import { fileURLToPath } from "node:url"; - -const sqlPath = fileURLToPath(new URL("../src/db/schema.sql", import.meta.url)); -const outPath = fileURLToPath( - new URL("../src/db/schema.generated.ts", import.meta.url), -); -const sql = readFileSync(sqlPath, "utf8"); - -const banner = `// AUTO-GENERATED by scripts/gen-schema.mjs from src/db/schema.sql — do not edit. -export const SCHEMA_SQL = ${JSON.stringify(sql)}; -`; - -writeFileSync(outPath, banner); -console.log("schema.generated.ts written"); diff --git a/worker/src/db/schema.sql b/worker/src/db/schema.sql deleted file mode 100644 index cf70403..0000000 --- a/worker/src/db/schema.sql +++ /dev/null @@ -1,113 +0,0 @@ --- nav database schema --- All table names use {prefix} placeholder, replaced at runtime. --- Idempotent: every statement is IF NOT EXISTS / OR IGNORE so the migration --- can be re-run safely on an empty or already-initialized database. - -CREATE TABLE IF NOT EXISTS {prefix}users ( - id TEXT PRIMARY KEY, - username TEXT UNIQUE NOT NULL, - password_hash TEXT NOT NULL, - is_active INTEGER NOT NULL DEFAULT 1, - created_at TEXT NOT NULL, - updated_at TEXT NOT NULL -); - -CREATE TABLE IF NOT EXISTS {prefix}passkey_credentials ( - id TEXT PRIMARY KEY, - user_id TEXT NOT NULL REFERENCES {prefix}users(id) ON DELETE CASCADE, - public_key TEXT NOT NULL, - counter INTEGER NOT NULL DEFAULT 0, - created_at TEXT NOT NULL, - updated_at TEXT NOT NULL -); - -CREATE INDEX IF NOT EXISTS idx_{prefix}passkey_credentials_user_id - ON {prefix}passkey_credentials(user_id); - -CREATE TABLE IF NOT EXISTS {prefix}sessions ( - id TEXT PRIMARY KEY, - user_id TEXT NOT NULL REFERENCES {prefix}users(id) ON DELETE CASCADE, - created_at TEXT NOT NULL, - expires_at TEXT NOT NULL, - last_seen_at TEXT NOT NULL, - ip TEXT, - user_agent TEXT -); - -CREATE INDEX IF NOT EXISTS idx_{prefix}sessions_user_id - ON {prefix}sessions(user_id); - -CREATE TABLE IF NOT EXISTS {prefix}login_attempts ( - id TEXT PRIMARY KEY, - username TEXT NOT NULL, - ip TEXT NOT NULL, - success INTEGER NOT NULL DEFAULT 0, - created_at TEXT NOT NULL, - locked_until TEXT -); - -CREATE INDEX IF NOT EXISTS idx_{prefix}login_attempts_created_at - ON {prefix}login_attempts(created_at); - -CREATE TABLE IF NOT EXISTS {prefix}challenges ( - id TEXT PRIMARY KEY, - kind TEXT NOT NULL, - user_id TEXT, - value TEXT NOT NULL, - created_at TEXT NOT NULL, - expires_at TEXT NOT NULL -); - -CREATE INDEX IF NOT EXISTS idx_{prefix}challenges_expires_at - ON {prefix}challenges(expires_at); - -CREATE TABLE IF NOT EXISTS {prefix}categories ( - id TEXT PRIMARY KEY, - name TEXT NOT NULL, - icon TEXT, - sort_order INTEGER NOT NULL DEFAULT 0, - visibility TEXT NOT NULL DEFAULT 'public' CHECK (visibility IN ('public', 'private')), - created_at TEXT NOT NULL, - updated_at TEXT NOT NULL -); - -CREATE TABLE IF NOT EXISTS {prefix}links ( - id TEXT PRIMARY KEY, - category_id TEXT NOT NULL REFERENCES {prefix}categories(id) ON DELETE CASCADE, - title TEXT NOT NULL, - url TEXT NOT NULL, - icon_url TEXT, - description TEXT, - sort_order INTEGER NOT NULL DEFAULT 0, - visibility TEXT NOT NULL DEFAULT 'public' CHECK (visibility IN ('public', 'private')), - -- Reserved per SPEC §5, not implemented in v1: click counting and - -- private-service health status. - click_count INTEGER NOT NULL DEFAULT 0, - status TEXT, - last_checked_at TEXT, - created_at TEXT NOT NULL, - updated_at TEXT NOT NULL -); - -CREATE INDEX IF NOT EXISTS idx_{prefix}links_category_id - ON {prefix}links(category_id); - -CREATE TABLE IF NOT EXISTS {prefix}search_engines ( - id TEXT PRIMARY KEY, - name TEXT NOT NULL, - url_template TEXT NOT NULL, - icon TEXT, - sort_order INTEGER NOT NULL DEFAULT 0, - is_default INTEGER NOT NULL DEFAULT 0, - created_at TEXT NOT NULL, - updated_at TEXT NOT NULL -); - -CREATE TABLE IF NOT EXISTS {prefix}settings ( - key TEXT PRIMARY KEY, - value TEXT NOT NULL, - updated_at TEXT NOT NULL -); - -INSERT OR IGNORE INTO {prefix}settings (key, value, updated_at) -VALUES ('setup_completed', '0', strftime('%Y-%m-%dT%H:%M:%fZ', 'now')); diff --git a/worker/src/db/sql.ts b/worker/src/db/sql.ts index 395e740..6328579 100644 --- a/worker/src/db/sql.ts +++ b/worker/src/db/sql.ts @@ -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 { - for (const stmt of splitStatements(sql)) { - await db.prepare(stmt).run(); - } -} - export function nowIso(): string { return new Date().toISOString(); } diff --git a/worker/src/lib/migrate.ts b/worker/src/lib/migrate.ts index 0122d2c..b145af1 100644 --- a/worker/src/lib/migrate.ts +++ b/worker/src/lib/migrate.ts @@ -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 { + 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 { if (schemaReady) return; - await runMigrations(env); + await applyMigrations(env); await countUsers(env.DB, getTablePrefix(env)); } diff --git a/worker/src/lib/migrations-runner.ts b/worker/src/lib/migrations-runner.ts new file mode 100644 index 0000000..85b3555 --- /dev/null +++ b/worker/src/lib/migrations-runner.ts @@ -0,0 +1,256 @@ +// Ledgered schema migration runner (ONE-346 / ONE-357), modelled on shortlink's +// lib/migrations-runner.ts. Every schema change goes through this one runner: +// migrations listed in lib/migrations.ts are applied in order, recorded in the +// ledger table `__schema_migrations`, skipped when already recorded, and +// execution stops at the first failure (the failed migration is not recorded). + +import { getTablePrefix, type Env } from "../types"; +import { + createMigrationsTableSql, + getMigrations, + migrationsTable, + prefixCore, + type Migration, +} from "./migrations"; + +export interface MigrationResult { + name: string; + status: "applied" | "skipped" | "error"; + error?: string; +} + +export interface RunMigrationsResult { + /** Effective table prefix resolved for this run ("" = no prefix). */ + prefix: string; + migrations: MigrationResult[]; +} + +// Thrown when the database already holds a nav schema under a different prefix +// than the one resolved from the environment: migrating would silently build a +// second, empty set of tables instead of using the existing one. +export class TablePrefixConflictError extends Error { + constructor(message: string) { + super(message); + this.name = "TablePrefixConflictError"; + } +} + +// Business tables that only nav has in the shared D1 database (eNotify_*, +// SL_*, ZETA_*, post_* … have none of them), so their co-occurrence under one +// prefix marks a nav schema. Never a single-table match. +const NAV_UNIQUE_SUFFIXES: readonly string[] = [ + "passkey_credentials", + "search_engines", + "login_attempts", +]; + +/** + * Prefixes (lowercased, `""` for unprefixed) under which nav's business-table + * family appears: `nav_passkey_credentials` + `nav_search_engines` + + * `nav_login_attempts` → `nav`. + */ +function detectNavSchemaPrefixes(names: string[]): string[] { + const byPrefix = new Map>(); + + for (const name of names) { + const lower = name.toLowerCase(); + for (const suffix of NAV_UNIQUE_SUFFIXES) { + let prefix: string | null = null; + if (lower === suffix) prefix = ""; + else if (lower.endsWith(`_${suffix}`)) { + prefix = lower.slice(0, lower.length - suffix.length - 1); + } + if (prefix === null) continue; + + let suffixes = byPrefix.get(prefix); + if (suffixes === undefined) { + suffixes = new Set(); + byPrefix.set(prefix, suffixes); + } + suffixes.add(suffix); + } + } + + const detected: string[] = []; + for (const [prefix, suffixes] of byPrefix) { + if (NAV_UNIQUE_SUFFIXES.every((suffix) => suffixes.has(suffix))) { + detected.push(prefix); + } + } + return detected; +} + +/** + * Prefixes under which any migration ledger (`__schema_migrations`) + * exists. A ledger name alone cannot be attributed to nav — other projects + * sharing the database keep their own ledger — so this signal is only used when + * TABLE_PREFIX resolves to no prefix at all, where building an unprefixed nav + * schema next to any ledger would be unsafe. + */ +function detectLedgerPrefixes(names: string[]): string[] { + const prefixes: string[] = []; + for (const name of names) { + const match = /^_(.+)_schema_migrations$/i.exec(name); + if (match !== null && match[1] !== undefined && match[1] !== "") { + prefixes.push(match[1]); + } + } + return prefixes; +} + +/** + * Describes the conflicting already-initialised nav schema, or returns null when + * it is safe to migrate under `prefix`. Read-only: never writes. + */ +async function detectTablePrefixConflict( + db: D1Database, + prefix: string, +): Promise { + const { results } = await db + .prepare("SELECT name FROM sqlite_master WHERE type = 'table'") + .all<{ name: string }>(); + const names = results.map((row) => row.name); + // SQLite identifiers are case-insensitive, so table-name existence checks are + // too (while every name we generate keeps the configured prefix's case). + const has = (table: string) => + names.some((name) => name.toLowerCase() === table.toLowerCase()); + + // Already initialised under this exact prefix → incremental migration. + if (has(migrationsTable(prefix))) return null; + + const navPrefixes = detectNavSchemaPrefixes(names); + const unprefixedNav = navPrefixes.includes(""); + const prefixedNav = navPrefixes.filter((detected) => detected !== ""); + + if (prefix === "") { + // No ledger yet: an unprefixed nav table family is our own schema from + // before the ledger existed (schema_v1 uses IF NOT EXISTS, so it adopts it), + // but a prefixed nav schema or an existing ledger would get duplicated. + if (unprefixedNav) return null; + + const ledgers = detectLedgerPrefixes(names); + if (ledgers.length > 0) { + return ( + `the database already contains schema ledgers ` + + `(${ledgers.map((p) => `_${p}_schema_migrations`).join(", ")}) — ` + + `these may belong to other projects sharing the database. Refusing to ` + + `initialise an unprefixed nav schema. Configure TABLE_PREFIX to nav's ` + + `dedicated prefix (e.g. TABLE_PREFIX=nav_).` + ); + } + if (prefixedNav.length > 0) { + return ( + `the database already contains a nav schema under the prefix ` + + `(${prefixedNav.map((p) => `${p}_*`).join(", ")}), but TABLE_PREFIX ` + + `resolves to an empty string. Refusing to initialise an unprefixed nav ` + + `schema. Configure TABLE_PREFIX to its current value ` + + `(e.g. TABLE_PREFIX=${prefixedNav[0]}_).` + ); + } + return null; + } + + // Prefixed target: an unprefixed nav schema (or the ledger `_schema_migrations` + // next to it) or another prefix's nav schema would be a silent switch. + if (unprefixedNav) { + return ( + `the database already contains an unprefixed nav schema, but ` + + `TABLE_PREFIX resolves to '${prefix}'. Refusing to initialise a new ` + + `'${prefix}'-prefixed schema. To keep the existing unprefixed schema, ` + + `explicitly configure TABLE_PREFIX='' (or TABLE_PREFIX=none in CI).` + ); + } + // Table-derived prefixes are cores (`nav_passkey_credentials` → `nav`), so + // compare against the configured prefix's core, not the raw wrapper value. + const targetCore = prefixCore(prefix).toLowerCase(); + const others = prefixedNav.filter((detected) => detected !== targetCore); + if (others.length > 0) { + return ( + `the database already contains a nav schema under the prefix ` + + `(${others.map((p) => `${p}_*`).join(", ")}), but TABLE_PREFIX resolves ` + + `to '${prefix}'. Refusing to initialise a second '${prefix}'-prefixed ` + + `schema. Configure TABLE_PREFIX to its current value ` + + `(e.g. TABLE_PREFIX=${others[0]}_).` + ); + } + return null; +} + +// D1's exec() only processes the first line of a multi-line string, so strip +// SQL line comments and collapse every migration onto a single line. +function toSingleLine(sql: string): string { + return sql + .split("\n") + .map((line) => { + const comment = line.indexOf("--"); + return comment >= 0 ? line.slice(0, comment) : line; + }) + .join(" ") + .replace(/\s+/g, " ") + .trim(); +} + +/** + * Applies `migrations` in order under `prefix`, recording each success in the + * ledger table. Skips recorded migrations, stops at the first error (reported + * inline instead of thrown) and never records the failed migration. + */ +export async function applyMigrationList( + db: D1Database, + prefix: string, + migrations: Migration[], +): Promise { + const ledger = migrationsTable(prefix); + await db.prepare(createMigrationsTableSql(prefix)).run(); + + const existing = await db + .prepare(`SELECT name FROM ${ledger}`) + .all<{ name: string }>(); + const recorded = new Set(existing.results.map((row) => row.name)); + + const results: MigrationResult[] = []; + + for (const migration of migrations) { + if (recorded.has(migration.name)) { + results.push({ name: migration.name, status: "skipped" }); + continue; + } + try { + await db.exec(toSingleLine(migration.sql)); + await db + .prepare(`INSERT INTO ${ledger} (name) VALUES (?)`) + .bind(migration.name) + .run(); + results.push({ name: migration.name, status: "applied" }); + } catch (err) { + results.push({ + name: migration.name, + status: "error", + error: String(err), + }); + break; + } + } + + return results; +} + +/** + * Resolves the effective prefix, guards against a silent prefix switch, then + * applies every migration not yet recorded in the ledger. Throws + * TablePrefixConflictError when the database already holds a nav schema under a + * different prefix. + */ +export async function runMigrations(env: Env): Promise { + const prefix = getTablePrefix(env); + + const conflict = await detectTablePrefixConflict(env.DB, prefix); + if (conflict !== null) throw new TablePrefixConflictError(conflict); + + const migrations = await applyMigrationList( + env.DB, + prefix, + getMigrations(prefix), + ); + return { prefix, migrations }; +} diff --git a/worker/src/lib/migrations.ts b/worker/src/lib/migrations.ts new file mode 100644 index 0000000..e90febc --- /dev/null +++ b/worker/src/lib/migrations.ts @@ -0,0 +1,168 @@ +// Schema migrations, parameterised by TABLE_PREFIX (ONE-346 / ONE-357). +// +// Single source of truth for the nav D1 schema: the versioned migration list +// below is the ONLY place the schema is defined. Both the public setup route +// (POST /api/auth/setup) and the read-path guard (lib/migrate.ts → +// ensureSchema) run this list through lib/migrations-runner.ts. +// +// Writing migrations from here on (README §迁移账本): +// - Already-merged migrations are immutable: never edit their name or SQL. +// - Append new migrations at the end as `schema_v2`, `schema_v3`, … +// - Additive only (CREATE TABLE/INDEX IF NOT EXISTS, ALTER TABLE ADD COLUMN, +// INSERT OR IGNORE). Destructive changes need a separate spec. + +/** + * Table prefix core: the effective prefix without its trailing underscore(s). + * `nav_` → `nav`, `""` → `""` (no prefix). Case is preserved verbatim. + * + * Exported because the conflict probe compares table-derived prefix cores + * (`nav_passkey_credentials` → `nav`) against the configured prefix. + */ +export function prefixCore(prefix: string): string { + return prefix.replace(/_+$/, ""); +} + +/** + * Name of the migration ledger table for a prefix — the single place that + * formula is implemented, e.g. `_nav_schema_migrations`. + * + * `nav_` → `_nav_schema_migrations`, `app_` → `_app_schema_migrations`, + * `abc123` → `_abc123_schema_migrations`, `""` → `_schema_migrations`. + */ +export function migrationsTable(prefix: string): string { + const core = prefixCore(prefix); + return core === "" ? "_schema_migrations" : `_${core}_schema_migrations`; +} + +export function createMigrationsTableSql(prefix: string): string { + return `CREATE TABLE IF NOT EXISTS ${migrationsTable(prefix)} (name TEXT PRIMARY KEY, applied_at INTEGER NOT NULL DEFAULT (unixepoch()))`; +} + +export interface Migration { + name: string; + sql: string; +} + +/** + * The migration list for a prefix. `schema_v1` is the whole current nav schema + * (tables, indexes and the `setup_completed` seed): nav v1 shipped without a + * ledger, so its history is collapsed into one baseline migration. + */ +export function getMigrations(prefix: string): Migration[] { + const t = (name: string) => `${prefix}${name}`; + const idx = (name: string) => `idx_${prefix}${name}`; + + return [ + { + name: "schema_v1", + sql: ` +CREATE TABLE IF NOT EXISTS ${t("users")} ( + id TEXT PRIMARY KEY, + username TEXT UNIQUE NOT NULL, + password_hash TEXT NOT NULL, + is_active INTEGER NOT NULL DEFAULT 1, + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL +); + +CREATE TABLE IF NOT EXISTS ${t("passkey_credentials")} ( + id TEXT PRIMARY KEY, + user_id TEXT NOT NULL REFERENCES ${t("users")}(id) ON DELETE CASCADE, + public_key TEXT NOT NULL, + counter INTEGER NOT NULL DEFAULT 0, + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL +); + +CREATE INDEX IF NOT EXISTS ${idx("passkey_credentials_user_id")} + ON ${t("passkey_credentials")}(user_id); + +CREATE TABLE IF NOT EXISTS ${t("sessions")} ( + id TEXT PRIMARY KEY, + user_id TEXT NOT NULL REFERENCES ${t("users")}(id) ON DELETE CASCADE, + created_at TEXT NOT NULL, + expires_at TEXT NOT NULL, + last_seen_at TEXT NOT NULL, + ip TEXT, + user_agent TEXT +); + +CREATE INDEX IF NOT EXISTS ${idx("sessions_user_id")} + ON ${t("sessions")}(user_id); + +CREATE TABLE IF NOT EXISTS ${t("login_attempts")} ( + id TEXT PRIMARY KEY, + username TEXT NOT NULL, + ip TEXT NOT NULL, + success INTEGER NOT NULL DEFAULT 0, + created_at TEXT NOT NULL, + locked_until TEXT +); + +CREATE INDEX IF NOT EXISTS ${idx("login_attempts_created_at")} + ON ${t("login_attempts")}(created_at); + +CREATE TABLE IF NOT EXISTS ${t("challenges")} ( + id TEXT PRIMARY KEY, + kind TEXT NOT NULL, + user_id TEXT, + value TEXT NOT NULL, + created_at TEXT NOT NULL, + expires_at TEXT NOT NULL +); + +CREATE INDEX IF NOT EXISTS ${idx("challenges_expires_at")} + ON ${t("challenges")}(expires_at); + +CREATE TABLE IF NOT EXISTS ${t("categories")} ( + id TEXT PRIMARY KEY, + name TEXT NOT NULL, + icon TEXT, + sort_order INTEGER NOT NULL DEFAULT 0, + visibility TEXT NOT NULL DEFAULT 'public' CHECK (visibility IN ('public', 'private')), + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL +); + +CREATE TABLE IF NOT EXISTS ${t("links")} ( + id TEXT PRIMARY KEY, + category_id TEXT NOT NULL REFERENCES ${t("categories")}(id) ON DELETE CASCADE, + title TEXT NOT NULL, + url TEXT NOT NULL, + icon_url TEXT, + description TEXT, + sort_order INTEGER NOT NULL DEFAULT 0, + visibility TEXT NOT NULL DEFAULT 'public' CHECK (visibility IN ('public', 'private')), + click_count INTEGER NOT NULL DEFAULT 0, + status TEXT, + last_checked_at TEXT, + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL +); + +CREATE INDEX IF NOT EXISTS ${idx("links_category_id")} + ON ${t("links")}(category_id); + +CREATE TABLE IF NOT EXISTS ${t("search_engines")} ( + id TEXT PRIMARY KEY, + name TEXT NOT NULL, + url_template TEXT NOT NULL, + icon TEXT, + sort_order INTEGER NOT NULL DEFAULT 0, + is_default INTEGER NOT NULL DEFAULT 0, + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL +); + +CREATE TABLE IF NOT EXISTS ${t("settings")} ( + key TEXT PRIMARY KEY, + value TEXT NOT NULL, + updated_at TEXT NOT NULL +); + +INSERT OR IGNORE INTO ${t("settings")} (key, value, updated_at) +VALUES ('setup_completed', '0', strftime('%Y-%m-%dT%H:%M:%fZ', 'now')); +`, + }, + ]; +} diff --git a/worker/src/routes/auth.ts b/worker/src/routes/auth.ts index 849fd81..12e60c9 100644 --- a/worker/src/routes/auth.ts +++ b/worker/src/routes/auth.ts @@ -1,7 +1,11 @@ import { Hono } from "hono"; import { deleteCookie, getCookie } from "hono/cookie"; import { getTablePrefix, type HonoEnv } from "../types"; -import { ensureSchema } from "../lib/migrate"; +import { applyMigrations } from "../lib/migrate"; +import { + TablePrefixConflictError, + type MigrationResult, +} from "../lib/migrations-runner"; import { generateId, generateToken, @@ -67,8 +71,20 @@ authRoutes.post("/setup", async (c) => { return c.json({ error: "invalid TABLE_PREFIX configuration" }, 500); } - // Apply the idempotent schema (creates {prefix}* tables on first setup). - await ensureSchema(c.env); + // Apply the ledgered migrations (creates {prefix}* tables on first setup) and + // report each migration's outcome in the response. + let migrations: MigrationResult[]; + try { + migrations = (await applyMigrations(c.env)).migrations; + } catch (err) { + if (err instanceof TablePrefixConflictError) { + return c.json( + { error: "table prefix conflict", detail: err.message }, + 409, + ); + } + throw err; + } const users = await countUsers(c.env.DB, prefix); if (users > 0) return c.json({ error: "setup already completed" }, 403); @@ -108,6 +124,10 @@ authRoutes.post("/setup", async (c) => { success: true, user: { id: created.id, username: created.username }, tablePrefix: prefix, + migrations: migrations.map((migration) => ({ + name: migration.name, + status: migration.status, + })), }, 201, ); diff --git a/worker/test/api-contract.test.ts b/worker/test/api-contract.test.ts index b26e618..d612a51 100644 --- a/worker/test/api-contract.test.ts +++ b/worker/test/api-contract.test.ts @@ -1,6 +1,6 @@ import { beforeEach, describe, expect, it } from "vitest"; import { Hono } from "hono"; -import { runMigrations } from "../src/lib/migrate"; +import { runMigrations } from "../src/lib/migrations-runner"; import { publicRoutes } from "../src/routes/public"; import { privateRoutes } from "../src/routes/private"; import { adminRoutes } from "../src/routes/admin"; diff --git a/worker/test/auth.test.ts b/worker/test/auth.test.ts index bb2b9fe..fd56a19 100644 --- a/worker/test/auth.test.ts +++ b/worker/test/auth.test.ts @@ -1,6 +1,6 @@ import { beforeEach, describe, expect, it } from "vitest"; import { Hono } from "hono"; -import { runMigrations } from "../src/lib/migrate"; +import { runMigrations } from "../src/lib/migrations-runner"; import { authRoutes } from "../src/routes/auth"; import { privateRoutes } from "../src/routes/private"; import { adminRoutes } from "../src/routes/admin"; @@ -209,3 +209,30 @@ describe("authenticated access after login", () => { expect(after.status).toBe(401); }); }); + +describe("setup response (ledgered migrations)", () => { + it("reports the effective prefix and each migration result", async () => { + const env = makeEnv(); + const app = makeApp(); + + const res = await setupRequest(app, env); + expect(res.status).toBe(201); + const body = await readJson(res); + expect(body.success).toBe(true); + expect(body.tablePrefix).toBe(""); + expect(body.migrations).toEqual([{ name: "schema_v1", status: "applied" }]); + }); + + it("turns a table-prefix conflict into 409 instead of building a second schema", async () => { + const env = makeEnv({ TABLE_PREFIX: "nav_" }); + const app = makeApp(); + await runMigrations(env); // database already holds the nav_* schema + + const conflicting: Env = { ...env, TABLE_PREFIX: "" }; + const res = await setupRequest(app, conflicting); + expect(res.status).toBe(409); + const body = await readJson(res); + expect(body.error).toBe("table prefix conflict"); + expect(body.detail).toContain("TABLE_PREFIX"); + }); +}); diff --git a/worker/test/helpers.ts b/worker/test/helpers.ts index af62a20..d16f153 100644 --- a/worker/test/helpers.ts +++ b/worker/test/helpers.ts @@ -35,6 +35,14 @@ export class SqliteD1 { }, }; } + + // D1Database.exec(): runs one or more semicolon-separated statements. Backed + // by node:sqlite's native exec, which accepts multi-statement SQL. + async exec(sql: string): Promise<{ count: number; duration: number }> { + this.queries.push(sql); + this.db.exec(sql); + return { count: 0, duration: 0 }; + } } export function makeEnv(overrides: Partial = {}): Env { diff --git a/worker/test/migrate.test.ts b/worker/test/migrate.test.ts index 9fd5c28..8d01bc2 100644 --- a/worker/test/migrate.test.ts +++ b/worker/test/migrate.test.ts @@ -1,12 +1,14 @@ import { describe, expect, it } from "vitest"; -import { runMigrations } from "../src/lib/migrate"; +import { runMigrations } from "../src/lib/migrations-runner"; import { makeEnv, type SqliteD1 } from "./helpers"; describe("D1 migration", () => { it("applies cleanly on an empty database", async () => { const env = makeEnv(); const result = await runMigrations(env); - expect(result.applied).toBe(true); + expect(result.migrations).toEqual([ + { name: "schema_v1", status: "applied" }, + ]); const db = (env.DB as unknown as SqliteD1).db; const tables = db @@ -34,8 +36,14 @@ describe("D1 migration", () => { it("is idempotent — can be re-run on an initialized database", async () => { const env = makeEnv(); await runMigrations(env); - await expect(runMigrations(env)).resolves.toEqual({ applied: true }); - await expect(runMigrations(env)).resolves.toEqual({ applied: true }); + await expect(runMigrations(env)).resolves.toEqual({ + prefix: "", + migrations: [{ name: "schema_v1", status: "skipped" }], + }); + await expect(runMigrations(env)).resolves.toEqual({ + prefix: "", + migrations: [{ name: "schema_v1", status: "skipped" }], + }); }); it("respects the table prefix", async () => { @@ -49,6 +57,7 @@ describe("D1 migration", () => { .map((row: any) => row.name); expect(tables).toContain("nav_users"); expect(tables).toContain("nav_links"); + expect(tables).toContain("_nav_schema_migrations"); expect(tables).not.toContain("users"); }); diff --git a/worker/test/migrations-ledger.test.ts b/worker/test/migrations-ledger.test.ts new file mode 100644 index 0000000..2bf55ac --- /dev/null +++ b/worker/test/migrations-ledger.test.ts @@ -0,0 +1,221 @@ +import { describe, expect, it } from "vitest"; +import { migrationsTable } from "../src/lib/migrations"; +import { + applyMigrationList, + runMigrations, + TablePrefixConflictError, +} from "../src/lib/migrations-runner"; +import { makeEnv, type SqliteD1 } from "./helpers"; + +type Db = ReturnType["DB"]; + +function sqliteOf(db: Db): SqliteD1["db"] { + return (db as unknown as SqliteD1).db; +} + +function tableNames(db: Db): string[] { + return sqliteOf(db) + .prepare( + "SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name", + ) + .all() + .map((row: { name: string }) => row.name); +} + +function ledgerRows(db: Db, prefix: string) { + return sqliteOf(db) + .prepare( + `SELECT name, applied_at FROM ${migrationsTable(prefix)} ORDER BY name`, + ) + .all() as Array<{ name: string; applied_at: number }>; +} + +describe("migrationsTable() naming (three states + case preserved)", () => { + it("derives the ledger table from the effective prefix", () => { + expect(migrationsTable("nav_")).toBe("_nav_schema_migrations"); + expect(migrationsTable("app_")).toBe("_app_schema_migrations"); + expect(migrationsTable("")).toBe("_schema_migrations"); + expect(migrationsTable("abc123")).toBe("_abc123_schema_migrations"); + }); + + it("preserves the prefix's original case and strips only the trailing underscore", () => { + expect(migrationsTable("ZETA_")).toBe("_ZETA_schema_migrations"); + expect(migrationsTable("NAV_")).toBe("_NAV_schema_migrations"); + expect(migrationsTable("nav__")).toBe("_nav_schema_migrations"); + }); +}); + +describe("ledgered migration runner", () => { + it("applies everything on an empty database and records exactly schema_v1", async () => { + const env = makeEnv({ TABLE_PREFIX: undefined }); // → nav_ + const result = await runMigrations(env); + + expect(result.prefix).toBe("nav_"); + expect(result.migrations.map((m) => [m.name, m.status])).toEqual([ + ["schema_v1", "applied"], + ]); + + const ledger = ledgerRows(env.DB, "nav_"); + expect(ledger.map((row) => row.name)).toEqual(["schema_v1"]); + expect(ledger[0]?.applied_at).toBeGreaterThan(0); + + const tables = tableNames(env.DB); + expect(tables).toContain("_nav_schema_migrations"); + for (const table of [ + "users", + "passkey_credentials", + "sessions", + "login_attempts", + "challenges", + "categories", + "links", + "search_engines", + "settings", + ]) { + expect(tables).toContain(`nav_${table}`); + } + }); + + it("skips everything on a second run and leaves the schema untouched", async () => { + const env = makeEnv({ TABLE_PREFIX: "nav_" }); + await runMigrations(env); + + const schemaBefore = tableNames(env.DB); + const indexesBefore = sqliteOf(env.DB) + .prepare( + "SELECT name FROM sqlite_master WHERE type = 'index' ORDER BY name", + ) + .all(); + const ledgerBefore = ledgerRows(env.DB, "nav_"); + + const second = await runMigrations(env); + expect(second.migrations).toEqual([ + { name: "schema_v1", status: "skipped" }, + ]); + + expect(tableNames(env.DB)).toEqual(schemaBefore); + expect( + sqliteOf(env.DB) + .prepare( + "SELECT name FROM sqlite_master WHERE type = 'index' ORDER BY name", + ) + .all(), + ).toEqual(indexesBefore); + expect(ledgerRows(env.DB, "nav_")).toEqual(ledgerBefore); + }); + + it("records the ledger under the no-prefix name for an explicit empty prefix", async () => { + const env = makeEnv({ TABLE_PREFIX: "" }); + const result = await runMigrations(env); + + expect(result.prefix).toBe(""); + expect(tableNames(env.DB)).toContain("_schema_migrations"); + expect(ledgerRows(env.DB, "").map((row) => row.name)).toEqual([ + "schema_v1", + ]); + }); + + it("adopts an existing nav_* schema that predates the ledger", async () => { + // Simulates a nav v1 database: all business tables present, no ledger yet. + const env = makeEnv({ TABLE_PREFIX: "nav_" }); + await runMigrations(env); + sqliteOf(env.DB).exec("DROP TABLE _nav_schema_migrations;"); + + const result = await runMigrations(env); + expect(result.prefix).toBe("nav_"); + expect(result.migrations).toEqual([ + { name: "schema_v1", status: "applied" }, + ]); + expect(ledgerRows(env.DB, "nav_").map((row) => row.name)).toEqual([ + "schema_v1", + ]); + expect(tableNames(env.DB)).toContain("_nav_schema_migrations"); + }); + + it("aborts instead of quietly switching to a different prefix", async () => { + const env = makeEnv({ TABLE_PREFIX: "nav_" }); + await runMigrations(env); + + // nav_ → no prefix + await expect(runMigrations(makeEnvFor(env, ""))).rejects.toBeInstanceOf( + TablePrefixConflictError, + ); + // nav_ → app_ + await expect(runMigrations(makeEnvFor(env, "app_"))).rejects.toBeInstanceOf( + TablePrefixConflictError, + ); + // still one schema, no second set of tables + const tables = tableNames(env.DB); + expect(tables).toContain("nav_users"); + expect(tables).not.toContain("users"); + expect(tables).not.toContain("app_users"); + expect(tables).not.toContain("_app_schema_migrations"); + }); + + it("aborts when the database already holds an unprefixed schema", async () => { + const env = makeEnv({ TABLE_PREFIX: "" }); + await runMigrations(env); + + await expect(runMigrations(makeEnvFor(env, "nav_"))).rejects.toBeInstanceOf( + TablePrefixConflictError, + ); + expect(tableNames(env.DB)).not.toContain("nav_users"); + }); + + it("does not mistake other projects' tables or ledgers for a nav schema", async () => { + const env = makeEnv({ TABLE_PREFIX: "nav_" }); + const db = sqliteOf(env.DB); + // Shared-D1 neighbours (eNotify / shortlink / Zeta) plus their ledgers. + db.exec( + "CREATE TABLE eNotify_settings (key TEXT, value TEXT);" + + "CREATE TABLE SL_links (id TEXT, slug TEXT);" + + "CREATE TABLE ZETA_users (id TEXT);" + + "CREATE TABLE _sl_schema_migrations (name TEXT PRIMARY KEY, applied_at INTEGER NOT NULL DEFAULT (unixepoch()));", + ); + + const result = await runMigrations(env); + expect(result.prefix).toBe("nav_"); + expect(result.migrations).toEqual([ + { name: "schema_v1", status: "applied" }, + ]); + }); + + it("stops at the first failing migration, without recording it or running later ones", async () => { + const env = makeEnv({ TABLE_PREFIX: "nav_" }); + const migrations = [ + { name: "schema_v1", sql: "CREATE TABLE t_one (id TEXT PRIMARY KEY);" }, + { + name: "schema_v2", + sql: + "CREATE TABLE t_two (id TEXT PRIMARY KEY);" + + "CREATE TABLE t_two (id TEXT PRIMARY KEY);", + }, + { name: "schema_v3", sql: "CREATE TABLE t_three (id TEXT PRIMARY KEY);" }, + ]; + + const first = await applyMigrationList(env.DB, "nav_", migrations); + expect(first.map((m) => [m.name, m.status])).toEqual([ + ["schema_v1", "applied"], + ["schema_v2", "error"], + ]); + expect(first[1]?.error).toContain("t_two"); + + // Failed migration not recorded, later migration never attempted. + expect(ledgerRows(env.DB, "nav_").map((row) => row.name)).toEqual([ + "schema_v1", + ]); + expect(tableNames(env.DB)).not.toContain("t_three"); + + // Re-running retries the failed migration rather than skipping it. + const retry = await applyMigrationList(env.DB, "nav_", migrations); + expect(retry.map((m) => [m.name, m.status])).toEqual([ + ["schema_v1", "skipped"], + ["schema_v2", "error"], + ]); + }); +}); + +/** Same database, different TABLE_PREFIX — simulates a config change. */ +function makeEnvFor(env: ReturnType, prefix: string) { + return { ...env, TABLE_PREFIX: prefix }; +} diff --git a/worker/test/table-prefix.test.ts b/worker/test/table-prefix.test.ts index f63fed1..6de3de6 100644 --- a/worker/test/table-prefix.test.ts +++ b/worker/test/table-prefix.test.ts @@ -4,7 +4,7 @@ import { getTablePrefix, isValidTablePrefix, } from "../src/types"; -import { runMigrations } from "../src/lib/migrate"; +import { runMigrations } from "../src/lib/migrations-runner"; import { makeEnv, type SqliteD1 } from "./helpers"; describe("table prefix three-state (SPEC v1.4)", () => {