Files
podcastdistributiona/app/(admin)/admin/jobs/page.tsx
T
Leon SerfatyandClaude Opus 5 3e9ba07175 feat: Cloudflare Turnstile on auth, CSP fixes, admin/SEO/analytics additions
Turnstile bot protection (sign-in, sign-up, password-reset):
- Register Better Auth's captcha plugin with the cloudflare-turnstile
  provider; endpoints listed explicitly rather than relying on defaults.
  /reset-password is intentionally excluded — it is reached only via a
  single-use emailed token.
- Add an explicit-render Turnstile widget component. Tokens are single-use,
  so each form resets the challenge after a failed submit; submit stays
  disabled until a token is held.
- Read the site key server-side and pass it down as a prop, so rotating it
  does not require a rebuild.
- Fail fast in production when TURNSTILE_SECRET_KEY is missing, and when a
  secret is set without a site key (that combination would demand a token
  no form can produce, locking every user out).
- Pass a throwaway secret during `next build` in the Dockerfile, mirroring
  the existing BETTER_AUTH_SECRET treatment, so image builds don't need it.

CSP fixes in middleware (these blocked Turnstile entirely):
- Add frame-src for challenges.cloudflare.com. Without it the widget's
  iframe fell back to default-src 'self' and was blocked outright.
- Allow 'unsafe-eval' and websockets in DEVELOPMENT only. `next dev`
  compiles with eval(), so the strict policy threw EvalError and killed
  hydration — no client JS ran at all, which also meant form submit
  handlers never fired. Production policy is unchanged and still strict.

Also included (concurrent work in the tree):
- Admin organizations pages and lib/admin/orgs.
- Episode moderation migration, SEO metadata (sitemap, robots, JSON-LD,
  OG/Twitter images, manifest), Umami analytics, not-found page.

Local dev database: docker-compose.dev.yml provisions Postgres 18 on port
5443 (5432-5442 are in use by other local projects).

Note: `npx tsc --noEmit` currently fails in app/(app)/team/page.tsx — an
`invitations` prop the component does not accept. This predates the commit
and will fail `next build` until fixed.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-07 11:10:55 -04:00

120 lines
4.1 KiB
TypeScript

import type { Metadata } from "next";
import Link from "next/link";
import { Clock, Loader2, CheckCircle2, XCircle } from "lucide-react";
import { listJobs, JOBS_PAGE_SIZE, getJobStatusCounts } from "@/lib/admin/ops";
import { PageHeader } from "@/components/app/page-header";
import { StatCard } from "@/components/admin/ui/stat-card";
import { DataTable, TableToolbar, type Column } from "@/components/admin/ui/data-table";
import { FilterSelect, Pagination } from "@/components/admin/ui/table-controls";
import { JobRowActions } from "@/components/admin/job-row-actions";
import { Badge, type BadgeProps } from "@/components/ui/badge";
import { requireAdmin } from "@/lib/auth/guards";
export const metadata: Metadata = { title: "Admin · Jobs" };
type Row = Awaited<ReturnType<typeof listJobs>>["rows"][number];
const STATUS_VARIANT: Record<string, BadgeProps["variant"]> = {
queued: "secondary",
running: "warning",
completed: "success",
failed: "destructive",
};
function duration(start: Date | null, end: Date | null): string {
if (!start || !end) return "—";
return `${Math.max(0, Math.round((end.getTime() - start.getTime()) / 1000))}s`;
}
export default async function AdminJobsPage({
searchParams,
}: {
searchParams: Promise<Record<string, string | undefined>>;
}) {
// Defence in depth: the (admin) layout also guards, but a layout is not an
// authorization boundary — pages render concurrently with it, and a route moved
// out of the group would silently lose its only check.
await requireAdmin();
const sp = await searchParams;
const page = Math.max(1, Number(sp.page ?? "1"));
const [{ rows, total }, counts] = await Promise.all([
listJobs({ status: sp.status, page }),
getJobStatusCounts(),
]);
const columns: Column<Row>[] = [
{
key: "episode",
header: "Episode",
cell: (j) => (
<Link href={`/episodes/${j.episode.id}`} className="truncate font-medium hover:text-brand">
{j.episode.title}
</Link>
),
},
{ key: "type", header: "Type", cell: (j) => <span className="capitalize">{j.type}</span> },
{
key: "status",
header: "Status",
cell: (j) => <Badge variant={STATUS_VARIANT[j.status] ?? "secondary"}>{j.status}</Badge>,
},
{ key: "attempts", header: "Attempts", align: "right", cell: (j) => j.attempts },
{
key: "duration",
header: "Duration",
align: "right",
cell: (j) => <span className="text-muted-foreground">{duration(j.startedAt, j.finishedAt)}</span>,
},
{
key: "error",
header: "Error",
cell: (j) =>
j.error ? (
<span className="truncate font-mono text-xs text-destructive" title={j.error}>
{j.error.slice(0, 40)}
</span>
) : (
"—"
),
},
{
key: "actions",
header: "",
align: "right",
cell: (j) => <JobRowActions job={{ id: j.id, status: j.status }} />,
},
];
return (
<>
<PageHeader title="Generation jobs" description="The episode pipeline, job by job." />
<div className="mb-6 grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
<StatCard label="Queued" value={String(counts.queued)} icon={Clock} />
<StatCard label="Running" value={String(counts.running)} icon={Loader2} />
<StatCard label="Completed" value={String(counts.completed)} icon={CheckCircle2} />
<StatCard label="Failed" value={String(counts.failed)} icon={XCircle} />
</div>
<TableToolbar>
<div />
<FilterSelect
param="status"
placeholder="Status"
allLabel="All status"
options={[
{ value: "queued", label: "Queued" },
{ value: "running", label: "Running" },
{ value: "completed", label: "Completed" },
{ value: "failed", label: "Failed" },
]}
/>
</TableToolbar>
<DataTable columns={columns} rows={rows} getRowKey={(j) => j.id} empty="No jobs yet." />
<div className="mt-4">
<Pagination page={page} pageSize={JOBS_PAGE_SIZE} total={total} />
</div>
</>
);
}