Files
mcpedia/apps/web/app/api/docs/route.ts
T
asepharyana c760c3c087
CI / typecheck + build (turbo) (push) Canceled after 0s
feat(core): dynamic custom frontmatter fields for CTF writeup metadata
- Add extra_fields JSONB column to documents table (migration 0003)
- CreateDocInput/UpdateDocInput: extraFields?: Record<string, string>
- parseFile: extracts non-standard frontmatter keys as extraFields
- stringifyFile: writes extraFields dynamically to YAML frontmatter
- toMeta: spreads extraFields from DB row into DocumentMeta
- DocForm: '+ Add field' UI for content creators to add any metadata
- API routes: splitPayload() separates standard vs custom fields
- Doc page: CustomFieldBadges dynamically renders any custom field
- Add db:migrate / db:push scripts + deploy workflow migration step
- Add CTF writeup template (content/writeups/ctf/template/)
- Add sample DEF CON writeup with event/challenge/category/difficulty/points
- Add @tailwindcss/typography for table rendering (prose classes)
- Add remark-gfm for GitHub Flavored Markdown table parsing
2026-08-20 23:18:57 +07:00

85 lines
2.9 KiB
TypeScript

import { NextRequest, NextResponse } from "next/server";
import {
createDocument,
updateDocument,
deleteDocument,
listDocuments,
} from "@mcpedia/core";
import { WEBHOOK_SECRET } from "@mcpedia/config";
import { timingSafeEqual } from "node:crypto";
// Web CRUD auth: either the x-webhook-secret header (API/MCP style) OR the
// mcpedia_admin cookie (web login). One of the two must be valid.
function isAuthorized(req: NextRequest): boolean {
if (!WEBHOOK_SECRET) return false;
const headerSecret = req.headers.get("x-webhook-secret") ?? "";
if (headerSecret && timingSafeEqual(Buffer.from(headerSecret), Buffer.from(WEBHOOK_SECRET))) {
return true;
}
const cookie = req.cookies.get("mcpedia_admin")?.value ?? "";
return cookie.startsWith("admin.");
}
function unauthorized() {
return NextResponse.json({ ok: false, error: "Unauthorized" }, { status: 401 });
}
// Standard DocumentMeta field names — NOT custom fields.
const STANDARD_FIELDS = new Set([
"slug", "title", "body", "section", "type", "status",
"author", "tags", "createdAt", "updatedAt", "id", "path",
]);
/**
* Separate a flat payload into standard CRUD fields + extraFields (custom metadata).
* The DocForm sends all fields flat — any key not in STANDARD_FIELDS becomes an
* entry in extraFields, which is stored as JSONB in the documents table.
*/
function splitPayload(body: Record<string, unknown>): {
standard: Record<string, unknown>;
extraFields: Record<string, unknown>;
} {
const standard: Record<string, unknown> = {};
const extraFields: Record<string, unknown> = {};
for (const [key, value] of Object.entries(body)) {
if (STANDARD_FIELDS.has(key)) {
standard[key] = value;
} else {
extraFields[key] = value;
}
}
return { standard, extraFields };
}
// GET /api/docs — list all documents (for sidebar navigation).
export async function GET() {
const docs = await listDocuments();
return NextResponse.json(docs);
}
// POST /api/docs — Create a new document.
export async function POST(req: NextRequest) {
if (!isAuthorized(req)) return unauthorized();
const body = await req.json().catch(() => null);
if (!body) {
return NextResponse.json({ ok: false, error: "Invalid JSON body" }, { status: 400 });
}
try {
const { standard, extraFields } = splitPayload(body);
// Coerce all extra field values to strings (form sends strings; API/MCP may send objects).
const stringExtra: Record<string, string> = {};
for (const [k, v] of Object.entries(extraFields)) {
if (v !== undefined && v !== null) {
stringExtra[k] = typeof v === "string" ? v : JSON.stringify(v);
}
}
const doc = await createDocument({ ...standard, extraFields: stringExtra } as any);
return NextResponse.json({ ok: true, slug: doc.slug, doc });
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
return NextResponse.json({ ok: false, error: msg }, { status: 400 });
}
}