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:
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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 },
|
||||
|
||||
@@ -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'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 }
|
||||
);
|
||||
}
|
||||
@@ -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 });
|
||||
}
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -0,0 +1,313 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { ChevronDown, ChevronUp, RotateCcw } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
|
||||
const ALL_EVENTS = ["user.signed_up", "support_ticket.created", "report.filed"] as const;
|
||||
|
||||
type AdminWebhookEventType = (typeof ALL_EVENTS)[number];
|
||||
|
||||
type Webhook = {
|
||||
id: string;
|
||||
url: string;
|
||||
events: string[];
|
||||
active: boolean;
|
||||
createdAt: string;
|
||||
};
|
||||
|
||||
type Delivery = {
|
||||
id: string;
|
||||
event: string;
|
||||
statusCode: number | null;
|
||||
success: boolean;
|
||||
attempts: number;
|
||||
createdAt: string;
|
||||
};
|
||||
|
||||
type CreateWebhookResponse = {
|
||||
id: string;
|
||||
url: string;
|
||||
events: string[];
|
||||
secret: string;
|
||||
active: boolean;
|
||||
createdAt: string;
|
||||
};
|
||||
|
||||
function formatDate(iso: string) {
|
||||
return new Date(iso).toLocaleDateString(undefined, { year: "numeric", month: "short", day: "numeric" });
|
||||
}
|
||||
|
||||
function formatDateTime(iso: string) {
|
||||
return new Date(iso).toLocaleString(undefined, { month: "short", day: "numeric", hour: "2-digit", minute: "2-digit" });
|
||||
}
|
||||
|
||||
export function AdminWebhooksManager({ initialWebhooks }: { initialWebhooks: Webhook[] }) {
|
||||
const [webhookList, setWebhookList] = useState<Webhook[]>(initialWebhooks);
|
||||
const [url, setUrl] = useState("");
|
||||
const [selectedEvents, setSelectedEvents] = useState<AdminWebhookEventType[]>([]);
|
||||
const [creating, setCreating] = useState(false);
|
||||
const [newSecret, setNewSecret] = useState<{ id: string; secret: string } | null>(null);
|
||||
const [copied, setCopied] = useState(false);
|
||||
const [deliveries, setDeliveries] = useState<Record<string, Delivery[]>>({});
|
||||
const [loadingDeliveries, setLoadingDeliveries] = useState<string | null>(null);
|
||||
const [expandedDeliveries, setExpandedDeliveries] = useState<Set<string>>(new Set());
|
||||
const [redelivering, setRedelivering] = useState<string | null>(null);
|
||||
|
||||
function toggleEvent(event: AdminWebhookEventType) {
|
||||
setSelectedEvents((prev) => (prev.includes(event) ? prev.filter((e) => e !== event) : [...prev, event]));
|
||||
}
|
||||
|
||||
async function handleCreate(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
if (!url.trim()) return;
|
||||
setCreating(true);
|
||||
try {
|
||||
const res = await fetch("/api/v1/admin/webhooks", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ url: url.trim(), events: selectedEvents }),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const data = await res.json() as { error?: string };
|
||||
throw new Error(data.error ?? "Failed to add webhook");
|
||||
}
|
||||
const data = await res.json() as CreateWebhookResponse;
|
||||
setNewSecret({ id: data.id, secret: data.secret });
|
||||
setWebhookList((prev) => [
|
||||
{ id: data.id, url: data.url, events: data.events, active: data.active, createdAt: data.createdAt },
|
||||
...prev,
|
||||
]);
|
||||
setUrl("");
|
||||
setSelectedEvents([]);
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : "Failed to add webhook");
|
||||
} finally {
|
||||
setCreating(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleDelete(id: string) {
|
||||
try {
|
||||
const res = await fetch(`/api/v1/admin/webhooks/${id}`, { method: "DELETE" });
|
||||
if (!res.ok && res.status !== 204) {
|
||||
const data = await res.json() as { error?: string };
|
||||
throw new Error(data.error ?? "Failed to delete webhook");
|
||||
}
|
||||
setWebhookList((prev) => prev.filter((w) => w.id !== id));
|
||||
if (newSecret?.id === id) setNewSecret(null);
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : "Failed to delete webhook");
|
||||
}
|
||||
}
|
||||
|
||||
async function handleToggleActive(id: string, currentActive: boolean) {
|
||||
try {
|
||||
const res = await fetch(`/api/v1/admin/webhooks/${id}`, {
|
||||
method: "PATCH",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ active: !currentActive }),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const data = await res.json() as { error?: string };
|
||||
throw new Error(data.error ?? "Failed to update webhook");
|
||||
}
|
||||
setWebhookList((prev) => prev.map((w) => (w.id === id ? { ...w, active: !currentActive } : w)));
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : "Failed to update webhook");
|
||||
}
|
||||
}
|
||||
|
||||
async function handleCopySecret() {
|
||||
if (!newSecret) return;
|
||||
try {
|
||||
await navigator.clipboard.writeText(newSecret.secret);
|
||||
setCopied(true);
|
||||
setTimeout(() => setCopied(false), 2000);
|
||||
} catch {
|
||||
toast.error("Copy failed");
|
||||
}
|
||||
}
|
||||
|
||||
async function toggleDeliveries(webhookId: string) {
|
||||
const isExpanded = expandedDeliveries.has(webhookId);
|
||||
if (isExpanded) {
|
||||
setExpandedDeliveries((prev) => { const s = new Set(prev); s.delete(webhookId); return s; });
|
||||
return;
|
||||
}
|
||||
|
||||
setExpandedDeliveries((prev) => new Set([...prev, webhookId]));
|
||||
if (deliveries[webhookId]) return;
|
||||
|
||||
setLoadingDeliveries(webhookId);
|
||||
try {
|
||||
const res = await fetch(`/api/v1/admin/webhooks/${webhookId}/deliveries`);
|
||||
if (res.ok) {
|
||||
const data = await res.json() as Delivery[];
|
||||
setDeliveries((prev) => ({ ...prev, [webhookId]: data }));
|
||||
}
|
||||
} finally {
|
||||
setLoadingDeliveries(null);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleRedeliver(webhookId: string, deliveryId: string) {
|
||||
setRedelivering(deliveryId);
|
||||
try {
|
||||
const res = await fetch(`/api/v1/admin/webhooks/${webhookId}/redeliver`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ deliveryId }),
|
||||
});
|
||||
if (res.ok) toast.success("Redelivered");
|
||||
else toast.error("Redelivery failed");
|
||||
} finally {
|
||||
setRedelivering(null);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
<form onSubmit={handleCreate} className="space-y-4 rounded-xl border p-6">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="admin-webhook-url">Endpoint URL</Label>
|
||||
<Input
|
||||
id="admin-webhook-url"
|
||||
type="url"
|
||||
placeholder="https://hooks.slack.com/services/..."
|
||||
value={url}
|
||||
onChange={(e) => setUrl(e.target.value)}
|
||||
maxLength={2048}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label>Events</Label>
|
||||
<p className="text-xs text-muted-foreground">Leave all unchecked to receive every event.</p>
|
||||
<div className="flex flex-wrap gap-3">
|
||||
{ALL_EVENTS.map((event) => {
|
||||
const checked = selectedEvents.includes(event);
|
||||
return (
|
||||
<label key={event} className="flex items-center gap-2 cursor-pointer select-none">
|
||||
<input type="checkbox" className="rounded" checked={checked} onChange={() => toggleEvent(event)} />
|
||||
<span className="text-sm font-mono">{event}</span>
|
||||
</label>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Button type="submit" disabled={creating || !url.trim()}>
|
||||
{creating ? "Adding…" : "Add webhook"}
|
||||
</Button>
|
||||
</form>
|
||||
|
||||
{newSecret && (
|
||||
<div className="rounded-md border border-yellow-400 bg-yellow-50 p-4 space-y-3 dark:bg-yellow-950 dark:border-yellow-700">
|
||||
<p className="text-sm font-medium text-yellow-800 dark:text-yellow-200">
|
||||
Save this secret now — it won't be shown again.
|
||||
</p>
|
||||
<p className="text-xs text-yellow-700 dark:text-yellow-300">
|
||||
Used to verify the X-Epicure-Signature header on each delivery.
|
||||
</p>
|
||||
<div className="flex items-center gap-2">
|
||||
<code className="flex-1 rounded bg-white dark:bg-black border px-3 py-2 text-sm font-mono break-all">
|
||||
{newSecret.secret}
|
||||
</code>
|
||||
<Button type="button" variant="outline" onClick={() => { void handleCopySecret(); }}>
|
||||
{copied ? "Copied" : "Copy"}
|
||||
</Button>
|
||||
</div>
|
||||
<Button type="button" variant="ghost" size="sm" onClick={() => setNewSecret(null)} className="text-muted-foreground">
|
||||
Dismiss
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{webhookList.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground">No webhooks configured yet.</p>
|
||||
) : (
|
||||
<div className="divide-y rounded-md border">
|
||||
{webhookList.map((w) => {
|
||||
const isExpanded = expandedDeliveries.has(w.id);
|
||||
const wDeliveries = deliveries[w.id] ?? [];
|
||||
return (
|
||||
<div key={w.id} className="px-4 py-3 space-y-2">
|
||||
<div className="flex items-start justify-between gap-4">
|
||||
<div className="min-w-0 flex-1 space-y-1">
|
||||
<p className="text-sm font-mono truncate">{w.url}</p>
|
||||
<div className="flex items-center gap-2 text-xs text-muted-foreground">
|
||||
<span>Added {formatDate(w.createdAt)}</span>
|
||||
<span>·</span>
|
||||
<Badge variant={w.active ? "default" : "secondary"} className="text-xs">
|
||||
{w.active ? "Active" : "Inactive"}
|
||||
</Badge>
|
||||
</div>
|
||||
{w.events.length > 0 ? (
|
||||
<div className="flex flex-wrap gap-1 pt-1">
|
||||
{w.events.map((ev) => (
|
||||
<Badge key={ev} variant="outline" className="text-xs font-mono">{ev}</Badge>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-xs text-muted-foreground pt-1">All events</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-2 shrink-0">
|
||||
<Button type="button" variant="ghost" size="sm" onClick={() => { void toggleDeliveries(w.id); }} className="text-muted-foreground gap-1">
|
||||
{isExpanded ? <ChevronUp className="h-3.5 w-3.5" /> : <ChevronDown className="h-3.5 w-3.5" />}
|
||||
Deliveries
|
||||
</Button>
|
||||
<Button type="button" variant="outline" size="sm" onClick={() => { void handleToggleActive(w.id, w.active); }}>
|
||||
{w.active ? "Disable" : "Enable"}
|
||||
</Button>
|
||||
<Button type="button" variant="destructive" size="sm" onClick={() => { void handleDelete(w.id); }}>
|
||||
Delete
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{isExpanded && (
|
||||
<div className="mt-2 rounded-md border bg-muted/30">
|
||||
{loadingDeliveries === w.id ? (
|
||||
<p className="text-xs text-muted-foreground px-3 py-2">Loading…</p>
|
||||
) : wDeliveries.length === 0 ? (
|
||||
<p className="text-xs text-muted-foreground px-3 py-2">No deliveries yet.</p>
|
||||
) : (
|
||||
<div className="divide-y">
|
||||
{wDeliveries.map((d) => (
|
||||
<div key={d.id} className="flex items-center gap-3 px-3 py-2 text-xs">
|
||||
<Badge variant={d.success ? "default" : "destructive"} className="text-xs shrink-0 w-14 justify-center">
|
||||
{d.statusCode ?? "err"}
|
||||
</Badge>
|
||||
<span className="font-mono text-muted-foreground shrink-0">{d.event}</span>
|
||||
<span className="text-muted-foreground flex-1 text-right">{formatDateTime(d.createdAt)}</span>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-6 px-2 shrink-0"
|
||||
disabled={redelivering === d.id}
|
||||
onClick={() => { void handleRedeliver(w.id, d.id); }}
|
||||
>
|
||||
<RotateCcw className="h-3 w-3" />
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,11 +1,13 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { usePathname, useRouter } from "next/navigation";
|
||||
import { useTheme } from "next-themes";
|
||||
import { BookOpen, Calendar, Package, ChefHat, User, FolderOpen, ShoppingCart, Shield, Search, Compass, Menu, Sun, Moon, Monitor, Apple, LifeBuoy, Settings, LogOut } from "lucide-react";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { Button, buttonVariants } from "@/components/ui/button";
|
||||
import type { FeaturePrefs } from "@/lib/feature-prefs";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
@@ -28,13 +30,13 @@ import { authClient } from "@/lib/auth/client";
|
||||
import { useTranslations } from "next-intl";
|
||||
|
||||
const NAV_ITEMS = [
|
||||
{ href: "/recipes", key: "recipes", icon: BookOpen },
|
||||
{ href: "/explore", key: "explore", icon: Search },
|
||||
{ href: "/collections", key: "collections", icon: FolderOpen },
|
||||
{ href: "/meal-plan", key: "mealPlan", icon: Calendar },
|
||||
{ href: "/nutrition", key: "nutrition", icon: Apple },
|
||||
{ href: "/pantry", key: "pantry", icon: Package },
|
||||
{ href: "/shopping-lists", key: "shopping", icon: ShoppingCart },
|
||||
{ href: "/recipes", key: "recipes", icon: BookOpen, feature: null },
|
||||
{ href: "/explore", key: "explore", icon: Search, feature: null },
|
||||
{ href: "/collections", key: "collections", icon: FolderOpen, feature: "collections" },
|
||||
{ href: "/meal-plan", key: "mealPlan", icon: Calendar, feature: "mealPlan" },
|
||||
{ href: "/nutrition", key: "nutrition", icon: Apple, feature: "nutrition" },
|
||||
{ href: "/pantry", key: "pantry", icon: Package, feature: "pantry" },
|
||||
{ href: "/shopping-lists", key: "shopping", icon: ShoppingCart, feature: "shoppingLists" },
|
||||
] as const;
|
||||
|
||||
export function Nav() {
|
||||
@@ -45,6 +47,30 @@ export function Nav() {
|
||||
const username = (session?.user as { username?: string } | undefined)?.username;
|
||||
const { theme, setTheme } = useTheme();
|
||||
const t = useTranslations("nav");
|
||||
|
||||
// Defaults to "everything on" until the fetch resolves, matching the
|
||||
// backend default — avoids a flash of items disappearing on load for the
|
||||
// (much more common) case where a user hasn't hidden anything.
|
||||
const [featurePrefs, setFeaturePrefs] = useState<FeaturePrefs>({
|
||||
nutrition: true, pantry: true, mealPlan: true, shoppingLists: true, collections: true, messages: true,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
function load() {
|
||||
fetch("/api/v1/users/me/feature-prefs")
|
||||
.then((res) => (res.ok ? res.json() : null))
|
||||
.then((json) => { if (json?.data) setFeaturePrefs(json.data); })
|
||||
.catch(() => {});
|
||||
}
|
||||
load();
|
||||
// Settings → Features saves on the same origin without a full nav
|
||||
// remount, so it fires this event to make the change visible immediately
|
||||
// rather than only on the next page load.
|
||||
window.addEventListener("epicure:feature-prefs-changed", load);
|
||||
return () => window.removeEventListener("epicure:feature-prefs-changed", load);
|
||||
}, []);
|
||||
|
||||
const visibleNavItems = NAV_ITEMS.filter((item) => item.feature === null || featurePrefs[item.feature]);
|
||||
const THEME_OPTIONS = [
|
||||
{ value: "light", icon: Sun, label: t("lightMode") },
|
||||
{ value: "dark", icon: Moon, label: t("darkMode") },
|
||||
@@ -68,7 +94,7 @@ export function Nav() {
|
||||
</SheetTitle>
|
||||
</SheetHeader>
|
||||
<nav className="flex flex-col gap-1 px-2">
|
||||
{NAV_ITEMS.map(({ href, key, icon: Icon }) => (
|
||||
{visibleNavItems.map(({ href, key, icon: Icon }) => (
|
||||
<SheetClose
|
||||
key={href}
|
||||
nativeButton={false}
|
||||
@@ -110,7 +136,7 @@ export function Nav() {
|
||||
))}
|
||||
</nav>
|
||||
<div className="ml-auto flex items-center gap-2">
|
||||
<MessagesNavLink />
|
||||
{featurePrefs.messages && <MessagesNavLink />}
|
||||
<NotificationBell />
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger className="rounded-full outline-none focus-visible:ring-2 focus-visible:ring-ring">
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { toast } from "sonner";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import type { FeatureKey, FeaturePrefs } from "@/lib/feature-prefs";
|
||||
|
||||
const FEATURES: FeatureKey[] = ["nutrition", "pantry", "mealPlan", "shoppingLists", "collections", "messages"];
|
||||
|
||||
export function FeatureTogglesForm() {
|
||||
const t = useTranslations("settingsForm.featureToggles");
|
||||
const t_common = useTranslations("common");
|
||||
const [prefs, setPrefs] = useState<FeaturePrefs | null>(null);
|
||||
const [saving, setSaving] = useState<FeatureKey | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
fetch("/api/v1/users/me/feature-prefs")
|
||||
.then((res) => (res.ok ? res.json() : null))
|
||||
.then((json) => setPrefs(json?.data ?? null))
|
||||
.catch(() => setPrefs(null));
|
||||
}, []);
|
||||
|
||||
async function toggle(feature: FeatureKey, checked: boolean) {
|
||||
if (!prefs) return;
|
||||
const previous = prefs;
|
||||
setPrefs({ ...prefs, [feature]: checked });
|
||||
setSaving(feature);
|
||||
try {
|
||||
const res = await fetch("/api/v1/users/me/feature-prefs", {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ [feature]: checked }),
|
||||
});
|
||||
if (!res.ok) {
|
||||
setPrefs(previous);
|
||||
toast.error(t_common("saveFailed"));
|
||||
} else {
|
||||
// Nav reads this same endpoint on its own mount — no shared client
|
||||
// cache to invalidate, so a hard reason to re-fetch is a full nav
|
||||
// refresh. Cheapest correct fix: reload so the nav picks it up now
|
||||
// instead of on the next navigation.
|
||||
window.dispatchEvent(new Event("epicure:feature-prefs-changed"));
|
||||
}
|
||||
} catch {
|
||||
setPrefs(previous);
|
||||
toast.error(t_common("saveFailed"));
|
||||
} finally {
|
||||
setSaving(null);
|
||||
}
|
||||
}
|
||||
|
||||
if (!prefs) return null;
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
{FEATURES.map((feature) => (
|
||||
<div key={feature} className="flex items-center justify-between gap-3">
|
||||
<div>
|
||||
<Label htmlFor={`feature-${feature}`} className="cursor-pointer">
|
||||
{t(feature)}
|
||||
</Label>
|
||||
<p className="text-xs text-muted-foreground">{t(`${feature}Description`)}</p>
|
||||
</div>
|
||||
<Switch
|
||||
id={`feature-${feature}`}
|
||||
checked={prefs[feature]}
|
||||
disabled={saving === feature}
|
||||
onCheckedChange={(checked) => { void toggle(feature, checked); }}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -11,11 +11,13 @@ const CATEGORIES: NotificationCategory[] = [
|
||||
"follow", "comment", "reply", "reaction", "rating", "mention", "leftoverExpiring", "shoppingList",
|
||||
];
|
||||
|
||||
type Field = keyof NotificationPrefs;
|
||||
|
||||
export function NotificationCategoriesForm() {
|
||||
const t = useTranslations("settingsForm.notificationCategories");
|
||||
const t_common = useTranslations("common");
|
||||
const [prefs, setPrefs] = useState<NotificationPrefs | null>(null);
|
||||
const [saving, setSaving] = useState<NotificationCategory | null>(null);
|
||||
const [saving, setSaving] = useState<Field | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
fetch("/api/v1/users/me/notification-prefs")
|
||||
@@ -24,16 +26,16 @@ export function NotificationCategoriesForm() {
|
||||
.catch(() => setPrefs(null));
|
||||
}, []);
|
||||
|
||||
async function toggle(category: NotificationCategory, checked: boolean) {
|
||||
async function toggle(field: Field, checked: boolean) {
|
||||
if (!prefs) return;
|
||||
const previous = prefs;
|
||||
setPrefs({ ...prefs, [category]: checked });
|
||||
setSaving(category);
|
||||
setPrefs({ ...prefs, [field]: checked });
|
||||
setSaving(field);
|
||||
try {
|
||||
const res = await fetch("/api/v1/users/me/notification-prefs", {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ [category]: checked }),
|
||||
body: JSON.stringify({ [field]: checked }),
|
||||
});
|
||||
if (!res.ok) {
|
||||
setPrefs(previous);
|
||||
@@ -50,20 +52,57 @@ export function NotificationCategoriesForm() {
|
||||
if (!prefs) return null;
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
{CATEGORIES.map((category) => (
|
||||
<div key={category} className="flex items-center justify-between gap-3">
|
||||
<Label htmlFor={`notif-${category}`} className="cursor-pointer">
|
||||
{t(category)}
|
||||
<div className="space-y-1">
|
||||
<div className="grid grid-cols-[1fr_auto_auto] items-center gap-3 pb-2">
|
||||
<span />
|
||||
<span className="text-xs font-medium text-muted-foreground w-12 text-center">{t("push")}</span>
|
||||
<span className="text-xs font-medium text-muted-foreground w-12 text-center">{t("email")}</span>
|
||||
</div>
|
||||
|
||||
{CATEGORIES.map((category) => {
|
||||
const emailField = `${category}Email` as const;
|
||||
return (
|
||||
<div key={category} className="grid grid-cols-[1fr_auto_auto] items-center gap-3 py-2 border-t first:border-t-0">
|
||||
<Label htmlFor={`notif-${category}`} className="cursor-pointer">
|
||||
{t(category)}
|
||||
</Label>
|
||||
<div className="w-12 flex justify-center">
|
||||
<Switch
|
||||
id={`notif-${category}`}
|
||||
checked={prefs[category]}
|
||||
disabled={saving === category}
|
||||
onCheckedChange={(checked) => { void toggle(category, checked); }}
|
||||
/>
|
||||
</div>
|
||||
<div className="w-12 flex justify-center">
|
||||
<Switch
|
||||
id={`notif-${emailField}`}
|
||||
checked={prefs[emailField]}
|
||||
disabled={saving === emailField}
|
||||
onCheckedChange={(checked) => { void toggle(emailField, checked); }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
|
||||
<div className="grid grid-cols-[1fr_auto_auto] items-center gap-3 py-2 border-t">
|
||||
<div>
|
||||
<Label htmlFor="notif-weeklyDigestEmail" className="cursor-pointer">
|
||||
{t("weeklyDigest")}
|
||||
</Label>
|
||||
<p className="text-xs text-muted-foreground">{t("weeklyDigestDescription")}</p>
|
||||
</div>
|
||||
<span className="w-12" />
|
||||
<div className="w-12 flex justify-center">
|
||||
<Switch
|
||||
id={`notif-${category}`}
|
||||
checked={prefs[category]}
|
||||
disabled={saving === category}
|
||||
onCheckedChange={(checked) => { void toggle(category, checked); }}
|
||||
id="notif-weeklyDigestEmail"
|
||||
checked={prefs.weeklyDigestEmail}
|
||||
disabled={saving === "weeklyDigestEmail"}
|
||||
onCheckedChange={(checked) => { void toggle("weeklyDigestEmail", checked); }}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
import Link from "next/link";
|
||||
import { usePathname } from "next/navigation";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { User, Shield, Bot, Bell, Apple, Key, Webhook } from "lucide-react";
|
||||
import { User, Shield, Bot, Bell, Apple, Key, Webhook, SlidersHorizontal } from "lucide-react";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
const NAV_ITEMS = [
|
||||
@@ -11,6 +11,7 @@ const NAV_ITEMS = [
|
||||
{ href: "/settings/security", key: "security", icon: Shield, exact: false },
|
||||
{ href: "/settings/ai", key: "aiModels", icon: Bot, exact: false },
|
||||
{ href: "/settings/notifications", key: "notifications", icon: Bell, exact: false },
|
||||
{ href: "/settings/features", key: "features", icon: SlidersHorizontal, exact: false },
|
||||
{ href: "/settings/nutrition", key: "nutrition", icon: Apple, exact: false },
|
||||
{ href: "/settings/api-keys", key: "apiKeys", icon: Key, exact: false },
|
||||
{ href: "/settings/webhooks", key: "webhooks", icon: Webhook, exact: false },
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import crypto from "crypto";
|
||||
import { db } from "@epicure/db";
|
||||
import { adminWebhooks, adminWebhookDeliveries } from "@epicure/db";
|
||||
import { eq } from "@epicure/db";
|
||||
import { deliverWebhook } from "@/lib/webhook-delivery";
|
||||
|
||||
// Site-wide ops events — distinct from WEBHOOK_EVENTS in lib/webhooks.ts,
|
||||
// which are per-user events on a user's own data. These fire regardless of
|
||||
// who's involved, for ops alerting (Slack/Discord/etc via a generic
|
||||
// incoming webhook), so only admins can subscribe to them.
|
||||
export const ADMIN_WEBHOOK_EVENTS = [
|
||||
"user.signed_up",
|
||||
"support_ticket.created",
|
||||
"report.filed",
|
||||
] as const;
|
||||
|
||||
export type AdminWebhookEvent = (typeof ADMIN_WEBHOOK_EVENTS)[number];
|
||||
|
||||
export async function dispatchAdminWebhook(event: AdminWebhookEvent, payload: object) {
|
||||
const hooks = await db.select().from(adminWebhooks).where(eq(adminWebhooks.active, true));
|
||||
const filtered = hooks.filter((h) => h.events.length === 0 || h.events.includes(event));
|
||||
|
||||
await Promise.allSettled(
|
||||
filtered.map(async (hook) => {
|
||||
const { statusCode, success } = await deliverWebhook(hook.url, hook.secret, event, payload);
|
||||
await db.insert(adminWebhookDeliveries).values({
|
||||
id: crypto.randomUUID(),
|
||||
webhookId: hook.id,
|
||||
event,
|
||||
payload: payload as Record<string, unknown>,
|
||||
statusCode,
|
||||
success,
|
||||
attempts: 1,
|
||||
createdAt: new Date(),
|
||||
});
|
||||
})
|
||||
);
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import { isSignupsDisabled } from "@/lib/site-settings";
|
||||
import { findValidInvite, consumeInvite, INVITE_COOKIE } from "@/lib/invites";
|
||||
import { generateUniqueUsername } from "@/lib/username";
|
||||
import { getRedis } from "@/lib/redis";
|
||||
import { dispatchAdminWebhook } from "@/lib/admin-webhooks";
|
||||
|
||||
// Without this, better-auth's own rate limiter (sign-in/sign-up/2FA/password
|
||||
// reset throttles below) defaults to an in-process Map — fine for a single
|
||||
@@ -178,6 +179,8 @@ export const auth = betterAuth({
|
||||
subject: "Welcome to Epicure",
|
||||
html: welcomeHtml(user.name),
|
||||
}).catch(() => {});
|
||||
|
||||
void dispatchAdminWebhook("user.signed_up", { id: user.id, email: user.email, name: user.name });
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// Mirrors CHANGELOG.md at the repo root — update both together.
|
||||
export const APP_VERSION = "0.60.0";
|
||||
export const APP_VERSION = "0.61.0";
|
||||
|
||||
export type ChangelogEntry = {
|
||||
version: string;
|
||||
@@ -11,6 +11,15 @@ export type ChangelogEntry = {
|
||||
};
|
||||
|
||||
export const CHANGELOG: ChangelogEntry[] = [
|
||||
{
|
||||
version: "0.61.0",
|
||||
date: "2026-07-20 23:15",
|
||||
added: [
|
||||
"Settings → Notifications now has an email toggle for every category alongside the existing push toggle, plus a Weekly Digest toggle to opt out of the weekly email summary entirely.",
|
||||
"Admin → Webhooks: site-wide ops webhooks (new signups, support tickets, reports filed) — separate from the existing per-user webhooks, for Slack/Discord-style ops alerting.",
|
||||
"Settings → Features: hide Nutrition, Pantry, Meal Plan, Shopping Lists, Collections, or Messages from your own navigation. Cosmetic only — hidden pages stay reachable by direct link.",
|
||||
],
|
||||
},
|
||||
{
|
||||
version: "0.60.0",
|
||||
date: "2026-07-20 22:15",
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
import { db, userFeaturePrefs, eq } from "@epicure/db";
|
||||
|
||||
export type FeatureKey = "nutrition" | "pantry" | "mealPlan" | "shoppingLists" | "collections" | "messages";
|
||||
|
||||
export type FeaturePrefs = Record<FeatureKey, boolean>;
|
||||
|
||||
const DEFAULT_PREFS: FeaturePrefs = {
|
||||
nutrition: true, pantry: true, mealPlan: true, shoppingLists: true, collections: true, messages: true,
|
||||
};
|
||||
|
||||
/** No row yet means every feature defaults to on — same default the DB columns encode. */
|
||||
export async function getFeaturePrefs(userId: string): Promise<FeaturePrefs> {
|
||||
const row = await db.query.userFeaturePrefs.findFirst({ where: eq(userFeaturePrefs.userId, userId) });
|
||||
if (!row) return { ...DEFAULT_PREFS };
|
||||
return {
|
||||
nutrition: row.nutrition, pantry: row.pantry, mealPlan: row.mealPlan,
|
||||
shoppingLists: row.shoppingLists, collections: row.collections, messages: row.messages,
|
||||
};
|
||||
}
|
||||
@@ -4,11 +4,20 @@ export type NotificationCategory =
|
||||
| "follow" | "comment" | "reply" | "reaction" | "rating" | "mention"
|
||||
| "leftoverExpiring" | "shoppingList";
|
||||
|
||||
export type NotificationPrefs = Record<NotificationCategory, boolean>;
|
||||
export type NotificationPrefs = {
|
||||
follow: boolean; comment: boolean; reply: boolean; reaction: boolean; rating: boolean; mention: boolean;
|
||||
leftoverExpiring: boolean; shoppingList: boolean;
|
||||
followEmail: boolean; commentEmail: boolean; replyEmail: boolean; reactionEmail: boolean;
|
||||
ratingEmail: boolean; mentionEmail: boolean; leftoverExpiringEmail: boolean; shoppingListEmail: boolean;
|
||||
weeklyDigestEmail: boolean;
|
||||
};
|
||||
|
||||
const DEFAULT_PREFS: NotificationPrefs = {
|
||||
follow: true, comment: true, reply: true, reaction: true, rating: true, mention: true,
|
||||
leftoverExpiring: true, shoppingList: true,
|
||||
followEmail: true, commentEmail: true, replyEmail: true, reactionEmail: true,
|
||||
ratingEmail: true, mentionEmail: true, leftoverExpiringEmail: true, shoppingListEmail: true,
|
||||
weeklyDigestEmail: true,
|
||||
};
|
||||
|
||||
export async function getNotificationPrefs(userId: string): Promise<NotificationPrefs> {
|
||||
@@ -17,6 +26,10 @@ export async function getNotificationPrefs(userId: string): Promise<Notification
|
||||
return {
|
||||
follow: row.follow, comment: row.comment, reply: row.reply, reaction: row.reaction,
|
||||
rating: row.rating, mention: row.mention, leftoverExpiring: row.leftoverExpiring, shoppingList: row.shoppingList,
|
||||
followEmail: row.followEmail, commentEmail: row.commentEmail, replyEmail: row.replyEmail,
|
||||
reactionEmail: row.reactionEmail, ratingEmail: row.ratingEmail, mentionEmail: row.mentionEmail,
|
||||
leftoverExpiringEmail: row.leftoverExpiringEmail, shoppingListEmail: row.shoppingListEmail,
|
||||
weeklyDigestEmail: row.weeklyDigestEmail,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -25,3 +38,14 @@ export async function isNotificationCategoryEnabled(userId: string, category: No
|
||||
const prefs = await getNotificationPrefs(userId);
|
||||
return prefs[category];
|
||||
}
|
||||
|
||||
/** Same as isNotificationCategoryEnabled, but for the email variant of the category. */
|
||||
export async function isEmailCategoryEnabled(userId: string, category: NotificationCategory): Promise<boolean> {
|
||||
const prefs = await getNotificationPrefs(userId);
|
||||
return prefs[`${category}Email`];
|
||||
}
|
||||
|
||||
export async function isWeeklyDigestEnabled(userId: string): Promise<boolean> {
|
||||
const prefs = await getNotificationPrefs(userId);
|
||||
return prefs.weeklyDigestEmail;
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@ import { randomUUID } from "crypto";
|
||||
import { sendPushNotification } from "./push";
|
||||
import { sendEmail, notificationEmailHtml } from "./email";
|
||||
import { getMessages, formatMessage } from "./i18n/server";
|
||||
import { isNotificationCategoryEnabled } from "./notification-prefs";
|
||||
import { isNotificationCategoryEnabled, isEmailCategoryEnabled } from "./notification-prefs";
|
||||
|
||||
type NotificationType = "follow" | "comment" | "reply" | "reaction" | "rating" | "mention";
|
||||
|
||||
@@ -82,7 +82,7 @@ async function dispatchAlerts(opts: CreateNotificationOpts): Promise<void> {
|
||||
});
|
||||
}
|
||||
|
||||
if (recipient.email) {
|
||||
if (recipient.email && (await isEmailCategoryEnabled(opts.userId, opts.type))) {
|
||||
const baseUrl = process.env["BETTER_AUTH_URL"] ?? "http://localhost:3000";
|
||||
void sendEmail({
|
||||
to: recipient.email,
|
||||
|
||||
+45
-1
@@ -465,11 +465,26 @@ export function generateOpenApiSpec(): object {
|
||||
const NotificationPrefsRef = registry.register("NotificationPrefs", z.object({
|
||||
follow: z.boolean(), comment: z.boolean(), reply: z.boolean(), reaction: z.boolean(),
|
||||
rating: z.boolean(), mention: z.boolean(), leftoverExpiring: z.boolean(), shoppingList: z.boolean(),
|
||||
}));
|
||||
followEmail: z.boolean(), commentEmail: z.boolean(), replyEmail: z.boolean(), reactionEmail: z.boolean(),
|
||||
ratingEmail: z.boolean(), mentionEmail: z.boolean(), leftoverExpiringEmail: z.boolean(), shoppingListEmail: z.boolean(),
|
||||
weeklyDigestEmail: z.boolean(),
|
||||
}).describe("The non-Email fields gate push notifications; the *Email fields gate the matching email. weeklyDigestEmail gates the weekly digest email (no push equivalent)."));
|
||||
const UpdateNotificationPrefsRef = registry.register("UpdateNotificationPrefs", z.object({
|
||||
follow: z.boolean().optional(), comment: z.boolean().optional(), reply: z.boolean().optional(), reaction: z.boolean().optional(),
|
||||
rating: z.boolean().optional(), 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(),
|
||||
}));
|
||||
const FeaturePrefsRef = registry.register("FeaturePrefs", z.object({
|
||||
nutrition: z.boolean(), pantry: z.boolean(), mealPlan: z.boolean(),
|
||||
shoppingLists: z.boolean(), collections: z.boolean(), messages: z.boolean(),
|
||||
}).describe("Purely cosmetic — hides the feature from the user's own nav. Never restricts access to the underlying pages/routes."));
|
||||
const UpdateFeaturePrefsRef = registry.register("UpdateFeaturePrefs", 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(),
|
||||
}));
|
||||
|
||||
const NutritionGoalsRef2 = registry.register("NutritionGoalsMe", z.object({
|
||||
id: z.string(), userId: z.string(),
|
||||
caloriesKcal: z.number().int().nullable(), proteinG: z.number().int().nullable(),
|
||||
@@ -509,6 +524,8 @@ export function generateOpenApiSpec(): object {
|
||||
registry.registerPath({ method: "put", path: "/api/v1/users/me/model-prefs", summary: "Set your AI model provider/model preferences", security, request: { body: { content: { "application/json": { schema: UpdateModelPrefsRef } }, required: true } }, responses: { 200: { description: "Saved", content: { "application/json": { schema: z.object({ ok: z.boolean() }) } } }, 400: { description: "Invalid request", content: { "application/json": { schema: ApiErrorRef } } }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } } } });
|
||||
registry.registerPath({ method: "get", path: "/api/v1/users/me/notification-prefs", summary: "Get your notification category preferences", description: "Categories with no saved row default to enabled.", security, responses: { 200: { description: "Preferences", content: { "application/json": { schema: z.object({ data: NotificationPrefsRef }) } } }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } } } });
|
||||
registry.registerPath({ method: "put", path: "/api/v1/users/me/notification-prefs", summary: "Set your notification category preferences", security, request: { body: { content: { "application/json": { schema: UpdateNotificationPrefsRef } }, required: true } }, responses: { 200: { description: "Saved", content: { "application/json": { schema: z.object({ ok: z.boolean() }) } } }, 400: { description: "Invalid request", content: { "application/json": { schema: ApiErrorRef } } }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } } } });
|
||||
registry.registerPath({ method: "get", path: "/api/v1/users/me/feature-prefs", summary: "Get your feature visibility preferences", description: "Features with no saved row default to visible.", security, responses: { 200: { description: "Preferences", content: { "application/json": { schema: z.object({ data: FeaturePrefsRef }) } } }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } } } });
|
||||
registry.registerPath({ method: "put", path: "/api/v1/users/me/feature-prefs", summary: "Set your feature visibility preferences", description: "Purely cosmetic (hides nav items) — does not restrict access to the underlying pages.", security, request: { body: { content: { "application/json": { schema: UpdateFeaturePrefsRef } }, required: true } }, responses: { 200: { description: "Saved", content: { "application/json": { schema: z.object({ ok: z.boolean() }) } } }, 400: { description: "Invalid request", content: { "application/json": { schema: ApiErrorRef } } }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } } } });
|
||||
registry.registerPath({ method: "get", path: "/api/v1/users/me/nutrition-diary", summary: "Get a day's cooked-recipe nutrition totals vs. your goals", security, request: { query: z.object({ date: z.string().optional().describe("ISO date YYYY-MM-DD, defaults to today (UTC)") }) }, responses: { 200: { description: "Diary", content: { "application/json": { schema: NutritionDiaryRef } } }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } } } });
|
||||
registry.registerPath({ method: "get", path: "/api/v1/users/me/nutrition-goals", summary: "Get your daily nutrition goals", security, responses: { 200: { description: "Goals", content: { "application/json": { schema: z.object({ data: NutritionGoalsRef2 }) } } }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } } } });
|
||||
registry.registerPath({ method: "put", path: "/api/v1/users/me/nutrition-goals", summary: "Set your daily nutrition goals", security, request: { body: { content: { "application/json": { schema: UpdateNutritionGoalsRef } }, required: true } }, responses: { 200: { description: "Saved", content: { "application/json": { schema: z.object({ ok: z.boolean() }) } } }, 400: { description: "Invalid request", content: { "application/json": { schema: ApiErrorRef } } }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } } } });
|
||||
@@ -600,6 +617,26 @@ export function generateOpenApiSpec(): object {
|
||||
registry.registerPath({ method: "get", path: "/api/v1/webhooks/{id}/deliveries", summary: "List recent delivery attempts (most recent 20)", security, request: { params: idParam }, responses: { 200: { description: "Deliveries, newest first", content: { "application/json": { schema: z.array(WebhookDeliveryRef) } } }, 404: { description: "Not found", content: { "application/json": { schema: ApiErrorRef } } } } });
|
||||
registry.registerPath({ method: "post", path: "/api/v1/webhooks/{id}/redeliver", summary: "Re-send a past delivery's payload", security, request: { params: idParam, body: { content: { "application/json": { schema: z.object({ deliveryId: z.string().uuid() }) } }, required: true } }, responses: { 200: { description: "Redelivery dispatched", content: { "application/json": { schema: z.object({ ok: z.boolean() }) } } }, 400: { description: "Validation error", content: { "application/json": { schema: ApiErrorRef } } }, 404: { description: "Webhook or delivery not found", content: { "application/json": { schema: ApiErrorRef } } } } });
|
||||
|
||||
const AdminWebhookEventEnum = z.enum(["user.signed_up", "support_ticket.created", "report.filed"]);
|
||||
const AdminWebhookRef = registry.register("AdminWebhook", z.object({
|
||||
id: z.string(), url: z.string(), events: z.array(AdminWebhookEventEnum), active: z.boolean(), createdAt: z.string().datetime(),
|
||||
}));
|
||||
const CreateAdminWebhookRef = registry.register("CreateAdminWebhook", z.object({
|
||||
url: z.string().min(1).max(2048), events: z.array(AdminWebhookEventEnum).default([]),
|
||||
}));
|
||||
const CreatedAdminWebhookRef = registry.register("CreatedAdminWebhook", z.object({
|
||||
id: z.string(), url: z.string(), events: z.array(AdminWebhookEventEnum),
|
||||
secret: z.string().describe("Signing secret — shown only in this response, never returned again."),
|
||||
active: z.boolean(), createdAt: z.string().datetime(),
|
||||
}));
|
||||
const UpdateAdminWebhookRef = registry.register("UpdateAdminWebhook", z.object({
|
||||
url: z.string().min(1).max(2048).optional(), events: z.array(AdminWebhookEventEnum).optional(), active: z.boolean().optional(),
|
||||
}));
|
||||
const AdminWebhookDeliveryRef = registry.register("AdminWebhookDelivery", z.object({
|
||||
id: z.string(), webhookId: z.string(), event: z.string(), payload: z.record(z.string(), z.unknown()).nullable(),
|
||||
statusCode: z.number().int().nullable(), success: z.boolean(), attempts: z.number().int(), createdAt: z.string().datetime(),
|
||||
}));
|
||||
|
||||
// --- Support: bug reports, suggestions, and questions submitted in-app ---
|
||||
const SupportTicketTypeEnum = z.enum(["bug", "suggestion", "question"]);
|
||||
const SupportTicketStatusEnum = z.enum(["open", "triaged", "closed"]);
|
||||
@@ -842,6 +879,13 @@ export function generateOpenApiSpec(): object {
|
||||
|
||||
registry.registerPath({ method: "get", path: "/api/v1/admin/support", summary: "List all support tickets, newest first", description: "Admin only.", security: adminSecurity, responses: { 200: { description: "Tickets", content: { "application/json": { schema: z.array(AdminSupportTicketRef) } } }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } }, 403: { description: "Forbidden", content: { "application/json": { schema: ApiErrorRef } } } } });
|
||||
registry.registerPath({ method: "patch", path: "/api/v1/admin/support/{id}", summary: "Update a support ticket's status, or retry opening its Gitea issue", description: "Admin only.", security: adminSecurity, request: { params: idParam, body: { content: { "application/json": { schema: UpdateAdminSupportTicketRef } }, required: true } }, responses: { 200: { description: "Updated", content: { "application/json": { schema: z.object({ ok: z.boolean() }) } } }, 400: { description: "Validation error", content: { "application/json": { schema: ApiErrorRef } } }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } }, 403: { description: "Forbidden", content: { "application/json": { schema: ApiErrorRef } } }, 404: { description: "Not found", content: { "application/json": { schema: ApiErrorRef } } } } });
|
||||
|
||||
registry.registerPath({ method: "get", path: "/api/v1/admin/webhooks", summary: "List site-wide ops webhooks", description: "Admin only. Site-wide events (new signups, support tickets, reports) — distinct from the per-user webhooks under /api/v1/webhooks. The signing secret is never included — it is only ever returned once, at creation time.", security: adminSecurity, responses: { 200: { description: "Webhooks", content: { "application/json": { schema: z.array(AdminWebhookRef) } } }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } }, 403: { description: "Forbidden", content: { "application/json": { schema: ApiErrorRef } } } } });
|
||||
registry.registerPath({ method: "post", path: "/api/v1/admin/webhooks", summary: "Create a site-wide ops webhook", description: "Admin only. Validates the URL against SSRF targets. Generates a signing secret returned once in this response only.", security: adminSecurity, request: { body: { content: { "application/json": { schema: CreateAdminWebhookRef } }, required: true } }, responses: { 201: { description: "Created — includes the signing secret (write-once)", content: { "application/json": { schema: CreatedAdminWebhookRef } } }, 400: { description: "Validation error or blocked URL", content: { "application/json": { schema: ApiErrorRef } } }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } }, 403: { description: "Forbidden", content: { "application/json": { schema: ApiErrorRef } } } } });
|
||||
registry.registerPath({ method: "patch", path: "/api/v1/admin/webhooks/{id}", summary: "Update a site-wide ops webhook's URL, events, or active state", description: "Admin only. Validates the URL against SSRF targets if changed.", security: adminSecurity, request: { params: idParam, body: { content: { "application/json": { schema: UpdateAdminWebhookRef } }, required: true } }, responses: { 200: { description: "Updated", content: { "application/json": { schema: AdminWebhookRef } } }, 400: { description: "Validation error, blocked URL, or no fields to update", content: { "application/json": { schema: ApiErrorRef } } }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } }, 403: { description: "Forbidden", content: { "application/json": { schema: ApiErrorRef } } }, 404: { description: "Not found", content: { "application/json": { schema: ApiErrorRef } } } } });
|
||||
registry.registerPath({ method: "delete", path: "/api/v1/admin/webhooks/{id}", summary: "Delete a site-wide ops webhook", description: "Admin only.", security: adminSecurity, request: { params: idParam }, responses: { 204: { description: "Deleted" }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } }, 403: { description: "Forbidden", content: { "application/json": { schema: ApiErrorRef } } }, 404: { description: "Not found", content: { "application/json": { schema: ApiErrorRef } } } } });
|
||||
registry.registerPath({ method: "get", path: "/api/v1/admin/webhooks/{id}/deliveries", summary: "List recent delivery attempts for a site-wide ops webhook (most recent 20)", description: "Admin only.", security: adminSecurity, request: { params: idParam }, responses: { 200: { description: "Deliveries, newest first", content: { "application/json": { schema: z.array(AdminWebhookDeliveryRef) } } }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } }, 403: { description: "Forbidden", content: { "application/json": { schema: ApiErrorRef } } }, 404: { description: "Not found", content: { "application/json": { schema: ApiErrorRef } } } } });
|
||||
registry.registerPath({ method: "post", path: "/api/v1/admin/webhooks/{id}/redeliver", summary: "Re-send a past delivery's payload for a site-wide ops webhook", description: "Admin only.", security: adminSecurity, request: { params: idParam, body: { content: { "application/json": { schema: z.object({ deliveryId: z.string().uuid() }) } }, required: true } }, responses: { 200: { description: "Redelivery dispatched", content: { "application/json": { schema: z.object({ ok: z.boolean() }) } } }, 400: { description: "Validation error", content: { "application/json": { schema: ApiErrorRef } } }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } }, 403: { description: "Forbidden", content: { "application/json": { schema: ApiErrorRef } } }, 404: { description: "Webhook or delivery not found", content: { "application/json": { schema: ApiErrorRef } } } } });
|
||||
registry.registerPath({ method: "patch", path: "/api/v1/admin/reports/{id}", summary: "Resolve a report (mark reviewed or dismissed)", description: "Admin only.", security: adminSecurity, request: { params: idParam, body: { content: { "application/json": { schema: ResolveReportBodyRef } }, required: true } }, responses: { 200: { description: "Updated", content: { "application/json": { schema: z.object({ report: ResolvedReportRef }) } } }, 400: { description: "Invalid status", content: { "application/json": { schema: ApiErrorRef } } }, 403: { description: "Forbidden", content: { "application/json": { schema: ApiErrorRef } } }, 404: { description: "Not found", content: { "application/json": { schema: ApiErrorRef } } } } });
|
||||
|
||||
registry.registerPath({ method: "put", path: "/api/v1/admin/settings", summary: "Update site settings (AI provider keys, VAPID keys, signups toggle)", description: "Admin only. Secret-flagged keys are encrypted at rest and never echoed back by any endpoint; this route only accepts new values, it does not return current ones.", security: adminSecurity, request: { body: { content: { "application/json": { schema: UpdateSiteSettingsRef } }, required: true } }, responses: { 200: { description: "Saved", content: { "application/json": { schema: z.object({ ok: z.boolean() }) } } }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } }, 403: { description: "Forbidden", content: { "application/json": { schema: ApiErrorRef } } } } });
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import crypto from "crypto";
|
||||
import { safeFetch } from "@/lib/validate-webhook-url";
|
||||
import { decrypt } from "@/lib/encrypt";
|
||||
|
||||
// Secrets created before encryption-at-rest was added are a bare 64-char hex
|
||||
// string (crypto.randomBytes(32).toString("hex")) with no ":" separators —
|
||||
// encrypt()'s output is always "iv:authTag:ciphertext". Fall back to treating
|
||||
// the value as already-plaintext rather than a hard migration, since this is
|
||||
// only reached with a value this app itself generated (never user input).
|
||||
export function decryptWebhookSecret(stored: string): string {
|
||||
return stored.split(":").length === 3 ? decrypt(stored) : stored;
|
||||
}
|
||||
|
||||
/**
|
||||
* Signs and POSTs a single webhook payload. Shared by the per-user
|
||||
* (`lib/webhooks.ts`) and admin (`lib/admin-webhooks.ts`) dispatchers so the
|
||||
* signing/delivery mechanics — which are security-relevant — live in exactly
|
||||
* one place instead of two copies that could drift.
|
||||
*/
|
||||
export async function deliverWebhook(
|
||||
url: string,
|
||||
secret: string,
|
||||
event: string,
|
||||
payload: object
|
||||
): Promise<{ statusCode: number; success: boolean }> {
|
||||
const body = JSON.stringify({ event, payload, timestamp: new Date().toISOString() });
|
||||
const sig = crypto.createHmac("sha256", decryptWebhookSecret(secret)).update(body).digest("hex");
|
||||
|
||||
try {
|
||||
// safeFetch resolves and pins the connection to a single validated IP
|
||||
// (and re-validates + re-pins every redirect hop), so there's no
|
||||
// separate re-resolution for a rebinding attack to exploit.
|
||||
const res = await safeFetch(url, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"X-Epicure-Signature": `sha256=${sig}`,
|
||||
"X-Epicure-Event": event,
|
||||
},
|
||||
body,
|
||||
signal: AbortSignal.timeout(10000),
|
||||
});
|
||||
return { statusCode: res.status, success: res.ok };
|
||||
} catch {
|
||||
return { statusCode: 0, success: false };
|
||||
}
|
||||
}
|
||||
@@ -2,17 +2,7 @@ import crypto from "crypto";
|
||||
import { db } from "@epicure/db";
|
||||
import { webhooks, webhookDeliveries } from "@epicure/db";
|
||||
import { eq, and } from "@epicure/db";
|
||||
import { safeFetch } from "@/lib/validate-webhook-url";
|
||||
import { decrypt } from "@/lib/encrypt";
|
||||
|
||||
// Secrets created before encryption-at-rest was added are a bare 64-char hex
|
||||
// string (crypto.randomBytes(32).toString("hex")) with no ":" separators —
|
||||
// encrypt()'s output is always "iv:authTag:ciphertext". Fall back to treating
|
||||
// the value as already-plaintext rather than a hard migration, since this is
|
||||
// only reached with a value this app itself generated (never user input).
|
||||
function decryptWebhookSecret(stored: string): string {
|
||||
return stored.split(":").length === 3 ? decrypt(stored) : stored;
|
||||
}
|
||||
import { deliverWebhook } from "@/lib/webhook-delivery";
|
||||
|
||||
export const WEBHOOK_EVENTS = [
|
||||
"recipe.created",
|
||||
@@ -36,29 +26,7 @@ export async function dispatchWebhook(userId: string, event: WebhookEvent, paylo
|
||||
|
||||
await Promise.allSettled(
|
||||
filtered.map(async (hook) => {
|
||||
const body = JSON.stringify({ event, payload, timestamp: new Date().toISOString() });
|
||||
const sig = crypto.createHmac("sha256", decryptWebhookSecret(hook.secret)).update(body).digest("hex");
|
||||
let statusCode = 0;
|
||||
let success = false;
|
||||
try {
|
||||
// safeFetch resolves and pins the connection to a single validated IP
|
||||
// (and re-validates + re-pins every redirect hop), so there's no
|
||||
// separate re-resolution for a rebinding attack to exploit.
|
||||
const res = await safeFetch(hook.url, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"X-Epicure-Signature": `sha256=${sig}`,
|
||||
"X-Epicure-Event": event,
|
||||
},
|
||||
body,
|
||||
signal: AbortSignal.timeout(10000),
|
||||
});
|
||||
statusCode = res.status;
|
||||
success = res.ok;
|
||||
} catch {
|
||||
// delivery failed; statusCode stays 0, success stays false
|
||||
}
|
||||
const { statusCode, success } = await deliverWebhook(hook.url, hook.secret, event, payload);
|
||||
await db.insert(webhookDeliveries).values({
|
||||
id: crypto.randomUUID(),
|
||||
webhookId: hook.id,
|
||||
|
||||
@@ -415,6 +415,7 @@
|
||||
"security": "Security",
|
||||
"aiModels": "AI & Models",
|
||||
"notifications": "Notifications",
|
||||
"features": "Features",
|
||||
"nutrition": "Nutrition",
|
||||
"apiKeys": "API Keys",
|
||||
"webhooks": "Webhooks",
|
||||
@@ -1399,7 +1400,9 @@
|
||||
"settingsForm": {
|
||||
"notificationCategories": {
|
||||
"title": "Notification categories",
|
||||
"description": "Choose which push notifications you want to receive.",
|
||||
"description": "Choose which notifications you want to receive, and whether by push, email, or both.",
|
||||
"push": "Push",
|
||||
"email": "Email",
|
||||
"follow": "New followers",
|
||||
"comment": "Comments on your recipes",
|
||||
"reply": "Replies to your comments",
|
||||
@@ -1407,7 +1410,25 @@
|
||||
"rating": "Ratings on your recipes",
|
||||
"mention": "Mentions in comments",
|
||||
"leftoverExpiring": "Leftovers expiring soon",
|
||||
"shoppingList": "Shared shopping list updates"
|
||||
"shoppingList": "Shared shopping list updates",
|
||||
"weeklyDigest": "Weekly digest",
|
||||
"weeklyDigestDescription": "A weekly email summary of new followers, comments, and ratings, plus trending recipes."
|
||||
},
|
||||
"featureToggles": {
|
||||
"title": "Features",
|
||||
"description": "Hide features you don't use from your navigation. This only affects your own view — hidden pages stay reachable by direct link, nothing is deleted.",
|
||||
"nutrition": "Nutrition",
|
||||
"nutritionDescription": "Nutrition diary and goals.",
|
||||
"pantry": "Pantry",
|
||||
"pantryDescription": "Track what you have on hand.",
|
||||
"mealPlan": "Meal Plan",
|
||||
"mealPlanDescription": "Weekly meal planning.",
|
||||
"shoppingLists": "Shopping Lists",
|
||||
"shoppingListsDescription": "Shared shopping lists.",
|
||||
"collections": "Collections",
|
||||
"collectionsDescription": "Organize recipes into collections.",
|
||||
"messages": "Messages",
|
||||
"messagesDescription": "Direct messages with other cooks."
|
||||
},
|
||||
"profile": "Profile",
|
||||
"changePhoto": "Change photo",
|
||||
|
||||
@@ -415,6 +415,7 @@
|
||||
"security": "Sécurité",
|
||||
"aiModels": "IA et modèles",
|
||||
"notifications": "Notifications",
|
||||
"features": "Fonctionnalités",
|
||||
"nutrition": "Nutrition",
|
||||
"apiKeys": "Clés API",
|
||||
"webhooks": "Webhooks",
|
||||
@@ -1390,7 +1391,9 @@
|
||||
"settingsForm": {
|
||||
"notificationCategories": {
|
||||
"title": "Catégories de notifications",
|
||||
"description": "Choisissez les notifications push que vous souhaitez recevoir.",
|
||||
"description": "Choisissez les notifications que vous souhaitez recevoir, par push, par e-mail, ou les deux.",
|
||||
"push": "Push",
|
||||
"email": "E-mail",
|
||||
"follow": "Nouveaux abonnés",
|
||||
"comment": "Commentaires sur vos recettes",
|
||||
"reply": "Réponses à vos commentaires",
|
||||
@@ -1398,7 +1401,25 @@
|
||||
"rating": "Notes sur vos recettes",
|
||||
"mention": "Mentions dans les commentaires",
|
||||
"leftoverExpiring": "Restes bientôt périmés",
|
||||
"shoppingList": "Mises à jour des listes de courses partagées"
|
||||
"shoppingList": "Mises à jour des listes de courses partagées",
|
||||
"weeklyDigest": "Résumé hebdomadaire",
|
||||
"weeklyDigestDescription": "Un résumé hebdomadaire par e-mail des nouveaux abonnés, commentaires et notes, ainsi que des recettes tendance."
|
||||
},
|
||||
"featureToggles": {
|
||||
"title": "Fonctionnalités",
|
||||
"description": "Masquez les fonctionnalités que vous n'utilisez pas de votre navigation. Cela n'affecte que votre propre vue — les pages masquées restent accessibles par lien direct, rien n'est supprimé.",
|
||||
"nutrition": "Nutrition",
|
||||
"nutritionDescription": "Journal et objectifs nutritionnels.",
|
||||
"pantry": "Placard",
|
||||
"pantryDescription": "Suivez ce que vous avez sous la main.",
|
||||
"mealPlan": "Planning de repas",
|
||||
"mealPlanDescription": "Planification hebdomadaire des repas.",
|
||||
"shoppingLists": "Listes de courses",
|
||||
"shoppingListsDescription": "Listes de courses partagées.",
|
||||
"collections": "Collections",
|
||||
"collectionsDescription": "Organisez vos recettes en collections.",
|
||||
"messages": "Messages",
|
||||
"messagesDescription": "Messages directs avec d'autres cuisiniers."
|
||||
},
|
||||
"profile": "Profil",
|
||||
"changePhoto": "Changer la photo",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@epicure/web",
|
||||
"version": "0.60.0",
|
||||
"version": "0.61.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "next dev",
|
||||
|
||||
Reference in New Issue
Block a user