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:
@@ -2,6 +2,7 @@ import { test, expect, beforeEach, mock } from "bun:test";
|
||||
import { createApp } from "../src/app";
|
||||
import type { ApiDeps } from "../src/app";
|
||||
import { DASHBOARD_HTML } from "../src/dashboard";
|
||||
import { Hono } from "hono";
|
||||
|
||||
// -------------------------------------------------------------------
|
||||
// A fake queue that records calls and returns canned counts. Injected into
|
||||
@@ -39,6 +40,37 @@ mock.module("@mcpedia/queue", () => ({
|
||||
INDEX_QUEUE: "mcpedia-index",
|
||||
}));
|
||||
|
||||
// Mock @mcpedia/core so tRPC CRUD procedures don't hit Postgres.
|
||||
// Only the functions used by the router are faked; assertions record calls.
|
||||
const coreCalls = {
|
||||
createDocument: [] as Array<any[]>,
|
||||
updateDocument: [] as Array<any[]>,
|
||||
deleteDocument: [] as Array<any[]>,
|
||||
};
|
||||
mock.module("@mcpedia/core", () => ({
|
||||
keywordSearch: () => Promise.resolve([]),
|
||||
getDocument: () => Promise.resolve(null),
|
||||
getRelated: () => Promise.resolve([]),
|
||||
hybridSearch: () => Promise.resolve([]),
|
||||
semanticSearch: () => Promise.resolve([]),
|
||||
listDocuments: () => Promise.resolve([]),
|
||||
listRevisions: () => Promise.resolve([]),
|
||||
getRevision: () => Promise.resolve(null),
|
||||
restoreRevision: () => Promise.resolve(null),
|
||||
createDocument: (...args: any[]) => {
|
||||
coreCalls.createDocument.push(args);
|
||||
return Promise.resolve({ slug: "docs/test", title: "Test" });
|
||||
},
|
||||
updateDocument: (...args: any[]) => {
|
||||
coreCalls.updateDocument.push(args);
|
||||
return Promise.resolve({ slug: args[0], title: "Updated" });
|
||||
},
|
||||
deleteDocument: (...args: any[]) => {
|
||||
coreCalls.deleteDocument.push(args);
|
||||
return Promise.resolve({ deleted: true });
|
||||
},
|
||||
}));
|
||||
|
||||
let SECRET: string;
|
||||
beforeEach(() => {
|
||||
SECRET = "test-secret-" + Math.random().toString(36).slice(2);
|
||||
@@ -131,3 +163,66 @@ test("GET /dashboard returns the self-contained HTML", async () => {
|
||||
expect(html).toContain("Index Queue (BullMQ)");
|
||||
expect(html).toContain(DASHBOARD_HTML.slice(0, 100));
|
||||
});
|
||||
|
||||
// --- Phase 11: CRUD tRPC procedures (auth-gated) ---
|
||||
|
||||
function trpcRequest(app: Hono, procedure: string, input: unknown, secret?: string) {
|
||||
const headers: Record<string, string> = {
|
||||
"content-type": "application/json",
|
||||
};
|
||||
if (secret) headers["x-webhook-secret"] = secret;
|
||||
// tRPC fetch adapter expects the procedure input directly as the JSON body
|
||||
// (not wrapped in a JSON-RPC envelope). The procedure name comes from the URL.
|
||||
return app.request("/trpc/" + procedure, {
|
||||
method: "POST",
|
||||
headers,
|
||||
body: JSON.stringify(input),
|
||||
});
|
||||
}
|
||||
|
||||
test("tRPC createDocument without secret -> rejects (tRPC error)", async () => {
|
||||
const app = await createApp(makeDeps(SECRET, fakeQueue({})));
|
||||
const res = await trpcRequest(app, "createDocument", {
|
||||
slug: "docs/test", title: "Test", section: "docs", body: "# Hi"
|
||||
});
|
||||
// tRPC middleware throws Error -> JSON-RPC error (httpStatus 500, not 401)
|
||||
expect(res.status).toBe(500);
|
||||
expect(coreCalls.createDocument).toHaveLength(0);
|
||||
});
|
||||
|
||||
test("tRPC createDocument with secret -> 200 + calls core", async () => {
|
||||
const app = await createApp(makeDeps(SECRET, fakeQueue({})));
|
||||
const res = await trpcRequest(app, "createDocument", {
|
||||
slug: "docs/test", title: "Test", section: "docs", body: "# Hi"
|
||||
}, SECRET);
|
||||
expect(res.status).toBe(200);
|
||||
expect(coreCalls.createDocument).toHaveLength(1);
|
||||
});
|
||||
|
||||
test("tRPC updateDocument with secret -> 200 + calls core", async () => {
|
||||
const app = await createApp(makeDeps(SECRET, fakeQueue({})));
|
||||
const res = await trpcRequest(app, "updateDocument", {
|
||||
slug: "docs/test", body: "# Updated"
|
||||
}, SECRET);
|
||||
expect(res.status).toBe(200);
|
||||
expect(coreCalls.updateDocument).toHaveLength(1);
|
||||
});
|
||||
|
||||
test("tRPC deleteDocument without secret -> rejects (tRPC error)", async () => {
|
||||
const app = await createApp(makeDeps(SECRET, fakeQueue({})));
|
||||
const res = await trpcRequest(app, "deleteDocument", {
|
||||
slug: "docs/test"
|
||||
});
|
||||
// tRPC middleware throws Error -> JSON-RPC error (httpStatus 500, not 401)
|
||||
expect(res.status).toBe(500);
|
||||
expect(coreCalls.deleteDocument).toHaveLength(0);
|
||||
});
|
||||
|
||||
test("tRPC deleteDocument with secret -> 200 + calls core", async () => {
|
||||
const app = await createApp(makeDeps(SECRET, fakeQueue({})));
|
||||
const res = await trpcRequest(app, "deleteDocument", {
|
||||
slug: "docs/test"
|
||||
}, SECRET);
|
||||
expect(res.status).toBe(200);
|
||||
expect(coreCalls.deleteDocument).toHaveLength(1);
|
||||
});
|
||||
|
||||
@@ -140,6 +140,7 @@ export async function createApp(deps?: ApiDeps): Promise<Hono> {
|
||||
createContext: (): Context => ({
|
||||
db, // real Postgres connection (read procedures use it via @mcpedia/db).
|
||||
webhookSecret: c.req.raw.headers.get("x-webhook-secret") ?? undefined,
|
||||
expectedSecret: d.webhookSecret,
|
||||
}),
|
||||
}),
|
||||
);
|
||||
|
||||
+45
-3
@@ -10,20 +10,22 @@ import {
|
||||
listRevisions,
|
||||
getRevision,
|
||||
restoreRevision,
|
||||
createDocument,
|
||||
updateDocument,
|
||||
deleteDocument,
|
||||
} from "@mcpedia/core";
|
||||
import { getQueue, INDEX_QUEUE } from "@mcpedia/queue";
|
||||
import { getConnection, BULLMQ_PREFIX } from "@mcpedia/queue/client";
|
||||
import { WEBHOOK_SECRET } from "@mcpedia/config";
|
||||
|
||||
// restoreRevision is a state-changing action (it rewrites the live document row
|
||||
// + rebuilds its chunks). It must NOT be callable anonymously over the network —
|
||||
// only the Web UI (which calls @mcpedia/core directly) and an operator with the
|
||||
// webhook secret may use it. Anything else is rejected.
|
||||
const requireWriteAuth = t.middleware(({ ctx, next }) => {
|
||||
if (!WEBHOOK_SECRET) {
|
||||
if (!ctx.expectedSecret) {
|
||||
throw new Error("WEBHOOK_SECRET is not configured; writes are disabled");
|
||||
}
|
||||
if (ctx.webhookSecret !== WEBHOOK_SECRET) {
|
||||
if (ctx.webhookSecret !== ctx.expectedSecret) {
|
||||
throw new Error("unauthorized: missing or invalid x-webhook-secret");
|
||||
}
|
||||
return next();
|
||||
@@ -68,6 +70,46 @@ export const appRouter = router({
|
||||
.input(z.object({ id: z.string() }))
|
||||
.mutation(async ({ input }) => restoreRevision(input.id)),
|
||||
|
||||
// --- Phase 11: CRUD (gated by x-webhook-secret / admin auth) ---
|
||||
createDocument: publicProcedure
|
||||
.use(requireWriteAuth)
|
||||
.input(
|
||||
z.object({
|
||||
slug: z.string().min(1),
|
||||
title: z.string().min(1),
|
||||
section: z.enum(["docs", "writeups", "research", "notes"]),
|
||||
body: z.string(),
|
||||
type: z.enum(["documentation", "writeup", "research", "note"]).optional(),
|
||||
status: z.enum(["published", "draft"]).optional(),
|
||||
author: z.string().optional(),
|
||||
tags: z.array(z.string()).optional(),
|
||||
}),
|
||||
)
|
||||
.mutation(async ({ input }) => createDocument(input)),
|
||||
|
||||
updateDocument: publicProcedure
|
||||
.use(requireWriteAuth)
|
||||
.input(
|
||||
z.object({
|
||||
slug: z.string().min(1),
|
||||
title: z.string().min(1).optional(),
|
||||
body: z.string().optional(),
|
||||
type: z.enum(["documentation", "writeup", "research", "note"]).optional(),
|
||||
status: z.enum(["published", "draft"]).optional(),
|
||||
tags: z.array(z.string()).optional(),
|
||||
author: z.string().optional(),
|
||||
}),
|
||||
)
|
||||
.mutation(async ({ input }) => {
|
||||
const { slug, ...rest } = input;
|
||||
return updateDocument(slug, rest);
|
||||
}),
|
||||
|
||||
deleteDocument: publicProcedure
|
||||
.use(requireWriteAuth)
|
||||
.input(z.object({ slug: z.string().min(1) }))
|
||||
.mutation(async ({ input }) => deleteDocument(input.slug)),
|
||||
|
||||
// --- Phase 3: async job status ---
|
||||
jobStatus: publicProcedure
|
||||
.input(z.object({ id: z.string() }))
|
||||
|
||||
@@ -4,9 +4,12 @@ import { db } from "@mcpedia/db";
|
||||
export interface Context {
|
||||
db: typeof db;
|
||||
// Raw `x-webhook-secret` header from the incoming request, if present.
|
||||
// State-changing tRPC mutations (restoreRevision) require it to match
|
||||
// WEBHOOK_SECRET; read-only procedures ignore it.
|
||||
// State-changing tRPC mutations (restoreRevision, CRUD) require it to match
|
||||
// the configured secret; read-only procedures ignore it.
|
||||
webhookSecret?: string;
|
||||
// The configured expected secret (from deps). Used by requireWriteAuth
|
||||
// to validate the header — request-scoped so tests can inject a fake.
|
||||
expectedSecret: string;
|
||||
}
|
||||
|
||||
export const t = initTRPC.context<Context>().create();
|
||||
|
||||
Reference in New Issue
Block a user