feat(mcpedia): Phase 4 — operability + correctness hardening

Reinterpreted from the plan's YAGNI 'Scale-out' (OpenSearch/object-storage
/multi-tenant deferred at KB scale). Phase 4 = make the Phase 3 async +
revision system correct, secure, observable, deployable.

- T1 (correctness bug): restoreRevision now rebuilds semantic chunks via new
  @mcpedia/core reindexChunks(slug) so semantic/hybrid search stay consistent
  after a restore (previously document_chunks held the NEW body while
  documents.body held the restored OLD body -> stale search).
- T2 (security): /hooks/* git-sync webhooks now require x-webhook-secret header
  matching WEBHOOK_SECRET (401 otherwise); API fails fast at startup if unset.
  Added WEBHOOK_SECRET to @mcpedia/config + .env.example; set real secret in .env.
- T3 (UX): web doc page shows a History panel (revision no/reason/date/length)
  with per-revision Restore; app/api/revisions/restore/route.ts calls
  restoreRevision + revalidatePath (server-component only, no client JS).
- T4: listRevisions gains offset paging; summary never includes body.
- T5 (ops): deploy/mcpedia-api.service + deploy/mcpedia-worker.service systemd
  units (Restart=on-failure, EnvironmentFile=.env). Not auto-enabled on host.

Verified against live imrnes Redis + Postgres: turbo typecheck+build green;
restore-rebuilds-chunks (marker present -> gone after restore); webhook 401/200;
web restore route redirects to doc + reverts body; revisions API returns summary
(no body); systemd-analyze verify passes.
This commit is contained in:
asepharyana
2026-08-19 21:54:54 +07:00
parent 8f2229d447
commit b92f6f91fa
11 changed files with 335 additions and 6 deletions
+19 -1
View File
@@ -5,22 +5,40 @@ import { db } from "@mcpedia/db";
import { appRouter } from "./router";
import type { Context } from "./trpc";
import { enqueueIndexDoc, enqueueFullIndex } from "@mcpedia/queue";
import { WEBHOOK_SECRET } from "@mcpedia/config";
// Fail fast: never expose an open git-sync endpoint. If the operator hasn't
// set WEBHOOK_SECRET, refuse to start rather than run an unauthenticated hook.
if (!WEBHOOK_SECRET) {
throw new Error(
"WEBHOOK_SECRET is not set — /hooks/* would be open. Set it (see .env.example) before starting the API.",
);
}
const app = new Hono();
// Health check.
// Health check (no auth — safe to expose).
app.get("/health", (c) => c.json({ ok: true }));
// Shared guard for the git-sync webhooks: require `x-webhook-secret` header to
// match the configured secret. Reject anything else with 401.
function assertWebhookAuth(c: { req: { header: (k: string) => string | undefined } }): boolean {
const provided = c.req.header("x-webhook-secret");
return provided != null && provided === WEBHOOK_SECRET;
}
// --- Phase 3: Git synchronization hook ---
// POST /hooks/reindex -> enqueue a full-corpus reindex (git push webhook)
// POST /hooks/index?slug=... -> enqueue a single document reindex
// Returns the created job id(s). The worker processes them asynchronously.
app.post("/hooks/reindex", async (c) => {
if (!assertWebhookAuth(c)) return c.json({ ok: false, error: "unauthorized" }, 401);
const job = await enqueueFullIndex("git-push");
return c.json({ ok: true, jobId: job.id, kind: "full" });
});
app.post("/hooks/index", async (c) => {
if (!assertWebhookAuth(c)) return c.json({ ok: false, error: "unauthorized" }, 401);
const slug = c.req.query("slug");
if (!slug) return c.json({ ok: false, error: "slug query param required" }, 400);
// slug is the relative path without extension, e.g. docs/websocket/contract
+30 -1
View File
@@ -1,6 +1,6 @@
import Link from "next/link";
import { notFound } from "next/navigation";
import { getDocument, listDocuments, getRelated } from "@mcpedia/core";
import { getDocument, listDocuments, getRelated, listRevisions } from "@mcpedia/core";
import Markdown from "@/components/Markdown";
export default async function DocPage({
@@ -14,6 +14,7 @@ export default async function DocPage({
if (!doc) notFound();
const related = await getRelated(fullSlug, 5);
const revisions = await listRevisions(fullSlug, 10);
return (
<article className="space-y-4">
@@ -48,6 +49,34 @@ export default async function DocPage({
</ul>
</aside>
)}
{revisions.length > 0 && (
<aside className="mt-8 border-t border-zinc-200 dark:border-zinc-800 pt-4">
<h2 className="text-sm font-medium mb-2">History</h2>
<ul className="text-sm space-y-1">
{revisions.map((rev) => (
<li
key={rev.id}
className="flex items-center justify-between gap-2"
>
<span className="text-zinc-600 dark:text-zinc-400">
#{rev.revisionNo} · {rev.reason} ·{" "}
{new Date(rev.createdAt).toLocaleString()} · {rev.bodyLength} chars
</span>
<form action={`/api/revisions/restore/`} method="post">
<input type="hidden" name="id" value={rev.id} />
<button
type="submit"
className="rounded border border-zinc-300 dark:border-zinc-700 px-2 py-0.5 text-xs hover:bg-zinc-100 dark:hover:bg-zinc-800"
>
Restore
</button>
</form>
</li>
))}
</ul>
</aside>
)}
</article>
);
}
@@ -0,0 +1,31 @@
import { NextRequest, NextResponse } from "next/server";
import { restoreRevision, getRevision } from "@mcpedia/core";
import { revalidatePath } from "next/cache";
// POST /api/revisions/restore — restore a document to a past revision.
// Body (form-urlencoded): id=<revision uuid>
// After restoring, we rebuild semantic chunks (handled inside restoreRevision)
// and revalidate the doc page so the Web UI reflects the restored body.
export async function POST(req: NextRequest) {
const form = await req.formData().catch(() => null);
const id = form?.get("id");
if (typeof id !== "string" || id.length === 0) {
return NextResponse.json({ ok: false, error: "missing id" }, { status: 400 });
}
const rev = await getRevision(id);
if (!rev) {
return NextResponse.json({ ok: false, error: "revision not found" }, { status: 404 });
}
const result = await restoreRevision(id);
if (!result) {
return NextResponse.json({ ok: false, error: "restore failed" }, { status: 500 });
}
// Revalidate the doc route + home so the change is visible immediately.
revalidatePath(`/${result.slug}`);
revalidatePath("/");
return NextResponse.redirect(new URL(`/${result.slug}`, req.url));
}