diff --git a/.github/scripts/d1-migration-files.mjs b/.github/scripts/d1-migration-files.mjs new file mode 100644 index 0000000..a1186f3 --- /dev/null +++ b/.github/scripts/d1-migration-files.mjs @@ -0,0 +1,31 @@ +// Prints this app's Wrangler migration file names (apps/worker/migrations/*.sql), +// one per line, for the deploy scripts' anti-silent-switch guards. +// +// Wrangler's `d1_migrations` ledger is a database-wide singleton table: any +// other application on the shared D1 database that ever ran +// `wrangler d1 migrations apply` leaves it behind, recording *that* app's file +// names. Its mere existence therefore says nothing about an unprefixed schema +// of this app — only an intersection with this list does. +// +// The migrations directory is the single source of truth on the deploy side +// (enumerated here so no script carries a hardcoded list); the runtime +// equivalent is WRANGLER_MIGRATION_FILES in apps/worker/src/lib/migrations.ts, +// and apps/worker/test/migrations-runner.test.ts asserts the two are equal, so +// a drift between them fails CI. +import { readdirSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; + +const dir = fileURLToPath( + new URL('../../apps/worker/migrations/', import.meta.url), +); + +const files = readdirSync(dir) + .filter((name) => name.endsWith('.sql')) + .sort(); + +if (files.length === 0) { + console.error(`No migration files found in ${dir}`); + process.exit(1); +} + +process.stdout.write(`${files.join('\n')}\n`); diff --git a/.github/scripts/d1-prefixed-migrations.sh b/.github/scripts/d1-prefixed-migrations.sh index 4a1941e..ad0d3e6 100644 --- a/.github/scripts/d1-prefixed-migrations.sh +++ b/.github/scripts/d1-prefixed-migrations.sh @@ -45,6 +45,27 @@ while IFS= read -r name; do done < <(jq -r '.migrations[].name' <<<"$plan") tables="$(d1_query "SELECT name FROM sqlite_master WHERE type = 'table'")" + +# This app's Wrangler migration file names (apps/worker/migrations/*.sql), +# enumerated on the spot so the list can never drift from the directory. +app_migration_files="$(node --disable-warning=MODULE_TYPELESS_PACKAGE_JSON "$here/d1-migration-files.mjs")" + +# True when Wrangler's `d1_migrations` ledger records at least one of THIS app's +# migration files. The table alone is no signal: it is a database-wide +# singleton, so any other app on the shared D1 database that ever ran +# `wrangler d1 migrations apply` leaves it behind with that app's file names. +has_app_migration_history() { + grep -qx d1_migrations <<<"$tables" || return 1 + local applied name + applied="$(d1_query "SELECT name FROM d1_migrations")" + while IFS= read -r name; do + if grep -qxF "$name" <<<"$applied"; then + return 0 + fi + done <<<"$app_migration_files" + return 1 +} + # SQLite identifiers are case-insensitive, so match the prefix the same way. own_tables="$(grep -i "^${prefix}_" <<<"$tables" || true)" has_history=false @@ -88,10 +109,11 @@ elif [[ -n "$own_tables" ]]; then 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 + # or Wrangler's `d1_migrations` holding this app's own migration files) 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, and so does a `d1_migrations` ledger written by another app. + if has_app_migration_history || (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 diff --git a/.github/scripts/d1-prepare-migrations.sh b/.github/scripts/d1-prepare-migrations.sh index a33ae51..b115e58 100755 --- a/.github/scripts/d1-prepare-migrations.sh +++ b/.github/scripts/d1-prepare-migrations.sh @@ -52,15 +52,36 @@ tables="$(d1_query "SELECT name FROM sqlite_master WHERE type = 'table'")" has_table() { grep -qx "$1" <<<"$tables"; } has_table_i() { grep -qixF "$1" <<<"$tables"; } +# This app's Wrangler migration file names (apps/worker/migrations/*.sql), +# enumerated on the spot so the list can never drift from the directory. +app_migration_files="$(node --disable-warning=MODULE_TYPELESS_PACKAGE_JSON "$here/d1-migration-files.mjs")" + +# True when Wrangler's `d1_migrations` ledger records at least one of THIS app's +# migration files. The table alone is no signal: it is a database-wide +# singleton, so any other app on the shared D1 database that ever ran +# `wrangler d1 migrations apply` leaves it behind with that app's file names. +has_app_migration_history() { + has_table d1_migrations || return 1 + local applied name + applied="$(d1_query "SELECT name FROM d1_migrations")" + while IFS= read -r name; do + if grep -qxF "$name" <<<"$applied"; then + return 0 + fi + done <<<"$app_migration_files" + return 1 +} + # 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 +# `d1_migrations` — but only when that ledger holds this app's own migration +# files. A bare `users` table alone is NOT a signal either — 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 +if has_app_migration_history; then unprefixed=true fi diff --git a/.github/scripts/test-d1-migrations.mjs b/.github/scripts/test-d1-migrations.mjs index 432ab42..4304f11 100644 --- a/.github/scripts/test-d1-migrations.mjs +++ b/.github/scripts/test-d1-migrations.mjs @@ -2,7 +2,13 @@ // 在仓库根目录运行:node --test .github/scripts/test-d1-migrations.mjs import assert from 'node:assert/strict'; import { execFileSync } from 'node:child_process'; -import { mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'; +import { + mkdtempSync, + readFileSync, + rmSync, + symlinkSync, + writeFileSync, +} from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { test } from 'node:test'; @@ -95,6 +101,20 @@ migrations_dir = "migrations" CREATE INDEX idx_ZETA_links_slug ON ZETA_links(slug);`); return foreignSnapshot(); }; + // Wrangler 自己的迁移账本:全库单例表,共享 D1 上任何应用跑过 + // `wrangler d1 migrations apply` 都会留下它,并记下那家应用的文件名。表结构按 + // Wrangler 实际建的来(id/name/applied_at)。 + const wranglerHistory = (...names) => { + query(`CREATE TABLE d1_migrations ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT UNIQUE, + applied_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL + );${names + .map((n) => `INSERT INTO d1_migrations (name) VALUES ('${n}');`) + .join('')}`); + }; + // prepare 脚本把 mode=… 写到 $GITHUB_OUTPUT,不看 stdout。 + const outputs = () => readFileSync(join(cwd, 'outputs'), 'utf8'); // SQLite 索引名全库唯一:若别的应用已占用同名索引,CREATE INDEX IF NOT EXISTS // 会静默跳过。逐个核对迁移声明的索引确实建在本应用的表上。 const assertOwnIndexes = (prefix) => { @@ -120,6 +140,8 @@ migrations_dir = "migrations" script, setup, shared, + wranglerHistory, + outputs, foreignSnapshot, assertOwnIndexes, env, @@ -307,3 +329,55 @@ test('回归:共享库他表 + Hop 显式空前缀 → 放行,不误判他 CREATE TABLE eNotify_settings (key TEXT, value TEXT);`); assert.match(f.script('d1-prepare-migrations.sh', ''), /Empty database/); }); + +// ─── 回归:d1_migrations 内容判定(ONE-478)──────────────────────────── + +// d1_migrations 是全库单例表,只含别家文件名时不算本应用的无前缀信号: +// SL 表全删后的从零重装必须能过,且不动共享库任何东西。 +test('回归:仅外来 d1_migrations(别家文件名)+ SL 表全删 → 放行从零重建', (t) => { + const f = fixture(t); + const before = f.shared(); // 他应用的表、索引与数据 + f.wranglerHistory('0001_other_app.sql', '0002_other_app.sql'); + const ledgerBefore = f.query( + 'SELECT id, name, applied_at FROM d1_migrations ORDER BY id', + ); + f.script('d1-prepare-migrations.sh', 'SL'); + assert.match(f.outputs(), /mode=prefixed/); + assert.match( + f.script('d1-prefixed-migrations.sh', 'SL'), + /Planned migrations: schema_v1 schema_v2\n/, + ); + assert.deepEqual( + f.query('SELECT name FROM _SL_schema_migrations ORDER BY name')[0], + [{ name: 'schema_v1' }, { name: 'schema_v2' }], + ); + f.assertOwnIndexes('SL'); + assert.deepEqual(f.foreignSnapshot(), before); + assert.deepEqual( + f.query('SELECT id, name, applied_at FROM d1_migrations ORDER BY id'), + ledgerBefore, + ); +}); + +// 防修过头:本应用自己的迁移文件名命中时,真正的静默切换仍必须拒绝; +// 部署侧两处同源守卫(prepare / prefixed 新装分支)口径一致。 +test('回归:d1_migrations 含本应用迁移文件名 + 非空前缀 → 仍拒绝', (t) => { + const f = fixture(t); + const before = f.shared(); + f.wranglerHistory('0001_init.sql', '0002_token_version.sql'); + assert.throws( + () => f.script('d1-prepare-migrations.sh', 'SL'), + (err) => /unprefixed schema/.test(err.stdout ?? ''), + ); + assert.throws( + () => f.script('d1-prefixed-migrations.sh', 'SL'), + (err) => /Refusing to initialise/.test(err.stdout ?? ''), + ); + assert.deepEqual( + f.query( + `SELECT name FROM sqlite_master WHERE type = 'table' AND (name GLOB 'SL_*' OR name GLOB '_SL_*')`, + )[0], + [], + ); + assert.deepEqual(f.foreignSnapshot(), before); +}); diff --git a/apps/worker/src/lib/migrations-runner.ts b/apps/worker/src/lib/migrations-runner.ts index 7aad3f2..caa60b7 100644 --- a/apps/worker/src/lib/migrations-runner.ts +++ b/apps/worker/src/lib/migrations-runner.ts @@ -3,6 +3,7 @@ import { createMigrationsTableSql, getMigrations, migrationsTable, + WRANGLER_MIGRATION_FILES, } from './migrations.js'; import { resolveTablePrefix } from './table-prefix.js'; @@ -92,8 +93,19 @@ async function detectTablePrefixConflict( // 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'); + // D1 database can carry other apps' tables. Neither is a bare `d1_migrations` + // table: it is a database-wide singleton, left behind by any other app on the + // shared database that ran `wrangler d1 migrations apply`, recording that + // app's file names. Only rows naming this app's own migration files count. + let hasUnprefixed = false; + if (has('d1_migrations')) { + const applied = await db + .prepare('SELECT name FROM d1_migrations') + .all<{ name: string }>(); + hasUnprefixed = applied.results.some((r) => + WRANGLER_MIGRATION_FILES.includes(r.name), + ); + } if (has('_schema_migrations')) { const history = await db .prepare('SELECT name FROM _schema_migrations') diff --git a/apps/worker/src/lib/migrations.ts b/apps/worker/src/lib/migrations.ts index 0557ba2..931e7fa 100644 --- a/apps/worker/src/lib/migrations.ts +++ b/apps/worker/src/lib/migrations.ts @@ -161,3 +161,22 @@ ALTER TABLE ${t('users')} ADD COLUMN token_version INTEGER NOT NULL DEFAULT 0; }, ]; } + +// ─── Wrangler migration files owned by this app ─────────────────────────────── +// The `name` values Wrangler records in its `d1_migrations` ledger when it +// applies this app's migrations (migrations/*.sql) without a table prefix. +// +// The silent-switch guard (src/lib/migrations-runner.ts) compares the ledger's +// contents against this set instead of only checking that the table exists: +// `d1_migrations` is a database-wide singleton, so any other app on the shared +// D1 database that ever ran `wrangler d1 migrations apply` leaves it behind, +// recording *that* app's file names — never a sign of an unprefixed schema here. +// +// Derived from each migration's `fileName`, the same single source of truth that +// generates migrations/*.sql (scripts/generate-migrations.ts): adding a Wrangler +// migration means adding a migration here, so there is no second list to keep +// in sync. test/migrations-runner.test.ts asserts this set equals the files +// actually present in migrations/, so a hand-edited directory fails CI. +export const WRANGLER_MIGRATION_FILES: readonly string[] = getMigrations( + '', +).map((m) => m.fileName); diff --git a/apps/worker/test/migrations-runner.test.ts b/apps/worker/test/migrations-runner.test.ts index d666272..dc67425 100644 --- a/apps/worker/test/migrations-runner.test.ts +++ b/apps/worker/test/migrations-runner.test.ts @@ -1,11 +1,15 @@ // Silent-switch guard + three-state resolution for the shared migration runner // (ONE-203 / ONE-205). import assert from 'node:assert/strict'; +import { readdirSync } from 'node:fs'; +import { dirname, join } from 'node:path'; import { test } from 'node:test'; +import { fileURLToPath } from 'node:url'; import { createMigrationsTableSql, getMigrations, migrationsTable, + WRANGLER_MIGRATION_FILES, } from '../src/lib/migrations.ts'; import { runMigrations, @@ -27,6 +31,20 @@ function initializedDb(prefix: string): D1Mock { return db; } +// Wrangler's own migration ledger as it appears on the shared D1 database: a +// database-wide singleton table, left behind (with that app's file names) by +// any other app that ran `wrangler d1 migrations apply` there. +function wranglerHistory(db: D1Mock, names: string[]): void { + db.exec(`CREATE TABLE d1_migrations ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT UNIQUE, + applied_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL + );`); + for (const name of names) { + db.prepare('INSERT INTO d1_migrations (name) VALUES (?)').bind(name).run(); + } +} + test('runMigrations 返回实际生效前缀(未配置 → hop)', async () => { const db = new D1Mock(false); const result = await runMigrations({ @@ -147,3 +165,70 @@ test('回归:共享库他表(ZETA_*/eNotify_*)+ 显式空前缀 → 不误 ], ); }); + +// ─── 回归:d1_migrations 内容判定(ONE-478)──────────────────────────────── + +// d1_migrations 是全库单例表,只含别家文件名时不算本应用的无前缀信号: +// 前缀表全删后的从零重装必须能过。 +test('回归:仅外来 d1_migrations(别家文件名)+ prefix=SL → 不误判为静默切换', async () => { + const db = new D1Mock(false); + wranglerHistory(db, ['0001_other_app.sql', '0002_other_app.sql']); + 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.name, m.status]), + [ + ['schema_v1', 'applied'], + ['schema_v2', 'applied'], + ], + ); + assert.deepEqual( + db + .prepare('SELECT name FROM _SL_schema_migrations ORDER BY name') + .all<{ name: string }>() + .results.map((r) => r.name), + ['schema_v1', 'schema_v2'], + ); +}); + +// 防修过头:本应用自己的迁移文件名命中时,真正的静默切换仍必须拒绝。 +test('回归:d1_migrations 含本应用迁移文件名 + prefix=SL → 仍抛 TablePrefixConflict', async () => { + const db = new D1Mock(false); + wranglerHistory(db, ['0001_other_app.sql', '0001_init.sql']); + await assert.rejects( + runMigrations({ DB: db as unknown as never, TABLE_PREFIX: 'SL' }), + (err: unknown) => { + assert.ok(err instanceof TablePrefixConflictError); + assert.match((err as Error).message, /unprefixed schema/); + return true; + }, + ); + // 被拒后不得写入任何 SL 表或账本。 + assert.deepEqual( + db + .prepare( + "SELECT name FROM sqlite_master WHERE type = 'table' AND (name GLOB 'SL_*' OR name GLOB '_SL_*')", + ) + .all<{ name: string }>() + .results.map((r) => r.name), + [], + ); +}); + +// 部署脚本侧以 apps/worker/migrations/ 目录枚举为真源、运行时以常量为真源, +// 两者漂移即红(新增 Wrangler 迁移文件却漏同步常量时 CI 会挂)。 +test('WRANGLER_MIGRATION_FILES 与 migrations/ 目录实际文件集合相等', () => { + const migrationsDir = join( + dirname(fileURLToPath(import.meta.url)), + '..', + 'migrations', + ); + const onDisk = readdirSync(migrationsDir) + .filter((name) => name.endsWith('.sql')) + .sort(); + assert.ok(onDisk.length > 0); + assert.deepEqual([...WRANGLER_MIGRATION_FILES].sort(), onDisk); +});