Add the owner admin area: invites, people, reset links

Creating an invite previously meant writing SQL by hand, which made the
whole feature unusable in practice. The owner can now create invites
with a use count and expiry, copy the link, show a QR code, and revoke.

QR codes are generated locally by node-qrcode as inline SVG. The CSP
forbids loading from any other origin, so an external generator was not
an option, and img-src 'self' already covers a same-origin SVG.

People lists everyone with what they have added and what their AI use
has cost over 30 days, with suspend, reactivate, per-user AI toggle and
delete. Deleting collects image keys and the minted gateway key id
before the cascade removes the rows, then cleans both up best-effort -
storage or the gateway being unavailable must not leave an account
half-deleted. Guards refuse to suspend or delete yourself or the last
owner.

Password reset links close the gap that came with keeping email and
password sign-in: with no email infrastructure, a member who forgets
their password had no way back in and the owner had no way to help. The
owner generates a single-use 24 hour link and delivers it the same way
as an invite. Issuing one invalidates any earlier unused reset, and the
reset endpoint answers identically for unknown, used and expired tokens
so it cannot be used to probe which exist.

The admin area 404s for members rather than 403ing, so its existence is
not advertised, and every /api/admin handler independently requires the
owner role.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
JP
2026-08-08 21:26:33 +00:00
parent 34afc497f4
commit 0ead1385f7
21 changed files with 1491 additions and 25 deletions

View File

@@ -0,0 +1,20 @@
import { Header } from "@/components/layout/header"
import { InvitesClient } from "@/components/admin/invites-client"
export default function AdminInvitesPage() {
return (
<div>
<Header title="Invites" />
<div className="p-4 md:p-8 max-w-3xl mx-auto space-y-6">
<div>
<h1 className="text-2xl font-bold">Invites</h1>
<p className="text-muted-foreground">
Signing up requires an invitation. Share a link or have someone scan the
QR code.
</p>
</div>
<InvitesClient />
</div>
</div>
)
}

View File

@@ -0,0 +1,20 @@
import { notFound } from "next/navigation"
import { auth } from "@/lib/auth"
/**
* Owner-only area.
*
* 404 rather than 403 so the admin area's existence is not advertised to members.
* This is the real gate - hiding the nav links is only presentation, and every
* /api/admin route independently calls requireOwner().
*/
export default async function AdminLayout({
children,
}: {
children: React.ReactNode
}) {
const session = await auth()
if (session?.user?.role !== "OWNER") notFound()
return <>{children}</>
}

View File

@@ -0,0 +1,20 @@
import { Header } from "@/components/layout/header"
import { UsersClient } from "@/components/admin/users-client"
export default function AdminUsersPage() {
return (
<div>
<Header title="People" />
<div className="p-4 md:p-8 max-w-3xl mx-auto space-y-6">
<div>
<h1 className="text-2xl font-bold">People</h1>
<p className="text-muted-foreground">
Everyone with an account, what they have added, and what their AI use has
cost over the last 30 days.
</p>
</div>
<UsersClient />
</div>
</div>
)
}

View File

@@ -0,0 +1,57 @@
import Link from "next/link"
import { KeyRound } from "lucide-react"
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card"
import { ResetForm } from "@/components/auth/reset-form"
import { prisma } from "@/lib/prisma"
export const dynamic = "force-dynamic"
export default async function ResetPage({
params,
}: {
params: { token: string }
}) {
const reset = await prisma.passwordReset.findUnique({
where: { token: params.token },
select: { usedAt: true, expiresAt: true },
})
const usable = !!reset && !reset.usedAt && reset.expiresAt > new Date()
return (
<div className="min-h-screen flex items-center justify-center bg-background p-4">
<Card className="w-full max-w-md">
<CardHeader className="text-center">
<div className="flex justify-center mb-4">
<KeyRound className="h-12 w-12 text-primary" />
</div>
<CardTitle className="text-2xl">Set a new password</CardTitle>
<CardDescription>
{usable
? "Choose a new password for your account."
: "That reset link is no longer valid. Ask the owner for a new one."}
</CardDescription>
</CardHeader>
<CardContent>
{usable ? (
<ResetForm token={params.token} />
) : (
<p className="text-center text-sm text-muted-foreground">
<Link
href="/login"
className="text-primary underline-offset-4 hover:underline"
>
Back to sign in
</Link>
</p>
)}
</CardContent>
</Card>
</div>
)
}

View File

@@ -0,0 +1,42 @@
import { NextResponse } from "next/server"
import QRCode from "qrcode"
import { requireOwner } from "@/lib/authz"
import { prisma } from "@/lib/prisma"
import { inviteUrl } from "@/lib/invites"
import { publicOrigin } from "@/lib/origin"
/**
* QR code for an invite link, as an SVG.
*
* Generated locally by node-qrcode - no external service, which matters because the
* CSP forbids loading from anywhere but this origin. Served as image/svg+xml so it
* can be used in a plain <img>, which `img-src 'self'` already allows.
*/
export async function GET(
request: Request,
{ params }: { params: { id: string } }
) {
const session = await requireOwner()
if (session instanceof NextResponse) return session
const invite = await prisma.invite.findUnique({
where: { id: params.id },
select: { token: true },
})
if (!invite) return new Response(null, { status: 404 })
const svg = await QRCode.toString(inviteUrl(invite.token, publicOrigin(request)), {
type: "svg",
margin: 1,
width: 320,
errorCorrectionLevel: "M",
})
return new Response(svg, {
headers: {
"Content-Type": "image/svg+xml",
// The link is a bearer token; keep it out of shared caches.
"Cache-Control": "private, no-store",
},
})
}

View File

@@ -0,0 +1,27 @@
import { NextResponse } from "next/server"
import { requireOwner } from "@/lib/authz"
import { prisma } from "@/lib/prisma"
/**
* Revokes rather than deletes, so the redemption history of an already-used invite
* survives - that is the record of who invited whom.
*/
export async function DELETE(
_request: Request,
{ params }: { params: { id: string } }
) {
const session = await requireOwner()
if (session instanceof NextResponse) return session
const invite = await prisma.invite.findUnique({ where: { id: params.id } })
if (!invite) {
return NextResponse.json({ error: "Not found" }, { status: 404 })
}
await prisma.invite.update({
where: { id: params.id },
data: { revokedAt: new Date() },
})
return NextResponse.json({ success: true })
}

View File

@@ -0,0 +1,56 @@
import { NextResponse } from "next/server"
import { z } from "zod"
import { requireOwner } from "@/lib/authz"
import { prisma } from "@/lib/prisma"
import { generateInviteToken } from "@/lib/invites"
const createSchema = z.object({
label: z.string().max(100).optional(),
maxUses: z.number().int().min(1).max(50).default(1),
expiresInHours: z.number().int().min(1).max(24 * 90).nullable().optional(),
})
export async function GET() {
const session = await requireOwner()
if (session instanceof NextResponse) return session
const invites = await prisma.invite.findMany({
orderBy: { createdAt: "desc" },
include: {
redemptions: {
select: { id: true, email: true, createdAt: true },
},
},
})
return NextResponse.json({ invites })
}
export async function POST(request: Request) {
const session = await requireOwner()
if (session instanceof NextResponse) return session
const parsed = createSchema.safeParse(await request.json().catch(() => ({})))
if (!parsed.success) {
return NextResponse.json(
{ error: "Invalid input", details: parsed.error.flatten() },
{ status: 400 }
)
}
const { label, maxUses, expiresInHours } = parsed.data
const invite = await prisma.invite.create({
data: {
token: generateInviteToken(),
label: label?.trim() || null,
createdById: session.user.id,
maxUses,
expiresAt: expiresInHours
? new Date(Date.now() + expiresInHours * 60 * 60 * 1000)
: null,
},
})
return NextResponse.json({ invite }, { status: 201 })
}

View File

@@ -0,0 +1,57 @@
import { NextResponse } from "next/server"
import { randomBytes } from "crypto"
import { requireOwner } from "@/lib/authz"
import { prisma } from "@/lib/prisma"
import { publicOrigin } from "@/lib/origin"
const RESET_TTL_HOURS = 24
/**
* Issues a single-use password reset link for a member.
*
* There is no email infrastructure, so the owner delivers this out of band, the same
* way an invite is delivered. Without it a member who forgets their password is
* permanently locked out and the owner has no way to help.
*
* Any unused reset for the same user is invalidated first, so only the newest link works.
*/
export async function POST(
request: Request,
{ params }: { params: { id: string } }
) {
const session = await requireOwner()
if (session instanceof NextResponse) return session
const user = await prisma.user.findUnique({
where: { id: params.id },
select: { id: true, email: true, password: true },
})
if (!user) return NextResponse.json({ error: "Not found" }, { status: 404 })
if (!user.password) {
return NextResponse.json(
{ error: "That account does not use a password" },
{ status: 400 }
)
}
const token = randomBytes(32).toString("hex")
await prisma.$transaction([
prisma.passwordReset.updateMany({
where: { userId: params.id, usedAt: null },
data: { usedAt: new Date() },
}),
prisma.passwordReset.create({
data: {
token,
userId: params.id,
expiresAt: new Date(Date.now() + RESET_TTL_HOURS * 60 * 60 * 1000),
},
}),
])
return NextResponse.json({
url: `${publicOrigin(request)}/reset/${token}`,
expiresInHours: RESET_TTL_HOURS,
})
}

View File

@@ -0,0 +1,113 @@
import { NextResponse } from "next/server"
import { z } from "zod"
import { requireOwner } from "@/lib/authz"
import { prisma } from "@/lib/prisma"
import { deleteImage } from "@/lib/s3"
import { revokeGatewayKey } from "@/lib/ai/switchboard-keys"
const patchSchema = z.object({
status: z.enum(["ACTIVE", "SUSPENDED"]).optional(),
aiEnabled: z.boolean().optional(),
aiDailyBudgetUsd: z.number().min(0).max(100).nullable().optional(),
})
/** Refuse to strand the deployment without a usable owner. */
async function guardLastOwner(targetId: string): Promise<string | null> {
const target = await prisma.user.findUnique({
where: { id: targetId },
select: { role: true },
})
if (!target) return "Not found"
if (target.role !== "OWNER") return null
const activeOwners = await prisma.user.count({
where: { role: "OWNER", status: "ACTIVE" },
})
return activeOwners <= 1 ? "Cannot suspend or delete the only owner" : null
}
export async function PATCH(
request: Request,
{ params }: { params: { id: string } }
) {
const session = await requireOwner()
if (session instanceof NextResponse) return session
const parsed = patchSchema.safeParse(await request.json().catch(() => ({})))
if (!parsed.success) {
return NextResponse.json({ error: "Invalid input" }, { status: 400 })
}
if (parsed.data.status === "SUSPENDED") {
if (params.id === session.user.id) {
return NextResponse.json(
{ error: "You cannot suspend your own account" },
{ status: 400 }
)
}
const problem = await guardLastOwner(params.id)
if (problem) return NextResponse.json({ error: problem }, { status: 400 })
}
const user = await prisma.user.update({
where: { id: params.id },
data: parsed.data,
select: { id: true, status: true, aiEnabled: true, aiDailyBudgetUsd: true },
})
return NextResponse.json({ user })
}
export async function DELETE(
_request: Request,
{ params }: { params: { id: string } }
) {
const session = await requireOwner()
if (session instanceof NextResponse) return session
if (params.id === session.user.id) {
return NextResponse.json(
{ error: "You cannot delete your own account" },
{ status: 400 }
)
}
const problem = await guardLastOwner(params.id)
if (problem) {
return NextResponse.json({ error: problem }, { status: problem === "Not found" ? 404 : 400 })
}
// Collect what the cascade will make unreachable, before it happens.
const [drinks, barItems, scans, keys] = await Promise.all([
prisma.drink.findMany({ where: { userId: params.id }, select: { imageUrl: true } }),
prisma.barItem.findMany({ where: { userId: params.id }, select: { imageUrl: true } }),
prisma.menuScan.findMany({ where: { userId: params.id }, select: { imageUrl: true } }),
prisma.userApiKey.findMany({
where: { userId: params.id },
select: { gatewayKeyId: true },
}),
])
await prisma.user.delete({ where: { id: params.id } })
// Best effort after the fact: never let storage or the gateway block a deletion
// the user asked for, and never leave the account half-deleted.
const keyPrefix = "/minio-images/"
const objectKeys = [...drinks, ...barItems, ...scans]
.map((r) => r.imageUrl)
.filter((u): u is string => !!u && u.startsWith(keyPrefix))
.map((u) => u.slice(keyPrefix.length))
await Promise.allSettled([
...objectKeys.map((k) => deleteImage(k)),
...keys
.map((k) => k.gatewayKeyId)
.filter((id): id is string => !!id)
.map((id) => revokeGatewayKey(id)),
])
return NextResponse.json({
success: true,
imagesDeleted: objectKeys.length,
gatewayKeysRevoked: keys.filter((k) => k.gatewayKeyId).length,
})
}

View File

@@ -0,0 +1,42 @@
import { NextResponse } from "next/server"
import { requireOwner } from "@/lib/authz"
import { prisma } from "@/lib/prisma"
export async function GET() {
const session = await requireOwner()
if (session instanceof NextResponse) return session
const users = await prisma.user.findMany({
orderBy: { createdAt: "asc" },
select: {
id: true,
name: true,
email: true,
role: true,
status: true,
aiEnabled: true,
aiDailyBudgetUsd: true,
createdAt: true,
_count: { select: { drinks: true, ratings: true, menuScans: true } },
},
})
// Spend for the trailing 30 days, grouped in one query rather than per user.
const since = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000)
const spend = await prisma.aiCall.groupBy({
by: ["userId"],
where: { createdAt: { gte: since } },
_sum: { costUsd: true },
_count: { _all: true },
})
const spendByUser = new Map(
spend.map((s) => [s.userId, { usd: s._sum.costUsd ?? 0, calls: s._count._all }])
)
return NextResponse.json({
users: users.map((u) => ({
...u,
aiSpend30d: spendByUser.get(u.id) ?? { usd: 0, calls: 0 },
})),
})
}

View File

@@ -0,0 +1,62 @@
import { NextResponse } from "next/server"
import { z } from "zod"
import bcrypt from "bcryptjs"
import { prisma } from "@/lib/prisma"
import { rateLimit } from "@/lib/rate-limit"
const resetSchema = z.object({
token: z.string().min(32).max(128),
password: z
.string()
.min(10, "Password must be at least 10 characters")
.max(128, "Password must be 128 characters or less")
.regex(/[a-z]/, "Password must contain at least one lowercase letter")
.regex(/[A-Z]/, "Password must contain at least one uppercase letter")
.regex(/[0-9]/, "Password must contain at least one number"),
})
export async function POST(request: Request) {
const parsed = resetSchema.safeParse(await request.json().catch(() => ({})))
if (!parsed.success) {
return NextResponse.json(
{ error: parsed.error.issues[0]?.message ?? "Invalid input" },
{ status: 400 }
)
}
const { token, password } = parsed.data
// Keyed on the token so guessing one costs attempts against that token alone.
const rl = rateLimit(`reset:${token.slice(0, 16)}`, 5, 15 * 60 * 1000)
if (!rl.success) {
return NextResponse.json(
{ error: "Too many attempts. Please try again later." },
{ status: 429 }
)
}
const reset = await prisma.passwordReset.findUnique({ where: { token } })
// One message for every failure mode, so this cannot be used to probe which
// tokens exist or have been used.
if (!reset || reset.usedAt || reset.expiresAt <= new Date()) {
return NextResponse.json(
{ error: "That reset link is no longer valid. Ask the owner for a new one." },
{ status: 400 }
)
}
const hashed = await bcrypt.hash(password, 10)
await prisma.$transaction([
prisma.user.update({
where: { id: reset.userId },
data: { password: hashed },
}),
prisma.passwordReset.update({
where: { id: reset.id },
data: { usedAt: new Date() },
}),
])
return NextResponse.json({ success: true })
}

View File

@@ -1,5 +1,6 @@
import { NextResponse } from "next/server"
import { INVITE_COOKIE, INVITE_COOKIE_MAX_AGE, inspectInvite } from "@/lib/invites"
import { publicOrigin } from "@/lib/origin"
/**
* Entry point for an invite link or QR code.
@@ -13,20 +14,6 @@ import { INVITE_COOKIE, INVITE_COOKIE_MAX_AGE, inspectInvite } from "@/lib/invit
*/
export const dynamic = "force-dynamic"
/**
* The app binds 0.0.0.0:3000 behind a reverse proxy, so `request.url` carries the
* internal address and redirects built from it are unreachable. NEXTAUTH_URL is the
* configured public origin and cannot be influenced by a request header.
*/
function publicOrigin(request: Request): string {
const configured = process.env.NEXTAUTH_URL
if (configured) return configured.replace(/\/$/, "")
const host = request.headers.get("x-forwarded-host") ?? request.headers.get("host")
const proto = request.headers.get("x-forwarded-proto") ?? "https"
return host ? `${proto}://${host}` : new URL(request.url).origin
}
export async function GET(
request: Request,
{ params }: { params: { token: string } }