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
24 changes: 22 additions & 2 deletions docs/api-contract.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
"settings": {
"siteTitle": "nav",
"backgroundUrl": "",
"logoUrl": "",
"theme": "system",
"columns": 0
}
Expand Down Expand Up @@ -111,11 +112,30 @@ 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)}` → 更新后对象
- `GET /api/admin/settings` → `{siteTitle, backgroundUrl, logoUrl, theme, columns}`
- `PUT /api/admin/settings` body 可含 `{siteTitle, backgroundUrl, logoUrl, theme(light|dark|system), columns(1–12)}` → 更新后对象

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

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

### 资源(上传图片,ONE-444)

上传对象存在 R2 桶 `nav-assets`(Worker 绑定名 `R2`;`ASSETS` 已被 Workers Static Assets 占用)。对象键 `assets/{purpose}/{uuid}.{ext}`,公开路径 `/assets/{key}`(因此实际形如 `/assets/assets/background/…`,为父单冻结的字面规则)。
- `POST /api/admin/assets`(需会话,`multipart/form-data`)
- 字段:`file`(必填)、`purpose`(必填,`background` | `logo` | `icon`)。
- 双重校验:声明的 Content-Type 必须是 `image/png` / `image/jpeg` / `image/webp` / `image/gif` / `image/svg+xml` / `image/x-icon`(也接受 `image/vnd.microsoft.icon`)之一,**且**文件头魔数与之相符;SVG 无魔数,改为校验内容前缀(允许 BOM/空白后)为 `<?xml` 或 `<svg>`。扩展名由校验出的类型决定(png/jpg/webp/gif/svg/ico),不信任文件名。
- 大小:`background` ≤ 5MB;`logo`、`icon` ≤ 1MB。
- 201 `{ "path": "/assets/assets/{purpose}/{uuid}.{ext}" }`
- 400 `{"error":"…"}`:purpose 非法/缺失、缺 file、Content-Type 不支持、内容与声明不符、空文件;413 `{"error":"…"}`:超出该用途上限(文案含实际字节数与上限)。
- 环境未绑定 R2 → 503 `{"error":"asset storage unavailable: …"}`(不崩)。
- `GET /assets/*`(公开读,无鉴权;`*` 即对象键)
- 200:正确 `Content-Type`;`Cache-Control: public, max-age=31536000, immutable`;`X-Content-Type-Options: nosniff`(SVG 固定 `image/svg+xml`,不会被当 HTML 解析)。
- 对象不存在或环境未绑定 R2 → 404。
- `DELETE /api/admin/assets`(需会话)body `{ "key": "assets/{purpose}/{uuid}.{ext}" }`(也接受公开路径形式)→ `{ "success": true }`;缺 key → 400;未绑定 R2 → 503。

自动清旧:`PUT /api/admin/settings` 中 `backgroundUrl` 或 `logoUrl` 从某个 `/assets/…` 值被替换成别的值(外链或新上传路径)时,旧 R2 对象被删除;旧值为外链时不删。

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

- `POST /api/admin/setup` → 免密钥跑账本迁移,响应形状与 `POST /api/setup` 完全一致(含 409 冲突形状)
Expand Down
5 changes: 5 additions & 0 deletions worker/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { publicRoutes } from "./routes/public";
import { privateRoutes } from "./routes/private";
import { adminRoutes } from "./routes/admin";
import { setupRoutes } from "./routes/setup";
import { assetPublicRoutes } from "./routes/assets";
import { getSetting } from "./db/queries/settings";
import { deleteExpiredSessions } from "./db/queries/users";

Expand Down Expand Up @@ -74,6 +75,10 @@ app.get("/api/system/info", async (c) => {
}
});

// Uploaded assets are served straight from R2. This MUST be registered before
// the SPA fallback below, otherwise static assets would answer every request.
app.route("/assets", assetPublicRoutes);

// Static assets (Workers Static Assets binding), SPA fallback to index.html.
app.get("*", async (c) => {
const res = await c.env.ASSETS.fetch(c.req.raw);
Expand Down
42 changes: 41 additions & 1 deletion worker/src/routes/admin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ import { listRecordedMigrations } from "../lib/migrations-runner";
import { generateId } from "../core/auth";
import type { Link } from "../types";
import { toSearchEngineDto, toSiteSettingsDto } from "../services/site-data";
import { deleteAssetByPublicPath } from "../services/assets";
import { deleteAsset, uploadAsset } from "./assets";
import {
getSetupPageEnabled,
runSetupMigrations,
Expand Down Expand Up @@ -408,6 +410,7 @@ adminRoutes.post("/search-engines/reorder", async (c) => {
const SETTING_KEYS = [
"site_title",
"background_url",
"logo_url",
"theme",
"columns",
] as const;
Expand All @@ -422,11 +425,25 @@ adminRoutes.get("/settings", async (c) => {
adminRoutes.put("/settings", async (c) => {
const prefix = getTablePrefix(c.env);
const body = await c.req.json().catch(() => ({}));
const previous = await getAllSettings(c.env.DB, prefix);

const updates: Record<string, string> = {};
/** Local `/assets/…` values orphaned by this write (owner of the binding). */
const replacedAssets: string[] = [];

if (body.siteTitle !== undefined) updates.site_title = String(body.siteTitle);
if (body.backgroundUrl !== undefined)
if (body.backgroundUrl !== undefined) {
updates.background_url = String(body.backgroundUrl);
collectReplacedAsset(
previous.background_url,
updates.background_url,
replacedAssets,
);
}
if (body.logoUrl !== undefined) {
updates.logo_url = String(body.logoUrl);
collectReplacedAsset(previous.logo_url, updates.logo_url, replacedAssets);
}
if (body.theme !== undefined) {
const theme = String(body.theme);
if (!["light", "dark", "system"].includes(theme))
Expand All @@ -444,12 +461,35 @@ adminRoutes.put("/settings", async (c) => {
await setSetting(c.env.DB, prefix, key, value);
}

// Auto-clean: a local upload that was just replaced is deleted from R2.
// External URLs never reach this list, and a missing binding is a no-op.
for (const publicPath of replacedAssets) {
await deleteAssetByPublicPath(c.env.R2, publicPath);
}

const settings = await getAllSettings(c.env.DB, prefix);
return c.json(toSiteSettingsDto(settings));
});

/** Queue the old value for deletion when a local upload is replaced by anything else. */
function collectReplacedAsset(
previousValue: string | undefined,
nextValue: string,
into: string[],
): void {
if (!previousValue || previousValue === nextValue) return;
if (previousValue.startsWith("/assets/")) into.push(previousValue);
}

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

// ─── Assets (uploaded images in R2, SPEC ONE-444) ────────────────────────────

// Both handlers sit inside adminRoutes, so authMiddleware already requires a
// session. Must stay above the strict admin 404 fallback below.
adminRoutes.post("/assets", uploadAsset);
adminRoutes.delete("/assets", deleteAsset);

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

/**
Expand Down
138 changes: 138 additions & 0 deletions worker/src/routes/assets.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
import type { Context } from "hono";
import { Hono } from "hono";
import type { HonoEnv } from "../types";
import {
ASSET_CACHE_CONTROL,
ASSET_PUBLIC_PREFIX,
assetKeyFromPublicPath,
assetObjectKey,
assetPublicPath,
assetSizeError,
isAssetPurpose,
mimeForExt,
validateImageUpload,
} from "../services/assets";

/**
* Public asset surface: `GET /assets/*` streams objects back from R2.
* Mounted in index.ts BEFORE the SPA fallback (`app.get("*")`), otherwise the
* static-assets handler would swallow every request.
*/
export const assetPublicRoutes = new Hono<HonoEnv>();

function assetHeaders(contentType: string): Record<string, string> {
return {
"Content-Type": contentType,
"Cache-Control": ASSET_CACHE_CONTROL,
// Uploads are user-supplied: never let a browser re-sniff (SVG → HTML).
"X-Content-Type-Options": "nosniff",
};
}

assetPublicRoutes.get("/*", async (c) => {
// Local/preview environments may have no R2 binding at all: 404, never 500.
const bucket = c.env.R2;
if (!bucket) return c.json({ error: "not found" }, 404);

const key = c.req.path.slice(ASSET_PUBLIC_PREFIX.length);
if (!key || key.includes("..")) return c.json({ error: "not found" }, 404);

const object = await bucket.get(key);
if (!object) return c.json({ error: "not found" }, 404);

const ext = key.split(".").pop() ?? "";
const contentType =
ext === "svg"
? "image/svg+xml"
: (mimeForExt(ext) ?? "application/octet-stream");

return new Response(object.body, {
status: 200,
headers: assetHeaders(contentType),
});
});

// ─── Admin handlers (registered inside adminRoutes → session required) ────────

function storageUnavailable(c: Context<HonoEnv>): Response {
return c.json(
{
error:
"asset storage unavailable: the R2 binding is not configured in this environment",
},
503,
);
}

function isFileLike(value: unknown): value is File {
return (
typeof value === "object" &&
value !== null &&
typeof (value as File).arrayBuffer === "function" &&
typeof (value as File).size === "number"
);
}

/**
* `POST /api/admin/assets` — multipart `file` + `purpose`
* (`background` | `logo` | `icon`) → 201 `{path: "/assets/assets/{purpose}/{uuid}.{ext}"}`.
*/
export async function uploadAsset(c: Context<HonoEnv>): Promise<Response> {
const bucket = c.env.R2;
if (!bucket) return storageUnavailable(c);

const body = await c.req
.parseBody()
.catch(() => ({}) as Record<string, string | File>);

const purpose = body.purpose;
if (!isAssetPurpose(purpose)) {
return c.json(
{ error: "purpose is required and must be background, logo or icon" },
400,
);
}

const file = body.file;
if (!isFileLike(file)) {
return c.json({ error: "file is required (multipart field 'file')" }, 400);
}

const sizeError = assetSizeError(purpose, file.size);
if (sizeError) return c.json({ error: sizeError }, 413);

const bytes = new Uint8Array(await file.arrayBuffer());
const validation = validateImageUpload({
purpose,
contentType: file.type,
bytes,
});
if (!validation.ok) {
return c.json({ error: validation.error }, validation.status);
}

const key = assetObjectKey(purpose, validation.image.ext);
await bucket.put(key, bytes, {
httpMetadata: {
contentType: validation.image.mime,
cacheControl: ASSET_CACHE_CONTROL,
},
});

return c.json({ path: assetPublicPath(key) }, 201);
}

/** `DELETE /api/admin/assets` — body `{key}` → `{success:true}`. */
export async function deleteAsset(c: Context<HonoEnv>): Promise<Response> {
const bucket = c.env.R2;
if (!bucket) return storageUnavailable(c);

const body = await c.req.json().catch(() => ({}));
const key = typeof body?.key === "string" ? body.key.trim() : "";
if (!key) return c.json({ error: "key is required" }, 400);
// Accept both the raw object key and the public path clients were handed.
const objectKey = assetKeyFromPublicPath(key) ?? key;

await bucket.delete(objectKey);
return c.json({ success: true });
}
Loading
Loading