fix: audit fixes — tier-quota bypass, webhook SSRF, auth hardening, pagination, a11y

Full audit (bugs/UI-UX/backend/feature-gap) turned up a money-leak AI quota
bypass, webhook SSRF, and a long tail of missing pagination/auth/a11y work.
Fixes land together since HANDOFF.md tracked them as one backlog.

- AI routes charge tier quota before generating; nutrition POST is author-only
- Webhook dispatch re-validates URL per delivery (SSRF/DNS-rebinding), treats
  redirects as failures; recipe.published now actually dispatches
- New indexes/unique constraints on recipes, meal-planning, comments FK cascade
- Recipe PUT/restore snapshot only inside the transaction, after validation
- Recipe DELETE cleans up S3 objects (recipe + review photos)
- Optimistic UI (favorite/star/follow/shopping-list) rolls back on failure
- Upload presign enforces file size cap + per-tier storage quota
- Route-level loading/error/not-found states across (app), admin, and root
- middleware.ts guards (app)/admin; requireAdmin checks DB role, not cached
  session; rate limiting applied to both session and API-key branches,
  bucketed per key; Stripe webhook dedupes by event id
- Pagination added to recipes, feed, profile, comments, pantry, admin tables
- Nav shows real avatar + profile link + dark-mode toggle; destructive actions
  standardized on AlertDialog
- Unsaved-changes guard + real ingredient/step validation on recipe form;
  canonical /recipes/[id] used in-app; next/image migration; aria-labels and
  alt text across icon buttons, avatars, recipe photos
- packages/api-types removed (zero callers, too drifted to safely rewire);
  openapi.ts and ai-keys error shape drift fixed; BYOK decrypt failures now
  surface instead of silently falling back to the platform key

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
Arnaud
2026-07-09 21:50:35 +02:00
parent b4b964aafb
commit 362f65656b
128 changed files with 11271 additions and 970 deletions
@@ -0,0 +1,14 @@
import { PageHeaderSkeleton, InfoCardSkeleton } from "@/components/shared/skeletons";
export default function CollectionsLoading() {
return (
<div className="space-y-6">
<PageHeaderSkeleton actions={1} />
<div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-4">
{Array.from({ length: 6 }).map((_, i) => (
<InfoCardSkeleton key={i} />
))}
</div>
</div>
);
}
+27
View File
@@ -0,0 +1,27 @@
"use client";
import { useEffect } from "react";
import { Button } from "@/components/ui/button";
export default function AppError({
error,
reset,
}: {
error: Error & { digest?: string };
reset: () => void;
}) {
useEffect(() => {
console.error(error);
}, [error]);
return (
<div className="flex flex-col items-center justify-center gap-4 py-24 text-center">
<h2 className="text-xl font-semibold">Something went wrong</h2>
<p className="text-muted-foreground max-w-md">
An unexpected error occurred while loading this page. You can try again, or head back
later.
</p>
<Button onClick={() => reset()}>Try again</Button>
</div>
);
}
+25
View File
@@ -0,0 +1,25 @@
import { Skeleton } from "@/components/ui/skeleton";
import { InfoCardSkeleton } from "@/components/shared/skeletons";
function ExploreSection() {
return (
<div className="space-y-4">
<Skeleton className="h-6 w-32" />
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
{Array.from({ length: 4 }).map((_, i) => (
<InfoCardSkeleton key={i} />
))}
</div>
</div>
);
}
export default function ExploreLoading() {
return (
<div className="space-y-8">
<Skeleton className="h-12 w-full max-w-xl rounded-md" />
<ExploreSection />
<ExploreSection />
</div>
);
}
+11
View File
@@ -0,0 +1,11 @@
import { FeedItemSkeleton } from "@/components/shared/skeletons";
export default function FeedLoading() {
return (
<div className="max-w-2xl mx-auto space-y-8">
{Array.from({ length: 4 }).map((_, i) => (
<FeedItemSkeleton key={i} />
))}
</div>
);
}
+2 -37
View File
@@ -1,8 +1,7 @@
import type { Metadata } from "next";
import { headers } from "next/headers";
import { auth } from "@/lib/auth/server";
import { db, recipes, users, userFollows, eq, desc, inArray } from "@epicure/db";
import { getPublicUrl } from "@/lib/storage";
import { db, userFollows, eq } from "@epicure/db";
import { FeedPageContent } from "@/components/feed/feed-page-content";
export const metadata: Metadata = {};
@@ -16,39 +15,5 @@ export default async function FeedPage() {
.from(userFollows)
.where(eq(userFollows.followerId, session.user.id));
const followedIds = followedRows.map((r) => r.followingId);
if (followedIds.length === 0) {
return <FeedPageContent followedCount={0} feedRecipes={[]} />;
}
const feedRecipes = await db
.select({
id: recipes.id,
title: recipes.title,
description: recipes.description,
baseServings: recipes.baseServings,
prepMins: recipes.prepMins,
cookMins: recipes.cookMins,
difficulty: recipes.difficulty,
visibility: recipes.visibility,
aiGenerated: recipes.aiGenerated,
createdAt: recipes.createdAt,
authorId: recipes.authorId,
authorName: users.name,
authorUsername: users.username,
authorAvatarUrl: users.avatarUrl,
})
.from(recipes)
.innerJoin(users, eq(recipes.authorId, users.id))
.where(inArray(recipes.authorId, followedIds))
.orderBy(desc(recipes.createdAt))
.limit(40);
return (
<FeedPageContent
followedCount={followedIds.length}
feedRecipes={feedRecipes.map((r) => ({ ...r, createdAt: r.createdAt.toISOString() }))}
/>
);
return <FeedPageContent followedCount={followedRows.length} />;
}
+10
View File
@@ -0,0 +1,10 @@
import { PageHeaderSkeleton, RecipeCardGridSkeleton } from "@/components/shared/skeletons";
export default function AppLoading() {
return (
<div className="space-y-6">
<PageHeaderSkeleton actions={1} />
<RecipeCardGridSkeleton />
</div>
);
}
+16
View File
@@ -0,0 +1,16 @@
import { Skeleton } from "@/components/ui/skeleton";
import { PageHeaderSkeleton } from "@/components/shared/skeletons";
export default function MealPlanLoading() {
return (
<div className="space-y-6">
<PageHeaderSkeleton actions={4} subtitle />
<Skeleton className="h-16 w-full rounded-xl" />
<div className="grid grid-cols-1 md:grid-cols-7 gap-3">
{Array.from({ length: 7 }).map((_, i) => (
<Skeleton key={i} className="h-64 w-full rounded-xl" />
))}
</div>
</div>
);
}
+1 -1
View File
@@ -31,7 +31,7 @@ export default async function ConversationPage({ params }: Params) {
<div className="border-b p-3 flex items-center gap-3">
<Link href={`/u/${other.username}`} className="flex items-center gap-3">
<Avatar className="h-8 w-8">
{other.avatarUrl && <AvatarImage src={other.avatarUrl} />}
{other.avatarUrl && <AvatarImage src={other.avatarUrl} alt={other.name} />}
<AvatarFallback className="text-xs">{other.name.slice(0, 2).toUpperCase()}</AvatarFallback>
</Avatar>
<span className="font-medium text-sm hover:underline">{other.name}</span>
+16
View File
@@ -0,0 +1,16 @@
import Link from "next/link";
import { buttonVariants } from "@/components/ui/button";
export default function AppNotFound() {
return (
<div className="flex flex-col items-center justify-center gap-4 py-24 text-center">
<h1 className="text-2xl font-bold tracking-tight">Page not found</h1>
<p className="text-muted-foreground max-w-md">
The page you&apos;re looking for doesn&apos;t exist or may have been moved.
</p>
<Link href="/recipes" className={buttonVariants({ variant: "default" })}>
Back home
</Link>
</div>
);
}
+16
View File
@@ -0,0 +1,16 @@
import { Skeleton } from "@/components/ui/skeleton";
import { PageHeaderSkeleton, ListRowSkeleton } from "@/components/shared/skeletons";
export default function PantryLoading() {
return (
<div className="space-y-6">
<PageHeaderSkeleton actions={1} />
<Skeleton className="h-20 w-full rounded-xl" />
<div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-4">
{Array.from({ length: 6 }).map((_, i) => (
<ListRowSkeleton key={i} />
))}
</div>
</div>
);
}
@@ -0,0 +1,29 @@
import { Skeleton } from "@/components/ui/skeleton";
import { ListRowSkeleton } from "@/components/shared/skeletons";
export default function RecipeDetailLoading() {
return (
<div className="max-w-4xl mx-auto space-y-8">
<div className="space-y-4">
<Skeleton className="h-9 w-2/3" />
<div className="flex items-center gap-2">
{Array.from({ length: 6 }).map((_, i) => (
<Skeleton key={i} className="h-8 w-8 rounded-lg" />
))}
</div>
<Skeleton className="h-4 w-full max-w-lg" />
<div className="flex flex-wrap items-center gap-3">
<Skeleton className="h-5 w-16" />
<Skeleton className="h-5 w-20" />
<Skeleton className="h-5 w-20" />
</div>
</div>
<Skeleton className="aspect-video w-full rounded-xl" />
<div className="space-y-4">
<Skeleton className="h-6 w-32" />
<ListRowSkeleton />
<ListRowSkeleton />
</div>
</div>
);
}
+13 -6
View File
@@ -1,4 +1,5 @@
import type { Metadata } from "next";
import Image from "next/image";
import { notFound } from "next/navigation";
import { headers } from "next/headers";
import Link from "next/link";
@@ -287,11 +288,12 @@ export default async function RecipePage({ params }: Params) {
{/* Cover photo */}
{cover && (
<div className="aspect-video overflow-hidden rounded-xl bg-muted">
<img
<div className="relative aspect-video overflow-hidden rounded-xl bg-muted">
<Image
src={getPublicUrl(cover.storageKey)}
alt={recipe.title}
className="w-full h-full object-cover"
fill
className="object-cover"
/>
</div>
)}
@@ -373,9 +375,14 @@ export default async function RecipePage({ params }: Params) {
<div className="space-y-3">
<h2 className="text-xl font-semibold">Photos</h2>
<div className="grid grid-cols-3 gap-3">
{recipe.photos.map((photo) => (
<div key={photo.id} className="aspect-square rounded-lg overflow-hidden bg-muted">
<img src={getPublicUrl(photo.storageKey)} alt="" className="w-full h-full object-cover" />
{recipe.photos.map((photo, i) => (
<div key={photo.id} className="relative aspect-square rounded-lg overflow-hidden bg-muted">
<Image
src={getPublicUrl(photo.storageKey)}
alt={`${recipe.title} photo ${i + 1}`}
fill
className="object-cover"
/>
</div>
))}
</div>
+10
View File
@@ -0,0 +1,10 @@
import { PageHeaderSkeleton, RecipeCardGridSkeleton } from "@/components/shared/skeletons";
export default function RecipesLoading() {
return (
<div className="space-y-6">
<PageHeaderSkeleton actions={2} subtitle />
<RecipeCardGridSkeleton />
</div>
);
}
+64 -18
View File
@@ -1,7 +1,8 @@
import type { Metadata } from "next";
import { headers } from "next/headers";
import Link from "next/link";
import { auth } from "@/lib/auth/server";
import { db, recipes, sql } from "@epicure/db";
import { db, recipes, sql, count } from "@epicure/db";
import { eq, desc, asc, and, ilike, or } from "@epicure/db";
import { RecipesHeader } from "@/components/recipe/recipes-header";
import { RecipesEmptyState } from "@/components/recipe/recipes-empty-state";
@@ -9,12 +10,15 @@ import { RecipesGrid } from "@/components/recipe/recipes-grid";
export const metadata: Metadata = {};
const PAGE_SIZE = 24;
type SearchParams = Promise<{
q?: string;
sort?: string;
visibility?: string;
difficulty?: string;
tag?: string;
page?: string;
}>;
const SORT_MAP = {
@@ -32,10 +36,12 @@ export default async function RecipesPage({ searchParams }: { searchParams: Sear
const session = await auth.api.getSession({ headers: await headers() });
if (!session) return null;
const { q, sort, visibility, difficulty, tag } = await searchParams;
const { q, sort, visibility, difficulty, tag, page: pageParam } = await searchParams;
const query = (q ?? "").trim().slice(0, 200);
const sortKey: SortKey = (sort && sort in SORT_MAP ? sort : "updated_desc") as SortKey;
const tagFilter = tag?.trim().slice(0, 50) || undefined;
const page = Math.max(1, parseInt(pageParam ?? "1", 10) || 1);
const offset = (page - 1) * PAGE_SIZE;
const visibilityFilter = visibility && ["private", "unlisted", "public"].includes(visibility)
? (visibility as "private" | "unlisted" | "public")
@@ -44,32 +50,72 @@ export default async function RecipesPage({ searchParams }: { searchParams: Sear
? (difficulty as "easy" | "medium" | "hard")
: undefined;
const userRecipes = await db.query.recipes.findMany({
where: and(
eq(recipes.authorId, session.user.id),
query
? or(ilike(recipes.title, `%${query}%`), ilike(recipes.description, `%${query}%`))
: undefined,
visibilityFilter ? eq(recipes.visibility, visibilityFilter) : undefined,
difficultyFilter ? eq(recipes.difficulty, difficultyFilter) : undefined,
tagFilter ? sql`${recipes.tags} @> ARRAY[${tagFilter}]::text[]` : undefined,
),
orderBy: SORT_MAP[sortKey],
with: { photos: true },
});
const where = and(
eq(recipes.authorId, session.user.id),
query
? or(ilike(recipes.title, `%${query}%`), ilike(recipes.description, `%${query}%`))
: undefined,
visibilityFilter ? eq(recipes.visibility, visibilityFilter) : undefined,
difficultyFilter ? eq(recipes.difficulty, difficultyFilter) : undefined,
tagFilter ? sql`${recipes.tags} @> ARRAY[${tagFilter}]::text[]` : undefined,
);
const [userRecipes, totalRow] = await Promise.all([
db.query.recipes.findMany({
where,
orderBy: SORT_MAP[sortKey],
with: { photos: true },
limit: PAGE_SIZE,
offset,
}),
db.select({ count: count() }).from(recipes).where(where),
]);
const total = totalRow[0]?.count ?? 0;
const totalPages = Math.max(1, Math.ceil(total / PAGE_SIZE));
const pageHref = (p: number) => {
const params = new URLSearchParams();
if (query) params.set("q", query);
if (sortKey !== "updated_desc") params.set("sort", sortKey);
if (visibilityFilter) params.set("visibility", visibilityFilter);
if (difficultyFilter) params.set("difficulty", difficultyFilter);
if (tagFilter) params.set("tag", tagFilter);
if (p > 1) params.set("page", String(p));
const qs = params.toString();
return qs ? `/recipes?${qs}` : "/recipes";
};
return (
<div className="space-y-6">
<RecipesHeader
count={userRecipes.length}
count={total}
initialQuery={query}
initialSort={sortKey}
initialVisibility={visibilityFilter ?? ""}
initialDifficulty={difficultyFilter ?? ""}
initialTag={tagFilter ?? ""}
/>
<RecipesEmptyState query={query} count={userRecipes.length} />
<RecipesGrid key={`${query}-${sortKey}-${visibilityFilter}-${difficultyFilter}-${tagFilter}`} recipes={userRecipes} />
<RecipesEmptyState query={query} count={total} />
<RecipesGrid key={`${query}-${sortKey}-${visibilityFilter}-${difficultyFilter}-${tagFilter}-${page}`} recipes={userRecipes} />
{totalPages > 1 && (
<div className="flex items-center justify-center gap-2 pt-2">
{page > 1 && (
<Link href={pageHref(page - 1)} className="rounded-md border px-3 py-1.5 text-sm hover:bg-accent">
Previous
</Link>
)}
<span className="text-sm text-muted-foreground px-2">
Page {page} of {totalPages}
</span>
{page < totalPages && (
<Link href={pageHref(page + 1)} className="rounded-md border px-3 py-1.5 text-sm hover:bg-accent">
Next
</Link>
)}
</div>
)}
</div>
);
}
+22
View File
@@ -0,0 +1,22 @@
import { Skeleton } from "@/components/ui/skeleton";
import { InfoCardSkeleton } from "@/components/shared/skeletons";
export default function SearchLoading() {
return (
<div className="max-w-5xl mx-auto space-y-6">
<div>
<Skeleton className="h-9 w-56 mb-6" />
<Skeleton className="h-12 w-full rounded-md" />
<div className="mt-3 flex flex-wrap items-center gap-3">
<Skeleton className="h-9 w-40" />
<Skeleton className="h-9 w-36" />
</div>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
{Array.from({ length: 8 }).map((_, i) => (
<InfoCardSkeleton key={i} />
))}
</div>
</div>
);
}
@@ -0,0 +1,14 @@
import { PageHeaderSkeleton, ListRowSkeleton } from "@/components/shared/skeletons";
export default function ShoppingListsLoading() {
return (
<div className="space-y-6">
<PageHeaderSkeleton actions={1} />
<div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-4">
{Array.from({ length: 6 }).map((_, i) => (
<ListRowSkeleton key={i} />
))}
</div>
</div>
);
}
@@ -0,0 +1,32 @@
import { Skeleton } from "@/components/ui/skeleton";
import { SquareTileSkeleton } from "@/components/shared/skeletons";
export default function UserProfileLoading() {
return (
<div className="max-w-4xl mx-auto space-y-10">
<div className="flex flex-col sm:flex-row gap-6 items-start sm:items-center">
<Skeleton className="h-24 w-24 shrink-0 rounded-full" />
<div className="flex-1 space-y-3">
<div className="space-y-2">
<Skeleton className="h-7 w-40" />
<Skeleton className="h-4 w-24" />
</div>
<Skeleton className="h-4 w-64" />
<div className="flex flex-wrap gap-2">
<Skeleton className="h-6 w-20 rounded-full" />
<Skeleton className="h-6 w-24 rounded-full" />
<Skeleton className="h-6 w-24 rounded-full" />
</div>
</div>
</div>
<div className="space-y-4">
<Skeleton className="h-6 w-24" />
<div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-4">
{Array.from({ length: 8 }).map((_, i) => (
<SquareTileSkeleton key={i} />
))}
</div>
</div>
</div>
);
}
+44 -7
View File
@@ -1,6 +1,7 @@
import { notFound } from "next/navigation";
import { headers } from "next/headers";
import Link from "next/link";
import Image from "next/image";
import { auth } from "@/lib/auth/server";
import {
db,
@@ -20,7 +21,12 @@ import { BlockButton } from "@/components/social/block-button";
import { MessageButton } from "@/components/social/message-button";
import { getPublicUrl } from "@/lib/storage";
type Params = { params: Promise<{ username: string }> };
const PAGE_SIZE = 24;
type Params = {
params: Promise<{ username: string }>;
searchParams: Promise<{ page?: string }>;
};
export async function generateMetadata({ params }: Params) {
const { username } = await params;
@@ -28,8 +34,11 @@ export async function generateMetadata({ params }: Params) {
return { title: user ? `${user.name} (@${user.username})` : "Profile" };
}
export default async function UserProfilePage({ params }: Params) {
export default async function UserProfilePage({ params, searchParams }: Params) {
const { username } = await params;
const { page: pageParam } = await searchParams;
const page = Math.max(1, parseInt(pageParam ?? "1", 10) || 1);
const offset = (page - 1) * PAGE_SIZE;
const session = await auth.api.getSession({ headers: await headers() });
@@ -52,7 +61,8 @@ export default async function UserProfilePage({ params }: Params) {
db.query.recipes.findMany({
where: and(eq(recipes.authorId, user.id), eq(recipes.visibility, "public")),
orderBy: desc(recipes.createdAt),
limit: 24,
limit: PAGE_SIZE,
offset,
with: {
photos: { orderBy: (t, { asc }) => asc(t.order), limit: 1 },
},
@@ -62,6 +72,7 @@ export default async function UserProfilePage({ params }: Params) {
const followerCount = followerCountRow[0]?.count ?? 0;
const followingCount = followingCountRow[0]?.count ?? 0;
const recipeCount = recipeCountRow[0]?.count ?? 0;
const totalPages = Math.max(1, Math.ceil(recipeCount / PAGE_SIZE));
let isFollowing = false;
let isBlocked = false;
@@ -148,15 +159,17 @@ export default async function UserProfilePage({ params }: Params) {
return (
<Link
key={recipe.id}
href={`/r/${recipe.id}`}
href={`/recipes/${recipe.id}`}
className="group block rounded-xl overflow-hidden border bg-card hover:shadow-md transition-shadow"
>
<div className="aspect-square bg-muted overflow-hidden">
<div className="relative aspect-square bg-muted overflow-hidden">
{cover ? (
<img
<Image
src={getPublicUrl(cover.storageKey)}
alt={recipe.title}
className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-200"
fill
sizes="(max-width: 640px) 50vw, (max-width: 768px) 33vw, 25vw"
className="object-cover group-hover:scale-105 transition-transform duration-200"
/>
) : (
<div className="w-full h-full flex items-center justify-center text-muted-foreground text-3xl">
@@ -171,6 +184,30 @@ export default async function UserProfilePage({ params }: Params) {
);
})}
</div>
{totalPages > 1 && (
<div className="flex items-center justify-center gap-2 pt-2">
{page > 1 && (
<Link
href={`/u/${username}${page - 1 > 1 ? `?page=${page - 1}` : ""}`}
className="rounded-md border px-3 py-1.5 text-sm hover:bg-accent"
>
Previous
</Link>
)}
<span className="text-sm text-muted-foreground px-2">
Page {page} of {totalPages}
</span>
{page < totalPages && (
<Link
href={`/u/${username}?page=${page + 1}`}
className="rounded-md border px-3 py-1.5 text-sm hover:bg-accent"
>
Next
</Link>
)}
</div>
)}
</div>
) : (
<div className="text-center py-16 text-muted-foreground">
+26
View File
@@ -0,0 +1,26 @@
"use client";
import { useEffect } from "react";
import { Button } from "@/components/ui/button";
export default function AdminError({
error,
reset,
}: {
error: Error & { digest?: string };
reset: () => void;
}) {
useEffect(() => {
console.error(error);
}, [error]);
return (
<div className="flex flex-col items-center justify-center gap-4 py-24 text-center">
<h2 className="text-xl font-semibold">Something went wrong</h2>
<p className="text-muted-foreground max-w-md">
An unexpected error occurred in the admin panel. You can try again.
</p>
<Button onClick={() => reset()}>Try again</Button>
</div>
);
}
+15
View File
@@ -0,0 +1,15 @@
import { Skeleton } from "@/components/ui/skeleton";
import { StatCardSkeleton } from "@/components/shared/skeletons";
export default function AdminLoading() {
return (
<div className="space-y-6">
<Skeleton className="h-8 w-32" />
<div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
{Array.from({ length: 4 }).map((_, i) => (
<StatCardSkeleton key={i} />
))}
</div>
</div>
);
}
+51 -17
View File
@@ -1,31 +1,46 @@
import type { Metadata } from "next";
import { db, recipes, users, eq, desc } from "@epicure/db";
import { db, recipes, users, eq, desc, count } from "@epicure/db";
import { Badge } from "@/components/ui/badge";
import Link from "next/link";
export const metadata: Metadata = {};
const PAGE_SIZE = 100;
const VISIBILITY_COLORS = {
public: "default",
unlisted: "outline",
private: "secondary",
} as const;
export default async function AdminRecipesPage() {
const publicRecipes = await db
.select({
id: recipes.id,
title: recipes.title,
visibility: recipes.visibility,
createdAt: recipes.createdAt,
authorName: users.name,
authorId: users.id,
})
.from(recipes)
.leftJoin(users, eq(recipes.authorId, users.id))
.where(eq(recipes.visibility, "public"))
.orderBy(desc(recipes.createdAt))
.limit(200);
interface PageProps {
searchParams: Promise<{ page?: string }>;
}
export default async function AdminRecipesPage({ searchParams }: PageProps) {
const { page: pageParam } = await searchParams;
const page = Math.max(1, parseInt(pageParam ?? "1", 10) || 1);
const offset = (page - 1) * PAGE_SIZE;
const [publicRecipes, totalRow] = await Promise.all([
db
.select({
id: recipes.id,
title: recipes.title,
visibility: recipes.visibility,
createdAt: recipes.createdAt,
authorName: users.name,
authorId: users.id,
})
.from(recipes)
.leftJoin(users, eq(recipes.authorId, users.id))
.where(eq(recipes.visibility, "public"))
.orderBy(desc(recipes.createdAt))
.limit(PAGE_SIZE)
.offset(offset),
db.select({ count: count() }).from(recipes).where(eq(recipes.visibility, "public")),
]);
const total = totalRow[0]?.count ?? 0;
return (
<div className="space-y-6">
@@ -36,7 +51,7 @@ export default async function AdminRecipesPage() {
</p>
</div>
<div className="rounded-md border">
<div className="rounded-md border overflow-x-auto">
<table className="w-full text-sm">
<thead className="border-b bg-muted/50">
<tr>
@@ -94,6 +109,25 @@ export default async function AdminRecipesPage() {
</tbody>
</table>
</div>
<div className="flex gap-2">
{page > 1 && (
<Link
href={`/admin/recipes?page=${page - 1}`}
className="rounded-md border px-3 py-1 text-sm hover:bg-accent"
>
Previous
</Link>
)}
{offset + publicRecipes.length < total && (
<Link
href={`/admin/recipes?page=${page + 1}`}
className="rounded-md border px-3 py-1 text-sm hover:bg-accent"
>
Next
</Link>
)}
</div>
</div>
);
}
+52 -17
View File
@@ -1,25 +1,41 @@
import type { Metadata } from "next";
import { db, reports, users, eq, desc } from "@epicure/db";
import Link from "next/link";
import { db, reports, users, eq, desc, count } from "@epicure/db";
import { ReportsQueue } from "@/components/admin/reports-queue";
export const metadata: Metadata = {};
export default async function AdminReportsPage() {
const rows = await db
.select({
id: reports.id,
targetType: reports.targetType,
targetId: reports.targetId,
reason: reports.reason,
createdAt: reports.createdAt,
reporterName: users.name,
reporterEmail: users.email,
})
.from(reports)
.innerJoin(users, eq(reports.reporterId, users.id))
.where(eq(reports.status, "pending"))
.orderBy(desc(reports.createdAt))
.limit(100);
const PAGE_SIZE = 100;
interface PageProps {
searchParams: Promise<{ page?: string }>;
}
export default async function AdminReportsPage({ searchParams }: PageProps) {
const { page: pageParam } = await searchParams;
const page = Math.max(1, parseInt(pageParam ?? "1", 10) || 1);
const offset = (page - 1) * PAGE_SIZE;
const [rows, totalRow] = await Promise.all([
db
.select({
id: reports.id,
targetType: reports.targetType,
targetId: reports.targetId,
reason: reports.reason,
createdAt: reports.createdAt,
reporterName: users.name,
reporterEmail: users.email,
})
.from(reports)
.innerJoin(users, eq(reports.reporterId, users.id))
.where(eq(reports.status, "pending"))
.orderBy(desc(reports.createdAt))
.limit(PAGE_SIZE)
.offset(offset),
db.select({ count: count() }).from(reports).where(eq(reports.status, "pending")),
]);
const total = totalRow[0]?.count ?? 0;
return (
<div className="space-y-6">
@@ -32,6 +48,25 @@ export default async function AdminReportsPage() {
<ReportsQueue
reports={rows.map((r) => ({ ...r, createdAt: r.createdAt.toISOString() }))}
/>
<div className="flex gap-2">
{page > 1 && (
<Link
href={`/admin/reports?page=${page - 1}`}
className="rounded-md border px-3 py-1 text-sm hover:bg-accent"
>
Previous
</Link>
)}
{offset + rows.length < total && (
<Link
href={`/admin/reports?page=${page + 1}`}
className="rounded-md border px-3 py-1 text-sm hover:bg-accent"
>
Next
</Link>
)}
</div>
</div>
);
}
+1 -1
View File
@@ -72,7 +72,7 @@ export default async function AdminUserDetailPage({ params }: PageProps) {
<div className="flex items-center gap-4">
<Avatar className="h-16 w-16">
<AvatarImage src={user.avatarUrl ?? ""} />
<AvatarImage src={user.avatarUrl ?? ""} alt={user.name} />
<AvatarFallback className="text-lg">
{user.name.slice(0, 2).toUpperCase()}
</AvatarFallback>
+43 -9
View File
@@ -1,5 +1,5 @@
import type { Metadata } from "next";
import { db } from "@epicure/db";
import { db, count } from "@epicure/db";
import { users } from "@epicure/db";
import { desc } from "@epicure/db";
import { Badge } from "@/components/ui/badge";
@@ -9,6 +9,12 @@ import Link from "next/link";
export const metadata: Metadata = {};
const PAGE_SIZE = 100;
interface PageProps {
searchParams: Promise<{ page?: string }>;
}
const ROLE_COLORS = {
user: "secondary",
moderator: "outline",
@@ -20,12 +26,21 @@ const TIER_COLORS = {
pro: "default",
} as const;
export default async function AdminUsersPage() {
const allUsers = await db
.select()
.from(users)
.orderBy(desc(users.createdAt))
.limit(100);
export default async function AdminUsersPage({ searchParams }: PageProps) {
const { page: pageParam } = await searchParams;
const page = Math.max(1, parseInt(pageParam ?? "1", 10) || 1);
const offset = (page - 1) * PAGE_SIZE;
const [allUsers, totalRow] = await Promise.all([
db
.select()
.from(users)
.orderBy(desc(users.createdAt))
.limit(PAGE_SIZE)
.offset(offset),
db.select({ count: count() }).from(users),
]);
const total = totalRow[0]?.count ?? 0;
return (
<div className="space-y-6">
@@ -33,7 +48,7 @@ export default async function AdminUsersPage() {
<h1 className="text-2xl font-bold tracking-tight">Users</h1>
<CreateUserDialog />
</div>
<div className="rounded-md border">
<div className="rounded-md border overflow-x-auto">
<table className="w-full text-sm">
<thead className="border-b bg-muted/50">
<tr>
@@ -49,7 +64,7 @@ export default async function AdminUsersPage() {
<td className="px-4 py-3">
<Link href={`/admin/users/${user.id}`} className="flex items-center gap-3 group">
<Avatar className="h-8 w-8">
<AvatarImage src={user.avatarUrl ?? ""} />
<AvatarImage src={user.avatarUrl ?? ""} alt={user.name} />
<AvatarFallback className="text-xs">
{user.name.slice(0, 2).toUpperCase()}
</AvatarFallback>
@@ -74,6 +89,25 @@ export default async function AdminUsersPage() {
</tbody>
</table>
</div>
<div className="flex gap-2">
{page > 1 && (
<Link
href={`/admin/users?page=${page - 1}`}
className="rounded-md border px-3 py-1 text-sm hover:bg-accent"
>
Previous
</Link>
)}
{offset + allUsers.length < total && (
<Link
href={`/admin/users?page=${page + 1}`}
className="rounded-md border px-3 py-1 text-sm hover:bg-accent"
>
Next
</Link>
)}
</div>
</div>
);
}
+1 -1
View File
@@ -32,7 +32,7 @@ export async function POST(req: Request) {
if (limited) return limited;
const body = PostSchema.safeParse(await req.json());
if (!body.success) return NextResponse.json({ error: body.error.flatten() }, { status: 400 });
if (!body.success) return NextResponse.json({ error: "Validation error", issues: body.error.issues }, { status: 400 });
const { provider, apiKey } = body.data;
const userId = session!.user.id;
+5 -3
View File
@@ -3,7 +3,7 @@ import { z } from "zod";
import { and, eq } from "@epicure/db";
import { db, recipes, recipeIngredients, recipeSteps } from "@epicure/db";
import { requireSession } from "@/lib/api-auth";
import { withAiQuota } from "@/lib/ai/ai-error";
import { withAiQuota, resolveAiConfigOrError } from "@/lib/ai/ai-error";
import { adaptRecipe } from "@/lib/ai/features/adapt-recipe";
import { withUserKey } from "@/lib/ai/resolve-user-key";
import { getUserPrivateBio } from "@/lib/ai/user-bio";
@@ -43,10 +43,12 @@ export async function POST(req: NextRequest, { params }: Params) {
return NextResponse.json({ error: "Provide at least one constraint" }, { status: 400 });
}
const [aiConfig, privateBio] = await Promise.all([
withUserKey(userId, { provider: parsed.data.provider, model: parsed.data.model }),
const [configResult, privateBio] = await Promise.all([
resolveAiConfigOrError(() => withUserKey(userId, { provider: parsed.data.provider, model: parsed.data.model })),
getUserPrivateBio(userId),
]);
if (!configResult.ok) return configResult.response;
const aiConfig = configResult.data;
const result = await withAiQuota(userId, session!.user.tier as "free" | "pro", () =>
adaptRecipe(
+7 -3
View File
@@ -3,7 +3,7 @@ import { z } from "zod";
import { and, eq } from "@epicure/db";
import { db, recipes } from "@epicure/db";
import { requireSession } from "@/lib/api-auth";
import { withAiQuota } from "@/lib/ai/ai-error";
import { withAiQuota, resolveAiConfigOrError } from "@/lib/ai/ai-error";
import { suggestDrinks } from "@/lib/ai/features/suggest-drinks";
import { withUserKey } from "@/lib/ai/resolve-user-key";
import { getUserPrivateBio } from "@/lib/ai/user-bio";
@@ -34,10 +34,14 @@ export async function POST(req: NextRequest, { params }: Params) {
const parsed = Schema.safeParse(body ?? {});
if (!parsed.success) return NextResponse.json({ error: "Validation error" }, { status: 400 });
const [aiConfig, privateBio] = await Promise.all([
withUserKey(session!.user.id, { provider: parsed.data.provider, model: parsed.data.model }),
const [configResult, privateBio] = await Promise.all([
resolveAiConfigOrError(() =>
withUserKey(session!.user.id, { provider: parsed.data.provider, model: parsed.data.model })
),
getUserPrivateBio(session!.user.id),
]);
if (!configResult.ok) return configResult.response;
const aiConfig = configResult.data;
const result = await withAiQuota(session!.user.id, session!.user.tier as "free" | "pro", () =>
suggestDrinks(
+4 -2
View File
@@ -3,7 +3,7 @@ import { z } from "zod";
import { db, recipes, recipeIngredients, recipeSteps } from "@epicure/db";
import { requireSession } from "@/lib/api-auth";
import { applyRateLimit } from "@/lib/rate-limit";
import { withAiQuota } from "@/lib/ai/ai-error";
import { withAiQuota, resolveAiConfigOrError } from "@/lib/ai/ai-error";
import { importFromPhoto } from "@/lib/ai/features/import-photo";
import { getModelConfigForUseCase } from "@/lib/ai/resolve-user-key";
@@ -28,7 +28,9 @@ export async function POST(req: NextRequest) {
const userId = session!.user.id;
const locale = (session!.user as { locale?: string }).locale ?? "en";
const aiConfig = await getModelConfigForUseCase(userId, "vision");
const configResult = await resolveAiConfigOrError(() => getModelConfigForUseCase(userId, "vision"));
if (!configResult.ok) return configResult.response;
const aiConfig = configResult.data;
// Fall back to vision-capable defaults if no explicit model configured
if (!aiConfig.model) {
@@ -4,7 +4,8 @@ import { db, recipes, recipeIngredients, recipeSteps, mealPlans, mealPlanEntries
import { requireSession } from "@/lib/api-auth";
import { applyRateLimit } from "@/lib/rate-limit";
import { getDefaultProviderWithKey } from "@/lib/ai/resolve-user-key";
import { aiErrorResponse } from "@/lib/ai/ai-error";
import { withAiQuota, resolveAiConfigOrError } from "@/lib/ai/ai-error";
import { checkAndIncrementTierLimit, incrementUsage, TierLimitError } from "@/lib/tiers";
import { generateMealPlan } from "@/lib/ai/features/generate-meal-plan";
import { getUserPrivateBio } from "@/lib/ai/user-bio";
@@ -35,10 +36,12 @@ export async function POST(req: NextRequest) {
const userId = session!.user.id;
const locale = (session!.user as { locale?: string }).locale ?? "en";
const [config, privateBio] = await Promise.all([
getDefaultProviderWithKey(userId),
const [configResult, privateBio] = await Promise.all([
resolveAiConfigOrError(() => getDefaultProviderWithKey(userId)),
getUserPrivateBio(userId),
]);
if (!configResult.ok) return configResult.response;
const config = configResult.data;
// pantryMode forces usePantry on so pantry items are always fetched when maximizing pantry use
const effectiveUsePantry = parsed.data.usePantry || parsed.data.pantryMode;
@@ -53,9 +56,8 @@ export async function POST(req: NextRequest) {
pantryItemNames = pantry.map((p) => p.rawName);
}
let plan;
try {
plan = await generateMealPlan(
const result = await withAiQuota(userId, session!.user.tier as "free" | "pro", () =>
generateMealPlan(
{
dietaryPrefs: parsed.data.dietaryPrefs,
servings: parsed.data.servings,
@@ -66,9 +68,26 @@ export async function POST(req: NextRequest) {
},
{ ...config, userContext: privateBio ?? undefined },
locale
);
)
);
if (!result.ok) return result.response;
const plan = result.data;
// Each plan entry creates a draft recipe — charge the recipe limit for all
// of them before inserting anything, refunding on breach so a rejected plan
// doesn't consume quota.
let chargedRecipes = 0;
try {
for (let i = 0; i < plan.entries.length; i++) {
await checkAndIncrementTierLimit(userId, session!.user.tier as "free" | "pro", "recipe");
chargedRecipes++;
}
} catch (err) {
return aiErrorResponse(err);
if (err instanceof TierLimitError) {
if (chargedRecipes > 0) await incrementUsage(userId, "recipe", -chargedRecipes);
return NextResponse.json({ error: "Recipe limit reached for your tier" }, { status: 403 });
}
throw err;
}
// Ensure meal plan row exists for the week
@@ -3,7 +3,7 @@ import { z } from "zod";
import { and, eq } from "@epicure/db";
import { db, recipes } from "@epicure/db";
import { requireSession } from "@/lib/api-auth";
import { withAiQuota } from "@/lib/ai/ai-error";
import { withAiQuota, resolveAiConfigOrError } from "@/lib/ai/ai-error";
import { suggestPairings } from "@/lib/ai/features/suggest-pairings";
import { withUserKey } from "@/lib/ai/resolve-user-key";
import { getUserPrivateBio } from "@/lib/ai/user-bio";
@@ -35,10 +35,14 @@ export async function POST(req: NextRequest, { params }: Params) {
const parsed = Schema.safeParse(body ?? {});
if (!parsed.success) return NextResponse.json({ error: "Validation error" }, { status: 400 });
const [aiConfig, privateBio] = await Promise.all([
withUserKey(session!.user.id, { provider: parsed.data.provider, model: parsed.data.model }),
const [configResult, privateBio] = await Promise.all([
resolveAiConfigOrError(() =>
withUserKey(session!.user.id, { provider: parsed.data.provider, model: parsed.data.model })
),
getUserPrivateBio(session!.user.id),
]);
if (!configResult.ok) return configResult.response;
const aiConfig = configResult.data;
const result = await withAiQuota(session!.user.id, session!.user.tier as "free" | "pro", () =>
suggestPairings(
+14 -9
View File
@@ -3,6 +3,7 @@ import { z } from "zod";
import { generateText } from "ai";
import { requireSession } from "@/lib/api-auth";
import { applyRateLimit } from "@/lib/rate-limit";
import { withAiQuota, resolveAiConfigOrError } from "@/lib/ai/ai-error";
import { getModelConfigForUseCase } from "@/lib/ai/resolve-user-key";
import { resolveModel } from "@/lib/ai/factory";
import { db, recipes, eq, and } from "@epicure/db";
@@ -62,22 +63,26 @@ STEPS:
${stepList || "None listed"}
`.trim();
const [config, privateBio] = await Promise.all([
getModelConfigForUseCase(session!.user.id, "text"),
const [configResult, privateBio] = await Promise.all([
resolveAiConfigOrError(() => getModelConfigForUseCase(session!.user.id, "text")),
getUserPrivateBio(session!.user.id),
]);
const model = resolveModel(config);
if (!configResult.ok) return configResult.response;
const model = resolveModel(configResult.data);
const bioContext = buildUserBioContext(privateBio);
const locale = (session!.user as { locale?: string }).locale ?? "en";
const lang = LANG[locale] ?? "English";
const { text } = await generateText({
model,
system: `You are a helpful culinary assistant. Answer questions about the following recipe concisely and accurately. If a question is not related to the recipe or cooking, politely redirect. Keep answers under 200 words. Respond in ${lang}.
const result = await withAiQuota(session!.user.id, session!.user.tier as "free" | "pro", () =>
generateText({
model,
system: `You are a helpful culinary assistant. Answer questions about the following recipe concisely and accurately. If a question is not related to the recipe or cooking, politely redirect. Keep answers under 200 words. Respond in ${lang}.
${recipeContext}${bioContext}`,
prompt: parsed.data.question,
});
prompt: parsed.data.question,
})
);
if (!result.ok) return result.response;
return NextResponse.json({ answer: text });
return NextResponse.json({ answer: result.data.text });
}
+15 -10
View File
@@ -3,6 +3,7 @@ import { z } from "zod";
import { generateObject } from "ai";
import { requireSession } from "@/lib/api-auth";
import { applyRateLimit } from "@/lib/rate-limit";
import { withAiQuota, resolveAiConfigOrError } from "@/lib/ai/ai-error";
import { getModelConfigForUseCase } from "@/lib/ai/resolve-user-key";
import { resolveModel } from "@/lib/ai/factory";
import { getUserPrivateBio, buildUserBioContext } from "@/lib/ai/user-bio";
@@ -36,11 +37,12 @@ export async function POST(req: NextRequest) {
const limited = await applyRateLimit(`rl:ai:${session!.user.id}`, 10, 60);
if (limited) return limited;
const [config, privateBio] = await Promise.all([
getModelConfigForUseCase(session!.user.id, "text"),
const [configResult, privateBio] = await Promise.all([
resolveAiConfigOrError(() => getModelConfigForUseCase(session!.user.id, "text")),
getUserPrivateBio(session!.user.id),
]);
const model = resolveModel(config);
if (!configResult.ok) return configResult.response;
const model = resolveModel(configResult.data);
const bioContext = buildUserBioContext(privateBio);
const userContext = bioContext
@@ -54,12 +56,15 @@ export async function POST(req: NextRequest) {
? `${userContext}Generate 6 diverse recipe ideas based on: "${parsed.data.prompt}". Include a mix of difficulty levels.`
: `${userContext}Generate 6 diverse, creative recipe ideas. Include different cuisines, difficulty levels, and meal types.`;
const { object } = await generateObject({
model,
schema: IdeasSchema,
system: `Respond in ${lang}.`,
prompt,
});
const result = await withAiQuota(session!.user.id, session!.user.tier as "free" | "pro", () =>
generateObject({
model,
schema: IdeasSchema,
system: `Respond in ${lang}.`,
prompt,
})
);
if (!result.ok) return result.response;
return NextResponse.json(object.ideas);
return NextResponse.json(result.data.object.ideas);
}
+4 -2
View File
@@ -4,7 +4,7 @@ import { db, recipes, eq, and, or } from "@epicure/db";
import { requireSession } from "@/lib/api-auth";
import { applyRateLimit } from "@/lib/rate-limit";
import { getDefaultProviderWithKey } from "@/lib/ai/resolve-user-key";
import { withAiQuota } from "@/lib/ai/ai-error";
import { withAiQuota, resolveAiConfigOrError } from "@/lib/ai/ai-error";
import { scaleRecipe } from "@/lib/ai/features/scale-recipe";
const Schema = z.object({
@@ -40,7 +40,9 @@ export async function POST(req: NextRequest) {
return NextResponse.json({ error: "Not found" }, { status: 404 });
}
const aiConfig = await getDefaultProviderWithKey(session!.user.id);
const configResult = await resolveAiConfigOrError(() => getDefaultProviderWithKey(session!.user.id));
if (!configResult.ok) return configResult.response;
const aiConfig = configResult.data;
const result = await withAiQuota(session!.user.id, session!.user.tier as "free" | "pro", () =>
scaleRecipe(
+9 -4
View File
@@ -1,7 +1,7 @@
import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { requireSession } from "@/lib/api-auth";
import { withAiQuota } from "@/lib/ai/ai-error";
import { withAiQuota, resolveAiConfigOrError } from "@/lib/ai/ai-error";
import { applyRateLimit } from "@/lib/rate-limit";
import { getDefaultProviderWithKey } from "@/lib/ai/resolve-user-key";
import { substituteIngredient } from "@/lib/ai/features/substitute-ingredient";
@@ -28,9 +28,14 @@ export async function POST(req: NextRequest) {
? `recipe "${parsed.data.recipeTitle}"`
: "a general recipe";
const aiConfig = parsed.data.provider
? { provider: parsed.data.provider, model: parsed.data.model }
: await getDefaultProviderWithKey(session!.user.id);
let aiConfig;
if (parsed.data.provider) {
aiConfig = { provider: parsed.data.provider, model: parsed.data.model };
} else {
const configResult = await resolveAiConfigOrError(() => getDefaultProviderWithKey(session!.user.id));
if (!configResult.ok) return configResult.response;
aiConfig = configResult.data;
}
const locale = (session!.user as { locale?: string }).locale ?? "en";
@@ -3,7 +3,7 @@ import { z } from "zod";
import { and, eq } from "@epicure/db";
import { db, recipes } from "@epicure/db";
import { requireSession } from "@/lib/api-auth";
import { withAiQuota } from "@/lib/ai/ai-error";
import { withAiQuota, resolveAiConfigOrError } from "@/lib/ai/ai-error";
import { suggestVariations } from "@/lib/ai/features/suggest-variations";
import { withUserKey } from "@/lib/ai/resolve-user-key";
import { getUserPrivateBio } from "@/lib/ai/user-bio";
@@ -38,10 +38,14 @@ export async function POST(req: NextRequest, { params }: Params) {
return NextResponse.json({ error: "Validation error", issues: parsed.error.issues }, { status: 400 });
}
const [aiConfig, privateBio] = await Promise.all([
withUserKey(session!.user.id, { provider: parsed.data.provider, model: parsed.data.model }),
const [configResult, privateBio] = await Promise.all([
resolveAiConfigOrError(() =>
withUserKey(session!.user.id, { provider: parsed.data.provider, model: parsed.data.model })
),
getUserPrivateBio(session!.user.id),
]);
if (!configResult.ok) return configResult.response;
const aiConfig = configResult.data;
const result = await withAiQuota(session!.user.id, session!.user.tier as "free" | "pro", () =>
suggestVariations(
@@ -1,6 +1,6 @@
import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { db, conversations, conversationReads, messages, eq, asc } from "@epicure/db";
import { db, conversations, conversationReads, messages, eq, and, desc, lt } from "@epicure/db";
import { requireSession } from "@/lib/api-auth";
import { applyRateLimit } from "@/lib/rate-limit";
import { isParticipant, otherParticipantId } from "@/lib/messaging";
@@ -13,7 +13,9 @@ interface RouteContext {
const Schema = z.object({ content: z.string().min(1).max(4000) });
export async function GET(_req: NextRequest, { params }: RouteContext) {
const PAGE_SIZE = 50;
export async function GET(req: NextRequest, { params }: RouteContext) {
const { session, response } = await requireSession();
if (response) return response;
const { id } = await params;
@@ -23,22 +25,42 @@ export async function GET(_req: NextRequest, { params }: RouteContext) {
return NextResponse.json({ error: "Not found" }, { status: 404 });
}
// Cursor-based pagination: fetch the page ending just before `before`
// (an ISO createdAt timestamp), newest-first, then reverse so the client
// still receives oldest-first order for the page. This avoids the old
// `asc + limit(200)` bug, which permanently hid every message past the
// 200th once a conversation grew beyond that.
const before = req.nextUrl.searchParams.get("before");
const beforeDate = before ? new Date(before) : null;
const validBefore = beforeDate && !isNaN(beforeDate.getTime()) ? beforeDate : null;
const rows = await db
.select()
.from(messages)
.where(eq(messages.conversationId, id))
.orderBy(asc(messages.createdAt))
.limit(200);
.where(
validBefore
? and(eq(messages.conversationId, id), lt(messages.createdAt, validBefore))
: eq(messages.conversationId, id)
)
.orderBy(desc(messages.createdAt))
.limit(PAGE_SIZE);
await db
.insert(conversationReads)
.values({ conversationId: id, userId: session!.user.id, lastReadAt: new Date() })
.onConflictDoUpdate({
target: [conversationReads.conversationId, conversationReads.userId],
set: { lastReadAt: new Date() },
});
const ordered = rows.slice().reverse();
const nextCursor = rows.length === PAGE_SIZE ? rows[rows.length - 1]!.createdAt.toISOString() : null;
return NextResponse.json({ messages: rows });
// Only mark the conversation read when loading the latest page, not when
// paging through history.
if (!validBefore) {
await db
.insert(conversationReads)
.values({ conversationId: id, userId: session!.user.id, lastReadAt: new Date() })
.onConflictDoUpdate({
target: [conversationReads.conversationId, conversationReads.userId],
set: { lastReadAt: new Date() },
});
}
return NextResponse.json({ messages: ordered, nextCursor });
}
export async function POST(req: NextRequest, { params }: RouteContext) {
+6 -2
View File
@@ -10,6 +10,8 @@ export async function GET(req: NextRequest) {
const { searchParams } = new URL(req.url);
const limit = Math.min(parseInt(searchParams.get("limit") ?? "20"), 50);
const offsetRaw = parseInt(searchParams.get("offset") ?? "0");
const offset = Number.isNaN(offsetRaw) ? 0 : Math.max(0, offsetRaw);
// Recipes the user has favorited, or rated 4+, define their taste profile.
const [favoritedRows, highRatedRows] = await Promise.all([
@@ -60,10 +62,12 @@ export async function GET(req: NextRequest) {
? rankForYou(candidates, preferences)
: [...candidates].sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());
const data = ranked.slice(0, limit).map(({ tags: _tags, dietaryTags: _dietaryTags, ...r }) => ({
const data = ranked.slice(offset, offset + limit).map(({ tags: _tags, dietaryTags: _dietaryTags, ...r }) => ({
...r,
createdAt: r.createdAt.toISOString(),
}));
return NextResponse.json({ data });
// `ranked` is capped to a bounded recent window (see `candidates` query above), so this
// total reflects the size of that ranked window rather than every eligible recipe.
return NextResponse.json({ data, total: ranked.length, limit, offset });
}
+37 -26
View File
@@ -1,5 +1,5 @@
import { NextRequest, NextResponse } from "next/server";
import { db, recipes, users, userFollows, eq, and, ne } from "@epicure/db";
import { db, recipes, users, userFollows, eq, and, ne, sql } from "@epicure/db";
import { requireSession } from "@/lib/api-auth";
import { desc, inArray } from "@epicure/db";
@@ -20,32 +20,43 @@ export async function GET(req: NextRequest) {
const followedIds = followedRows.map((r) => r.followingId);
if (followedIds.length === 0) {
return NextResponse.json({ data: [], limit, offset, message: "Follow some users to see their recipes here." });
return NextResponse.json({ data: [], total: 0, limit, offset, message: "Follow some users to see their recipes here." });
}
const feedRecipes = await db
.select({
id: recipes.id,
title: recipes.title,
description: recipes.description,
baseServings: recipes.baseServings,
prepMins: recipes.prepMins,
cookMins: recipes.cookMins,
difficulty: recipes.difficulty,
visibility: recipes.visibility,
createdAt: recipes.createdAt,
updatedAt: recipes.updatedAt,
authorId: recipes.authorId,
authorName: users.name,
authorUsername: users.username,
authorAvatarUrl: users.avatarUrl,
})
.from(recipes)
.innerJoin(users, eq(recipes.authorId, users.id))
.where((t) => and(inArray(t.authorId, followedIds), ne(recipes.visibility, "private")))
.orderBy(desc(recipes.createdAt))
.limit(limit)
.offset(offset);
const where = and(inArray(recipes.authorId, followedIds), ne(recipes.visibility, "private"));
return NextResponse.json({ data: feedRecipes, limit, offset });
const [feedRecipes, totalRow] = await Promise.all([
db
.select({
id: recipes.id,
title: recipes.title,
description: recipes.description,
baseServings: recipes.baseServings,
prepMins: recipes.prepMins,
cookMins: recipes.cookMins,
difficulty: recipes.difficulty,
visibility: recipes.visibility,
createdAt: recipes.createdAt,
updatedAt: recipes.updatedAt,
authorId: recipes.authorId,
authorName: users.name,
authorUsername: users.username,
authorAvatarUrl: users.avatarUrl,
})
.from(recipes)
.innerJoin(users, eq(recipes.authorId, users.id))
.where(where)
.orderBy(desc(recipes.createdAt))
.limit(limit)
.offset(offset),
db
.select({ total: sql<number>`count(*)::int` })
.from(recipes)
.innerJoin(users, eq(recipes.authorId, users.id))
.where(where),
]);
const total = totalRow[0]?.total ?? 0;
return NextResponse.json({ data: feedRecipes, total, limit, offset });
}
+44 -29
View File
@@ -3,40 +3,55 @@ import { db, recipes, users, favorites, eq, desc, sql, and, gte } from "@epicure
export async function GET(req: NextRequest) {
const { searchParams } = new URL(req.url);
const limit = Math.min(parseInt(searchParams.get("limit") ?? "20"), 50);
const limitRaw = parseInt(searchParams.get("limit") ?? "20");
const limit = Math.min(Number.isNaN(limitRaw) ? 20 : Math.max(1, limitRaw), 50);
const offsetRaw = parseInt(searchParams.get("offset") ?? "0");
const offset = Number.isNaN(offsetRaw) ? 0 : Math.max(0, offsetRaw);
const sevenDaysAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
const trending = await db
.select({
id: recipes.id,
title: recipes.title,
description: recipes.description,
baseServings: recipes.baseServings,
prepMins: recipes.prepMins,
cookMins: recipes.cookMins,
difficulty: recipes.difficulty,
visibility: recipes.visibility,
aiGenerated: recipes.aiGenerated,
createdAt: recipes.createdAt,
authorId: recipes.authorId,
authorName: users.name,
authorUsername: users.username,
authorAvatarUrl: users.avatarUrl,
favoriteCount: sql<number>`cast(count(${favorites.recipeId}) as int)`,
})
.from(recipes)
.innerJoin(users, eq(recipes.authorId, users.id))
.leftJoin(
favorites,
and(eq(favorites.recipeId, recipes.id), gte(favorites.createdAt, sevenDaysAgo))
)
.where(eq(recipes.visibility, "public"))
.groupBy(recipes.id, users.id)
.orderBy(desc(sql`count(${favorites.recipeId})`), desc(recipes.createdAt))
.limit(limit);
const [trending, totalRow] = await Promise.all([
db
.select({
id: recipes.id,
title: recipes.title,
description: recipes.description,
baseServings: recipes.baseServings,
prepMins: recipes.prepMins,
cookMins: recipes.cookMins,
difficulty: recipes.difficulty,
visibility: recipes.visibility,
aiGenerated: recipes.aiGenerated,
createdAt: recipes.createdAt,
authorId: recipes.authorId,
authorName: users.name,
authorUsername: users.username,
authorAvatarUrl: users.avatarUrl,
favoriteCount: sql<number>`cast(count(${favorites.recipeId}) as int)`,
})
.from(recipes)
.innerJoin(users, eq(recipes.authorId, users.id))
.leftJoin(
favorites,
and(eq(favorites.recipeId, recipes.id), gte(favorites.createdAt, sevenDaysAgo))
)
.where(eq(recipes.visibility, "public"))
.groupBy(recipes.id, users.id)
.orderBy(desc(sql`count(${favorites.recipeId})`), desc(recipes.createdAt))
.limit(limit)
.offset(offset),
db
.select({ total: sql<number>`count(*)::int` })
.from(recipes)
.where(eq(recipes.visibility, "public")),
]);
const total = totalRow[0]?.total ?? 0;
return NextResponse.json({
data: trending.map((r) => ({ ...r, createdAt: r.createdAt.toISOString() })),
total,
limit,
offset,
});
}
@@ -1,6 +1,6 @@
import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { db, mealPlans, mealPlanEntries, eq, and } from "@epicure/db";
import { db, mealPlans, mealPlanEntries, recipes, eq, and, or, ne } from "@epicure/db";
import { requireSession } from "@/lib/api-auth";
import { dispatchWebhook } from "@/lib/webhooks";
@@ -34,6 +34,16 @@ export async function POST(req: NextRequest, { params }: Params) {
const parsed = Schema.safeParse(body);
if (!parsed.success) return NextResponse.json({ error: "Validation error" }, { status: 400 });
if (parsed.data.recipeId) {
const recipe = await db.query.recipes.findFirst({
where: and(
eq(recipes.id, parsed.data.recipeId),
or(eq(recipes.authorId, session!.user.id), ne(recipes.visibility, "private"))
),
});
if (!recipe) return NextResponse.json({ error: "Recipe not found" }, { status: 404 });
}
const plan = await getOrCreatePlan(session!.user.id, weekStart);
// Remove existing entry for same day+mealType before inserting
@@ -103,16 +103,20 @@ export async function DELETE(req: NextRequest, { params }: Params) {
const memberId = req.nextUrl.searchParams.get("memberId");
if (!memberId) return NextResponse.json({ error: "memberId required" }, { status: 400 });
const plan = await db.query.mealPlans.findFirst({
where: and(eq(mealPlans.userId, session!.user.id), eq(mealPlans.weekStart, weekStart)),
});
if (!plan) return NextResponse.json({ error: "Not found" }, { status: 404 });
// Look up the member row first (not scoped to plans owned by the caller) —
// a member removing themselves isn't the plan owner, so scoping the plan
// lookup to `ownerId = session.user.id` would 404 before we ever reach the
// self-leave check below.
const member = await db.query.mealPlanMembers.findFirst({
where: and(eq(mealPlanMembers.id, memberId), eq(mealPlanMembers.mealPlanId, plan.id)),
where: eq(mealPlanMembers.id, memberId),
});
if (!member) return NextResponse.json({ error: "Not found" }, { status: 404 });
const plan = await db.query.mealPlans.findFirst({
where: and(eq(mealPlans.id, member.mealPlanId), eq(mealPlans.weekStart, weekStart)),
});
if (!plan) return NextResponse.json({ error: "Not found" }, { status: 404 });
const isOwner = plan.userId === session!.user.id;
const isSelf = member.userId === session!.user.id;
if (!isOwner && !isSelf) return NextResponse.json({ error: "Forbidden" }, { status: 403 });
+23 -7
View File
@@ -1,6 +1,6 @@
import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { db, pantryItems, eq, desc } from "@epicure/db";
import { db, pantryItems, eq, desc, sql } from "@epicure/db";
import { requireSession } from "@/lib/api-auth";
const Schema = z.object({
@@ -10,16 +10,32 @@ const Schema = z.object({
expiresAt: z.string().datetime().optional(),
});
export async function GET(_req: NextRequest) {
export async function GET(req: NextRequest) {
const { session, response } = await requireSession();
if (response) return response;
const items = await db.query.pantryItems.findMany({
where: eq(pantryItems.userId, session!.user.id),
orderBy: desc(pantryItems.createdAt),
});
const { searchParams } = req.nextUrl;
const limitRaw = parseInt(searchParams.get("limit") ?? "50");
const limit = Math.min(Number.isNaN(limitRaw) ? 50 : Math.max(1, limitRaw), 100);
const offsetRaw = parseInt(searchParams.get("offset") ?? "0");
const offset = Number.isNaN(offsetRaw) ? 0 : Math.max(0, offsetRaw);
return NextResponse.json(items);
const [items, totalRow] = await Promise.all([
db.query.pantryItems.findMany({
where: eq(pantryItems.userId, session!.user.id),
orderBy: desc(pantryItems.createdAt),
limit,
offset,
}),
db
.select({ total: sql<number>`count(*)::int` })
.from(pantryItems)
.where(eq(pantryItems.userId, session!.user.id)),
]);
const total = totalRow[0]?.total ?? 0;
return NextResponse.json({ data: items, total, limit, offset });
}
export async function POST(req: NextRequest) {
@@ -1,6 +1,6 @@
import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { db, recipes, comments, users, userBlocks, eq, and, inArray } from "@epicure/db";
import { db, recipes, comments, users, userBlocks, eq, and, inArray, isNull, sql } from "@epicure/db";
import { requireSession } from "@/lib/api-auth";
import { applyRateLimit } from "@/lib/rate-limit";
import { dispatchWebhook } from "@/lib/webhooks";
@@ -16,7 +16,19 @@ const Schema = z.object({
type Params = { params: Promise<{ id: string }> };
export async function GET(_req: NextRequest, { params }: Params) {
const COMMENT_COLUMNS = {
id: comments.id,
content: comments.content,
parentId: comments.parentId,
createdAt: comments.createdAt,
updatedAt: comments.updatedAt,
userId: comments.userId,
userName: users.name,
userUsername: users.username,
userAvatarUrl: users.avatarUrl,
} as const;
export async function GET(req: NextRequest, { params }: Params) {
const { id } = await params;
const recipe = await db.query.recipes.findFirst({ where: eq(recipes.id, id) });
if (!recipe || recipe.visibility === "private") {
@@ -25,32 +37,55 @@ export async function GET(_req: NextRequest, { params }: Params) {
const { session } = await requireSession();
const rows = await db
.select({
id: comments.id,
content: comments.content,
parentId: comments.parentId,
createdAt: comments.createdAt,
updatedAt: comments.updatedAt,
userId: comments.userId,
userName: users.name,
userUsername: users.username,
userAvatarUrl: users.avatarUrl,
})
.from(comments)
.innerJoin(users, eq(comments.userId, users.id))
.where(eq(comments.recipeId, id))
.orderBy(comments.createdAt);
const { searchParams } = req.nextUrl;
const limitRaw = parseInt(searchParams.get("limit") ?? "20");
const limit = Math.min(Number.isNaN(limitRaw) ? 20 : Math.max(1, limitRaw), 50);
const offsetRaw = parseInt(searchParams.get("offset") ?? "0");
const offset = Number.isNaN(offsetRaw) ? 0 : Math.max(0, offsetRaw);
if (!session) return NextResponse.json(rows);
// Paginate top-level comments; replies to a loaded top-level comment are always
// fetched alongside it so threads render complete (threads are typically small).
const [topLevel, totalRow] = await Promise.all([
db
.select(COMMENT_COLUMNS)
.from(comments)
.innerJoin(users, eq(comments.userId, users.id))
.where(and(eq(comments.recipeId, id), isNull(comments.parentId)))
.orderBy(comments.createdAt)
.limit(limit)
.offset(offset),
db
.select({ total: sql<number>`count(*)::int` })
.from(comments)
.where(and(eq(comments.recipeId, id), isNull(comments.parentId))),
]);
const blocked = await db
.select({ blockedId: userBlocks.blockedId })
.from(userBlocks)
.where(eq(userBlocks.blockerId, session.user.id));
const blockedIds = new Set(blocked.map((b) => b.blockedId));
const total = totalRow[0]?.total ?? 0;
const topLevelIds = topLevel.map((c) => c.id);
return NextResponse.json(rows.filter((r) => !blockedIds.has(r.userId)));
const replies = topLevelIds.length > 0
? await db
.select(COMMENT_COLUMNS)
.from(comments)
.innerJoin(users, eq(comments.userId, users.id))
.where(inArray(comments.parentId, topLevelIds))
.orderBy(comments.createdAt)
: [];
const rows = [...topLevel, ...replies];
const data = session
? await (async () => {
const blocked = await db
.select({ blockedId: userBlocks.blockedId })
.from(userBlocks)
.where(eq(userBlocks.blockerId, session.user.id));
const blockedIds = new Set(blocked.map((b) => b.blockedId));
return rows.filter((r) => !blockedIds.has(r.userId));
})()
: rows;
return NextResponse.json({ data, total, limit, offset });
}
export async function POST(req: NextRequest, { params }: Params) {
@@ -2,6 +2,8 @@ import { NextRequest, NextResponse } from "next/server";
import { db, recipes, recipeIngredients } from "@epicure/db";
import { eq, and, or, ne } from "@epicure/db";
import { requireSession } from "@/lib/api-auth";
import { applyRateLimit } from "@/lib/rate-limit";
import { withAiQuota } from "@/lib/ai/ai-error";
import { estimateNutrition } from "@/lib/ai/features/estimate-nutrition";
type Params = { params: Promise<{ id: string }> };
@@ -31,14 +33,12 @@ export async function POST(_req: NextRequest, { params }: Params) {
if (response) return response;
const { id } = await params;
const limited = await applyRateLimit(`rl:ai:${session!.user.id}`, 10, 60);
if (limited) return limited;
// Only the recipe author may trigger a (paid) nutrition estimate
const recipe = await db.query.recipes.findFirst({
where: and(
eq(recipes.id, id),
or(
eq(recipes.authorId, session!.user.id),
ne(recipes.visibility, "private")
)
),
where: and(eq(recipes.id, id), eq(recipes.authorId, session!.user.id)),
with: {
ingredients: { orderBy: (t, { asc }) => asc(t.order) },
},
@@ -46,17 +46,20 @@ export async function POST(_req: NextRequest, { params }: Params) {
if (!recipe) return NextResponse.json({ error: "Not found" }, { status: 404 });
const result = await estimateNutrition({
title: recipe.title,
baseServings: recipe.baseServings,
ingredients: recipe.ingredients.map((i) => ({
rawName: i.rawName,
quantity: i.quantity,
unit: i.unit,
})),
});
const result = await withAiQuota(session!.user.id, session!.user.tier as "free" | "pro", () =>
estimateNutrition({
title: recipe.title,
baseServings: recipe.baseServings,
ingredients: recipe.ingredients.map((i) => ({
rawName: i.rawName,
quantity: i.quantity,
unit: i.unit,
})),
})
);
if (!result.ok) return result.response;
await db.update(recipes).set({ nutritionData: result }).where(and(eq(recipes.id, id), eq(recipes.authorId, session!.user.id)));
await db.update(recipes).set({ nutritionData: result.data }).where(and(eq(recipes.id, id), eq(recipes.authorId, session!.user.id)));
return NextResponse.json({ nutrition: result });
return NextResponse.json({ nutrition: result.data });
}
+64 -37
View File
@@ -1,8 +1,9 @@
import { NextRequest, NextResponse } from "next/server";
import { db, recipes, recipeIngredients, recipeSteps, recipeSnapshots } from "@epicure/db";
import { eq, and, max } from "@epicure/db";
import { db, recipes, recipeIngredients, recipeSteps, recipeSnapshots, ratings } from "@epicure/db";
import { eq, and, max, isNotNull } from "@epicure/db";
import { z } from "zod";
import { requireSessionOrApiKey } from "@/lib/api-auth";
import { deleteObject } from "@/lib/storage";
import { dispatchWebhook } from "@/lib/webhooks";
import { parseQuantity } from "@/lib/parse-quantity";
@@ -69,41 +70,6 @@ export async function PUT(req: NextRequest, { params }: Params) {
});
if (!existing) return NextResponse.json({ error: "Not found" }, { status: 404 });
// Create a snapshot of the current state before updating
const [maxVersionRow] = await db
.select({ v: max(recipeSnapshots.version) })
.from(recipeSnapshots)
.where(eq(recipeSnapshots.recipeId, id));
const nextVersion = (maxVersionRow?.v ?? 0) + 1;
await db.insert(recipeSnapshots).values({
id: crypto.randomUUID(),
recipeId: id,
authorId: session!.user.id,
version: nextVersion,
title: existing.title,
snapshotData: {
title: existing.title,
description: existing.description,
baseServings: existing.baseServings,
difficulty: existing.difficulty,
prepMins: existing.prepMins,
cookMins: existing.cookMins,
dietaryTags: existing.dietaryTags ?? {},
ingredients: existing.ingredients.map((i) => ({
rawName: i.rawName,
quantity: i.quantity,
unit: i.unit,
note: i.note,
order: i.order,
})),
steps: existing.steps.map((s) => ({
instruction: s.instruction,
timerSeconds: s.timerSeconds,
order: s.order,
})),
},
});
const body = await req.json() as unknown;
const parsed = UpdateRecipeSchema.safeParse(body);
if (!parsed.success) {
@@ -113,6 +79,41 @@ export async function PUT(req: NextRequest, { params }: Params) {
const data = parsed.data;
await db.transaction(async (tx) => {
// Create a snapshot of the current state before updating
const [maxVersionRow] = await tx
.select({ v: max(recipeSnapshots.version) })
.from(recipeSnapshots)
.where(eq(recipeSnapshots.recipeId, id));
const nextVersion = (maxVersionRow?.v ?? 0) + 1;
await tx.insert(recipeSnapshots).values({
id: crypto.randomUUID(),
recipeId: id,
authorId: session!.user.id,
version: nextVersion,
title: existing.title,
snapshotData: {
title: existing.title,
description: existing.description,
baseServings: existing.baseServings,
difficulty: existing.difficulty,
prepMins: existing.prepMins,
cookMins: existing.cookMins,
dietaryTags: existing.dietaryTags ?? {},
ingredients: existing.ingredients.map((i) => ({
rawName: i.rawName,
quantity: i.quantity,
unit: i.unit,
note: i.note,
order: i.order,
})),
steps: existing.steps.map((s) => ({
instruction: s.instruction,
timerSeconds: s.timerSeconds,
order: s.order,
})),
},
});
const updates: Partial<typeof recipes.$inferInsert> = { updatedAt: new Date() };
if (data.title !== undefined) updates.title = data.title;
if (data.description !== undefined) updates.description = data.description;
@@ -161,6 +162,9 @@ export async function PUT(req: NextRequest, { params }: Params) {
const updated = await getOwnedRecipe(id, session!.user.id);
void dispatchWebhook(session!.user.id, "recipe.updated", { id, title: updated?.title });
if (existing.visibility === "private" && data.visibility === "public") {
void dispatchWebhook(session!.user.id, "recipe.published", { id, title: updated?.title });
}
return NextResponse.json(updated);
}
@@ -171,10 +175,33 @@ export async function DELETE(req: NextRequest, { params }: Params) {
const existing = await db.query.recipes.findFirst({
where: and(eq(recipes.id, id), eq(recipes.authorId, session!.user.id)),
with: { photos: true },
});
if (!existing) return NextResponse.json({ error: "Not found" }, { status: 404 });
// Collect storage keys before the cascade delete removes the rows.
// recipeSteps.photoUrl stores a full URL rather than a storage key, so it
// is intentionally not deleted here — only objects this app stored by key.
const reviewPhotos = await db
.select({ photoKey: ratings.photoKey })
.from(ratings)
.where(and(eq(ratings.recipeId, id), isNotNull(ratings.photoKey)));
const storageKeys = [
...existing.photos.map((p) => p.storageKey),
...reviewPhotos.map((r) => r.photoKey).filter((k): k is string => k !== null),
];
await db.delete(recipes).where(eq(recipes.id, id));
// Best-effort object cleanup: a storage failure must not fail the response.
for (const key of storageKeys) {
try {
await deleteObject(key);
} catch (err) {
console.error(`Failed to delete storage object ${key} for recipe ${id}`, err);
}
}
void dispatchWebhook(session!.user.id, "recipe.deleted", { id });
return new NextResponse(null, { status: 204 });
}
@@ -55,41 +55,6 @@ export async function POST(req: NextRequest, { params }: Params) {
});
if (!snapshot) return NextResponse.json({ error: "Snapshot not found" }, { status: 404 });
// Create a snapshot of the current state before restoring
const [maxVersionRow] = await db
.select({ v: max(recipeSnapshots.version) })
.from(recipeSnapshots)
.where(eq(recipeSnapshots.recipeId, id));
const nextVersion = (maxVersionRow?.v ?? 0) + 1;
await db.insert(recipeSnapshots).values({
id: crypto.randomUUID(),
recipeId: id,
authorId: session!.user.id,
version: nextVersion,
title: currentRecipe.title,
snapshotData: {
title: currentRecipe.title,
description: currentRecipe.description,
baseServings: currentRecipe.baseServings,
difficulty: currentRecipe.difficulty,
prepMins: currentRecipe.prepMins,
cookMins: currentRecipe.cookMins,
dietaryTags: currentRecipe.dietaryTags ?? {},
ingredients: currentRecipe.ingredients.map((i) => ({
rawName: i.rawName,
quantity: i.quantity,
unit: i.unit,
note: i.note,
order: i.order,
})),
steps: currentRecipe.steps.map((s) => ({
instruction: s.instruction,
timerSeconds: s.timerSeconds,
order: s.order,
})),
},
});
// Restore the recipe from the snapshot
const data = snapshot.snapshotData as {
title: string;
+5 -2
View File
@@ -66,11 +66,14 @@ export async function GET(req: NextRequest) {
: [];
// --- Build WHERE conditions ---
// Escape ilike wildcard chars (% and _) so user input like "100%" is matched literally.
const escapedQ = q.replace(/[\\%_]/g, (c) => `\\${c}`);
const conditions = [
eq(recipes.visibility, "public"),
or(
ilike(recipes.title, `%${q}%`),
ilike(recipes.description, `%${q}%`)
ilike(recipes.title, `%${escapedQ}%`),
ilike(recipes.description, `%${escapedQ}%`)
)!,
];
@@ -1,10 +1,15 @@
import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { db, shoppingListItems, eq, and } from "@epicure/db";
import { requireSession } from "@/lib/api-auth";
import { getShoppingListAccess, canWriteShoppingList } from "@/lib/shopping-list-access";
type Params = { params: Promise<{ id: string; itemId: string }> };
const UpdateItemSchema = z.object({
checked: z.boolean().optional(),
});
export async function PUT(req: NextRequest, { params }: Params) {
const { session, response } = await requireSession();
if (response) return response;
@@ -14,9 +19,13 @@ export async function PUT(req: NextRequest, { params }: Params) {
if (!access) return NextResponse.json({ error: "Not found" }, { status: 404 });
if (!canWriteShoppingList(access.role)) return NextResponse.json({ error: "Forbidden" }, { status: 403 });
const body = await req.json() as { checked?: boolean };
const parsed = UpdateItemSchema.safeParse(await req.json());
if (!parsed.success) {
return NextResponse.json({ error: "Validation error", issues: parsed.error.issues }, { status: 400 });
}
await db.update(shoppingListItems)
.set({ checked: body.checked ?? false })
.set({ checked: parsed.data.checked ?? false })
.where(and(eq(shoppingListItems.id, itemId), eq(shoppingListItems.listId, id)));
return NextResponse.json({ updated: true });
+14 -1
View File
@@ -3,9 +3,11 @@ import { z } from "zod";
import { requireSession } from "@/lib/api-auth";
import { createPresignedUploadUrl } from "@/lib/storage";
import { db, recipes, eq, and } from "@epicure/db";
import { checkAndIncrementTierLimit, TierLimitError } from "@/lib/tiers";
const ALLOWED_TYPES = ["image/jpeg", "image/png", "image/webp", "image/avif"] as const;
type AllowedType = (typeof ALLOWED_TYPES)[number];
const MAX_FILE_SIZE = 10 * 1024 * 1024;
const Schema = z.object({
contentType: z.string().refine((t): t is AllowedType => (ALLOWED_TYPES as readonly string[]).includes(t), {
@@ -13,6 +15,7 @@ const Schema = z.object({
}),
recipeId: z.string().uuid(),
purpose: z.enum(["recipe", "review"]).default("recipe"),
fileSize: z.number().int().positive().max(MAX_FILE_SIZE, "File exceeds 10MB limit"),
});
export async function POST(req: NextRequest) {
@@ -25,7 +28,7 @@ export async function POST(req: NextRequest) {
return NextResponse.json({ error: "Validation error", issues: parsed.error.issues }, { status: 400 });
}
const { recipeId, contentType, purpose } = parsed.data;
const { recipeId, contentType, purpose, fileSize } = parsed.data;
const recipe = await db.query.recipes.findFirst({
where: purpose === "recipe"
? and(eq(recipes.id, recipeId), eq(recipes.authorId, session!.user.id))
@@ -37,6 +40,16 @@ export async function POST(req: NextRequest) {
return NextResponse.json({ error: "Not found" }, { status: 404 });
}
try {
const sizeMb = Math.ceil(fileSize / (1024 * 1024));
await checkAndIncrementTierLimit(session!.user.id, session!.user.tier as "free" | "pro", "storage", sizeMb);
} catch (err) {
if (err instanceof TierLimitError) {
return NextResponse.json({ error: "Storage limit reached for your tier" }, { status: 403 });
}
throw err;
}
const ext = contentType.split("/")[1] ?? "jpg";
const folder = purpose === "review" ? "reviews" : "photos";
const key = `recipes/${recipeId}/${folder}/${session!.user.id}-${crypto.randomUUID()}.${ext}`;
+2 -3
View File
@@ -3,12 +3,11 @@ import { z } from "zod";
import { db, webhooks, eq, and } from "@epicure/db";
import { requireSession } from "@/lib/api-auth";
import { validateWebhookUrl } from "@/lib/validate-webhook-url";
const VALID_EVENTS = ["recipe.created", "recipe.updated", "recipe.published", "recipe.deleted"] as const;
import { WEBHOOK_EVENTS } from "@/lib/webhooks";
const UpdateWebhookBody = z.object({
url: z.string().min(1).max(2048).optional(),
events: z.array(z.enum(VALID_EVENTS)).optional(),
events: z.array(z.enum(WEBHOOK_EVENTS)).optional(),
active: z.boolean().optional(),
});
+3 -4
View File
@@ -4,17 +4,16 @@ import { z } from "zod";
import { db, webhooks, eq } from "@epicure/db";
import { requireSession } from "@/lib/api-auth";
import { validateWebhookUrl } from "@/lib/validate-webhook-url";
const VALID_EVENTS = ["recipe.created", "recipe.updated", "recipe.published", "recipe.deleted"] as const;
import { WEBHOOK_EVENTS } from "@/lib/webhooks";
const CreateWebhookBody = z.object({
url: z.string().min(1).max(2048),
events: z.array(z.enum(VALID_EVENTS)).default([]),
events: z.array(z.enum(WEBHOOK_EVENTS)).default([]),
});
const UpdateWebhookBody = z.object({
url: z.string().min(1).max(2048).optional(),
events: z.array(z.enum(VALID_EVENTS)).optional(),
events: z.array(z.enum(WEBHOOK_EVENTS)).optional(),
active: z.boolean().optional(),
});
+20 -2
View File
@@ -1,6 +1,6 @@
import { NextRequest, NextResponse } from "next/server";
import crypto from "node:crypto";
import { db, users, eq } from "@epicure/db";
import { db, users, processedStripeEvents, eq } from "@epicure/db";
// Stripe webhook handler — verifies stripe-signature header using HMAC-SHA256.
// Handles:
@@ -68,13 +68,31 @@ export async function POST(req: NextRequest) {
return NextResponse.json({ error: "Invalid signature" }, { status: 400 });
}
let event: { type: string; data: { object: Record<string, unknown> } };
let event: { id: string; type: string; data: { object: Record<string, unknown> } };
try {
event = JSON.parse(body) as typeof event;
} catch {
return NextResponse.json({ error: "Invalid JSON" }, { status: 400 });
}
if (!event.id) {
return NextResponse.json({ error: "Missing event id" }, { status: 400 });
}
// Dedup: Stripe may redeliver the same event within its retry/tolerance
// window. Record the event id before processing; if it's already been
// recorded, skip processing (but still ack with 200 so Stripe stops
// retrying).
const [inserted] = await db
.insert(processedStripeEvents)
.values({ id: event.id, type: event.type })
.onConflictDoNothing()
.returning({ id: processedStripeEvents.id });
if (!inserted) {
return NextResponse.json({ received: true, duplicate: true });
}
switch (event.type) {
case "checkout.session.completed": {
// client_reference_id is set to our internal userId when the Checkout Session is created.
+50
View File
@@ -0,0 +1,50 @@
"use client";
import { useEffect } from "react";
export default function RootError({
error,
reset,
}: {
error: Error & { digest?: string };
reset: () => void;
}) {
useEffect(() => {
console.error(error);
}, [error]);
return (
<div
style={{
display: "flex",
flexDirection: "column",
alignItems: "center",
justifyContent: "center",
gap: "1rem",
minHeight: "60vh",
padding: "2rem",
textAlign: "center",
fontFamily: "system-ui, sans-serif",
}}
>
<h2 style={{ fontSize: "1.25rem", fontWeight: 600 }}>Something went wrong</h2>
<p style={{ color: "#666", maxWidth: "28rem" }}>
An unexpected error occurred. Please try again.
</p>
<button
onClick={() => reset()}
style={{
padding: "0.5rem 1rem",
borderRadius: "0.5rem",
border: "1px solid #ccc",
background: "#111",
color: "#fff",
cursor: "pointer",
fontSize: "0.875rem",
}}
>
Try again
</button>
</div>
);
}
+35
View File
@@ -0,0 +1,35 @@
export default function RootNotFound() {
return (
<div
style={{
display: "flex",
flexDirection: "column",
alignItems: "center",
justifyContent: "center",
gap: "1rem",
minHeight: "60vh",
padding: "2rem",
textAlign: "center",
fontFamily: "system-ui, sans-serif",
}}
>
<h1 style={{ fontSize: "1.5rem", fontWeight: 700 }}>Page not found</h1>
<p style={{ color: "#666", maxWidth: "28rem" }}>
The page you&apos;re looking for doesn&apos;t exist or may have been moved.
</p>
<a
href="/"
style={{
padding: "0.5rem 1rem",
borderRadius: "0.5rem",
background: "#111",
color: "#fff",
textDecoration: "none",
fontSize: "0.875rem",
}}
>
Back home
</a>
</div>
);
}
+3 -2
View File
@@ -1,4 +1,5 @@
import type { Metadata } from "next";
import Image from "next/image";
import Script from "next/script";
import { notFound } from "next/navigation";
import { headers } from "next/headers";
@@ -124,8 +125,8 @@ export default async function PublicRecipePage({ params }: Params) {
</div>
{cover && (
<div className="aspect-video overflow-hidden rounded-xl bg-muted">
<img src={getPublicUrl(cover.storageKey)} alt={recipe.title} className="w-full h-full object-cover" />
<div className="relative aspect-video overflow-hidden rounded-xl bg-muted">
<Image src={getPublicUrl(cover.storageKey)} alt={recipe.title} fill className="object-cover" />
</div>
)}