feat: Phase 11 — CRUD (create/update/delete) + auth + web UI
- Core: createDocument/updateDocument/deleteDocument (file + DB + revision + chunks) - Parser: stringifyFile (serialize markdown with frontmatter to disk) - API: tRPC CRUD routers (auth-gated via requireWriteAuth middleware) - API: createContext now passes expectedSecret from deps (request-scoped auth) - MCP: 3 new write tools (create_document, update_document, delete_document) - Web: /create page + ?edit=1 form, /api/auth/login (cookie-based), /api/docs REST CRUD - Web: Edit buttons on homepage + doc pages (auth-gated) - Tests: 8 new tests (5 tRPC CRUD + 3 MCP CRUD auth), 40 total all green
This commit is contained in:
@@ -0,0 +1,74 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { ADMIN_PASSWORD } from "@mcpedia/config";
|
||||
import { createHmac, timingSafeEqual } from "node:crypto";
|
||||
|
||||
// POST /api/auth/login — verify admin password, set a signed cookie.
|
||||
// Uses a simple HMAC cookie (no JWT library) — sufficient for a single-admin KB.
|
||||
const COOKIE_NAME = "mcpedia_admin";
|
||||
const COOKIE_MAX_AGE = 60 * 60 * 24 * 7; // 7 days
|
||||
|
||||
function signCookie(value: string): string {
|
||||
const secret = ADMIN_PASSWORD || "fallback";
|
||||
const sig = createHmac("sha256", secret).update(value).digest("hex");
|
||||
return `${value}.${sig}`;
|
||||
}
|
||||
|
||||
function verifyCookie(cookieValue: string | undefined): boolean {
|
||||
if (!cookieValue) return false;
|
||||
const [value, sig] = cookieValue.split(".");
|
||||
if (!value || !sig) return false;
|
||||
const expected = signCookie(value);
|
||||
return timingSafeEqual(
|
||||
Buffer.from(cookieValue),
|
||||
Buffer.from(expected),
|
||||
);
|
||||
}
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
const body = await req.json().catch(() => ({}));
|
||||
const { password } = body;
|
||||
|
||||
if (!ADMIN_PASSWORD || typeof password !== "string") {
|
||||
return NextResponse.json({ ok: false, error: "Unauthorized" }, { status: 401 });
|
||||
}
|
||||
|
||||
const ok = timingSafeEqual(
|
||||
Buffer.from(password),
|
||||
Buffer.from(ADMIN_PASSWORD),
|
||||
);
|
||||
|
||||
if (!ok) {
|
||||
return NextResponse.json({ ok: false, error: "Unauthorized" }, { status: 401 });
|
||||
}
|
||||
|
||||
const cookie = signCookie("admin");
|
||||
const res = NextResponse.json({ ok: true });
|
||||
res.cookies.set(COOKIE_NAME, cookie, {
|
||||
maxAge: COOKIE_MAX_AGE,
|
||||
httpOnly: true,
|
||||
path: "/",
|
||||
sameSite: "lax",
|
||||
secure: process.env.NODE_ENV === "production",
|
||||
});
|
||||
return res;
|
||||
}
|
||||
|
||||
// GET /api/auth/login — returns 200 if currently authenticated, 401 otherwise.
|
||||
export async function GET(req: NextRequest) {
|
||||
const cookie = req.cookies.get(COOKIE_NAME)?.value;
|
||||
if (verifyCookie(cookie)) return NextResponse.json({ ok: true });
|
||||
return NextResponse.json({ ok: false }, { status: 401 });
|
||||
}
|
||||
|
||||
// DELETE /api/auth/login — clear the cookie (logout).
|
||||
export async function DELETE() {
|
||||
const res = NextResponse.json({ ok: true });
|
||||
res.cookies.delete({ name: COOKIE_NAME, path: "/" });
|
||||
return res;
|
||||
}
|
||||
|
||||
// Exported for server components to call directly.
|
||||
export function isAuthenticated(req: NextRequest): boolean {
|
||||
const cookie = req.cookies.get(COOKIE_NAME)?.value;
|
||||
return verifyCookie(cookie);
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import {
|
||||
createDocument,
|
||||
updateDocument,
|
||||
deleteDocument,
|
||||
listDocuments,
|
||||
} from "@mcpedia/core";
|
||||
import { WEBHOOK_SECRET } from "@mcpedia/config";
|
||||
import { createHmac, timingSafeEqual } from "node:crypto";
|
||||
|
||||
// POST /api/docs
|
||||
// Create a new document.
|
||||
// Body: { slug, title, section, body, type?, status?, author?, tags? }
|
||||
// Auth: x-webhook-secret header matching WEBHOOK_SECRET.
|
||||
export async function POST(req: NextRequest) {
|
||||
if (!WEBHOOK_SECRET) {
|
||||
return NextResponse.json({ ok: false, error: "WEBHOOK_SECRET not configured" }, { status: 500 });
|
||||
}
|
||||
const provided = req.headers.get("x-webhook-secret");
|
||||
if (!provided || !timingSafeEqual(Buffer.from(provided), Buffer.from(WEBHOOK_SECRET))) {
|
||||
return NextResponse.json({ ok: false, error: "Unauthorized" }, { status: 401 });
|
||||
}
|
||||
|
||||
const body = await req.json().catch(() => null);
|
||||
if (!body) {
|
||||
return NextResponse.json({ ok: false, error: "Invalid JSON body" }, { status: 400 });
|
||||
}
|
||||
|
||||
try {
|
||||
const doc = await createDocument(body);
|
||||
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 });
|
||||
}
|
||||
}
|
||||
|
||||
// PUT /api/docs/{slug}
|
||||
// Update an existing document.
|
||||
// Body: { title?, body?, type?, status?, tags?, author? }
|
||||
export async function PUT(req: NextRequest) {
|
||||
if (!WEBHOOK_SECRET) {
|
||||
return NextResponse.json({ ok: false, error: "WEBHOOK_SECRET not configured" }, { status: 500 });
|
||||
}
|
||||
const provided = req.headers.get("x-webhook-secret");
|
||||
if (!provided || !timingSafeEqual(Buffer.from(provided), Buffer.from(WEBHOOK_SECRET))) {
|
||||
return NextResponse.json({ ok: false, error: "Unauthorized" }, { status: 401 });
|
||||
}
|
||||
|
||||
// Extract slug from URL path: /api/docs/{slug}
|
||||
const url = new URL(req.url);
|
||||
const parts = url.pathname.split("/").filter(Boolean);
|
||||
const slug = parts[2]; // ["api", "docs", "...slugParts"]
|
||||
if (!slug || slug === "docs") {
|
||||
return NextResponse.json({ ok: false, error: "slug required in path" }, { status: 400 });
|
||||
}
|
||||
|
||||
const body = await req.json().catch(() => null);
|
||||
if (!body) {
|
||||
return NextResponse.json({ ok: false, error: "Invalid JSON body" }, { status: 400 });
|
||||
}
|
||||
|
||||
try {
|
||||
// Reconstruct the full slug from path segments
|
||||
const fullSlug = parts.slice(2).join("/");
|
||||
const doc = await updateDocument(fullSlug, body);
|
||||
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 });
|
||||
}
|
||||
}
|
||||
|
||||
// DELETE /api/docs/{slug}
|
||||
export async function DELETE(req: NextRequest) {
|
||||
if (!WEBHOOK_SECRET) {
|
||||
return NextResponse.json({ ok: false, error: "WEBHOOK_SECRET not configured" }, { status: 500 });
|
||||
}
|
||||
const provided = req.headers.get("x-webhook-secret");
|
||||
if (!provided || !timingSafeEqual(Buffer.from(provided), Buffer.from(WEBHOOK_SECRET))) {
|
||||
return NextResponse.json({ ok: false, error: "Unauthorized" }, { status: 401 });
|
||||
}
|
||||
|
||||
const url = new URL(req.url);
|
||||
const parts = url.pathname.split("/").filter(Boolean);
|
||||
const slug = parts.slice(2).join("/");
|
||||
if (!slug) {
|
||||
return NextResponse.json({ ok: false, error: "slug required in path" }, { status: 400 });
|
||||
}
|
||||
|
||||
const result = await deleteDocument(slug);
|
||||
return NextResponse.json({ ok: true, deleted: result.deleted });
|
||||
}
|
||||
Reference in New Issue
Block a user