diff --git a/.server-changes/admin-back-office-rate-limit.md b/.server-changes/admin-back-office-rate-limit.md new file mode 100644 index 0000000000..da6835f0c5 --- /dev/null +++ b/.server-changes/admin-back-office-rate-limit.md @@ -0,0 +1,6 @@ +--- +area: webapp +type: feature +--- + +Add a "Back office" tab to `/admin` and a per-organization detail page at `/admin/back-office/orgs/:orgId`. The first action available on that page is editing the org's API rate limit: admins can save a `tokenBucket` override (refill rate, interval, max tokens) and see a plain-English preview of the resulting sustained rate and burst allowance. Writes are audit-logged via the server logger. diff --git a/apps/webapp/app/components/primitives/Tabs.tsx b/apps/webapp/app/components/primitives/Tabs.tsx index cbc5cf4275..0fb8a020a7 100644 --- a/apps/webapp/app/components/primitives/Tabs.tsx +++ b/apps/webapp/app/components/primitives/Tabs.tsx @@ -11,6 +11,7 @@ export type TabsProps = { tabs: { label: string; to: string; + end?: boolean; }[]; className?: string; layoutId: string; @@ -21,7 +22,13 @@ export function Tabs({ tabs, className, layoutId, variant = "underline" }: TabsP return ( {tabs.map((tab, index) => ( - + {tab.label} ))} @@ -62,18 +69,20 @@ export function TabLink({ children, layoutId, variant = "underline", + end = true, }: { to: string; children: ReactNode; layoutId: string; variant?: Variants; + end?: boolean; }) { if (variant === "segmented") { return ( {({ isActive, isPending }) => { const active = isActive || isPending; @@ -110,7 +119,7 @@ export function TabLink({ {({ isActive, isPending }) => { const active = isActive || isPending; @@ -131,7 +140,7 @@ export function TabLink({ // underline variant (default) return ( - + {({ isActive, isPending }) => { return ( <> diff --git a/apps/webapp/app/routes/admin.back-office._index.tsx b/apps/webapp/app/routes/admin.back-office._index.tsx new file mode 100644 index 0000000000..15e6f699b9 --- /dev/null +++ b/apps/webapp/app/routes/admin.back-office._index.tsx @@ -0,0 +1,29 @@ +import type { LoaderFunctionArgs } from "@remix-run/server-runtime"; +import { redirect, typedjson } from "remix-typedjson"; +import { LinkButton } from "~/components/primitives/Buttons"; +import { Header2 } from "~/components/primitives/Headers"; +import { Paragraph } from "~/components/primitives/Paragraph"; +import { requireUser } from "~/services/session.server"; + +export async function loader({ request }: LoaderFunctionArgs) { + const user = await requireUser(request); + if (!user.admin) { + return redirect("/"); + } + return typedjson({}); +} + +export default function BackOfficeIndex() { + return ( +
+ Back office + + Back-office actions are applied to a single organization. Pick an org from the + Organizations tab to open its detail page. + + + Pick an organization + +
+ ); +} diff --git a/apps/webapp/app/routes/admin.back-office.orgs.$orgId.tsx b/apps/webapp/app/routes/admin.back-office.orgs.$orgId.tsx new file mode 100644 index 0000000000..211a5a4fd2 --- /dev/null +++ b/apps/webapp/app/routes/admin.back-office.orgs.$orgId.tsx @@ -0,0 +1,452 @@ +import { Form, useNavigation, useSearchParams } from "@remix-run/react"; +import type { ActionFunctionArgs, LoaderFunctionArgs } from "@remix-run/server-runtime"; +import { useEffect, useState } from "react"; +import { redirect, typedjson, useTypedActionData, useTypedLoaderData } from "remix-typedjson"; +import { z } from "zod"; +import { Button, LinkButton } from "~/components/primitives/Buttons"; +import { CopyableText } from "~/components/primitives/CopyableText"; +import { FormError } from "~/components/primitives/FormError"; +import { Header1, Header2 } from "~/components/primitives/Headers"; +import { Input } from "~/components/primitives/Input"; +import { Label } from "~/components/primitives/Label"; +import { Paragraph } from "~/components/primitives/Paragraph"; +import * as Property from "~/components/primitives/PropertyTable"; +import { prisma } from "~/db.server"; +import { env } from "~/env.server"; +import { + RateLimitTokenBucketConfig, + RateLimiterConfig, +} from "~/services/authorizationRateLimitMiddleware.server"; +import { logger } from "~/services/logger.server"; +import { type Duration } from "~/services/rateLimiter.server"; +import { requireUser } from "~/services/session.server"; + +const SAVED_QUERY_KEY = "saved"; +const SAVED_QUERY_VALUE = "1"; + +type EffectiveRateLimit = { + source: "override" | "default"; + config: RateLimiterConfig; +}; + +function systemDefaultRateLimit(): RateLimiterConfig { + return { + type: "tokenBucket", + refillRate: env.API_RATE_LIMIT_REFILL_RATE, + interval: env.API_RATE_LIMIT_REFILL_INTERVAL as Duration, + maxTokens: env.API_RATE_LIMIT_MAX, + }; +} + +function resolveEffectiveRateLimit(override: unknown): EffectiveRateLimit { + if (override == null) { + return { source: "default", config: systemDefaultRateLimit() }; + } + const parsed = RateLimiterConfig.safeParse(override); + if (parsed.success) { + return { source: "override", config: parsed.data }; + } + // Column holds malformed JSON — fall back silently. Admin must investigate + // at the DB level; this UI can't recover it. + return { source: "default", config: systemDefaultRateLimit() }; +} + +function parseDurationToMs(duration: string): number { + const match = duration.trim().match(/^(\d+)\s*(ms|s|m|h|d)$/); + if (!match) return 0; + const value = parseInt(match[1], 10); + switch (match[2]) { + case "ms": + return value; + case "s": + return value * 1_000; + case "m": + return value * 60_000; + case "h": + return value * 3_600_000; + case "d": + return value * 86_400_000; + default: + return 0; + } +} + +function describeRateLimit( + refillRate: number, + intervalMs: number, + maxTokens: number +): { sustained: string; burst: string } | null { + if (refillRate <= 0 || intervalMs <= 0 || maxTokens <= 0) return null; + const perMin = (refillRate * 60_000) / intervalMs; + let sustained: string; + if (perMin >= 1) { + sustained = `${Math.round(perMin).toLocaleString()} requests per minute`; + } else { + const perHour = perMin * 60; + if (perHour >= 1) { + sustained = `${Math.round(perHour).toLocaleString()} requests per hour`; + } else { + const perDay = perHour * 24; + const formatted = + perDay >= 10 ? Math.round(perDay).toLocaleString() : perDay.toFixed(1); + sustained = `${formatted} requests per day`; + } + } + return { + sustained, + burst: `${maxTokens.toLocaleString()} request burst allowance`, + }; +} + +export async function loader({ request, params }: LoaderFunctionArgs) { + const user = await requireUser(request); + if (!user.admin) { + return redirect("/"); + } + + const orgId = params.orgId; + if (!orgId) { + throw new Response(null, { status: 404 }); + } + + const org = await prisma.organization.findFirst({ + where: { id: orgId }, + select: { + id: true, + slug: true, + title: true, + createdAt: true, + apiRateLimiterConfig: true, + }, + }); + + if (!org) { + throw new Response(null, { status: 404 }); + } + + const effective = resolveEffectiveRateLimit(org.apiRateLimiterConfig); + + return typedjson({ + org, + effective, + }); +} + +const SetRateLimitSchema = z.object({ + intent: z.literal("set-rate-limit"), + refillRate: z.coerce.number().int().min(1), + interval: z + .string() + .trim() + .refine((v) => parseDurationToMs(v) > 0, { + message: "Must be a duration like 10s, 1m, 500ms.", + }), + maxTokens: z.coerce.number().int().min(1), +}); + +export async function action({ request, params }: ActionFunctionArgs) { + const user = await requireUser(request); + if (!user.admin) { + return redirect("/"); + } + + const orgId = params.orgId; + if (!orgId) { + throw new Response(null, { status: 404 }); + } + + const formData = await request.formData(); + const submission = SetRateLimitSchema.safeParse(Object.fromEntries(formData)); + if (!submission.success) { + return typedjson( + { errors: submission.error.flatten().fieldErrors }, + { status: 400 } + ); + } + + const existing = await prisma.organization.findFirst({ + where: { id: orgId }, + select: { apiRateLimiterConfig: true }, + }); + if (!existing) { + throw new Response(null, { status: 404 }); + } + + const built = RateLimitTokenBucketConfig.safeParse({ + type: "tokenBucket", + refillRate: submission.data.refillRate, + interval: submission.data.interval, + maxTokens: submission.data.maxTokens, + }); + if (!built.success) { + return typedjson( + { errors: built.error.flatten().fieldErrors }, + { status: 400 } + ); + } + const next = built.data; + + await prisma.organization.update({ + where: { id: orgId }, + data: { apiRateLimiterConfig: next as any }, + }); + + logger.info("admin.backOffice.rateLimit", { + adminUserId: user.id, + orgId, + previous: existing.apiRateLimiterConfig, + next, + }); + + return redirect( + `/admin/back-office/orgs/${orgId}?${SAVED_QUERY_KEY}=${SAVED_QUERY_VALUE}` + ); +} + +export default function BackOfficeOrgPage() { + const { org, effective } = useTypedLoaderData(); + const actionData = useTypedActionData(); + const navigation = useNavigation(); + const isSubmitting = navigation.state !== "idle"; + + const errors = + actionData && "errors" in actionData ? actionData.errors : null; + const hasFieldErrors = + !!errors && typeof errors === "object" && Object.keys(errors).length > 0; + const fieldError = (field: string) => + errors && typeof errors === "object" && field in errors + ? (errors as Record)[field]?.[0] + : undefined; + + const current = + effective.config.type === "tokenBucket" ? effective.config : null; + + const [isEditing, setIsEditing] = useState(false); + const [refillRate, setRefillRate] = useState( + current ? String(current.refillRate) : "" + ); + const [intervalStr, setIntervalStr] = useState( + current ? String(current.interval) : "" + ); + const [maxTokens, setMaxTokens] = useState( + current ? String(current.maxTokens) : "" + ); + + const [searchParams, setSearchParams] = useSearchParams(); + const savedJustNow = searchParams.get(SAVED_QUERY_KEY) === SAVED_QUERY_VALUE; + + // If a submit comes back with validation errors, re-open edit mode so the + // admin can see and correct them without clicking Edit again. + useEffect(() => { + if (hasFieldErrors) setIsEditing(true); + }, [hasFieldErrors]); + + // On successful save, drop back to view mode (the component stays mounted + // across the same-route redirect, so `isEditing` wouldn't reset on its own). + useEffect(() => { + if (savedJustNow) setIsEditing(false); + }, [savedJustNow]); + + // Auto-dismiss the "saved" banner after a few seconds. + useEffect(() => { + if (!savedJustNow) return; + const t = setTimeout(() => { + setSearchParams( + (prev) => { + prev.delete(SAVED_QUERY_KEY); + return prev; + }, + { replace: true, preventScrollReset: true } + ); + }, 3000); + return () => clearTimeout(t); + }, [savedJustNow, setSearchParams]); + + const currentDescription = current + ? describeRateLimit( + current.refillRate, + parseDurationToMs(String(current.interval)), + current.maxTokens + ) + : null; + + const previewDescription = describeRateLimit( + Number(refillRate) || 0, + parseDurationToMs(intervalStr), + Number(maxTokens) || 0 + ); + + const cancelEdit = () => { + setRefillRate(current ? String(current.refillRate) : ""); + setIntervalStr(current ? String(current.interval) : ""); + setMaxTokens(current ? String(current.maxTokens) : ""); + setIsEditing(false); + }; + + return ( +
+
+
+ {org.title} + + · + +
+ + Back to organizations + +
+ +
+
+ API rate limit + {!isEditing && ( + + )} +
+ + {savedJustNow && ( +
+ + Rate limit saved. + +
+ )} + + + Status:{" "} + {effective.source === "override" + ? "Custom override active." + : "Using system default."} + + + {!isEditing ? ( + <> + + {effective.config.type === "tokenBucket" ? ( + currentDescription ? ( + <> + + Sustained rate + {currentDescription.sustained} + + + Burst allowance + {currentDescription.burst} + + + ) : ( + + + Invalid interval on the stored config. + + + ) + ) : ( + <> + + Type + {effective.config.type} + + + Window + {String(effective.config.window)} + + + Tokens + + {effective.config.tokens.toLocaleString()} + + + + )} + + {effective.config.type !== "tokenBucket" && ( + + This override is a {effective.config.type} limit and can't be + edited from this form. Change it in the database directly. + + )} + + ) : ( +
+ + +
+ + setRefillRate(e.target.value)} + required + /> + {fieldError("refillRate")} +
+ +
+ + setIntervalStr(e.target.value)} + required + /> + {fieldError("interval")} +
+ +
+ + setMaxTokens(e.target.value)} + required + /> + {fieldError("maxTokens")} +
+ + + {previewDescription + ? `Preview: ${previewDescription.sustained} · ${previewDescription.burst}.` + : "Preview: enter valid values to see the effective limit."} + + +
+ + +
+
+ )} +
+
+ ); +} diff --git a/apps/webapp/app/routes/admin.back-office.tsx b/apps/webapp/app/routes/admin.back-office.tsx new file mode 100644 index 0000000000..026fc13fdc --- /dev/null +++ b/apps/webapp/app/routes/admin.back-office.tsx @@ -0,0 +1,23 @@ +import { Outlet } from "@remix-run/react"; +import type { LoaderFunctionArgs } from "@remix-run/server-runtime"; +import { redirect, typedjson } from "remix-typedjson"; +import { requireUser } from "~/services/session.server"; + +export async function loader({ request }: LoaderFunctionArgs) { + const user = await requireUser(request); + if (!user.admin) { + return redirect("/"); + } + return typedjson({}); +} + +export default function BackOfficeLayout() { + return ( +
+ +
+ ); +} diff --git a/apps/webapp/app/routes/admin.orgs.tsx b/apps/webapp/app/routes/admin.orgs.tsx index 6f49636294..6d16ab99c9 100644 --- a/apps/webapp/app/routes/admin.orgs.tsx +++ b/apps/webapp/app/routes/admin.orgs.tsx @@ -85,15 +85,14 @@ export default function AdminDashboardRoute() { Slug Members id - v2? - v3? Deleted? + Back office Actions {organizations.length === 0 ? ( - + No orgs found for search ) : ( @@ -120,9 +119,15 @@ export default function AdminDashboardRoute() { - {org.v2Enabled ? "✅" : ""} - {org.v3Enabled ? "✅" : ""} {org.deletedAt ? "☠️" : ""} + + + Open + +