Files
Leon SerfatyandClaude Opus 5 1d02598786 chore: sync in-progress work across marketing, admin, API and tests
Snapshot of uncommitted work that had accumulated in the tree alongside
the Turnstile changes:

- marketing pages, SEO helpers (lib/seo.ts, lib/marketing/) and
  structured data
- admin billing actions and a per-user portfolio view, plus an admin
  error boundary
- rate limiting (lib/rate-limit.ts) applied across the /api/v1 surface
- CSP and proxy adjustments, accounting/webhook lib updates
- Playwright config and an e2e/unit test suite
- next bumped to ^16.3.4 with the lockfile regenerated
- generated AGENTS.md / CLAUDE.md

Authored by other sessions working in this tree; committed here so the
Turnstile work could be pushed without leaving the tree dirty.
Typecheck passes.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-05 16:27:16 -04:00

120 lines
4.3 KiB
TypeScript

import { NextResponse } from "next/server"
import { and, eq } from "drizzle-orm"
import { db } from "@/lib/db"
import { webhook_endpoints } from "@/lib/db/schema"
import { resolveApiRequest } from "@/lib/api-auth"
import { enforceRateLimit } from "@/lib/rate-limit"
import { webhookEndpointSchema } from "@/lib/validations"
import { isWebhookEvent } from "@/lib/webhooks/events"
import { assertSafeWebhookUrl, WebhookUrlError } from "@/lib/webhooks/ssrf"
// Public REST API (v1) — read/update/delete a single webhook subscription.
// DELETE is what Zapier's REST-hook unsubscribe calls. Owner-scoped by id.
const unauthorized = () =>
NextResponse.json({ error: { code: 401, message: "Unauthorized" } }, { status: 401 })
const forbidden = () =>
NextResponse.json({ error: { code: 403, message: "Forbidden" } }, { status: 403 })
const notFound = () =>
NextResponse.json({ error: { code: 404, message: "Not found" } }, { status: 404 })
// Fields returned to API consumers (never the signing secret).
const RETURN_COLUMNS = {
id: webhook_endpoints.id,
url: webhook_endpoints.url,
description: webhook_endpoints.description,
events: webhook_endpoints.events,
status: webhook_endpoints.status,
source: webhook_endpoints.source,
created_at: webhook_endpoints.created_at,
}
export async function GET(request: Request, { params }: { params: Promise<{ id: string }> }) {
const ctx = await resolveApiRequest(request)
if (!ctx) return unauthorized()
// Public API budget: 120 requests/minute per key owner.
const limited = enforceRateLimit(`v1:${ctx.userId}`, 120, 60)
if (limited) return limited
const { id } = await params
const data = await db.query.webhook_endpoints.findFirst({
where: and(eq(webhook_endpoints.id, id), eq(webhook_endpoints.user_id, ctx.ownerId)),
columns: { secret: false },
})
if (!data) return notFound()
return NextResponse.json({ data })
}
export async function PATCH(request: Request, { params }: { params: Promise<{ id: string }> }) {
const ctx = await resolveApiRequest(request)
if (!ctx) return unauthorized()
// Public API budget: 120 requests/minute per key owner.
const limited = enforceRateLimit(`v1:${ctx.userId}`, 120, 60)
if (limited) return limited
if (!ctx.canWrite) return forbidden()
const { id } = await params
const body = (await request.json().catch(() => null)) as Record<string, unknown> | null
const parsed = webhookEndpointSchema.partial().safeParse(body ?? {})
if (!parsed.success) {
return NextResponse.json(
{ error: { code: 400, message: parsed.error.flatten() } },
{ status: 400 }
)
}
const patch: Partial<typeof webhook_endpoints.$inferInsert> = {}
if (parsed.data.url !== undefined) {
try {
await assertSafeWebhookUrl(parsed.data.url)
} catch (e) {
return NextResponse.json(
{
error: {
code: 400,
message: e instanceof WebhookUrlError ? e.message : "Invalid webhook URL",
},
},
{ status: 400 }
)
}
patch.url = parsed.data.url
}
if (parsed.data.events !== undefined) {
patch.events = Array.from(new Set(parsed.data.events.filter(isWebhookEvent)))
}
if (parsed.data.description !== undefined) patch.description = parsed.data.description || null
if (body?.status === "active" || body?.status === "disabled") patch.status = body.status
const [data] = await db
.update(webhook_endpoints)
.set(patch)
.where(and(eq(webhook_endpoints.id, id), eq(webhook_endpoints.user_id, ctx.ownerId)))
.returning(RETURN_COLUMNS)
if (!data) return notFound()
return NextResponse.json({ data })
}
export async function DELETE(request: Request, { params }: { params: Promise<{ id: string }> }) {
const ctx = await resolveApiRequest(request)
if (!ctx) return unauthorized()
// Public API budget: 120 requests/minute per key owner.
const limited = enforceRateLimit(`v1:${ctx.userId}`, 120, 60)
if (limited) return limited
if (!ctx.canWrite) return forbidden()
const { id } = await params
const [deleted] = await db
.delete(webhook_endpoints)
.where(and(eq(webhook_endpoints.id, id), eq(webhook_endpoints.user_id, ctx.ownerId)))
.returning({ id: webhook_endpoints.id })
if (!deleted) return notFound()
return NextResponse.json({ data: { id: deleted.id, deleted: true } })
}