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
4 changes: 3 additions & 1 deletion docs/api-contract.md
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,9 @@ Passkey(WebAuthn,/api/auth/passkey/*,@simplewebauthn/server v14):
### 站点设置

- `GET /api/admin/settings` → `{siteTitle, backgroundUrl, logoUrl, theme, columns}`
- `PUT /api/admin/settings` body 可含 `{siteTitle, backgroundUrl, logoUrl, theme(light|dark|system), columns(1–12)}` → 更新后对象
- `PUT /api/admin/settings` body 可含 `{siteTitle, backgroundUrl, logoUrl, theme(light|dark|system), columns(0–12)}` → 更新后对象

`columns` 允许 `0–12`,其中 `0` 表示**未配置**(用默认值):`0` 原样存入并原样返回,不会被替换成默认列数。`GET /api/admin/settings` 对未配置的库返回 `columns: 0`,所以 `0–12` 都能往返提交;超出范围返回 400 `columns must be between 0 and 12`。

`backgroundUrl` / `logoUrl` 的值可以是外链 URL,也可以是本地上传路径(`/assets/…`,见下节)。`/assets/…` 被替换成**任何**其他值时,旧 R2 对象自动删除;外链旧值一律不删。

Expand Down
2 changes: 1 addition & 1 deletion web/src/lib/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ export interface SiteSettings {
siteTitle: string;
backgroundUrl: string;
theme: "system" | "light" | "dark";
/** 1–12,0 表示未配置(用默认值) */
/** 0–12(后端接受并原样存储),0 表示未配置(用默认值) */
columns: number;
}

Expand Down
7 changes: 5 additions & 2 deletions worker/src/routes/admin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -452,8 +452,11 @@ adminRoutes.put("/settings", async (c) => {
}
if (body.columns !== undefined) {
const columns = Number.parseInt(String(body.columns), 10);
if (!Number.isFinite(columns) || columns < 1 || columns > 12)
return badRequest("columns must be between 1 and 12");
// 0 is a valid value: it means "unconfigured" (the GET DTO reports it
// since a fresh database has no columns row), so it must round-trip and is
// stored verbatim rather than coerced to a default.
if (!Number.isFinite(columns) || columns < 0 || columns > 12)
return badRequest("columns must be between 0 and 12");
updates.columns = String(columns);
}

Expand Down
1 change: 1 addition & 0 deletions worker/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,7 @@ export interface SiteSettingsDto {
/** Local upload path (`/assets/…`) or an external URL; "" when unset. */
logoUrl: string;
theme: string;
/** 0–12; 0 means "unconfigured" (the consumer applies its default). */
columns: number;
}

Expand Down
148 changes: 148 additions & 0 deletions worker/test/settings.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
import { beforeEach, describe, expect, it } from "vitest";
import { Hono } from "hono";
import { runMigrations } from "../src/lib/migrations-runner";
import { authRoutes } from "../src/routes/auth";
import { adminRoutes } from "../src/routes/admin";
import type { Env } from "../src/types";
import { makeEnv, readJson, type SqliteD1 } from "./helpers";

/**
* `PUT /api/admin/settings` columns validation (contract: 0–12).
*
* `0` means "unconfigured": `GET /api/admin/settings` reports it on a fresh
* database, so it has to be writable verbatim — otherwise reading a fresh
* setting and saving it back fails with a 400.
*/

const OWNER_PASSWORD = "correct horse battery";

function makeApp(): Hono {
const app = new Hono();
app.route("/api/auth", authRoutes);
app.route("/api/admin", adminRoutes);
return app;
}

async function signIn(app: Hono, env: Env): Promise<string> {
const res = await app.request(
"/api/auth/setup",
{
method: "POST",
body: JSON.stringify({ username: "owner", password: OWNER_PASSWORD }),
headers: {
"content-type": "application/json",
"x-setup-secret": "test-setup-secret",
},
},
env,
);
expect(res.status).toBe(201);
return res.headers.get("set-cookie") ?? "";
}

function getSettings(app: Hono, env: Env, cookie: string): Promise<Response> {
return app.request("/api/admin/settings", { headers: { cookie } }, env);
}

function putSettings(
app: Hono,
env: Env,
cookie: string,
body: unknown,
): Promise<Response> {
return app.request(
"/api/admin/settings",
{
method: "PUT",
body: JSON.stringify(body),
headers: { "content-type": "application/json", cookie },
},
env,
);
}

/** Raw stored value of the `columns` setting row, or `null` when absent. */
function storedColumns(env: Env): string | null {
const row = (env.DB as unknown as SqliteD1).db
.prepare("SELECT value FROM settings WHERE key = 'columns'")
.get() as { value: string } | undefined;
return row?.value ?? null;
}

describe("PUT /api/admin/settings columns", () => {
let env: Env;
let app: Hono;
let cookie: string;

beforeEach(async () => {
env = makeEnv();
app = makeApp();
await runMigrations(env);
cookie = await signIn(app, env);
});

it("round-trips columns=0 on a fresh database (GET 0 → PUT 0 → GET 0)", async () => {
// Fresh D1: no columns row yet, so the contract-visible value is 0.
const before = await readJson(await getSettings(app, env, cookie));
expect(before.columns).toBe(0);

const res = await putSettings(app, env, cookie, {
columns: before.columns,
});
expect(res.status).toBe(200);
expect((await readJson(res)).columns).toBe(0);

// Stored verbatim — not coerced to a default column count.
expect(storedColumns(env)).toBe("0");

const after = await readJson(await getSettings(app, env, cookie));
expect(after.columns).toBe(0);
});

it("keeps 0 when it is written together with other settings", async () => {
const res = await putSettings(app, env, cookie, {
siteTitle: "nav",
backgroundUrl: "",
logoUrl: "",
theme: "dark",
columns: 0,
});
expect(res.status).toBe(200);
const body = await readJson(res);
expect(body).toMatchObject({ siteTitle: "nav", theme: "dark", columns: 0 });
expect(storedColumns(env)).toBe("0");
});

it("accepts every value in 1–12 (existing range unchanged)", async () => {
for (let columns = 1; columns <= 12; columns++) {
const res = await putSettings(app, env, cookie, { columns });
expect(res.status).toBe(200);
expect((await readJson(res)).columns).toBe(columns);
expect(storedColumns(env)).toBe(String(columns));
}
});

it("still rejects values outside 0–12", async () => {
await putSettings(app, env, cookie, { columns: 5 });

for (const columns of [-1, 13, 100]) {
const res = await putSettings(app, env, cookie, { columns });
expect(res.status).toBe(400);
expect(await readJson(res)).toEqual({
error: "columns must be between 0 and 12",
});
}
// A rejected write must not touch the stored value.
expect(storedColumns(env)).toBe("5");
});

it("rejects non-numeric columns with the same 400", async () => {
for (const columns of ["abc", "", null, true]) {
const res = await putSettings(app, env, cookie, { columns });
expect(res.status).toBe(400);
expect(await readJson(res)).toEqual({
error: "columns must be between 0 and 12",
});
}
});
});
Loading