From 5e8ffdd5156daac7559ecba52feca86fbfdca6c4 Mon Sep 17 00:00:00 2001 From: mapxn <16299874+mapxn@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:34:42 +0800 Subject: [PATCH] =?UTF-8?q?ONE-450:=20R2=20=E8=B5=84=E6=BA=90=E4=B8=8A?= =?UTF-8?q?=E4=BC=A0/=E5=85=AC=E5=BC=80=E8=AF=BB=E5=8F=96/=E5=88=A0?= =?UTF-8?q?=E9=99=A4=20+=20=E7=AB=99=E7=82=B9=E8=AE=BE=E7=BD=AE=20logoUrl?= =?UTF-8?q?=EF=BC=88=E5=A4=8D=E6=9D=82=E6=A1=A3=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/api-contract.md | 24 +- worker/src/index.ts | 5 + worker/src/routes/admin.ts | 42 ++- worker/src/routes/assets.ts | 138 ++++++++ worker/src/services/assets.ts | 257 ++++++++++++++ worker/src/services/site-data.ts | 1 + worker/src/types.ts | 8 + worker/test/assets.test.ts | 584 +++++++++++++++++++++++++++++++ worker/test/helpers.ts | 59 ++++ worker/test/setup.test.ts | 1 + worker/wrangler.toml | 7 + 11 files changed, 1123 insertions(+), 3 deletions(-) create mode 100644 worker/src/routes/assets.ts create mode 100644 worker/src/services/assets.ts create mode 100644 worker/test/assets.test.ts diff --git a/docs/api-contract.md b/docs/api-contract.md index 37dabdf..f2fb812 100644 --- a/docs/api-contract.md +++ b/docs/api-contract.md @@ -42,6 +42,7 @@ "settings": { "siteTitle": "nav", "backgroundUrl": "", + "logoUrl": "", "theme": "system", "columns": 0 } @@ -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/空白后)为 ``。扩展名由校验出的类型决定(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 冲突形状) diff --git a/worker/src/index.ts b/worker/src/index.ts index 352bb3a..90baa05 100644 --- a/worker/src/index.ts +++ b/worker/src/index.ts @@ -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"; @@ -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); diff --git a/worker/src/routes/admin.ts b/worker/src/routes/admin.ts index 61eb8c5..20c89fa 100644 --- a/worker/src/routes/admin.ts +++ b/worker/src/routes/admin.ts @@ -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, @@ -408,6 +410,7 @@ adminRoutes.post("/search-engines/reorder", async (c) => { const SETTING_KEYS = [ "site_title", "background_url", + "logo_url", "theme", "columns", ] as const; @@ -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 = {}; + /** 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)) @@ -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) ──────────── /** diff --git a/worker/src/routes/assets.ts b/worker/src/routes/assets.ts new file mode 100644 index 0000000..9568c9b --- /dev/null +++ b/worker/src/routes/assets.ts @@ -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(); + +function assetHeaders(contentType: string): Record { + 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): 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): Promise { + const bucket = c.env.R2; + if (!bucket) return storageUnavailable(c); + + const body = await c.req + .parseBody() + .catch(() => ({}) as Record); + + 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): Promise { + 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 }); +} diff --git a/worker/src/services/assets.ts b/worker/src/services/assets.ts new file mode 100644 index 0000000..2178dca --- /dev/null +++ b/worker/src/services/assets.ts @@ -0,0 +1,257 @@ +/** + * Asset (R2) helpers: upload validation, object keys, public paths. + * Contract: docs/api-contract.md §资源(/assets/*、/api/admin/assets). + * + * Validation is deliberately double: the declared Content-Type must be one of + * the allowed image types AND the file's leading bytes must prove that same + * type. The extension we store is derived from the verified type — the user's + * filename is never trusted. + */ + +export const ASSET_PURPOSES = ["background", "logo", "icon"] as const; +export type AssetPurpose = (typeof ASSET_PURPOSES)[number]; + +export function isAssetPurpose(value: unknown): value is AssetPurpose { + return ( + typeof value === "string" && + (ASSET_PURPOSES as readonly string[]).includes(value) + ); +} + +/** Per-purpose upload limits. */ +export const MAX_ASSET_BYTES: Record = { + background: 5 * 1024 * 1024, + logo: 1024 * 1024, + icon: 1024 * 1024, +}; + +export type ImageKind = "png" | "jpg" | "webp" | "gif" | "svg" | "ico"; + +/** Declared Content-Type → image kind (the only accepted declarations). */ +const KIND_BY_MIME: Record = { + "image/png": "png", + "image/jpeg": "jpg", + "image/webp": "webp", + "image/gif": "gif", + "image/svg+xml": "svg", + "image/x-icon": "ico", + "image/vnd.microsoft.icon": "ico", +}; + +/** Verified image kind → extension used in the object key. */ +const EXT_BY_KIND: Record = { + png: "png", + jpg: "jpg", + webp: "webp", + gif: "gif", + svg: "svg", + ico: "ico", +}; + +/** Verified image kind → Content-Type served by GET /assets/*. */ +const MIME_BY_KIND: Record = { + png: "image/png", + jpg: "image/jpeg", + webp: "image/webp", + gif: "image/gif", + svg: "image/svg+xml", + ico: "image/x-icon", +}; + +export const ALLOWED_UPLOAD_MIME_TYPES = Object.keys(KIND_BY_MIME); + +/** Immutable caching: object keys are uuid-based and never rewritten. */ +export const ASSET_CACHE_CONTROL = "public, max-age=31536000, immutable"; + +/** Objects are keyed `assets/…` and publicly served at `/assets/{key}`. */ +export const ASSET_PUBLIC_PREFIX = "/assets/"; + +export function mimeForExt(ext: string): string | null { + const entry = Object.entries(EXT_BY_KIND).find(([, value]) => value === ext); + return entry ? MIME_BY_KIND[entry[0] as ImageKind] : null; +} + +/** Object key for a validated upload: `assets/{purpose}/{uuid}.{ext}`. */ +export function assetObjectKey(purpose: AssetPurpose, ext: string): string { + return `assets/${purpose}/${crypto.randomUUID()}.${ext}`; +} + +/** `/assets/{key}` — the value returned to clients and stored in settings. */ +export function assetPublicPath(key: string): string { + return `${ASSET_PUBLIC_PREFIX}${key}`; +} + +/** + * Inverse of `assetPublicPath`: only local uploads are R2-backed. External + * URLs (anything not starting with `/assets/`) return null and are never + * deleted from the bucket. + */ +export function assetKeyFromPublicPath(value: string): string | null { + if (!value.startsWith(ASSET_PUBLIC_PREFIX)) return null; + const key = value.slice(ASSET_PUBLIC_PREFIX.length); + return key || null; +} + +/** Delete a replaced local asset; missing binding or errors are non-fatal. */ +export async function deleteAssetByPublicPath( + bucket: R2Bucket | undefined, + publicPath: string, +): Promise { + const key = assetKeyFromPublicPath(publicPath); + if (!key || !bucket) return false; + try { + await bucket.delete(key); + return true; + } catch (err) { + // Cleaning up an orphan must never fail the settings write that replaced it. + console.warn(`failed to delete replaced asset "${key}"`, err); + return false; + } +} + +// ─── Content inspection ────────────────────────────────────────────────────── + +function asciiBytes(text: string): number[] { + return Array.from(text, (char) => char.charCodeAt(0)); +} + +function startsWithBytes( + bytes: Uint8Array, + offset: number, + signature: readonly number[], +): boolean { + if (bytes.length < offset + signature.length) return false; + return signature.every((byte, i) => bytes[offset + i] === byte); +} + +const PNG_SIGNATURE = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]; +const JPEG_SIGNATURE = [0xff, 0xd8, 0xff]; +const RIFF_SIGNATURE = asciiBytes("RIFF"); +const WEBP_SIGNATURE = asciiBytes("WEBP"); +const GIF87A_SIGNATURE = asciiBytes("GIF87a"); +const GIF89A_SIGNATURE = asciiBytes("GIF89a"); +const ICO_SIGNATURE = [0x00, 0x00, 0x01, 0x00]; + +/** Binary image kinds proven by their magic bytes. SVG has no magic bytes. */ +export function detectBinaryImageKind(bytes: Uint8Array): ImageKind | null { + if (startsWithBytes(bytes, 0, PNG_SIGNATURE)) return "png"; + if (startsWithBytes(bytes, 0, JPEG_SIGNATURE)) return "jpg"; + if ( + startsWithBytes(bytes, 0, RIFF_SIGNATURE) && + startsWithBytes(bytes, 8, WEBP_SIGNATURE) + ) + return "webp"; + if ( + startsWithBytes(bytes, 0, GIF87A_SIGNATURE) || + startsWithBytes(bytes, 0, GIF89A_SIGNATURE) + ) + return "gif"; + if (startsWithBytes(bytes, 0, ICO_SIGNATURE)) return "ico"; + return null; +} + +/** + * SVG probe: after an optional BOM and leading whitespace the document must + * open with ` 0 ? columns : 0, }; diff --git a/worker/src/types.ts b/worker/src/types.ts index c25587b..5bc0718 100644 --- a/worker/src/types.ts +++ b/worker/src/types.ts @@ -22,6 +22,12 @@ export interface Env { /** Wrangler secret / local env var — never in wrangler.toml. */ SETUP_SECRET: string; ASSETS: Fetcher; + /** + * R2 bucket `nav-assets` for uploaded images (binding name `R2` — `ASSETS` + * is already taken by Workers Static Assets). Absent in environments + * without the binding; handlers must degrade to 503/404 accordingly. + */ + R2: R2Bucket; /** * Table prefix (SPEC v1.4). Injected at deploy time; absent when * unconfigured so the Worker defaults to DEFAULT_TABLE_PREFIX. @@ -144,6 +150,8 @@ export interface SearchEngineDto { export interface SiteSettingsDto { siteTitle: string; backgroundUrl: string; + /** Local upload path (`/assets/…`) or an external URL; "" when unset. */ + logoUrl: string; theme: string; columns: number; } diff --git a/worker/test/assets.test.ts b/worker/test/assets.test.ts new file mode 100644 index 0000000..05e87f7 --- /dev/null +++ b/worker/test/assets.test.ts @@ -0,0 +1,584 @@ +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 { assetPublicRoutes } from "../src/routes/assets"; +import type { Env } from "../src/types"; +import { MemoryR2, makeEnv, readJson } from "./helpers"; + +const SETUP_SECRET_HEADER = "x-setup-secret"; +const OWNER_PASSWORD = "owner-password-1"; + +// ─── Fixtures ──────────────────────────────────────────────────────────────── + +const PNG_BYTES = new Uint8Array([ + 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, + 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, +]); + +const JPEG_BYTES = new Uint8Array([ + 0xff, 0xd8, 0xff, 0xe0, 0x00, 0x10, 0x4a, 0x46, 0x49, 0x46, +]); + +const WEBP_BYTES = new Uint8Array([ + // "RIFF" + size + "WEBP" + 0x52, 0x49, 0x46, 0x46, 0x24, 0x00, 0x00, 0x00, 0x57, 0x45, 0x42, 0x50, 0x56, + 0x50, 0x38, 0x20, +]); + +const GIF_BYTES = new Uint8Array([ + // "GIF89a" + 0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0x01, 0x00, 0x01, 0x00, +]); + +const ICO_BYTES = new Uint8Array([ + 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x10, 0x10, 0x00, 0x00, +]); + +const SVG_BYTES = new TextEncoder().encode( + '', +); + +/** PNG magic bytes padded to `size` so only the size check can fail. */ +function pngOfSize(size: number): Uint8Array { + const bytes = new Uint8Array(size); + bytes.set(PNG_BYTES.subarray(0, Math.min(PNG_BYTES.length, size))); + return bytes; +} + +// ─── Harness ───────────────────────────────────────────────────────────────── + +function makeApp(): Hono { + const app = new Hono(); + app.route("/api/auth", authRoutes); + app.route("/api/admin", adminRoutes); + app.route("/assets", assetPublicRoutes); + return app; +} + +async function signIn(app: Hono, env: Env): Promise { + const res = await app.request( + "/api/auth/setup", + { + method: "POST", + body: JSON.stringify({ username: "owner", password: OWNER_PASSWORD }), + headers: { + "content-type": "application/json", + [SETUP_SECRET_HEADER]: "test-setup-secret", + }, + }, + env, + ); + expect(res.status).toBe(201); + return res.headers.get("set-cookie") ?? ""; +} + +function upload( + app: Hono, + env: Env, + cookie: string, + bytes: Uint8Array, + type: string, + options: { purpose?: string; filename?: string } = {}, +): Promise { + const form = new FormData(); + if (options.purpose !== undefined) form.set("purpose", options.purpose); + form.set( + "file", + new File([bytes], options.filename ?? "upload.bin", { type }), + ); + return app.request( + "/api/admin/assets", + { method: "POST", body: form, headers: { cookie } }, + env, + ); +} + +function putSettings( + app: Hono, + env: Env, + cookie: string, + body: unknown, +): Promise { + return app.request( + "/api/admin/settings", + { + method: "PUT", + body: JSON.stringify(body), + headers: { "content-type": "application/json", cookie }, + }, + env, + ); +} + +const KEY_RE = + /^\/assets\/assets\/(background|logo|icon)\/[0-9a-f-]{36}\.(png|jpg|webp|gif|svg|ico)$/; + +/** `/assets/{key}` → `{key}` (the R2 object key). */ +function objectKeyFromPath(publicPath: string): string { + return publicPath.replace(/^\/assets\//, ""); +} + +describe("POST /api/admin/assets", () => { + let env: Env; + let r2: MemoryR2; + let app: Hono; + let cookie: string; + + beforeEach(async () => { + r2 = new MemoryR2(); + env = makeEnv({ R2: r2 as unknown as R2Bucket }); + app = makeApp(); + await runMigrations(env); + cookie = await signIn(app, env); + }); + + it("requires a session (401 JSON)", async () => { + const form = new FormData(); + form.set("purpose", "background"); + form.set("file", new File([PNG_BYTES], "bg.png", { type: "image/png" })); + const res = await app.request( + "/api/admin/assets", + { method: "POST", body: form }, + env, + ); + expect(res.status).toBe(401); + expect(await readJson(res)).toEqual({ error: "unauthorized" }); + expect(r2.objects.size).toBe(0); + }); + + it("accepts a PNG and returns the frozen /assets/ + key path", async () => { + const res = await upload(app, env, cookie, PNG_BYTES, "image/png", { + purpose: "background", + // Filename must never influence the stored extension. + filename: "not-really-a-page.html", + }); + expect(res.status).toBe(201); + const { path } = await readJson(res); + expect(path).toMatch(KEY_RE); + expect(path.startsWith("/assets/assets/background/")).toBe(true); + expect(path.endsWith(".png")).toBe(true); + + const stored = r2.objects.get(objectKeyFromPath(path)); + expect(stored).toBeTruthy(); + expect(stored?.httpMetadata?.contentType).toBe("image/png"); + expect(stored?.httpMetadata?.cacheControl).toContain("immutable"); + expect(Array.from(stored?.bytes ?? [])).toEqual(Array.from(PNG_BYTES)); + }); + + it("accepts every allowed image type with matching magic bytes", async () => { + const cases: Array<[string, Uint8Array, string]> = [ + ["image/jpeg", JPEG_BYTES, ".jpg"], + ["image/webp", WEBP_BYTES, ".webp"], + ["image/gif", GIF_BYTES, ".gif"], + ["image/x-icon", ICO_BYTES, ".ico"], + ["image/svg+xml", SVG_BYTES, ".svg"], + ]; + for (const [type, bytes, ext] of cases) { + const res = await upload(app, env, cookie, bytes, type, { + purpose: "icon", + }); + expect(res.status, `${type} should be accepted`).toBe(201); + const { path } = await readJson(res); + expect(path.endsWith(ext)).toBe(true); + expect(path.startsWith("/assets/assets/icon/")).toBe(true); + } + }); + + it("rejects a Content-Type/magic-byte mismatch", async () => { + const res = await upload(app, env, cookie, JPEG_BYTES, "image/png", { + purpose: "background", + }); + expect(res.status).toBe(400); + const { error } = await readJson(res); + expect(error).toContain("does not match"); + expect(error).toContain("image/jpeg"); + expect(r2.objects.size).toBe(0); + }); + + it("rejects a disallowed Content-Type", async () => { + const res = await upload(app, env, cookie, PNG_BYTES, "image/bmp", { + purpose: "background", + }); + expect(res.status).toBe(400); + const { error } = await readJson(res); + expect(error).toContain("unsupported Content-Type"); + expect(error).toContain("image/png"); + expect(r2.objects.size).toBe(0); + }); + + it("rejects an SVG Content-Type carrying HTML instead of SVG", async () => { + const html = new TextEncoder().encode( + "", + ); + const res = await upload(app, env, cookie, html, "image/svg+xml", { + purpose: "logo", + }); + expect(res.status).toBe(400); + expect((await readJson(res)).error).toContain("not an SVG document"); + expect(r2.objects.size).toBe(0); + }); + + it("accepts an SVG behind a BOM and leading whitespace", async () => { + const bytes = new TextEncoder().encode( + '\uFEFF\n ', + ); + const res = await upload(app, env, cookie, bytes, "image/svg+xml", { + purpose: "logo", + }); + expect(res.status).toBe(201); + expect((await readJson(res)).path.endsWith(".svg")).toBe(true); + }); + + it("rejects a missing or unknown purpose", async () => { + const missing = await upload(app, env, cookie, PNG_BYTES, "image/png"); + expect(missing.status).toBe(400); + expect((await readJson(missing)).error).toContain("purpose"); + + const unknown = await upload(app, env, cookie, PNG_BYTES, "image/png", { + purpose: "avatar", + }); + expect(unknown.status).toBe(400); + expect((await readJson(unknown)).error).toContain( + "background, logo or icon", + ); + expect(r2.objects.size).toBe(0); + }); + + it("rejects a missing file field", async () => { + const form = new FormData(); + form.set("purpose", "background"); + const res = await app.request( + "/api/admin/assets", + { method: "POST", body: form, headers: { cookie } }, + env, + ); + expect(res.status).toBe(400); + expect((await readJson(res)).error).toContain("file is required"); + }); + + it("enforces 1MB for logo/icon and 5MB for background", async () => { + const oneMb = 1024 * 1024; + const fiveMb = 5 * 1024 * 1024; + + const logoTooBig = await upload( + app, + env, + cookie, + pngOfSize(oneMb + 1), + "image/png", + { purpose: "logo" }, + ); + expect(logoTooBig.status).toBe(413); + const logoError = (await readJson(logoTooBig)).error; + expect(logoError).toContain("logo image is too large"); + expect(logoError).toContain("1MB"); + expect(logoError).toContain(String(oneMb)); + + const iconOk = await upload( + app, + env, + cookie, + pngOfSize(oneMb), + "image/png", + { purpose: "icon" }, + ); + expect(iconOk.status).toBe(201); + + // 1.5MB is fine for a background but not for a logo. + const bgOk = await upload( + app, + env, + cookie, + pngOfSize(oneMb + 512 * 1024), + "image/png", + { purpose: "background" }, + ); + expect(bgOk.status).toBe(201); + + const bgTooBig = await upload( + app, + env, + cookie, + pngOfSize(fiveMb + 1), + "image/png", + { purpose: "background" }, + ); + expect(bgTooBig.status).toBe(413); + const bgError = (await readJson(bgTooBig)).error; + expect(bgError).toContain("background image is too large"); + expect(bgError).toContain("5MB"); + expect(bgError).toContain(String(fiveMb)); + }); + + it("returns 503 (not a crash) when the R2 binding is missing", async () => { + const noR2 = makeEnv(); + await runMigrations(noR2); + const noR2App = makeApp(); + const noR2Cookie = await signIn(noR2App, noR2); + + const res = await upload( + noR2App, + noR2, + noR2Cookie, + PNG_BYTES, + "image/png", + { purpose: "background" }, + ); + expect(res.status).toBe(503); + expect((await readJson(res)).error).toContain("R2 binding"); + }); +}); + +describe("GET /assets/*", () => { + let env: Env; + let r2: MemoryR2; + let app: Hono; + let cookie: string; + + beforeEach(async () => { + r2 = new MemoryR2(); + env = makeEnv({ R2: r2 as unknown as R2Bucket }); + app = makeApp(); + await runMigrations(env); + cookie = await signIn(app, env); + }); + + it("serves an uploaded PNG with immutable caching and nosniff", async () => { + const { path } = await readJson( + await upload(app, env, cookie, PNG_BYTES, "image/png", { + purpose: "background", + }), + ); + + const res = await app.request(path, {}, env); + expect(res.status).toBe(200); + expect(res.headers.get("content-type")).toBe("image/png"); + expect(res.headers.get("cache-control")).toBe( + "public, max-age=31536000, immutable", + ); + expect(res.headers.get("x-content-type-options")).toBe("nosniff"); + expect(new Uint8Array(await res.arrayBuffer())).toEqual(PNG_BYTES); + }); + + it("serves SVG as image/svg+xml with nosniff (never HTML)", async () => { + const { path } = await readJson( + await upload(app, env, cookie, SVG_BYTES, "image/svg+xml", { + purpose: "logo", + }), + ); + const res = await app.request(path, {}, env); + expect(res.status).toBe(200); + expect(res.headers.get("content-type")).toBe("image/svg+xml"); + expect(res.headers.get("x-content-type-options")).toBe("nosniff"); + expect(await res.text()).toContain(" { + const res = await app.request( + "/assets/assets/background/00000000-0000-0000-0000-000000000000.png", + {}, + env, + ); + expect(res.status).toBe(404); + }); + + it("404s (no 500) when the R2 binding is missing", async () => { + const noR2 = makeEnv(); + const res = await makeApp().request("/assets/assets/logo/x.svg", {}, noR2); + expect(res.status).toBe(404); + }); +}); + +describe("DELETE /api/admin/assets", () => { + let env: Env; + let r2: MemoryR2; + let app: Hono; + let cookie: string; + + beforeEach(async () => { + r2 = new MemoryR2(); + env = makeEnv({ R2: r2 as unknown as R2Bucket }); + app = makeApp(); + await runMigrations(env); + cookie = await signIn(app, env); + }); + + it("deletes the object by key", async () => { + const { path } = await readJson( + await upload(app, env, cookie, PNG_BYTES, "image/png", { + purpose: "logo", + }), + ); + const key = objectKeyFromPath(path); + expect(r2.objects.has(key)).toBe(true); + + const res = await app.request( + "/api/admin/assets", + { + method: "DELETE", + body: JSON.stringify({ key }), + headers: { "content-type": "application/json", cookie }, + }, + env, + ); + expect(res.status).toBe(200); + expect(await readJson(res)).toEqual({ success: true }); + expect(r2.objects.has(key)).toBe(false); + + const read = await app.request(path, {}, env); + expect(read.status).toBe(404); + }); + + it("rejects a missing key", async () => { + const res = await app.request( + "/api/admin/assets", + { + method: "DELETE", + body: JSON.stringify({}), + headers: { "content-type": "application/json", cookie }, + }, + env, + ); + expect(res.status).toBe(400); + expect((await readJson(res)).error).toContain("key is required"); + }); + + it("returns 503 when the R2 binding is missing", async () => { + const noR2 = makeEnv(); + await runMigrations(noR2); + const noR2App = makeApp(); + const noR2Cookie = await signIn(noR2App, noR2); + const res = await noR2App.request( + "/api/admin/assets", + { + method: "DELETE", + body: JSON.stringify({ key: "assets/logo/x.png" }), + headers: { "content-type": "application/json", cookie: noR2Cookie }, + }, + noR2, + ); + expect(res.status).toBe(503); + }); +}); + +describe("settings.logoUrl + replaced-upload cleanup", () => { + let env: Env; + let r2: MemoryR2; + let app: Hono; + let cookie: string; + + beforeEach(async () => { + r2 = new MemoryR2(); + env = makeEnv({ R2: r2 as unknown as R2Bucket }); + app = makeApp(); + await runMigrations(env); + cookie = await signIn(app, env); + }); + + it("exposes logoUrl in the settings DTO (default empty string)", async () => { + const res = await app.request( + "/api/admin/settings", + { headers: { cookie } }, + env, + ); + const body = await readJson(res); + expect(body.logoUrl).toBe(""); + expect( + ( + await readJson( + await app.request( + "/api/admin/settings/keys", + { headers: { cookie } }, + env, + ), + ) + ).keys, + ).toContain("logo_url"); + }); + + it("stores logoUrl through PUT /api/admin/settings", async () => { + const res = await putSettings(app, env, cookie, { + logoUrl: "/assets/assets/logo/abc.svg", + }); + expect(res.status).toBe(200); + expect((await readJson(res)).logoUrl).toBe("/assets/assets/logo/abc.svg"); + + const again = await readJson( + await app.request("/api/admin/settings", { headers: { cookie } }, env), + ); + expect(again.logoUrl).toBe("/assets/assets/logo/abc.svg"); + }); + + it("deletes the old R2 object when a local background is replaced by an URL", async () => { + const { path } = await readJson( + await upload(app, env, cookie, PNG_BYTES, "image/png", { + purpose: "background", + }), + ); + const key = objectKeyFromPath(path); + + await putSettings(app, env, cookie, { backgroundUrl: path }); + expect(r2.deleted).toEqual([]); + + await putSettings(app, env, cookie, { + backgroundUrl: "https://cdn.example.com/bg.jpg", + }); + expect(r2.deleted).toEqual([key]); + expect(r2.objects.has(key)).toBe(false); + }); + + it("deletes the old logo when it is replaced by a new upload path", async () => { + const first = await readJson( + await upload(app, env, cookie, SVG_BYTES, "image/svg+xml", { + purpose: "logo", + }), + ); + const second = await readJson( + await upload(app, env, cookie, SVG_BYTES, "image/svg+xml", { + purpose: "logo", + }), + ); + const oldKey = objectKeyFromPath(first.path); + const newKey = objectKeyFromPath(second.path); + + await putSettings(app, env, cookie, { logoUrl: first.path }); + await putSettings(app, env, cookie, { logoUrl: second.path }); + + expect(r2.deleted).toEqual([oldKey]); + expect(r2.objects.has(oldKey)).toBe(false); + expect(r2.objects.has(newKey)).toBe(true); + }); + + it("never deletes external URLs and keeps unchanged values", async () => { + await putSettings(app, env, cookie, { + backgroundUrl: "https://cdn.example.com/bg.jpg", + logoUrl: "https://cdn.example.com/logo.svg", + }); + await putSettings(app, env, cookie, { + backgroundUrl: "https://cdn.example.com/other.jpg", + }); + // Same value written again is not a replacement. + await putSettings(app, env, cookie, { + backgroundUrl: "https://cdn.example.com/other.jpg", + }); + expect(r2.deleted).toEqual([]); + }); + + it("keeps the settings write working when the R2 binding is missing", async () => { + const noR2 = makeEnv(); + await runMigrations(noR2); + const noR2App = makeApp(); + const noR2Cookie = await signIn(noR2App, noR2); + + const res = await putSettings(noR2App, noR2, noR2Cookie, { + backgroundUrl: "https://cdn.example.com/bg.jpg", + logoUrl: "https://cdn.example.com/logo.svg", + }); + expect(res.status).toBe(200); + expect((await readJson(res)).backgroundUrl).toBe( + "https://cdn.example.com/bg.jpg", + ); + }); +}); diff --git a/worker/test/helpers.ts b/worker/test/helpers.ts index d16f153..951adc3 100644 --- a/worker/test/helpers.ts +++ b/worker/test/helpers.ts @@ -54,10 +54,69 @@ export function makeEnv(overrides: Partial = {}): Env { ASSETS: { fetch: async () => new Response("not found", { status: 404 }), } as unknown as Fetcher, + // No R2 binding by default: that mirrors local/preview environments, and + // asset tests opt in with `{ R2: new MemoryR2() }`. + R2: undefined as unknown as R2Bucket, ...overrides, }; } +/** + * In-memory `R2Bucket` stand-in for unit tests (same spirit as the ASSETS stub + * above). Only the surface the Worker uses is implemented: put / get / delete + * plus stored `httpMetadata`, with a `deleted` log for assertions. + */ +export class MemoryR2 { + readonly objects = new Map< + string, + { bytes: Uint8Array; httpMetadata?: Record } + >(); + readonly deleted: string[] = []; + + async put( + key: string, + value: Uint8Array | ArrayBuffer | ArrayBufferView | string, + options?: { httpMetadata?: Record }, + ): Promise { + const bytes = + typeof value === "string" + ? new TextEncoder().encode(value) + : value instanceof Uint8Array + ? value + : value instanceof ArrayBuffer + ? new Uint8Array(value) + : new Uint8Array(value.buffer, value.byteOffset, value.byteLength); + // Copy so later mutation of the source buffer cannot affect the stored body. + this.objects.set(key, { + bytes: new Uint8Array(bytes), + httpMetadata: options?.httpMetadata, + }); + return { key }; + } + + async get(key: string): Promise { + const object = this.objects.get(key); + if (!object) return null; + return { + key, + size: object.bytes.byteLength, + httpMetadata: object.httpMetadata, + body: object.bytes, + }; + } + + async delete(key: string): Promise { + this.deleted.push(key); + this.objects.delete(key); + } + + async head(key: string): Promise { + const object = this.objects.get(key); + if (!object) return null; + return { key, size: object.bytes.byteLength }; + } +} + export function setTablePrefix(env: Env, prefix: string): Env { return { ...env, TABLE_PREFIX: prefix }; } diff --git a/worker/test/setup.test.ts b/worker/test/setup.test.ts index 2272d56..eadbff1 100644 --- a/worker/test/setup.test.ts +++ b/worker/test/setup.test.ts @@ -410,6 +410,7 @@ describe("admin system endpoints", () => { expect(Object.keys(publicBody.settings).sort()).toEqual([ "backgroundUrl", "columns", + "logoUrl", "siteTitle", "theme", ]); diff --git a/worker/wrangler.toml b/worker/wrangler.toml index 64a9eca..446c3b6 100644 --- a/worker/wrangler.toml +++ b/worker/wrangler.toml @@ -19,6 +19,13 @@ binding = "DB" database_name = "D1_DATABASE_NAME_PLACEHOLDER" database_id = "D1_DATABASE_ID_PLACEHOLDER" +# Uploaded images (ONE-444). Binding name is R2 — ASSETS is already taken by +# Workers Static Assets above. Bucket name is not a secret; it is created by +# the account owner, never by this Worker. +[[r2_buckets]] +binding = "R2" +bucket_name = "nav-assets" + # 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