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
77 changes: 77 additions & 0 deletions web/src/lib/api.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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")
})
})
46 changes: 40 additions & 6 deletions web/src/lib/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -102,6 +109,29 @@ async function request<T>(

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/")) {
Expand All @@ -111,17 +141,21 @@ async function request<T>(
}
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
}

/* 公开数据 */
Expand Down
4 changes: 4 additions & 0 deletions worker/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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()
Expand Down
75 changes: 75 additions & 0 deletions worker/src/middleware/cors.ts
Original file line number Diff line number Diff line change
@@ -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<HonoEnv> = 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")
}
}
32 changes: 16 additions & 16 deletions worker/src/routes/admin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) => {
Expand Down Expand Up @@ -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) => {
Expand Down Expand Up @@ -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) => {
Expand All @@ -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) => {
Expand All @@ -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) => {
Expand All @@ -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) => {
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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
Expand All @@ -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") {
Expand All @@ -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) => {
Expand All @@ -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) => {
Expand All @@ -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") {
Expand All @@ -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) => {
Expand Down Expand Up @@ -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) => {
Expand All @@ -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) => {
Expand Down
Loading
Loading