From 4a83476955dbef5193fb954c2837ac417af71821 Mon Sep 17 00:00:00 2001 From: mapxn <16299874+mapxn@users.noreply.github.com> Date: Wed, 18 Nov 2026 09:36:44 +0800 Subject: [PATCH] fix(worker): add cors handling and unify response envelopes - implement cors middleware with safe domain validation and preflight 204 - converge admin settings and users endpoints to calineSuccess envelope - unwrap response envelopes in web client request helper - add cors and envelope unwrapping test suites Checkpoint: -GO3I0Sjk21Ojo63wIFPA --- web/src/lib/api.test.ts | 77 +++++++++ web/src/lib/api.ts | 46 ++++- worker/src/index.ts | 4 + worker/src/middleware/cors.ts | 75 ++++++++ worker/src/routes/admin.ts | 32 ++-- worker/test/admin-comments-management.test.ts | 26 +-- worker/test/admin-user-actions.test.ts | 22 +-- worker/test/admin-users.test.ts | 76 +++++---- worker/test/auth-register.test.ts | 16 +- worker/test/cors.test.ts | 161 ++++++++++++++++++ worker/test/email-guard.test.ts | 12 +- worker/test/email-provider.test.ts | 12 +- worker/test/me-lock.test.ts | 22 ++- worker/test/single-mode.test.ts | 10 +- 14 files changed, 498 insertions(+), 93 deletions(-) create mode 100644 worker/src/middleware/cors.ts create mode 100644 worker/test/cors.test.ts diff --git a/web/src/lib/api.test.ts b/web/src/lib/api.test.ts index 87182b5..2cf0467 100644 --- a/web/src/lib/api.test.ts +++ b/web/src/lib/api.test.ts @@ -109,3 +109,80 @@ describe("用户管理操作列端点", () => { ]) }) }) + +describe("响应信封统一解包与错误契约(QA #7 缺陷②)", () => { + it("成功响应自动解包 { data: T } 信封", async () => { + stubFetch(200, { + data: { + items: [{ id: 1, contentRaw: "hello" }], + total: 1, + page: 1, + pageSize: 10, + totalPages: 1 + } + }) + + const result = await adminApi.comments() + // 必须直接拿到解包后的 items 与 total,而不是 undefined + expect(result.items).toHaveLength(1) + expect(result.items[0].id).toBe(1) + expect(result.total).toBe(1) + }) + + it("导出数据 exportData 正确剥开信封,避免备份多包一层 data", async () => { + const rawDump = { + version: "1.0.0", + exportedAt: "2026-11-18T00:00:00.000Z", + comments: [], + counters: [], + users: [] + } + stubFetch(200, { data: rawDump }) + + const dump = await adminApi.exportData() + expect(dump).toEqual(rawDump) + expect(dump).not.toHaveProperty("data") + }) + + it("解析统一错误信封 { error: { code, message, retryAfter, details } }", async () => { + stubFetch(429, { + error: { + code: "RATE_LIMITED", + message: "Too many requests", + retryAfter: 45 + } + }) + + let caught: ApiError | null = null + try { + await meApi.get() + } catch (err) { + if (err instanceof ApiError) caught = err + } + + expect(caught).not.toBeNull() + expect(caught?.status).toBe(429) + expect(caught?.code).toBe("RATE_LIMITED") + expect(caught?.message).toBe("Too many requests") + expect(caught?.retryAfter).toBe(45) + }) + + it("兼容旧错误格式 { error: string, code: string }", async () => { + stubFetch(400, { + error: "Bad request message", + code: "INVALID_PARAM" + }) + + let caught: ApiError | null = null + try { + await meApi.get() + } catch (err) { + if (err instanceof ApiError) caught = err + } + + expect(caught).not.toBeNull() + expect(caught?.status).toBe(400) + expect(caught?.code).toBe("INVALID_PARAM") + expect(caught?.message).toBe("Bad request message") + }) +}) diff --git a/web/src/lib/api.ts b/web/src/lib/api.ts index e948500..a311e8a 100644 --- a/web/src/lib/api.ts +++ b/web/src/lib/api.ts @@ -66,7 +66,14 @@ export class ApiError extends Error { } interface ErrorEnvelope { - error?: string + error?: + | string + | { + code?: string + message?: string + retryAfter?: number + details?: unknown + } code?: string retryAfter?: number detail?: string @@ -102,6 +109,29 @@ async function request( if (!response.ok) { const envelope = (await response.json().catch(() => ({}))) as ErrorEnvelope + let code: string | undefined + let message: string | undefined + let retryAfter: number | undefined + let detail: string | undefined + + if (envelope.error && typeof envelope.error === "object") { + const errObj = envelope.error as { + code?: string + message?: string + retryAfter?: number + details?: unknown + } + code = errObj.code + message = errObj.message + retryAfter = errObj.retryAfter + detail = typeof errObj.details === "string" ? errObj.details : undefined + } else { + code = envelope.code + message = typeof envelope.error === "string" ? envelope.error : undefined + retryAfter = envelope.retryAfter + detail = envelope.detail + } + // 会话中途失效:清掉本地用户态,RequireAuth 会把人送回登录页。 // 登录/找回等公开鉴权端点的 401 是业务结果,不动全局状态。 if (response.status === 401 && !path.startsWith("/auth/")) { @@ -111,17 +141,21 @@ async function request( } throw new ApiError({ status: response.status, - message: envelope.error ?? response.statusText, - code: envelope.code, - retryAfter: envelope.retryAfter, - detail: envelope.detail + message: message ?? response.statusText, + code, + retryAfter, + detail }) } if (response.status === 204) return undefined as T const text = await response.text() if (!text) return undefined as T - return JSON.parse(text) as T + const json = JSON.parse(text) + if (json && typeof json === "object" && "data" in json) { + return json.data as T + } + return json as T } /* 公开数据 */ diff --git a/worker/src/index.ts b/worker/src/index.ts index a880ccb..fbef37a 100644 --- a/worker/src/index.ts +++ b/worker/src/index.ts @@ -9,6 +9,7 @@ import { Hono } from "hono" import { wakerGateState } from "./core/waker-gate" import { buildWebAppManifest } from "./lib/manifest" import { getTablePrefix, isValidTablePrefix } from "./lib/table-prefix" +import { corsMiddleware } from "./middleware/cors" import { authMiddleware } from "./middleware/auth" import { adminRoutes } from "./routes/admin" import { authRoutes } from "./routes/auth" @@ -37,6 +38,9 @@ app.use("*", async (c, next) => { await next() }) +// CORS 跨域治理(规格 §5):OPTIONS 预检 204;业务响应按 safeDomains 注入 Access-Control-* 头。 +app.use("/api/*", corsMiddleware) + // 未登录/敏感响应一律 no-store;路由自己设了缓存头的保留它自己的(/api/public)。 app.use("/api/*", async (c, next) => { await next() diff --git a/worker/src/middleware/cors.ts b/worker/src/middleware/cors.ts new file mode 100644 index 0000000..4eb02f2 --- /dev/null +++ b/worker/src/middleware/cors.ts @@ -0,0 +1,75 @@ +/** + * CORS 中间件(规格 §5 安全域名)。 + * + * 1. OPTIONS 预检请求: + * - 匹配 safeDomains(若未配置 safeDomains,则默认放行所有 Origin); + * - 允许时直接回 204 No Content,并返回 Access-Control-* 头,不再穿透到下游守卫; + * - 拒绝时回 403 Forbidden,不返回 Access-Control-Allow-Origin。 + * 2. 实际业务请求(带 Origin 头): + * - 允许时下游执行后注入 Access-Control-Allow-Origin / Credentials / Vary; + * - 拒绝时不注入 CORS 头,由浏览器同源策略拦截。 + * 3. 同源/无 Origin 头请求:原样通行。 + */ +import type { MiddlewareHandler } from "hono" +import { isDomainAllowed } from "../core/pipeline" +import { readCalineSettings } from "../lib/settings" +import type { HonoEnv } from "../types" + +export const corsMiddleware: MiddlewareHandler = async (c, next) => { + const origin = c.req.header("origin") + + // 非跨域请求(无 Origin 请求头) + if (!origin) { + if (c.req.method === "OPTIONS") { + return c.body(null, 204) + } + return next() + } + + // 跨域请求:按安全域名校验 + let safeDomains: string[] = [] + try { + const settings = await readCalineSettings(c.env) + safeDomains = settings.safeDomains + } catch { + // 数据库未就绪等异常降级为默认空列表(默认全放行) + safeDomains = [] + } + + const allowed = isDomainAllowed(origin, safeDomains) + + if (!allowed) { + if (c.req.method === "OPTIONS") { + return c.json({ error: "Origin not allowed" }, 403) + } + // 业务请求未在安全域名内,不注入 CORS 响应头 + return next() + } + + // 域名允许时:处理 OPTIONS 预检请求 + if (c.req.method === "OPTIONS") { + const reqHeaders = c.req.header("access-control-request-headers") + return new Response(null, { + status: 204, + headers: { + "Access-Control-Allow-Origin": origin, + "Access-Control-Allow-Credentials": "true", + "Access-Control-Allow-Methods": + "GET, POST, PUT, PATCH, DELETE, OPTIONS", + "Access-Control-Allow-Headers": + reqHeaders || "Content-Type, Authorization, X-Setup-Secret, Accept", + "Access-Control-Max-Age": "86400", + Vary: "Origin" + } + }) + } + + // 业务请求:继续下游路由并注入 CORS 头 + try { + await next() + } finally { + c.header("Access-Control-Allow-Origin", origin) + c.header("Access-Control-Allow-Credentials", "true") + c.header("Vary", "Origin") + } +} diff --git a/worker/src/routes/admin.ts b/worker/src/routes/admin.ts index 7295bbb..e3e8ad3 100644 --- a/worker/src/routes/admin.ts +++ b/worker/src/routes/admin.ts @@ -97,7 +97,7 @@ adminRoutes.post("/setup", async (c) => { adminRoutes.get("/settings", async (c) => { const base = await buildAdminSettings(c.env) const site = await readCalineSettings(c.env) - return c.json({ ...base, site }) + return calineSuccess(c, { ...base, site }) }) adminRoutes.put("/settings", async (c) => { @@ -178,7 +178,7 @@ adminRoutes.put("/settings", async (c) => { const base = await buildAdminSettings(c.env) const site = await readCalineSettings(c.env) - return c.json({ ...base, site }) + return calineSuccess(c, { ...base, site }) }) adminRoutes.post("/settings/test-email", async (c) => { @@ -216,7 +216,7 @@ adminRoutes.post("/settings/test-email", async (c) => { detail: result.error ?? "unknown error" }) } - return c.json({ success: true }) + return calineSuccess(c, { success: true }) }) adminRoutes.get("/users", async (c) => { @@ -231,7 +231,7 @@ adminRoutes.get("/users", async (c) => { } const prefix = getTablePrefix(c.env) const items = await listUsers(c.env.DB, prefix, status) - return c.json({ items, data: { items } }) + return calineSuccess(c, { items }) }) adminRoutes.post("/users/:id/approve", async (c) => { @@ -246,7 +246,7 @@ adminRoutes.post("/users/:id/approve", async (c) => { if (!user) return apiError(c, 404, "USER_NOT_FOUND", "User not found") return apiError(c, 409, "USER_NOT_PENDING", "User is not pending approval") } - return c.json({ success: true }) + return calineSuccess(c, { success: true }) }) adminRoutes.post("/users/:id/reject", async (c) => { @@ -261,7 +261,7 @@ adminRoutes.post("/users/:id/reject", async (c) => { if (!user) return apiError(c, 404, "USER_NOT_FOUND", "User not found") return apiError(c, 409, "USER_NOT_PENDING", "User is not pending approval") } - return c.json({ success: true }) + return calineSuccess(c, { success: true }) }) adminRoutes.post("/users", async (c) => { @@ -336,7 +336,7 @@ adminRoutes.post("/users", async (c) => { throw err } - return c.json({ + return calineSuccess(c, { id: user.id, email: user.email, role: user.role, @@ -364,7 +364,7 @@ adminRoutes.post("/users/:id/reset-password", async (c) => { must_change_password: 1 }) await revokeAllSessions(c.env.DB, prefix, id) - return c.json({ + return calineSuccess(c, { id: user.id, email: user.email, temporaryPassword @@ -390,7 +390,7 @@ adminRoutes.post("/users/:id/disable", async (c) => { if (!user) return apiError(c, 404, "USER_NOT_FOUND", "User not found") // 重复停用:幂等 200。 - if (user.status === "disabled") return c.json({ success: true }) + if (user.status === "disabled") return calineSuccess(c, { success: true }) // 停用一个「能登录的管理员」时,若他是最后一个,拒绝。 if (user.role === "admin" && user.status === "active") { @@ -401,7 +401,7 @@ adminRoutes.post("/users/:id/disable", async (c) => { await updateUserFields(c.env.DB, prefix, id, { status: "disabled" }) await revokeAllSessions(c.env.DB, prefix, id) - return c.json({ success: true }) + return calineSuccess(c, { success: true }) }) adminRoutes.post("/users/:id/enable", async (c) => { @@ -414,10 +414,10 @@ adminRoutes.post("/users/:id/enable", async (c) => { if (!user) return apiError(c, 404, "USER_NOT_FOUND", "User not found") // 重复启用:幂等 200。 - if (user.status === "active") return c.json({ success: true }) + if (user.status === "active") return calineSuccess(c, { success: true }) await updateUserFields(c.env.DB, prefix, id, { status: "active" }) - return c.json({ success: true }) + return calineSuccess(c, { success: true }) }) adminRoutes.post("/users/:id/role", async (c) => { @@ -437,7 +437,7 @@ adminRoutes.post("/users/:id/role", async (c) => { if (!user) return apiError(c, 404, "USER_NOT_FOUND", "User not found") // 角色未变化:幂等 200。 - if (user.role === role) return c.json({ success: true }) + if (user.role === role) return calineSuccess(c, { success: true }) // 降级护栏:把「能登录的管理员」降成普通用户时,若他是最后一个,拒绝。 if (user.role === "admin" && role === "user" && user.status === "active") { @@ -447,7 +447,7 @@ adminRoutes.post("/users/:id/role", async (c) => { } await updateUserFields(c.env.DB, prefix, id, { role }) - return c.json({ success: true }) + return calineSuccess(c, { success: true }) }) adminRoutes.post("/users/:id/delete", async (c) => { @@ -476,7 +476,7 @@ adminRoutes.post("/users/:id/delete", async (c) => { } await deleteUser(c.env.DB, prefix, id) - return c.json({ success: true }) + return calineSuccess(c, { success: true }) }) adminRoutes.delete("/users/:id", async (c) => { @@ -503,7 +503,7 @@ adminRoutes.delete("/users/:id", async (c) => { } await deleteUser(c.env.DB, prefix, id) - return c.json({ success: true }) + return calineSuccess(c, { success: true }) }) adminRoutes.patch("/users/:id", async (c) => { diff --git a/worker/test/admin-comments-management.test.ts b/worker/test/admin-comments-management.test.ts index 2a0a069..bb286d7 100644 --- a/worker/test/admin-comments-management.test.ts +++ b/worker/test/admin-comments-management.test.ts @@ -305,9 +305,11 @@ describe("Admin Comments and System Management", () => { headers: { Cookie: adminSession.cookie } }) const listBody = (await listRes.json()) as { - items: Array<{ id: number; label?: string; role: string }> + data: { items: Array<{ id: number; label?: string; role: string }> } } - const target = listBody.items.find((u) => u.id === targetSession.userId) + const target = listBody.data.items.find( + (u) => u.id === targetSession.userId + ) expect(target?.label).toBe("协管员") expect(target?.role).toBe("admin") @@ -358,9 +360,11 @@ describe("Admin Comments and System Management", () => { headers: { Cookie: adminSession.cookie } }) expect(getRes.status).toBe(200) - const getBody = (await getRes.json()) as { site: CalineSiteSettings } - expect(getBody.site.auditSwitch).toBe(false) - expect(getBody.site.guestMode).toBe("open") + const getBody = (await getRes.json()) as { + data: { site: CalineSiteSettings } + } + expect(getBody.data.site.auditSwitch).toBe(false) + expect(getBody.data.site.guestMode).toBe("open") // Update settings const putRes = await request(env, "/api/admin/settings", { @@ -380,11 +384,13 @@ describe("Admin Comments and System Management", () => { }) }) expect(putRes.status).toBe(200) - const putBody = (await putRes.json()) as { site: CalineSiteSettings } - expect(putBody.site.auditSwitch).toBe(true) - expect(putBody.site.guestMode).toBe("login_only") - expect(putBody.site.reservedNicks).toContain("Root") - expect(putBody.site.maxContentLength).toBe(500) + const putBody = (await putRes.json()) as { + data: { site: CalineSiteSettings } + } + expect(putBody.data.site.auditSwitch).toBe(true) + expect(putBody.data.site.guestMode).toBe("login_only") + expect(putBody.data.site.reservedNicks).toContain("Root") + expect(putBody.data.site.maxContentLength).toBe(500) }) it("handles export and import with overwrite confirmation guard", async () => { diff --git a/worker/test/admin-user-actions.test.ts b/worker/test/admin-user-actions.test.ts index 53d576c..023da08 100644 --- a/worker/test/admin-user-actions.test.ts +++ b/worker/test/admin-user-actions.test.ts @@ -105,15 +105,17 @@ describe("用户管理操作列:重置密码", () => { ) expect(res.status).toBe(200) const body = (await res.json()) as { - id: number - email: string - temporaryPassword: string + data: { + id: number + email: string + temporaryPassword: string + } } - expect(body).toMatchObject({ + expect(body.data).toMatchObject({ id: target.userId, email: "victim@example.test" }) - expect(body.temporaryPassword.length).toBeGreaterThanOrEqual(8) + expect(body.data.temporaryPassword.length).toBeGreaterThanOrEqual(8) // 库里只存哈希、置首登强制改密。 const row = db.db @@ -125,7 +127,7 @@ describe("用户管理操作列:重置密码", () => { password_hash: string must_change_password: number } - expect(row.password_hash).not.toContain(body.temporaryPassword) + expect(row.password_hash).not.toContain(body.data.temporaryPassword) expect(row.must_change_password).toBe(1) // 目标会话全部失效。 @@ -137,7 +139,7 @@ describe("用户管理操作列:重置密码", () => { // 一次性密码可登录(重置后新密码即为该临时密码)。 const login = await postJson(env, "/api/auth/login", { email: "victim@example.test", - password: body.temporaryPassword + password: body.data.temporaryPassword }) expect(login.status).toBe(200) }) @@ -161,7 +163,7 @@ describe("用户管理操作列:停用 / 启用", () => { { cookie: admin.cookie } ) expect(disable.status).toBe(200) - expect(await disable.json()).toEqual({ success: true }) + expect(await disable.json()).toEqual({ data: { success: true } }) const disabled = db.db .prepare(`SELECT status FROM ${usersTable(prefix)} WHERE id = ?`) @@ -299,7 +301,7 @@ describe("用户管理操作列:删除用户", () => { { cookie: admin.cookie } ) expect(res.status).toBe(200) - expect(await res.json()).toEqual({ success: true }) + expect(await res.json()).toEqual({ data: { success: true } }) const usersLeft = db.db .prepare(`SELECT COUNT(*) AS n FROM ${usersTable(prefix)} WHERE id = ?`) @@ -394,6 +396,6 @@ describe("用户管理操作列:护栏", () => { { cookie: admin.cookie } ) expect(res.status).toBe(200) - expect(await res.json()).toEqual({ success: true }) + expect(await res.json()).toEqual({ data: { success: true } }) }) }) diff --git a/worker/test/admin-users.test.ts b/worker/test/admin-users.test.ts index 2e3f016..4faff41 100644 --- a/worker/test/admin-users.test.ts +++ b/worker/test/admin-users.test.ts @@ -60,20 +60,22 @@ describe("系统管理面", () => { }) expect(res.status).toBe(200) const raw = await res.text() - const body = JSON.parse(raw) as { - appMode: string - tablePrefix: string - registration: { - enabled: boolean - approvalRequired: boolean - emailVerificationRequired: boolean - } - setup: { pageEnabled: boolean } - email: { - provider: string - configured: boolean - smtp: { passwordSet: boolean } - resend: { apiKeySet: boolean } + const { data: body } = JSON.parse(raw) as { + data: { + appMode: string + tablePrefix: string + registration: { + enabled: boolean + approvalRequired: boolean + emailVerificationRequired: boolean + } + setup: { pageEnabled: boolean } + email: { + provider: string + configured: boolean + smtp: { passwordSet: boolean } + resend: { apiKeySet: boolean } + } } } expect(body.appMode).toBe("multi") @@ -203,9 +205,13 @@ describe("全量用户列表", () => { headers: { cookie: admin } }) expect(res.status).toBe(200) - const body = (await res.json()) as { - items: Array> - } + const body = ( + (await res.json()) as { + data: { + items: Array> + } + } + ).data expect(body.items.map((item) => item.email)).toEqual([ "owner@example.test", @@ -248,9 +254,13 @@ describe("全量用户列表", () => { headers: { cookie: admin } }) expect(pending.status).toBe(200) - const pendingBody = (await pending.json()) as { - items: Array<{ email: string }> - } + const pendingBody = ( + (await pending.json()) as { + data: { + items: Array<{ email: string }> + } + } + ).data expect(pendingBody.items.map((item) => item.email)).toEqual([ "pending@example.test" ]) @@ -277,13 +287,17 @@ describe("管理员手动建号", () => { { cookie: admin } ) expect(res.status).toBe(200) - const created = (await res.json()) as { - id: number - email: string - role: string - status: string - temporaryPassword: string - } + const created = ( + (await res.json()) as { + data: { + id: number + email: string + role: string + status: string + temporaryPassword: string + } + } + ).data expect(created).toMatchObject({ email: "newbie@example.test", role: "user", @@ -391,7 +405,9 @@ describe("管理员手动建号", () => { { cookie: admin } ) expect(res.status).toBe(200) - expect(await res.json()).toMatchObject({ + expect( + ((await res.json()) as { data: Record }).data + ).toMatchObject({ email: "boss@example.test", role: "admin", status: "active" @@ -435,7 +451,9 @@ describe("管理员手动建号", () => { { cookie: admin } ) expect(ignored.status).toBe(200) - expect(await ignored.json()).toMatchObject({ + expect( + ((await ignored.json()) as { data: Record }).data + ).toMatchObject({ email: "u1@example.test", status: "active" }) diff --git a/worker/test/auth-register.test.ts b/worker/test/auth-register.test.ts index 827c22c..9878c8b 100644 --- a/worker/test/auth-register.test.ts +++ b/worker/test/auth-register.test.ts @@ -83,9 +83,11 @@ describe("注册:首个用户与审核", () => { const pending = await request(env, "/api/admin/users?status=pending", { headers: { cookie: admin } }) - const pendingBody = (await pending.json()) as { - items: Array<{ id: number; email: string }> - } + const pendingBody = ( + (await pending.json()) as { + data: { items: Array<{ id: number; email: string }> } + } + ).data expect(pendingBody.items).toHaveLength(1) const memberId = pendingBody.items[0].id @@ -132,9 +134,11 @@ describe("注册:首个用户与审核", () => { const admin = await adminCookie(env) await registerUser(env, { email: "spam@example.test" }) - const list = (await ( - await request(env, "/api/admin/users", { headers: { cookie: admin } }) - ).json()) as { items: Array<{ id: number; email: string }> } + const list = ( + (await ( + await request(env, "/api/admin/users", { headers: { cookie: admin } }) + ).json()) as { data: { items: Array<{ id: number; email: string }> } } + ).data const spam = list.items.find((item) => item.email === "spam@example.test") if (!spam) throw new Error("spam user missing from admin list") const id = spam.id diff --git a/worker/test/cors.test.ts b/worker/test/cors.test.ts new file mode 100644 index 0000000..1ab0fd3 --- /dev/null +++ b/worker/test/cors.test.ts @@ -0,0 +1,161 @@ +/** + * CORS 跨域治理与安全域名测试(QA #7 缺陷①、规格 §5)。 + * + * 覆盖: + * 1. OPTIONS 预检 204(无论公开还是私有路由,不被 401 拦截,不落入 404)。 + * 2. 预检与业务请求正确附带 Access-Control-Allow-Origin / Credentials / Methods / Headers / Vary。 + * 3. safeDomains 白名单生效:非法源预检 403、合法源放行、合法子域名放行。 + * 4. 业务错误响应(401 / 404)在合法源下依然携带 CORS 头,避免浏览器拦截遮蔽真实业务错误。 + * 5. 无 Origin 请求(同源)正常响应,不注入多余 CORS 头。 + */ +import { describe, expect, it } from "vitest" +import { initializedContext, request } from "./support/app" +import { writeCalineSettings } from "../src/lib/settings" + +describe("CORS 跨域与预检处理", () => { + it("默认无 safeDomains 配置时:OPTIONS 预检对公开与受保护接口均返回 204", async () => { + const { env } = await initializedContext() + + // 公开端点预检 + const publicOpt = await request(env, "/api/comments", { + method: "OPTIONS", + headers: { + Origin: "https://myblog.com", + "Access-Control-Request-Method": "POST", + "Access-Control-Request-Headers": "Content-Type, Authorization" + } + }) + expect(publicOpt.status).toBe(204) + expect(publicOpt.headers.get("access-control-allow-origin")).toBe( + "https://myblog.com" + ) + expect(publicOpt.headers.get("access-control-allow-credentials")).toBe( + "true" + ) + expect(publicOpt.headers.get("access-control-allow-methods")).toContain( + "POST" + ) + expect(publicOpt.headers.get("access-control-allow-headers")).toContain( + "Content-Type" + ) + expect(publicOpt.headers.get("vary")).toBe("Origin") + + // 受保护端点预检(不能被 401 拦截,也不能回 404) + const protectedOpt = await request(env, "/api/me", { + method: "OPTIONS", + headers: { + Origin: "https://myblog.com", + "Access-Control-Request-Method": "GET" + } + }) + expect(protectedOpt.status).toBe(204) + expect(protectedOpt.headers.get("access-control-allow-origin")).toBe( + "https://myblog.com" + ) + expect(protectedOpt.headers.get("access-control-allow-credentials")).toBe( + "true" + ) + }) + + it("跨域业务请求携带 Access-Control-* 与 Vary 头", async () => { + const { env } = await initializedContext() + + const res = await request(env, "/api/public", { + headers: { Origin: "https://myblog.com" } + }) + expect(res.status).toBe(200) + expect(res.headers.get("access-control-allow-origin")).toBe( + "https://myblog.com" + ) + expect(res.headers.get("access-control-allow-credentials")).toBe("true") + expect(res.headers.get("vary")).toBe("Origin") + }) + + it("业务错误响应(401 / 404)在合法源下保留 CORS 头以供浏览器读取", async () => { + const { env } = await initializedContext() + + // 401 未登录 + const unauth = await request(env, "/api/me", { + headers: { Origin: "https://myblog.com" } + }) + expect(unauth.status).toBe(401) + expect(unauth.headers.get("access-control-allow-origin")).toBe( + "https://myblog.com" + ) + expect(unauth.headers.get("access-control-allow-credentials")).toBe("true") + + // 404 接口不存在(公开前缀下的未命中路径) + const notFound = await request(env, "/api/comments/non-existent-subpath", { + headers: { Origin: "https://myblog.com" } + }) + expect(notFound.status).toBe(404) + expect(notFound.headers.get("access-control-allow-origin")).toBe( + "https://myblog.com" + ) + expect(notFound.headers.get("access-control-allow-credentials")).toBe( + "true" + ) + }) + + it("配置 safeDomains 时,严格限制允许源,拒绝非法域名", async () => { + const { env } = await initializedContext() + + // 设置安全域名白名单 + await writeCalineSettings(env, { + safeDomains: ["https://allowed.com", "myblog.org"] + }) + + // 1. 非法 Origin 发起预检 -> 403 Forbidden 且无 allow-origin 头 + const evilOpt = await request(env, "/api/comments", { + method: "OPTIONS", + headers: { + Origin: "https://evil.com", + "Access-Control-Request-Method": "POST" + } + }) + expect(evilOpt.status).toBe(403) + expect(evilOpt.headers.get("access-control-allow-origin")).toBeNull() + + // 2. 合法完整源发起预检 -> 204 + const goodOpt = await request(env, "/api/comments", { + method: "OPTIONS", + headers: { + Origin: "https://allowed.com", + "Access-Control-Request-Method": "POST" + } + }) + expect(goodOpt.status).toBe(204) + expect(goodOpt.headers.get("access-control-allow-origin")).toBe( + "https://allowed.com" + ) + + // 3. 合法子域名发起预检 -> 204 + const subOpt = await request(env, "/api/comments", { + method: "OPTIONS", + headers: { + Origin: "https://sub.myblog.org", + "Access-Control-Request-Method": "GET" + } + }) + expect(subOpt.status).toBe(204) + expect(subOpt.headers.get("access-control-allow-origin")).toBe( + "https://sub.myblog.org" + ) + + // 4. 非法源发起业务请求 -> 响应不含 CORS 头 + const evilReq = await request(env, "/api/public", { + headers: { Origin: "https://attacker.com" } + }) + expect(evilReq.status).toBe(200) + expect(evilReq.headers.get("access-control-allow-origin")).toBeNull() + }) + + it("同源/无 Origin 头请求正常通行,不增加 Access-Control-* 头", async () => { + const { env } = await initializedContext() + + const res = await request(env, "/api/public") + expect(res.status).toBe(200) + expect(res.headers.get("access-control-allow-origin")).toBeNull() + expect(res.headers.get("access-control-allow-credentials")).toBeNull() + }) +}) diff --git a/worker/test/email-guard.test.ts b/worker/test/email-guard.test.ts index 76ecd44..ebc0df8 100644 --- a/worker/test/email-guard.test.ts +++ b/worker/test/email-guard.test.ts @@ -53,9 +53,15 @@ describe("邮件未配置守卫", () => { "EMAIL_NOT_CONFIGURED" ) - const view = (await ( - await request(env, "/api/admin/settings", { headers: { cookie: admin } }) - ).json()) as { registration: { emailVerificationRequired: boolean } } + const view = ( + (await ( + await request(env, "/api/admin/settings", { + headers: { cookie: admin } + }) + ).json()) as { + data: { registration: { emailVerificationRequired: boolean } } + } + ).data expect(view.registration.emailVerificationRequired).toBe(false) }) diff --git a/worker/test/email-provider.test.ts b/worker/test/email-provider.test.ts index fc85719..839271f 100644 --- a/worker/test/email-provider.test.ts +++ b/worker/test/email-provider.test.ts @@ -302,7 +302,7 @@ describe("管理面发送测试邮件", () => { { cookie } ) expect(res.status).toBe(200) - expect(await res.json()).toEqual({ success: true }) + expect(await res.json()).toEqual({ data: { success: true } }) expect(stub.sent).toHaveLength(1) }) @@ -324,9 +324,13 @@ describe("管理面发送测试邮件", () => { { cookie } ) expect(put.status).toBe(200) - const body = (await put.json()) as { - email: { configured: boolean; resend: { apiKeySet: boolean } } - } + const body = ( + (await put.json()) as { + data: { + email: { configured: boolean; resend: { apiKeySet: boolean } } + } + } + ).data expect(body.email.configured).toBe(true) expect(body.email.resend.apiKeySet).toBe(true) expect(JSON.stringify(body)).not.toContain("re_live_key") diff --git a/worker/test/me-lock.test.ts b/worker/test/me-lock.test.ts index 725f58d..dd84326 100644 --- a/worker/test/me-lock.test.ts +++ b/worker/test/me-lock.test.ts @@ -116,14 +116,18 @@ describe("个人资料修改锁", () => { { cookie: admin } ) expect(put.status).toBe(200) - expect(await put.json()).toMatchObject({ + expect( + ((await put.json()) as { data: Record }).data + ).toMatchObject({ profileLocks: { displayNameLocked: true } }) const got = await request(env, "/api/admin/settings", { headers: { cookie: admin } }) - expect(await got.json()).toMatchObject({ + expect( + ((await got.json()) as { data: Record }).data + ).toMatchObject({ profileLocks: { displayNameLocked: true } }) @@ -134,7 +138,9 @@ describe("个人资料修改锁", () => { { profileLocks: { displayNameLocked: false } }, { cookie: admin } ) - expect(await partial.json()).toMatchObject({ + expect( + ((await partial.json()) as { data: Record }).data + ).toMatchObject({ profileLocks: { displayNameLocked: false } }) }) @@ -151,9 +157,13 @@ describe("个人资料修改锁", () => { { cookie: admin } ) expect(put.status).toBe(200) - const body = (await put.json()) as { - profileLocks: Record - } + const body = ( + (await put.json()) as { + data: { + profileLocks: Record + } + } + ).data expect(body.profileLocks).not.toHaveProperty("usernameLocked") expect( db.db diff --git a/worker/test/single-mode.test.ts b/worker/test/single-mode.test.ts index 3335bef..0067662 100644 --- a/worker/test/single-mode.test.ts +++ b/worker/test/single-mode.test.ts @@ -125,9 +125,13 @@ describe("单人档", () => { await loginUser(env, { email: "owner@example.test" }) ) - const view = (await ( - await request(env, "/api/admin/settings", { headers: { cookie } }) - ).json()) as { registration: unknown; setup: { pageEnabled: boolean } } + const view = ( + (await ( + await request(env, "/api/admin/settings", { headers: { cookie } }) + ).json()) as { + data: { registration: unknown; setup: { pageEnabled: boolean } } + } + ).data expect(view.registration).toBeNull() const write = await putJson(