From 740fb61fceb7b960a0740f3b673ee53cc52865bd Mon Sep 17 00:00:00 2001 From: mapxn <16299874+mapxn@users.noreply.github.com> Date: Mon, 26 Oct 2026 14:03:07 +0800 Subject: [PATCH] =?UTF-8?q?feat(worker):=20=E8=BF=81=E7=A7=BB=E8=B4=A6?= =?UTF-8?q?=E6=9C=AC=E5=8C=96=EF=BC=88schema=5Fmigrations=20=E8=B4=A6?= =?UTF-8?q?=E6=9C=AC=20+=20=E5=8E=86=E5=8F=B2=E5=A1=8C=E7=BC=A9=20schema?= =?UTF-8?q?=5Fv1=EF=BC=89(ONE-400)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增 worker/src/lib/migrations.ts:迁移清单单一真源,历史塌缩为一条 schema_v1(原 getSchema() DDL 逐字迁入),文件头写明追加规矩。 - 新增 worker/src/lib/migrations-runner.ts:migrationsTable() 是账本表名唯一 构造点;runLedgerMigrations() 逐条应用未记录的迁移,全部语句成功后才记账, 任一失败立即抛错(含迁移名与原始错误),不再吞错。 - setup.ts:getSchema() 删除;runMigrations() 更名 runLegacyMigrations()(逻辑 未改,仅过渡分支调用);runSetup() 按账本三分支重组(账本存在→runner + 一致性 检查;无账本有业务表→旧补丁→验形→打戳;都没有→新装 runner + 默认设置播种), SetupResult 成功变体新增 migrations 字段。前缀冲突守卫与 detectTablePrefixes 未动。 - 测试:新增 ledger.test.ts(新装/结构对照快照/存量过渡/验形失败/前缀变体/守卫/ 账本一致性)、ledger-failure.test.ts(失败可见性与续跑);既有 setup 相关用例按 新状态机调整,无删用例。SqliteD1 提取到 test/support 复用。 - docs/migration-ledger-cutover-runbook.md:生产切换 runbook(§8 逐步清单 + 每步 核对与回滚 + 两条路径关系);CLAUDE.md 同步账本制。 --- CLAUDE.md | 7 +- docs/migration-ledger-cutover-runbook.md | 147 ++++ worker/src/lib/migrations-runner.ts | 105 +++ worker/src/lib/migrations.ts | 146 ++++ worker/src/lib/setup.ts | 331 +++++--- worker/test/admin.test.ts | 25 +- .../test/fixtures/schema-before-ledger.json | 626 ++++++++++++++ worker/test/helpers.ts | 29 +- worker/test/ledger-failure.test.ts | 132 +++ worker/test/ledger.test.ts | 798 ++++++++++++++++++ worker/test/migrations.test.ts | 71 +- worker/test/prefix.test.ts | 19 +- worker/test/setup.test.ts | 8 +- worker/test/support/sqlite-d1.ts | 39 + 14 files changed, 2302 insertions(+), 181 deletions(-) create mode 100644 docs/migration-ledger-cutover-runbook.md create mode 100644 worker/src/lib/migrations-runner.ts create mode 100644 worker/src/lib/migrations.ts create mode 100644 worker/test/fixtures/schema-before-ledger.json create mode 100644 worker/test/ledger-failure.test.ts create mode 100644 worker/test/ledger.test.ts create mode 100644 worker/test/support/sqlite-d1.ts diff --git a/CLAUDE.md b/CLAUDE.md index 1a33142..f84cf76 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -52,11 +52,14 @@ The worker serves the frontend's static assets from `web/dist/` via the `ASSETS` - `dashboard.ts` — spending stats, expiry summary - `admin.ts` — user management, system settings; also manages items per user at `/api/admin/users/:uid/items` - `notify.ts` — manual notification test trigger -- `setup.ts` — one-time DB initialization via `SETUP_SECRET` (rate-limited, 3/10min per IP); also exposes `GET /api/setup/state` (public setup-page toggle) and `POST /api/admin/setup` (admin-only, no secret). Core setup/migration logic lives in `worker/src/lib/setup.ts`. +- `setup.ts` — one-time DB initialization via `SETUP_SECRET` (rate-limited, 3/10min per IP); also exposes `GET /api/setup/state` (public setup-page toggle) and `POST /api/admin/setup` (admin-only, no secret). Core setup/migration logic lives in `worker/src/lib/setup.ts`. `runSetup` is a three-branch state machine after the prefix guard: ledger present → apply unrecorded migrations; no ledger but business tables present → pre-ledger in-place transition (legacy patches → shape verification → stamp `schema_v1`); neither → fresh install through the ledger. **Database** (`worker/src/db/`): -- Cloudflare D1 (SQLite). Schema defined in `worker/src/db/schema.sql`. +- Cloudflare D1 (SQLite). `worker/src/db/schema.sql` is the readable full schema (used by tests); the runtime source of truth is the migration list below. +- **Migrations are ledger-based.** The ordered list lives in `worker/src/lib/migrations.ts` (`getMigrations(prefix)`, currently a single collapsed `schema_v1` = the whole schema); `worker/src/lib/migrations-runner.ts` applies the not-yet-recorded ones in order and records each name in the ledger, throwing on the first failure (a migration is recorded only after all of its statements succeeded). Append new migrations only at the END of the list as `schema_vN`; never rename, edit or reorder a merged migration; migrations must be additive (`CREATE TABLE/INDEX IF NOT EXISTS`, `ADD COLUMN`, `INSERT OR IGNORE` — no `DROP`/`RENAME`/data rewrites); migration SQL string literals must not contain `;` (the runner splits on `;` and runs the statements one by one). +- The ledger table name is built only by `migrationsTable()`: `_` + prefix core (trailing `_` stripped, case preserved) + `_schema_migrations`, i.e. `_enotify_schema_migrations` for the default prefix and `_schema_migrations` with no prefix. Ledger tables are not part of the eNotify table family and are ignored by `detectTablePrefixes()` (other projects' ledgers coexist in a shared D1). +- Transitioning a pre-ledger database, production cutover and rollback: `docs/migration-ledger-cutover-runbook.md`. - All table names use a `{prefix}` placeholder at definition time, resolved at runtime via `TABLE_PREFIX` env var and the `getTablePrefix()` helper in `types.ts` (the ONLY resolution point). Three states: unset/null → default `enotify` (`enotify_`); custom non-empty value → verbatim with trailing `_`; explicit `""` → no prefix. `runSetup` in `worker/src/lib/setup.ts` detects existing initialized schemas under other prefixes via `detectTablePrefixes()` and aborts with 409 `PREFIX_CONFLICT` instead of silently re-initializing; CI maps unset/empty vars to `enotify` and the reserved word `none` to `""`. - Query functions are organized by entity in `worker/src/db/queries/`. Key entities: `items`, `payments`, `users`, `notifications` (channel config), `settings`. diff --git a/docs/migration-ledger-cutover-runbook.md b/docs/migration-ledger-cutover-runbook.md new file mode 100644 index 0000000..5716454 --- /dev/null +++ b/docs/migration-ledger-cutover-runbook.md @@ -0,0 +1,147 @@ +# 生产切换 runbook:迁移账本(schema_v1)+ 全站档重导入 + +> 适用:本仓库引入迁移账本(`worker/src/lib/migrations.ts` / `migrations-runner.ts` / `setup.ts` 状态机)之后的**生产库切换**。 +> 执行者:仓库所有者本人。团队只提供本清单,不执行、不接触生产库。 +> 本文按父单 ONE-400 规格 §8 的顺序写成可逐步执行清单,每步都有核对方法与回滚方法。 + +## 两条路径的关系(先读这一段) + +- **合并即自动部署**(`main` 推送触发 deploy)。部署完成、用户执行下文切换之前,生产库处于「旧代码已下线、新代码待过渡」状态:新代码对存量库走的是**就地过渡分支**(旧补丁集最后跑一遍 → 验形 → 打戳 `schema_v1`),所以即使有人先点了「检查并升级数据库」,也只会安全打戳完成过渡,不会损坏数据。 +- 本文的 §8 完整关口(导出 → 改名 → 新装 → 恢复导入 → 验收 → 重签 Key)是当初定下的**从严路径**:它给出的是一份「干净的新 schema_v1 结构 + 官方恢复通道」的库,代价是需要重导入与重签 API Key。 +- **二选一由用户在关口决定**: + - 选「就地过渡」:部署后点一次「检查并升级数据库」,核对账本出现 `schema_v1` 即可收工,不动数据、不重签 Key; + - 选「§8 完整切换」:按下面 0–7 步执行。 + + 两条路径最终都是「7 张业务表 + `_enotify_schema_migrations` 账本含一条 `schema_v1`」,结构一致;区别只在于数据是怎么进新表的(就地 vs 导出再导入)。 + +--- + +## 0. 前置检查(不改动任何东西) + +1. 确认已部署的版本包含本次改动:管理面板「检查并升级数据库」的返回里应带 `migrations` 字段(就地过渡会是 `[{"name":"schema_v1","status":"stamped"}]`,新装是 `applied`,之后是 `skipped`)。 +2. 记录切换前的基线数字(第 5 步要逐项对照): + + ```bash + npx wrangler d1 execute --remote --command \ + "SELECT (SELECT COUNT(*) FROM enotify_users) AS users, (SELECT COUNT(*) FROM enotify_items) AS items, (SELECT COUNT(*) FROM enotify_notification_configs) AS configs, (SELECT COUNT(*) FROM enotify_payment_history) AS payments, (SELECT COUNT(*) FROM enotify_notification_history) AS history" + ``` + + **核对**:命令有返回、数字非空。**回滚**:无(只读)。 + +## 1. 全站档导出(切换前最后一份现行格式备份) + +管理面板 → 备份页 → 全站档导出 → 下载 JSON 并妥善保存。 + +**核对**:文件能打开、`format`/`version` 字段存在、`users`/`items`/`notification_configs` 等条目数与第 0 步的数字对得上。 +**回滚**:无(只读,不改库)。这份 JSON 是后续所有步骤的兜底。 + +## 2. 把 7 张业务表逐张 RENAME 到备份命名(不直删) + +> ⚠️ **命名方式与规格 §2 的字面写法不同,原因写在这里**:`runSetup` 的前缀冲突守卫用 `detectTablePrefixes()` 识别「另一套 eNotify 表族」——只要库里存在 ≥4 张 `<前缀>_users` / `<前缀>_items` 这类命名的表且含 `users`,就会被判为另一个前缀并返回 409 `PREFIX_CONFLICT`。若把 7 张表改名成 `bak_users`、`bak_items` 这类**前缀形式**,第 3 步的新装会被守卫拦下。因此备份命名统一采用**后缀形式**:`enotify__bak_`,语义仍是「改名而不是删除」、随时可改回,但不会命中守卫的识别规则。 + +1. 先看账本表是否存在(部署后有人点过「检查并升级数据库」就会有): + + ```bash + npx wrangler d1 execute --remote --command \ + "SELECT name FROM sqlite_master WHERE type='table' AND name LIKE '%_schema_migrations' ORDER BY name" + ``` + + 如果出现 `_enotify_schema_migrations`,它描述的是马上要被改名的那批旧表,必须同时挪开,否则第 3 步会走「账本已存在」分支并因为业务表缺失而报 `LEDGER_INCONSISTENT`(这是刻意的安全闸,不是 bug): + + ```bash + npx wrangler d1 execute --remote --command \ + "ALTER TABLE _enotify_schema_migrations RENAME TO _enotify_schema_migrations_bak_" + ``` + +2. 逐张改名(7 条,`` 由执行时确定并记入交付评论): + + ```bash + npx wrangler d1 execute --remote --command "ALTER TABLE enotify_users RENAME TO enotify_users_bak_" + npx wrangler d1 execute --remote --command "ALTER TABLE enotify_user_2fa RENAME TO enotify_user_2fa_bak_" + npx wrangler d1 execute --remote --command "ALTER TABLE enotify_items RENAME TO enotify_items_bak_" + npx wrangler d1 execute --remote --command "ALTER TABLE enotify_payment_history RENAME TO enotify_payment_history_bak_" + npx wrangler d1 execute --remote --command "ALTER TABLE enotify_notification_configs RENAME TO enotify_notification_configs_bak_" + npx wrangler d1 execute --remote --command "ALTER TABLE enotify_system_settings RENAME TO enotify_system_settings_bak_" + npx wrangler d1 execute --remote --command "ALTER TABLE enotify_notification_history RENAME TO enotify_notification_history_bak_" + ``` + + 注意:SQLite 的 `RENAME TO` 会把其他表里指向它的外键定义一并改写到新名字,所以备份表族内部仍然自洽(改回时同样自动还原)。 + +**核对**: + +```bash +npx wrangler d1 execute --remote --command \ + "SELECT name FROM sqlite_master WHERE type='table' ORDER BY name" +``` + +应看到 7 张 `enotify_*_bak_`,且**没有**任何以 `users`/`user_2fa`/`items`/`payment_history`/`notification_configs`/`system_settings`/`notification_history` 结尾或等值的表名(这是第 3 步能顺利新装的关键)。 + +**回滚**:把这 7 条改回去(`ALTER TABLE enotify_users_bak_ RENAME TO enotify_users`,其余同理),并把第 1 小步挪开的账本表改回原名;然后重跑一次 setup 让它按当前真实结构决定打戳或跳过。 + +## 3. 触发 setup,走新装路径生成 schema_v1 全量结构 + 账本 + +管理面板「检查并升级数据库」,或: + +```bash +curl -X POST https://<你的域名>/api/setup -H "X-Setup-Secret: " +``` + +**核对**:返回 `{"success":true,"effectivePrefix":"enotify_","migrations":[{"name":"schema_v1","status":"applied"}]}`(此路径**不应**出现 `alreadyInitialized`); + +```bash +npx wrangler d1 execute --remote --command \ + "SELECT name FROM _enotify_schema_migrations" +``` + +应只有一行 `schema_v1`;`SELECT name FROM sqlite_master WHERE type='table' AND name LIKE 'enotify_%'` 应是 7 张业务表。 + +**回滚**:把这一步新生成的 7 张空表改名或删除(`DROP TABLE enotify_users` …),把 `_enotify_schema_migrations` 改名为 `_enotify_schema_migrations_discard_`,再把第 2 步的备份表族改回原名。库即回到切换前状态(数据仍在备份表里)。 + +## 4. 用全站档「恢复模式」导入第 1 步的 JSON + +管理面板 → 备份页 → 导入 → 选择**恢复模式**(只进空实例,此刻正是空实例)。 + +**核对**:导入返回的计数与第 0 步基线一致;`SELECT COUNT(*) FROM enotify_users` 等数字与基线逐项相同。 + +**回滚**:重复第 3 步的「回滚」操作即可(清掉新表后把备份表族改回原名);导入进来的数据随之丢弃。 + +## 5. 验收(全部通过才继续) + +1. 用户数/事项数/渠道配置数与第 0 步基线逐项相同(含 `payment_history`、`notification_history`)。 +2. 用管理员账号登录成功;开启过 TOTP / Passkey 的账号可继续用原 secret/凭据登录(secret 原样在导出内)。 +3. 通知设置页「默认渠道」可保存;用一条测试直推验证只走默认渠道。 +4. 账本核对: + + ```bash + npx wrangler d1 execute --remote --command \ + "SELECT name, applied_at FROM _enotify_schema_migrations" + ``` + + 应有且仅有 `schema_v1`。 +5. 再次点「检查并升级数据库」应返回 `migrations:[{"name":"schema_v1","status":"skipped"}]`(幂等、无副作用)。 + +**任一项不过**:立即执行第 3 步的回滚,把备份表族改回原名,回到切换前状态,并把失败项记入交付评论。 + +## 6. 重签 API Key + +导出不含 API Key(KV 里只存哈希),切换后按规格统一重签:逐个使用者新建 Key(新建后经安全卡片交付),再在「API Key」页面吊销旧记录。包括 Muse 的 `custom.enotify` 连接器所用的那把——重签后 Muse 负责重连并实测。 + +**核对**:新 Key 调用 `GET /api/items` 返回 200;旧 Key 调用返回 401。 +**回滚**:KV 未参与本次 D1 切换,旧 Key 记录仍在 KV 中,未吊销前仍可用——因此这一步的回滚就是「暂缓吊销、保留旧 Key」;重签本身不需要回滚。 + +## 7. 备份表族的去留 + +`enotify_*_bak_` 与 `_enotify_schema_migrations_bak_` 在验收通过后**保留不删**,去留由用户另行决定(删掉即失去手动回退能力;如需删除,先用 `SELECT COUNT(*)` 确认新表数据完整)。 + +--- + +## 附:就地过渡路径(与上面的二选一) + +部署后不执行第 1–7 步,只点一次「检查并升级数据库」: + +- 返回 `migrations:[{"name":"schema_v1","status":"stamped"}]`; +- 旧补丁集最后跑一遍(补齐历史增量、清理退役渠道 ID),验形通过后写入账本一条 `schema_v1`; +- 数据原地不动,无需重签 API Key; +- 之后每次升级再点一次,返回 `skipped` 或新迁移的 `applied`。 + +若验形失败,setup 返回 `SCHEMA_VERIFY_FAILED` 并列出缺失的表/列,**账本不会被打戳**;按错误提示修复后重试即可,旧补丁产生的增量都是幂等的、无害的。 diff --git a/worker/src/lib/migrations-runner.ts b/worker/src/lib/migrations-runner.ts new file mode 100644 index 0000000..cf47834 --- /dev/null +++ b/worker/src/lib/migrations-runner.ts @@ -0,0 +1,105 @@ +import { getMigrations } from "./migrations"; + +/** + * Ledger migration runner. + * + * The ledger table records which migrations have already been applied, so a + * migration runs at most once per database and a failure is visible instead of + * being swallowed. Table names are always resolved through `migrationsTable()` + * — no other module may build the ledger name by hand. + */ + +export type LedgerMigrationStatus = "applied" | "skipped"; + +export interface LedgerMigrationResult { + name: string; + status: LedgerMigrationStatus; +} + +/** + * Name of the migration ledger for a table prefix: + * `_` + prefix core (trailing `_` stripped, case preserved) + `_schema_migrations`. + * No prefix (or a bare `_`) yields the shared `_schema_migrations` name. + */ +export function migrationsTable(prefix: string): string { + const core = prefix.replace(/_$/, ""); + if (core === "") return "_schema_migrations"; + return `_${core}_schema_migrations`; +} + +/** Create the ledger table if it does not exist yet; returns its name. */ +export async function ensureLedgerTable( + db: D1Database, + prefix: string, +): Promise { + const ledger = migrationsTable(prefix); + await db + .prepare( + `CREATE TABLE IF NOT EXISTS ${ledger} (name TEXT PRIMARY KEY, applied_at INTEGER NOT NULL DEFAULT (unixepoch()))`, + ) + .run(); + return ledger; +} + +/** Record `name` as applied in the ledger. */ +export async function recordMigration( + db: D1Database, + prefix: string, + name: string, +): Promise { + const ledger = migrationsTable(prefix); + await db.prepare(`INSERT INTO ${ledger} (name) VALUES (?)`).bind(name).run(); +} + +/** Split a migration into single statements, matching the pre-ledger install path. */ +export function splitStatements(sql: string): string[] { + return sql + .split(";") + .map((s) => s.trim()) + .filter((s) => s.length > 0); +} + +function migrationError(name: string, err: unknown): Error { + const reason = err instanceof Error ? err.message : String(err); + return new Error(`Migration "${name}" failed: ${reason}`, { cause: err }); +} + +/** + * Apply every not-yet-recorded migration in `getMigrations(prefix)` order. + * + * A migration's statements are all executed first and only then recorded, so a + * partially applied migration is retried on the next run (every statement is + * guarded by `IF NOT EXISTS` / probes). Any failure throws immediately, naming + * the migration and the original error; the failing migration is not recorded + * and later migrations are not executed. + */ +export async function runLedgerMigrations( + db: D1Database, + prefix: string, +): Promise { + const ledger = await ensureLedgerTable(db, prefix); + + const recorded = await db + .prepare(`SELECT name FROM ${ledger}`) + .all<{ name: string }>(); + const applied = new Set(recorded.results.map((r) => r.name)); + + const results: LedgerMigrationResult[] = []; + for (const migration of getMigrations(prefix)) { + if (applied.has(migration.name)) { + results.push({ name: migration.name, status: "skipped" }); + continue; + } + try { + for (const statement of splitStatements(migration.sql)) { + await db.prepare(statement).run(); + } + await recordMigration(db, prefix, migration.name); + } catch (err) { + throw migrationError(migration.name, err); + } + results.push({ name: migration.name, status: "applied" }); + } + + return results; +} diff --git a/worker/src/lib/migrations.ts b/worker/src/lib/migrations.ts new file mode 100644 index 0000000..4eca597 --- /dev/null +++ b/worker/src/lib/migrations.ts @@ -0,0 +1,146 @@ +/** + * Single source of truth for the database schema: an ordered migration list. + * + * Rules for adding migrations (see the ledger migration spec §2.2): + * + * - Append new migrations ONLY at the END of the list, named `schema_vN`. + * - Never rename, re-edit or reorder a migration that has already been merged. + * A database that recorded it will not run it again, so editing it only makes + * old and new databases diverge. + * - Migrations must be additive: `CREATE TABLE/INDEX IF NOT EXISTS`, + * `ADD COLUMN`, `INSERT OR IGNORE`. No `DROP` / `RENAME` / data rewrites — + * destructive changes need their own spec and their own migration plan. + * - Migration SQL string literals must not contain `;`: the runner splits each + * migration on `;` and executes the statements one by one. + */ +export interface Migration { + name: string; + sql: string; +} + +/** + * schema_v1 — the whole schema at the time the migration ledger was introduced. + * Moved verbatim out of the former `getSchema()`; no column definition was + * changed. `{prefix}` is replaced with the effective table prefix when the + * migration list is produced. + */ +const SCHEMA_V1 = `CREATE TABLE IF NOT EXISTS {prefix}users ( + id TEXT PRIMARY KEY, + email TEXT UNIQUE NOT NULL, + password_hash TEXT NOT NULL, + role TEXT NOT NULL DEFAULT 'user', + is_active INTEGER NOT NULL DEFAULT 1, + email_verified INTEGER NOT NULL DEFAULT 0, + base_currency TEXT NOT NULL DEFAULT 'CNY', + timezone TEXT NOT NULL DEFAULT 'UTC', + language TEXT NOT NULL DEFAULT 'zh', + theme TEXT NOT NULL DEFAULT 'system', + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL +); + +CREATE TABLE IF NOT EXISTS {prefix}user_2fa ( + user_id TEXT PRIMARY KEY REFERENCES {prefix}users(id) ON DELETE CASCADE, + totp_secret TEXT, + totp_enabled INTEGER NOT NULL DEFAULT 0, + passkey_credentials TEXT, + passkey_enabled INTEGER NOT NULL DEFAULT 0, + email_otp_enabled INTEGER NOT NULL DEFAULT 0, + preferred_method TEXT, + updated_at TEXT NOT NULL +); + +CREATE TABLE IF NOT EXISTS {prefix}items ( + id TEXT PRIMARY KEY, + user_id TEXT NOT NULL REFERENCES {prefix}users(id) ON DELETE CASCADE, + name TEXT NOT NULL, + item_mode TEXT NOT NULL DEFAULT 'cycle', + category TEXT NOT NULL DEFAULT '', + start_date TEXT, + expiry_date TEXT NOT NULL, + period_value INTEGER NOT NULL DEFAULT 1, + period_unit TEXT NOT NULL DEFAULT 'month', + reminder_unit TEXT NOT NULL DEFAULT 'day', + reminder_value INTEGER NOT NULL DEFAULT 7, + notes TEXT NOT NULL DEFAULT '', + amount REAL, + currency TEXT NOT NULL DEFAULT 'CNY', + last_payment_date TEXT, + is_active INTEGER NOT NULL DEFAULT 1, + auto_renew INTEGER NOT NULL DEFAULT 1, + calendar_mode TEXT NOT NULL DEFAULT 'solar', + lunar_expiry_date TEXT, + channels TEXT NOT NULL DEFAULT '[]', + notification_hours TEXT NOT NULL DEFAULT '[]', + item_kind TEXT NOT NULL DEFAULT 'regular', + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL +); + +CREATE INDEX IF NOT EXISTS idx_{prefix}items_user_id + ON {prefix}items(user_id); + +CREATE TABLE IF NOT EXISTS {prefix}payment_history ( + id TEXT PRIMARY KEY, + item_id TEXT NOT NULL REFERENCES {prefix}items(id) ON DELETE CASCADE, + user_id TEXT NOT NULL, + date TEXT NOT NULL, + amount REAL NOT NULL DEFAULT 0, + currency TEXT NOT NULL DEFAULT 'CNY', + type TEXT NOT NULL DEFAULT 'manual', + note TEXT NOT NULL DEFAULT '', + period_start TEXT, + period_end TEXT, + created_at TEXT NOT NULL +); + +CREATE INDEX IF NOT EXISTS idx_{prefix}payment_history_item_id + ON {prefix}payment_history(item_id); +CREATE INDEX IF NOT EXISTS idx_{prefix}payment_history_user_id + ON {prefix}payment_history(user_id); + +CREATE TABLE IF NOT EXISTS {prefix}notification_configs ( + user_id TEXT PRIMARY KEY REFERENCES {prefix}users(id) ON DELETE CASCADE, + enabled_channels TEXT NOT NULL DEFAULT '[]', + default_channel TEXT NOT NULL DEFAULT '', + telegram_config TEXT NOT NULL DEFAULT '{}', + webhook_config TEXT NOT NULL DEFAULT '{}', + wechatbot_config TEXT NOT NULL DEFAULT '{}', + email_config TEXT NOT NULL DEFAULT '{}', + bark_config TEXT NOT NULL DEFAULT '{}', + slack_config TEXT NOT NULL DEFAULT '{}', + feishu_config TEXT NOT NULL DEFAULT '{}', + discord_config TEXT NOT NULL DEFAULT '{}', + notification_hours TEXT NOT NULL DEFAULT '[]', + updated_at TEXT NOT NULL +); + +CREATE TABLE IF NOT EXISTS {prefix}system_settings ( + key TEXT PRIMARY KEY, + value TEXT NOT NULL, + updated_at TEXT NOT NULL +); + +CREATE TABLE IF NOT EXISTS {prefix}notification_history ( + id TEXT PRIMARY KEY, + user_id TEXT NOT NULL, + item_id TEXT, + channel TEXT NOT NULL, + title TEXT NOT NULL, + body TEXT, + success INTEGER NOT NULL DEFAULT 1, + error TEXT, + created_at TEXT NOT NULL +); + +CREATE INDEX IF NOT EXISTS idx_{prefix}notification_history_user_id + ON {prefix}notification_history(user_id, created_at)`; + +export function getMigrations(prefix: string): Migration[] { + return [ + { + name: "schema_v1", + sql: SCHEMA_V1.replace(/\{prefix\}/g, prefix), + }, + ]; +} diff --git a/worker/src/lib/setup.ts b/worker/src/lib/setup.ts index bcc264d..b44c3ed 100644 --- a/worker/src/lib/setup.ts +++ b/worker/src/lib/setup.ts @@ -4,9 +4,30 @@ import { getTablePrefix, } from "../types"; import type { Env } from "../types"; +import { + ensureLedgerTable, + migrationsTable, + recordMigration, + runLedgerMigrations, +} from "./migrations-runner"; + +/** + * A migration as reported back to the admin UI. `applied`/`skipped` come from + * the ledger runner; `stamped` only happens when a pre-ledger database is + * verified and its history is collapsed into `schema_v1` for the first time. + */ +export type SetupMigration = { + name: string; + status: "applied" | "skipped" | "stamped"; +}; export type SetupResult = - | { success: true; alreadyInitialized?: true; effectivePrefix: string } + | { + success: true; + alreadyInitialized?: true; + effectivePrefix: string; + migrations?: SetupMigration[]; + } | { success: false; code: "PREFIX_CONFLICT"; @@ -14,6 +35,21 @@ export type SetupResult = message: string; resolvedPrefix: string; detectedPrefixes: string[]; + } + | { + success: false; + code: "LEDGER_INCONSISTENT"; + error: string; + message: string; + resolvedPrefix: string; + } + | { + success: false; + code: "SCHEMA_VERIFY_FAILED"; + error: string; + message: string; + resolvedPrefix: string; + missing: string[]; }; // Unprefixed names of the tables that make up an initialized eNotify schema. @@ -74,7 +110,33 @@ const DEFAULT_SETTINGS: Record = { // enabled_channels is stripped so it cannot fail every push. const RETIRED_CHANNELS = ["serverchan", "pushplus", "gotify", "notifyx"]; -async function runMigrations(db: D1Database, prefix: string): Promise { +// The single collapsed migration name, see `worker/src/lib/migrations.ts`. +const SCHEMA_V1_MIGRATION = "schema_v1"; + +// Incremental columns the legacy patch set was supposed to have produced. Used +// to verify a pre-ledger database before stamping it (see runSetup). +const LEGACY_REQUIRED_COLUMNS: Record = { + notification_history: ["body"], + notification_configs: [ + "slack_config", + "feishu_config", + "discord_config", + "default_channel", + ], + items: ["calendar_mode", "lunar_expiry_date"], +}; + +/** + * The pre-ledger patch set, kept unchanged and now run only once, as the last + * step before a pre-ledger database is verified and stamped. It is a + * best-effort catch-up: it swallows its own errors (one block at a time) and + * the shape verification afterwards is what decides whether the database may + * be stamped. The ledger path and the fresh-install path never call it. + */ +async function runLegacyMigrations( + db: D1Database, + prefix: string, +): Promise { // Migration: add body column to notification_history try { const histCols = await db @@ -225,6 +287,23 @@ async function runMigrations(db: D1Database, prefix: string): Promise { } } +/** + * Initialize or upgrade the database under the resolved table prefix. + * + * The prefix-conflict guard runs first and never touches a database that + * belongs to another prefix. After it, the state of the resolved prefix + * decides what happens: + * + * 1. the migration ledger exists → apply whatever it does not record yet (and + * refuse a ledger that describes tables which are gone); + * 2. no ledger but business tables → pre-ledger database: run the legacy patch + * set one last time, verify the resulting shape, then stamp `schema_v1`; + * 3. neither → fresh install through the ledger, then seed the default + * settings. + * + * A failing migration propagates as an error (setup reports a failure instead + * of pretending it succeeded); the recorded migrations make it resumable. + */ export async function runSetup(env: Env): Promise { const prefix = getTablePrefix(env); const db = env.DB; @@ -268,29 +347,129 @@ export async function runSetup(env: Env): Promise { }; } - // Check if already initialized under the resolved prefix - const existing = await db - .prepare(`SELECT name FROM sqlite_master WHERE type='table' AND name=?`) - .bind(`${prefix}users`) - .first(); + // State machine, resolved prefix, after the guard above: + // 1. ledger exists → run whatever is not recorded yet + // 2. no ledger, business tables → in-place transition: legacy patches → + // shape verification → stamp + // 3. no ledger, no tables → fresh install through the ledger + const ledger = migrationsTable(prefix); + const ledgerExists = await tableExists(db, ledger); + const hasBusinessTables = await tableExists(db, `${prefix}users`); + + if (ledgerExists) { + // A ledger that records migrations while the tables it describes are gone + // is inconsistent: never silently re-run the runner over that database. + const recorded = await db + .prepare(`SELECT name FROM ${ledger}`) + .all<{ name: string }>(); + if (recorded.results.length > 0 && !hasBusinessTables) { + const error = + `Migration ledger "${ledger}" records applied migrations, but the business ` + + `tables ("${prefix}users") are missing. If the tables were deleted on ` + + `purpose, drop the ledger table as well and run setup again; otherwise ` + + `restore the tables.`; + return { + success: false, + code: "LEDGER_INCONSISTENT", + error, + message: error, + resolvedPrefix: prefix, + }; + } + + // Recorded migrations are skipped; anything unrecorded (including a ledger + // that is still empty after an interrupted run) is applied now. + const migrations = await runLedgerMigrations(db, prefix); + return { + success: true, + alreadyInitialized: true, + effectivePrefix: prefix, + migrations, + }; + } + + if (hasBusinessTables) { + // Pre-ledger database: it may sit at any historical migration state, so it + // must not be stamped blindly. Catch it up, verify the shape, then stamp. + await runLegacyMigrations(db, prefix); + + const missing = await verifyLegacyShape(db, prefix); + if (missing.length > 0) { + const error = + `Existing database is missing schema the legacy patch set should have ` + + `provided: ${missing.join(", ")}. The migration ledger was not stamped; ` + + `fix the database and run setup again.`; + return { + success: false, + code: "SCHEMA_VERIFY_FAILED", + error, + message: error, + resolvedPrefix: prefix, + missing, + }; + } - if (existing) { - await runMigrations(db, prefix); - return { success: true, alreadyInitialized: true, effectivePrefix: prefix }; + await ensureLedgerTable(db, prefix); + await recordMigration(db, prefix, SCHEMA_V1_MIGRATION); + return { + success: true, + alreadyInitialized: true, + effectivePrefix: prefix, + migrations: [{ name: SCHEMA_V1_MIGRATION, status: "stamped" }], + }; } - const schemaSQL = getSchema(); - const resolvedSQL = schemaSQL.replace(/\{prefix\}/g, prefix); + const migrations = await runLedgerMigrations(db, prefix); + await seedDefaultSettings(db, prefix); - const statements = resolvedSQL - .split(";") - .map((s) => s.trim()) - .filter((s) => s.length > 0); + return { success: true, effectivePrefix: prefix, migrations }; +} - for (const stmt of statements) { - await db.prepare(stmt).run(); +async function tableExists(db: D1Database, name: string): Promise { + const row = await db + .prepare(`SELECT name FROM sqlite_master WHERE type='table' AND name=?`) + .bind(name) + .first(); + return row !== null; +} + +/** + * Verify that a pre-ledger database really carries everything the legacy patch + * set promised, before its history is collapsed to schema_v1. Returns the list + * of missing tables/columns (empty when the shape is complete). + */ +async function verifyLegacyShape( + db: D1Database, + prefix: string, +): Promise { + const missing: string[] = []; + + for (const table of EONOTIFY_TABLES) { + const full = `${prefix}${table}`; + if (!(await tableExists(db, full))) { + missing.push(`table ${full}`); + continue; + } + + const required = LEGACY_REQUIRED_COLUMNS[table] ?? []; + if (required.length === 0) continue; + + const columns = await db + .prepare(`PRAGMA table_info(${full})`) + .all<{ name: string }>(); + const present = new Set(columns.results.map((c) => c.name)); + for (const column of required) { + if (!present.has(column)) missing.push(`column ${full}.${column}`); + } } + return missing; +} + +async function seedDefaultSettings( + db: D1Database, + prefix: string, +): Promise { const now = new Date().toISOString(); for (const [key, value] of Object.entries(DEFAULT_SETTINGS)) { await db @@ -300,120 +479,4 @@ export async function runSetup(env: Env): Promise { .bind(key, value, now) .run(); } - - return { success: true, effectivePrefix: prefix }; -} - -function getSchema(): string { - return `CREATE TABLE IF NOT EXISTS {prefix}users ( - id TEXT PRIMARY KEY, - email TEXT UNIQUE NOT NULL, - password_hash TEXT NOT NULL, - role TEXT NOT NULL DEFAULT 'user', - is_active INTEGER NOT NULL DEFAULT 1, - email_verified INTEGER NOT NULL DEFAULT 0, - base_currency TEXT NOT NULL DEFAULT 'CNY', - timezone TEXT NOT NULL DEFAULT 'UTC', - language TEXT NOT NULL DEFAULT 'zh', - theme TEXT NOT NULL DEFAULT 'system', - created_at TEXT NOT NULL, - updated_at TEXT NOT NULL -); - -CREATE TABLE IF NOT EXISTS {prefix}user_2fa ( - user_id TEXT PRIMARY KEY REFERENCES {prefix}users(id) ON DELETE CASCADE, - totp_secret TEXT, - totp_enabled INTEGER NOT NULL DEFAULT 0, - passkey_credentials TEXT, - passkey_enabled INTEGER NOT NULL DEFAULT 0, - email_otp_enabled INTEGER NOT NULL DEFAULT 0, - preferred_method TEXT, - updated_at TEXT NOT NULL -); - -CREATE TABLE IF NOT EXISTS {prefix}items ( - id TEXT PRIMARY KEY, - user_id TEXT NOT NULL REFERENCES {prefix}users(id) ON DELETE CASCADE, - name TEXT NOT NULL, - item_mode TEXT NOT NULL DEFAULT 'cycle', - category TEXT NOT NULL DEFAULT '', - start_date TEXT, - expiry_date TEXT NOT NULL, - period_value INTEGER NOT NULL DEFAULT 1, - period_unit TEXT NOT NULL DEFAULT 'month', - reminder_unit TEXT NOT NULL DEFAULT 'day', - reminder_value INTEGER NOT NULL DEFAULT 7, - notes TEXT NOT NULL DEFAULT '', - amount REAL, - currency TEXT NOT NULL DEFAULT 'CNY', - last_payment_date TEXT, - is_active INTEGER NOT NULL DEFAULT 1, - auto_renew INTEGER NOT NULL DEFAULT 1, - calendar_mode TEXT NOT NULL DEFAULT 'solar', - lunar_expiry_date TEXT, - channels TEXT NOT NULL DEFAULT '[]', - notification_hours TEXT NOT NULL DEFAULT '[]', - item_kind TEXT NOT NULL DEFAULT 'regular', - created_at TEXT NOT NULL, - updated_at TEXT NOT NULL -); - -CREATE INDEX IF NOT EXISTS idx_{prefix}items_user_id - ON {prefix}items(user_id); - -CREATE TABLE IF NOT EXISTS {prefix}payment_history ( - id TEXT PRIMARY KEY, - item_id TEXT NOT NULL REFERENCES {prefix}items(id) ON DELETE CASCADE, - user_id TEXT NOT NULL, - date TEXT NOT NULL, - amount REAL NOT NULL DEFAULT 0, - currency TEXT NOT NULL DEFAULT 'CNY', - type TEXT NOT NULL DEFAULT 'manual', - note TEXT NOT NULL DEFAULT '', - period_start TEXT, - period_end TEXT, - created_at TEXT NOT NULL -); - -CREATE INDEX IF NOT EXISTS idx_{prefix}payment_history_item_id - ON {prefix}payment_history(item_id); -CREATE INDEX IF NOT EXISTS idx_{prefix}payment_history_user_id - ON {prefix}payment_history(user_id); - -CREATE TABLE IF NOT EXISTS {prefix}notification_configs ( - user_id TEXT PRIMARY KEY REFERENCES {prefix}users(id) ON DELETE CASCADE, - enabled_channels TEXT NOT NULL DEFAULT '[]', - default_channel TEXT NOT NULL DEFAULT '', - telegram_config TEXT NOT NULL DEFAULT '{}', - webhook_config TEXT NOT NULL DEFAULT '{}', - wechatbot_config TEXT NOT NULL DEFAULT '{}', - email_config TEXT NOT NULL DEFAULT '{}', - bark_config TEXT NOT NULL DEFAULT '{}', - slack_config TEXT NOT NULL DEFAULT '{}', - feishu_config TEXT NOT NULL DEFAULT '{}', - discord_config TEXT NOT NULL DEFAULT '{}', - notification_hours TEXT NOT NULL DEFAULT '[]', - updated_at TEXT NOT NULL -); - -CREATE TABLE IF NOT EXISTS {prefix}system_settings ( - key TEXT PRIMARY KEY, - value TEXT NOT NULL, - updated_at TEXT NOT NULL -); - -CREATE TABLE IF NOT EXISTS {prefix}notification_history ( - id TEXT PRIMARY KEY, - user_id TEXT NOT NULL, - item_id TEXT, - channel TEXT NOT NULL, - title TEXT NOT NULL, - body TEXT, - success INTEGER NOT NULL DEFAULT 1, - error TEXT, - created_at TEXT NOT NULL -); - -CREATE INDEX IF NOT EXISTS idx_{prefix}notification_history_user_id - ON {prefix}notification_history(user_id, created_at)`; } diff --git a/worker/test/admin.test.ts b/worker/test/admin.test.ts index a852ac8..05bd9c9 100644 --- a/worker/test/admin.test.ts +++ b/worker/test/admin.test.ts @@ -24,7 +24,11 @@ describe("POST /api/admin/setup", () => { headers: cookieHeader(token), }); expect(res.status).toBe(200); - expect(res.body).toEqual({ success: true, effectivePrefix: "" }); + expect(res.body).toEqual({ + success: true, + effectivePrefix: "", + migrations: [{ name: "schema_v1", status: "applied" }], + }); const db = env.DB as MockD1; expect(db.tables.has("users")).toBe(true); @@ -35,8 +39,18 @@ describe("POST /api/admin/setup", () => { DB: new MockD1({ tables: { users: ["id", "email"], - notification_history: ["id", "body"], + user_2fa: ["user_id"], items: ["id", "calendar_mode", "lunar_expiry_date"], + payment_history: ["id"], + notification_configs: [ + "user_id", + "slack_config", + "feishu_config", + "discord_config", + "default_channel", + ], + system_settings: ["key", "value", "updated_at"], + notification_history: ["id", "body"], }, }), }); @@ -56,6 +70,7 @@ describe("POST /api/admin/setup", () => { success: true, alreadyInitialized: true, effectivePrefix: "", + migrations: [{ name: "schema_v1", status: "stamped" }], }); }); @@ -94,6 +109,10 @@ describe("POST /api/admin/setup", () => { headers: cookieHeader(token), }); expect(res.status).toBe(200); - expect(res.body).toEqual({ success: true, effectivePrefix: "" }); + expect(res.body).toEqual({ + success: true, + effectivePrefix: "", + migrations: [{ name: "schema_v1", status: "applied" }], + }); }); }); diff --git a/worker/test/fixtures/schema-before-ledger.json b/worker/test/fixtures/schema-before-ledger.json new file mode 100644 index 0000000..77a310c --- /dev/null +++ b/worker/test/fixtures/schema-before-ledger.json @@ -0,0 +1,626 @@ +{ + "prefix": "", + "tables": [ + { + "name": "users", + "table_info": [ + { + "name": "id", + "type": "TEXT", + "notnull": 0, + "dflt_value": null, + "pk": 1 + }, + { + "name": "email", + "type": "TEXT", + "notnull": 1, + "dflt_value": null, + "pk": 0 + }, + { + "name": "password_hash", + "type": "TEXT", + "notnull": 1, + "dflt_value": null, + "pk": 0 + }, + { + "name": "role", + "type": "TEXT", + "notnull": 1, + "dflt_value": "'user'", + "pk": 0 + }, + { + "name": "is_active", + "type": "INTEGER", + "notnull": 1, + "dflt_value": "1", + "pk": 0 + }, + { + "name": "email_verified", + "type": "INTEGER", + "notnull": 1, + "dflt_value": "0", + "pk": 0 + }, + { + "name": "base_currency", + "type": "TEXT", + "notnull": 1, + "dflt_value": "'CNY'", + "pk": 0 + }, + { + "name": "timezone", + "type": "TEXT", + "notnull": 1, + "dflt_value": "'UTC'", + "pk": 0 + }, + { + "name": "language", + "type": "TEXT", + "notnull": 1, + "dflt_value": "'zh'", + "pk": 0 + }, + { + "name": "theme", + "type": "TEXT", + "notnull": 1, + "dflt_value": "'system'", + "pk": 0 + }, + { + "name": "created_at", + "type": "TEXT", + "notnull": 1, + "dflt_value": null, + "pk": 0 + }, + { + "name": "updated_at", + "type": "TEXT", + "notnull": 1, + "dflt_value": null, + "pk": 0 + } + ], + "indexes": [] + }, + { + "name": "user_2fa", + "table_info": [ + { + "name": "user_id", + "type": "TEXT", + "notnull": 0, + "dflt_value": null, + "pk": 1 + }, + { + "name": "totp_secret", + "type": "TEXT", + "notnull": 0, + "dflt_value": null, + "pk": 0 + }, + { + "name": "totp_enabled", + "type": "INTEGER", + "notnull": 1, + "dflt_value": "0", + "pk": 0 + }, + { + "name": "passkey_credentials", + "type": "TEXT", + "notnull": 0, + "dflt_value": null, + "pk": 0 + }, + { + "name": "passkey_enabled", + "type": "INTEGER", + "notnull": 1, + "dflt_value": "0", + "pk": 0 + }, + { + "name": "email_otp_enabled", + "type": "INTEGER", + "notnull": 1, + "dflt_value": "0", + "pk": 0 + }, + { + "name": "preferred_method", + "type": "TEXT", + "notnull": 0, + "dflt_value": null, + "pk": 0 + }, + { + "name": "updated_at", + "type": "TEXT", + "notnull": 1, + "dflt_value": null, + "pk": 0 + } + ], + "indexes": [] + }, + { + "name": "items", + "table_info": [ + { + "name": "id", + "type": "TEXT", + "notnull": 0, + "dflt_value": null, + "pk": 1 + }, + { + "name": "user_id", + "type": "TEXT", + "notnull": 1, + "dflt_value": null, + "pk": 0 + }, + { + "name": "name", + "type": "TEXT", + "notnull": 1, + "dflt_value": null, + "pk": 0 + }, + { + "name": "item_mode", + "type": "TEXT", + "notnull": 1, + "dflt_value": "'cycle'", + "pk": 0 + }, + { + "name": "category", + "type": "TEXT", + "notnull": 1, + "dflt_value": "''", + "pk": 0 + }, + { + "name": "start_date", + "type": "TEXT", + "notnull": 0, + "dflt_value": null, + "pk": 0 + }, + { + "name": "expiry_date", + "type": "TEXT", + "notnull": 1, + "dflt_value": null, + "pk": 0 + }, + { + "name": "period_value", + "type": "INTEGER", + "notnull": 1, + "dflt_value": "1", + "pk": 0 + }, + { + "name": "period_unit", + "type": "TEXT", + "notnull": 1, + "dflt_value": "'month'", + "pk": 0 + }, + { + "name": "reminder_unit", + "type": "TEXT", + "notnull": 1, + "dflt_value": "'day'", + "pk": 0 + }, + { + "name": "reminder_value", + "type": "INTEGER", + "notnull": 1, + "dflt_value": "7", + "pk": 0 + }, + { + "name": "notes", + "type": "TEXT", + "notnull": 1, + "dflt_value": "''", + "pk": 0 + }, + { + "name": "amount", + "type": "REAL", + "notnull": 0, + "dflt_value": null, + "pk": 0 + }, + { + "name": "currency", + "type": "TEXT", + "notnull": 1, + "dflt_value": "'CNY'", + "pk": 0 + }, + { + "name": "last_payment_date", + "type": "TEXT", + "notnull": 0, + "dflt_value": null, + "pk": 0 + }, + { + "name": "is_active", + "type": "INTEGER", + "notnull": 1, + "dflt_value": "1", + "pk": 0 + }, + { + "name": "auto_renew", + "type": "INTEGER", + "notnull": 1, + "dflt_value": "1", + "pk": 0 + }, + { + "name": "calendar_mode", + "type": "TEXT", + "notnull": 1, + "dflt_value": "'solar'", + "pk": 0 + }, + { + "name": "lunar_expiry_date", + "type": "TEXT", + "notnull": 0, + "dflt_value": null, + "pk": 0 + }, + { + "name": "channels", + "type": "TEXT", + "notnull": 1, + "dflt_value": "'[]'", + "pk": 0 + }, + { + "name": "notification_hours", + "type": "TEXT", + "notnull": 1, + "dflt_value": "'[]'", + "pk": 0 + }, + { + "name": "item_kind", + "type": "TEXT", + "notnull": 1, + "dflt_value": "'regular'", + "pk": 0 + }, + { + "name": "created_at", + "type": "TEXT", + "notnull": 1, + "dflt_value": null, + "pk": 0 + }, + { + "name": "updated_at", + "type": "TEXT", + "notnull": 1, + "dflt_value": null, + "pk": 0 + } + ], + "indexes": [ + { + "name": "idx_items_user_id", + "sql": "CREATE INDEX idx_items_user_id\n ON items(user_id)" + } + ] + }, + { + "name": "payment_history", + "table_info": [ + { + "name": "id", + "type": "TEXT", + "notnull": 0, + "dflt_value": null, + "pk": 1 + }, + { + "name": "item_id", + "type": "TEXT", + "notnull": 1, + "dflt_value": null, + "pk": 0 + }, + { + "name": "user_id", + "type": "TEXT", + "notnull": 1, + "dflt_value": null, + "pk": 0 + }, + { + "name": "date", + "type": "TEXT", + "notnull": 1, + "dflt_value": null, + "pk": 0 + }, + { + "name": "amount", + "type": "REAL", + "notnull": 1, + "dflt_value": "0", + "pk": 0 + }, + { + "name": "currency", + "type": "TEXT", + "notnull": 1, + "dflt_value": "'CNY'", + "pk": 0 + }, + { + "name": "type", + "type": "TEXT", + "notnull": 1, + "dflt_value": "'manual'", + "pk": 0 + }, + { + "name": "note", + "type": "TEXT", + "notnull": 1, + "dflt_value": "''", + "pk": 0 + }, + { + "name": "period_start", + "type": "TEXT", + "notnull": 0, + "dflt_value": null, + "pk": 0 + }, + { + "name": "period_end", + "type": "TEXT", + "notnull": 0, + "dflt_value": null, + "pk": 0 + }, + { + "name": "created_at", + "type": "TEXT", + "notnull": 1, + "dflt_value": null, + "pk": 0 + } + ], + "indexes": [ + { + "name": "idx_payment_history_item_id", + "sql": "CREATE INDEX idx_payment_history_item_id\n ON payment_history(item_id)" + }, + { + "name": "idx_payment_history_user_id", + "sql": "CREATE INDEX idx_payment_history_user_id\n ON payment_history(user_id)" + } + ] + }, + { + "name": "notification_configs", + "table_info": [ + { + "name": "user_id", + "type": "TEXT", + "notnull": 0, + "dflt_value": null, + "pk": 1 + }, + { + "name": "enabled_channels", + "type": "TEXT", + "notnull": 1, + "dflt_value": "'[]'", + "pk": 0 + }, + { + "name": "default_channel", + "type": "TEXT", + "notnull": 1, + "dflt_value": "''", + "pk": 0 + }, + { + "name": "telegram_config", + "type": "TEXT", + "notnull": 1, + "dflt_value": "'{}'", + "pk": 0 + }, + { + "name": "webhook_config", + "type": "TEXT", + "notnull": 1, + "dflt_value": "'{}'", + "pk": 0 + }, + { + "name": "wechatbot_config", + "type": "TEXT", + "notnull": 1, + "dflt_value": "'{}'", + "pk": 0 + }, + { + "name": "email_config", + "type": "TEXT", + "notnull": 1, + "dflt_value": "'{}'", + "pk": 0 + }, + { + "name": "bark_config", + "type": "TEXT", + "notnull": 1, + "dflt_value": "'{}'", + "pk": 0 + }, + { + "name": "slack_config", + "type": "TEXT", + "notnull": 1, + "dflt_value": "'{}'", + "pk": 0 + }, + { + "name": "feishu_config", + "type": "TEXT", + "notnull": 1, + "dflt_value": "'{}'", + "pk": 0 + }, + { + "name": "discord_config", + "type": "TEXT", + "notnull": 1, + "dflt_value": "'{}'", + "pk": 0 + }, + { + "name": "notification_hours", + "type": "TEXT", + "notnull": 1, + "dflt_value": "'[]'", + "pk": 0 + }, + { + "name": "updated_at", + "type": "TEXT", + "notnull": 1, + "dflt_value": null, + "pk": 0 + } + ], + "indexes": [] + }, + { + "name": "system_settings", + "table_info": [ + { + "name": "key", + "type": "TEXT", + "notnull": 0, + "dflt_value": null, + "pk": 1 + }, + { + "name": "value", + "type": "TEXT", + "notnull": 1, + "dflt_value": null, + "pk": 0 + }, + { + "name": "updated_at", + "type": "TEXT", + "notnull": 1, + "dflt_value": null, + "pk": 0 + } + ], + "indexes": [] + }, + { + "name": "notification_history", + "table_info": [ + { + "name": "id", + "type": "TEXT", + "notnull": 0, + "dflt_value": null, + "pk": 1 + }, + { + "name": "user_id", + "type": "TEXT", + "notnull": 1, + "dflt_value": null, + "pk": 0 + }, + { + "name": "item_id", + "type": "TEXT", + "notnull": 0, + "dflt_value": null, + "pk": 0 + }, + { + "name": "channel", + "type": "TEXT", + "notnull": 1, + "dflt_value": null, + "pk": 0 + }, + { + "name": "title", + "type": "TEXT", + "notnull": 1, + "dflt_value": null, + "pk": 0 + }, + { + "name": "body", + "type": "TEXT", + "notnull": 0, + "dflt_value": null, + "pk": 0 + }, + { + "name": "success", + "type": "INTEGER", + "notnull": 1, + "dflt_value": "1", + "pk": 0 + }, + { + "name": "error", + "type": "TEXT", + "notnull": 0, + "dflt_value": null, + "pk": 0 + }, + { + "name": "created_at", + "type": "TEXT", + "notnull": 1, + "dflt_value": null, + "pk": 0 + } + ], + "indexes": [ + { + "name": "idx_notification_history_user_id", + "sql": "CREATE INDEX idx_notification_history_user_id\n ON notification_history(user_id, created_at)" + } + ] + } + ] +} diff --git a/worker/test/helpers.ts b/worker/test/helpers.ts index af8bc8b..f246cb8 100644 --- a/worker/test/helpers.ts +++ b/worker/test/helpers.ts @@ -65,14 +65,16 @@ export class MockKV { // ─── D1 mock ────────────────────────────────────────────────────────────────── // // A minimal in-memory stand-in for the D1 operations used by the setup and -// system-settings code paths. It models table existence, columns, and the -// system_settings key/value rows — nothing more. +// system-settings code paths. It models table existence, columns, the +// system_settings key/value rows and the migration ledger — nothing more. type Column = { name: string }; export class MockD1 { tables = new Map(); settings = new Map(); + /** Applied migration names, keyed by ledger table name. */ + ledger = new Map(); constructor(init?: { tables?: Record; @@ -129,11 +131,34 @@ export class MockD1 { ); if (create) { this.tables.set(create[1], parseColumns(create[2])); + // Ledger tables start empty; their rows are tracked in `ledger`. + if (create[1].endsWith("_schema_migrations")) { + this.ledger.set(create[1], this.ledger.get(create[1]) ?? []); + } return null; } if (/^CREATE (UNIQUE )?INDEX/i.test(s)) return null; + const ledgerInsert = s.match( + /^INSERT INTO\s+(\w+)\s*\(\s*name\s*\)\s*VALUES/i, + ); + if (ledgerInsert) { + const names = this.ledger.get(ledgerInsert[1]) ?? []; + names.push(String(args[0] ?? "")); + this.ledger.set(ledgerInsert[1], names); + return null; + } + + const ledgerSelect = s.match(/^SELECT name FROM\s+(\w+)$/i); + if (ledgerSelect) { + const rows = (this.ledger.get(ledgerSelect[1]) ?? []).map((name) => ({ + name, + })); + if (mode === "first") return rows[0] ?? null; + return rows; + } + const addCol = s.match(/ALTER TABLE\s+(\w+)\s+ADD COLUMN\s+(\w+)/i); if (addCol) { const cols = this.tables.get(addCol[1]) ?? []; diff --git a/worker/test/ledger-failure.test.ts b/worker/test/ledger-failure.test.ts new file mode 100644 index 0000000..32270b5 --- /dev/null +++ b/worker/test/ledger-failure.test.ts @@ -0,0 +1,132 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; +import type { Migration } from "../src/lib/migrations"; +import { runSetup } from "../src/lib/setup"; +import type { Env } from "../src/types"; +import { SqliteD1 } from "./support/sqlite-d1"; + +/** + * Failure visibility (spec §5.7): a failing migration must abort setup with an + * error naming the migration, must not be recorded, and must not run the + * migrations after it. Once fixed, the next setup continues from the ledger. + * + * The migration list is injected here — a migration cannot realistically fail + * on a healthy database, so the list is the test seam. + */ + +const state = vi.hoisted(() => ({ + migrations: [] as Migration[], +})); + +vi.mock("../src/lib/migrations", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + getMigrations: (prefix: string): Migration[] => + state.migrations.map((migration) => ({ + name: migration.name, + sql: migration.sql.replace(/\{prefix\}/g, prefix), + })), + }; +}); + +function makeEnv(d1: SqliteD1): Env { + return { DB: d1, TABLE_PREFIX: "" } as unknown as Env; +} + +function tableNames(d1: SqliteD1): string[] { + return ( + d1.db + .prepare( + `SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name`, + ) + .all() as { name: string }[] + ).map((r) => r.name); +} + +function ledgerNames(d1: SqliteD1): string[] { + return ( + d1.db + .prepare(`SELECT name FROM _schema_migrations ORDER BY rowid`) + .all() as { name: string }[] + ).map((r) => r.name); +} + +const V1: Migration = { + name: "schema_v1", + sql: "CREATE TABLE IF NOT EXISTS {prefix}users (id TEXT PRIMARY KEY, email TEXT NOT NULL)", +}; + +const V2_BROKEN: Migration = { + name: "schema_v2_broken", + sql: "CREATE TABLE IF NOT EXISTS {prefix}experimental (id TEXT); SELECT * FROM {prefix}table_that_does_not_exist", +}; + +const V3: Migration = { + name: "schema_v3", + sql: "CREATE TABLE IF NOT EXISTS {prefix}after_failure (id TEXT)", +}; + +beforeEach(() => { + state.migrations = []; +}); + +describe("failing migration", () => { + it("aborts setup with the migration name, records nothing and runs no later migration", async () => { + const d1 = new SqliteD1(); + state.migrations = [V1, V2_BROKEN, V3]; + + await expect(runSetup(makeEnv(d1))).rejects.toThrow( + /Migration "schema_v2_broken" failed: .*table_that_does_not_exist/, + ); + + // The earlier migration stays recorded; the failing one and everything + // after it do not. + expect(ledgerNames(d1)).toEqual(["schema_v1"]); + expect(tableNames(d1)).not.toContain("after_failure"); + }); + + it("continues from the ledger once the migration is fixed", async () => { + const d1 = new SqliteD1(); + state.migrations = [V1, V2_BROKEN, V3]; + await expect(runSetup(makeEnv(d1))).rejects.toThrow(/schema_v2_broken/); + + // Same name, fixed SQL — a broken migration is corrected in place only + // while no database has recorded it. + state.migrations = [ + V1, + { + ...V2_BROKEN, + sql: "CREATE TABLE IF NOT EXISTS {prefix}experimental (id TEXT)", + }, + V3, + ]; + + const result = await runSetup(makeEnv(d1)); + + expect(result).toEqual({ + success: true, + alreadyInitialized: true, + effectivePrefix: "", + migrations: [ + { name: "schema_v1", status: "skipped" }, + { name: "schema_v2_broken", status: "applied" }, + { name: "schema_v3", status: "applied" }, + ], + }); + expect(ledgerNames(d1)).toEqual([ + "schema_v1", + "schema_v2_broken", + "schema_v3", + ]); + expect(tableNames(d1)).toContain("experimental"); + expect(tableNames(d1)).toContain("after_failure"); + }); + + it("does not swallow a failure on the fresh-install path either", async () => { + const d1 = new SqliteD1(); + state.migrations = [V2_BROKEN]; + + await expect(runSetup(makeEnv(d1))).rejects.toThrow(/schema_v2_broken/); + expect(ledgerNames(d1)).toEqual([]); + }); +}); diff --git a/worker/test/ledger.test.ts b/worker/test/ledger.test.ts new file mode 100644 index 0000000..95b741b --- /dev/null +++ b/worker/test/ledger.test.ts @@ -0,0 +1,798 @@ +import { readFileSync } from "node:fs"; +import { describe, expect, it } from "vitest"; +import { getMigrations } from "../src/lib/migrations"; +import { migrationsTable } from "../src/lib/migrations-runner"; +import { runSetup } from "../src/lib/setup"; +import type { Env } from "../src/types"; +import { SqliteD1 } from "./support/sqlite-d1"; + +/** + * Migration ledger acceptance tests (spec §5): fresh install, structure parity + * with the pre-ledger schema, in-place transition of legacy databases, prefix + * variants and the prefix-conflict / foreign-ledger guard. + */ + +type Row = Record; + +const LEDGER_SUFFIX = "_schema_migrations"; + +function makeEnv(d1: SqliteD1, tablePrefix?: string): Env { + const env: Record = { DB: d1 }; + if (tablePrefix !== undefined) env.TABLE_PREFIX = tablePrefix; + return env as unknown as Env; +} + +function execSQL(d1: SqliteD1, sql: string): void { + for (const statement of sql + .split(";") + .map((s) => s.trim()) + .filter((s) => s.length > 0)) { + d1.db.exec(statement); + } +} + +function tableNames(d1: SqliteD1): string[] { + return ( + d1.db + .prepare( + `SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name`, + ) + .all() as { name: string }[] + ).map((r) => r.name); +} + +function columnsOf(d1: SqliteD1, table: string): ColumnInfo[] { + return d1.db.prepare(`PRAGMA table_info(${table})`).all() as ColumnInfo[]; +} + +function indexesOf(d1: SqliteD1, table: string) { + return d1.db + .prepare( + `SELECT name, sql FROM sqlite_master WHERE type = ? AND tbl_name = ? ORDER BY name`, + ) + .all("index", table) as { name: string; sql: string | null }[]; +} + +function rowsOf(d1: SqliteD1, table: string, orderBy = "rowid"): Row[] { + return d1.db.prepare(`SELECT * FROM ${table} ORDER BY ${orderBy}`).all() as + | Row[] + | never; +} + +function ledgerRows(d1: SqliteD1, ledger: string): Row[] { + return d1.db + .prepare(`SELECT name FROM ${ledger} ORDER BY name`) + .all() as Row[]; +} + +function exists(d1: SqliteD1, name: string): boolean { + return ( + d1.db + .prepare(`SELECT name FROM sqlite_master WHERE type='table' AND name = ?`) + .get(name) !== undefined + ); +} + +type ColumnInfo = { + name: string; + type: string; + notnull: number; + dflt_value: string | null; + pk: number; +}; + +/** Structural + data snapshot of a whole database, for "nothing changed" assertions. */ +function snapshot(d1: SqliteD1): Record { + const snap: Record = {}; + for (const table of tableNames(d1)) { + snap[table] = { + columns: columnsOf(d1, table), + indexes: indexesOf(d1, table), + rows: rowsOf(d1, table), + }; + } + return snap; +} + +// ─── fixtures ───────────────────────────────────────────────────────────────── + +/** `worker/src/db/schema.sql` is the current, fully patched shape (no ledger). */ +const CURRENT_SCHEMA = readFileSync( + new URL("../src/db/schema.sql", import.meta.url), + "utf8", +); + +/** Build an up-to-date eNotify database without a migration ledger. */ +function seedCurrentShape(d1: SqliteD1, prefix = ""): void { + execSQL(d1, CURRENT_SCHEMA.replace(/\{prefix\}/g, prefix)); +} + +/** + * The oldest shape the legacy patch set still has to fix: no + * notification_history.body, no slack/feishu/discord/default_channel columns, + * no calendar_mode/lunar_expiry_date (items still carries type/use_lunar), and + * channel configs still listing the retired channels. + */ +const OLDEST_SCHEMA = ` +CREATE TABLE users ( + id TEXT PRIMARY KEY, + email TEXT UNIQUE NOT NULL, + password_hash TEXT NOT NULL, + role TEXT NOT NULL DEFAULT 'user', + is_active INTEGER NOT NULL DEFAULT 1, + email_verified INTEGER NOT NULL DEFAULT 0, + base_currency TEXT NOT NULL DEFAULT 'CNY', + timezone TEXT NOT NULL DEFAULT 'UTC', + language TEXT NOT NULL DEFAULT 'zh', + theme TEXT NOT NULL DEFAULT 'system', + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL +); + +CREATE TABLE user_2fa ( + user_id TEXT PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE, + totp_secret TEXT, + totp_enabled INTEGER NOT NULL DEFAULT 0, + passkey_credentials TEXT, + passkey_enabled INTEGER NOT NULL DEFAULT 0, + email_otp_enabled INTEGER NOT NULL DEFAULT 0, + preferred_method TEXT, + updated_at TEXT NOT NULL +); + +CREATE TABLE items ( + id TEXT PRIMARY KEY, + user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE, + name TEXT NOT NULL, + item_mode TEXT NOT NULL DEFAULT 'cycle', + type TEXT NOT NULL DEFAULT 'subscription', + use_lunar INTEGER NOT NULL DEFAULT 0, + category TEXT NOT NULL DEFAULT '', + start_date TEXT, + expiry_date TEXT NOT NULL, + period_value INTEGER NOT NULL DEFAULT 1, + period_unit TEXT NOT NULL DEFAULT 'month', + reminder_unit TEXT NOT NULL DEFAULT 'day', + reminder_value INTEGER NOT NULL DEFAULT 7, + notes TEXT NOT NULL DEFAULT '', + amount REAL, + currency TEXT NOT NULL DEFAULT 'CNY', + last_payment_date TEXT, + is_active INTEGER NOT NULL DEFAULT 1, + auto_renew INTEGER NOT NULL DEFAULT 1, + channels TEXT NOT NULL DEFAULT '[]', + notification_hours TEXT NOT NULL DEFAULT '[]', + item_kind TEXT NOT NULL DEFAULT 'regular', + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL +); + +CREATE INDEX idx_items_user_id ON items(user_id); + +CREATE TABLE payment_history ( + id TEXT PRIMARY KEY, + item_id TEXT NOT NULL REFERENCES items(id) ON DELETE CASCADE, + user_id TEXT NOT NULL, + date TEXT NOT NULL, + amount REAL NOT NULL DEFAULT 0, + currency TEXT NOT NULL DEFAULT 'CNY', + type TEXT NOT NULL DEFAULT 'manual', + note TEXT NOT NULL DEFAULT '', + period_start TEXT, + period_end TEXT, + created_at TEXT NOT NULL +); + +CREATE INDEX idx_payment_history_item_id ON payment_history(item_id); +CREATE INDEX idx_payment_history_user_id ON payment_history(user_id); + +CREATE TABLE notification_configs ( + user_id TEXT PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE, + enabled_channels TEXT NOT NULL DEFAULT '[]', + telegram_config TEXT NOT NULL DEFAULT '{}', + webhook_config TEXT NOT NULL DEFAULT '{}', + wechatbot_config TEXT NOT NULL DEFAULT '{}', + email_config TEXT NOT NULL DEFAULT '{}', + bark_config TEXT NOT NULL DEFAULT '{}', + gotify_config TEXT NOT NULL DEFAULT '{}', + serverchan_config TEXT NOT NULL DEFAULT '{}', + pushplus_config TEXT NOT NULL DEFAULT '{}', + notifyx_config TEXT NOT NULL DEFAULT '{}', + notification_hours TEXT NOT NULL DEFAULT '[]', + updated_at TEXT NOT NULL +); + +CREATE TABLE system_settings ( + key TEXT PRIMARY KEY, + value TEXT NOT NULL, + updated_at TEXT NOT NULL +); + +CREATE TABLE notification_history ( + id TEXT PRIMARY KEY, + user_id TEXT NOT NULL, + item_id TEXT, + channel TEXT NOT NULL, + title TEXT NOT NULL, + success INTEGER NOT NULL DEFAULT 1, + error TEXT, + created_at TEXT NOT NULL +); + +CREATE INDEX idx_notification_history_user_id + ON notification_history(user_id, created_at); +`; + +function seedOldestShape(d1: SqliteD1): void { + execSQL(d1, OLDEST_SCHEMA); + execSQL( + d1, + ` +INSERT INTO users (id, email, password_hash, role, is_active, email_verified, + base_currency, timezone, language, theme, created_at, updated_at) +VALUES + ('u1', 'u1@example.com', 'hash-1', 'admin', 1, 1, 'CNY', 'Asia/Shanghai', 'zh', 'dark', '2025-01-01T00:00:00.000Z', '2025-01-02T00:00:00.000Z'), + ('u2', 'u2@example.com', 'hash-2', 'user', 1, 0, 'USD', 'UTC', 'en', 'light', '2025-02-01T00:00:00.000Z', '2025-02-02T00:00:00.000Z'); + +INSERT INTO user_2fa (user_id, totp_secret, totp_enabled, passkey_credentials, passkey_enabled, email_otp_enabled, preferred_method, updated_at) +VALUES ('u1', 'JBSWY3DPEHPK3PXP', 1, NULL, 0, 0, 'totp', '2025-01-03T00:00:00.000Z'); + +INSERT INTO items (id, user_id, name, item_mode, type, use_lunar, category, expiry_date, period_value, period_unit, reminder_unit, reminder_value, notes, amount, currency, is_active, auto_renew, channels, notification_hours, item_kind, created_at, updated_at) +VALUES + ('i1', 'u1', 'Lunar Plan', 'cycle', 'subscription', 1, 'work', '2025-03-01', 1, 'month', 'day', 7, 'note-1', 12.5, 'CNY', 1, 1, '["telegram"]', '[8,9]', 'subscription', '2025-01-01T00:00:00.000Z', '2025-01-01T00:00:00.000Z'), + ('i2', 'u2', 'Solar Plan', 'reset', 'regular', 0, '', '2025-04-01', 2, 'week', 'hour', 3, '', NULL, 'USD', 0, 1, '[]', '[]', 'regular', '2025-02-01T00:00:00.000Z', '2025-02-01T00:00:00.000Z'); + +INSERT INTO payment_history (id, item_id, user_id, date, amount, currency, type, note, period_start, period_end, created_at) +VALUES ('p1', 'i1', 'u1', '2025-01-01', 12.5, 'CNY', 'initial', 'first', '2025-01-01', '2025-02-01', '2025-01-01T00:00:00.000Z'); + +INSERT INTO notification_configs (user_id, enabled_channels, telegram_config, gotify_config, notification_hours, updated_at) +VALUES ('u1', '["telegram","serverchan","pushplus","gotify","notifyx"]', '{"bot_token":"secret","chat_id":"42"}', '{"server_url":"https://gotify.example.com","app_token":"tok"}', '[8,9]', '2025-01-04T00:00:00.000Z'); + +INSERT INTO system_settings (key, value, updated_at) +VALUES ('app_name', 'eNotify', '2025-01-01T00:00:00.000Z'); + +INSERT INTO notification_history (id, user_id, item_id, channel, title, success, error, created_at) +VALUES ('h1', 'u1', 'i1', 'telegram', 'Renewal due', 1, NULL, '2025-01-05T00:00:00.000Z'); +`, + ); +} + +// ─── ledger naming ──────────────────────────────────────────────────────────── + +describe("migrationsTable name formula", () => { + it("uses the prefix core with the trailing underscore stripped", () => { + expect(migrationsTable("enotify_")).toBe("_enotify_schema_migrations"); + expect(migrationsTable("eNotify_")).toBe("_eNotify_schema_migrations"); + expect(migrationsTable("X")).toBe("_X_schema_migrations"); + expect(migrationsTable("X_")).toBe("_X_schema_migrations"); + }); + + it("has no prefix core when there is no table prefix", () => { + expect(migrationsTable("")).toBe("_schema_migrations"); + }); +}); + +describe("migration list", () => { + it("collapses the pre-ledger history into a single schema_v1 entry", () => { + const migrations = getMigrations("enotify_"); + expect(migrations.map((m) => m.name)).toEqual(["schema_v1"]); + // `{prefix}` is resolved for the caller, the DDL itself carries no placeholder. + expect(migrations[0].sql).toContain( + "CREATE TABLE IF NOT EXISTS enotify_users", + ); + expect(migrations[0].sql).not.toContain("{prefix}"); + }); + + it("migration SQL contains no ';' inside string literals", () => { + for (const migration of getMigrations("")) { + for (const statement of migration.sql.split(";")) { + const literals = statement.match(/'[^']*'/g) ?? []; + for (const literal of literals) { + expect(literal).not.toContain(";"); + } + } + } + }); +}); + +// ─── fresh install ──────────────────────────────────────────────────────────── + +describe("fresh install through the ledger", () => { + it("creates the 7 tables, the ledger and the default settings", async () => { + const d1 = new SqliteD1(); + + const result = await runSetup(makeEnv(d1, "enotify")); + + expect(result).toEqual({ + success: true, + effectivePrefix: "enotify_", + migrations: [{ name: "schema_v1", status: "applied" }], + }); + + const tables = tableNames(d1); + for (const table of [ + "users", + "user_2fa", + "items", + "payment_history", + "notification_configs", + "system_settings", + "notification_history", + ]) { + expect(tables).toContain(`enotify_${table}`); + } + expect(tables).toContain("_enotify_schema_migrations"); + expect(ledgerRows(d1, "_enotify_schema_migrations")).toEqual([ + { name: "schema_v1" }, + ]); + + const settings = rowsOf(d1, "enotify_system_settings", "key").map( + (r) => r.key, + ); + expect(settings).toEqual([ + "app_name", + "email_provider", + "email_verification_enabled", + "registration_enabled", + "require_2fa", + "resend_config", + "smtp_config", + ]); + }); + + it("skips everything on the second run and leaves structure and data untouched", async () => { + const d1 = new SqliteD1(); + await runSetup(makeEnv(d1, "enotify_")); + + const before = snapshot(d1); + const second = await runSetup(makeEnv(d1, "enotify_")); + + expect(second).toEqual({ + success: true, + alreadyInitialized: true, + effectivePrefix: "enotify_", + migrations: [{ name: "schema_v1", status: "skipped" }], + }); + expect(snapshot(d1)).toEqual(before); + }); +}); + +// ─── structure parity with the pre-ledger schema (core acceptance) ──────────── + +describe("schema_v1 structure parity with the pre-ledger install", () => { + const fixture = JSON.parse( + readFileSync( + new URL("./fixtures/schema-before-ledger.json", import.meta.url), + "utf8", + ), + ) as { + prefix: string; + tables: { + name: string; + table_info: ColumnInfo[]; + indexes: { name: string; sql: string | null }[]; + }[]; + }; + + it("matches the pre-ledger snapshot table by table (PRAGMA table_info + indexes)", async () => { + const d1 = new SqliteD1(); + await runSetup(makeEnv(d1, "")); + + // Only the ledger table is new; every pre-existing table is described below. + const businessTables = tableNames(d1).filter( + (t) => !t.endsWith(LEDGER_SUFFIX), + ); + expect(businessTables).toEqual(fixture.tables.map((t) => t.name).sort()); + + for (const expected of fixture.tables) { + expect({ + name: expected.name, + table_info: columnsOf(d1, expected.name).map( + ({ cid: _cid, ...column }) => column, + ), + indexes: indexesOf(d1, expected.name).filter( + (index) => index.sql !== null, + ), + }).toEqual(expected); + } + }); + + it("keeps the structure of a pre-ledger database after the in-place transition", async () => { + const d1 = new SqliteD1(); + await runSetup(makeEnv(d1, "")); + + // Same 7 tables, same columns/indexes as the legacy patch set produced. + for (const expected of fixture.tables) { + expect( + columnsOf(d1, expected.name).map(({ cid: _cid, ...column }) => column), + ).toEqual(expected.table_info); + expect( + indexesOf(d1, expected.name).filter((index) => index.sql !== null), + ).toEqual(expected.indexes); + } + }); +}); + +// ─── legacy in-place transition ────────────────────────────────────────────── + +describe("legacy database transition", () => { + it("patches the oldest shape, verifies it and stamps schema_v1 without touching rows", async () => { + const d1 = new SqliteD1(); + seedOldestShape(d1); + + const beforeUsers = rowsOf(d1, "users"); + const beforePayments = rowsOf(d1, "payment_history"); + const beforeHistory = rowsOf(d1, "notification_history"); + const beforeSettings = rowsOf(d1, "system_settings"); + const beforeItems = rowsOf(d1, "items"); + const beforeConfigs = rowsOf(d1, "notification_configs"); + + const result = await runSetup(makeEnv(d1, "")); + + expect(result).toEqual({ + success: true, + alreadyInitialized: true, + effectivePrefix: "", + migrations: [{ name: "schema_v1", status: "stamped" }], + }); + expect(ledgerRows(d1, "_schema_migrations")).toEqual([ + { name: "schema_v1" }, + ]); + + // Incremental columns are in place. + const historyCols = columnsOf(d1, "notification_history").map( + (c) => c.name, + ); + expect(historyCols).toContain("body"); + const configCols = columnsOf(d1, "notification_configs").map((c) => c.name); + for (const column of [ + "slack_config", + "feishu_config", + "discord_config", + "default_channel", + ]) { + expect(configCols).toContain(column); + } + const itemCols = columnsOf(d1, "items").map((c) => c.name); + expect(itemCols).toContain("calendar_mode"); + expect(itemCols).toContain("lunar_expiry_date"); + // The legacy patch set's own DROP COLUMN steps still run. + expect(itemCols).not.toContain("use_lunar"); + expect(itemCols).not.toContain("type"); + + // Existing rows are untouched, one by one. + expect(rowsOf(d1, "users")).toEqual(beforeUsers); + expect(rowsOf(d1, "payment_history")).toEqual(beforePayments); + expect(rowsOf(d1, "system_settings")).toEqual(beforeSettings); + expect(rowsOf(d1, "notification_history")).toEqual( + beforeHistory.map((row) => ({ ...row, body: null })), + ); + + // items keeps every surviving column, and calendar_mode is backfilled from use_lunar. + expect( + rowsOf(d1, "items").map( + ({ calendar_mode, lunar_expiry_date, ...rest }) => ({ + ...rest, + calendar_mode, + }), + ), + ).toEqual( + beforeItems.map(({ type, use_lunar, ...rest }) => ({ + ...rest, + calendar_mode: use_lunar === 1 ? "lunar" : "solar", + })), + ); + + // Retired channel IDs are stripped, everything else stays; default_channel + // is the new empty default (spec §2.5 behaviour parity). + expect(rowsOf(d1, "notification_configs")).toEqual( + beforeConfigs.map((row) => ({ + ...row, + enabled_channels: '["telegram"]', + default_channel: "", + slack_config: "{}", + feishu_config: "{}", + discord_config: "{}", + })), + ); + }); + + it("stamps an already up-to-date database and is a no-op on the next run", async () => { + const d1 = new SqliteD1(); + seedCurrentShape(d1); + execSQL( + d1, + `INSERT INTO users (id, email, password_hash, created_at, updated_at) + VALUES ('u1', 'u1@example.com', 'hash', '2025-01-01', '2025-01-01'); + INSERT INTO notification_configs (user_id, enabled_channels, default_channel, updated_at) + VALUES ('u1', '["telegram"]', 'telegram', '2025-01-01');`, + ); + + const before = { + users: rowsOf(d1, "users"), + configs: rowsOf(d1, "notification_configs"), + }; + + const first = await runSetup(makeEnv(d1, "")); + expect(first).toEqual({ + success: true, + alreadyInitialized: true, + effectivePrefix: "", + migrations: [{ name: "schema_v1", status: "stamped" }], + }); + expect(rowsOf(d1, "users")).toEqual(before.users); + expect(rowsOf(d1, "notification_configs")).toEqual(before.configs); + + const afterFirst = snapshot(d1); + const second = await runSetup(makeEnv(d1, "")); + expect(second).toEqual({ + success: true, + alreadyInitialized: true, + effectivePrefix: "", + migrations: [{ name: "schema_v1", status: "skipped" }], + }); + expect(snapshot(d1)).toEqual(afterFirst); + }); + + it("clears retired channel IDs during the transition (same behaviour as before)", async () => { + const d1 = new SqliteD1(); + seedOldestShape(d1); + + await runSetup(makeEnv(d1, "")); + + expect( + d1.db.prepare(`SELECT enabled_channels FROM notification_configs`).all(), + ).toEqual([{ enabled_channels: '["telegram"]' }]); + }); + + describe("shape verification failure", () => { + it("refuses to stamp when a business table is missing", async () => { + const d1 = new SqliteD1(); + seedCurrentShape(d1); + d1.db.exec("DROP TABLE notification_history"); + + const result = await runSetup(makeEnv(d1, "")); + + expect(result).toMatchObject({ + success: false, + code: "SCHEMA_VERIFY_FAILED", + resolvedPrefix: "", + missing: ["table notification_history"], + }); + if (!result.success && result.code === "SCHEMA_VERIFY_FAILED") { + expect(result.error).toContain("notification_history"); + expect(result.error).toContain("was not stamped"); + } + // No ledger was created, so the admin can fix the database and retry. + expect(exists(d1, "_schema_migrations")).toBe(false); + }); + + it("refuses to stamp when a required column cannot be added", async () => { + const d1 = new SqliteD1(); + seedCurrentShape(d1); + // A mis-cased column name: SQLite treats column names case-insensitively, + // so the legacy `ADD COLUMN default_channel` fails as a duplicate while the + // verification (which checks the exact name) still sees the gap. + d1.db.exec( + "ALTER TABLE notification_configs RENAME COLUMN default_channel TO Default_Channel", + ); + + const result = await runSetup(makeEnv(d1, "")); + + expect(result).toMatchObject({ + success: false, + code: "SCHEMA_VERIFY_FAILED", + missing: ["column notification_configs.default_channel"], + }); + expect(exists(d1, "_schema_migrations")).toBe(false); + }); + }); + + it("re-runs the transition after the database is repaired", async () => { + const d1 = new SqliteD1(); + seedCurrentShape(d1); + d1.db.exec("DROP TABLE notification_history"); + + const failed = await runSetup(makeEnv(d1, "")); + expect(failed.success).toBe(false); + + execSQL( + d1, + `CREATE TABLE notification_history ( + id TEXT PRIMARY KEY, + user_id TEXT NOT NULL, + item_id TEXT, + channel TEXT NOT NULL, + title TEXT NOT NULL, + body TEXT, + success INTEGER NOT NULL DEFAULT 1, + error TEXT, + created_at TEXT NOT NULL + );`, + ); + + const repaired = await runSetup(makeEnv(d1, "")); + expect(repaired).toEqual({ + success: true, + alreadyInitialized: true, + effectivePrefix: "", + migrations: [{ name: "schema_v1", status: "stamped" }], + }); + }); +}); + +// ─── ledger consistency ────────────────────────────────────────────────────── + +describe("ledger consistency check", () => { + it("fails when the ledger records migrations but the business tables are gone", async () => { + const d1 = new SqliteD1(); + await runSetup(makeEnv(d1, "")); + + d1.db.exec("DROP TABLE users"); + + const result = await runSetup(makeEnv(d1, "")); + + expect(result).toMatchObject({ + success: false, + code: "LEDGER_INCONSISTENT", + resolvedPrefix: "", + }); + if (!result.success && result.code === "LEDGER_INCONSISTENT") { + expect(result.error).toContain("_schema_migrations"); + expect(result.error).toContain("drop the ledger table"); + } + // Nothing was recreated behind the admin's back. + expect(exists(d1, "users")).toBe(false); + }); + + it("completes a run that was interrupted between ledger creation and recording", async () => { + const d1 = new SqliteD1(); + // Ledger table exists but is empty, as after a crash before the first INSERT. + d1.db.exec( + "CREATE TABLE _schema_migrations (name TEXT PRIMARY KEY, applied_at INTEGER NOT NULL DEFAULT (unixepoch()))", + ); + + const result = await runSetup(makeEnv(d1, "")); + + expect(result).toEqual({ + success: true, + alreadyInitialized: true, + effectivePrefix: "", + migrations: [{ name: "schema_v1", status: "applied" }], + }); + expect(ledgerRows(d1, "_schema_migrations")).toEqual([ + { name: "schema_v1" }, + ]); + expect(exists(d1, "users")).toBe(true); + }); +}); + +// ─── prefix variants ──────────────────────────────────────────────────────── + +describe("prefix variants", () => { + it("defaults to _enotify_schema_migrations", async () => { + const d1 = new SqliteD1(); + // TABLE_PREFIX unset → default "enotify" → "enotify_". + await runSetup(makeEnv(d1)); + + expect(exists(d1, "_enotify_schema_migrations")).toBe(true); + expect(ledgerRows(d1, "_enotify_schema_migrations")).toEqual([ + { name: "schema_v1" }, + ]); + expect(exists(d1, "enotify_users")).toBe(true); + }); + + it("uses _schema_migrations for an explicit empty prefix", async () => { + const d1 = new SqliteD1(); + await runSetup(makeEnv(d1, "")); + + expect(exists(d1, "_schema_migrations")).toBe(true); + expect(ledgerRows(d1, "_schema_migrations")).toEqual([ + { name: "schema_v1" }, + ]); + expect(exists(d1, "users")).toBe(true); + }); + + it("uses _X_schema_migrations for a custom prefix X", async () => { + const d1 = new SqliteD1(); + await runSetup(makeEnv(d1, "X")); + + expect(exists(d1, "_X_schema_migrations")).toBe(true); + expect(ledgerRows(d1, "_X_schema_migrations")).toEqual([ + { name: "schema_v1" }, + ]); + expect(exists(d1, "X_users")).toBe(true); + }); + + it("leaves another prefix's tables and ledger untouched when two coexist", async () => { + const d1 = new SqliteD1(); + // Two instances that were both set up earlier under their own prefix. + seedCurrentShape(d1, "tenant_a_"); + seedCurrentShape(d1, "tenant_b_"); + d1.db.exec( + `CREATE TABLE _tenant_a_schema_migrations (name TEXT PRIMARY KEY, applied_at INTEGER NOT NULL DEFAULT (unixepoch())); + INSERT INTO _tenant_a_schema_migrations (name) VALUES ('schema_v1'); + INSERT INTO tenant_a_users (id, email, password_hash, created_at, updated_at) + VALUES ('a1', 'a@example.com', 'hash', '2025-01-01', '2025-01-01');`, + ); + + const result = await runSetup(makeEnv(d1, "tenant_b_")); + + expect(result).toEqual({ + success: true, + alreadyInitialized: true, + effectivePrefix: "tenant_b_", + migrations: [{ name: "schema_v1", status: "stamped" }], + }); + // tenant_a is untouched (ledger row count unchanged, its data still there). + expect(ledgerRows(d1, "_tenant_a_schema_migrations")).toEqual([ + { name: "schema_v1" }, + ]); + expect(rowsOf(d1, "tenant_a_users")).toHaveLength(1); + // tenant_b got its own record. + expect(ledgerRows(d1, "_tenant_b_schema_migrations")).toEqual([ + { name: "schema_v1" }, + ]); + }); +}); + +// ─── guard regressions ────────────────────────────────────────────────────── + +describe("prefix conflict guard with the ledger", () => { + it("still returns PREFIX_CONFLICT and creates no ledger table", async () => { + const d1 = new SqliteD1(); + seedCurrentShape(d1, "other_"); + + const result = await runSetup(makeEnv(d1, "enotify")); + + expect(result).toMatchObject({ + success: false, + code: "PREFIX_CONFLICT", + resolvedPrefix: "enotify_", + detectedPrefixes: ["other_"], + }); + expect(tableNames(d1).filter((t) => t.endsWith(LEDGER_SUFFIX))).toEqual([]); + expect(exists(d1, "enotify_users")).toBe(false); + }); + + it("ignores another project's ledger table on a fresh install", async () => { + const d1 = new SqliteD1(); + d1.db.exec( + "CREATE TABLE _ZETA_schema_migrations (name TEXT PRIMARY KEY, applied_at INTEGER NOT NULL DEFAULT (unixepoch()))", + ); + + const result = await runSetup(makeEnv(d1, "enotify")); + + expect(result).toEqual({ + success: true, + effectivePrefix: "enotify_", + migrations: [{ name: "schema_v1", status: "applied" }], + }); + // The foreign ledger is neither read nor written. + expect(ledgerRows(d1, "_ZETA_schema_migrations")).toEqual([]); + expect(ledgerRows(d1, "_enotify_schema_migrations")).toEqual([ + { name: "schema_v1" }, + ]); + }); + + it("does not let another project's ledger interfere with a legacy transition", async () => { + const d1 = new SqliteD1(); + seedCurrentShape(d1, "enotify_"); + d1.db.exec( + "CREATE TABLE _ZETA_schema_migrations (name TEXT PRIMARY KEY, applied_at INTEGER NOT NULL DEFAULT (unixepoch()))", + ); + + const result = await runSetup(makeEnv(d1, "enotify")); + + expect(result).toEqual({ + success: true, + alreadyInitialized: true, + effectivePrefix: "enotify_", + migrations: [{ name: "schema_v1", status: "stamped" }], + }); + expect(ledgerRows(d1, "_ZETA_schema_migrations")).toEqual([]); + expect(ledgerRows(d1, "_enotify_schema_migrations")).toEqual([ + { name: "schema_v1" }, + ]); + }); +}); diff --git a/worker/test/migrations.test.ts b/worker/test/migrations.test.ts index 42a61bc..ac574da 100644 --- a/worker/test/migrations.test.ts +++ b/worker/test/migrations.test.ts @@ -1,46 +1,14 @@ -import { DatabaseSync } from "node:sqlite"; import { afterEach, describe, expect, it, vi } from "vitest"; import { runSetup } from "../src/lib/setup"; import { sendNotifications } from "../src/services/notify/index"; import type { Env, NotificationConfig } from "../src/types"; - -/** - * Minimal D1 stand-in backed by a real in-memory SQLite database. Unlike the - * MockD1 in helpers.ts this keeps real column defaults and row data, which is - * what the slack_config migration needs to be verified against. - */ -class SqliteD1 { - readonly db = new DatabaseSync(":memory:"); - - prepare(sql: string): any { - const db = this.db; - const statement = () => db.prepare(sql); - - return { - bind: (...args: unknown[]) => ({ - first: async () => - (statement().get(...(args as any[])) ?? null) as T | null, - all: async () => ({ - results: statement().all(...(args as any[])) as T[], - }), - run: async () => { - statement().run(...(args as any[])); - return { success: true }; - }, - }), - first: async () => (statement().get() ?? null) as T | null, - all: async () => ({ results: statement().all() as T[] }), - run: async () => { - statement().run(); - return { success: true }; - }, - }; - } -} +import { SqliteD1 } from "./support/sqlite-d1"; const PREFIX = "en_"; // Schema as deployed before the Slack channel existed: no slack_config column. +// All 7 core tables are present, so runSetup takes the pre-ledger transition +// path (legacy patches → shape verification → stamp). const OLD_SCHEMA = ` CREATE TABLE ${PREFIX}users ( id TEXT PRIMARY KEY, @@ -91,6 +59,29 @@ CREATE TABLE ${PREFIX}items ( lunar_expiry_date TEXT ); +CREATE TABLE ${PREFIX}user_2fa ( + user_id TEXT PRIMARY KEY REFERENCES ${PREFIX}users(id) ON DELETE CASCADE, + totp_secret TEXT, + totp_enabled INTEGER NOT NULL DEFAULT 0, + passkey_credentials TEXT, + passkey_enabled INTEGER NOT NULL DEFAULT 0, + email_otp_enabled INTEGER NOT NULL DEFAULT 0, + preferred_method TEXT, + updated_at TEXT NOT NULL +); + +CREATE TABLE ${PREFIX}payment_history ( + id TEXT PRIMARY KEY, + item_id TEXT NOT NULL, + user_id TEXT NOT NULL +); + +CREATE TABLE ${PREFIX}system_settings ( + key TEXT PRIMARY KEY, + value TEXT NOT NULL, + updated_at TEXT NOT NULL +); + INSERT INTO ${PREFIX}users (id, email, password_hash, created_at, updated_at) VALUES @@ -186,10 +177,12 @@ describe("notification_configs slack_config migration", () => { d1.db.exec(OLD_SCHEMA); const result = await runSetup(makeEnv(d1)); + // Legacy database transition stamps the collapsed history as schema_v1. expect(result).toEqual({ success: true, alreadyInitialized: true, effectivePrefix: "en_", + migrations: [{ name: "schema_v1", status: "stamped" }], }); const columns = d1.db @@ -238,6 +231,7 @@ describe("notification_configs slack_config migration", () => { success: true, alreadyInitialized: true, effectivePrefix: "en_", + migrations: [{ name: "schema_v1", status: "skipped" }], }); const rows = d1.db @@ -410,6 +404,7 @@ describe("retired channel cleanup migration", () => { success: true, alreadyInitialized: true, effectivePrefix: "en_", + migrations: [{ name: "schema_v1", status: "skipped" }], }); expect(enabledChannelsOf(d1, "u1")).toBe('["telegram"]'); @@ -460,7 +455,11 @@ describe("fresh install schema", () => { const d1 = new SqliteD1(); const result = await runSetup(makeEnv(d1)); - expect(result).toEqual({ success: true, effectivePrefix: "en_" }); + expect(result).toEqual({ + success: true, + effectivePrefix: "en_", + migrations: [{ name: "schema_v1", status: "applied" }], + }); const columns = d1.db .prepare(`PRAGMA table_info(${PREFIX}notification_configs)`) diff --git a/worker/test/prefix.test.ts b/worker/test/prefix.test.ts index 7be0d90..b57b8f8 100644 --- a/worker/test/prefix.test.ts +++ b/worker/test/prefix.test.ts @@ -219,6 +219,7 @@ describe("runSetup anti-silent-switch guard", () => { success: true, alreadyInitialized: true, effectivePrefix: "old_", + migrations: [{ name: "schema_v1", status: "stamped" }], }); }); @@ -231,7 +232,11 @@ describe("runSetup anti-silent-switch guard", () => { headers: secretHeader(), }); expect(res.status).toBe(200); - expect(res.body).toEqual({ success: true, effectivePrefix: "enotify_" }); + expect(res.body).toEqual({ + success: true, + effectivePrefix: "enotify_", + migrations: [{ name: "schema_v1", status: "applied" }], + }); const db = env.DB as MockD1; expect(db.tables.has("enotify_users")).toBe(true); @@ -251,7 +256,11 @@ describe("runSetup anti-silent-switch guard", () => { headers: secretHeader(), }); expect(res.status).toBe(200); - expect(res.body).toEqual({ success: true, effectivePrefix: "enotify_" }); + expect(res.body).toEqual({ + success: true, + effectivePrefix: "enotify_", + migrations: [{ name: "schema_v1", status: "applied" }], + }); const db = env.DB as MockD1; expect(db.tables.has("enotify_users")).toBe(true); @@ -291,7 +300,11 @@ describe("admin setup route surfaces prefix conflicts", () => { const res = await adminSetup(env); expect(res.status).toBe(200); - expect(res.body).toEqual({ success: true, effectivePrefix: "eNotify_" }); + expect(res.body).toEqual({ + success: true, + effectivePrefix: "eNotify_", + migrations: [{ name: "schema_v1", status: "applied" }], + }); }); }); diff --git a/worker/test/setup.test.ts b/worker/test/setup.test.ts index 7dda976..9acdf8c 100644 --- a/worker/test/setup.test.ts +++ b/worker/test/setup.test.ts @@ -160,10 +160,15 @@ describe("POST /api/setup (regression)", () => { headers: secretHeader(), }); expect(res.status).toBe(200); - expect(res.body).toEqual({ success: true, effectivePrefix: "" }); + expect(res.body).toEqual({ + success: true, + effectivePrefix: "", + migrations: [{ name: "schema_v1", status: "applied" }], + }); const db = env.DB as MockD1; expect(db.tables.has("users")).toBe(true); + expect(db.ledger.get("_schema_migrations")).toEqual(["schema_v1"]); }); it("reports alreadyInitialized on a second call", async () => { @@ -183,6 +188,7 @@ describe("POST /api/setup (regression)", () => { success: true, alreadyInitialized: true, effectivePrefix: "", + migrations: [{ name: "schema_v1", status: "skipped" }], }); }); diff --git a/worker/test/support/sqlite-d1.ts b/worker/test/support/sqlite-d1.ts new file mode 100644 index 0000000..d243d3e --- /dev/null +++ b/worker/test/support/sqlite-d1.ts @@ -0,0 +1,39 @@ +/** + * Minimal D1 stand-in backed by a real in-memory SQLite database + * (`node:sqlite`, built into Node 22+). + * + * Unlike the `MockD1` in helpers.ts this keeps real column defaults, row data, + * foreign keys and PRAGMA output, which is what schema/migration assertions + * need to stay honest. D1 is SQLite, so the SQL under test runs unchanged. + */ +// @ts-expect-error node:sqlite ships with Node but is not in the Workers type set. +import { DatabaseSync } from "node:sqlite"; + +export class SqliteD1 { + readonly db = new DatabaseSync(":memory:"); + + prepare(sql: string): any { + const db = this.db; + const statement = () => db.prepare(sql); + + return { + bind: (...args: unknown[]) => ({ + first: async () => + (statement().get(...(args as any[])) ?? null) as T | null, + all: async () => ({ + results: statement().all(...(args as any[])) as T[], + }), + run: async () => { + statement().run(...(args as any[])); + return { success: true }; + }, + }), + first: async () => (statement().get() ?? null) as T | null, + all: async () => ({ results: statement().all() as T[] }), + run: async () => { + statement().run(); + return { success: true }; + }, + }; + } +}