From dbd2c1d414dd13a86681c645ef2023fc79e56676 Mon Sep 17 00:00:00 2001 From: mapxn <16299874+mapxn@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:34:12 +0800 Subject: [PATCH] =?UTF-8?q?ONE-446:=20=E5=B9=82=E7=AD=89=E8=A1=A5=E7=A7=8D?= =?UTF-8?q?=205=20=E4=B8=AA=E9=BB=98=E8=AE=A4=E6=90=9C=E7=B4=A2=E5=BC=95?= =?UTF-8?q?=E6=93=8E=EF=BC=88=E4=BB=85=E5=9C=A8=E7=A9=BA=E8=A1=A8=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 新装搜索框无引擎可用:search_engines 表与 CRUD 都在,但迁移与 setup 全程没有种子 INSERT。 - worker/src/db/seeds.ts:冻结的 5 引擎常量(固定 slug id、{q} 占位、 sort_order 1–5、仅 Google is_default)+ seedSearchEngines(),先 COUNT 探空表,再单条 INSERT OR IGNORE,任意一行存在即整表不碰。 - worker/src/lib/migrate.ts:applyMigrations 增加 seedDefaults 选项, 在 runMigrations 之后用 runner 解析出的 prefix 补种;不带该选项的 read-path guard(ensureSchema)永不补种,避免页面请求把用户删空的表 重新填上。 - 初始化 / 升级两条路显式开启:POST /api/auth/setup、 runSetupMigrations(POST /api/setup 与 POST /api/admin/setup)。 不动 schema、不新增迁移版本、不动 TABLE_PREFIX 逻辑、不改 DTO。 --- worker/src/db/seeds.ts | 124 ++++++++++ worker/src/lib/migrate.ts | 24 +- worker/src/routes/auth.ts | 6 +- worker/src/services/setup.ts | 7 +- worker/test/search-engine-seed.test.ts | 315 +++++++++++++++++++++++++ 5 files changed, 472 insertions(+), 4 deletions(-) create mode 100644 worker/src/db/seeds.ts create mode 100644 worker/test/search-engine-seed.test.ts diff --git a/worker/src/db/seeds.ts b/worker/src/db/seeds.ts new file mode 100644 index 0000000..7eabfb9 --- /dev/null +++ b/worker/src/db/seeds.ts @@ -0,0 +1,124 @@ +// Default seed data (ONE-446). +// +// A freshly initialised install has the whole schema but zero rows in +// `{prefix}search_engines`, which leaves the start page without a usable search +// box. The setup / upgrade path therefore tops that one table up with the five +// engines below — but ONLY while it is empty. As soon as the owner has any +// engine of their own (or deliberately emptied the table) nothing is written. +// +// Idempotency holds on two levels: +// - an emptiness probe (one COUNT) decides whether to write at all; +// - deterministic ids + `INSERT OR IGNORE`, so even two setup requests racing +// between probe and insert cannot create a second copy of the same engine — +// the primary key absorbs the duplicate. +// +// This is deliberately NOT a migration version: the ledger stays the single +// source of truth for the schema, and the seed is data, re-checkable on every +// upgrade without adding a `schema_v2`. + +import { nowIso } from "./sql"; + +/** One default search engine, written verbatim into `{prefix}search_engines`. */ +export interface SeedSearchEngine { + /** Stable id: fixed slug, never regenerated, so re-seeding is idempotent. */ + id: string; + name: string; + /** `{q}` is the query placeholder substituted by the client. */ + urlTemplate: string; + sortOrder: number; + isDefault: boolean; +} + +/** Frozen seed set (ONE-446 §冻结接口契约): order 1–5, only Google is default. */ +export const SEED_SEARCH_ENGINES: readonly SeedSearchEngine[] = [ + { + id: "seed-google", + name: "Google", + urlTemplate: "https://www.google.com/search?q={q}", + sortOrder: 1, + isDefault: true, + }, + { + id: "seed-bing", + name: "Bing", + urlTemplate: "https://www.bing.com/search?q={q}", + sortOrder: 2, + isDefault: false, + }, + { + id: "seed-duckduckgo", + name: "DuckDuckGo", + urlTemplate: "https://duckduckgo.com/?q={q}", + sortOrder: 3, + isDefault: false, + }, + { + id: "seed-baidu", + name: "百度", + urlTemplate: "https://www.baidu.com/s?wd={q}", + sortOrder: 4, + isDefault: false, + }, + { + id: "seed-github", + name: "GitHub", + urlTemplate: "https://github.com/search?q={q}", + sortOrder: 5, + isDefault: false, + }, +]; + +/** Table the defaults live in — keeps the `{prefix}` formula in one place. */ +export function searchEnginesTable(prefix: string): string { + return `${prefix}search_engines`; +} + +export interface SeedSearchEnginesOutcome { + /** `true` only when this call found the table empty and wrote the defaults. */ + seeded: boolean; + /** Rows written by this call (0 when the table already had engines). */ + inserted: number; +} + +/** + * Inserts {@link SEED_SEARCH_ENGINES} into `{prefix}search_engines` when — and + * only when — the table is empty. Any existing row makes this a no-op, so a + * second setup / upgrade run leaves the table byte-identical. + */ +export async function seedSearchEngines( + db: D1Database, + prefix: string, +): Promise { + const table = searchEnginesTable(prefix); + + const existing = await db + .prepare(`SELECT COUNT(*) AS count FROM ${table}`) + .first<{ count: number }>(); + // `?? 0` also covers a driver returning no row for the aggregate. + if ((existing?.count ?? 0) > 0) return { seeded: false, inserted: 0 }; + + const now = nowIso(); + const placeholders = SEED_SEARCH_ENGINES.map( + () => "(?, ?, ?, ?, ?, ?, ?, ?)", + ).join(", "); + const values = SEED_SEARCH_ENGINES.flatMap((engine) => [ + engine.id, + engine.name, + engine.urlTemplate, + // icon: optional by contract — no bundled artwork, so NULL. + null, + engine.sortOrder, + engine.isDefault ? 1 : 0, + now, + now, + ]); + + await db + .prepare( + `INSERT OR IGNORE INTO ${table} (id, name, url_template, icon, sort_order, is_default, created_at, updated_at) VALUES ${placeholders}`, + ) + .bind(...values) + .run(); + + return { seeded: true, inserted: SEED_SEARCH_ENGINES.length }; +} diff --git a/worker/src/lib/migrate.ts b/worker/src/lib/migrate.ts index b145af1..ae7e2e5 100644 --- a/worker/src/lib/migrate.ts +++ b/worker/src/lib/migrate.ts @@ -1,5 +1,6 @@ import { getTablePrefix, type Env } from "../types"; import { countUsers } from "../db/queries/users"; +import { seedSearchEngines } from "../db/seeds"; import { runMigrations, type RunMigrationsResult } from "./migrations-runner"; // Per-isolate flag: after the first successful run in this Worker isolate the @@ -7,13 +8,34 @@ import { runMigrations, type RunMigrationsResult } from "./migrations-runner"; // the ledger replay entirely (D1 tables persist across requests). let schemaReady = false; +export interface ApplyMigrationsOptions { + /** + * Top up `{prefix}search_engines` with the default engines when that table is + * empty (ONE-446). Setup and upgrade paths pass `true`; the read-path guard + * (`ensureSchema`) does not, so a table the owner emptied on purpose is never + * re-populated by an ordinary page load. + */ + seedDefaults?: boolean; +} + /** * Applies pending migrations and marks the isolate schema-ready. Returns the * per-migration ledger outcome so setup can report what was applied/skipped. * Idempotent: recorded migrations are skipped, so re-running is cheap. + * + * With `seedDefaults` the default search engines are ensured right after the + * schema exists — that seed is itself a no-op unless the table is empty. */ -export async function applyMigrations(env: Env): Promise { +export async function applyMigrations( + env: Env, + options: ApplyMigrationsOptions = {}, +): Promise { const result = await runMigrations(env); + if (options.seedDefaults === true) { + // Uses the prefix the runner resolved (not a second getTablePrefix call) so + // the seed always lands in the schema that was just migrated. + await seedSearchEngines(env.DB, result.prefix); + } schemaReady = true; return result; } diff --git a/worker/src/routes/auth.ts b/worker/src/routes/auth.ts index 1d04e09..d0ac43a 100644 --- a/worker/src/routes/auth.ts +++ b/worker/src/routes/auth.ts @@ -73,10 +73,12 @@ authRoutes.post("/setup", async (c) => { } // Apply the ledgered migrations (creates {prefix}* tables on first setup) and - // report each migration's outcome in the response. + // report each migration's outcome in the response. This is the initialisation + // path, so it also ensures the default search engines exist (ONE-446). let migrations: MigrationResult[]; try { - migrations = (await applyMigrations(c.env)).migrations; + migrations = (await applyMigrations(c.env, { seedDefaults: true })) + .migrations; } catch (err) { if (err instanceof TablePrefixConflictError) { return c.json( diff --git a/worker/src/services/setup.ts b/worker/src/services/setup.ts index e7c7cf0..6ae5fca 100644 --- a/worker/src/services/setup.ts +++ b/worker/src/services/setup.ts @@ -99,6 +99,10 @@ export type SetupMigrationOutcome = * Runs ONLY the ledgered migrations (forward-only, idempotent): no user is * created, no password changed, no table dropped. Both setup endpoints share * this so their payloads and their 409 conflict shape stay identical. + * + * This is also the «检查并升级数据库» path, so it tops up the default search + * engines when that table is empty (ONE-446) — a no-op on any install that + * already has an engine. */ export async function runSetupMigrations( env: Env, @@ -107,7 +111,8 @@ export async function runSetupMigrations( let migrations: MigrationResult[]; try { - migrations = (await applyMigrations(env)).migrations; + migrations = (await applyMigrations(env, { seedDefaults: true })) + .migrations; } catch (err) { if (err instanceof TablePrefixConflictError) { return { diff --git a/worker/test/search-engine-seed.test.ts b/worker/test/search-engine-seed.test.ts new file mode 100644 index 0000000..d2e11a3 --- /dev/null +++ b/worker/test/search-engine-seed.test.ts @@ -0,0 +1,315 @@ +import { describe, expect, it } from "vitest"; +import { Hono } from "hono"; +import { + SEED_SEARCH_ENGINES, + searchEnginesTable, + seedSearchEngines, +} from "../src/db/seeds"; +import { insertSearchEngine } from "../src/db/queries/content"; +import { applyMigrations } from "../src/lib/migrate"; +import { runSetupMigrations } from "../src/services/setup"; +import { setupRoutes } from "../src/routes/setup"; +import { authRoutes } from "../src/routes/auth"; +import { publicRoutes } from "../src/routes/public"; +import type { Env } from "../src/types"; +import { makeEnv, readJson, type SqliteD1 } from "./helpers"; + +/** + * Frozen seed contract (ONE-446): five engines, `{q}` placeholder, sort_order + * 1–5, only Google default. Written out independently of the implementation so + * a drifted constant fails here instead of passing by construction. + */ +const CONTRACT: ReadonlyArray<{ + name: string; + urlTemplate: string; + sortOrder: number; + isDefault: number; +}> = [ + { + name: "Google", + urlTemplate: "https://www.google.com/search?q={q}", + sortOrder: 1, + isDefault: 1, + }, + { + name: "Bing", + urlTemplate: "https://www.bing.com/search?q={q}", + sortOrder: 2, + isDefault: 0, + }, + { + name: "DuckDuckGo", + urlTemplate: "https://duckduckgo.com/?q={q}", + sortOrder: 3, + isDefault: 0, + }, + { + name: "百度", + urlTemplate: "https://www.baidu.com/s?wd={q}", + sortOrder: 4, + isDefault: 0, + }, + { + name: "GitHub", + urlTemplate: "https://github.com/search?q={q}", + sortOrder: 5, + isDefault: 0, + }, +]; + +const SECRET = "test-setup-secret"; + +interface EngineRow { + id: string; + name: string; + url_template: string; + icon: string | null; + sort_order: number; + is_default: number; + created_at: string; + updated_at: string; +} + +function sqliteOf(env: Env): SqliteD1["db"] { + return (env.DB as unknown as SqliteD1).db; +} + +function engines(env: Env, prefix: string): EngineRow[] { + return sqliteOf(env) + .prepare( + `SELECT * FROM ${searchEnginesTable(prefix)} ORDER BY sort_order, created_at`, + ) + .all() as EngineRow[]; +} + +function tableNames(env: Env): string[] { + return sqliteOf(env) + .prepare("SELECT name FROM sqlite_master WHERE type = 'table'") + .all() + .map((row: { name: string }) => row.name); +} + +function makeApp(): Hono { + const app = new Hono(); + app.route("/api", setupRoutes); + app.route("/api/auth", authRoutes); + app.route("/api/public", publicRoutes); + return app; +} + +// Every test spends its own IP budget for the setup rate limiter. +let ipCounter = 0; +function nextIp(): string { + ipCounter += 1; + return `203.0.113.${ipCounter}`; +} + +function setupUpgrade(app: Hono, env: Env): Promise { + return app.request( + "/api/setup", + { + method: "POST", + headers: { + "content-type": "application/json", + "x-forwarded-for": nextIp(), + "x-setup-secret": SECRET, + }, + }, + env, + ); +} + +function createOwner(app: Hono, env: Env): Promise { + return app.request( + "/api/auth/setup", + { + method: "POST", + body: JSON.stringify({ + username: "owner", + password: "correct horse battery", + }), + headers: { + "content-type": "application/json", + "x-setup-secret": SECRET, + }, + }, + env, + ); +} + +describe("default search engine seed — fresh initialisation (ONE-446)", () => { + it("writes exactly the five contract engines after runMigrations + seed", async () => { + const env = makeEnv({ TABLE_PREFIX: "nav_" }); + await applyMigrations(env, { seedDefaults: true }); + + const rows = engines(env, "nav_"); + expect(rows).toHaveLength(5); + expect( + rows.map((row) => ({ + name: row.name, + urlTemplate: row.url_template, + sortOrder: row.sort_order, + isDefault: row.is_default, + })), + ).toEqual(CONTRACT); + // icon is optional in the contract → NULL is allowed and used. + expect(rows.every((row) => row.icon === null)).toBe(true); + // Deterministic ids: fixed slugs, no random uuid, stable across runs. + expect(rows.map((row) => row.id)).toEqual( + SEED_SEARCH_ENGINES.map((engine) => engine.id), + ); + }); + + it("seeds the unprefixed schema and does not leak a prefixed table", async () => { + const env = makeEnv({ TABLE_PREFIX: "" }); + await applyMigrations(env, { seedDefaults: true }); + + expect(engines(env, "")).toHaveLength(5); + expect(tableNames(env)).toContain("search_engines"); + expect(tableNames(env)).not.toContain("nav_search_engines"); + }); + + it("follows any custom TABLE_PREFIX", async () => { + const env = makeEnv({ TABLE_PREFIX: "app_" }); + await applyMigrations(env, { seedDefaults: true }); + + expect(engines(env, "app_")).toHaveLength(5); + expect(tableNames(env)).toContain("app_search_engines"); + expect(tableNames(env)).not.toContain("search_engines"); + expect(tableNames(env)).not.toContain("nav_search_engines"); + }); + + it("is deterministic: two fresh databases get identical rows", async () => { + const first = makeEnv({ TABLE_PREFIX: "nav_" }); + const second = makeEnv({ TABLE_PREFIX: "nav_" }); + await applyMigrations(first, { seedDefaults: true }); + await applyMigrations(second, { seedDefaults: true }); + + const ids = (env: Env) => engines(env, "nav_").map((row) => row.id); + expect(ids(first)).toEqual(ids(second)); + expect(ids(first)).toEqual(SEED_SEARCH_ENGINES.map((engine) => engine.id)); + }); +}); + +describe("default search engine seed — idempotency", () => { + it("reports and skips on every run after the first", async () => { + const env = makeEnv({ TABLE_PREFIX: "nav_" }); + await applyMigrations(env); // schema only + + const first = await seedSearchEngines(env.DB, "nav_"); + expect(first).toEqual({ seeded: true, inserted: 5 }); + + const before = engines(env, "nav_"); + const second = await seedSearchEngines(env.DB, "nav_"); + expect(second).toEqual({ seeded: false, inserted: 0 }); + // Byte-identical: ids, timestamps and order untouched by the second pass. + expect(engines(env, "nav_")).toEqual(before); + }); + + it("does not re-seed when repeated setup / upgrade runs happen", async () => { + const env = makeEnv({ TABLE_PREFIX: "nav_" }); + + const firstRun = await runSetupMigrations(env); + expect(firstRun.ok).toBe(true); + const before = engines(env, "nav_"); + expect(before).toHaveLength(5); + + const secondRun = await runSetupMigrations(env); + expect(secondRun.ok).toBe(true); + expect(engines(env, "nav_")).toEqual(before); + expect(engines(env, "nav_")).toHaveLength(5); + }); + + it("leaves a non-empty table completely alone", async () => { + const env = makeEnv({ TABLE_PREFIX: "nav_" }); + await applyMigrations(env); // schema only, no seed + await insertSearchEngine(env.DB, "nav_", { + id: "owner-pick", + name: "Kagi", + url_template: "https://kagi.com/search?q={q}", + icon: null, + sort_order: 1, + is_default: 1, + }); + + const outcome = await runSetupMigrations(env); + expect(outcome.ok).toBe(true); + + const rows = engines(env, "nav_"); + expect(rows).toHaveLength(1); + expect(rows[0]?.id).toBe("owner-pick"); + expect(rows[0]?.name).toBe("Kagi"); + }); + + it("does not wipe or reorder any engine the owner already has", async () => { + const env = makeEnv({ TABLE_PREFIX: "nav_" }); + await applyMigrations(env, { seedDefaults: true }); + // Owner edits one seed row, then deletes another. + sqliteOf(env) + .prepare( + `UPDATE nav_search_engines SET name = 'Google (edited)', sort_order = 99 WHERE id = 'seed-google'`, + ) + .run(); + sqliteOf(env) + .prepare(`DELETE FROM nav_search_engines WHERE id = 'seed-bing'`) + .run(); + + await runSetupMigrations(env); + + const rows = engines(env, "nav_"); + expect(rows).toHaveLength(4); + expect(rows.some((row) => row.name === "Google (edited)")).toBe(true); + expect(rows.some((row) => row.id === "seed-bing")).toBe(false); + }); +}); + +describe("default search engine seed — path coverage", () => { + it("does not seed on the read-path guard (ensureSchema / applyMigrations without the option)", async () => { + const env = makeEnv({ TABLE_PREFIX: "nav_" }); + await applyMigrations(env, { seedDefaults: true }); + sqliteOf(env).prepare("DELETE FROM nav_search_engines").run(); + + // A page load must not resurrect engines the owner removed on purpose. + await applyMigrations(env); + expect(engines(env, "nav_")).toHaveLength(0); + }); + + it("seeds through POST /api/auth/setup (initialisation) and surfaces in /api/public", async () => { + const env = makeEnv({ TABLE_PREFIX: "nav_" }); + const app = makeApp(); + + const created = await createOwner(app, env); + expect(created.status).toBe(201); + expect(engines(env, "nav_")).toHaveLength(5); + + const res = await app.request("/api/public", {}, env); + expect(res.status).toBe(200); + const body = await readJson(res); + expect( + body.searchEngines.map((engine: { name: string; isDefault: boolean }) => [ + engine.name, + engine.isDefault, + ]), + ).toEqual([ + ["Google", true], + ["Bing", false], + ["DuckDuckGo", false], + ["百度", false], + ["GitHub", false], + ]); + }); + + it("seeds through POST /api/setup (secret-gated upgrade) and stays at five on repeat", async () => { + const env = makeEnv({ TABLE_PREFIX: "nav_" }); + const app = makeApp(); + + const first = await setupUpgrade(app, env); + expect(first.status).toBe(200); + expect(engines(env, "nav_")).toHaveLength(5); + + const before = engines(env, "nav_"); + const second = await setupUpgrade(app, env); + expect(second.status).toBe(200); + expect(engines(env, "nav_")).toEqual(before); + }); +});