From 77ee445b592ca54cc03781aae7b7516d19befdec Mon Sep 17 00:00:00 2001 From: mapxn <16299874+mapxn@users.noreply.github.com> Date: Sat, 24 Oct 2026 23:38:46 +0800 Subject: [PATCH 1/2] =?UTF-8?q?ONE-195:=20fix=20deploy=20workflow=20?= =?UTF-8?q?=E2=80=94=20codegen=20before=20wrangler=20deploy=20+=20ACCOUNT?= =?UTF-8?q?=5FID=20from=20vars?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/deploy.yml | 7 +++++-- worker/package.json | 2 +- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index a683498..55bcc5d 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -42,9 +42,12 @@ jobs: SETUP_SECRET: ${{ secrets.SETUP_SECRET }} run: node scripts/materialize-secrets.mjs + # The worker `deploy` script runs `pnpm codegen` first: schema.generated.ts + # is generated from schema.sql and not committed, so it must be regenerated + # before every wrangler deploy. - name: Deploy Worker working-directory: worker env: CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} - CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} - run: pnpm exec wrangler deploy --secrets-file "$RUNNER_TEMP/secrets.json" + CLOUDFLARE_ACCOUNT_ID: ${{ vars.CLOUDFLARE_ACCOUNT_ID }} + run: pnpm run deploy --secrets-file "$RUNNER_TEMP/secrets.json" diff --git a/worker/package.json b/worker/package.json index 8bdb3fa..3739ac4 100644 --- a/worker/package.json +++ b/worker/package.json @@ -8,7 +8,7 @@ "build": "pnpm codegen && tsc --noEmit", "typecheck": "pnpm codegen && tsc --noEmit", "test": "pnpm codegen && vitest run", - "deploy": "wrangler deploy" + "deploy": "pnpm codegen && wrangler deploy" }, "dependencies": { "@simplewebauthn/server": "^14.0.0", From 544c375805dcdfd362df435cf8d57e3759af2cb9 Mon Sep 17 00:00:00 2001 From: mapxn <16299874+mapxn@users.noreply.github.com> Date: Sun, 25 Oct 2026 00:19:03 +0800 Subject: [PATCH 2/2] =?UTF-8?q?ONE-196:=20nav=20v1.4=20=E2=80=94=20TABLE?= =?UTF-8?q?=5FPREFIX=20three-state=20+=20org-level=20D1=20wiring?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/deploy.yml | 10 ++++- README.md | 28 +++++++++---- scripts/materialize-secrets.mjs | 71 +++++++++++++++++++++++++++++--- worker/.dev.vars.example | 5 +++ worker/src/index.ts | 9 +++- worker/src/routes/auth.ts | 20 ++++++++- worker/src/types.ts | 42 ++++++++++++++++--- worker/test/table-prefix.test.ts | 56 +++++++++++++++++++++++++ worker/wrangler.toml | 10 +++-- 9 files changed, 222 insertions(+), 29 deletions(-) create mode 100644 worker/test/table-prefix.test.ts diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index 55bcc5d..823721b 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -35,11 +35,17 @@ jobs: run: pnpm build:web # Secrets are written to a private temp file and passed to wrangler as a - # secrets file — they never appear in the repo, logs, or wrangler.toml. - - name: Materialize secrets + # secrets file, and wrangler.toml placeholders (account id, D1 database, + # TABLE_PREFIX) are resolved from organization variables — real values + # never appear in the repo, logs, or wrangler.toml. + - name: Materialize secrets + wrangler config env: SESSION_SECRET: ${{ secrets.SESSION_SECRET }} SETUP_SECRET: ${{ secrets.SETUP_SECRET }} + CLOUDFLARE_ACCOUNT_ID: ${{ vars.CLOUDFLARE_ACCOUNT_ID }} + D1_DATABASE_NAME: ${{ vars.D1_DATABASE_NAME }} + D1_DATABASE_ID: ${{ vars.D1_DATABASE_ID }} + TABLE_PREFIX: ${{ vars.TABLE_PREFIX }} run: node scripts/materialize-secrets.mjs # The worker `deploy` script runs `pnpm codegen` first: schema.generated.ts diff --git a/README.md b/README.md index 40b675e..1338322 100644 --- a/README.md +++ b/README.md @@ -27,16 +27,28 @@ pnpm lint && pnpm format:check ## 部署 合并 `main` 后 GitHub Actions(`.github/workflows/deploy.yml`)自动部署 Cloudflare。 -需要在仓库 Secrets 配置(见 PR 说明,凭证不写入代码 / issue / 评论): +凭证不写入代码 / issue / 评论: -| Secret | 用途 | -| ----------------------- | -------------------------- | -| `CLOUDFLARE_API_TOKEN` | wrangler 部署 | -| `CLOUDFLARE_ACCOUNT_ID` | Cloudflare 账户 | -| `SESSION_SECRET` | 会话签名密钥(≥16 位随机) | -| `SETUP_SECRET` | setup 初始化令牌 | +**组织级(WorkerHub,已配置)** -`worker/wrangler.toml` 中的 `CLOUDFLARE_ACCOUNT_ID_PLACEHOLDER`、`D1_DATABASE_ID_PLACEHOLDER` 需替换为实际值(或改用 wrangler 部署时的环境注入)。 +| 配置项 | 类型 | 用途 | +| ----------------------- | -------- | ------------------------ | +| `CLOUDFLARE_API_TOKEN` | secret | wrangler 部署 | +| `CLOUDFLARE_ACCOUNT_ID` | variable | Cloudflare 账户 | +| `D1_DATABASE_NAME` | variable | 共享 D1 库名 | +| `D1_DATABASE_ID` | variable | 共享 D1 库 ID | +| `TABLE_PREFIX` | variable | 可选:表前缀三态(见下) | + +**仓库级(项目私有)** + +| Secret | 用途 | +| ---------------- | -------------------------- | +| `SESSION_SECRET` | 会话签名密钥(≥16 位随机) | +| `SETUP_SECRET` | setup 初始化令牌 | + +`worker/wrangler.toml` 只保留占位符;部署时 `scripts/materialize-secrets.mjs` 从组织变量注入真实值(真实值不进 wrangler.toml)。 + +表前缀三态(`TABLE_PREFIX`):未配置 → 项目默认 `nav_`;`none`(或空)→ 无前缀;其他值 → 原样注入(小写字母/数字/下划线)。 ## 初始化(setup) diff --git a/scripts/materialize-secrets.mjs b/scripts/materialize-secrets.mjs index 7d83dbb..205ce67 100644 --- a/scripts/materialize-secrets.mjs +++ b/scripts/materialize-secrets.mjs @@ -1,13 +1,16 @@ // Writes Cloudflare secrets to a private temp file for `wrangler deploy -// --secrets-file`. Values come from GitHub Actions secrets via env; they are -// never printed or committed. -import { mkdirSync, writeFileSync } from "node:fs"; +// --secrets-file`, and patches worker/wrangler.toml placeholders (account id, +// D1 database name/id, TABLE_PREFIX) from GitHub Actions vars. Values come +// from env; they are never printed or committed. +import { mkdirSync, readFileSync, writeFileSync } from "node:fs"; +import { fileURLToPath } from "node:url"; if (!process.env.RUNNER_TEMP) { console.error("RUNNER_TEMP is not set"); process.exit(1); } +// ─── Secrets (wrangler --secrets-file) ─────────────────────────────────────── const secrets = { SESSION_SECRET: process.env.SESSION_SECRET, SETUP_SECRET: process.env.SETUP_SECRET, @@ -19,7 +22,63 @@ for (const [key, value] of Object.entries(secrets)) { } } -const path = `${process.env.RUNNER_TEMP}/secrets.json`; +const secretsPath = `${process.env.RUNNER_TEMP}/secrets.json`; mkdirSync(process.env.RUNNER_TEMP, { recursive: true }); -writeFileSync(path, JSON.stringify(secrets), { mode: 0o600 }); -console.log(`secrets written to ${path}`); +writeFileSync(secretsPath, JSON.stringify(secrets), { mode: 0o600 }); +console.log(`secrets written to ${secretsPath}`); + +// ─── wrangler.toml placeholders (org-level shared config) ─────────────────── +// Required organization variables; fail fast so a deploy never ships a +// placeholder as a real value. +const required = { + CLOUDFLARE_ACCOUNT_ID: process.env.CLOUDFLARE_ACCOUNT_ID, + D1_DATABASE_NAME: process.env.D1_DATABASE_NAME, + D1_DATABASE_ID: process.env.D1_DATABASE_ID, +}; +for (const [name, value] of Object.entries(required)) { + if (!value) { + console.error( + `${name} is missing — configure it as an organization variable`, + ); + process.exit(1); + } +} + +// TABLE_PREFIX three-state (SPEC v1.4): unset/empty → project default "nav_", +// reserved word "none" → "" (explicit no-prefix), anything else → as-is. +const DEFAULT_TABLE_PREFIX = "nav_"; +function resolveTablePrefix(raw) { + if (raw === undefined || raw === "") return DEFAULT_TABLE_PREFIX; + if (raw === "none") return ""; + return raw; +} +const tablePrefix = resolveTablePrefix(process.env.TABLE_PREFIX); + +const wranglerPath = fileURLToPath( + new URL("../worker/wrangler.toml", import.meta.url), +); +let toml = readFileSync(wranglerPath, "utf8"); + +const replacements = { + CLOUDFLARE_ACCOUNT_ID_PLACEHOLDER: required.CLOUDFLARE_ACCOUNT_ID, + D1_DATABASE_NAME_PLACEHOLDER: required.D1_DATABASE_NAME, + D1_DATABASE_ID_PLACEHOLDER: required.D1_DATABASE_ID, +}; +for (const [placeholder, value] of Object.entries(replacements)) { + toml = toml.replaceAll(placeholder, value); +} + +// Append the [vars] table with the resolved prefix. The committed wrangler.toml +// intentionally has no [vars] section so an unconfigured deployment falls back +// to the Worker's DEFAULT_TABLE_PREFIX; deploy always pins a concrete value. +toml += `\n[vars]\nTABLE_PREFIX = ${JSON.stringify(tablePrefix)}\n`; + +if (toml.includes("_PLACEHOLDER")) { + console.error("Unreplaced placeholder remains in wrangler.toml"); + process.exit(1); +} + +writeFileSync(wranglerPath, toml); +console.log( + `wrangler.toml config resolved (TABLE_PREFIX=${JSON.stringify(tablePrefix)})`, +); diff --git a/worker/.dev.vars.example b/worker/.dev.vars.example index f9d400d..21faeae 100644 --- a/worker/.dev.vars.example +++ b/worker/.dev.vars.example @@ -5,3 +5,8 @@ SESSION_SECRET=replace-with-a-long-random-string # SETUP_SECRET: one-time token for creating the owner account SETUP_SECRET=replace-with-a-long-random-setup-token +# TABLE_PREFIX (optional): leave unset to use the project default "nav_"; +# "none" or empty for no prefix; otherwise a lowercase/digits/underscore +# prefix (a trailing "_" is recommended). wrangler dev reads .dev.vars as env +# vars, overriding any committed binding. +# TABLE_PREFIX=nav_ diff --git a/worker/src/index.ts b/worker/src/index.ts index b070395..f1c29ad 100644 --- a/worker/src/index.ts +++ b/worker/src/index.ts @@ -32,8 +32,11 @@ app.use("/api/*", async (c, next) => { }); app.use("*", async (c, next) => { - const prefix = c.env.TABLE_PREFIX || ""; - if (prefix && !/^[a-zA-Z0-9_]+$/.test(prefix)) { + // Resolve the table prefix once so a malformed custom prefix fails fast + // with a clear error (SPEC v1.4: lowercase letters / digits / underscore). + try { + getTablePrefix(c.env); + } catch { return c.json({ error: "invalid TABLE_PREFIX configuration" }, 500); } await next(); @@ -71,11 +74,13 @@ app.get("/api/system/info", async (c) => { return c.json({ app_name: settings ?? "nav", version: typeof APP_VERSION !== "undefined" ? APP_VERSION : "0.0.0", + tablePrefix: prefix, }); } catch { return c.json({ app_name: "nav", version: typeof APP_VERSION !== "undefined" ? APP_VERSION : "0.0.0", + tablePrefix: prefix, }); } }); diff --git a/worker/src/routes/auth.ts b/worker/src/routes/auth.ts index 3c37a4f..849fd81 100644 --- a/worker/src/routes/auth.ts +++ b/worker/src/routes/auth.ts @@ -1,6 +1,7 @@ import { Hono } from "hono"; import { deleteCookie, getCookie } from "hono/cookie"; import { getTablePrefix, type HonoEnv } from "../types"; +import { ensureSchema } from "../lib/migrate"; import { generateId, generateToken, @@ -57,7 +58,18 @@ authRoutes.get("/setup", async (c) => { }); authRoutes.post("/setup", async (c) => { - const prefix = getTablePrefix(c.env); + // Resolve the effective prefix before initialization (SPEC v1.4); a + // malformed custom prefix rejects setup outright. + let prefix: string; + try { + prefix = getTablePrefix(c.env); + } catch { + return c.json({ error: "invalid TABLE_PREFIX configuration" }, 500); + } + + // Apply the idempotent schema (creates {prefix}* tables on first setup). + await ensureSchema(c.env); + const users = await countUsers(c.env.DB, prefix); if (users > 0) return c.json({ error: "setup already completed" }, 403); @@ -92,7 +104,11 @@ authRoutes.post("/setup", async (c) => { await issueSession(c, created.id); return c.json( - { success: true, user: { id: created.id, username: created.username } }, + { + success: true, + user: { id: created.id, username: created.username }, + tablePrefix: prefix, + }, 201, ); }); diff --git a/worker/src/types.ts b/worker/src/types.ts index 58ac9cd..65c1c50 100644 --- a/worker/src/types.ts +++ b/worker/src/types.ts @@ -4,10 +4,15 @@ * wrangler.toml so they can never be committed. */ /** - * Wrangler `vars` (non-secret). Declared in wrangler.toml. + * Wrangler `vars` (non-secret). TABLE_PREFIX is injected at deploy time by + * scripts/materialize-secrets.mjs; no [vars] table is committed. */ export interface Vars { - TABLE_PREFIX: string; + /** + * Table prefix (SPEC v1.4). Absent when unconfigured so the Worker falls + * back to DEFAULT_TABLE_PREFIX; "" means an explicit no-prefix. + */ + TABLE_PREFIX?: string; } export interface Env { @@ -17,8 +22,11 @@ export interface Env { /** Wrangler secret / local env var — never in wrangler.toml. */ SETUP_SECRET: string; ASSETS: Fetcher; - /** Legacy-style table prefix kept for parity with eNotify/Zeta deployments. */ - TABLE_PREFIX: string; + /** + * Table prefix (SPEC v1.4). Injected at deploy time; absent when + * unconfigured so the Worker defaults to DEFAULT_TABLE_PREFIX. + */ + TABLE_PREFIX?: string; } export interface HonoEnv { @@ -157,8 +165,32 @@ export interface JWTPayload { // ─── Helpers ───────────────────────────────────────────────────────────────── +// ─── Table prefix (SPEC v1.4) ──────────────────────────────────────────────── + +/** Project default table prefix — the only hard-coded prefix allowed. */ +export const DEFAULT_TABLE_PREFIX = "nav_"; + +/** Lowercase letters / digits / underscore; a trailing "_" is recommended. */ +const TABLE_PREFIX_RE = /^[a-z0-9_]*$/; + +export function isValidTablePrefix(prefix: string): boolean { + return TABLE_PREFIX_RE.test(prefix); +} + +/** + * Three-state table prefix resolution (SPEC v1.4): + * - undefined → DEFAULT_TABLE_PREFIX ("nav_") — shared-DB zero-config isolation + * - "" → "" (explicit no-prefix; deployer accepts collision risk) + * - otherwise → validated custom prefix (throws when malformed) + */ export function getTablePrefix(env: Env): string { - return env.TABLE_PREFIX || ""; + const raw = env.TABLE_PREFIX; + if (raw === undefined) return DEFAULT_TABLE_PREFIX; + if (raw === "") return ""; + if (!isValidTablePrefix(raw)) { + throw new Error(`invalid TABLE_PREFIX "${raw}": must match /^[a-z0-9_]*$/`); + } + return raw; } export const VALID_VISIBILITY = ["public", "private"] as const; diff --git a/worker/test/table-prefix.test.ts b/worker/test/table-prefix.test.ts new file mode 100644 index 0000000..f63fed1 --- /dev/null +++ b/worker/test/table-prefix.test.ts @@ -0,0 +1,56 @@ +import { describe, expect, it } from "vitest"; +import { + DEFAULT_TABLE_PREFIX, + getTablePrefix, + isValidTablePrefix, +} from "../src/types"; +import { runMigrations } from "../src/lib/migrate"; +import { makeEnv, type SqliteD1 } from "./helpers"; + +describe("table prefix three-state (SPEC v1.4)", () => { + it("uses the project default nav_ as the only hard-coded prefix", () => { + expect(DEFAULT_TABLE_PREFIX).toBe("nav_"); + }); + + it("defaults to nav_ when TABLE_PREFIX is unconfigured", () => { + expect(getTablePrefix(makeEnv({ TABLE_PREFIX: undefined }))).toBe("nav_"); + }); + + it("treats an explicit empty string as no-prefix", () => { + expect(getTablePrefix(makeEnv({ TABLE_PREFIX: "" }))).toBe(""); + }); + + it("returns a valid custom prefix as-is (no auto underscore)", () => { + expect(getTablePrefix(makeEnv({ TABLE_PREFIX: "app_" }))).toBe("app_"); + expect(getTablePrefix(makeEnv({ TABLE_PREFIX: "nav_" }))).toBe("nav_"); + expect(getTablePrefix(makeEnv({ TABLE_PREFIX: "abc123" }))).toBe("abc123"); + }); + + it("rejects a malformed custom prefix", () => { + for (const bad of ["BadPrefix", "foo-bar", "foo bar", "foo.", "foo\\bar"]) { + expect(() => getTablePrefix(makeEnv({ TABLE_PREFIX: bad }))).toThrow(); + } + }); + + it("isValidTablePrefix matches lowercase letters / digits / underscore", () => { + expect(isValidTablePrefix("nav_")).toBe(true); + expect(isValidTablePrefix("abc123_")).toBe(true); + expect(isValidTablePrefix("")).toBe(true); + expect(isValidTablePrefix("BadPrefix")).toBe(false); + expect(isValidTablePrefix("foo-bar")).toBe(false); + }); + + it("migrates to nav_* tables when TABLE_PREFIX is unconfigured", async () => { + const env = makeEnv({ TABLE_PREFIX: undefined }); + await runMigrations(env); + + const db = (env.DB as unknown as SqliteD1).db; + const tables = db + .prepare("SELECT name FROM sqlite_master WHERE type='table'") + .all() + .map((row: { name: string }) => row.name); + expect(tables).toContain("nav_users"); + expect(tables).toContain("nav_links"); + expect(tables).not.toContain("users"); + }); +}); diff --git a/worker/wrangler.toml b/worker/wrangler.toml index f3672d3..64a9eca 100644 --- a/worker/wrangler.toml +++ b/worker/wrangler.toml @@ -19,7 +19,9 @@ binding = "DB" database_name = "D1_DATABASE_NAME_PLACEHOLDER" database_id = "D1_DATABASE_ID_PLACEHOLDER" -[vars] -TABLE_PREFIX = "" -# Local dev only: wrangler dev picks these up from the shell environment; -# production receives SESSION_SECRET / SETUP_SECRET as wrangler secrets. +# No [vars] table is committed. TABLE_PREFIX is injected at deploy time by +# scripts/materialize-secrets.mjs (three-state: unset/empty → "nav_", +# "none" → "" for no-prefix, otherwise the value as-is). With no TABLE_PREFIX +# binding, the Worker defaults to DEFAULT_TABLE_PREFIX = "nav_" (zero-config +# isolation on a shared D1 database); set TABLE_PREFIX in .dev.vars to override +# for local development.