buildmymcpserver/apps/web/app/admin/templates/page.tsx

203 lines
7.3 KiB
TypeScript
Raw Normal View History

feat(marketplace): template publish + fork + voting/ranking + admin moderation What this enables: - A user builds an MCP server. If others would benefit, they click 'Publish as template' on their server detail page. The spec + pre-rendered TypeScript snapshot is preserved. - Visitors browse /templates, filter by category, sort by trending/top/newest. Each template card shows fork count + active deployment count as natural manipulation-resistant popularity signal. - /templates/[slug] shows the full plan: tool list with input schemas, required-credential explanations (with 'how to get one' deep links), and a collapsible code preview so users can audit before forking. - Fork is one click → /servers/new?template=slug. The wizard skips Step 1 and pre-fills Step 2 with the template's parsed spec. Forker only fills in their own credentials. mcp_servers.template_id is recorded; template.fork_count is bumped atomically. Each fork gets its own isolated container with its own port, its own AES-256 secrets — the template author has zero visibility into the fork's traffic or data. - Admin /admin/templates moderation: verify quality templates (shows shield badge in marketplace), hide low-effort ones, takedown anything malicious. Takedowns cascade-pause every fork container — owners must re-deploy. Why template+fork instead of shared-container: - Shared containers would mean the publisher's quota + their secrets + their logs are exposed to forkers. Bad ergonomics, bad security, bad ownership. - Templates/forks decouple the spec (shared, vouched-for) from the runtime (isolated per user). Network-effect moat without the trust collapse. Why no 5-star voting in v1: - Manipulation-anfällig, empty lists without adoption. We use fork count + active deploys + verified badge. Trending algorithm: score = (activeDeploys * 3 + forks) / sqrt(ageDays + 1) Real signal, no brigading attack surface. Backend: - New schema: templates table (16 cols incl. tools_schema, generated_code, required_secrets, allowedDomains, status enum, verified, fork_count). - mcp_servers.template_id FK + idx for fork lookup. - @bmm/types: SpecEdit unchanged, CreateServerInput accepts optional templateId. - preview-cache.ts: new cachePrebuiltCode/loadPrebuiltCode for storing the template's full rendered server.ts alongside the spec. Generator worker detects this and skips the render step — uses the audited pre-built code verbatim. Banned-pattern re-scan at publish time. - routes/templates.ts: 5 public/auth routes + 2 admin routes. Banned-pattern re-scan before publish. Slug auto-uniqued. forkCount atomic-increment via SQL. UI: - /templates marketplace with trending/top/newest tabs, category filter, search. Cards show forks + live count + author + verified badge. - /templates/[slug] full detail with tools, credentials-with-hints, expandable code preview, fork CTA, ownership + stats sidebar, 'forking is safe' explainer. - /servers/new?template=slug — wizard auto-jumps to Step 2 with template spec pre-filled, fork banner at top with link back to template. - /servers/[id] new Publish tab with title, category, descriptions, per-secret hint fields (description + howToGetUrl per UPPER_SNAKE_CASE key). - /admin/templates moderation with verify/hide/takedown actions. - Marketing nav now includes /templates. Verified end-to-end: - Published Echo Demo Template from marco@test.local's live server - Marketplace lists it correctly with stats - Detail page renders with all sections - Fork CTA navigates to wizard with ?template= param - Wizard skips Step 1, shows fork banner, pre-fills spec - Build succeeds in ~10s (cached spec + prebuilt code path skips Claude AND render), container live on :4109 with proper OAuth 401 → token → 200 flow - DB: templates.fork_count=1, activeDeployments=1, mcp_servers.template_id populated on the fork - /admin/templates shows the new template with verify/hide/takedown controls
2026-05-19 23:22:35 +02:00
'use client';
import { useEffect, useState } from 'react';
import Link from 'next/link';
import { apiFetch } from '@/lib/api';
import { Button } from '@/components/ui/button';
import { ShieldCheck } from 'lucide-react';
interface AdminTemplate {
id: string;
slug: string;
title: string;
shortDescription: string;
category: string;
status: 'draft' | 'public' | 'hidden' | 'takedown';
verified: boolean;
takedownReason: string | null;
forkCount: number;
activeDeployments: number;
ownerEmail: string | null;
ownerOrgName: string | null;
createdAt: string;
}
const STATUS_FILTERS = ['', 'public', 'hidden', 'takedown', 'draft'];
export default function AdminTemplatesPage() {
const [rows, setRows] = useState<AdminTemplate[] | null>(null);
const [statusFilter, setStatusFilter] = useState('');
async function reload() {
const r = await apiFetch<{ templates: AdminTemplate[] }>('/v1/admin/templates');
setRows(r.templates);
}
useEffect(() => {
reload();
}, []);
async function toggleVerified(t: AdminTemplate) {
if (!confirm(`${t.verified ? 'Unverify' : 'Verify'} "${t.title}"?`)) return;
await apiFetch(`/v1/admin/templates/${t.id}`, {
method: 'PATCH',
body: JSON.stringify({ verified: !t.verified }),
});
reload();
}
async function takedown(t: AdminTemplate) {
if (t.status === 'takedown') {
if (!confirm(`Lift takedown on "${t.title}"? Forked servers stay paused — owners must re-deploy.`)) return;
await apiFetch(`/v1/admin/templates/${t.id}`, {
method: 'PATCH',
body: JSON.stringify({ status: 'public', takedownReason: null }),
});
} else {
const reason = prompt(
`Take down "${t.title}"? This pauses ALL ${t.activeDeployments} active fork containers. Reason:`,
'',
);
if (reason === null) return;
await apiFetch(`/v1/admin/templates/${t.id}`, {
method: 'PATCH',
body: JSON.stringify({ status: 'takedown', takedownReason: reason || 'Removed by admin' }),
});
}
reload();
}
async function toggleHidden(t: AdminTemplate) {
const next = t.status === 'public' ? 'hidden' : 'public';
await apiFetch(`/v1/admin/templates/${t.id}`, {
method: 'PATCH',
body: JSON.stringify({ status: next }),
});
reload();
}
const visible = rows?.filter((t) => (statusFilter ? t.status === statusFilter : true));
return (
<div className="px-8 py-8">
<header className="mb-6">
<h1 className="text-[22px] font-semibold tracking-tight">Templates moderation</h1>
<p className="mt-1 text-[13px] text-[--color-fg-muted]">
Verify quality templates, hide low-effort ones, take down anything malicious. Takedowns
cascade-pause every fork container.
</p>
</header>
<div className="mb-4 flex gap-2">
<select
value={statusFilter}
onChange={(e) => setStatusFilter(e.target.value)}
className="h-8 rounded-md border border-[--color-border] bg-[--color-bg-subtle] px-2 text-[13px] focus:border-[--color-accent] focus:outline-none"
>
{STATUS_FILTERS.map((s) => (
<option key={s} value={s}>
{s ? s : 'All statuses'}
</option>
))}
</select>
</div>
<div className="panel">
{rows === null && (
<p className="px-4 py-3 text-[12.5px] text-[--color-fg-muted]">Loading</p>
)}
{visible && visible.length === 0 && (
<p className="px-4 py-12 text-center text-[13px] text-[--color-fg-muted]">
No templates yet.
</p>
)}
{visible && visible.length > 0 && (
<table className="w-full text-[12.5px]">
<thead className="border-b border-[--color-border] text-[--color-fg-subtle]">
<tr>
<th className="px-4 py-2 text-left font-medium">Title</th>
<th className="px-4 py-2 text-left font-medium">Owner</th>
<th className="px-4 py-2 text-left font-medium">Category</th>
<th className="px-4 py-2 text-left font-medium">Status</th>
<th className="px-4 py-2 text-left font-medium">Stats</th>
<th className="px-4 py-2 text-right font-medium">Actions</th>
</tr>
</thead>
<tbody>
{visible.map((t) => (
<tr key={t.id} className="border-b border-[--color-border] last:border-0">
<td className="px-4 py-2.5">
<div className="flex items-center gap-1.5">
<Link
href={`/templates/${t.slug}`}
target="_blank"
className="font-medium hover:text-[--color-accent]"
>
{t.title}
</Link>
{t.verified && (
<ShieldCheck size={11} className="text-[--color-accent]" />
)}
</div>
<div className="mono text-[11px] text-[--color-fg-subtle]">{t.slug}</div>
</td>
<td className="px-4 py-2.5 mono text-[--color-fg-muted]">{t.ownerEmail ?? '—'}</td>
<td className="px-4 py-2.5">
<span className="mono rounded-full border border-[--color-border] bg-[--color-bg-subtle] px-2 py-0.5 text-[11px]">
{t.category}
</span>
</td>
<td className="px-4 py-2.5">
<StatusBadge status={t.status} reason={t.takedownReason} />
</td>
<td className="px-4 py-2.5 mono text-[--color-fg-muted]">
{t.forkCount} forks · {t.activeDeployments} live
</td>
<td className="px-4 py-2.5 text-right">
<div className="inline-flex gap-1">
<Button variant="ghost" size="sm" onClick={() => toggleVerified(t)}>
{t.verified ? 'unverify' : 'verify'}
</Button>
{t.status !== 'takedown' && (
<Button variant="ghost" size="sm" onClick={() => toggleHidden(t)}>
{t.status === 'public' ? 'hide' : 'show'}
</Button>
)}
<Button variant="danger" size="sm" onClick={() => takedown(t)}>
{t.status === 'takedown' ? 'restore' : 'takedown'}
</Button>
</div>
</td>
</tr>
))}
</tbody>
</table>
)}
</div>
</div>
);
}
function StatusBadge({
status,
reason,
}: {
status: AdminTemplate['status'];
reason: string | null;
}) {
const styles: Record<AdminTemplate['status'], string> = {
public: 'border-emerald-400/40 bg-emerald-400/10 text-emerald-300',
hidden: 'border-amber-400/40 bg-amber-400/10 text-amber-300',
takedown: 'border-red-400/40 bg-red-400/10 text-red-300',
draft: 'border-zinc-400/40 bg-zinc-400/10 text-zinc-300',
};
return (
<span
className={`mono inline-flex rounded-full border px-2 py-0.5 text-[11px] ${styles[status]}`}
title={reason ?? ''}
>
{status}
</span>
);
}