From a06fbd8db1723f5e3551dbf1b8b044778fa73867 Mon Sep 17 00:00:00 2001 From: mapxn <16299874+mapxn@users.noreply.github.com> Date: Sun, 25 Oct 2026 00:38:22 +0800 Subject: [PATCH] =?UTF-8?q?feat(worker):=20TABLE=5FPREFIX=20=E4=B8=89?= =?UTF-8?q?=E6=80=81=E8=AF=AD=E4=B9=89=20+=20=E9=98=B2=E9=9D=99=E9=BB=98?= =?UTF-8?q?=E5=88=87=E6=8D=A2=E6=8B=A6=E6=88=AA=20(ONE-210=20/=20ONE-201)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - getTablePrefix 三态:未配置 → 默认 enotify(enotify_);自定义 → 补尾 _;显式空串 → 无前缀;默认常量与解析集中 types.ts 一处 - 中间件消除第二解析点,改为校验解析后前缀(空串合法) - runSetup 前置 detectTablePrefixes 探测 sqlite_master,检测到异前缀已初始化 schema 时 409 PREFIX_CONFLICT 中止(含旧无前缀 schema 具名指引),绝不自动重建表;成功返回 effectivePrefix - SetupResult 失败分支补 error 字段(适配 web setupApi.run 的 body.error 提取) - setup/admin 路由非成功态显式 c.json(result, 409) - CI deploy.yml 三态注入:vars 未设/空 → enotify;none → 空串;其他原样 - MockD1 补全 sqlite_master 全表扫描;存量测试适配 effectivePrefix;新增 prefix.test.ts(三态解析 / 冲突中止 / detectTablePrefixes) - README.md / README.en.md / CLAUDE.md 更新三态语义、CI none 约定与升级警告 --- .github/workflows/deploy.yml | 15 +- CLAUDE.md | 4 +- README.en.md | 32 ++-- README.md | 32 ++-- worker/src/index.ts | 2 +- worker/src/lib/setup.ts | 106 ++++++++++- worker/src/routes/admin.ts | 3 + worker/src/routes/setup.ts | 3 + worker/src/types.ts | 29 ++- worker/test/admin.test.ts | 10 +- worker/test/helpers.ts | 7 + worker/test/migrations.test.ts | 20 ++- worker/test/prefix.test.ts | 317 +++++++++++++++++++++++++++++++++ worker/test/setup.test.ts | 8 +- 14 files changed, 542 insertions(+), 46 deletions(-) create mode 100644 worker/test/prefix.test.ts diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index 16f06af..d71baba 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -39,13 +39,26 @@ jobs: KV_NAMESPACE_ID: ${{ vars.KV_NAMESPACE_ID }} TABLE_PREFIX: ${{ vars.TABLE_PREFIX }} run: | + # Three-state TABLE_PREFIX resolution (must match runtime getTablePrefix): + # - vars unset or empty → inject "enotify" (default prefix) + # - vars "none" (reserved word) → inject "" (explicit no prefix) + # - anything else → inject verbatim + if [ -z "$TABLE_PREFIX" ]; then + RESOLVED_PREFIX="enotify" + elif [ "$TABLE_PREFIX" = "none" ]; then + RESOLVED_PREFIX="" + else + RESOLVED_PREFIX="$TABLE_PREFIX" + fi + export RESOLVED_PREFIX + APP_VERSION="$(node -p "require('../package.json').version")" \ perl -pi -e ' s/CLOUDFLARE_ACCOUNT_ID_PLACEHOLDER/$ENV{CLOUDFLARE_ACCOUNT_ID}/g; s/D1_DATABASE_NAME_PLACEHOLDER/$ENV{D1_DATABASE_NAME}/g; s/D1_DATABASE_ID_PLACEHOLDER/$ENV{D1_DATABASE_ID}/g; s/KV_NAMESPACE_ID_PLACEHOLDER/$ENV{KV_NAMESPACE_ID}/g; - s/TABLE_PREFIX_PLACEHOLDER/$ENV{TABLE_PREFIX}/g; + s/TABLE_PREFIX_PLACEHOLDER/$ENV{RESOLVED_PREFIX}/g; s/__APP_VERSION__/'\''$ENV{APP_VERSION}'\''/g; ' wrangler.toml diff --git a/CLAUDE.md b/CLAUDE.md index a5459ee..1a33142 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -57,7 +57,7 @@ The worker serves the frontend's static assets from `web/dist/` via the `ASSETS` **Database** (`worker/src/db/`): - Cloudflare D1 (SQLite). Schema defined in `worker/src/db/schema.sql`. -- 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`. +- 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`. **Core utilities** (`worker/src/core/`): @@ -81,7 +81,7 @@ The worker serves the frontend's static assets from `web/dist/` via the `ASSETS` - `KV` — KV namespace (used for scheduler deduplication and status) - `ASSETS` — static file serving - Secrets: `JWT_SECRET`, `SETUP_SECRET` -- Env var: `TABLE_PREFIX` (optional, allows shared DB with prefix isolation) +- Env var: `TABLE_PREFIX` (three states: unset → default `enotify`, tables like `enotify_users`; custom value → verbatim with trailing `_`; explicit `""`/CI `none` → no prefix; allows shared DB with prefix isolation) ### Frontend (`web/`) diff --git a/README.en.md b/README.en.md index 31154f0..059c9b4 100644 --- a/README.en.md +++ b/README.en.md @@ -63,12 +63,12 @@ In your repository Settings → Secrets and variables → Actions, add: In Settings → Secrets and variables → Actions → Variables, add: -| Variable | Description | -| ------------------ | ----------------------------------------------------- | -| `D1_DATABASE_NAME` | D1 database name | -| `D1_DATABASE_ID` | D1 database ID | -| `KV_NAMESPACE_ID` | KV namespace ID | -| `TABLE_PREFIX` | Optional prefix for all DB table names(e.g. `myapp_`) | +| Variable | Description | +| ------------------ | ------------------------------------------------------------------------------------------------------- | +| `D1_DATABASE_NAME` | D1 database name | +| `D1_DATABASE_ID` | D1 database ID | +| `KV_NAMESPACE_ID` | KV namespace ID | +| `TABLE_PREFIX` | Table prefix, three states: unset/empty → default `enotify` (tables like `enotify_users`); `none` → no prefix; other values (e.g. `eNotify`) → verbatim | ### 3. Deploy @@ -170,11 +170,21 @@ curl -X DELETE https://your-worker.workers.dev/api/me/api-keys/ -H "Cookie: `JWT_SECRET` and `SETUP_SECRET` are Secrets, uploaded by GitHub Actions via `wrangler deploy --secrets-file`. For local deploys, run `wrangler secret put JWT_SECRET` (and `SETUP_SECRET`) first. `TABLE_PREFIX` is injected into wrangler.toml. -| Variable | Description | -| -------------- | ------------------------------------------------------- | -| `JWT_SECRET` | JWT signing secret, any random 64-char string | -| `SETUP_SECRET` | Database initialization route secret, any random string | -| `TABLE_PREFIX` | Database table prefix (e.g., `hk_`), default is empty | +`TABLE_PREFIX` has three-state semantics (resolved solely by the `getTablePrefix()` helper in `worker/src/types.ts`): + +- **Unset** (not configured / `null`) → default prefix `enotify`, actual table names like `enotify_users`; +- **Custom non-empty value** (e.g. `eNotify`) → used verbatim with a trailing `_` appended (`eNotify_`); only letters, digits and underscores are allowed; +- **Explicit empty string `""`** → no prefix at all (table names like `users`). + +CI deployment convention (`.github/workflows/deploy.yml`): a GitHub Variables `TABLE_PREFIX` that is unset or empty → injects `enotify`; the reserved word `none` → injects the empty string (no prefix); any other value → injected verbatim. This matches the runtime three-state resolution. + +> ⚠️ **Upgrade warning**: older deployments that never configured `TABLE_PREFIX` (the old default was no prefix) must explicitly set `TABLE_PREFIX=none` in GitHub Variables before upgrading, in order to keep the existing unprefixed table names. Otherwise the setup/migration endpoints (`POST /api/setup`, `POST /api/admin/setup`) detect the conflict between the legacy unprefixed schema and the new default prefix `enotify_` and abort with 409 `PREFIX_CONFLICT` — they never re-create or silently switch tables. Deployments already using a custom value (e.g. `eNotify`) are unaffected. + +| Variable | Description | +| -------------- | ------------------------------------------------------------------------------------------------------- | +| `JWT_SECRET` | JWT signing secret, any random 64-char string | +| `SETUP_SECRET` | Database initialization route secret, any random string | +| `TABLE_PREFIX` | Table prefix, three states: unset → default `enotify` (tables like `enotify_users`); explicit empty string / CI `none` → no prefix; custom value → verbatim with trailing `_` | ## License diff --git a/README.md b/README.md index 2c3b42a..5893255 100644 --- a/README.md +++ b/README.md @@ -63,12 +63,12 @@ npx wrangler kv namespace create ENOTIFY_KV 在 Settings → Secrets and variables → Actions → Variables 中添加: -| Variable | 说明 | -| ------------------ | ---------------------------------- | -| `D1_DATABASE_NAME` | D1 数据库名称 | -| `D1_DATABASE_ID` | D1 数据库 ID | -| `KV_NAMESPACE_ID` | KV 命名空间 ID | -| `TABLE_PREFIX` | 数据库表前缀(如 `hk_`),默认为空 | +| Variable | 说明 | +| ------------------ | ------------------------------------------------------------------------------------------------------------------------ | +| `D1_DATABASE_NAME` | D1 数据库名称 | +| `D1_DATABASE_ID` | D1 数据库 ID | +| `KV_NAMESPACE_ID` | KV 命名空间 ID | +| `TABLE_PREFIX` | 数据库表前缀,三态:未设置/留空 → 默认 `enotify`(表名如 `enotify_users`);设为 `none` → 无前缀;其他值(如 `eNotify`)→ 原样 | ### 3. 部署 @@ -175,11 +175,21 @@ curl -X DELETE https://your-worker.workers.dev/api/me/api-keys/ -H "Cookie: `JWT_SECRET` 和 `SETUP_SECRET` 是 Secret,由 GitHub Actions 通过 `wrangler deploy --secrets-file` 上传;本地部署请先执行 `wrangler secret put JWT_SECRET`(`SETUP_SECRET` 同理)。`TABLE_PREFIX` 在 wrangler.toml 中注入。 -| 变量 | 说明 | -| -------------- | ------------------------------------ | -| `JWT_SECRET` | JWT 签名密钥,任意 64 位随机字符串 | -| `SETUP_SECRET` | 数据库初始化路由密钥,任意随机字符串 | -| `TABLE_PREFIX` | 数据库表前缀(如 `hk_`),默认为空 | +`TABLE_PREFIX` 为三态语义(在 `worker/src/types.ts` 的 `getTablePrefix()` 中统一解析,全仓唯一解析点): + +- **未配置**(未设置 / `null`)→ 默认前缀 `enotify`,实际表名如 `enotify_users`; +- **自定义非空值**(如 `eNotify`)→ 原样使用并自动补尾 `_`(`eNotify_`),仅允许字母/数字/下划线; +- **显式空字符串 `""`** → 无前缀,表名不带前缀(如 `users`)。 + +CI 部署约定(`.github/workflows/deploy.yml`):GitHub Variables 中的 `TABLE_PREFIX` 未设置或为空 → 注入 `enotify`;设为保留字 `none` → 注入空字符串(无前缀);其他值 → 原样注入。与运行时三态解析保持一致。 + +> ⚠️ **升级警告**:历史上从未配置过 `TABLE_PREFIX` 的旧部署(旧版默认无前缀)升级到本版本前,须先在 GitHub Variables 中显式配置 `TABLE_PREFIX=none` 保持原表名;否则初始化/迁移接口(`POST /api/setup`、`POST /api/admin/setup`)会检测到无前缀存量 schema 与新默认前缀 `enotify_` 冲突并中止(409 `PREFIX_CONFLICT`,绝不自动重建表)。配置为自定义值(如 `eNotify`)的存量部署不受影响。 + +| 变量 | 说明 | +| -------------- | ------------------------------------------------------------------------------------------------------------------------ | +| `JWT_SECRET` | JWT 签名密钥,任意 64 位随机字符串 | +| `SETUP_SECRET` | 数据库初始化路由密钥,任意随机字符串 | +| `TABLE_PREFIX` | 数据库表前缀,三态:未设置 → 默认 `enotify`(表名如 `enotify_users`);显式空串/CI `none` → 无前缀;自定义值 → 原样补尾 `_` | ## 许可证 diff --git a/worker/src/index.ts b/worker/src/index.ts index f347582..a06c249 100644 --- a/worker/src/index.ts +++ b/worker/src/index.ts @@ -40,7 +40,7 @@ app.use("/api/*", async (c, next) => { await next(); }); app.use("*", async (c, next) => { - const prefix = c.env.TABLE_PREFIX || ""; + const prefix = getTablePrefix(c.env); if (prefix && !/^[a-zA-Z0-9_]+$/.test(prefix)) { return c.json({ error: "Invalid TABLE_PREFIX configuration" }, 500); } diff --git a/worker/src/lib/setup.ts b/worker/src/lib/setup.ts index 7a1dfe8..bcc264d 100644 --- a/worker/src/lib/setup.ts +++ b/worker/src/lib/setup.ts @@ -1,9 +1,62 @@ -import { getTablePrefix } from "../types"; +import { + DEFAULT_TABLE_PREFIX, + ensureTrailingUnderscore, + getTablePrefix, +} from "../types"; import type { Env } from "../types"; -export interface SetupResult { - success: true; - alreadyInitialized?: true; +export type SetupResult = + | { success: true; alreadyInitialized?: true; effectivePrefix: string } + | { + success: false; + code: "PREFIX_CONFLICT"; + error: string; + message: string; + resolvedPrefix: string; + detectedPrefixes: string[]; + }; + +// Unprefixed names of the tables that make up an initialized eNotify schema. +// Used to detect which prefixes the database has already been initialized +// under, so a prefix change can never silently re-initialize fresh tables. +const EONOTIFY_TABLES = [ + "users", + "user_2fa", + "items", + "payment_history", + "notification_configs", + "system_settings", + "notification_history", +]; + +/** + * Detects the table prefixes under which an initialized eNotify schema exists. + * A prefix counts as initialized when at least 4 core tables carrying it are + * present and one of them is `users`. Unrelated tables (e.g. a lone `users` + * table from another app) do not trigger a detection. + */ +export function detectTablePrefixes(tableNames: string[]): Set { + const count: Record = {}; + const hasUsers: Record = {}; + + for (const t of tableNames) { + for (const suffix of EONOTIFY_TABLES) { + if (t === suffix) { + count[""] = (count[""] ?? 0) + 1; + if (suffix === "users") hasUsers[""] = true; + } else if (t.endsWith("_" + suffix)) { + const p = t.slice(0, t.length - suffix.length); // keeps the trailing underscore, e.g. "eNotify_" + count[p] = (count[p] ?? 0) + 1; + if (suffix === "users") hasUsers[p] = true; + } + } + } + + return new Set( + Object.entries(count) + .filter(([p, n]) => n >= 4 && hasUsers[p]) + .map(([p]) => p), + ); } const DEFAULT_SETTINGS: Record = { @@ -176,7 +229,46 @@ export async function runSetup(env: Env): Promise { const prefix = getTablePrefix(env); const db = env.DB; - // Check if already initialized + // Anti-silent-switch guard: if the database already holds an initialized + // eNotify schema under a different prefix, abort instead of re-initializing + // fresh tables under the resolved prefix. + const rows = await db + .prepare(`SELECT name FROM sqlite_master WHERE type='table'`) + .all<{ name: string }>(); + const detected = detectTablePrefixes(rows.results.map((r) => r.name)); + + if (!detected.has(prefix) && detected.size > 0) { + const detectedList = [...detected].sort(); + let message: string; + if ( + detected.has("") && + prefix === ensureTrailingUnderscore(DEFAULT_TABLE_PREFIX) + ) { + message = + `Detected a legacy schema without table prefix, but TABLE_PREFIX is unset ` + + `(resolves to "${prefix}"). To keep the legacy tables, set TABLE_PREFIX to an ` + + `explicit empty value (GitHub vars: TABLE_PREFIX=none, injected as "" by CI), ` + + `or migrate the tables to the "${prefix}" prefix per the README upgrade guide.`; + } else { + message = + `TABLE_PREFIX mismatch: this database is already initialized under a different ` + + `table prefix (detected: ${detectedList.join(", ")}), but TABLE_PREFIX resolves ` + + `to "${prefix}". Set TABLE_PREFIX explicitly to keep the existing tables ` + + `(e.g. "${detectedList[0]}"), or migrate the tables to the new prefix before ` + + `retrying setup.`; + } + + return { + success: false, + code: "PREFIX_CONFLICT", + error: message, + message, + resolvedPrefix: prefix, + detectedPrefixes: detectedList, + }; + } + + // 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`) @@ -184,7 +276,7 @@ export async function runSetup(env: Env): Promise { if (existing) { await runMigrations(db, prefix); - return { success: true, alreadyInitialized: true }; + return { success: true, alreadyInitialized: true, effectivePrefix: prefix }; } const schemaSQL = getSchema(); @@ -209,7 +301,7 @@ export async function runSetup(env: Env): Promise { .run(); } - return { success: true }; + return { success: true, effectivePrefix: prefix }; } function getSchema(): string { diff --git a/worker/src/routes/admin.ts b/worker/src/routes/admin.ts index 0930a8b..cfec59b 100644 --- a/worker/src/routes/admin.ts +++ b/worker/src/routes/admin.ts @@ -549,6 +549,9 @@ adminRoutes.put("/system/settings", async (c) => { adminRoutes.post("/setup", async (c) => { try { const result = await runSetup(c.env); + if (!result.success) { + return c.json(result, 409); + } return c.json(result, 200); } catch (err) { console.error("Admin setup failed:", err); diff --git a/worker/src/routes/setup.ts b/worker/src/routes/setup.ts index b2999c3..35ca328 100644 --- a/worker/src/routes/setup.ts +++ b/worker/src/routes/setup.ts @@ -61,6 +61,9 @@ setupRoutes.post( } const result = await runSetup(c.env); + if (!result.success) { + return c.json(result, 409); + } return c.json(result); }, ); diff --git a/worker/src/types.ts b/worker/src/types.ts index 284c069..af70165 100644 --- a/worker/src/types.ts +++ b/worker/src/types.ts @@ -3,7 +3,13 @@ export interface Env { KV: KVNamespace; JWT_SECRET: string; SETUP_SECRET: string; - TABLE_PREFIX: string; + /** + * Table prefix, three states: + * - undefined/null (unset) → DEFAULT_TABLE_PREFIX ("enotify"), normalized to "enotify_" + * - non-empty custom value → used verbatim with a trailing "_" appended + * - explicit empty string "" → no prefix at all + */ + TABLE_PREFIX?: string; ASSETS: Fetcher; } @@ -117,10 +123,25 @@ export type HonoEnv = { }; }; +/** Default table prefix used when TABLE_PREFIX is not configured (no trailing underscore). */ +export const DEFAULT_TABLE_PREFIX = "enotify"; + export function getTablePrefix(env: Env): string { - const raw = env.TABLE_PREFIX || ""; - if (!raw) return ""; - return raw.endsWith("_") ? raw : `${raw}_`; + const raw = env.TABLE_PREFIX; + // State 1: unset (undefined or null) → default prefix, normalized with trailing "_" + if (raw === undefined || raw === null) { + return ensureTrailingUnderscore(DEFAULT_TABLE_PREFIX); + } + // State 3: explicitly configured as empty string → no prefix + if (raw === "") { + return ""; + } + // State 2: custom non-empty value → existing normalization (append trailing "_") + return ensureTrailingUnderscore(raw); +} + +export function ensureTrailingUnderscore(v: string): string { + return v.endsWith("_") ? v : `${v}_`; } export const VALID_CHANNELS: string[] = [ diff --git a/worker/test/admin.test.ts b/worker/test/admin.test.ts index ff6438c..a852ac8 100644 --- a/worker/test/admin.test.ts +++ b/worker/test/admin.test.ts @@ -24,7 +24,7 @@ describe("POST /api/admin/setup", () => { headers: cookieHeader(token), }); expect(res.status).toBe(200); - expect(res.body).toEqual({ success: true }); + expect(res.body).toEqual({ success: true, effectivePrefix: "" }); const db = env.DB as MockD1; expect(db.tables.has("users")).toBe(true); @@ -52,7 +52,11 @@ describe("POST /api/admin/setup", () => { headers: cookieHeader(token), }); expect(res.status).toBe(200); - expect(res.body).toEqual({ success: true, alreadyInitialized: true }); + expect(res.body).toEqual({ + success: true, + alreadyInitialized: true, + effectivePrefix: "", + }); }); it("returns 403 for a non-admin user", async () => { @@ -90,6 +94,6 @@ describe("POST /api/admin/setup", () => { headers: cookieHeader(token), }); expect(res.status).toBe(200); - expect(res.body).toEqual({ success: true }); + expect(res.body).toEqual({ success: true, effectivePrefix: "" }); }); }); diff --git a/worker/test/helpers.ts b/worker/test/helpers.ts index d0bc6de..af8bc8b 100644 --- a/worker/test/helpers.ts +++ b/worker/test/helpers.ts @@ -102,6 +102,13 @@ export class MockD1 { const s = sql.trim(); if (s.includes("sqlite_master")) { + // Full-table scan (no "name=?" filter) enumerates every table, as the + // prefix-detection query in runSetup does. + if (!/name\s*=\s*\?/.test(s)) { + const rows = [...this.tables.keys()].map((name) => ({ name })); + if (mode === "first") return rows[0] ?? null; + return rows; + } const name = String(args[0] ?? ""); const exists = this.tables.has(name); if (mode === "first") return exists ? { name } : null; diff --git a/worker/test/migrations.test.ts b/worker/test/migrations.test.ts index a16693e..42a61bc 100644 --- a/worker/test/migrations.test.ts +++ b/worker/test/migrations.test.ts @@ -186,7 +186,11 @@ describe("notification_configs slack_config migration", () => { d1.db.exec(OLD_SCHEMA); const result = await runSetup(makeEnv(d1)); - expect(result).toEqual({ success: true, alreadyInitialized: true }); + expect(result).toEqual({ + success: true, + alreadyInitialized: true, + effectivePrefix: "en_", + }); const columns = d1.db .prepare(`PRAGMA table_info(${PREFIX}notification_configs)`) @@ -230,7 +234,11 @@ describe("notification_configs slack_config migration", () => { await runSetup(makeEnv(d1)); const second = await runSetup(makeEnv(d1)); - expect(second).toEqual({ success: true, alreadyInitialized: true }); + expect(second).toEqual({ + success: true, + alreadyInitialized: true, + effectivePrefix: "en_", + }); const rows = d1.db .prepare(`SELECT * FROM ${PREFIX}notification_configs`) @@ -398,7 +406,11 @@ describe("retired channel cleanup migration", () => { await runSetup(makeEnv(d1)); const second = await runSetup(makeEnv(d1)); - expect(second).toEqual({ success: true, alreadyInitialized: true }); + expect(second).toEqual({ + success: true, + alreadyInitialized: true, + effectivePrefix: "en_", + }); expect(enabledChannelsOf(d1, "u1")).toBe('["telegram"]'); expect(enabledChannelsOf(d1, "u2")).toBe('["bark"]'); @@ -448,7 +460,7 @@ describe("fresh install schema", () => { const d1 = new SqliteD1(); const result = await runSetup(makeEnv(d1)); - expect(result).toEqual({ success: true }); + expect(result).toEqual({ success: true, effectivePrefix: "en_" }); 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 new file mode 100644 index 0000000..7be0d90 --- /dev/null +++ b/worker/test/prefix.test.ts @@ -0,0 +1,317 @@ +import { describe, expect, it } from "vitest"; +import { DEFAULT_TABLE_PREFIX, getTablePrefix } from "../src/types"; +import type { Env } from "../src/types"; +import { detectTablePrefixes, runSetup } from "../src/lib/setup"; +import { + MockD1, + cookieHeader, + makeApp, + makeEnv, + makeToken, + request, + seedSession, + TEST_SETUP_SECRET, +} from "./helpers"; + +function secretHeader(): Record { + return { "X-Setup-Secret": TEST_SETUP_SECRET }; +} + +function envWith(overrides: Record): Env { + return makeEnv(overrides) as unknown as Env; +} + +describe("getTablePrefix three-state resolution", () => { + it("unset (undefined) resolves to the default prefix with a trailing underscore", () => { + expect(getTablePrefix(envWith({ TABLE_PREFIX: undefined }))).toBe( + "enotify_", + ); + }); + + it("unset (null) resolves to the default prefix with a trailing underscore", () => { + expect(getTablePrefix(envWith({ TABLE_PREFIX: null }))).toBe("enotify_"); + }); + + it("a custom value gets a trailing underscore appended", () => { + expect(getTablePrefix(envWith({ TABLE_PREFIX: "eNotify" }))).toBe( + "eNotify_", + ); + }); + + it("a custom value already ending with an underscore is kept as is", () => { + expect(getTablePrefix(envWith({ TABLE_PREFIX: "eNotify_" }))).toBe( + "eNotify_", + ); + }); + + it("an explicit empty string resolves to no prefix", () => { + expect(getTablePrefix(envWith({ TABLE_PREFIX: "" }))).toBe(""); + }); + + it("the default prefix constant is the bare project default", () => { + expect(DEFAULT_TABLE_PREFIX).toBe("enotify"); + expect(`${DEFAULT_TABLE_PREFIX}_`).toBe("enotify_"); + }); +}); + +describe("detectTablePrefixes", () => { + it("detects an initialized schema and keeps the trailing underscore", () => { + expect( + detectTablePrefixes([ + "eNotify_users", + "eNotify_user_2fa", + "eNotify_items", + "eNotify_payment_history", + "eNotify_notification_configs", + "eNotify_system_settings", + "eNotify_notification_history", + ]), + ).toEqual(new Set(["eNotify_"])); + }); + + it("detects a legacy no-prefix schema", () => { + expect( + detectTablePrefixes(["users", "user_2fa", "items", "payment_history"]), + ).toEqual(new Set([""])); + }); + + it("requires at least 4 core tables before a prefix counts as initialized", () => { + expect(detectTablePrefixes(["users", "user_2fa", "items"])).toEqual( + new Set(), + ); + }); + + it("requires a users table before a prefix counts as initialized", () => { + expect( + detectTablePrefixes([ + "a_user_2fa", + "a_items", + "a_payment_history", + "a_notification_configs", + ]), + ).toEqual(new Set()); + }); + + it("ignores unrelated tables from other apps sharing the database", () => { + expect( + detectTablePrefixes(["zeta_users", "shortlink_links", "sqlite_sequence"]), + ).toEqual(new Set()); + }); + + it("is case sensitive", () => { + expect( + detectTablePrefixes([ + "enotify_users", + "enotify_items", + "enotify_payment_history", + "enotify_notification_configs", + ]), + ).toEqual(new Set(["enotify_"])); + expect(detectTablePrefixes(["USERS", "ITEMS", "USERS_2FA"])).toEqual( + new Set(), + ); + }); +}); + +// A database initialized under the "old_" prefix (all 7 core tables). +const OLD_PREFIX_TABLES: Record = { + old_users: ["id", "email"], + old_user_2fa: ["user_id"], + old_items: ["id"], + old_payment_history: ["id"], + old_notification_configs: ["user_id"], + old_system_settings: ["key"], + old_notification_history: ["id"], +}; + +// A legacy database initialized without any prefix (all 7 core tables). +const LEGACY_NO_PREFIX_TABLES: Record = { + users: ["id", "email"], + user_2fa: ["user_id"], + items: ["id"], + payment_history: ["id"], + notification_configs: ["user_id"], + system_settings: ["key"], + notification_history: ["id"], +}; + +describe("runSetup anti-silent-switch guard", () => { + it("aborts with 409 PREFIX_CONFLICT when the DB is initialized under another prefix and TABLE_PREFIX is unset", async () => { + const env = envWith({ + TABLE_PREFIX: undefined, + DB: new MockD1({ tables: OLD_PREFIX_TABLES }), + }); + const app = makeApp(); + + const res = await request(app, env, "/api/setup", { + method: "POST", + headers: secretHeader(), + }); + expect(res.status).toBe(409); + expect(res.body.success).toBe(false); + expect(res.body.code).toBe("PREFIX_CONFLICT"); + expect(res.body.resolvedPrefix).toBe("enotify_"); + expect(res.body.detectedPrefixes).toEqual(["old_"]); + expect(res.body.error).toContain("TABLE_PREFIX"); + expect(res.body.message).toBe(res.body.error); + + // No fresh tables were silently created under the default prefix. + const db = env.DB as MockD1; + expect(db.tables.has("enotify_users")).toBe(false); + }); + + it("aborts with the legacy-schema guidance when a no-prefix schema exists and TABLE_PREFIX is unset", async () => { + const env = envWith({ + TABLE_PREFIX: undefined, + DB: new MockD1({ tables: LEGACY_NO_PREFIX_TABLES }), + }); + const app = makeApp(); + + const res = await request(app, env, "/api/setup", { + method: "POST", + headers: secretHeader(), + }); + expect(res.status).toBe(409); + expect(res.body.code).toBe("PREFIX_CONFLICT"); + expect(res.body.resolvedPrefix).toBe("enotify_"); + expect(res.body.detectedPrefixes).toEqual([""]); + expect(res.body.error).toContain("legacy schema without table prefix"); + expect(res.body.error).toContain("TABLE_PREFIX=none"); + + const db = env.DB as MockD1; + expect(db.tables.has("enotify_users")).toBe(false); + }); + + it("aborts with the generic mismatch message when an explicit empty prefix meets an old_ schema", async () => { + const env = envWith({ + TABLE_PREFIX: "", + DB: new MockD1({ tables: OLD_PREFIX_TABLES }), + }); + const app = makeApp(); + + const res = await request(app, env, "/api/setup", { + method: "POST", + headers: secretHeader(), + }); + expect(res.status).toBe(409); + expect(res.body.code).toBe("PREFIX_CONFLICT"); + expect(res.body.resolvedPrefix).toBe(""); + expect(res.body.error).toContain("TABLE_PREFIX mismatch"); + expect(res.body.error).toContain("old_"); + + const db = env.DB as MockD1; + expect(db.tables.has("users")).toBe(false); + }); + + it("succeeds with alreadyInitialized when the configured prefix matches the existing schema", async () => { + const env = envWith({ + TABLE_PREFIX: "old", + DB: new MockD1({ tables: OLD_PREFIX_TABLES }), + }); + const app = makeApp(); + + const res = await request(app, env, "/api/setup", { + method: "POST", + headers: secretHeader(), + }); + expect(res.status).toBe(200); + expect(res.body).toEqual({ + success: true, + alreadyInitialized: true, + effectivePrefix: "old_", + }); + }); + + it("initializes a fresh empty DB under the default prefix when TABLE_PREFIX is unset", async () => { + const env = envWith({ TABLE_PREFIX: undefined }); + const app = makeApp(); + + const res = await request(app, env, "/api/setup", { + method: "POST", + headers: secretHeader(), + }); + expect(res.status).toBe(200); + expect(res.body).toEqual({ success: true, effectivePrefix: "enotify_" }); + + const db = env.DB as MockD1; + expect(db.tables.has("enotify_users")).toBe(true); + }); + + it("does not treat unrelated tables from other apps as a conflict", async () => { + const env = envWith({ + TABLE_PREFIX: undefined, + DB: new MockD1({ + tables: { zeta_users: ["id"], shortlink_links: ["id"] }, + }), + }); + const app = makeApp(); + + const res = await request(app, env, "/api/setup", { + method: "POST", + headers: secretHeader(), + }); + expect(res.status).toBe(200); + expect(res.body).toEqual({ success: true, effectivePrefix: "enotify_" }); + + const db = env.DB as MockD1; + expect(db.tables.has("enotify_users")).toBe(true); + expect(db.tables.has("zeta_users")).toBe(true); + }); +}); + +describe("admin setup route surfaces prefix conflicts", () => { + async function adminSetup(env: Env): Promise<{ status: number; body: any }> { + const app = makeApp(); + const token = await makeToken("admin", { + sub: "admin-1", + sid: "sess-admin", + }); + await seedSession(env as Record, "admin-1", "sess-admin"); + return request(app, env, "/api/admin/setup", { + method: "POST", + headers: cookieHeader(token), + }); + } + + it("returns 409 with the conflict body instead of 200", async () => { + const env = envWith({ + TABLE_PREFIX: undefined, + DB: new MockD1({ tables: OLD_PREFIX_TABLES }), + }); + + const res = await adminSetup(env); + expect(res.status).toBe(409); + expect(res.body.code).toBe("PREFIX_CONFLICT"); + expect(res.body.error).toBeTypeOf("string"); + expect((env.DB as MockD1).tables.has("enotify_users")).toBe(false); + }); + + it("reports the effective prefix on success", async () => { + const env = envWith({ TABLE_PREFIX: "eNotify" }); + + const res = await adminSetup(env); + expect(res.status).toBe(200); + expect(res.body).toEqual({ success: true, effectivePrefix: "eNotify_" }); + }); +}); + +describe("runSetup conflict result shape (direct call)", () => { + it("returns the full conflict payload without touching the database", async () => { + const env = envWith({ + TABLE_PREFIX: undefined, + DB: new MockD1({ tables: OLD_PREFIX_TABLES }), + }); + + const result = await runSetup(env); + expect(result).toEqual({ + success: false, + code: "PREFIX_CONFLICT", + error: result.error, + message: result.error, + resolvedPrefix: "enotify_", + detectedPrefixes: ["old_"], + }); + expect(result.error).toContain('e.g. "old_"'); + expect((env.DB as MockD1).tables.has("enotify_users")).toBe(false); + }); +}); diff --git a/worker/test/setup.test.ts b/worker/test/setup.test.ts index 7148155..7dda976 100644 --- a/worker/test/setup.test.ts +++ b/worker/test/setup.test.ts @@ -160,7 +160,7 @@ describe("POST /api/setup (regression)", () => { headers: secretHeader(), }); expect(res.status).toBe(200); - expect(res.body).toEqual({ success: true }); + expect(res.body).toEqual({ success: true, effectivePrefix: "" }); const db = env.DB as MockD1; expect(db.tables.has("users")).toBe(true); @@ -179,7 +179,11 @@ describe("POST /api/setup (regression)", () => { headers: secretHeader(), }); expect(res.status).toBe(200); - expect(res.body).toEqual({ success: true, alreadyInitialized: true }); + expect(res.body).toEqual({ + success: true, + alreadyInitialized: true, + effectivePrefix: "", + }); }); it("rejects a wrong secret with 403", async () => {