diff --git a/.github/scripts/d1-prefixed-migrations.sh b/.github/scripts/d1-prefixed-migrations.sh index 322119e..4a1941e 100644 --- a/.github/scripts/d1-prefixed-migrations.sh +++ b/.github/scripts/d1-prefixed-migrations.sh @@ -87,6 +87,14 @@ elif [[ -n "$own_tables" ]]; then echo "::error::They may belong to another application or predate the migration history; refusing to migrate. Record the applied migrations in $history first." exit 1 else + # Silent-switch guard: an unprefixed schema of this app (history with schema_v1, + # or wrangler's d1_migrations) exists → abort rather than silently initialising + # a new prefixed schema. A bare `users` table alone is not a signal — the + # shared D1 database can carry other apps' tables. + if grep -qx d1_migrations <<<"$tables" || (grep -qx _schema_migrations <<<"$tables" && d1_query "SELECT name FROM _schema_migrations" | grep -qx schema_v1); then + echo "::error::The database contains an unprefixed schema (_schema_migrations / d1_migrations), but TABLE_PREFIX resolves to '$prefix'. Refusing to initialise a new '$prefix'-prefixed schema. To keep the existing unprefixed schema, set TABLE_PREFIX='' (or TABLE_PREFIX=none in CI)." + exit 1 + fi applied="" echo "No ${prefix}_ tables yet — fresh install." fi diff --git a/.github/scripts/d1-prepare-migrations.sh b/.github/scripts/d1-prepare-migrations.sh index 4f1f9b5..8c9515d 100755 --- a/.github/scripts/d1-prepare-migrations.sh +++ b/.github/scripts/d1-prepare-migrations.sh @@ -11,18 +11,20 @@ # # setup.ts migration `schema_vN` <=> migrations/NNNN_*.sql (N zero-padded) # -# Writes `mode=apply`, `mode=prefixed` or `mode=skip` to $GITHUB_OUTPUT -# (stdout if unset). -# apply — wrangler migrations can run safely +# Writes `mode=apply` or `mode=prefixed` to $GITHUB_OUTPUT (stdout if unset). +# apply — wrangler migrations can run safely (no prefix in use) # prefixed — TABLE_PREFIX is in use; migrations/*.sql are not prefix-aware, # so d1-prefixed-migrations.sh applies the setup-route migrations -# skip — prefixed tables found but TABLE_PREFIX is not set here; the -# schema must keep being managed through the setup route +# +# Three-state TABLE_PREFIX (unset → 'sl', '' → no prefix, other → as-is) is +# resolved by the deploy workflow before this script runs; a silent switch +# (database already initialised under a different prefix) aborts with an error. # # D1_LOCATION=local runs the queries against the local D1 database instead of # the remote one (for testing this script). set -euo pipefail +here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" out="${GITHUB_OUTPUT:-/dev/stdout}" location="${D1_LOCATION:-remote}" if [[ "$location" != remote && "$location" != local ]]; then @@ -30,14 +32,15 @@ if [[ "$location" != remote && "$location" != local ]]; then exit 1 fi -if [[ -n "${TABLE_PREFIX:-}" ]]; then - if ! [[ "$TABLE_PREFIX" =~ ^[A-Za-z0-9_]+$ ]]; then - echo "::error::TABLE_PREFIX '$TABLE_PREFIX' may only contain letters, digits and underscores." - exit 1 - fi - echo "TABLE_PREFIX=$TABLE_PREFIX — prefixed setup-route migrations will be applied instead of wrangler's." - echo "mode=prefixed" >>"$out" - exit 0 +# Three-state resolution: the deploy workflow already resolves vars.TABLE_PREFIX +# (none → '', unset/empty → 'sl') before calling this script. When invoked +# directly with TABLE_PREFIX unset, resolve it to the project default. +# `${TABLE_PREFIX+x}` is empty when unset and 'x' when set (even to ''), which +# is portable across bash 3.x and 5.x. +if [[ -n "${TABLE_PREFIX+x}" ]]; then + prefix="$TABLE_PREFIX" +else + prefix="$(node --disable-warning=MODULE_TYPELESS_PACKAGE_JSON "$here/default-table-prefix.mjs")" fi d1_query() { @@ -47,6 +50,48 @@ d1_query() { tables="$(d1_query "SELECT name FROM sqlite_master WHERE type = 'table'")" has_table() { grep -qx "$1" <<<"$tables"; } +has_table_i() { grep -qixF "$1" <<<"$tables"; } + +# An unprefixed schema of this app: the legacy setup route records its history +# in `_schema_migrations` (with schema_v1), and wrangler's unprefixed path in +# `d1_migrations`. A bare `users` table alone is NOT a signal — the shared D1 +# database can carry other apps' tables. +unprefixed=false +if has_table _schema_migrations && d1_query "SELECT name FROM _schema_migrations" | grep -qx schema_v1; then + unprefixed=true +fi +if has_table d1_migrations; then + unprefixed=true +fi + +if [[ -n "$prefix" ]]; then + if ! [[ "$prefix" =~ ^[A-Za-z0-9_]+$ ]]; then + echo "::error::TABLE_PREFIX '$prefix' may only contain letters, digits and underscores." + exit 1 + fi + # Already initialised under this prefix → incremental/idempotent migration, + # not a silent switch. Allow it. + if has_table_i "_${prefix}_schema_migrations" || has_table_i "${prefix}_users"; then + echo "TABLE_PREFIX=$prefix — prefixed setup-route migrations will be applied instead of wrangler's." + echo "mode=prefixed" >>"$out" + exit 0 + fi + # Current prefix not initialised, but an unprefixed schema of this app exists + # → switching would point at a new set of tables. + if [[ "$unprefixed" == true ]]; then + echo "::error::The database already contains an unprefixed schema (_schema_migrations / d1_migrations), but TABLE_PREFIX resolves to '$prefix'. Refusing to initialise a new '$prefix'-prefixed schema. To keep the existing unprefixed schema, set TABLE_PREFIX='' (or TABLE_PREFIX=none in CI)." + exit 1 + fi + echo "TABLE_PREFIX=$prefix — prefixed setup-route migrations will be applied instead of wrangler's." + echo "mode=prefixed" >>"$out" + exit 0 +fi + +# Prefix resolves to empty (explicit no-prefix). +if [[ "$unprefixed" != true ]] && grep -Eq '^_[A-Za-z0-9_]+_schema_migrations$' <<<"$tables"; then + echo "::error::The database already contains a prefixed schema, but TABLE_PREFIX resolves to an empty string (no prefix). Refusing to initialise an unprefixed schema. To keep the existing prefixed schema, configure TABLE_PREFIX to its current value." + exit 1 +fi if has_table d1_migrations; then echo "d1_migrations present — database is already tracked by wrangler." @@ -55,11 +100,6 @@ if has_table d1_migrations; then fi if ! has_table users; then - if grep -Eq '^(_[A-Za-z0-9_]+_schema_migrations|[A-Za-z0-9_]+_users)$' <<<"$tables"; then - echo "::warning::Found prefixed tables but no unprefixed schema; looks like TABLE_PREFIX is in use. Set the TABLE_PREFIX variable on the production environment so deploys apply prefixed migrations. Skipping D1 migrations." - echo "mode=skip" >>"$out" - exit 0 - fi echo "Empty database — wrangler will apply all migrations." echo "mode=apply" >>"$out" exit 0 diff --git a/.github/scripts/default-table-prefix.mjs b/.github/scripts/default-table-prefix.mjs new file mode 100644 index 0000000..3fc190c --- /dev/null +++ b/.github/scripts/default-table-prefix.mjs @@ -0,0 +1,5 @@ +// Prints the project default TABLE_PREFIX from the single source of truth +// (apps/worker/src/lib/table-prefix.ts), so bash scripts never hardcode it. +import { DEFAULT_TABLE_PREFIX } from '../../apps/worker/src/lib/table-prefix.ts'; + +process.stdout.write(DEFAULT_TABLE_PREFIX); diff --git a/.github/scripts/resolve-table-prefix.mjs b/.github/scripts/resolve-table-prefix.mjs new file mode 100644 index 0000000..dd36f17 --- /dev/null +++ b/.github/scripts/resolve-table-prefix.mjs @@ -0,0 +1,27 @@ +// CI three-state TABLE_PREFIX resolution (the "none" convention). +// +// GitHub Actions `vars.TABLE_PREFIX` cannot distinguish "unset" from "empty", +// so the deploy workflow uses a reserved word to preserve the three runtime +// states: +// unset / empty → DEFAULT_TABLE_PREFIX ('sl') +// 'none' → '' (explicit no prefix; the deployer accepts the +// table-collision risk) +// anything else → as-is +// +// The default constant comes from the single source of truth +// (apps/worker/src/lib/table-prefix.ts), loaded via Node type stripping. +// Reads the raw value from the TABLE_PREFIX environment variable and prints the +// resolved value to stdout. +import { DEFAULT_TABLE_PREFIX } from '../../apps/worker/src/lib/table-prefix.ts'; + +const raw = process.env.TABLE_PREFIX; + +let resolved; +if (raw === undefined || raw === '') { + resolved = DEFAULT_TABLE_PREFIX; +} else if (raw === 'none') { + resolved = ''; +} else { + resolved = raw; +} +process.stdout.write(resolved); diff --git a/.github/scripts/test-d1-migrations.mjs b/.github/scripts/test-d1-migrations.mjs index 2908b0b..64b95c0 100644 --- a/.github/scripts/test-d1-migrations.mjs +++ b/.github/scripts/test-d1-migrations.mjs @@ -262,3 +262,48 @@ test('已知限制:别的应用占用同名索引时,本应用索引会被 ); assert.throws(() => f.assertOwnIndexes('SL'), /Expected values/); }); + +// ─── 防静默切换(部署侧)───────────────────────────────────────────────────── + +test('防静默切换:库中已有无前缀 schema + 解析为 sl → 中止并提示显式配置', (t) => { + const f = fixture(t); + f.setup('', ['schema_v1']); + assert.throws( + () => f.script('d1-prepare-migrations.sh', 'sl'), + (err) => /unprefixed schema/.test(err.stdout ?? ''), + ); +}); + +test('防静默切换:库中已有 prefixed schema + 显式空前缀 → 中止并提示显式配置', (t) => { + const f = fixture(t); + f.setup('SL', ['schema_v1']); + assert.throws( + () => f.script('d1-prepare-migrations.sh', ''), + (err) => /prefixed schema/.test(err.stdout ?? ''), + ); +}); + +// ─── 回归:共享库他表 + 三态边界(ONE-206 修复)───────────────────────────── + +test('回归:共享库他表 + shortlink 已有 SL 前缀 → 增量迁移放行,不误杀', (t) => { + const f = fixture(t); + const before = f.shared(); // 他应用:bare users + ZETA_* + f.setup('SL', ['schema_v1', 'schema_v2']); + assert.match(f.script('d1-prepare-migrations.sh', 'SL'), /prefixed/); + assert.match( + f.script('d1-prefixed-migrations.sh', 'SL'), + /Planned migrations: none/, + ); + assert.deepEqual(f.foreignSnapshot(), before); +}); + +test('回归:共享库他表 + shortlink 显式空前缀 → 放行,不误判他表为前缀', (t) => { + const f = fixture(t); + // 仅他应用的前缀表,shortlink 自身无任何 schema。 + f.query(`CREATE TABLE ZETA_users (id TEXT PRIMARY KEY); + INSERT INTO ZETA_users VALUES ('zeta-user'); + CREATE TABLE ZETA_links (id TEXT, slug TEXT); + INSERT INTO ZETA_links VALUES ('zeta-link', 'keep'); + CREATE TABLE eNotify_settings (key TEXT, value TEXT);`); + assert.match(f.script('d1-prepare-migrations.sh', ''), /Empty database/); +}); diff --git a/.github/scripts/test-deploy-checks.mjs b/.github/scripts/test-deploy-checks.mjs index 41707d6..968e4a1 100644 --- a/.github/scripts/test-deploy-checks.mjs +++ b/.github/scripts/test-deploy-checks.mjs @@ -155,3 +155,52 @@ esac } }); } + +// ─── CI 三态解析(none 约定)───────────────────────────────────────────────── + +for (const scenario of [ + { name: 'vars 未设 → 默认 sl', env: undefined, expected: 'sl' }, + { name: 'vars 为空 → 默认 sl', env: '', expected: 'sl' }, + { name: 'vars 为保留字 none → 空字符串', env: 'none', expected: '' }, + { name: 'vars 为其他值 → 原样(含大小写)', env: 'SL', expected: 'SL' }, +]) { + test(`三态解析(none 约定):${scenario.name}`, (t) => { + const f = fixture(t); + const env = { ...f.env }; + if (scenario.env === undefined) { + delete env.TABLE_PREFIX; + } else { + env.TABLE_PREFIX = scenario.env; + } + const out = execFileSync( + 'node', + [ + '--disable-warning=MODULE_TYPELESS_PACKAGE_JSON', + join(scripts, 'resolve-table-prefix.mjs'), + ], + { env, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }, + ); + assert.equal(out, scenario.expected); + }); +} + +test('worker-table-prefix.sh:未设置绑定 → 默认 sl', (t) => { + const f = fixture(t); + writeFileSync( + join(f.dir, 'pnpm'), + `#!/bin/sh +case "$*" in + 'exec wrangler versions view v1 --json') + printf '%s\\n' '{"id":"v1","resources":{"bindings":[]}}' ;; + *) exit 99 ;; +esac +`, + { mode: 0o755 }, + ); + const out = execFileSync( + 'bash', + [join(scripts, 'worker-table-prefix.sh'), 'v1'], + { env: f.env, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }, + ); + assert.equal(out, 'sl'); +}); diff --git a/.github/scripts/verify-deployment.sh b/.github/scripts/verify-deployment.sh index f4f99ee..0f328e2 100644 --- a/.github/scripts/verify-deployment.sh +++ b/.github/scripts/verify-deployment.sh @@ -7,7 +7,7 @@ # Run from apps/worker (needs wrangler.toml with real IDs injected). # # Env: WRANGLER_OUTPUT_FILE_PATH — the ND-JSON file `wrangler deploy` wrote -# TABLE_PREFIX — GitHub variable (may be empty) +# TABLE_PREFIX — resolved prefix ('' means explicit no prefix) set -euo pipefail here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" @@ -41,12 +41,12 @@ done live="$(bash "$here/worker-table-prefix.sh" "$version")" live="${live//[^A-Za-z0-9_]/}" +# worker-table-prefix.sh already maps an unset Worker binding to the default +# 'sl'; compare literally (case-sensitive) so e.g. production `SL` is never +# folded into `sl` and reported as a false match. expected="${TABLE_PREFIX:-}" -if [[ -n "$expected" && "$live" != "$expected" ]]; then - echo "::error::Deployed version uses TABLE_PREFIX='$live', but migrations were applied for '$expected'." +if [[ "$live" != "$expected" ]]; then + echo "::error::Deployed version uses TABLE_PREFIX='$live', but migrations were applied for '${expected:-}'." exit 1 fi -if [[ -z "$expected" && -n "$live" ]]; then - echo "::warning::The Worker uses TABLE_PREFIX=$live but the GitHub TABLE_PREFIX variable is unset; set it on the production environment so deploys apply schema migrations automatically." -fi echo "TABLE_PREFIX: ${live:-}" diff --git a/.github/scripts/worker-table-prefix.sh b/.github/scripts/worker-table-prefix.sh index f55f99a..54f284a 100644 --- a/.github/scripts/worker-table-prefix.sh +++ b/.github/scripts/worker-table-prefix.sh @@ -1,6 +1,8 @@ #!/usr/bin/env bash -# Prints the TABLE_PREFIX variable of a deployed Worker version (nothing if it -# is unset). Run from apps/worker (needs wrangler.toml with real IDs injected). +# Prints the effective TABLE_PREFIX of a deployed Worker version. When the +# Worker has no TABLE_PREFIX binding, the project default ('sl') is printed — +# matching the runtime three-state resolution in src/lib/table-prefix.ts. +# Run from apps/worker (needs wrangler.toml with real IDs injected). # # bash worker-table-prefix.sh # @@ -8,6 +10,7 @@ # value can't be read back, so it can't be compared with the GitHub variable. set -euo pipefail +here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" version="${1:?usage: worker-table-prefix.sh }" view="$(pnpm exec wrangler versions view "$version" --json)" @@ -15,6 +18,8 @@ view="$(pnpm exec wrangler versions view "$version" --json)" jq -e --arg v "$version" '.id == $v and (.resources.bindings | type == "array")' <<<"$view" >/dev/null binding="$(jq -c '[.resources.bindings[] | select(.name == "TABLE_PREFIX")] | first // empty' <<<"$view")" if [[ -z "$binding" ]]; then + # No binding: the runtime resolves this to the project default prefix. + node --disable-warning=MODULE_TYPELESS_PACKAGE_JSON "$here/default-table-prefix.mjs" exit 0 fi diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index 1880c1b..19b7f7b 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -91,12 +91,21 @@ jobs: # Order: migrate first, then deploy code. Migrations must therefore be # backward compatible with the code currently live (expand → deploy → # contract: add columns/tables now, drop old ones in a later release). + - name: Resolve TABLE_PREFIX (three-state) + id: prefix + env: + TABLE_PREFIX: ${{ vars.TABLE_PREFIX }} + run: | + resolved="$(node --disable-warning=MODULE_TYPELESS_PACKAGE_JSON .github/scripts/resolve-table-prefix.mjs)" + echo "resolved TABLE_PREFIX: ${resolved:-}" + echo "table_prefix=${resolved}" >> "$GITHUB_OUTPUT" + - name: Prepare D1 migrations id: d1 working-directory: apps/worker env: CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} - TABLE_PREFIX: ${{ vars.TABLE_PREFIX }} + TABLE_PREFIX: ${{ steps.prefix.outputs.table_prefix }} run: bash ../../.github/scripts/d1-prepare-migrations.sh - name: Apply D1 migrations @@ -113,7 +122,7 @@ jobs: working-directory: apps/worker env: CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} - TABLE_PREFIX: ${{ vars.TABLE_PREFIX }} + TABLE_PREFIX: ${{ steps.prefix.outputs.table_prefix }} run: bash ../../.github/scripts/d1-prefixed-migrations.sh # Web and worker were built above; deploy the worker directly so wrangler @@ -133,7 +142,7 @@ jobs: env: CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} WRANGLER_OUTPUT_FILE_PATH: ${{ runner.temp }}/wrangler-output.ndjson - TABLE_PREFIX: ${{ vars.TABLE_PREFIX }} + TABLE_PREFIX: ${{ steps.prefix.outputs.table_prefix }} run: bash ../../.github/scripts/verify-deployment.sh - name: Smoke test diff --git a/CLAUDE.md b/CLAUDE.md index 813e659..545236c 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -97,7 +97,8 @@ shortlink/ │ │ │ │ └── auth.ts # requireAuth and requireAdmin middleware (JWT verification) │ │ │ └── lib/ │ │ │ ├── crypto.ts # PBKDF2 password hash/verify; AES-256-GCM encrypt/decrypt TOTP -│ │ │ ├── db.ts # tbl() helper: applies TABLE_PREFIX to all table names +│ │ │ ├── db.ts # tbl(env, name) helper: applies the three-state TABLE_PREFIX to all table names +│ │ │ ├── table-prefix.ts # DEFAULT_TABLE_PREFIX + three-state resolveTablePrefix() (single source) │ │ │ ├── jwt.ts # issueTokenPair, verifyAccessToken, verifyRefreshToken │ │ │ ├── slug.ts # generateSlug (rejection-sampling), isValidSlug, isReservedSlug, RESERVED_SLUGS │ │ │ ├── totp.ts # TOTP generate/verify with otpauth library @@ -228,7 +229,7 @@ All set via the Cloudflare dashboard (Variables and Secrets). `keep_vars = true` | `APP_NAME` | Yes | Default app name (overridable in admin UI) | | `RP_ID` | Yes | WebAuthn relying party ID (domain only, no protocol) | | `APP_ORIGIN` | Yes | WebAuthn origin (full URL with protocol) | -| `TABLE_PREFIX` | No | Prefix for all D1 table names (e.g. `sl` → `sl_users`, `sl_links`, …). Default: empty (no prefix). Must be configured **before** running the setup route — changing it after initial setup requires renaming all tables manually. Only alphanumeric and underscore characters are used; all others are stripped. | +| `TABLE_PREFIX` | No | Three-state prefix for all D1 table names. Unset → default `sl` (`sl_users`, `sl_links`, …); a custom value → that value (case preserved, `[^a-zA-Z0-9_]` stripped); explicit empty string → no prefix (deployer accepts table-collision risk). Must be configured **before** running the setup route — changing it after initial setup requires renaming all tables manually. On GitHub Actions, `none` is the reserved word for the explicit empty string (unset/empty both become the default `sl`). A silent switch (database initialised under a different prefix) aborts setup/migrations with an error. | Email sender config and API keys are managed in the **admin UI settings**, not here. @@ -245,7 +246,7 @@ Two files in `apps/worker/migrations/`: **HTTP setup route (production):** The public initialization page lives at `/setup` (an SPA route). `POST /api/setup` with a JSON body `{"secret": ""}` runs migrations via the shared `lib/migrations-runner.ts` (`runMigrations`). Two migrations: -- `schema_v1` — identical DDL as `0001_init.sql`, but parameterized by `TABLE_PREFIX` and tracked in `_schema_migrations` table +- `schema_v1` — identical DDL as `0001_init.sql`, but parameterized by `TABLE_PREFIX` and tracked in `__schema_migrations` table - `schema_v2` — adds `token_version` to `users` (mirrors `0002_token_version.sql`) The legacy `X-Setup-Secret` header is still accepted when the body is empty. The endpoint is rate-limited to 3 attempts per IP per 10 minutes (counted before the secret check; a `429` carries a `Retry-After` header). `GET /api/setup/state` (public) reports `{ enabled }` from the `setup_page_enabled` setting (default enabled); `GET /api/setup/*` returns `405` pointing at the POST form. An admin can run the same migrations keylessly via `POST /api/admin/setup` (no IP rate limit; writes an audit log entry). `setup_page_enabled` only hides the setup page — it never disables the `POST` migration channel. diff --git a/README.md b/README.md index 69ee63a..061cdb3 100644 --- a/README.md +++ b/README.md @@ -77,7 +77,7 @@ Go to [Cloudflare dashboard](https://dash.cloudflare.com) → **Workers & Pages | `APP_NAME` | Variable | Yes | `ShortLink` — default app name, overridable in admin UI | | `RP_ID` | Variable | Yes | `yourdomain.com` — WebAuthn relying party ID (domain only) | | `APP_ORIGIN` | Variable | Yes | `https://yourdomain.com` — WebAuthn origin (full URL) | -| `TABLE_PREFIX` | Variable | No | e.g. `sl` — prefixes all D1 table names (`sl_users`, `sl_links`, …). Must be set **before** running the setup route. Leave empty to use unprefixed names. | +| `TABLE_PREFIX` | Variable | No | Three-state table prefix. Unset → default `sl` (`sl_users`, `sl_links`, …). A custom value → that value, case preserved, `[^a-zA-Z0-9_]` stripped. Explicit empty string → no prefix (deployer accepts the table-collision risk). Set **before** first setup and never change it once data exists. | | `JWT_SECRET` | Secret | Yes | Any random string ≥ 32 chars | | `TOTP_ENCRYPTION_KEY` | Secret | Yes | `openssl rand -hex 32` | | `SETUP_SECRET` | Secret | Yes | `openssl rand -hex 24` — used to trigger migrations | @@ -101,6 +101,17 @@ the setup route runs), skips those already recorded in `__schema_migrati and prints the planned migrations in the log. Migrations must stay backward compatible: only add tables, indexes or columns — never drop, rename or rewrite existing data. +GitHub Actions cannot distinguish an unset `vars.TABLE_PREFIX` from an empty one, so +the deploy workflow resolves it to the three runtime states: **unset or empty → `sl`** +(the default), **`none` → explicit empty string** (no prefix), **anything else → as-is**. + +> **Upgrade warning** — a legacy deployment that never set a prefix used unprefixed +> tables. If the resolved prefix differs from the prefix the database was initialised +> under, setup and migrations **abort with an error** instead of silently switching to +> a different (usually empty) set of tables. Configure `TABLE_PREFIX` to its previous +> value (`TABLE_PREFIX=''`, or `TABLE_PREFIX=none` in CI, to keep unprefixed tables) +> before upgrading. + When using a prefix, set `TABLE_PREFIX` under the GitHub **production environment → Variables** to exactly the same value as the Worker's `TABLE_PREFIX` **plain-text variable** in Cloudflare (e.g. `SL`; letters, digits and underscores only). Do not store @@ -284,7 +295,7 @@ All variables and secrets are managed in the **Cloudflare dashboard** (Workers & | `APP_NAME` | Var | Yes | Default app name; overridable in admin UI | | `RP_ID` | Var | Yes | WebAuthn relying party ID (domain without protocol) | | `APP_ORIGIN` | Var | Yes | WebAuthn origin (full URL) | -| `TABLE_PREFIX` | Var | No | Prefix for all D1 table names (e.g. `sl` → `sl_users`, `sl_links`, …). Set once before the first migration — changing it later requires manually renaming tables. Only alphanumeric and underscore characters are used. | +| `TABLE_PREFIX` | Var | No | Three-state prefix for all D1 table names. Unset → default `sl` (`sl_users`, `sl_links`, …); custom value → that value (case preserved); explicit empty → no prefix. Set once before the first migration — changing it later requires renaming tables. Only alphanumeric and underscore characters are used. | | `JWT_SECRET` | Secret | Yes | HS256 signing key, ≥ 32 chars | | `TOTP_ENCRYPTION_KEY` | Secret | Yes | Hex string from `openssl rand -hex 32` | | `SETUP_SECRET` | Secret | Yes | Secret path for triggering DB migrations via HTTP | diff --git a/README.zh-CN.md b/README.zh-CN.md index e172425..41de71d 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -78,7 +78,7 @@ | `APP_NAME` | Variable | 是 | `ShortLink` — 默认应用名称,可在管理界面覆盖 | | `RP_ID` | Variable | 是 | `yourdomain.com` — WebAuthn 依赖方 ID(仅域名) | | `APP_ORIGIN` | Variable | 是 | `https://yourdomain.com` — WebAuthn 来源(完整 URL) | -| `TABLE_PREFIX` | Variable | 否 | 例如 `sl` — 为所有 D1 表名添加前缀(`sl_users`、`sl_links` 等)。必须在运行 setup 路由**之前**设置。留空则使用无前缀名称。 | +| `TABLE_PREFIX` | Variable | 否 | 三态表前缀。未配置 → 默认 `sl`(`sl_users`、`sl_links` 等);配置自定义值 → 该值(保留大小写,剔除 `[^a-zA-Z0-9_]`);显式配置为空字符串 → 无前缀(部署者自担撞表风险)。必须在**首次** setup 前设置,一旦有数据后不得更改。 | | `JWT_SECRET` | Secret | 是 | 任意长度 ≥ 32 字符的随机字符串 | | `TOTP_ENCRYPTION_KEY` | Secret | 是 | `openssl rand -hex 32` | | `SETUP_SECRET` | Secret | 是 | `openssl rand -hex 24` — 用于触发迁移 | @@ -102,6 +102,10 @@ GitHub Actions 会在部署代码**之前**自动执行迁移:无前缀时仍 `apps/worker/src/lib/migrations.ts`,按 `__schema_migrations` 跳过已执行项, 并在日志中打印待执行计划。迁移必须向后兼容,只添加表、索引或列,不删除、重命名或修改现有数据。 +GitHub Actions 无法区分「未设置的 `vars.TABLE_PREFIX`」与「空字符串」,因此部署脚本按三态约定解析:**未设置或为空 → 默认 `sl`**;**保留字 `none` → 显式空字符串**(无前缀);**其他值 → 原样使用**。 + +> **升级警告** — 从未配置过前缀的旧部署使用无前缀表。若解析出的前缀与库中已初始化的前缀不一致,setup 与迁移会**中止报错**,而不是静默切换到另一套(通常是空的)表。升级前请先把 `TABLE_PREFIX` 配成原值(保持无前缀则配置 `TABLE_PREFIX=''`,CI 中为 `TABLE_PREFIX=none`)。 + 使用前缀时,在 GitHub 的 **production environment → Variables** 中设置 `TABLE_PREFIX`,与 Cloudflare Worker 的同名**明文变量**完全一致(例如 `SL`,仅字母、数字和下划线)。 不要把它设为 Secret,也不要在已有数据后更换前缀。GitHub 中的 `APP_URL` 也必须指向生产地址。 @@ -276,7 +280,7 @@ GET /:slug → 302 跳转到目标 URL | `APP_NAME` | 变量 | 是 | 默认应用名称;可在管理界面覆盖 | | `RP_ID` | 变量 | 是 | WebAuthn 依赖方 ID(不含协议的域名) | | `APP_ORIGIN` | 变量 | 是 | WebAuthn 来源(完整 URL) | -| `TABLE_PREFIX` | 变量 | 否 | 所有 D1 表名的前缀(例如 `sl` → `sl_users`、`sl_links` 等)。在第一次迁移前设置一次 — 之后更改需手动重命名所有表。只使用字母数字和下划线字符。 | +| `TABLE_PREFIX` | 变量 | 否 | 所有 D1 表名的三态前缀。未配置 → 默认 `sl`(`sl_users`、`sl_links` 等);自定义值 → 该值(保留大小写);显式空 → 无前缀。在第一次迁移前设置一次 — 之后更改需手动重命名所有表。只使用字母数字和下划线字符。 | | `JWT_SECRET` | 密钥 | 是 | HS256 签名密钥,≥ 32 字符 | | `TOTP_ENCRYPTION_KEY` | 密钥 | 是 | 来自 `openssl rand -hex 32` 的十六进制字符串 | | `SETUP_SECRET` | 密钥 | 是 | 通过 HTTP 触发数据库迁移的密钥路径 | diff --git a/apps/web/src/i18n/locales/en.ts b/apps/web/src/i18n/locales/en.ts index 7561afd..38961dc 100644 --- a/apps/web/src/i18n/locales/en.ts +++ b/apps/web/src/i18n/locales/en.ts @@ -214,6 +214,7 @@ export const en = { errorTooManyRequests: 'Too many requests. Try again in {{seconds}}s.', errorServer: 'The server is not configured, or the migration failed.', errorNotFound: 'The backend has not provided this endpoint yet.', + errorConflict: 'Table prefix conflict: {{message}}', errorGeneric: 'Setup failed. Please try again.', }, admin: { diff --git a/apps/web/src/i18n/locales/zh-CN.ts b/apps/web/src/i18n/locales/zh-CN.ts index 3196ac6..a3227ff 100644 --- a/apps/web/src/i18n/locales/zh-CN.ts +++ b/apps/web/src/i18n/locales/zh-CN.ts @@ -207,6 +207,7 @@ export const zhCN: Translations = { errorTooManyRequests: '请求过于频繁,请在 {{seconds}} 秒后重试。', errorServer: '服务端未配置密钥,或迁移执行失败。', errorNotFound: '后端尚未提供该接口。', + errorConflict: '表前缀冲突:{{message}}', errorGeneric: '初始化失败,请重试。', }, admin: { diff --git a/apps/web/src/lib/setup.test.ts b/apps/web/src/lib/setup.test.ts index b269630..eb26c11 100644 --- a/apps/web/src/lib/setup.test.ts +++ b/apps/web/src/lib/setup.test.ts @@ -149,6 +149,21 @@ describe('resolveSetupError', () => { }); }); + test('maps a 409 table-prefix conflict, passing through the backend message', () => { + assert.deepEqual( + resolveSetupError({ + status: 409, + message: 'the database already contains an unprefixed schema', + }), + { + key: 'setup.errorConflict', + params: { + message: 'the database already contains an unprefixed schema', + }, + }, + ); + }); + test('falls back to the generic key for unmatched errors', () => { assert.deepEqual(resolveSetupError(new Error('boom')), { key: 'setup.errorGeneric', diff --git a/apps/web/src/lib/setup.ts b/apps/web/src/lib/setup.ts index 4d9377b..fd982ea 100644 --- a/apps/web/src/lib/setup.ts +++ b/apps/web/src/lib/setup.ts @@ -67,6 +67,13 @@ export function resolveSetupError(error: unknown): SetupErrorMsg | null { return { key: 'setup.errorForbidden' }; case 404: return { key: 'setup.errorNotFound' }; + case 409: + // Table-prefix silent-switch conflict: pass the backend's actionable + // message through so the operator sees exactly which TABLE_PREFIX to set. + return { + key: 'setup.errorConflict', + params: { message: e.message ?? '' }, + }; case 429: return { key: 'setup.errorTooManyRequests', diff --git a/apps/worker/src/lib/db.ts b/apps/worker/src/lib/db.ts index d362309..f462945 100644 --- a/apps/worker/src/lib/db.ts +++ b/apps/worker/src/lib/db.ts @@ -1,11 +1,12 @@ -// Database table name helper — applies TABLE_PREFIX from env. -// The prefix is sanitized (alphanumeric + underscore only) to prevent SQL issues. -// TABLE_PREFIX is read-only at deploy time; changing it after initial setup requires -// migrating data to the new table names. +// Database table name helper — applies TABLE_PREFIX from env. The three-state +// resolution and the default constant live in table-prefix.ts (single source of +// truth); TABLE_PREFIX is read-only at deploy time, so changing it after initial +// setup requires migrating data to the new table names. + +import { tbl as applyPrefix, resolveTablePrefix } from './table-prefix.js'; export function tbl(env: { TABLE_PREFIX?: string }, name: string): string { - const prefix = (env.TABLE_PREFIX ?? '').replace(/[^a-zA-Z0-9_]/g, ''); - return prefix ? `${prefix}_${name}` : name; + return applyPrefix(resolveTablePrefix(env.TABLE_PREFIX), name); } // BE-C3: True when a D1 error is a UNIQUE constraint violation. D1 surfaces the diff --git a/apps/worker/src/lib/migrations-runner.ts b/apps/worker/src/lib/migrations-runner.ts index 7b82a97..0559312 100644 --- a/apps/worker/src/lib/migrations-runner.ts +++ b/apps/worker/src/lib/migrations-runner.ts @@ -4,6 +4,7 @@ import { getMigrations, migrationsTable, } from './migrations.js'; +import { resolveTablePrefix } from './table-prefix.js'; // Shared schema-migration execution, parameterised by TABLE_PREFIX. Both the // secret-keyed HTTP endpoint (routes/setup.ts → POST /api/setup) and the @@ -17,9 +18,128 @@ export interface MigrationResult { } export interface RunMigrationsResult { + // The effective table prefix that was resolved for this run ('' when the + // deployer explicitly configured no prefix). + prefix: string; migrations: MigrationResult[]; } +// Thrown when the database already contains an initialised schema under a +// different prefix than the one resolved from the environment — migrating +// would silently switch the app to a different (usually empty) set of tables. +export class TablePrefixConflictError extends Error { + constructor(message: string) { + super(message); + this.name = 'TablePrefixConflictError'; + } +} + +// Tables that are unique to this app across the shared D1 database. Other apps +// sharing the database (ZETA_*, eNotify_*, …) have none of these three, so their +// presence under one prefix marks a shortlink schema. Never used for +// single-table matching. +const SHORTLINK_UNIQUE_SUFFIXES = ['passkeys', 'links', 'totp_used'] as const; + +// Collects the prefixes under which a shortlink schema appears to be +// initialised: either a prefixed migration-history table +// (`__schema_migrations`) or the intersection of the shortlink-unique +// tables under the same prefix. +function detectPrefixedSchema(names: string[]): string[] { + const prefixes = new Set(); + + for (const n of names) { + const m = /^_([A-Za-z0-9_]+)_schema_migrations$/.exec(n); + if (m !== null) prefixes.add(m[1] ?? ''); + } + + const byPrefix = new Map>(); + for (const n of names) { + const m = /^([A-Za-z0-9_]+)_(passkeys|links|totp_used)$/.exec(n); + if (m === null) continue; + const prefix = m[1] ?? ''; + const suffix = m[2] ?? ''; + let suffixes = byPrefix.get(prefix); + if (suffixes === undefined) { + suffixes = new Set(); + byPrefix.set(prefix, suffixes); + } + suffixes.add(suffix); + } + for (const [prefix, suffixes] of byPrefix) { + const unique = SHORTLINK_UNIQUE_SUFFIXES as readonly string[]; + if (unique.every((s) => suffixes.has(s))) { + prefixes.add(prefix); + } + } + + return [...prefixes]; +} + +// Returns a human-readable description of a conflicting already-initialised +// schema, or null when the database is safe to migrate under `prefix`. +// Read-only: never writes to the database. +async function detectTablePrefixConflict( + db: Pick['DB'], + prefix: string, +): Promise { + const { results } = await db + .prepare("SELECT name FROM sqlite_master WHERE type = 'table'") + .all<{ name: string }>(); + const names = results.map((r) => r.name); + const has = (t: string) => + names.some((n) => n.toLowerCase() === t.toLowerCase()); + + // An unprefixed schema of this app: the legacy setup route records its + // history in `_schema_migrations`, and wrangler's unprefixed path in + // `d1_migrations`. A bare `users` table alone is NOT a signal — the shared + // D1 database can carry other apps' tables. + let hasUnprefixed = has('d1_migrations'); + if (has('_schema_migrations')) { + const history = await db + .prepare('SELECT name FROM _schema_migrations') + .all<{ name: string }>(); + hasUnprefixed = + hasUnprefixed || history.results.some((r) => r.name === 'schema_v1'); + } + + if (prefix !== '') { + // Already initialised under this prefix → an incremental/idempotent + // migration, not a silent switch. Allow it. + if (has(migrationsTable(prefix))) { + return null; + } + // Current prefix not initialised, but an unprefixed schema of this app + // exists → switching would point at a new set of tables. + if (hasUnprefixed) { + return ( + `the database already contains an unprefixed schema (` + + `_schema_migrations / d1_migrations), but TABLE_PREFIX resolves to '${prefix}'. ` + + `Refusing to initialise a new '${prefix}'-prefixed schema. ` + + `To keep the existing unprefixed schema, explicitly configure ` + + `TABLE_PREFIX='' (or TABLE_PREFIX=none in CI).` + ); + } + return null; + } + + // Resolving to no prefix: already-unprefixed is legal (incremental); a + // prefixed schema of this app is a switch and must abort. + if (hasUnprefixed) { + return null; + } + const detected = detectPrefixedSchema(names); + if (detected.length > 0) { + return ( + `the database already contains a prefixed schema ` + + `(${detected.map((p) => `${p}_*`).join(', ')}), but TABLE_PREFIX resolves ` + + `to an empty string (no prefix). Refusing to initialise an unprefixed ` + + `schema. To keep the existing prefixed schema, configure TABLE_PREFIX to ` + + `its current value (e.g. TABLE_PREFIX=${detected[0]}).` + ); + } + return null; +} + // D1's exec() only processes the first line of a multi-line string. // Strip SQL line comments and collapse all whitespace to a single line. function toSingleLine(sql: string): string { @@ -40,7 +160,15 @@ function toSingleLine(sql: string): string { export async function runMigrations( env: Pick, ): Promise { - const prefix = env.TABLE_PREFIX ?? ''; + const prefix = resolveTablePrefix(env.TABLE_PREFIX); + + // Silent-switch guard (highest priority): never initialise a schema under a + // different prefix than the one the database already holds. + const conflict = await detectTablePrefixConflict(env.DB, prefix); + if (conflict !== null) { + throw new TablePrefixConflictError(conflict); + } + const historyTable = migrationsTable(prefix); // Use prepare().run() for single-statement DDL — avoids exec()'s newline limitation @@ -74,5 +202,5 @@ export async function runMigrations( } } - return { migrations }; + return { prefix, migrations }; } diff --git a/apps/worker/src/lib/migrations.ts b/apps/worker/src/lib/migrations.ts index a16c9e3..0c383bf 100644 --- a/apps/worker/src/lib/migrations.ts +++ b/apps/worker/src/lib/migrations.ts @@ -1,19 +1,19 @@ // Schema migrations, parameterised by TABLE_PREFIX. Single source of truth for // both the HTTP setup route (routes/setup.ts) and the deploy workflow // (.github/scripts/d1-migrations.mjs loads this file with Node's built-in -// TypeScript type stripping) — so keep it free of imports and of TS-only -// runtime syntax (enums, namespaces, parameter properties). +// TypeScript type stripping) — so keep it free of imports other than the +// type-strippable table-prefix.ts, and of TS-only runtime syntax (enums, +// namespaces, parameter properties). // // Migrations must stay additive (CREATE TABLE/INDEX IF NOT EXISTS, ALTER TABLE // ADD COLUMN, INSERT OR IGNORE): the deploy workflow runs them before the new // code goes live, and its guard rejects anything else. -// ─── Table-prefix helper (mirrors src/lib/db.ts) ────────────────────────────── +// ─── Table-prefix helper (single source: src/lib/table-prefix.ts) ──────────── -export function tbl(prefix: string, name: string): string { - const p = prefix.replace(/[^a-zA-Z0-9_]/g, ''); - return p ? `${p}_${name}` : name; -} +import { DEFAULT_TABLE_PREFIX, tbl } from './table-prefix.ts'; + +export { DEFAULT_TABLE_PREFIX, tbl }; // Name of the table recording applied migrations, e.g. `_SL_schema_migrations`. export function migrationsTable(prefix: string): string { diff --git a/apps/worker/src/lib/table-prefix.ts b/apps/worker/src/lib/table-prefix.ts new file mode 100644 index 0000000..3b1e404 --- /dev/null +++ b/apps/worker/src/lib/table-prefix.ts @@ -0,0 +1,27 @@ +// Single source of truth for the project's TABLE_PREFIX semantics. +// +// Three states, distinguished at the call site by whether TABLE_PREFIX is +// `undefined` versus the empty string: +// undefined → DEFAULT_TABLE_PREFIX ('sl') +// '' → '' (no prefix — the deployer accepts the table-collision risk) +// any other → the value with [^a-zA-Z0-9_] stripped, case preserved +// +// Keep this file free of imports and of TS-only runtime syntax: it is loaded by +// .github/scripts/d1-migrations.mjs (through migrations.ts) via Node's built-in +// TypeScript type stripping. + +export const DEFAULT_TABLE_PREFIX = 'sl'; + +// Three-state resolution of a raw TABLE_PREFIX value. +export function resolveTablePrefix(raw: string | undefined): string { + const source = raw === undefined ? DEFAULT_TABLE_PREFIX : raw; + return source.replace(/[^a-zA-Z0-9_]/g, ''); +} + +// Applies a resolved prefix to a table name, adding the trailing underscore. +// Sanitising here too is idempotent with resolveTablePrefix and keeps table +// names safe even when a raw prefix is passed straight in. +export function tbl(prefix: string, name: string): string { + const p = prefix.replace(/[^a-zA-Z0-9_]/g, ''); + return p ? `${p}_${name}` : name; +} diff --git a/apps/worker/src/routes/admin.ts b/apps/worker/src/routes/admin.ts index 081f16a..646e625 100644 --- a/apps/worker/src/routes/admin.ts +++ b/apps/worker/src/routes/admin.ts @@ -9,7 +9,10 @@ import { getCachedSetting, setCachedSetting, } from '../lib/kv.js'; -import { runMigrations } from '../lib/migrations-runner.js'; +import { + runMigrations, + TablePrefixConflictError, +} from '../lib/migrations-runner.js'; import { parsePagination } from '../lib/params.js'; import { requireAdmin } from '../middleware/auth.js'; import type { Env, LinkRow, UserRow, Variables } from '../types.js'; @@ -615,7 +618,16 @@ admin.delete('/links/:id', async (c) => { // first-time setup; the initial setup still happens through POST /api/setup. admin.post('/setup', async (c) => { const adminId = c.get('userId'); - const result = await runMigrations(c.env); + + let result: Awaited>; + try { + result = await runMigrations(c.env); + } catch (err) { + if (err instanceof TablePrefixConflictError) { + return c.json({ error: err.message }, 409); + } + throw err; + } const applied = result.migrations.filter( (m) => m.status === 'applied', diff --git a/apps/worker/src/routes/setup.ts b/apps/worker/src/routes/setup.ts index 9b13044..cc87281 100644 --- a/apps/worker/src/routes/setup.ts +++ b/apps/worker/src/routes/setup.ts @@ -2,7 +2,10 @@ import { Hono } from 'hono'; import { constantTimeEqual } from '../lib/crypto.js'; import { tbl } from '../lib/db.js'; import { checkSetupRateLimit } from '../lib/kv.js'; -import { runMigrations } from '../lib/migrations-runner.js'; +import { + runMigrations, + TablePrefixConflictError, +} from '../lib/migrations-runner.js'; import type { Env, Variables } from '../types.js'; const app = new Hono<{ Bindings: Env; Variables: Variables }>(); @@ -101,7 +104,14 @@ app.post('/', async (c) => { return c.json({ error: 'Invalid setup secret.' }, 403); } - return c.json(await runMigrations(c.env)); + try { + return c.json(await runMigrations(c.env)); + } catch (err) { + if (err instanceof TablePrefixConflictError) { + return c.json({ error: err.message }, 409); + } + throw err; + } }); export default app; diff --git a/apps/worker/test/migrations-runner.test.ts b/apps/worker/test/migrations-runner.test.ts new file mode 100644 index 0000000..8b7edc1 --- /dev/null +++ b/apps/worker/test/migrations-runner.test.ts @@ -0,0 +1,149 @@ +// Silent-switch guard + three-state resolution for the shared migration runner +// (ONE-203 / ONE-205). +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import { + createMigrationsTableSql, + getMigrations, + migrationsTable, +} from '../src/lib/migrations.ts'; +import { + runMigrations, + TablePrefixConflictError, +} from '../src/lib/migrations-runner.ts'; +import { D1Mock } from './helpers/env.ts'; + +// A database initialised under `prefix`: schema + migration history with every +// migration already recorded as applied. +function initializedDb(prefix: string): D1Mock { + const db = new D1Mock(false); + db.exec(createMigrationsTableSql(prefix)); + for (const migration of getMigrations(prefix)) { + db.exec(migration.sql); + db.prepare(`INSERT INTO ${migrationsTable(prefix)} (name) VALUES (?)`) + .bind(migration.name) + .run(); + } + return db; +} + +test('runMigrations 返回实际生效前缀(未配置 → sl)', async () => { + const db = new D1Mock(false); + const result = await runMigrations({ + DB: db as unknown as never, + TABLE_PREFIX: undefined, + }); + assert.equal(result.prefix, 'sl'); + assert.deepEqual( + result.migrations.map((m) => [m.name, m.status]), + [ + ['schema_v1', 'applied'], + ['schema_v2', 'applied'], + ], + ); +}); + +test('runMigrations 返回实际生效前缀(显式空 → 无前缀)', async () => { + const db = new D1Mock(false); + const result = await runMigrations({ + DB: db as unknown as never, + TABLE_PREFIX: '', + }); + assert.equal(result.prefix, ''); +}); + +test('防静默切换:未配置(→ sl)但库中已有无前缀 schema → 中止报错', async () => { + const db = initializedDb(''); + await assert.rejects( + runMigrations({ DB: db as unknown as never, TABLE_PREFIX: undefined }), + (err: unknown) => { + assert.ok(err instanceof TablePrefixConflictError); + assert.match((err as Error).message, /unprefixed schema/); + assert.match((err as Error).message, /TABLE_PREFIX=''/); + return true; + }, + ); +}); + +test('防静默切换:显式空前缀但库中已有 prefixed schema → 中止报错', async () => { + const db = initializedDb('sl'); + await assert.rejects( + runMigrations({ DB: db as unknown as never, TABLE_PREFIX: '' }), + (err: unknown) => { + assert.ok(err instanceof TablePrefixConflictError); + assert.match((err as Error).message, /prefixed schema/); + assert.match((err as Error).message, /sl_\*/); + return true; + }, + ); +}); + +test('前缀一致时不误报:prefixed schema + 同名前缀正常迁移', async () => { + const db = initializedDb('sl'); + const result = await runMigrations({ + DB: db as unknown as never, + TABLE_PREFIX: 'sl', + }); + assert.equal(result.prefix, 'sl'); + assert.deepEqual( + result.migrations.map((m) => m.status), + ['skipped', 'skipped'], + ); +}); + +test('前缀一致时不误报:unprefixed schema + 显式空前缀正常迁移', async () => { + const db = initializedDb(''); + const result = await runMigrations({ + DB: db as unknown as never, + TABLE_PREFIX: '', + }); + assert.equal(result.prefix, ''); + assert.deepEqual( + result.migrations.map((m) => m.status), + ['skipped', 'skipped'], + ); +}); + +test('migrationsTable 与迁移 helper 共用前缀语义', () => { + assert.equal(migrationsTable(''), '_schema_migrations'); + assert.equal(migrationsTable('sl'), '_sl_schema_migrations'); + assert.equal(migrationsTable('SL'), '_SL_schema_migrations'); +}); + +// ─── 回归:共享库他表 + 三态边界(ONE-206 修复)───────────────────────────── + +test('回归:共享库他表 bare users + shortlink 已有前缀 → 增量放行不误杀', async () => { + const db = initializedDb('SL'); + // 他应用留下的 bare users 表,不应触发防静默切换误判。 + db.exec('CREATE TABLE users (id TEXT PRIMARY KEY);'); + const result = await runMigrations({ + DB: db as unknown as never, + TABLE_PREFIX: 'SL', + }); + assert.equal(result.prefix, 'SL'); + assert.deepEqual( + result.migrations.map((m) => m.status), + ['skipped', 'skipped'], + ); +}); + +test('回归:共享库他表(ZETA_*/eNotify_*)+ 显式空前缀 → 不误判为前缀', async () => { + const db = new D1Mock(false); + // 仅他应用的前缀表,shortlink 自身无任何 schema;显式空前缀应放行。 + db.exec( + 'CREATE TABLE ZETA_links (id TEXT, slug TEXT);' + + 'CREATE TABLE eNotify_settings (key TEXT, value TEXT);', + ); + const result = await runMigrations({ + DB: db as unknown as never, + TABLE_PREFIX: '', + }); + assert.equal(result.prefix, ''); + assert.deepEqual( + result.migrations.map((m) => [m.name, m.status]), + [ + ['schema_v1', 'applied'], + ['schema_v2', 'applied'], + ], + ); +}); diff --git a/apps/worker/test/setup.test.ts b/apps/worker/test/setup.test.ts index 29f7fce..67b936c 100644 --- a/apps/worker/test/setup.test.ts +++ b/apps/worker/test/setup.test.ts @@ -125,6 +125,29 @@ test('POST /api/setup: 密钥错误返回 403', async () => { assert.match((await res.json()).error, /Invalid setup secret/); }); +test('POST /api/setup: 库中已初始化在其他前缀下 → 409 中止并提示显式配置', async () => { + const ctx = makeEnv({ TABLE_PREFIX: undefined }); + // 无前缀 schema 已初始化(含 _schema_migrations 历史),未配置前缀解析为 sl。 + ctx.db.exec(createMigrationsTableSql('')); + ctx.db + .prepare(`INSERT INTO ${migrationsTable('')} (name) VALUES (?)`) + .bind('schema_v1') + .run(); + const res = await request( + app, + '/api/setup', + json( + { secret: 'test-setup-secret' }, + { 'cf-connecting-ip': '{{IP_prefix_conflict}}' }, + ), + ctx, + ); + assert.equal(res.status, 409); + const body = await res.json(); + assert.match(body.error, /unprefixed schema/); + assert.match(body.error, /TABLE_PREFIX=''/); +}); + test('POST /api/setup: SETUP_SECRET 未配置返回 500', async () => { const ctx = makeEnv({ SETUP_SECRET: '' }); const res = await request( diff --git a/apps/worker/test/table-prefix.test.ts b/apps/worker/test/table-prefix.test.ts new file mode 100644 index 0000000..915994b --- /dev/null +++ b/apps/worker/test/table-prefix.test.ts @@ -0,0 +1,48 @@ +// Three-state TABLE_PREFIX resolution (ONE-203 / ONE-205). +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import { tbl } from '../src/lib/db.ts'; +import { + tbl as applyPrefix, + DEFAULT_TABLE_PREFIX, + resolveTablePrefix, +} from '../src/lib/table-prefix.ts'; + +test('默认前缀常量是 sl', () => { + assert.equal(DEFAULT_TABLE_PREFIX, 'sl'); +}); + +test('三态解析:未配置(undefined)→ 默认 sl', () => { + assert.equal(resolveTablePrefix(undefined), 'sl'); +}); + +test('三态解析:显式空字符串 → 无前缀', () => { + assert.equal(resolveTablePrefix(''), ''); +}); + +test('三态解析:自定义值原样保留(含大小写)', () => { + assert.equal(resolveTablePrefix('SL'), 'SL'); + assert.equal(resolveTablePrefix('sl'), 'sl'); + assert.equal(resolveTablePrefix('ZETA'), 'ZETA'); +}); + +test('三态解析:自定义值仅剔除非法字符,不改大小写', () => { + assert.equal(resolveTablePrefix('SL-x'), 'SLx'); + assert.equal(resolveTablePrefix('a_b-c'), 'a_bc'); + assert.equal(resolveTablePrefix('x.y_z!'), 'xy_z'); +}); + +test('tbl 在表名前补下划线,无前缀则原样返回', () => { + assert.equal(applyPrefix('sl', 'users'), 'sl_users'); + assert.equal(applyPrefix('SL', 'users'), 'SL_users'); + assert.equal(applyPrefix('', 'users'), 'users'); + // 即使直接传入未清洗的前缀也保持安全 + assert.equal(applyPrefix('sl-x', 'users'), 'slx_users'); +}); + +test('db.ts 的 tbl(env, name) 走同一三态解析', () => { + assert.equal(tbl({ TABLE_PREFIX: undefined }, 'users'), 'sl_users'); + assert.equal(tbl({}, 'users'), 'sl_users'); + assert.equal(tbl({ TABLE_PREFIX: '' }, 'users'), 'users'); + assert.equal(tbl({ TABLE_PREFIX: 'SL' }, 'users'), 'SL_users'); +}); diff --git a/apps/worker/tsconfig.json b/apps/worker/tsconfig.json index 06edded..5ebeb88 100644 --- a/apps/worker/tsconfig.json +++ b/apps/worker/tsconfig.json @@ -7,6 +7,8 @@ "types": ["@cloudflare/workers-types"], "strict": true, "noUncheckedIndexedAccess": true, + "noEmit": true, + "allowImportingTsExtensions": true, "skipLibCheck": true, "outDir": "./dist", "rootDir": "./src", diff --git a/turbo.json b/turbo.json index fa1de95..e0bce4d 100644 --- a/turbo.json +++ b/turbo.json @@ -1,5 +1,6 @@ { "$schema": "https://turbo.build/schema.json", + "globalPassThroughEnv": ["TABLE_PREFIX"], "tasks": { "build": { "dependsOn": ["^build"],