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
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,13 @@ pnpm lint && pnpm format:check

线上首次部署、库中无账号时开放 setup:`POST /api/auth/setup`(header `X-Setup-Secret`)创建唯一所有者账号,创建后 setup 永久关闭,不设注册接口。响应在 `{ success, user, tablePrefix }` 之外附 `migrations: [{ name, status }]`(`applied` / `skipped`)。

数据库升级/初始化也可走 setup 三件套(SPEC SETUP-PAGE-SPEC v1.0):
- `GET /api/setup/state`(无鉴权,`no-store`)→ `{enabled, ownerExists, tablePrefix}`;`GET /api/setup/status` 为同逻辑兼容别名。
- `POST /api/setup`(header `X-Setup-Secret`,按 IP 每 10 分钟 3 次)→ **只跑账本迁移**,不建用户/不改密码/不删表;响应 `{success, tablePrefix, migrations, ownerExists}`,前缀冲突 409。
- `POST /api/admin/setup`(会话鉴权、免密钥)、`GET /api/admin/system`、`PUT /api/admin/system/setup-page`:管理面「系统管理」的升级按钮与 setup 页面开关。

setup 页面开关存在 `{prefix}settings.setup_page_enabled`(`'1'` 开 / `'0'` 关,**默认关**:所有者创建成功即写入 `'0'`):未初始化时页面恒开;开关只门控页面,不门控两个密钥接口本身(密钥即门闩,避免把自己锁在门外)。

## 数据库迁移账本(schema ledger)

schema 的唯一可信源是 `worker/src/lib/migrations.ts` 的 `getMigrations(prefix)` 迁移列表,执行由 `worker/src/lib/migrations-runner.ts` 的 `runMigrations(env)` 完成(setup 路由与读路径 `ensureSchema` 共用同一个 runner)。原 `worker/src/db/schema.sql` + `gen-schema.mjs` codegen 已删除,不再有第二份 schema 定义。
Expand Down
15 changes: 15 additions & 0 deletions docs/api-contract.md
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,21 @@ Passkey(WebAuthn,/api/auth/passkey/*,@simplewebauthn/server v14):
- `GET /api/admin/settings` → `{siteTitle, backgroundUrl, theme, columns}`
- `PUT /api/admin/settings` body 可含 `{siteTitle, backgroundUrl, theme(light|dark|system), columns(1–12)}` → 更新后对象

`setup_page_enabled`(setup 页面开关)**不在**站点设置白名单内,也不出现在 `SiteSettingsDto` / `/api/public` 输出;它只走下面的系统管理端点。

### 系统管理(`/api/admin/setup`、`/api/admin/system*`,需会话)

- `POST /api/admin/setup` → 免密钥跑账本迁移,响应形状与 `POST /api/setup` 完全一致(含 409 冲突形状)
- `GET /api/admin/system` → `{tablePrefix, setupPageEnabled, ledger}`(`ledger` 为账本已记录迁移名,按应用顺序)
- `PUT /api/admin/system/setup-page` body `{enabled: boolean}`(严格布尔,非布尔 400 `{"error":"enabled must be a boolean"}`)→ `{setupPageEnabled}`

## Setup(`/api/setup/*`)

- `GET /api/setup/state` → 无鉴权,`Cache-Control: no-store`,`{enabled, ownerExists, tablePrefix}`;不含任何密钥/哈希。`ownerExists` = `{prefix}users` 行数 > 0(表不存在按 `false`)。`enabled`:未初始化恒 `true`;已初始化时只有 `{prefix}settings.setup_page_enabled = '1'` 为开,缺省(无此行)与 `'0'` 均为关。
- `GET /api/setup/status` → 同一逻辑/同一载荷的兼容别名(SPA 已迁到 `state`)。
- `POST /api/setup` → header `X-Setup-Secret`(只走请求头,无 GET/查询参数形态);密钥缺失/占位符 → 500 `{"error":"server misconfigured"}`,不匹配 → 403;按来源 IP 每 10 分钟最多 3 次,超限 429(带 `Retry-After` 与 `retryAfterSeconds`)。动作只有账本迁移(不建用户、不改密码、不删表):200 `{success, tablePrefix, migrations:[{name,status}], ownerExists}`,前缀冲突 409 `{"error":"table prefix conflict","detail":…}`。
- setup 页面开关**只门控页面**,不门控 `POST /api/setup` 与 `POST /api/auth/setup`(密钥即门闩)。

## 说明

- favicon 自动抓取不在后端做:前端直接请求目标站 / 公共 favicon 服务,失败回退首字圆;后端只存 `iconUrl` 字段。
Expand Down
91 changes: 91 additions & 0 deletions worker/src/core/setup-rate-limit.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
import { recordAttempt } from "./login-attempts";
import { generateId } from "./auth";

/**
* Setup-secret throttle (§3.2): at most 3 `POST /api/setup` attempts per source
* IP per 10 minutes → 429.
*
* Reuses the existing `{prefix}login_attempts` store instead of adding a table
* or a framework: rows are keyed by a reserved pseudo-username namespace, so
* they can never collide with a real account (`USERNAME_RE` forbids `:` and
* caps length at 64) and never affect login lockout counters.
*
* An uninitialised database has no `login_attempts` table yet, so the limiter
* falls back to a per-isolate in-memory window — brute force stays throttled
* before the first migration has ever run.
*/
export const SETUP_RATE_LIMIT_MAX = 3;
export const SETUP_RATE_LIMIT_WINDOW_SECONDS = 10 * 60;

const WINDOW_MS = SETUP_RATE_LIMIT_WINDOW_SECONDS * 1000;
const SETUP_ATTEMPT_KEY_PREFIX = "__setup_rate__:";
const MEMORY_MAX_IPS = 500;

/** ip → attempt timestamps (ms), used only while the schema does not exist yet. */
const memoryAttempts = new Map<string, number[]>();

function attemptKey(ip: string): string {
return `${SETUP_ATTEMPT_KEY_PREFIX}${ip}`;
}

function recentMemoryAttempts(ip: string, now: number): number[] {
const recent = (memoryAttempts.get(ip) ?? []).filter(
(at) => now - at < WINDOW_MS,
);
if (recent.length > 0) memoryAttempts.set(ip, recent);
else memoryAttempts.delete(ip);
return recent;
}

function pruneMemory(now: number): void {
if (memoryAttempts.size <= MEMORY_MAX_IPS) return;
for (const ip of [...memoryAttempts.keys()]) {
if (recentMemoryAttempts(ip, now).length === 0) {
memoryAttempts.delete(ip);
}
}
}

/** True when this IP already spent its attempt budget for the window. */
export async function isSetupRateLimited(
db: D1Database,
prefix: string,
ip: string,
): Promise<boolean> {
const now = Date.now();
try {
const since = new Date(now - WINDOW_MS).toISOString();
const row = await db
.prepare(
`SELECT COUNT(*) AS n FROM ${prefix}login_attempts
WHERE username = ? AND created_at > ?`,
)
.bind(attemptKey(ip), since)
.first<{ n: number }>();
return (row?.n ?? 0) >= SETUP_RATE_LIMIT_MAX;
} catch {
return recentMemoryAttempts(ip, now).length >= SETUP_RATE_LIMIT_MAX;
}
}

/** Counts one attempt against the IP's budget (best-effort, never throws). */
export async function recordSetupAttempt(
db: D1Database,
prefix: string,
ip: string,
): Promise<void> {
const now = Date.now();
try {
await recordAttempt(db, prefix, {
id: generateId(),
username: attemptKey(ip),
ip,
success: true,
lockUntil: null,
});
} catch {
// Uninitialised database: keep the window in memory for this isolate.
memoryAttempts.set(ip, [...recentMemoryAttempts(ip, now), now]);
pruneMemory(now);
}
}
21 changes: 5 additions & 16 deletions worker/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,9 @@ import { webauthnRoutes } from "./routes/passkey";
import { publicRoutes } from "./routes/public";
import { privateRoutes } from "./routes/private";
import { adminRoutes } from "./routes/admin";
import { setupRoutes } from "./routes/setup";
import { getSetting } from "./db/queries/settings";
import { countUsers, deleteExpiredSessions } from "./db/queries/users";
import { deleteExpiredSessions } from "./db/queries/users";

const app = new Hono<HonoEnv>();

Expand Down Expand Up @@ -47,26 +48,14 @@ app.route("/api/auth/passkey", webauthnRoutes);
app.route("/api/public", publicRoutes);
app.route("/api/private", privateRoutes);
app.route("/api/admin", adminRoutes);
// Setup surface: GET /api/setup/state (canonical), GET /api/setup/status
// (legacy alias), POST /api/setup (secret-gated upgrade — SETUP-PAGE-SPEC §3).
app.route("/api", setupRoutes);

app.get("/api/health", (c) =>
c.json({ status: "ok", timestamp: new Date().toISOString() }),
);

/**
* GET /api/setup/status — the one endpoint the SPA calls before rendering.
* 200 { enabled: true } while the owner account does not exist yet.
*/
app.get("/api/setup/status", async (c) => {
const prefix = getTablePrefix(c.env);
try {
const users = await countUsers(c.env.DB, prefix);
return c.json({ enabled: users === 0 });
} catch {
// Uninitialized DB: setup is open (migration runs on first setup call).
return c.json({ enabled: true });
}
});

app.get("/api/system/info", async (c) => {
const prefix = getTablePrefix(c.env);
try {
Expand Down
19 changes: 19 additions & 0 deletions worker/src/lib/migrations-runner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -235,6 +235,25 @@ export async function applyMigrationList(
return results;
}

/**
* Migration names already recorded in the ledger, in application order. Read-only
* and tolerant of a not-yet-created ledger table (returns an empty list), so the
* admin system panel can always render.
*/
export async function listRecordedMigrations(
db: D1Database,
prefix: string,
): Promise<string[]> {
try {
const { results } = await db
.prepare(`SELECT name FROM ${migrationsTable(prefix)} ORDER BY rowid`)
.all<{ name: string }>();
return results.map((row) => row.name);
} catch {
return [];
}
}

/**
* Resolves the effective prefix, guards against a silent prefix switch, then
* applies every migration not yet recorded in the ledger. Throws
Expand Down
38 changes: 38 additions & 0 deletions worker/src/routes/admin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,15 @@ import {
updateSearchEngine,
} from "../db/queries/content";
import { getAllSettings, setSetting } from "../db/queries/settings";
import { listRecordedMigrations } from "../lib/migrations-runner";
import { generateId } from "../core/auth";
import type { Link } from "../types";
import { toSearchEngineDto, toSiteSettingsDto } from "../services/site-data";
import {
getSetupPageEnabled,
runSetupMigrations,
setSetupPageEnabled,
} from "../services/setup";

export const adminRoutes = new Hono<HonoEnv>();

Expand Down Expand Up @@ -444,5 +450,37 @@ adminRoutes.put("/settings", async (c) => {

adminRoutes.get("/settings/keys", (c) => c.json({ keys: SETTING_KEYS }));

// ─── System: database maintenance + setup page switch (SPEC §3.5) ────────────

/**
* POST /api/admin/setup — session-authenticated (no setup secret) upgrade.
* Payload and 409 conflict shape are identical to POST /api/setup.
*/
adminRoutes.post("/setup", async (c) => {
const outcome = await runSetupMigrations(c.env);
if (!outcome.ok) return c.json(outcome.body, outcome.status);
return c.json(outcome.body);
});

/** GET /api/admin/system — effective prefix, page switch, recorded ledger. */
adminRoutes.get("/system", async (c) => {
const prefix = getTablePrefix(c.env);
const [ledger, setupPageEnabled] = await Promise.all([
listRecordedMigrations(c.env.DB, prefix),
getSetupPageEnabled(c.env, prefix),
]);
return c.json({ tablePrefix: prefix, setupPageEnabled, ledger });
});

/** PUT /api/admin/system/setup-page — body `{enabled: boolean}` (strict). */
adminRoutes.put("/system/setup-page", async (c) => {
const body = await c.req.json().catch(() => ({}));
if (typeof body?.enabled !== "boolean")
return badRequest("enabled must be a boolean");

await setSetupPageEnabled(c.env, body.enabled);
return c.json({ setupPageEnabled: body.enabled });
});

// Fallbacks kept intentionally strict: unknown admin routes are 404 JSON.
adminRoutes.all("*", (c) => c.json({ error: "not found" }, 404));
6 changes: 6 additions & 0 deletions worker/src/routes/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ import {
putChallenge,
} from "../core/challenges";
import { getSetting } from "../db/queries/settings";
import { setSetupPageEnabled } from "../services/setup";
import { verifyTOTP } from "../core/totp";
import { SESSION_COOKIE, unauthorized } from "../middleware/auth";
import { issueSession, clientIp } from "../services/session";
Expand Down Expand Up @@ -118,6 +119,11 @@ authRoutes.post("/setup", async (c) => {
const created = await findUserByUsername(c.env.DB, prefix, username);
if (!created) return c.json({ error: "setup failed" }, 500);

// SETUP-PAGE-SPEC §3.4: completion closes the setup page by default (nav is a
// single-user site). Routine upgrades go through the admin button; the secret
// endpoints themselves stay reachable regardless of this switch.
await setSetupPageEnabled(c.env, false, prefix);

await issueSession(c, created.id);
return c.json(
{
Expand Down
68 changes: 68 additions & 0 deletions worker/src/routes/setup.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import { Hono, type Context } from "hono";
import { getTablePrefix, type HonoEnv } from "../types";
import { safeEqual } from "../core/auth";
import {
isSetupRateLimited,
recordSetupAttempt,
SETUP_RATE_LIMIT_WINDOW_SECONDS,
} from "../core/setup-rate-limit";
import { clientIp } from "../services/session";
import { resolveSetupState, runSetupMigrations } from "../services/setup";

/**
* Setup surface (SETUP-PAGE-SPEC §3.1–§3.2). Mounted at `/api`, so:
* - `GET /api/setup/state` — canonical state endpoint (no auth, no-store)
* - `GET /api/setup/status` — legacy alias, identical payload/logic
* - `POST /api/setup` — secret-gated, migration-only upgrade endpoint
*
* The switch in §3.4 gates the PAGE only; it never gates these secret-gated
* endpoints (the secret is the latch), so a closed page can never deadlock
* recovery.
*/
export const setupRoutes = new Hono<HonoEnv>();

async function setupState(c: Context<HonoEnv>): Promise<Response> {
const state = await resolveSetupState(c.env);
c.header("Cache-Control", "no-store");
return c.json(state);
}

setupRoutes.get("/setup/state", setupState);

// Deprecated alias kept for SPA compatibility; same logic, same payload.
setupRoutes.get("/setup/status", setupState);

setupRoutes.post("/setup", async (c) => {
// The secret is a request header only — never URL/query (no GET variant).
const expected = c.env.SETUP_SECRET;
if (!expected || expected.endsWith("_PLACEHOLDER")) {
return c.json({ error: "server misconfigured" }, 500);
}

const prefix = getTablePrefix(c.env);
const ip = clientIp(c);

if (await isSetupRateLimited(c.env.DB, prefix, ip)) {
return c.json(
{
error: "too many setup attempts, try again later",
retryAfterSeconds: SETUP_RATE_LIMIT_WINDOW_SECONDS,
},
429,
{ "Retry-After": String(SETUP_RATE_LIMIT_WINDOW_SECONDS) },
);
}
// Every attempt spends budget, including wrong secrets.
await recordSetupAttempt(c.env.DB, prefix, ip);

const secret = c.req.header("X-Setup-Secret");
if (!secret || !(await safeEqual(secret, expected))) {
return c.json({ error: "invalid setup secret" }, 403);
}

// Forward-only, ledgered migrations only: no user created, no password
// changed, no table dropped.
const outcome = await runSetupMigrations(c.env);
if (!outcome.ok) return c.json(outcome.body, outcome.status);
return c.json(outcome.body);
});
Loading
Loading