Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 13 additions & 4 deletions .github/workflows/deploy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -35,16 +35,25 @@ 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
# 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"
28 changes: 20 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
71 changes: 65 additions & 6 deletions scripts/materialize-secrets.mjs
Original file line number Diff line number Diff line change
@@ -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,
Expand All @@ -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)})`,
);
5 changes: 5 additions & 0 deletions worker/.dev.vars.example
Original file line number Diff line number Diff line change
Expand Up @@ -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_
2 changes: 1 addition & 1 deletion worker/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
9 changes: 7 additions & 2 deletions worker/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down Expand Up @@ -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,
});
}
});
Expand Down
20 changes: 18 additions & 2 deletions worker/src/routes/auth.ts
Original file line number Diff line number Diff line change
@@ -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,
Expand Down Expand Up @@ -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);

Expand Down Expand Up @@ -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,
);
});
Expand Down
42 changes: 37 additions & 5 deletions worker/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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 {
Expand Down Expand Up @@ -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;
Expand Down
56 changes: 56 additions & 0 deletions worker/test/table-prefix.test.ts
Original file line number Diff line number Diff line change
@@ -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");
});
});
10 changes: 6 additions & 4 deletions worker/wrangler.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Loading