feat: developer access permission gates webhooks/API keys/BYOK (v0.71.0)
Webhooks, self-serve API keys, and BYOK AI provider keys had zero access gating -- any logged-in user, any tier. Adds users.isDeveloper (boolean, admin-toggled in admin/users/[id] alongside role/tier), checked via a single hasDeveloperAccess() (lib/permissions.ts) so a future subscription-tier auto-grant is a one-line change there, not a redesign across call sites. requireDeveloper() (lib/api-auth.ts) wraps requireSession() with a fresh isDeveloper check (same reasoning as requireAdmin re-querying role: session.user's cookieCache can be up to 5 minutes stale) and replaces requireSession in all 8 gated routes: webhooks CRUD + deliveries + redeliver, api-keys CRUD, ai-keys CRUD. Settings UI: the sidebar hides API Keys/Webhooks nav entries for non-developers; those pages and the BYOK section of Settings -> AI show a locked notice instead of the manager component when accessed directly. Migration grandfathers in anyone who already has a webhook, API key, or BYOK key row -- ships as a new gate on existing features, not a silent lockout of active integrations. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
@@ -6,6 +6,7 @@ import { UNLIMITED, getRecipeCount, getStorageUsedMb } from "@/lib/tiers";
|
||||
import { ByokManager } from "@/components/settings/byok-manager";
|
||||
import { ModelPrefsForm } from "@/components/settings/model-prefs-form";
|
||||
import { UsageQuotaSection } from "@/components/settings/usage-quota-section";
|
||||
import { DeveloperLockedNotice } from "@/components/settings/developer-locked-notice";
|
||||
import { getMessages, formatMessage } from "@/lib/i18n/server";
|
||||
|
||||
export const metadata: Metadata = {};
|
||||
@@ -27,7 +28,7 @@ export default async function AiSettingsPage() {
|
||||
}),
|
||||
// Tier comes from the DB, not the (up to 5-minute-stale) session cookie
|
||||
// cache, so a just-changed tier's limits show up immediately here.
|
||||
db.query.users.findFirst({ where: eq(users.id, session.user.id), columns: { tier: true } }),
|
||||
db.query.users.findFirst({ where: eq(users.id, session.user.id), columns: { tier: true, isDeveloper: true } }),
|
||||
]);
|
||||
|
||||
const [tierDef, usage, recipeCount, storageUsedMb] = await Promise.all([
|
||||
@@ -80,7 +81,11 @@ export default async function AiSettingsPage() {
|
||||
{m.settings.byok.description}
|
||||
</p>
|
||||
</div>
|
||||
<ByokManager initialKeys={aiKeys.map((k) => k.provider)} />
|
||||
{dbUser?.isDeveloper ? (
|
||||
<ByokManager initialKeys={aiKeys.map((k) => k.provider)} />
|
||||
) : (
|
||||
<DeveloperLockedNotice message={m.settings.developerLockedNotice} />
|
||||
)}
|
||||
</section>
|
||||
|
||||
<section className="rounded-xl border p-6 space-y-4">
|
||||
|
||||
@@ -3,8 +3,9 @@ import { headers } from "next/headers";
|
||||
import Link from "next/link";
|
||||
import { ExternalLink } from "lucide-react";
|
||||
import { auth } from "@/lib/auth/server";
|
||||
import { db, apiKeys, eq } from "@epicure/db";
|
||||
import { db, apiKeys, users, eq } from "@epicure/db";
|
||||
import { ApiKeysManager } from "@/components/settings/api-keys-manager";
|
||||
import { DeveloperLockedNotice } from "@/components/settings/developer-locked-notice";
|
||||
import { getMessages } from "@/lib/i18n/server";
|
||||
|
||||
export const metadata: Metadata = {};
|
||||
@@ -14,16 +15,20 @@ export default async function ApiKeysPage() {
|
||||
if (!session) return null;
|
||||
const m = getMessages((session.user as { locale?: string }).locale);
|
||||
|
||||
const keys = await db
|
||||
.select({
|
||||
id: apiKeys.id,
|
||||
name: apiKeys.name,
|
||||
scope: apiKeys.scope,
|
||||
lastUsedAt: apiKeys.lastUsedAt,
|
||||
createdAt: apiKeys.createdAt,
|
||||
})
|
||||
.from(apiKeys)
|
||||
.where(eq(apiKeys.userId, session.user.id));
|
||||
const dbUser = (await db.select({ isDeveloper: users.isDeveloper }).from(users).where(eq(users.id, session.user.id)).limit(1))[0];
|
||||
|
||||
const keys = dbUser?.isDeveloper
|
||||
? await db
|
||||
.select({
|
||||
id: apiKeys.id,
|
||||
name: apiKeys.name,
|
||||
scope: apiKeys.scope,
|
||||
lastUsedAt: apiKeys.lastUsedAt,
|
||||
createdAt: apiKeys.createdAt,
|
||||
})
|
||||
.from(apiKeys)
|
||||
.where(eq(apiKeys.userId, session.user.id))
|
||||
: [];
|
||||
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
@@ -42,15 +47,18 @@ export default async function ApiKeysPage() {
|
||||
{m.settings.apiKeysPage.docsLink}
|
||||
</Link>
|
||||
</div>
|
||||
<ApiKeysManager
|
||||
initialKeys={keys.map((k) => ({
|
||||
id: k.id,
|
||||
name: k.name,
|
||||
scope: k.scope,
|
||||
lastUsedAt: k.lastUsedAt ? k.lastUsedAt.toISOString() : null,
|
||||
createdAt: k.createdAt.toISOString(),
|
||||
}))}
|
||||
/>
|
||||
{!dbUser?.isDeveloper && <DeveloperLockedNotice message={m.settings.developerLockedNotice} />}
|
||||
{dbUser?.isDeveloper && (
|
||||
<ApiKeysManager
|
||||
initialKeys={keys.map((k) => ({
|
||||
id: k.id,
|
||||
name: k.name,
|
||||
scope: k.scope,
|
||||
lastUsedAt: k.lastUsedAt ? k.lastUsedAt.toISOString() : null,
|
||||
createdAt: k.createdAt.toISOString(),
|
||||
}))}
|
||||
/>
|
||||
)}
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { headers } from "next/headers";
|
||||
import { auth } from "@/lib/auth/server";
|
||||
import { db, users, eq } from "@epicure/db";
|
||||
import { SettingsSidebar } from "@/components/settings/settings-sidebar";
|
||||
import { getMessages } from "@/lib/i18n/server";
|
||||
|
||||
@@ -7,6 +8,10 @@ export default async function SettingsLayout({ children }: { children: React.Rea
|
||||
const session = await auth.api.getSession({ headers: await headers() });
|
||||
const m = getMessages((session?.user as { locale?: string })?.locale);
|
||||
|
||||
const dbUser = session
|
||||
? (await db.select({ isDeveloper: users.isDeveloper }).from(users).where(eq(users.id, session.user.id)).limit(1))[0]
|
||||
: undefined;
|
||||
|
||||
return (
|
||||
<div className="max-w-5xl mx-auto">
|
||||
<div className="mb-8">
|
||||
@@ -14,7 +19,7 @@ export default async function SettingsLayout({ children }: { children: React.Rea
|
||||
<p className="text-muted-foreground mt-1">{m.settings.subtitle}</p>
|
||||
</div>
|
||||
<div className="flex flex-col md:flex-row gap-4 md:gap-8 md:items-start">
|
||||
<SettingsSidebar />
|
||||
<SettingsSidebar isDeveloper={dbUser?.isDeveloper ?? false} />
|
||||
<main className="flex-1 min-w-0 space-y-6">{children}</main>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import type { Metadata } from "next";
|
||||
import { headers } from "next/headers";
|
||||
import { auth } from "@/lib/auth/server";
|
||||
import { db, webhooks, eq } from "@epicure/db";
|
||||
import { db, webhooks, users, eq } from "@epicure/db";
|
||||
import { WebhooksManager } from "@/components/settings/webhooks-manager";
|
||||
import { DeveloperLockedNotice } from "@/components/settings/developer-locked-notice";
|
||||
import { getMessages } from "@/lib/i18n/server";
|
||||
|
||||
export const metadata: Metadata = {};
|
||||
@@ -12,16 +13,20 @@ export default async function WebhooksPage() {
|
||||
if (!session) return null;
|
||||
const m = getMessages((session.user as { locale?: string }).locale);
|
||||
|
||||
const rows = await db
|
||||
.select({
|
||||
id: webhooks.id,
|
||||
url: webhooks.url,
|
||||
events: webhooks.events,
|
||||
active: webhooks.active,
|
||||
createdAt: webhooks.createdAt,
|
||||
})
|
||||
.from(webhooks)
|
||||
.where(eq(webhooks.userId, session.user.id));
|
||||
const dbUser = (await db.select({ isDeveloper: users.isDeveloper }).from(users).where(eq(users.id, session.user.id)).limit(1))[0];
|
||||
|
||||
const rows = dbUser?.isDeveloper
|
||||
? await db
|
||||
.select({
|
||||
id: webhooks.id,
|
||||
url: webhooks.url,
|
||||
events: webhooks.events,
|
||||
active: webhooks.active,
|
||||
createdAt: webhooks.createdAt,
|
||||
})
|
||||
.from(webhooks)
|
||||
.where(eq(webhooks.userId, session.user.id))
|
||||
: [];
|
||||
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
@@ -32,15 +37,18 @@ export default async function WebhooksPage() {
|
||||
{m.settings.webhooksPage.description}
|
||||
</p>
|
||||
</div>
|
||||
<WebhooksManager
|
||||
initialWebhooks={rows.map((w) => ({
|
||||
id: w.id,
|
||||
url: w.url,
|
||||
events: w.events,
|
||||
active: w.active,
|
||||
createdAt: w.createdAt.toISOString(),
|
||||
}))}
|
||||
/>
|
||||
{!dbUser?.isDeveloper && <DeveloperLockedNotice message={m.settings.developerLockedNotice} />}
|
||||
{dbUser?.isDeveloper && (
|
||||
<WebhooksManager
|
||||
initialWebhooks={rows.map((w) => ({
|
||||
id: w.id,
|
||||
url: w.url,
|
||||
events: w.events,
|
||||
active: w.active,
|
||||
createdAt: w.createdAt.toISOString(),
|
||||
}))}
|
||||
/>
|
||||
)}
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -102,7 +102,7 @@ export default async function AdminUserDetailPage({ params }: PageProps) {
|
||||
<CardTitle className="text-base">Edit Role & Tier</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<UserEditor userId={user.id} currentRole={user.role} currentTier={user.tier} />
|
||||
<UserEditor userId={user.id} currentRole={user.role} currentTier={user.tier} currentIsDeveloper={user.isDeveloper} />
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
|
||||
@@ -12,8 +12,8 @@ export async function PATCH(req: NextRequest, { params }: RouteContext) {
|
||||
if (response) return response;
|
||||
|
||||
const { id } = await params;
|
||||
const body = await req.json() as { role?: string; tier?: string };
|
||||
const { role, tier } = body;
|
||||
const body = await req.json() as { role?: string; tier?: string; isDeveloper?: boolean };
|
||||
const { role, tier, isDeveloper } = body;
|
||||
|
||||
const validRoles = ["user", "moderator", "admin"] as const;
|
||||
const validTiers = ["free", "pro", "family"] as const;
|
||||
@@ -24,18 +24,22 @@ export async function PATCH(req: NextRequest, { params }: RouteContext) {
|
||||
if (tier !== undefined && !validTiers.includes(tier as typeof validTiers[number])) {
|
||||
return NextResponse.json({ error: "Invalid tier" }, { status: 400 });
|
||||
}
|
||||
if (isDeveloper !== undefined && typeof isDeveloper !== "boolean") {
|
||||
return NextResponse.json({ error: "Invalid isDeveloper" }, { status: 400 });
|
||||
}
|
||||
|
||||
const updateData: Partial<{ role: "user" | "moderator" | "admin"; tier: "free" | "pro" | "family"; updatedAt: Date }> = {
|
||||
const updateData: Partial<{ role: "user" | "moderator" | "admin"; tier: "free" | "pro" | "family"; isDeveloper: boolean; updatedAt: Date }> = {
|
||||
updatedAt: new Date(),
|
||||
};
|
||||
if (role) updateData.role = role as "user" | "moderator" | "admin";
|
||||
if (tier) updateData.tier = tier as "free" | "pro" | "family";
|
||||
if (isDeveloper !== undefined) updateData.isDeveloper = isDeveloper;
|
||||
|
||||
const [updated] = await db
|
||||
.update(users)
|
||||
.set(updateData)
|
||||
.where(eq(users.id, id))
|
||||
.returning({ id: users.id, role: users.role, tier: users.tier });
|
||||
.returning({ id: users.id, role: users.role, tier: users.tier, isDeveloper: users.isDeveloper });
|
||||
|
||||
if (!updated) {
|
||||
return NextResponse.json({ error: "User not found" }, { status: 404 });
|
||||
@@ -48,7 +52,7 @@ export async function PATCH(req: NextRequest, { params }: RouteContext) {
|
||||
action: "admin.user.update",
|
||||
targetType: "user",
|
||||
targetId: id,
|
||||
metadata: JSON.stringify({ role, tier }),
|
||||
metadata: JSON.stringify({ role, tier, isDeveloper }),
|
||||
createdAt: new Date(),
|
||||
});
|
||||
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { db, userAiKeys, eq, and } from "@epicure/db";
|
||||
import { requireSession } from "@/lib/api-auth";
|
||||
import { requireDeveloper } from "@/lib/api-auth";
|
||||
|
||||
type Params = { params: Promise<{ provider: string }> };
|
||||
|
||||
export async function DELETE(_req: Request, { params }: Params) {
|
||||
const { session, response } = await requireSession();
|
||||
const { session, response } = await requireDeveloper();
|
||||
if (response) return response;
|
||||
|
||||
const { provider } = await params;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { db, userAiKeys, eq, and } from "@epicure/db";
|
||||
import { requireSession } from "@/lib/api-auth";
|
||||
import { requireDeveloper } from "@/lib/api-auth";
|
||||
import { encrypt } from "@/lib/encrypt";
|
||||
import { applyRateLimit } from "@/lib/rate-limit";
|
||||
|
||||
@@ -13,7 +13,7 @@ const PostSchema = z.object({
|
||||
});
|
||||
|
||||
export async function GET() {
|
||||
const { session, response } = await requireSession();
|
||||
const { session, response } = await requireDeveloper();
|
||||
if (response) return response;
|
||||
|
||||
const keys = await db.query.userAiKeys.findMany({
|
||||
@@ -25,7 +25,7 @@ export async function GET() {
|
||||
}
|
||||
|
||||
export async function POST(req: Request) {
|
||||
const { session, response } = await requireSession();
|
||||
const { session, response } = await requireDeveloper();
|
||||
if (response) return response;
|
||||
|
||||
const limited = await applyRateLimit(`rl:ai-keys:${session!.user.id}`, 5, 3600);
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { db, apiKeys, eq, and } from "@epicure/db";
|
||||
import { requireSession } from "@/lib/api-auth";
|
||||
import { requireDeveloper } from "@/lib/api-auth";
|
||||
|
||||
export async function DELETE(
|
||||
_req: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
const { session, response } = await requireSession();
|
||||
const { session, response } = await requireDeveloper();
|
||||
if (response) return response;
|
||||
|
||||
const { id } = await params;
|
||||
|
||||
@@ -2,7 +2,7 @@ import { NextRequest, NextResponse } from "next/server";
|
||||
import crypto from "node:crypto";
|
||||
import { z } from "zod";
|
||||
import { db, apiKeys, eq, sql } from "@epicure/db";
|
||||
import { requireSession } from "@/lib/api-auth";
|
||||
import { requireDeveloper } from "@/lib/api-auth";
|
||||
|
||||
const CreateApiKeyBody = z.object({
|
||||
name: z.string().min(1).max(100),
|
||||
@@ -10,7 +10,7 @@ const CreateApiKeyBody = z.object({
|
||||
});
|
||||
|
||||
export async function GET() {
|
||||
const { session, response } = await requireSession();
|
||||
const { session, response } = await requireDeveloper();
|
||||
if (response) return response;
|
||||
|
||||
const rows = await db
|
||||
@@ -28,7 +28,7 @@ export async function GET() {
|
||||
}
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
const { session, response } = await requireSession();
|
||||
const { session, response } = await requireDeveloper();
|
||||
if (response) return response;
|
||||
|
||||
const body = await req.json() as unknown;
|
||||
|
||||
@@ -4,7 +4,7 @@ import { NextRequest } from "next/server";
|
||||
const mockSession = { user: { id: "user-1" } };
|
||||
|
||||
vi.mock("@/lib/api-auth", () => ({
|
||||
requireSession: vi.fn(),
|
||||
requireDeveloper: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/validate-webhook-url", () => ({
|
||||
@@ -33,7 +33,7 @@ vi.mock("@epicure/db", () => ({
|
||||
and: vi.fn((...args) => ({ args, op: "and" })),
|
||||
}));
|
||||
|
||||
const { requireSession } = await import("@/lib/api-auth");
|
||||
const { requireDeveloper } = await import("@/lib/api-auth");
|
||||
const { validateWebhookUrl } = await import("@/lib/validate-webhook-url");
|
||||
import { DELETE, PATCH } from "../route";
|
||||
|
||||
@@ -49,7 +49,7 @@ const ctx = { params: Promise.resolve({ id: "wh-1" }) };
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(requireSession).mockResolvedValue({ session: mockSession as never, response: null });
|
||||
vi.mocked(requireDeveloper).mockResolvedValue({ session: mockSession as never, response: null });
|
||||
vi.mocked(validateWebhookUrl).mockResolvedValue(null);
|
||||
mockSelectChain.limit.mockResolvedValue([{ id: "wh-1" }]);
|
||||
});
|
||||
|
||||
@@ -4,7 +4,7 @@ import { NextRequest } from "next/server";
|
||||
const mockSession = { user: { id: "user-1" } };
|
||||
|
||||
vi.mock("@/lib/api-auth", () => ({
|
||||
requireSession: vi.fn(),
|
||||
requireDeveloper: vi.fn(),
|
||||
}));
|
||||
|
||||
const { mockFindFirst, mockSelectChain } = vi.hoisted(() => {
|
||||
@@ -29,21 +29,21 @@ vi.mock("@epicure/db", () => ({
|
||||
desc: vi.fn((a) => ({ a, op: "desc" })),
|
||||
}));
|
||||
|
||||
const { requireSession } = await import("@/lib/api-auth");
|
||||
const { requireDeveloper } = await import("@/lib/api-auth");
|
||||
import { GET } from "../route";
|
||||
|
||||
const ctx = { params: Promise.resolve({ id: "wh-1" }) };
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(requireSession).mockResolvedValue({ session: mockSession as never, response: null });
|
||||
vi.mocked(requireDeveloper).mockResolvedValue({ session: mockSession as never, response: null });
|
||||
mockFindFirst.mockResolvedValue({ id: "wh-1" });
|
||||
mockSelectChain.limit.mockResolvedValue([]);
|
||||
});
|
||||
|
||||
describe("GET /api/v1/webhooks/[id]/deliveries", () => {
|
||||
it("returns 401 when not authenticated", async () => {
|
||||
vi.mocked(requireSession).mockResolvedValue({
|
||||
vi.mocked(requireDeveloper).mockResolvedValue({
|
||||
session: null,
|
||||
response: new Response(JSON.stringify({ error: "Unauthorized" }), { status: 401 }),
|
||||
} as never);
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { db, webhooks, webhookDeliveries, eq, and, desc } from "@epicure/db";
|
||||
import { requireSession } from "@/lib/api-auth";
|
||||
import { requireDeveloper } from "@/lib/api-auth";
|
||||
|
||||
type Params = { params: Promise<{ id: string }> };
|
||||
|
||||
export async function GET(_req: NextRequest, { params }: Params) {
|
||||
const { session, response } = await requireSession();
|
||||
const { session, response } = await requireDeveloper();
|
||||
if (response) return response;
|
||||
|
||||
const { id } = await params;
|
||||
|
||||
@@ -4,7 +4,7 @@ import { NextRequest } from "next/server";
|
||||
const mockSession = { user: { id: "user-1" } };
|
||||
|
||||
vi.mock("@/lib/api-auth", () => ({
|
||||
requireSession: vi.fn(),
|
||||
requireDeveloper: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/webhooks", () => ({
|
||||
@@ -29,7 +29,7 @@ vi.mock("@epicure/db", () => ({
|
||||
and: vi.fn((...args) => ({ args, op: "and" })),
|
||||
}));
|
||||
|
||||
const { requireSession } = await import("@/lib/api-auth");
|
||||
const { requireDeveloper } = await import("@/lib/api-auth");
|
||||
const { dispatchWebhook } = await import("@/lib/webhooks");
|
||||
import { POST } from "../route";
|
||||
|
||||
@@ -47,7 +47,7 @@ const ctx = { params: Promise.resolve({ id: "wh-1" }) };
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(requireSession).mockResolvedValue({ session: mockSession as never, response: null });
|
||||
vi.mocked(requireDeveloper).mockResolvedValue({ session: mockSession as never, response: null });
|
||||
mockWebhookFindFirst.mockResolvedValue({ id: "wh-1" });
|
||||
mockDeliveryFindFirst.mockResolvedValue({
|
||||
id: VALID_DELIVERY_ID,
|
||||
@@ -58,7 +58,7 @@ beforeEach(() => {
|
||||
|
||||
describe("POST /api/v1/webhooks/[id]/redeliver", () => {
|
||||
it("returns 401 when not authenticated", async () => {
|
||||
vi.mocked(requireSession).mockResolvedValue({
|
||||
vi.mocked(requireDeveloper).mockResolvedValue({
|
||||
session: null,
|
||||
response: new Response(JSON.stringify({ error: "Unauthorized" }), { status: 401 }),
|
||||
} as never);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { db, webhooks, webhookDeliveries, eq, and } from "@epicure/db";
|
||||
import { requireSession } from "@/lib/api-auth";
|
||||
import { requireDeveloper } from "@/lib/api-auth";
|
||||
import { dispatchWebhook, type WebhookEvent } from "@/lib/webhooks";
|
||||
|
||||
const Schema = z.object({ deliveryId: z.string().uuid() });
|
||||
@@ -9,7 +9,7 @@ const Schema = z.object({ deliveryId: z.string().uuid() });
|
||||
type Params = { params: Promise<{ id: string }> };
|
||||
|
||||
export async function POST(req: NextRequest, { params }: Params) {
|
||||
const { session, response } = await requireSession();
|
||||
const { session, response } = await requireDeveloper();
|
||||
if (response) return response;
|
||||
|
||||
const { id } = await params;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { db, webhooks, eq, and } from "@epicure/db";
|
||||
import { requireSession } from "@/lib/api-auth";
|
||||
import { requireDeveloper } from "@/lib/api-auth";
|
||||
import { validateWebhookUrl } from "@/lib/validate-webhook-url";
|
||||
import { WEBHOOK_EVENTS } from "@/lib/webhooks";
|
||||
|
||||
@@ -15,7 +15,7 @@ export async function DELETE(
|
||||
_req: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
const { session, response } = await requireSession();
|
||||
const { session, response } = await requireDeveloper();
|
||||
if (response) return response;
|
||||
|
||||
const { id } = await params;
|
||||
@@ -41,7 +41,7 @@ export async function PATCH(
|
||||
req: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
const { session, response } = await requireSession();
|
||||
const { session, response } = await requireDeveloper();
|
||||
if (response) return response;
|
||||
|
||||
const { id } = await params;
|
||||
|
||||
@@ -4,7 +4,7 @@ import { NextRequest } from "next/server";
|
||||
const mockSession = { user: { id: "user-1" } };
|
||||
|
||||
vi.mock("@/lib/api-auth", () => ({
|
||||
requireSession: vi.fn(),
|
||||
requireDeveloper: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/validate-webhook-url", () => ({
|
||||
@@ -28,7 +28,7 @@ vi.mock("@epicure/db", () => ({
|
||||
eq: vi.fn((a, b) => ({ a, b, op: "eq" })),
|
||||
}));
|
||||
|
||||
const { requireSession } = await import("@/lib/api-auth");
|
||||
const { requireDeveloper } = await import("@/lib/api-auth");
|
||||
const { validateWebhookUrl } = await import("@/lib/validate-webhook-url");
|
||||
import { GET, POST } from "../route";
|
||||
|
||||
@@ -42,14 +42,14 @@ function makeRequest(method: string, body?: unknown) {
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(requireSession).mockResolvedValue({ session: mockSession as never, response: null });
|
||||
vi.mocked(requireDeveloper).mockResolvedValue({ session: mockSession as never, response: null });
|
||||
vi.mocked(validateWebhookUrl).mockResolvedValue(null);
|
||||
mockSelectChain.where.mockResolvedValue([]);
|
||||
});
|
||||
|
||||
describe("GET /api/v1/webhooks", () => {
|
||||
it("returns 401 when not authenticated", async () => {
|
||||
vi.mocked(requireSession).mockResolvedValue({
|
||||
vi.mocked(requireDeveloper).mockResolvedValue({
|
||||
session: null,
|
||||
response: new Response(JSON.stringify({ error: "Unauthorized" }), { status: 401 }),
|
||||
} as never);
|
||||
@@ -82,7 +82,7 @@ describe("POST /api/v1/webhooks", () => {
|
||||
});
|
||||
|
||||
it("returns 401 when not authenticated", async () => {
|
||||
vi.mocked(requireSession).mockResolvedValue({
|
||||
vi.mocked(requireDeveloper).mockResolvedValue({
|
||||
session: null,
|
||||
response: new Response(JSON.stringify({ error: "Unauthorized" }), { status: 401 }),
|
||||
} as never);
|
||||
|
||||
@@ -2,7 +2,7 @@ import { NextRequest, NextResponse } from "next/server";
|
||||
import crypto from "node:crypto";
|
||||
import { z } from "zod";
|
||||
import { db, webhooks, eq } from "@epicure/db";
|
||||
import { requireSession } from "@/lib/api-auth";
|
||||
import { requireDeveloper } from "@/lib/api-auth";
|
||||
import { validateWebhookUrl } from "@/lib/validate-webhook-url";
|
||||
import { WEBHOOK_EVENTS } from "@/lib/webhooks";
|
||||
import { encrypt } from "@/lib/encrypt";
|
||||
@@ -19,7 +19,7 @@ const UpdateWebhookBody = z.object({
|
||||
});
|
||||
|
||||
export async function GET() {
|
||||
const { session, response } = await requireSession();
|
||||
const { session, response } = await requireDeveloper();
|
||||
if (response) return response;
|
||||
|
||||
const rows = await db
|
||||
@@ -38,7 +38,7 @@ export async function GET() {
|
||||
}
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
const { session, response } = await requireSession();
|
||||
const { session, response } = await requireDeveloper();
|
||||
if (response) return response;
|
||||
|
||||
const body = await req.json() as unknown;
|
||||
|
||||
@@ -11,16 +11,19 @@ import {
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
|
||||
interface UserEditorProps {
|
||||
userId: string;
|
||||
currentRole: "user" | "moderator" | "admin";
|
||||
currentTier: "free" | "pro" | "family";
|
||||
currentIsDeveloper: boolean;
|
||||
}
|
||||
|
||||
export function UserEditor({ userId, currentRole, currentTier }: UserEditorProps) {
|
||||
export function UserEditor({ userId, currentRole, currentTier, currentIsDeveloper }: UserEditorProps) {
|
||||
const [role, setRole] = useState<"user" | "moderator" | "admin">(currentRole);
|
||||
const [tier, setTier] = useState<"free" | "pro" | "family">(currentTier);
|
||||
const [isDeveloper, setIsDeveloper] = useState(currentIsDeveloper);
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
||||
async function handleSave() {
|
||||
@@ -29,7 +32,7 @@ export function UserEditor({ userId, currentRole, currentTier }: UserEditorProps
|
||||
const res = await fetch(`/api/v1/admin/users/${userId}`, {
|
||||
method: "PATCH",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ role, tier }),
|
||||
body: JSON.stringify({ role, tier, isDeveloper }),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const data = await res.json().catch(() => ({}));
|
||||
@@ -73,6 +76,13 @@ export function UserEditor({ userId, currentRole, currentTier }: UserEditorProps
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center justify-between gap-3 rounded-lg border p-3 max-w-md">
|
||||
<div>
|
||||
<Label htmlFor="developer-switch">Developer access</Label>
|
||||
<p className="text-xs text-muted-foreground">Enables webhooks, self-serve API keys, and BYOK AI provider keys.</p>
|
||||
</div>
|
||||
<Switch id="developer-switch" checked={isDeveloper} onCheckedChange={setIsDeveloper} />
|
||||
</div>
|
||||
<div>
|
||||
<Button onClick={handleSave} disabled={saving}>
|
||||
{saving ? "Saving…" : "Save Changes"}
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
import { Lock } from "lucide-react";
|
||||
|
||||
export function DeveloperLockedNotice({ message }: { message: string }) {
|
||||
return (
|
||||
<div className="flex items-start gap-3 rounded-lg border bg-muted/30 p-4 text-sm text-muted-foreground">
|
||||
<Lock className="h-4 w-4 shrink-0 mt-0.5" />
|
||||
<p>{message}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -17,14 +17,18 @@ const NAV_ITEMS = [
|
||||
{ href: "/settings/webhooks", key: "webhooks", icon: Webhook, exact: false },
|
||||
] as const;
|
||||
|
||||
export function SettingsSidebar() {
|
||||
const DEVELOPER_ONLY_KEYS = new Set(["apiKeys", "webhooks"]);
|
||||
|
||||
export function SettingsSidebar({ isDeveloper }: { isDeveloper: boolean }) {
|
||||
const pathname = usePathname();
|
||||
const t = useTranslations("settings");
|
||||
|
||||
const visibleItems = NAV_ITEMS.filter((item) => isDeveloper || !DEVELOPER_ONLY_KEYS.has(item.key));
|
||||
|
||||
return (
|
||||
<nav className="w-full md:w-48 md:shrink-0 md:sticky md:top-6">
|
||||
<ul className="flex overflow-x-auto gap-1 pb-2 -mx-4 px-4 md:mx-0 md:px-0 md:flex-col md:overflow-visible md:gap-0.5 md:pb-0 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
|
||||
{NAV_ITEMS.map(({ href, key, icon: Icon, exact }) => {
|
||||
{visibleItems.map(({ href, key, icon: Icon, exact }) => {
|
||||
const active = exact ? pathname === href : pathname.startsWith(href);
|
||||
return (
|
||||
<li key={href} className="shrink-0 md:shrink">
|
||||
|
||||
@@ -4,6 +4,7 @@ import { NextRequest, NextResponse } from "next/server";
|
||||
import { auth } from "@/lib/auth/server";
|
||||
import { db, apiKeys, users, eq } from "@epicure/db";
|
||||
import { applyRateLimit } from "@/lib/rate-limit";
|
||||
import { hasDeveloperAccess } from "@/lib/permissions";
|
||||
|
||||
export async function requireSession() {
|
||||
const session = await auth.api.getSession({ headers: await headers() });
|
||||
@@ -39,6 +40,29 @@ export async function requireAdmin(opts?: { allowModerator?: boolean }) {
|
||||
return { session, response: null };
|
||||
}
|
||||
|
||||
/** Gates webhooks, self-serve API keys, and BYOK routes behind
|
||||
* users.isDeveloper — re-queried fresh for the same reason requireAdmin
|
||||
* re-queries role (session.user's cookieCache can be up to 5 minutes
|
||||
* stale, e.g. right after an admin grants access). */
|
||||
export async function requireDeveloper() {
|
||||
const { session, response } = await requireSession();
|
||||
if (response) return { session: null, response };
|
||||
|
||||
const [dbUser] = await db
|
||||
.select({ isDeveloper: users.isDeveloper })
|
||||
.from(users)
|
||||
.where(eq(users.id, session!.user.id))
|
||||
.limit(1);
|
||||
|
||||
if (!dbUser || !hasDeveloperAccess(dbUser)) {
|
||||
return {
|
||||
session: null,
|
||||
response: NextResponse.json({ error: "Developer access required — ask an admin to enable it" }, { status: 403 }),
|
||||
};
|
||||
}
|
||||
return { session, response: null };
|
||||
}
|
||||
|
||||
type SessionLike = {
|
||||
user: {
|
||||
id: string;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// Mirrors CHANGELOG.md at the repo root — update both together.
|
||||
export const APP_VERSION = "0.70.0";
|
||||
export const APP_VERSION = "0.71.0";
|
||||
|
||||
export type ChangelogEntry = {
|
||||
version: string;
|
||||
@@ -11,6 +11,13 @@ export type ChangelogEntry = {
|
||||
};
|
||||
|
||||
export const CHANGELOG: ChangelogEntry[] = [
|
||||
{
|
||||
version: "0.71.0",
|
||||
date: "2026-07-22 10:00",
|
||||
added: [
|
||||
"New \"developer access\" permission, admin-toggled per user (Admin -> Users), gates webhooks, self-serve API keys, and BYOK AI provider keys — previously available to every logged-in user with no gating at all. Anyone who already had a webhook, API key, or BYOK key configured keeps access automatically.",
|
||||
],
|
||||
},
|
||||
{
|
||||
version: "0.70.0",
|
||||
date: "2026-07-22 09:30",
|
||||
|
||||
+15
-14
@@ -584,18 +584,18 @@ export function generateOpenApiSpec(): object {
|
||||
registry.registerPath({ method: "delete", path: "/api/v1/shopping-lists/{id}/members", summary: "Remove a collaborator (owner or the member themselves)", security, request: { params: idParam, query: z.object({ memberId: z.string() }) }, responses: { 204: { description: "Removed" }, 400: { description: "memberId required", 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/shopping-lists/{id}/export", summary: "Export items in a normalized grocery-provider format", security, request: { params: idParam }, responses: { 200: { description: "Export payload", content: { "application/json": { schema: GroceryExportRef } } }, 404: { description: "Not found", content: { "application/json": { schema: ApiErrorRef } } } } });
|
||||
registry.registerPath({ method: "post", path: "/api/v1/shopping-lists/{id}/export/instacart", summary: "Create an Instacart shopping-list link", description: "501 if Instacart isn't configured server-side.", security, request: { params: idParam }, responses: { 200: { description: "Link", content: { "application/json": { schema: z.record(z.string(), z.unknown()) } } }, 404: { description: "Not found", content: { "application/json": { schema: ApiErrorRef } } }, 501: { description: "Not configured", content: { "application/json": { schema: ApiErrorRef } } } } });
|
||||
registry.registerPath({ method: "get", path: "/api/v1/api-keys", summary: "List API keys", security, responses: { 200: { description: "Keys (hash never returned)", content: { "application/json": { schema: z.array(ApiKeyRef) } } }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } } } });
|
||||
registry.registerPath({ method: "post", path: "/api/v1/api-keys", summary: "Create API key", security, request: { body: { content: { "application/json": { schema: z.object({ name: z.string().min(1).max(100), scope: z.enum(["full", "read"]).default("full").describe("read-only keys can only make GET requests") }) } }, required: true } }, responses: { 201: { description: "Key created — shown once", content: { "application/json": { schema: CreateApiKeyResponseRef } } }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } }, 403: { description: "API key limit reached (max 10)", content: { "application/json": { schema: ApiErrorRef } } } } });
|
||||
registry.registerPath({ method: "delete", path: "/api/v1/api-keys/{id}", summary: "Revoke API key", security, request: { params: idParam }, responses: { 204: { description: "Revoked" }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } }, 404: { description: "Not found", content: { "application/json": { schema: ApiErrorRef } } } } });
|
||||
registry.registerPath({ method: "get", path: "/api/v1/api-keys", summary: "List API keys", description: "Requires developer access (an admin must enable it for your account).", security, responses: { 200: { description: "Keys (hash never returned)", content: { "application/json": { schema: z.array(ApiKeyRef) } } }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } }, 403: { description: "Developer access required", content: { "application/json": { schema: ApiErrorRef } } } } });
|
||||
registry.registerPath({ method: "post", path: "/api/v1/api-keys", summary: "Create API key", description: "Requires developer access (an admin must enable it for your account).", security, request: { body: { content: { "application/json": { schema: z.object({ name: z.string().min(1).max(100), scope: z.enum(["full", "read"]).default("full").describe("read-only keys can only make GET requests") }) } }, required: true } }, responses: { 201: { description: "Key created — shown once", content: { "application/json": { schema: CreateApiKeyResponseRef } } }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } }, 403: { description: "Developer access required, or API key limit reached (max 10)", content: { "application/json": { schema: ApiErrorRef } } } } });
|
||||
registry.registerPath({ method: "delete", path: "/api/v1/api-keys/{id}", summary: "Revoke API key", description: "Requires developer access (an admin must enable it for your account).", security, request: { params: idParam }, responses: { 204: { description: "Revoked" }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } }, 403: { description: "Developer access required", content: { "application/json": { schema: ApiErrorRef } } }, 404: { description: "Not found", content: { "application/json": { schema: ApiErrorRef } } } } });
|
||||
|
||||
// --- AI keys: users' own third-party provider keys (BYOK), used instead of app-wide AI credentials ---
|
||||
const AiKeyRef = registry.register("AiKey", z.object({
|
||||
provider: z.enum(["openai", "anthropic", "openrouter", "ollama"]), createdAt: z.string().datetime(),
|
||||
}).describe("Never includes the encrypted key value itself — only which providers are configured."));
|
||||
|
||||
registry.registerPath({ method: "get", path: "/api/v1/ai-keys", summary: "List your configured AI provider keys", description: "Returns only provider + createdAt — the encrypted key value is never exposed via the API.", security, responses: { 200: { description: "Configured providers", content: { "application/json": { schema: z.object({ keys: z.array(AiKeyRef) }) } } }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } } } });
|
||||
registry.registerPath({ method: "post", path: "/api/v1/ai-keys", summary: "Set (or replace) your API key for a provider", description: "Rate-limited: 5 req/hour. The key is encrypted at rest; it is never echoed back in any response.", security, request: { body: { content: { "application/json": { schema: z.object({ provider: z.enum(["openai", "anthropic", "openrouter", "ollama"]), apiKey: z.string().min(1).max(500) }) } }, required: true } }, responses: { 200: { description: "Saved", 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 } } }, 429: { description: "Rate limited", content: { "application/json": { schema: ApiErrorRef } } } } });
|
||||
registry.registerPath({ method: "delete", path: "/api/v1/ai-keys/{provider}", summary: "Remove your stored key for a provider", security, request: { params: z.object({ provider: z.enum(["openai", "anthropic", "openrouter", "ollama"]) }) }, responses: { 200: { description: "Removed", content: { "application/json": { schema: z.object({ ok: z.boolean() }) } } }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } } } });
|
||||
registry.registerPath({ method: "get", path: "/api/v1/ai-keys", summary: "List your configured AI provider keys", description: "Returns only provider + createdAt — the encrypted key value is never exposed via the API. Requires developer access (an admin must enable it for your account).", security, responses: { 200: { description: "Configured providers", content: { "application/json": { schema: z.object({ keys: z.array(AiKeyRef) }) } } }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } }, 403: { description: "Developer access required", content: { "application/json": { schema: ApiErrorRef } } } } });
|
||||
registry.registerPath({ method: "post", path: "/api/v1/ai-keys", summary: "Set (or replace) your API key for a provider", description: "Rate-limited: 5 req/hour. The key is encrypted at rest; it is never echoed back in any response. Requires developer access (an admin must enable it for your account).", security, request: { body: { content: { "application/json": { schema: z.object({ provider: z.enum(["openai", "anthropic", "openrouter", "ollama"]), apiKey: z.string().min(1).max(500) }) } }, required: true } }, responses: { 200: { description: "Saved", 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: "Developer access required", content: { "application/json": { schema: ApiErrorRef } } }, 429: { description: "Rate limited", content: { "application/json": { schema: ApiErrorRef } } } } });
|
||||
registry.registerPath({ method: "delete", path: "/api/v1/ai-keys/{provider}", summary: "Remove your stored key for a provider", description: "Requires developer access (an admin must enable it for your account).", security, request: { params: z.object({ provider: z.enum(["openai", "anthropic", "openrouter", "ollama"]) }) }, responses: { 200: { description: "Removed", content: { "application/json": { schema: z.object({ ok: z.boolean() }) } } }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } }, 403: { description: "Developer access required", content: { "application/json": { schema: ApiErrorRef } } } } });
|
||||
|
||||
// --- Webhooks: outbound event notifications to a user-provided URL, plus delivery log/redelivery ---
|
||||
const WebhookEventEnum = z.enum(["recipe.created", "recipe.updated", "recipe.published", "recipe.deleted", "meal_plan.updated", "shopping_list.completed", "comment.added"]);
|
||||
@@ -618,12 +618,12 @@ export function generateOpenApiSpec(): object {
|
||||
statusCode: z.number().int().nullable(), success: z.boolean(), attempts: z.number().int(), createdAt: z.string().datetime(),
|
||||
}));
|
||||
|
||||
registry.registerPath({ method: "get", path: "/api/v1/webhooks", summary: "List your webhooks", description: "The signing secret is never included — it is only ever returned once, at creation time.", security, responses: { 200: { description: "Webhooks", content: { "application/json": { schema: z.array(WebhookRef) } } }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } } } });
|
||||
registry.registerPath({ method: "post", path: "/api/v1/webhooks", summary: "Create a webhook", description: "Validates the URL against SSRF targets. Generates a signing secret returned once in this response only.", security, request: { body: { content: { "application/json": { schema: CreateWebhookRef } }, required: true } }, responses: { 201: { description: "Created — includes the signing secret (write-once)", content: { "application/json": { schema: CreatedWebhookRef } } }, 400: { description: "Validation error or blocked URL", content: { "application/json": { schema: ApiErrorRef } } }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } } } });
|
||||
registry.registerPath({ method: "patch", path: "/api/v1/webhooks/{id}", summary: "Update a webhook's URL, events, or active state", description: "Validates the URL against SSRF targets if changed.", security, request: { params: idParam, body: { content: { "application/json": { schema: UpdateWebhookRef } }, required: true } }, responses: { 200: { description: "Updated", content: { "application/json": { schema: WebhookRef } } }, 400: { description: "Validation error, blocked URL, or no fields to update", content: { "application/json": { schema: ApiErrorRef } } }, 404: { description: "Not found", content: { "application/json": { schema: ApiErrorRef } } } } });
|
||||
registry.registerPath({ method: "delete", path: "/api/v1/webhooks/{id}", summary: "Delete a webhook", security, request: { params: idParam }, responses: { 204: { description: "Deleted" }, 404: { description: "Not found", content: { "application/json": { schema: ApiErrorRef } } } } });
|
||||
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 } } } } });
|
||||
registry.registerPath({ method: "get", path: "/api/v1/webhooks", summary: "List your webhooks", description: "The signing secret is never included — it is only ever returned once, at creation time. Requires developer access (an admin must enable it for your account).", security, responses: { 200: { description: "Webhooks", content: { "application/json": { schema: z.array(WebhookRef) } } }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } }, 403: { description: "Developer access required", content: { "application/json": { schema: ApiErrorRef } } } } });
|
||||
registry.registerPath({ method: "post", path: "/api/v1/webhooks", summary: "Create a webhook", description: "Validates the URL against SSRF targets. Generates a signing secret returned once in this response only. Requires developer access (an admin must enable it for your account).", security, request: { body: { content: { "application/json": { schema: CreateWebhookRef } }, required: true } }, responses: { 201: { description: "Created — includes the signing secret (write-once)", content: { "application/json": { schema: CreatedWebhookRef } } }, 400: { description: "Validation error or blocked URL", content: { "application/json": { schema: ApiErrorRef } } }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } }, 403: { description: "Developer access required", content: { "application/json": { schema: ApiErrorRef } } } } });
|
||||
registry.registerPath({ method: "patch", path: "/api/v1/webhooks/{id}", summary: "Update a webhook's URL, events, or active state", description: "Validates the URL against SSRF targets if changed. Requires developer access (an admin must enable it for your account).", security, request: { params: idParam, body: { content: { "application/json": { schema: UpdateWebhookRef } }, required: true } }, responses: { 200: { description: "Updated", content: { "application/json": { schema: WebhookRef } } }, 400: { description: "Validation error, blocked URL, or no fields to update", content: { "application/json": { schema: ApiErrorRef } } }, 403: { description: "Developer access required", content: { "application/json": { schema: ApiErrorRef } } }, 404: { description: "Not found", content: { "application/json": { schema: ApiErrorRef } } } } });
|
||||
registry.registerPath({ method: "delete", path: "/api/v1/webhooks/{id}", summary: "Delete a webhook", description: "Requires developer access (an admin must enable it for your account).", security, request: { params: idParam }, responses: { 204: { description: "Deleted" }, 403: { description: "Developer access required", content: { "application/json": { schema: ApiErrorRef } } }, 404: { description: "Not found", content: { "application/json": { schema: ApiErrorRef } } } } });
|
||||
registry.registerPath({ method: "get", path: "/api/v1/webhooks/{id}/deliveries", summary: "List recent delivery attempts (most recent 20)", description: "Requires developer access (an admin must enable it for your account).", security, request: { params: idParam }, responses: { 200: { description: "Deliveries, newest first", content: { "application/json": { schema: z.array(WebhookDeliveryRef) } } }, 403: { description: "Developer access required", content: { "application/json": { schema: ApiErrorRef } } }, 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", description: "Requires developer access (an admin must enable it for your account).", 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 } } }, 403: { description: "Developer access required", 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({
|
||||
@@ -879,9 +879,10 @@ export function generateOpenApiSpec(): object {
|
||||
|
||||
const AdminUpdateUserBodyRef = registry.register("AdminUpdateUserBody", z.object({
|
||||
role: z.enum(["user", "moderator", "admin"]).optional(), tier: z.enum(["free", "pro", "family"]).optional(),
|
||||
isDeveloper: z.boolean().optional().describe("Gates webhooks, self-serve API keys, and BYOK AI provider keys."),
|
||||
}));
|
||||
const AdminUpdatedUserRef = registry.register("AdminUpdatedUser", z.object({
|
||||
user: z.object({ id: z.string(), role: z.string(), tier: z.string() }),
|
||||
user: z.object({ id: z.string(), role: z.string(), tier: z.string(), isDeveloper: z.boolean() }),
|
||||
}));
|
||||
|
||||
const AdminUserUsageRef = registry.register("AdminUserUsage", z.object({
|
||||
@@ -933,7 +934,7 @@ export function generateOpenApiSpec(): object {
|
||||
registry.registerPath({ method: "patch", path: "/api/v1/admin/feature-flags", summary: "Enable or disable a feature for a tier", description: "Admin only. Disabling a feature doesn't hide its button client-side — the corresponding AI route (variations/drinks/pairings) returns 403 with code FEATURE_DISABLED for users on that tier, and the UI shows an upgrade prompt instead.", security: adminSecurity, request: { body: { content: { "application/json": { schema: UpdateFeatureFlagRef } }, required: true } }, responses: { 200: { description: "Saved", content: { "application/json": { schema: z.object({ ok: z.boolean() }) } } }, 400: { description: "Validation error", content: { "application/json": { schema: ApiErrorRef } } }, 403: { description: "Forbidden", content: { "application/json": { schema: ApiErrorRef } } } } });
|
||||
|
||||
registry.registerPath({ method: "post", path: "/api/v1/admin/users", summary: "Create a user directly (bypasses open/closed signup state via an internal one-time invite)", description: "Admin only. The new user is created email-verified with a random unusable password, then sent a password-reset email so they can set their own.", security: adminSecurity, request: { body: { content: { "application/json": { schema: AdminCreateUserBodyRef } }, required: true } }, responses: { 200: { description: "Created", content: { "application/json": { schema: AdminCreatedUserRef } } }, 400: { description: "Missing fields, invalid role/tier, or Better Auth signup error", content: { "application/json": { schema: ApiErrorRef } } }, 403: { description: "Forbidden", content: { "application/json": { schema: ApiErrorRef } } }, 409: { description: "A user with this email already exists", content: { "application/json": { schema: ApiErrorRef } } }, 500: { description: "User creation failed", content: { "application/json": { schema: ApiErrorRef } } } } });
|
||||
registry.registerPath({ method: "patch", path: "/api/v1/admin/users/{id}", summary: "Update a user's role and/or tier", description: "Admin only.", security: adminSecurity, request: { params: idParam, body: { content: { "application/json": { schema: AdminUpdateUserBodyRef } } } }, responses: { 200: { description: "Updated", content: { "application/json": { schema: AdminUpdatedUserRef } } }, 400: { description: "Invalid role or tier", content: { "application/json": { schema: ApiErrorRef } } }, 403: { description: "Forbidden", content: { "application/json": { schema: ApiErrorRef } } }, 404: { description: "User not found", content: { "application/json": { schema: ApiErrorRef } } } } });
|
||||
registry.registerPath({ method: "patch", path: "/api/v1/admin/users/{id}", summary: "Update a user's role, tier, and/or developer access", description: "Admin only.", security: adminSecurity, request: { params: idParam, body: { content: { "application/json": { schema: AdminUpdateUserBodyRef } } } }, responses: { 200: { description: "Updated", content: { "application/json": { schema: AdminUpdatedUserRef } } }, 400: { description: "Invalid role or tier", content: { "application/json": { schema: ApiErrorRef } } }, 403: { description: "Forbidden", content: { "application/json": { schema: ApiErrorRef } } }, 404: { description: "User not found", content: { "application/json": { schema: ApiErrorRef } } } } });
|
||||
registry.registerPath({ method: "patch", path: "/api/v1/admin/users/{id}/usage", summary: "Reset a user's AI call count for the current month", description: "Admin only. Recipe count and storage are lifetime totals derived from real data, not resettable counters.", security: adminSecurity, request: { params: idParam }, responses: { 200: { description: "Reset usage (zeros, whether or not a usage row already existed)", content: { "application/json": { schema: z.object({ usage: AdminUserUsageRef }) } } }, 403: { description: "Forbidden", content: { "application/json": { schema: ApiErrorRef } } } } });
|
||||
|
||||
const generator = new OpenApiGeneratorV31(registry.definitions);
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
/** Gates webhooks, self-serve API keys, and BYOK AI provider keys.
|
||||
* Admin-granted only for now (users.isDeveloper, toggled in
|
||||
* admin/users/[id]) — kept as a single function so a future
|
||||
* subscription-based auto-grant (e.g. `|| tier !== "free"`) is a one-line
|
||||
* change here, not a redesign across every call site. */
|
||||
export function hasDeveloperAccess(user: { isDeveloper: boolean }): boolean {
|
||||
return user.isDeveloper;
|
||||
}
|
||||
@@ -420,6 +420,7 @@
|
||||
"nutrition": "Nutrition",
|
||||
"apiKeys": "API Keys",
|
||||
"webhooks": "Webhooks",
|
||||
"developerLockedNotice": "Developer access required. Ask an admin to enable it for your account.",
|
||||
"usage": {
|
||||
"title": "Usage & limits",
|
||||
"description": "AI calls reset monthly ({month}). Recipes and storage are lifetime totals.",
|
||||
|
||||
@@ -420,6 +420,7 @@
|
||||
"nutrition": "Nutrition",
|
||||
"apiKeys": "Clés API",
|
||||
"webhooks": "Webhooks",
|
||||
"developerLockedNotice": "Accès développeur requis. Demandez à un administrateur de l'activer pour votre compte.",
|
||||
"usage": {
|
||||
"title": "Utilisation et limites",
|
||||
"description": "Les appels IA se réinitialisent chaque mois ({month}). Les recettes et le stockage sont des totaux à vie.",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@epicure/web",
|
||||
"version": "0.70.0",
|
||||
"version": "0.71.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "next dev",
|
||||
|
||||
Reference in New Issue
Block a user