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>
This commit is contained in:
Leon Serfaty
2026-09-05 16:27:16 -04:00
co-authored by Claude Opus 5
parent 8f90347659
commit 1d02598786
71 changed files with 3641 additions and 819 deletions
+57
View File
@@ -0,0 +1,57 @@
"use client"
import { useEffect } from "react"
import Link from "next/link"
import { AlertTriangle, RefreshCw, ArrowLeft } from "lucide-react"
/**
* Error boundary for the admin surface. Without this, a failure in any admin
* page (a Stripe call, an aggregate query) fell through to app/global-error.tsx,
* which replaces the whole document and drops the admin chrome — leaving no way
* back except editing the URL.
*
* Admin pages read across every account, so the message is shown verbatim: the
* audience is staff, and the detail is what makes the failure diagnosable.
*/
export default function AdminError({
error,
reset,
}: {
error: Error & { digest?: string }
reset: () => void
}) {
useEffect(() => {
console.error("[admin]", error)
}, [error])
return (
<div className="flex min-h-[400px] flex-col items-center justify-center rounded-xl border border-red-500/10 bg-red-500/5 text-center">
<div className="mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-red-500/10">
<AlertTriangle className="h-6 w-6 text-red-400" />
</div>
<h2 className="text-base font-semibold text-white">Admin page failed to load</h2>
<p className="mt-2 max-w-md text-sm text-white/50">
{error.message || "An unexpected error occurred."}
</p>
{error.digest && (
<p className="mt-1 font-mono text-xs text-white/25">digest: {error.digest}</p>
)}
<div className="mt-6 flex items-center gap-3">
<button
onClick={reset}
className="flex items-center gap-2 rounded-lg border border-white/10 px-4 py-2 text-sm text-white/60 transition hover:border-white/20 hover:text-white"
>
<RefreshCw className="h-4 w-4" />
Try again
</button>
<Link
href="/admin"
className="flex items-center gap-2 rounded-lg border border-white/10 px-4 py-2 text-sm text-white/60 transition hover:border-white/20 hover:text-white"
>
<ArrowLeft className="h-4 w-4" />
Back to overview
</Link>
</div>
</div>
)
}
+27
View File
@@ -1,3 +1,4 @@
import Link from "next/link"
import { notFound } from "next/navigation"
import {
Building2,
@@ -11,12 +12,15 @@ import {
ShieldAlert,
Ban,
Activity,
Table2,
} from "lucide-react"
import { getUserDetail } from "@/lib/db/admin-queries"
import { requireAdmin } from "@/lib/session"
import { BackButton } from "@/components/ui/back-button"
import { CopyButton } from "@/components/shared/copy-button"
import { UserActions } from "@/components/admin/user-actions"
import { BillingActions } from "@/components/admin/billing-actions"
import { getSubscriptionSummary, listUserCharges } from "@/lib/admin/billing"
import { formatDate, initials, cn } from "@/lib/utils"
export const dynamic = "force-dynamic"
@@ -49,6 +53,15 @@ export default async function AdminUserDetailPage({
if (!detail) notFound()
// Live billing state, read straight from Stripe rather than the mirrored
// columns — the admin needs the truth, not our cached copy of it. Both helpers
// return empty/null rather than throwing when Stripe is unreachable or unset,
// so the page still renders without billing.
const [subscription, charges] = await Promise.all([
getSubscriptionSummary(id),
listUserCharges(id, 10),
])
const { profile, account, counts, recentActivity } = detail
const isSelf = me.id === profile.id
const planKey = profile.plan ?? "starter"
@@ -107,6 +120,15 @@ export default async function AdminUserDetailPage({
</div>
{/* Counts grid */}
<div className="flex items-center justify-between">
<h2 className="text-sm font-semibold text-white">Portfolio</h2>
<Link
href={`/admin/users/${profile.id}/portfolio`}
className="inline-flex items-center gap-1.5 rounded-lg border border-white/10 px-3 py-1.5 text-xs font-medium text-white/60 transition hover:border-white/20 hover:text-white"
>
<Table2 className="h-3.5 w-3.5" /> View records
</Link>
</div>
<div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
{COUNT_META.map(({ key, label, icon: Icon }) => (
<div
@@ -197,6 +219,9 @@ export default async function AdminUserDetailPage({
</ul>
)}
</div>
{/* Payments + refunds */}
<BillingActions userId={profile.id} charges={charges} />
</div>
{/* Right: actions */}
@@ -207,6 +232,8 @@ export default async function AdminUserDetailPage({
currentPlan={planKey}
banned={!!account?.banned}
isSelf={isSelf}
isAdminRole={account?.role === "admin"}
subscription={subscription}
/>
</div>
</div>
@@ -0,0 +1,293 @@
import { notFound } from "next/navigation"
import { Building2, Home, Users as UsersIcon, FileText, CreditCard, Wrench } from "lucide-react"
import { getUserDetail, getUserPortfolio } from "@/lib/db/admin-queries"
import { requireAdmin } from "@/lib/session"
import { BackButton } from "@/components/ui/back-button"
import { formatCurrency, formatDate, cn } from "@/lib/utils"
export const dynamic = "force-dynamic"
/**
* Read-only support view of one user's actual records.
*
* This exists so an admin can answer "what does this customer actually have?"
* WITHOUT impersonating them — impersonation mutates the user's session and
* lands in their own activity trail, which is a heavy tool for a support lookup.
* Nothing on this page mutates anything.
*/
const STATUS_TONE: Record<string, string> = {
active: "bg-emerald-500/10 text-emerald-300",
occupied: "bg-emerald-500/10 text-emerald-300",
paid: "bg-emerald-500/10 text-emerald-300",
vacant: "bg-white/[0.06] text-white/50",
pending: "bg-amber-500/10 text-amber-300",
open: "bg-amber-500/10 text-amber-300",
in_progress: "bg-sky-500/10 text-sky-300",
overdue: "bg-red-500/10 text-red-300",
expired: "bg-red-500/10 text-red-300",
}
function Pill({ value }: { value: string | null | undefined }) {
if (!value) return <span className="text-white/25"></span>
return (
<span
className={cn(
"rounded-md px-1.5 py-0.5 text-xs font-medium",
STATUS_TONE[value] ?? "bg-white/[0.06] text-white/50"
)}
>
{value.replace(/_/g, " ")}
</span>
)
}
function Section({
title,
icon: Icon,
count,
shown,
children,
}: {
title: string
icon: typeof Building2
count: number
shown: number
children: React.ReactNode
}) {
return (
<div className="rounded-2xl border border-white/[0.06] bg-[#16161f] p-5">
<div className="mb-4 flex items-center justify-between">
<div className="flex items-center gap-2 text-white">
<Icon className="h-4 w-4 text-white/40" />
<h2 className="text-sm font-semibold">{title}</h2>
<span className="text-xs text-white/30">({count})</span>
</div>
{shown < count && (
<span className="text-xs text-white/30">showing first {shown}</span>
)}
</div>
{count === 0 ? (
<p className="text-xs text-white/30">None.</p>
) : (
<div className="overflow-x-auto">{children}</div>
)}
</div>
)
}
const TH = "pb-2 text-left text-xs font-medium text-white/40"
const TD = "py-2.5 text-sm text-white/70"
export default async function AdminUserPortfolioPage({
params,
}: {
params: Promise<{ id: string }>
}) {
const { id } = await params
await requireAdmin()
const [detail, portfolio] = await Promise.all([getUserDetail(id), getUserPortfolio(id)])
if (!detail) notFound()
const { profile, counts } = detail
const unitsByProperty = new Map<string, number>()
for (const u of portfolio.units) {
unitsByProperty.set(u.property_id ?? "", (unitsByProperty.get(u.property_id ?? "") ?? 0) + 1)
}
return (
<div className="space-y-6">
<BackButton href={`/admin/users/${id}`} label="Back to user" />
<div>
<h1 className="text-xl font-bold text-white">Portfolio</h1>
<p className="mt-0.5 text-sm text-white/40">
Read-only view of {profile.email}&apos;s records. Nothing here can be edited.
</p>
</div>
<Section
title="Properties"
icon={Building2}
count={counts.propertyCount}
shown={portfolio.properties.length}
>
<table className="w-full min-w-[560px]">
<thead>
<tr className="border-b border-white/[0.06]">
<th className={TH}>Name</th>
<th className={TH}>Address</th>
<th className={TH}>Units</th>
<th className={TH}>Added</th>
</tr>
</thead>
<tbody>
{portfolio.properties.map((p) => (
<tr key={p.id} className="border-b border-white/[0.04] last:border-0">
<td className={cn(TD, "text-white")}>{p.name}</td>
<td className={TD}>
{[p.address_line1, p.city, p.state].filter(Boolean).join(", ") || "—"}
</td>
<td className={TD}>{unitsByProperty.get(p.id) ?? p.total_units ?? 0}</td>
<td className={TD}>{p.created_at ? formatDate(p.created_at) : "—"}</td>
</tr>
))}
</tbody>
</table>
</Section>
<Section title="Units" icon={Home} count={counts.unitCount} shown={portfolio.units.length}>
<table className="w-full min-w-[420px]">
<thead>
<tr className="border-b border-white/[0.06]">
<th className={TH}>Unit</th>
<th className={TH}>Rent</th>
<th className={TH}>Status</th>
</tr>
</thead>
<tbody>
{portfolio.units.map((u) => (
<tr key={u.id} className="border-b border-white/[0.04] last:border-0">
<td className={cn(TD, "text-white")}>{u.unit_number}</td>
<td className={TD}>
{u.rent_amount != null ? formatCurrency(Number(u.rent_amount)) : "—"}
</td>
<td className={TD}>
<Pill value={u.status} />
</td>
</tr>
))}
</tbody>
</table>
</Section>
<Section
title="Tenants"
icon={UsersIcon}
count={counts.tenantCount}
shown={portfolio.tenants.length}
>
<table className="w-full min-w-[600px]">
<thead>
<tr className="border-b border-white/[0.06]">
<th className={TH}>Name</th>
<th className={TH}>Email</th>
<th className={TH}>Phone</th>
<th className={TH}>Status</th>
<th className={TH}>Moved in</th>
</tr>
</thead>
<tbody>
{portfolio.tenants.map((t) => (
<tr key={t.id} className="border-b border-white/[0.04] last:border-0">
<td className={cn(TD, "text-white")}>
{t.first_name} {t.last_name}
</td>
<td className={TD}>{t.email ?? "—"}</td>
<td className={TD}>{t.phone ?? "—"}</td>
<td className={TD}>
<Pill value={t.status} />
</td>
<td className={TD}>{t.move_in_date ? formatDate(t.move_in_date) : "—"}</td>
</tr>
))}
</tbody>
</table>
</Section>
<Section
title="Leases"
icon={FileText}
count={counts.leaseCount}
shown={portfolio.leases.length}
>
<table className="w-full min-w-[480px]">
<thead>
<tr className="border-b border-white/[0.06]">
<th className={TH}>Term</th>
<th className={TH}>Rent</th>
<th className={TH}>Status</th>
</tr>
</thead>
<tbody>
{portfolio.leases.map((l) => (
<tr key={l.id} className="border-b border-white/[0.04] last:border-0">
<td className={TD}>
{l.lease_start ? formatDate(l.lease_start) : "—"} {" "}
{l.lease_end ? formatDate(l.lease_end) : "—"}
</td>
<td className={TD}>
{l.rent_amount != null ? formatCurrency(Number(l.rent_amount)) : "—"}
</td>
<td className={TD}>
<Pill value={l.status} />
</td>
</tr>
))}
</tbody>
</table>
</Section>
<Section
title="Recent rent payments"
icon={CreditCard}
count={counts.paymentCount}
shown={portfolio.payments.length}
>
<table className="w-full min-w-[480px]">
<thead>
<tr className="border-b border-white/[0.06]">
<th className={TH}>Due</th>
<th className={TH}>Amount</th>
<th className={TH}>Paid</th>
<th className={TH}>Status</th>
</tr>
</thead>
<tbody>
{portfolio.payments.map((p) => (
<tr key={p.id} className="border-b border-white/[0.04] last:border-0">
<td className={TD}>{p.due_date ? formatDate(p.due_date) : "—"}</td>
<td className={cn(TD, "text-white")}>{formatCurrency(Number(p.amount))}</td>
<td className={TD}>{p.paid_date ? formatDate(p.paid_date) : "—"}</td>
<td className={TD}>
<Pill value={p.status} />
</td>
</tr>
))}
</tbody>
</table>
</Section>
<Section
title="Recent maintenance"
icon={Wrench}
count={counts.maintenanceCount}
shown={portfolio.maintenance.length}
>
<table className="w-full min-w-[480px]">
<thead>
<tr className="border-b border-white/[0.06]">
<th className={TH}>Title</th>
<th className={TH}>Priority</th>
<th className={TH}>Status</th>
<th className={TH}>Opened</th>
</tr>
</thead>
<tbody>
{portfolio.maintenance.map((m) => (
<tr key={m.id} className="border-b border-white/[0.04] last:border-0">
<td className={cn(TD, "text-white")}>{m.title}</td>
<td className={TD}>{m.priority ?? "—"}</td>
<td className={TD}>
<Pill value={m.status} />
</td>
<td className={TD}>{m.created_at ? formatDate(m.created_at) : "—"}</td>
</tr>
))}
</tbody>
</table>
</Section>
</div>
)
}
+12
View File
@@ -3,6 +3,18 @@ import { Logo } from "@/components/shared/logo"
import { TurnstileWidget } from "@/components/shared/turnstile-widget"
import { signUp, signInWithGoogle } from "@/app/actions/auth"
import { isGoogleConfigured } from "@/lib/auth"
import { pageMetadata } from "@/lib/seo"
// /signup is listed in the sitemap as a conversion landing page, so it needs
// its own title, description and canonical rather than inheriting the "Sign in"
// title from app/(auth)/layout.tsx.
export const metadata = pageMetadata({
title: "Create your free Property Management Network account",
absoluteTitle: true,
description:
"Create a free landlord account — track rent, maintenance, leases and expenses for your first property. No credit card required.",
path: "/signup",
})
export default async function SignupPage({
searchParams,
+4 -3
View File
@@ -1,11 +1,12 @@
import { LegalPage, Section, LegalContact } from "@/components/marketing/legal"
import { LEGAL } from "@/lib/legal"
import { pageMetadata } from "@/lib/seo"
export const metadata = {
export const metadata = pageMetadata({
title: "Acceptable Use Policy",
description: `The rules that govern acceptable use of the ${LEGAL.service} platform and the activities that are prohibited.`,
alternates: { canonical: "/acceptable-use" },
}
path: "/acceptable-use",
})
export default function Page() {
return (
+6 -4
View File
@@ -1,12 +1,14 @@
import Link from "next/link"
import { Code2, Lock, Zap, BookOpen, Webhook } from "lucide-react"
import { WEBHOOK_EVENTS } from "@/lib/webhooks/events"
import { pageMetadata } from "@/lib/seo"
export const metadata = {
export const metadata = pageMetadata({
title: "API Docs",
description: "Property Management Network REST API documentation for developers.",
alternates: { canonical: "/api-docs" },
}
description:
"REST API reference for Property Management Network — endpoints for properties, tenants, rent payments, maintenance and webhooks, with API key auth.",
path: "/api-docs",
})
// The real, deployed origin. Falls back to a placeholder only when the env var
// isn't set (e.g. local docs previews).
+5 -5
View File
@@ -1,12 +1,12 @@
import { LegalPage, Section, LegalContact } from "@/components/marketing/legal"
import { LEGAL } from "@/lib/legal"
import { pageMetadata } from "@/lib/seo"
export const metadata = {
export const metadata = pageMetadata({
title: "Cookie Policy",
description:
"How we use cookies and similar technologies, what we deliberately avoid, and how to manage them in your browser.",
alternates: { canonical: "/cookie-policy" },
}
description: "How we use cookies and similar technologies, what we deliberately avoid, and how to manage them in your browser.",
path: "/cookie-policy",
})
const COOKIE_ROWS: { name: string; type: string; purpose: string; expires: string }[] = [
{
+5 -5
View File
@@ -1,12 +1,12 @@
import { LegalPage, Section, Callout, LegalContact } from "@/components/marketing/legal"
import { LEGAL } from "@/lib/legal"
import { pageMetadata } from "@/lib/seo"
export const metadata = {
export const metadata = pageMetadata({
title: "Disclaimer",
description:
"Important limitations on the information and outputs provided by the Service, including AI-generated content and financial reports.",
alternates: { canonical: "/disclaimer" },
}
description: "Important limitations on the information and outputs provided by the Service, including AI-generated content and financial reports.",
path: "/disclaimer",
})
export default function Page() {
return (
+4 -3
View File
@@ -1,12 +1,13 @@
import Link from "next/link"
import { LegalPage, Section, Callout, LegalContact } from "@/components/marketing/legal"
import { LEGAL } from "@/lib/legal"
import { pageMetadata } from "@/lib/seo"
export const metadata = {
export const metadata = pageMetadata({
title: "Data Processing Addendum",
description: `The Data Processing Addendum governing how ${LEGAL.entity} processes personal data on behalf of Customers using ${LEGAL.service}.`,
alternates: { canonical: "/dpa" },
}
path: "/dpa",
})
export default function DpaPage() {
return (
+4 -3
View File
@@ -1,12 +1,13 @@
import Link from "next/link"
import { LegalPage, Section, LegalContact } from "@/components/marketing/legal"
import { LEGAL } from "@/lib/legal"
import { pageMetadata } from "@/lib/seo"
export const metadata = {
export const metadata = pageMetadata({
title: "GDPR & Data Rights",
description: `How ${LEGAL.entity} complies with the GDPR and UK GDPR, and the data rights available to you as a data subject.`,
alternates: { canonical: "/gdpr" },
}
path: "/gdpr",
})
export default function GdprPage() {
return (
+2 -2
View File
@@ -1,6 +1,6 @@
import { Navbar } from "@/components/marketing/navbar"
import { Footer } from "@/components/marketing/footer"
import { StructuredData } from "@/components/marketing/structured-data"
import { SiteStructuredData } from "@/components/marketing/structured-data"
import { getSession, isAdminUser } from "@/lib/session"
import { getMaintenanceMode } from "@/lib/settings"
import { MaintenanceScreen } from "@/components/shared/maintenance-screen"
@@ -17,7 +17,7 @@ export default async function MarketingLayout({ children }: { children: React.Re
return (
<div className="min-h-screen bg-[#09090b] text-white">
<StructuredData />
<SiteStructuredData />
<Navbar />
{children}
<Footer />
+11 -11
View File
@@ -7,23 +7,23 @@ import { Testimonials } from "@/components/marketing/testimonials"
import { PricingSection } from "@/components/marketing/pricing-section"
import { FAQ } from "@/components/marketing/faq"
import { CtaBanner } from "@/components/marketing/cta-banner"
import { HomeStructuredData } from "@/components/marketing/structured-data"
import { annualEnabled } from "@/lib/stripe/plans"
import { pageMetadata } from "@/lib/seo"
export const metadata = {
title: { absolute: "Property Management Software for Independent Landlords" },
description: "Track rent, manage maintenance, monitor leases, and keep expenses organised — all in one dashboard built for independent landlords. Free to start.",
alternates: { canonical: "/" },
openGraph: {
title: "Property management without the chaos",
description: "Track rent, manage maintenance, monitor leases, and keep expenses organised — all in one dashboard built for independent landlords. Free to start.",
url: "/",
type: "website",
},
}
export const metadata = pageMetadata({
title: "Property Management Software for Independent Landlords",
absoluteTitle: true,
description:
"Track rent, manage maintenance, monitor leases, and keep expenses organised — all in one dashboard built for independent landlords. Free to start.",
path: "/",
socialTitle: "Property management without the chaos",
})
export default function LandingPage() {
return (
<>
<HomeStructuredData />
<Hero />
<Marquee />
<Problem />
+5 -5
View File
@@ -1,12 +1,12 @@
import { LegalPage, Section, Callout, LegalContact } from "@/components/marketing/legal"
import { LEGAL, SUBPROCESSORS } from "@/lib/legal"
import { pageMetadata } from "@/lib/seo"
export const metadata = {
export const metadata = pageMetadata({
title: "Privacy Policy",
description:
"How we collect, use, share, and protect personal data, and the privacy rights available to you under the GDPR and California law.",
alternates: { canonical: "/privacy" },
}
description: "How we collect, use, share, and protect personal data, and the privacy rights available to you under the GDPR and California law.",
path: "/privacy",
})
export default function Page() {
return (
+5 -4
View File
@@ -1,11 +1,12 @@
import { LegalPage, Section, Callout, LegalContact } from "@/components/marketing/legal"
import { LEGAL } from "@/lib/legal"
import { pageMetadata } from "@/lib/seo"
export const metadata = {
title: "Refund & Cancellation Policy",
export const metadata = pageMetadata({
title: "Refund & Cancellation",
description: `How subscriptions, cancellations, and refunds work for the ${LEGAL.service} platform.`,
alternates: { canonical: "/refund-policy" },
}
path: "/refund-policy",
})
export default function Page() {
return (
+4 -3
View File
@@ -1,12 +1,13 @@
import Link from "next/link"
import { LegalPage, Section, LegalContact } from "@/components/marketing/legal"
import { LEGAL, SUBPROCESSORS } from "@/lib/legal"
import { pageMetadata } from "@/lib/seo"
export const metadata = {
export const metadata = pageMetadata({
title: "Sub-processors",
description: `The third-party sub-processors that ${LEGAL.entity} engages to process personal data on behalf of Customers of ${LEGAL.service}.`,
alternates: { canonical: "/subprocessors" },
}
path: "/subprocessors",
})
export default function SubprocessorsPage() {
return (
+6 -4
View File
@@ -1,11 +1,13 @@
import Link from "next/link"
import { Building2, CheckCircle2, Smartphone, Bell, FileText, ArrowRight } from "lucide-react"
import { pageMetadata } from "@/lib/seo"
export const metadata = {
export const metadata = pageMetadata({
title: "Tenant Portal",
description: "Give your tenants a dedicated portal to pay rent, submit maintenance requests, and view lease details.",
alternates: { canonical: "/tenant-portal-info" },
}
description:
"Give your tenants a dedicated portal to pay rent, submit maintenance requests, and view lease details.",
path: "/tenant-portal-info",
})
const FEATURES = [
{ icon: CheckCircle2, color: "text-emerald-400", bg: "bg-emerald-500/10 border-emerald-500/20", title: "Online Rent Payment", desc: "Tenants pay rent securely via Stripe — card or bank transfer. Auto-receipts sent by email." },
+4 -3
View File
@@ -1,11 +1,12 @@
import { LegalPage, Section, LegalContact } from "@/components/marketing/legal"
import { LEGAL } from "@/lib/legal"
import { pageMetadata } from "@/lib/seo"
export const metadata = {
export const metadata = pageMetadata({
title: "Terms of Service",
description: `The terms and conditions that govern your access to and use of the ${LEGAL.service} platform.`,
alternates: { canonical: "/terms" },
}
path: "/terms",
})
export default function Page() {
return (
+139 -4
View File
@@ -13,6 +13,13 @@ import { auth } from "@/lib/auth"
import { db } from "@/lib/db"
import { profiles, user as userTable } from "@/lib/db/schema"
import { executeAccountDeletion } from "@/lib/gdpr/delete"
import {
changePlanInStripe,
cancelSubscription,
resumeSubscription,
refundCharge,
} from "@/lib/admin/billing"
import type { Plan } from "@/types"
// ── gate ────────────────────────────────────────────────────────────────────
// Every server action re-verifies the caller is an admin. NEVER skip — these
@@ -26,24 +33,152 @@ async function guard() {
const planSchema = z.enum(["starter", "pro", "landlord", "lifetime"])
// ── change plan ─────────────────────────────────────────────────────────────
export async function changeUserPlan(userId: string, plan: string) {
// TWO DISTINCT OPERATIONS, deliberately not merged:
//
// "comp" — grant the entitlement in our database only. Stripe is untouched,
// so the user is billed exactly as before. This is the right choice
// for a free upgrade, a support gesture, or a user with no
// subscription at all.
// "stripe" — actually move their Stripe subscription (prorated), then mirror
// it locally. This CHARGES OR CREDITS REAL MONEY.
//
// Before this split, the only behaviour was "comp" while the UI called it
// "change plan" — so an admin granting Pro left the customer on their old
// Stripe subscription, silently desyncing entitlement from billing.
export async function changeUserPlan(
userId: string,
plan: string,
mode: "comp" | "stripe" = "comp",
interval: "month" | "year" = "month"
) {
const a = await guard()
const nextPlan = planSchema.parse(plan)
const existing = await db.query.profiles.findFirst({ where: eq(profiles.id, userId) })
const oldPlan = existing?.plan ?? null
if (mode === "stripe") {
const result = await changePlanInStripe(userId, nextPlan as Plan, interval)
if (!result.ok) return { ok: false as const, error: result.error }
await logAdminAction({
adminId: a.user.id,
action: "plan_change_stripe",
targetUserId: userId,
metadata: { from: oldPlan, to: nextPlan, interval, detail: result.detail },
})
revalidatePath(`/admin/users/${userId}`)
return { ok: true as const, detail: result.detail }
}
// Comp: entitlement only. Recorded as such so the audit trail distinguishes a
// deliberate free grant from a paid upgrade.
await db.update(profiles).set({ plan: nextPlan }).where(eq(profiles.id, userId))
await logAdminAction({
adminId: a.user.id,
action: "plan_change",
targetUserId: userId,
metadata: { from: oldPlan, to: nextPlan },
metadata: { from: oldPlan, to: nextPlan, mode: "comp", billingUnchanged: true },
})
revalidatePath(`/admin/users/${userId}`)
return { ok: true }
return {
ok: true as const,
detail: `Plan set to ${nextPlan} as a comp. Stripe billing was NOT changed.`,
}
}
// ── subscription lifecycle ──────────────────────────────────────────────────
export async function cancelUserSubscription(userId: string, immediate = false) {
const a = await guard()
const result = await cancelSubscription(userId, immediate)
if (!result.ok) return { ok: false as const, error: result.error }
await logAdminAction({
adminId: a.user.id,
action: "cancel_subscription",
targetUserId: userId,
metadata: { immediate, detail: result.detail },
})
revalidatePath(`/admin/users/${userId}`)
return { ok: true as const, detail: result.detail }
}
export async function resumeUserSubscription(userId: string) {
const a = await guard()
const result = await resumeSubscription(userId)
if (!result.ok) return { ok: false as const, error: result.error }
await logAdminAction({
adminId: a.user.id,
action: "resume_subscription",
targetUserId: userId,
metadata: { detail: result.detail },
})
revalidatePath(`/admin/users/${userId}`)
return { ok: true as const, detail: result.detail }
}
// ── refunds ─────────────────────────────────────────────────────────────────
// `amountCents` omitted refunds everything still outstanding on the charge. The
// charge is verified to belong to this user inside refundCharge().
export async function refundUserCharge(
userId: string,
chargeId: string,
amountCents?: number,
reason?: "duplicate" | "fraudulent" | "requested_by_customer"
) {
const a = await guard()
const result = await refundCharge(userId, chargeId, amountCents, reason)
if (!result.ok) return { ok: false as const, error: result.error }
await logAdminAction({
adminId: a.user.id,
action: "refund",
targetUserId: userId,
metadata: {
chargeId,
refundId: result.data.refundId,
amountCents: result.data.amount,
reason: reason ?? null,
},
})
revalidatePath(`/admin/users/${userId}`)
return { ok: true as const, detail: result.detail }
}
// ── admin role management ───────────────────────────────────────────────────
// Promotes/demotes via the Better Auth admin plugin, which writes `user.role`.
// This replaces the previous situation where the ONLY way to create an admin was
// editing ADMIN_USER_IDS in env and redeploying.
//
// Self-demotion is blocked: an admin removing their own last access would need a
// redeploy to undo, and ADMIN_USER_IDS remains the break-glass path.
export async function setUserRole(userId: string, role: "admin" | "user") {
const a = await guard()
if (userId === a.user.id) {
throw new Error("You cannot change your own role. Ask another admin.")
}
await auth.api.setRole({
body: { userId, role },
headers: await headers(),
})
await logAdminAction({
adminId: a.user.id,
action: "set_role",
targetUserId: userId,
metadata: { role },
})
revalidatePath(`/admin/users/${userId}`)
return { ok: true as const, detail: role === "admin" ? "User promoted to admin." : "Admin access revoked." }
}
// ── ban ─────────────────────────────────────────────────────────────────────
@@ -132,7 +267,7 @@ export async function markEmailVerified(userId: string) {
await logAdminAction({
adminId: a.user.id,
action: "resend_verification",
action: "mark_email_verified",
targetUserId: userId,
metadata: { markedVerified: true },
})
+17 -4
View File
@@ -35,6 +35,19 @@ export async function GET() {
return NextResponse.json(data)
}
// Shape of one item in the model's JSON response. Every field is optional
// because the model is not a trusted schema — the insert below supplies a
// fallback for each, so a missing key degrades instead of throwing.
type AiPrediction = {
type?: string
title?: string
prediction?: string
confidence?: string
timeframe?: string
risk_level?: string
data?: Record<string, unknown> | null
}
export async function POST() {
const user = await getSessionUser()
if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
@@ -184,7 +197,7 @@ Only return valid JSON, no other text.`
json: true,
})
let predictions: any[] = []
let predictions: AiPrediction[] = []
try {
const parsed = JSON.parse(content || "{}")
predictions = Array.isArray(parsed) ? parsed : (parsed.predictions ?? [])
@@ -195,11 +208,11 @@ Only return valid JSON, no other text.`
// Replace old predictions
await db.delete(ai_predictions).where(eq(ai_predictions.user_id, ownerId))
const toInsert = predictions.map((p: any) => ({
const toInsert = predictions.map((p: AiPrediction) => ({
user_id: ownerId,
type: p.type ?? "growth_opportunity",
title: p.title,
prediction: p.prediction,
title: p.title ?? "Untitled prediction",
prediction: p.prediction ?? "",
confidence: p.confidence ?? "medium",
timeframe: p.timeframe ?? "Next 30 days",
risk_level: p.risk_level ?? "low",
+20 -7
View File
@@ -34,6 +34,18 @@ export async function GET() {
return NextResponse.json(data)
}
// Shape of one item in the model's JSON response. Optional for the same reason
// as AiPrediction: the model output is untrusted input, not a schema.
type AiRecommendation = {
type?: string
title?: string
description?: string
impact?: string
priority?: string
action_label?: string
action_data?: Record<string, unknown> | null
}
export async function POST() {
const user = await getSessionUser()
if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
@@ -169,7 +181,7 @@ Return a JSON object with key "recommendations" containing an array. Each recomm
Only return valid JSON, no other text.`
let recommendations: any[] = []
let recommendations: AiRecommendation[] = []
try {
const content = await aiComplete({
messages: [{ role: "user", content: prompt }],
@@ -178,8 +190,9 @@ Only return valid JSON, no other text.`
})
const parsed = JSON.parse(content || "{}")
recommendations = Array.isArray(parsed) ? parsed : (parsed.recommendations ?? [])
} catch (err: any) {
return NextResponse.json({ error: err?.message ?? "AI generation failed" }, { status: 500 })
} catch (err) {
const message = err instanceof Error ? err.message : "AI generation failed"
return NextResponse.json({ error: message }, { status: 500 })
}
// Delete old pending recommendations and insert new ones
@@ -187,12 +200,12 @@ Only return valid JSON, no other text.`
.delete(ai_recommendations)
.where(and(eq(ai_recommendations.user_id, ownerId), eq(ai_recommendations.status, "pending")))
const toInsert = recommendations.map((r: any) => ({
const toInsert = recommendations.map((r: AiRecommendation) => ({
user_id: ownerId,
type: r.type ?? "opportunity",
title: r.title,
description: r.description,
impact: r.impact,
title: r.title ?? "Untitled recommendation",
description: r.description ?? "",
impact: r.impact ?? "",
priority: r.priority ?? "medium",
status: "pending",
action_label: r.action_label ?? "Apply",
+3 -1
View File
@@ -38,7 +38,9 @@ export async function POST(request: Request) {
}
// Pass only the whitelisted, validated fields to the model.
const { payment_id, ...receiptFields } = parsed.data
// payment_id identifies the row but must not reach the model — destructured
// out deliberately, hence the leading underscore.
const { payment_id: _payment_id, ...receiptFields } = parsed.data
const text = await aiComplete({
messages: [
+6 -1
View File
@@ -115,7 +115,12 @@ export async function GET(_req: Request, { params }: { params: Promise<{ token:
headers: {
"Content-Type": "text/calendar; charset=utf-8",
"Content-Disposition": 'inline; filename="property-management-network.ics"',
"Cache-Control": "public, max-age=3600",
// PRIVATE, never shared-cacheable: the only credential is the token in the
// URL, and the body carries tenant names, rent amounts, property addresses
// and lease dates. A `public` cache directive would let any intermediary
// or CDN retain that PII.
"Cache-Control": "private, max-age=3600",
"X-Robots-Tag": "noindex, nofollow",
},
})
}
+12 -1
View File
@@ -8,6 +8,7 @@ import { ownsProperty, ownsUnit, ownsTenant } from "@/lib/db/ownership"
import { logActivity } from "@/lib/activity"
import { getEffectiveOwnerId, getAccountContext } from "@/lib/account"
import { emitWebhookEvent } from "@/lib/webhooks/emit"
import { enforceRateLimit, clientIp } from "@/lib/rate-limit"
const VALID_STATUSES = ["open", "in_progress", "resolved", "closed"]
const VALID_PRIORITIES = ["low", "medium", "high", "emergency"]
@@ -62,12 +63,22 @@ export async function POST(request: Request) {
if (!ctx.canWrite) return NextResponse.json({ error: "Forbidden" }, { status: 403 })
userId = ctx.ownerId
} else {
// Tenant portal submission — verify portal_token
// Tenant portal submission — verify portal_token.
//
// This is the one unauthenticated write path in the app, so it carries its
// own limits: a per-IP budget that also caps portal-token guessing, and a
// tighter per-token budget so a leaked token cannot flood a landlord's queue.
const ipLimited = enforceRateLimit(`portal-maintenance-ip:${clientIp(request)}`, 20, 3600)
if (ipLimited) return ipLimited
const portalToken = body.portal_token as string | undefined
if (!portalToken) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
}
const tokenLimited = enforceRateLimit(`portal-maintenance:${portalToken}`, 10, 3600)
if (tokenLimited) return tokenLimited
const tenant = await db.query.tenants.findFirst({
where: eq(tenants.portal_token, portalToken),
columns: { id: true, user_id: true, property_id: true, unit_id: true },
+4 -13
View File
@@ -1,11 +1,10 @@
import { NextResponse } from "next/server"
import { desc, eq, sql } from "drizzle-orm"
import { desc, eq } from "drizzle-orm"
import { db } from "@/lib/db"
import { properties } from "@/lib/db/schema"
import { getSessionUser } from "@/lib/session"
import { propertySchema } from "@/lib/validations"
import { getUserPlan } from "@/lib/plan-limits"
import { checkLimit } from "@/lib/stripe/plans"
import { checkPropertyLimit } from "@/lib/plan-limits"
import { getEffectiveOwnerId, getAccountContext } from "@/lib/account"
import { emitWebhookEvent } from "@/lib/webhooks/emit"
import { geocodeAddress } from "@/lib/geocoding"
@@ -37,16 +36,8 @@ export async function POST(request: Request) {
const parsed = propertySchema.safeParse(body)
if (!parsed.success) return NextResponse.json({ error: parsed.error.flatten() }, { status: 400 })
// Check plan limit
const [{ count }] = await db
.select({ count: sql<number>`count(*)::int` })
.from(properties)
.where(eq(properties.user_id, ownerId))
const plan = await getUserPlan(ownerId)
if (!checkLimit(plan, "maxProperties", count)) {
return NextResponse.json({ error: "Plan limit reached. Upgrade to add more properties." }, { status: 403 })
}
const limitError = await checkPropertyLimit(ownerId)
if (limitError) return NextResponse.json({ error: limitError }, { status: 403 })
// Best-effort geocode so the property shows up on the map (never blocks save).
const coords = await geocodeAddress(parsed.data)
+12 -2
View File
@@ -5,6 +5,16 @@ import { db } from "@/lib/db"
import { profiles, rent_payments } from "@/lib/db/schema"
import type Stripe from "stripe"
/**
* `current_period_end` is present on the webhook payload but absent from the
* Subscription type in this pinned API version, so it is read through a narrow
* accessor rather than casting the whole object to `any`.
*/
function subscriptionPeriodEnd(sub: Stripe.Subscription): number | null {
const v = (sub as unknown as { current_period_end?: unknown }).current_period_end
return typeof v === "number" ? v : null
}
export async function POST(request: Request) {
const body = await request.text()
const sig = request.headers.get("stripe-signature")!
@@ -54,8 +64,8 @@ export async function POST(request: Request) {
plan: (plan ?? "starter") as typeof profiles.$inferSelect.plan,
stripe_subscription_id: subscription.id,
subscription_status: subscription.status,
plan_expires_at: (subscription as any).current_period_end
? new Date((subscription as any).current_period_end * 1000).toISOString()
plan_expires_at: subscriptionPeriodEnd(subscription)
? new Date(subscriptionPeriodEnd(subscription)! * 1000).toISOString()
: null,
})
.where(eq(profiles.id, userId))
+3 -14
View File
@@ -5,8 +5,7 @@ import { tenants, units } from "@/lib/db/schema"
import { getSessionUser } from "@/lib/session"
import { tenantSchema } from "@/lib/validations"
import { ownsProperty, ownsUnit } from "@/lib/db/ownership"
import { getUserPlan } from "@/lib/plan-limits"
import { checkLimit } from "@/lib/stripe/plans"
import { checkTenantLimit } from "@/lib/plan-limits"
import { logActivity } from "@/lib/activity"
import { getEffectiveOwnerId, getAccountContext } from "@/lib/account"
import { emitWebhookEvent } from "@/lib/webhooks/emit"
@@ -64,18 +63,8 @@ export async function POST(request: Request) {
const parsed = tenantSchema.safeParse(body)
if (!parsed.success) return NextResponse.json({ error: parsed.error.flatten() }, { status: 400 })
// Enforce per-plan tenant limit (Starter = 3).
const plan = await getUserPlan(ownerId)
const [{ count }] = await db
.select({ count: sql<number>`count(*)::int` })
.from(tenants)
.where(eq(tenants.user_id, ownerId))
if (!checkLimit(plan, "maxTenants", count)) {
return NextResponse.json(
{ error: "Plan limit reached. Upgrade to add more tenants." },
{ status: 403 }
)
}
const limitError = await checkTenantLimit(ownerId)
if (limitError) return NextResponse.json({ error: limitError }, { status: 403 })
if (
!(await ownsProperty(ownerId, parsed.data.property_id)) ||
+6
View File
@@ -9,6 +9,7 @@ import {
extOf,
} from "@/lib/storage"
import { checkStorageLimit } from "@/lib/plan-limits"
import { enforceRateLimit } from "@/lib/rate-limit"
const ALLOWED_SCOPES = ["property-images", "maintenance", "documents", "misc"]
@@ -24,6 +25,11 @@ export async function POST(request: Request) {
if (!ctx.canWrite) return NextResponse.json({ error: "Forbidden" }, { status: 403 })
const ownerId = ctx.ownerId
// Storage quota caps total bytes, but not the rate of writes — throttle so a
// single account cannot hammer Spaces (or fill a plan's quota) in one burst.
const limited = enforceRateLimit(`upload:${ownerId}`, 60, 60)
if (limited) return limited
const fd = await request.formData()
const file = fd.get("file") as File | null
const scopeRaw = (fd.get("scope") as string) || "misc"
+5
View File
@@ -6,6 +6,7 @@ import { maintenance_requests } from "@/lib/db/schema"
import { maintenanceSchema } from "@/lib/validations"
import { ownsProperty, ownsUnit, ownsTenant } from "@/lib/db/ownership"
import { resolveApiRequest } from "@/lib/api-auth"
import { enforceRateLimit } from "@/lib/rate-limit"
import { emitWebhookEvent } from "@/lib/webhooks/emit"
// Public REST API (v1) — update a single maintenance request. Bearer API-key
@@ -26,6 +27,10 @@ const maintenancePatchSchema = maintenanceSchema.partial().extend({
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
+9
View File
@@ -5,6 +5,7 @@ import { maintenance_requests } from "@/lib/db/schema"
import { maintenanceSchema } from "@/lib/validations"
import { ownsProperty, ownsUnit, ownsTenant } from "@/lib/db/ownership"
import { resolveApiRequest } from "@/lib/api-auth"
import { enforceRateLimit } from "@/lib/rate-limit"
import { emitWebhookEvent } from "@/lib/webhooks/emit"
// Public REST API (v1) — maintenance requests. Bearer API-key auth.
@@ -22,6 +23,10 @@ export async function GET(request: Request) {
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 { searchParams } = new URL(request.url)
const status = searchParams.get("status")
const priority = searchParams.get("priority")
@@ -55,6 +60,10 @@ export async function GET(request: Request) {
export async function POST(request: Request) {
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 body = await request.json().catch(() => null)
+9
View File
@@ -5,6 +5,7 @@ import { rent_payments } from "@/lib/db/schema"
import { rentPaymentSchema } from "@/lib/validations"
import { ownsProperty, ownsUnit, ownsTenant } from "@/lib/db/ownership"
import { resolveApiRequest } from "@/lib/api-auth"
import { enforceRateLimit } from "@/lib/rate-limit"
import { emitWebhookEvent } from "@/lib/webhooks/emit"
// Public REST API (v1) — rent payments. Bearer API-key auth. Maps to the
@@ -21,6 +22,10 @@ export async function GET(request: Request) {
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 { searchParams } = new URL(request.url)
const status = searchParams.get("status")
const tenantId = searchParams.get("tenant_id")
@@ -57,6 +62,10 @@ export async function GET(request: Request) {
export async function POST(request: Request) {
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 body = await request.json().catch(() => null)
+18
View File
@@ -4,6 +4,8 @@ import { db } from "@/lib/db"
import { properties } from "@/lib/db/schema"
import { propertySchema } from "@/lib/validations"
import { resolveApiRequest } from "@/lib/api-auth"
import { enforceRateLimit } from "@/lib/rate-limit"
import { checkPropertyLimit } from "@/lib/plan-limits"
import { emitWebhookEvent } from "@/lib/webhooks/emit"
import { geocodeAddress } from "@/lib/geocoding"
@@ -19,6 +21,10 @@ export async function GET(request: Request) {
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 data = await db.query.properties.findMany({
where: eq(properties.user_id, ctx.ownerId),
with: { units: { columns: { id: true, status: true } } },
@@ -31,6 +37,10 @@ export async function GET(request: Request) {
export async function POST(request: Request) {
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 body = await request.json().catch(() => null)
@@ -42,6 +52,14 @@ export async function POST(request: Request) {
)
}
// Same plan cap the session route enforces — the public API is a creation
// entry point too, and skipping this here let a Starter key create unlimited
// properties.
const limitError = await checkPropertyLimit(ctx.ownerId)
if (limitError) {
return NextResponse.json({ error: { code: 403, message: limitError } }, { status: 403 })
}
const coords = await geocodeAddress(parsed.data)
const [data] = await db
+5
View File
@@ -3,6 +3,7 @@ import { and, desc, eq } from "drizzle-orm"
import { db } from "@/lib/db"
import { tenants } from "@/lib/db/schema"
import { resolveApiRequest } from "@/lib/api-auth"
import { enforceRateLimit } from "@/lib/rate-limit"
// Public REST API (v1) — Bearer API-key auth. Scoped by the resolved owner id.
@@ -13,6 +14,10 @@ export async function GET(request: Request) {
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 { searchParams } = new URL(request.url)
const propertyId = searchParams.get("property_id")
const status = searchParams.get("status")
+13
View File
@@ -3,6 +3,7 @@ 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"
@@ -32,6 +33,10 @@ export async function GET(request: Request, { params }: { params: Promise<{ id:
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)),
@@ -44,6 +49,10 @@ export async function GET(request: Request, { params }: { params: Promise<{ id:
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
@@ -93,6 +102,10 @@ export async function PATCH(request: Request, { params }: { params: Promise<{ id
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
+9
View File
@@ -3,6 +3,7 @@ import { desc, 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"
@@ -37,6 +38,10 @@ export async function GET(request: Request) {
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 data = await db
.select(PUBLIC_COLUMNS)
.from(webhook_endpoints)
@@ -49,6 +54,10 @@ export async function GET(request: Request) {
export async function POST(request: Request) {
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 body = await request.json().catch(() => null)
+9
View File
@@ -1,5 +1,14 @@
import type { Metadata } from "next"
import Link from "next/link"
// A 404 already returns the right status code, but without its own title it
// would surface the site-wide default title in tabs, share previews and logs.
// Next.js emits its own `noindex` for not-found, so no robots field here —
// adding one only produces a second, redundant <meta name="robots">.
export const metadata: Metadata = {
title: "Page not found",
}
export default function NotFound() {
return (
<div className="flex min-h-screen flex-col items-center justify-center bg-[#09090b] text-white">
+6 -1
View File
@@ -5,7 +5,12 @@ import { acceptInvite } from "@/app/actions/team"
import { Logo } from "@/components/shared/logo"
import { XCircle } from "lucide-react"
export const metadata = { title: "Accept Team Invite" }
// The URL carries a single-use invite token, so this page is noindex/nofollow
// to keep tokens out of search results.
export const metadata = {
title: "Accept team invite",
robots: { index: false, follow: false },
}
export default async function AcceptInvitePage({
params,