import type { NextApiRequest, NextApiResponse } from "next"; import { authenticateDocumentKey } from "./document-keys"; import { DocumentConflictError, DocumentValidationError, validateDocument, type Doc } from "./docs"; export function authorizeDocuments(request: NextApiRequest, response: NextApiResponse, write = false) { response.setHeader("Cache-Control", "private, no-store"); response.setHeader("X-Content-Type-Options", "nosniff"); const header = request.headers.authorization; const token = typeof header === "string" && header.startsWith("Bearer ") ? header.slice(7) : undefined; const key = authenticateDocumentKey(token); if (!key) { response.status(401).json({ error: "需要有效的文档 API Key", code: "unauthorized" }); return null; } if (write && key.scope !== "read-write") { response.status(403).json({ error: "该 API Key 仅允许读取文档", code: "read_only" }); return null; } return key; } export function documentApiError(response: NextApiResponse, error: unknown) { if (error instanceof DocumentConflictError) return response.status(409).json({ error: error.message, code: "conflict" }); if (error instanceof DocumentValidationError) return response.status(400).json({ error: error.message, code: "invalid_document" }); return response.status(503).json({ error: "文档数据库暂时不可用", code: "unavailable" }); } export function parseDocument(value: unknown): Doc { if (!value || typeof value !== "object" || Array.isArray(value)) throw new DocumentValidationError("Expected a document object"); const row = value as Record; const fields = ["slug", "sourceSlug", "title", "category", "collection", "group", "description", "draft", "featured", "content", "revision"]; if (Object.keys(row).some((key) => !fields.includes(key))) throw new DocumentValidationError("Unknown document field"); const doc = Object.fromEntries(fields.map((key) => [key, row[key]])) as Doc; validateDocument(doc); if (!Number.isSafeInteger(doc.revision) || doc.revision < 0) throw new DocumentValidationError("Provide expected revision"); return doc; } export function pagination(request: NextApiRequest) { const number = (value: string | string[] | undefined, fallback: number) => { if (value === undefined) return fallback; if (typeof value !== "string" || !/^\d+$/.test(value)) throw new DocumentValidationError("Invalid pagination"); return Number(value); }; return { limit: number(request.query.limit, 50), offset: number(request.query.offset, 0) }; } export function idempotency(request: NextApiRequest, namespace: string) { const id = request.headers["idempotency-key"]; if (id === undefined) return undefined; if (typeof id !== "string" || !/^[A-Za-z0-9._:-]{1,128}$/.test(id)) throw new DocumentValidationError("Invalid Idempotency-Key"); return { namespace, id }; }