feat: per-category email prefs, admin ops webhooks, per-user feature toggles (v0.61.0)

- Notification email preferences: every push category (follow, comment,
  reply, reaction, rating, mention, leftoverExpiring, shoppingList) now has
  an independent email toggle, plus a Weekly Digest toggle. Previously email
  sent unconditionally whenever the recipient had one; now gated the same
  way push already was. The weekly-digest cron route excludes opted-out
  users.

- Admin-only site-wide webhooks (Admin → Webhooks): new signups, support
  tickets, and reports filed can now fire an HMAC-signed HTTP webhook
  (Slack/Discord/ops alerting), independent of the existing per-user
  webhooks (which stay scoped to a user's own recipe/meal-plan/shopping-list
  events). Signing/delivery logic factored into lib/webhook-delivery.ts and
  shared by both dispatchers instead of duplicated.

- Settings → Features: users can hide Nutrition, Pantry, Meal Plan,
  Shopping Lists, Collections, or Messages from their own nav. Purely
  cosmetic — hidden pages stay reachable by direct link, nothing is
  access-restricted.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
Arnaud
2026-07-20 23:07:28 +02:00
parent cced962bff
commit c5e1643d39
40 changed files with 18383 additions and 79 deletions
@@ -0,0 +1,24 @@
import type { Metadata } from "next";
import { headers } from "next/headers";
import { auth } from "@/lib/auth/server";
import { FeatureTogglesForm } from "@/components/settings/feature-toggles-form";
import { getMessages } from "@/lib/i18n/server";
export const metadata: Metadata = {};
export default async function FeaturesSettingsPage() {
const session = await auth.api.getSession({ headers: await headers() });
const m = getMessages((session?.user as { locale?: string })?.locale);
return (
<section className="rounded-xl border p-6 space-y-4">
<div>
<h2 className="font-semibold text-lg">{m.settingsForm.featureToggles.title}</h2>
<p className="text-sm text-muted-foreground mt-1">
{m.settingsForm.featureToggles.description}
</p>
</div>
<FeatureTogglesForm />
</section>
);
}
+2 -1
View File
@@ -3,7 +3,7 @@ import { headers } from "next/headers";
import { auth } from "@/lib/auth/server";
import { db, users, eq } from "@epicure/db";
import Link from "next/link";
import { Shield, Users, BookOpen, Settings, BarChart3, ClipboardList, HardDrive, Bot, ArrowLeft, Gauge, Mail, Flag, History, LifeBuoy, TrendingUp } from "lucide-react";
import { Shield, Users, BookOpen, Settings, BarChart3, ClipboardList, HardDrive, Bot, ArrowLeft, Gauge, Mail, Flag, History, LifeBuoy, TrendingUp, Webhook } from "lucide-react";
import { cn } from "@/lib/utils";
const adminNav = [
@@ -15,6 +15,7 @@ const adminNav = [
{ href: "/admin/reports", label: "Reports", icon: Flag },
{ href: "/admin/support", label: "Support", icon: LifeBuoy },
{ href: "/admin/tiers", label: "Tier Limits", icon: Gauge },
{ href: "/admin/webhooks", label: "Webhooks", icon: Webhook },
{ href: "/admin/audit-logs", label: "Audit Logs", icon: ClipboardList },
{ href: "/admin/storage", label: "Storage", icon: HardDrive },
{ href: "/admin/ai-config", label: "AI Config", icon: Bot },
+31
View File
@@ -0,0 +1,31 @@
import type { Metadata } from "next";
import { db, adminWebhooks } from "@epicure/db";
import { AdminWebhooksManager } from "@/components/admin/admin-webhooks-manager";
export const metadata: Metadata = {};
export default async function AdminWebhooksPage() {
const rows = await db
.select({
id: adminWebhooks.id,
url: adminWebhooks.url,
events: adminWebhooks.events,
active: adminWebhooks.active,
createdAt: adminWebhooks.createdAt,
})
.from(adminWebhooks);
const webhooks = rows.map((w) => ({ ...w, createdAt: w.createdAt.toISOString() }));
return (
<div className="space-y-6">
<div>
<h1 className="text-2xl font-bold tracking-tight">Webhooks</h1>
<p className="text-muted-foreground text-sm mt-1">
Site-wide ops events (new signups, support tickets, reports) deliver to any HTTP endpoint (Slack/Discord incoming webhook, internal alerting, etc). Fires regardless of who&apos;s involved, unlike the per-user webhooks under Settings.
</p>
</div>
<AdminWebhooksManager initialWebhooks={webhooks} />
</div>
);
}
@@ -8,6 +8,7 @@ import {
ratings,
userFollows,
favorites,
userNotificationPrefs,
eq,
and,
gte,
@@ -21,10 +22,11 @@ import { sendEmail, weeklyDigestHtml } from "@/lib/email";
// schedule (see compose.prod.yml). Not part of the public API surface;
// protected by a shared secret rather than user auth.
//
// Computes, for every user: new followers / new comments / new ratings on
// their recipes in the last 7 days, plus a site-wide top-3 trending list, and
// emails a summary. Sends to all users (all users have a non-null email) —
// there's no per-user opt-out preference yet; out of scope for this pass.
// Computes, for every opted-in user: new followers / new comments / new
// ratings on their recipes in the last 7 days, plus a site-wide top-3
// trending list, and emails a summary. Excludes users who turned off
// "Weekly digest" in Settings → Notifications (userNotificationPrefs.weeklyDigestEmail,
// default true — no row means opted in).
const CHUNK_SIZE = 20;
@@ -56,8 +58,12 @@ export async function POST(req: NextRequest) {
const weekAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
const baseUrl = process.env["BETTER_AUTH_URL"] ?? "http://localhost:3000";
const [allUsers, followerRows, commentRows, ratingRows, trending] = await Promise.all([
const [allUsers, optedOutRows, followerRows, commentRows, ratingRows, trending] = await Promise.all([
db.select({ id: users.id, email: users.email }).from(users),
db
.select({ userId: userNotificationPrefs.userId })
.from(userNotificationPrefs)
.where(eq(userNotificationPrefs.weeklyDigestEmail, false)),
db
.select({ userId: userFollows.followingId, n: count() })
.from(userFollows)
@@ -92,6 +98,9 @@ export async function POST(req: NextRequest) {
.limit(3),
]);
const optedOut = new Set(optedOutRows.map((r) => r.userId));
const recipients = allUsers.filter((u) => !optedOut.has(u.id));
const followerMap = new Map(followerRows.map((r) => [r.userId, r.n]));
const commentMap = new Map(commentRows.map((r) => [r.userId, r.n]));
const ratingMap = new Map(ratingRows.map((r) => [r.userId, r.n]));
@@ -100,7 +109,7 @@ export async function POST(req: NextRequest) {
let sent = 0;
let failed = 0;
for (const batch of chunk(allUsers, CHUNK_SIZE)) {
for (const batch of chunk(recipients, CHUNK_SIZE)) {
const results = await Promise.allSettled(
batch.map((user) => {
const newFollowers = followerMap.get(user.id) ?? 0;
@@ -127,5 +136,5 @@ export async function POST(req: NextRequest) {
}
}
return NextResponse.json({ ok: true, totalUsers: allUsers.length, sent, failed });
return NextResponse.json({ ok: true, totalUsers: allUsers.length, optedOut: optedOut.size, sent, failed });
}
@@ -0,0 +1,24 @@
import { NextRequest, NextResponse } from "next/server";
import { db, adminWebhooks, adminWebhookDeliveries, eq, desc } from "@epicure/db";
import { requireAdmin } from "@/lib/api-auth";
type Params = { params: Promise<{ id: string }> };
export async function GET(_req: NextRequest, { params }: Params) {
const { response } = await requireAdmin();
if (response) return response;
const { id } = await params;
const hook = await db.query.adminWebhooks.findFirst({ where: eq(adminWebhooks.id, id), columns: { id: true } });
if (!hook) return NextResponse.json({ error: "Not found" }, { status: 404 });
const deliveries = await db
.select()
.from(adminWebhookDeliveries)
.where(eq(adminWebhookDeliveries.webhookId, id))
.orderBy(desc(adminWebhookDeliveries.createdAt))
.limit(20);
return NextResponse.json(deliveries);
}
@@ -0,0 +1,31 @@
import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { db, adminWebhooks, adminWebhookDeliveries, eq, and } from "@epicure/db";
import { requireAdmin } from "@/lib/api-auth";
import { dispatchAdminWebhook, type AdminWebhookEvent } from "@/lib/admin-webhooks";
const Schema = z.object({ deliveryId: z.string().uuid() });
type Params = { params: Promise<{ id: string }> };
export async function POST(req: NextRequest, { params }: Params) {
const { response } = await requireAdmin();
if (response) return response;
const { id } = await params;
const hook = await db.query.adminWebhooks.findFirst({ where: eq(adminWebhooks.id, id), columns: { id: true } });
if (!hook) return NextResponse.json({ error: "Not found" }, { status: 404 });
const body = Schema.safeParse(await req.json());
if (!body.success) return NextResponse.json({ error: "Validation error", issues: body.error.issues }, { status: 400 });
const delivery = await db.query.adminWebhookDeliveries.findFirst({
where: and(eq(adminWebhookDeliveries.id, body.data.deliveryId), eq(adminWebhookDeliveries.webhookId, id)),
});
if (!delivery) return NextResponse.json({ error: "Delivery not found" }, { status: 404 });
void dispatchAdminWebhook(delivery.event as AdminWebhookEvent, (delivery.payload ?? {}) as object);
return NextResponse.json({ ok: true });
}
@@ -0,0 +1,73 @@
import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { db, adminWebhooks, eq } from "@epicure/db";
import { requireAdmin } from "@/lib/api-auth";
import { validateWebhookUrl } from "@/lib/validate-webhook-url";
import { ADMIN_WEBHOOK_EVENTS } from "@/lib/admin-webhooks";
const UpdateWebhookBody = z.object({
url: z.string().min(1).max(2048).optional(),
events: z.array(z.enum(ADMIN_WEBHOOK_EVENTS)).optional(),
active: z.boolean().optional(),
});
type Params = { params: Promise<{ id: string }> };
export async function DELETE(_req: NextRequest, { params }: Params) {
const { response } = await requireAdmin();
if (response) return response;
const { id } = await params;
const existing = await db.select({ id: adminWebhooks.id }).from(adminWebhooks).where(eq(adminWebhooks.id, id)).limit(1);
if (existing.length === 0) return NextResponse.json({ error: "Not found" }, { status: 404 });
await db.delete(adminWebhooks).where(eq(adminWebhooks.id, id));
return new NextResponse(null, { status: 204 });
}
export async function PATCH(req: NextRequest, { params }: Params) {
const { response } = await requireAdmin();
if (response) return response;
const { id } = await params;
const existing = await db.select({ id: adminWebhooks.id }).from(adminWebhooks).where(eq(adminWebhooks.id, id)).limit(1);
if (existing.length === 0) return NextResponse.json({ error: "Not found" }, { status: 404 });
const body = await req.json() as unknown;
const parsed = UpdateWebhookBody.safeParse(body);
if (!parsed.success) {
return NextResponse.json({ error: "Validation error", issues: parsed.error.issues }, { status: 400 });
}
if (parsed.data.url) {
const ssrfError = await validateWebhookUrl(parsed.data.url);
if (ssrfError) return NextResponse.json({ error: ssrfError }, { status: 400 });
}
const updates: Partial<{ url: string; events: string[]; active: boolean }> = {};
if (parsed.data.url !== undefined) updates.url = parsed.data.url;
if (parsed.data.events !== undefined) updates.events = parsed.data.events;
if (parsed.data.active !== undefined) updates.active = parsed.data.active;
if (Object.keys(updates).length === 0) {
return NextResponse.json({ error: "No fields to update" }, { status: 400 });
}
await db.update(adminWebhooks).set(updates).where(eq(adminWebhooks.id, id));
const updated = await db
.select({
id: adminWebhooks.id,
url: adminWebhooks.url,
events: adminWebhooks.events,
active: adminWebhooks.active,
createdAt: adminWebhooks.createdAt,
})
.from(adminWebhooks)
.where(eq(adminWebhooks.id, id))
.limit(1);
return NextResponse.json(updated[0]);
}
@@ -0,0 +1,65 @@
import { NextRequest, NextResponse } from "next/server";
import crypto from "node:crypto";
import { z } from "zod";
import { db, adminWebhooks } from "@epicure/db";
import { requireAdmin } from "@/lib/api-auth";
import { validateWebhookUrl } from "@/lib/validate-webhook-url";
import { ADMIN_WEBHOOK_EVENTS } from "@/lib/admin-webhooks";
import { encrypt } from "@/lib/encrypt";
const CreateWebhookBody = z.object({
url: z.string().min(1).max(2048),
events: z.array(z.enum(ADMIN_WEBHOOK_EVENTS)).default([]),
});
export async function GET() {
const { response } = await requireAdmin();
if (response) return response;
const rows = await db
.select({
id: adminWebhooks.id,
url: adminWebhooks.url,
events: adminWebhooks.events,
active: adminWebhooks.active,
createdAt: adminWebhooks.createdAt,
})
.from(adminWebhooks);
return NextResponse.json(rows);
}
export async function POST(req: NextRequest) {
const { session, response } = await requireAdmin();
if (response) return response;
const body = await req.json() as unknown;
const parsed = CreateWebhookBody.safeParse(body);
if (!parsed.success) {
return NextResponse.json({ error: "Validation error", issues: parsed.error.issues }, { status: 400 });
}
const ssrfError = await validateWebhookUrl(parsed.data.url);
if (ssrfError) {
return NextResponse.json({ error: ssrfError }, { status: 400 });
}
const secret = crypto.randomBytes(32).toString("hex");
const id = crypto.randomUUID();
const now = new Date();
await db.insert(adminWebhooks).values({
id,
createdById: session!.user.id,
url: parsed.data.url,
events: parsed.data.events,
secret: encrypt(secret),
active: true,
createdAt: now,
});
return NextResponse.json(
{ id, url: parsed.data.url, events: parsed.data.events, secret, active: true, createdAt: now.toISOString() },
{ status: 201 }
);
}
+5 -1
View File
@@ -3,6 +3,7 @@ import { z } from "zod";
import { db, reports, comments, recipes, users, eq } from "@epicure/db";
import { requireSession } from "@/lib/api-auth";
import { applyRateLimit } from "@/lib/rate-limit";
import { dispatchAdminWebhook } from "@/lib/admin-webhooks";
import { randomUUID } from "crypto";
const Schema = z.object({
@@ -33,13 +34,16 @@ export async function POST(req: NextRequest) {
if (!exists) return NextResponse.json({ error: "Target not found" }, { status: 404 });
const id = randomUUID();
await db.insert(reports).values({
id: randomUUID(),
id,
reporterId: session!.user.id,
targetType,
targetId,
reason,
});
void dispatchAdminWebhook("report.filed", { id, reporterId: session!.user.id, targetType, targetId, reason });
return NextResponse.json({ ok: true }, { status: 201 });
}
+3
View File
@@ -6,6 +6,7 @@ import { requireSession } from "@/lib/api-auth";
import { sendEmail, supportTicketReceivedHtml } from "@/lib/email";
import { createGiteaIssue, buildGiteaIssueBody } from "@/lib/gitea";
import { getPublicUrl, isOwnedSupportAttachmentKey } from "@/lib/storage";
import { dispatchAdminWebhook } from "@/lib/admin-webhooks";
const MAX_ATTACHMENTS = 5;
@@ -84,6 +85,8 @@ export async function POST(req: NextRequest) {
updatedAt: now,
});
void dispatchAdminWebhook("support_ticket.created", { id, userId: session!.user.id, type, title });
if (attachments.length > 0) {
await db.insert(supportTicketAttachments).values(
attachments.map((a) => ({
@@ -0,0 +1,45 @@
import { NextRequest, NextResponse } from "next/server";
import { db, userFeaturePrefs } from "@epicure/db";
import { requireSession } from "@/lib/api-auth";
import { getFeaturePrefs } from "@/lib/feature-prefs";
import { z } from "zod";
const PutSchema = z.object({
nutrition: z.boolean().optional(),
pantry: z.boolean().optional(),
mealPlan: z.boolean().optional(),
shoppingLists: z.boolean().optional(),
collections: z.boolean().optional(),
messages: z.boolean().optional(),
});
export async function GET() {
const { session, response } = await requireSession();
if (response) return response;
const prefs = await getFeaturePrefs(session!.user.id);
return NextResponse.json({ data: prefs });
}
export async function PUT(req: NextRequest) {
const { session, response } = await requireSession();
if (response) return response;
const parsed = PutSchema.safeParse(await req.json());
if (!parsed.success) {
return NextResponse.json({ error: parsed.error.flatten() }, { status: 400 });
}
const body = parsed.data;
const userId = session!.user.id;
await db
.insert(userFeaturePrefs)
.values({ id: crypto.randomUUID(), userId, ...body, updatedAt: new Date() })
.onConflictDoUpdate({
target: userFeaturePrefs.userId,
set: { ...body, updatedAt: new Date() },
});
return NextResponse.json({ ok: true });
}
@@ -13,6 +13,15 @@ const PutSchema = z.object({
mention: z.boolean().optional(),
leftoverExpiring: z.boolean().optional(),
shoppingList: z.boolean().optional(),
followEmail: z.boolean().optional(),
commentEmail: z.boolean().optional(),
replyEmail: z.boolean().optional(),
reactionEmail: z.boolean().optional(),
ratingEmail: z.boolean().optional(),
mentionEmail: z.boolean().optional(),
leftoverExpiringEmail: z.boolean().optional(),
shoppingListEmail: z.boolean().optional(),
weeklyDigestEmail: z.boolean().optional(),
});
export async function GET() {