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
15 changes: 14 additions & 1 deletion .github/workflows/deploy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -39,13 +39,26 @@ jobs:
KV_NAMESPACE_ID: ${{ vars.KV_NAMESPACE_ID }}
TABLE_PREFIX: ${{ vars.TABLE_PREFIX }}
run: |
# Three-state TABLE_PREFIX resolution (must match runtime getTablePrefix):
# - vars unset or empty → inject "enotify" (default prefix)
# - vars "none" (reserved word) → inject "" (explicit no prefix)
# - anything else → inject verbatim
if [ -z "$TABLE_PREFIX" ]; then
RESOLVED_PREFIX="enotify"
elif [ "$TABLE_PREFIX" = "none" ]; then
RESOLVED_PREFIX=""
else
RESOLVED_PREFIX="$TABLE_PREFIX"
fi
export RESOLVED_PREFIX

APP_VERSION="$(node -p "require('../package.json').version")" \
perl -pi -e '
s/CLOUDFLARE_ACCOUNT_ID_PLACEHOLDER/$ENV{CLOUDFLARE_ACCOUNT_ID}/g;
s/D1_DATABASE_NAME_PLACEHOLDER/$ENV{D1_DATABASE_NAME}/g;
s/D1_DATABASE_ID_PLACEHOLDER/$ENV{D1_DATABASE_ID}/g;
s/KV_NAMESPACE_ID_PLACEHOLDER/$ENV{KV_NAMESPACE_ID}/g;
s/TABLE_PREFIX_PLACEHOLDER/$ENV{TABLE_PREFIX}/g;
s/TABLE_PREFIX_PLACEHOLDER/$ENV{RESOLVED_PREFIX}/g;
s/__APP_VERSION__/'\''$ENV{APP_VERSION}'\''/g;
' wrangler.toml

Expand Down
4 changes: 2 additions & 2 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ The worker serves the frontend's static assets from `web/dist/` via the `ASSETS`
**Database** (`worker/src/db/`):

- Cloudflare D1 (SQLite). Schema defined in `worker/src/db/schema.sql`.
- All table names use a `{prefix}` placeholder at definition time, resolved at runtime via `TABLE_PREFIX` env var and the `getTablePrefix()` helper in `types.ts`.
- All table names use a `{prefix}` placeholder at definition time, resolved at runtime via `TABLE_PREFIX` env var and the `getTablePrefix()` helper in `types.ts` (the ONLY resolution point). Three states: unset/null → default `enotify` (`enotify_`); custom non-empty value → verbatim with trailing `_`; explicit `""` → no prefix. `runSetup` in `worker/src/lib/setup.ts` detects existing initialized schemas under other prefixes via `detectTablePrefixes()` and aborts with 409 `PREFIX_CONFLICT` instead of silently re-initializing; CI maps unset/empty vars to `enotify` and the reserved word `none` to `""`.
- Query functions are organized by entity in `worker/src/db/queries/`. Key entities: `items`, `payments`, `users`, `notifications` (channel config), `settings`.

**Core utilities** (`worker/src/core/`):
Expand All @@ -81,7 +81,7 @@ The worker serves the frontend's static assets from `web/dist/` via the `ASSETS`
- `KV` — KV namespace (used for scheduler deduplication and status)
- `ASSETS` — static file serving
- Secrets: `JWT_SECRET`, `SETUP_SECRET`
- Env var: `TABLE_PREFIX` (optional, allows shared DB with prefix isolation)
- Env var: `TABLE_PREFIX` (three states: unset → default `enotify`, tables like `enotify_users`; custom value → verbatim with trailing `_`; explicit `""`/CI `none` → no prefix; allows shared DB with prefix isolation)

### Frontend (`web/`)

Expand Down
32 changes: 21 additions & 11 deletions README.en.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,12 +63,12 @@ In your repository Settings → Secrets and variables → Actions, add:

In Settings → Secrets and variables → Actions → Variables, add:

| Variable | Description |
| ------------------ | ----------------------------------------------------- |
| `D1_DATABASE_NAME` | D1 database name |
| `D1_DATABASE_ID` | D1 database ID |
| `KV_NAMESPACE_ID` | KV namespace ID |
| `TABLE_PREFIX` | Optional prefix for all DB table names(e.g. `myapp_`) |
| Variable | Description |
| ------------------ | ------------------------------------------------------------------------------------------------------- |
| `D1_DATABASE_NAME` | D1 database name |
| `D1_DATABASE_ID` | D1 database ID |
| `KV_NAMESPACE_ID` | KV namespace ID |
| `TABLE_PREFIX` | Table prefix, three states: unset/empty → default `enotify` (tables like `enotify_users`); `none` → no prefix; other values (e.g. `eNotify`) → verbatim |

### 3. Deploy

Expand Down Expand Up @@ -170,11 +170,21 @@ curl -X DELETE https://your-worker.workers.dev/api/me/api-keys/<id> -H "Cookie:

`JWT_SECRET` and `SETUP_SECRET` are Secrets, uploaded by GitHub Actions via `wrangler deploy --secrets-file`. For local deploys, run `wrangler secret put JWT_SECRET` (and `SETUP_SECRET`) first. `TABLE_PREFIX` is injected into wrangler.toml.

| Variable | Description |
| -------------- | ------------------------------------------------------- |
| `JWT_SECRET` | JWT signing secret, any random 64-char string |
| `SETUP_SECRET` | Database initialization route secret, any random string |
| `TABLE_PREFIX` | Database table prefix (e.g., `hk_`), default is empty |
`TABLE_PREFIX` has three-state semantics (resolved solely by the `getTablePrefix()` helper in `worker/src/types.ts`):

- **Unset** (not configured / `null`) → default prefix `enotify`, actual table names like `enotify_users`;
- **Custom non-empty value** (e.g. `eNotify`) → used verbatim with a trailing `_` appended (`eNotify_`); only letters, digits and underscores are allowed;
- **Explicit empty string `""`** → no prefix at all (table names like `users`).

CI deployment convention (`.github/workflows/deploy.yml`): a GitHub Variables `TABLE_PREFIX` that is unset or empty → injects `enotify`; the reserved word `none` → injects the empty string (no prefix); any other value → injected verbatim. This matches the runtime three-state resolution.

> ⚠️ **Upgrade warning**: older deployments that never configured `TABLE_PREFIX` (the old default was no prefix) must explicitly set `TABLE_PREFIX=none` in GitHub Variables before upgrading, in order to keep the existing unprefixed table names. Otherwise the setup/migration endpoints (`POST /api/setup`, `POST /api/admin/setup`) detect the conflict between the legacy unprefixed schema and the new default prefix `enotify_` and abort with 409 `PREFIX_CONFLICT` — they never re-create or silently switch tables. Deployments already using a custom value (e.g. `eNotify`) are unaffected.

| Variable | Description |
| -------------- | ------------------------------------------------------------------------------------------------------- |
| `JWT_SECRET` | JWT signing secret, any random 64-char string |
| `SETUP_SECRET` | Database initialization route secret, any random string |
| `TABLE_PREFIX` | Table prefix, three states: unset → default `enotify` (tables like `enotify_users`); explicit empty string / CI `none` → no prefix; custom value → verbatim with trailing `_` |

## License

Expand Down
32 changes: 21 additions & 11 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,12 +63,12 @@ npx wrangler kv namespace create ENOTIFY_KV

在 Settings → Secrets and variables → Actions → Variables 中添加:

| Variable | 说明 |
| ------------------ | ---------------------------------- |
| `D1_DATABASE_NAME` | D1 数据库名称 |
| `D1_DATABASE_ID` | D1 数据库 ID |
| `KV_NAMESPACE_ID` | KV 命名空间 ID |
| `TABLE_PREFIX` | 数据库表前缀(如 `hk_`),默认为空 |
| Variable | 说明 |
| ------------------ | ------------------------------------------------------------------------------------------------------------------------ |
| `D1_DATABASE_NAME` | D1 数据库名称 |
| `D1_DATABASE_ID` | D1 数据库 ID |
| `KV_NAMESPACE_ID` | KV 命名空间 ID |
| `TABLE_PREFIX` | 数据库表前缀,三态:未设置/留空 → 默认 `enotify`(表名如 `enotify_users`);设为 `none` → 无前缀;其他值(如 `eNotify`)→ 原样 |

### 3. 部署

Expand Down Expand Up @@ -175,11 +175,21 @@ curl -X DELETE https://your-worker.workers.dev/api/me/api-keys/<id> -H "Cookie:

`JWT_SECRET` 和 `SETUP_SECRET` 是 Secret,由 GitHub Actions 通过 `wrangler deploy --secrets-file` 上传;本地部署请先执行 `wrangler secret put JWT_SECRET`(`SETUP_SECRET` 同理)。`TABLE_PREFIX` 在 wrangler.toml 中注入。

| 变量 | 说明 |
| -------------- | ------------------------------------ |
| `JWT_SECRET` | JWT 签名密钥,任意 64 位随机字符串 |
| `SETUP_SECRET` | 数据库初始化路由密钥,任意随机字符串 |
| `TABLE_PREFIX` | 数据库表前缀(如 `hk_`),默认为空 |
`TABLE_PREFIX` 为三态语义(在 `worker/src/types.ts` 的 `getTablePrefix()` 中统一解析,全仓唯一解析点):

- **未配置**(未设置 / `null`)→ 默认前缀 `enotify`,实际表名如 `enotify_users`;
- **自定义非空值**(如 `eNotify`)→ 原样使用并自动补尾 `_`(`eNotify_`),仅允许字母/数字/下划线;
- **显式空字符串 `""`** → 无前缀,表名不带前缀(如 `users`)。

CI 部署约定(`.github/workflows/deploy.yml`):GitHub Variables 中的 `TABLE_PREFIX` 未设置或为空 → 注入 `enotify`;设为保留字 `none` → 注入空字符串(无前缀);其他值 → 原样注入。与运行时三态解析保持一致。

> ⚠️ **升级警告**:历史上从未配置过 `TABLE_PREFIX` 的旧部署(旧版默认无前缀)升级到本版本前,须先在 GitHub Variables 中显式配置 `TABLE_PREFIX=none` 保持原表名;否则初始化/迁移接口(`POST /api/setup`、`POST /api/admin/setup`)会检测到无前缀存量 schema 与新默认前缀 `enotify_` 冲突并中止(409 `PREFIX_CONFLICT`,绝不自动重建表)。配置为自定义值(如 `eNotify`)的存量部署不受影响。

| 变量 | 说明 |
| -------------- | ------------------------------------------------------------------------------------------------------------------------ |
| `JWT_SECRET` | JWT 签名密钥,任意 64 位随机字符串 |
| `SETUP_SECRET` | 数据库初始化路由密钥,任意随机字符串 |
| `TABLE_PREFIX` | 数据库表前缀,三态:未设置 → 默认 `enotify`(表名如 `enotify_users`);显式空串/CI `none` → 无前缀;自定义值 → 原样补尾 `_` |

## 许可证

Expand Down
2 changes: 1 addition & 1 deletion worker/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ app.use("/api/*", async (c, next) => {
await next();
});
app.use("*", async (c, next) => {
const prefix = c.env.TABLE_PREFIX || "";
const prefix = getTablePrefix(c.env);
if (prefix && !/^[a-zA-Z0-9_]+$/.test(prefix)) {
return c.json({ error: "Invalid TABLE_PREFIX configuration" }, 500);
}
Expand Down
106 changes: 99 additions & 7 deletions worker/src/lib/setup.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,62 @@
import { getTablePrefix } from "../types";
import {
DEFAULT_TABLE_PREFIX,
ensureTrailingUnderscore,
getTablePrefix,
} from "../types";
import type { Env } from "../types";

export interface SetupResult {
success: true;
alreadyInitialized?: true;
export type SetupResult =
| { success: true; alreadyInitialized?: true; effectivePrefix: string }
| {
success: false;
code: "PREFIX_CONFLICT";
error: string;
message: string;
resolvedPrefix: string;
detectedPrefixes: string[];
};

// Unprefixed names of the tables that make up an initialized eNotify schema.
// Used to detect which prefixes the database has already been initialized
// under, so a prefix change can never silently re-initialize fresh tables.
const EONOTIFY_TABLES = [
"users",
"user_2fa",
"items",
"payment_history",
"notification_configs",
"system_settings",
"notification_history",
];

/**
* Detects the table prefixes under which an initialized eNotify schema exists.
* A prefix counts as initialized when at least 4 core tables carrying it are
* present and one of them is `users`. Unrelated tables (e.g. a lone `users`
* table from another app) do not trigger a detection.
*/
export function detectTablePrefixes(tableNames: string[]): Set<string> {
const count: Record<string, number> = {};
const hasUsers: Record<string, boolean> = {};

for (const t of tableNames) {
for (const suffix of EONOTIFY_TABLES) {
if (t === suffix) {
count[""] = (count[""] ?? 0) + 1;
if (suffix === "users") hasUsers[""] = true;
} else if (t.endsWith("_" + suffix)) {
const p = t.slice(0, t.length - suffix.length); // keeps the trailing underscore, e.g. "eNotify_"
count[p] = (count[p] ?? 0) + 1;
if (suffix === "users") hasUsers[p] = true;
}
}
}

return new Set(
Object.entries(count)
.filter(([p, n]) => n >= 4 && hasUsers[p])
.map(([p]) => p),
);
}

const DEFAULT_SETTINGS: Record<string, string> = {
Expand Down Expand Up @@ -176,15 +229,54 @@ export async function runSetup(env: Env): Promise<SetupResult> {
const prefix = getTablePrefix(env);
const db = env.DB;

// Check if already initialized
// Anti-silent-switch guard: if the database already holds an initialized
// eNotify schema under a different prefix, abort instead of re-initializing
// fresh tables under the resolved prefix.
const rows = await db
.prepare(`SELECT name FROM sqlite_master WHERE type='table'`)
.all<{ name: string }>();
const detected = detectTablePrefixes(rows.results.map((r) => r.name));

if (!detected.has(prefix) && detected.size > 0) {
const detectedList = [...detected].sort();
let message: string;
if (
detected.has("") &&
prefix === ensureTrailingUnderscore(DEFAULT_TABLE_PREFIX)
) {
message =
`Detected a legacy schema without table prefix, but TABLE_PREFIX is unset ` +
`(resolves to "${prefix}"). To keep the legacy tables, set TABLE_PREFIX to an ` +
`explicit empty value (GitHub vars: TABLE_PREFIX=none, injected as "" by CI), ` +
`or migrate the tables to the "${prefix}" prefix per the README upgrade guide.`;
} else {
message =
`TABLE_PREFIX mismatch: this database is already initialized under a different ` +
`table prefix (detected: ${detectedList.join(", ")}), but TABLE_PREFIX resolves ` +
`to "${prefix}". Set TABLE_PREFIX explicitly to keep the existing tables ` +
`(e.g. "${detectedList[0]}"), or migrate the tables to the new prefix before ` +
`retrying setup.`;
}

return {
success: false,
code: "PREFIX_CONFLICT",
error: message,
message,
resolvedPrefix: prefix,
detectedPrefixes: detectedList,
};
}

// Check if already initialized under the resolved prefix
const existing = await db
.prepare(`SELECT name FROM sqlite_master WHERE type='table' AND name=?`)
.bind(`${prefix}users`)
.first();

if (existing) {
await runMigrations(db, prefix);
return { success: true, alreadyInitialized: true };
return { success: true, alreadyInitialized: true, effectivePrefix: prefix };
}

const schemaSQL = getSchema();
Expand All @@ -209,7 +301,7 @@ export async function runSetup(env: Env): Promise<SetupResult> {
.run();
}

return { success: true };
return { success: true, effectivePrefix: prefix };
}

function getSchema(): string {
Expand Down
3 changes: 3 additions & 0 deletions worker/src/routes/admin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -549,6 +549,9 @@ adminRoutes.put("/system/settings", async (c) => {
adminRoutes.post("/setup", async (c) => {
try {
const result = await runSetup(c.env);
if (!result.success) {
return c.json(result, 409);
}
return c.json(result, 200);
} catch (err) {
console.error("Admin setup failed:", err);
Expand Down
3 changes: 3 additions & 0 deletions worker/src/routes/setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,9 @@ setupRoutes.post(
}

const result = await runSetup(c.env);
if (!result.success) {
return c.json(result, 409);
}
return c.json(result);
},
);
29 changes: 25 additions & 4 deletions worker/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,13 @@ export interface Env {
KV: KVNamespace;
JWT_SECRET: string;
SETUP_SECRET: string;
TABLE_PREFIX: string;
/**
* Table prefix, three states:
* - undefined/null (unset) → DEFAULT_TABLE_PREFIX ("enotify"), normalized to "enotify_"
* - non-empty custom value → used verbatim with a trailing "_" appended
* - explicit empty string "" → no prefix at all
*/
TABLE_PREFIX?: string;
ASSETS: Fetcher;
}

Expand Down Expand Up @@ -117,10 +123,25 @@ export type HonoEnv = {
};
};

/** Default table prefix used when TABLE_PREFIX is not configured (no trailing underscore). */
export const DEFAULT_TABLE_PREFIX = "enotify";

export function getTablePrefix(env: Env): string {
const raw = env.TABLE_PREFIX || "";
if (!raw) return "";
return raw.endsWith("_") ? raw : `${raw}_`;
const raw = env.TABLE_PREFIX;
// State 1: unset (undefined or null) → default prefix, normalized with trailing "_"
if (raw === undefined || raw === null) {
return ensureTrailingUnderscore(DEFAULT_TABLE_PREFIX);
}
// State 3: explicitly configured as empty string → no prefix
if (raw === "") {
return "";
}
// State 2: custom non-empty value → existing normalization (append trailing "_")
return ensureTrailingUnderscore(raw);
}

export function ensureTrailingUnderscore(v: string): string {
return v.endsWith("_") ? v : `${v}_`;
}

export const VALID_CHANNELS: string[] = [
Expand Down
10 changes: 7 additions & 3 deletions worker/test/admin.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ describe("POST /api/admin/setup", () => {
headers: cookieHeader(token),
});
expect(res.status).toBe(200);
expect(res.body).toEqual({ success: true });
expect(res.body).toEqual({ success: true, effectivePrefix: "" });

const db = env.DB as MockD1;
expect(db.tables.has("users")).toBe(true);
Expand Down Expand Up @@ -52,7 +52,11 @@ describe("POST /api/admin/setup", () => {
headers: cookieHeader(token),
});
expect(res.status).toBe(200);
expect(res.body).toEqual({ success: true, alreadyInitialized: true });
expect(res.body).toEqual({
success: true,
alreadyInitialized: true,
effectivePrefix: "",
});
});

it("returns 403 for a non-admin user", async () => {
Expand Down Expand Up @@ -90,6 +94,6 @@ describe("POST /api/admin/setup", () => {
headers: cookieHeader(token),
});
expect(res.status).toBe(200);
expect(res.body).toEqual({ success: true });
expect(res.body).toEqual({ success: true, effectivePrefix: "" });
});
});
7 changes: 7 additions & 0 deletions worker/test/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,13 @@ export class MockD1 {
const s = sql.trim();

if (s.includes("sqlite_master")) {
// Full-table scan (no "name=?" filter) enumerates every table, as the
// prefix-detection query in runSetup does.
if (!/name\s*=\s*\?/.test(s)) {
const rows = [...this.tables.keys()].map((name) => ({ name }));
if (mode === "first") return rows[0] ?? null;
return rows;
}
const name = String(args[0] ?? "");
const exists = this.tables.has(name);
if (mode === "first") return exists ? { name } : null;
Expand Down
Loading
Loading