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:
Arnaud
2026-07-22 09:49:07 +02:00
parent f0632cce95
commit eb99faf655
35 changed files with 6268 additions and 109 deletions
+5
View File
@@ -2,6 +2,11 @@
All notable changes to Epicure are documented here. This file is mirrored in-app at `/changelog` (and in the admin dashboard) via `apps/web/lib/changelog.ts` — update both together. All notable changes to Epicure are documented here. This file is mirrored in-app at `/changelog` (and in the admin dashboard) via `apps/web/lib/changelog.ts` — update both together.
## 0.71.0 — 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.
## 0.70.0 — 2026-07-22 09:30 ## 0.70.0 — 2026-07-22 09:30
### Added ### Added
+4 -3
View File
@@ -105,10 +105,11 @@ Status legend: **Exists** (fully working) · **Partial** (works but with a real
| **Self-serve billing portal** | **Missing** | No Stripe customer portal; tier changes today only happen via direct admin edit at `/admin/users/[id]` | — | | **Self-serve billing portal** | **Missing** | No Stripe customer portal; tier changes today only happen via direct admin edit at `/admin/users/[id]` | — |
| Admin dashboard | Exists | 13 sections: overview, insights/analytics, users, invites, recipe moderation, reports, support, tiers, webhooks, audit logs, storage, AI config, site settings, changelog | `apps/web/app/admin/**` | | Admin dashboard | Exists | 13 sections: overview, insights/analytics, users, invites, recipe moderation, reports, support, tiers, webhooks, audit logs, storage, AI config, site settings, changelog | `apps/web/app/admin/**` |
| Feature flags (per-tier) vs feature prefs (per-user cosmetic) | Exists, two distinct systems | Flags gate 3 AI capabilities by tier; prefs let users hide 7 nav sections, no billing implication | `apps/web/lib/{feature-flags,feature-prefs}.ts` | | Feature flags (per-tier) vs feature prefs (per-user cosmetic) | Exists, two distinct systems | Flags gate 3 AI capabilities by tier; prefs let users hide 7 nav sections, no billing implication | `apps/web/lib/{feature-flags,feature-prefs}.ts` |
| User webhooks (personal automation) | Exists | 7 events, Zapier-style | `apps/web/lib/webhooks.ts` | | **Developer permission** (new, 2026-07-22) | Exists | A fourth, orthogonal access dimension — `users.isDeveloper`, admin-toggled in `admin/users/[id]`, gates user webhooks + self-serve API keys + BYOK. Previously all three had zero gating (any logged-in user, any tier). Existing users with a webhook/API key/BYOK key were grandfathered in by the migration. Deliberately a single `hasDeveloperAccess()` function so a future subscription-tier auto-grant is a one-line change, not a redesign. | `apps/web/lib/permissions.ts`, `apps/web/lib/api-auth.ts` (`requireDeveloper`) |
| Admin ops webhooks (site-wide) | Exists | 3 events (signup, ticket, report) | `apps/web/lib/admin-webhooks.ts` | | User webhooks (personal automation) | Exists | 7 events, Zapier-style, requires developer access | `apps/web/lib/webhooks.ts` |
| Admin ops webhooks (site-wide) | Exists | 3 events (signup, ticket, report) — admin-only, unrelated to developer access | `apps/web/lib/admin-webhooks.ts` |
| Support tickets ↔ Gitea two-way sync | Exists, verified real | Outbound (create/comment/close mirror to Gitea issue) + inbound (signed webhook receiver, dedup, loop-safe) | `apps/web/lib/gitea.ts`, `apps/web/app/api/webhooks/gitea/route.ts` | | Support tickets ↔ Gitea two-way sync | Exists, verified real | Outbound (create/comment/close mirror to Gitea issue) + inbound (signed webhook receiver, dedup, loop-safe) | `apps/web/lib/gitea.ts`, `apps/web/app/api/webhooks/gitea/route.ts` |
| Self-serve API keys | Exists | Up to 10 per user, scoped full/read, SHA-256 hashed at rest | `apps/web/app/api/v1/api-keys` | | Self-serve API keys | Exists | Up to 10 per user, scoped full/read, SHA-256 hashed at rest, requires developer access | `apps/web/app/api/v1/api-keys` |
| Public OpenAPI spec + docs page | Exists | Scalar-rendered at `/docs`, spec at `/api/v1/openapi.json` | `apps/web/lib/openapi.ts` | | Public OpenAPI spec + docs page | Exists | Scalar-rendered at `/docs`, spec at `/api/v1/openapi.json` | `apps/web/lib/openapi.ts` |
| i18n | Partial | Only `en` and `fr` — no other locales | `apps/web/messages/*.json` | | i18n | Partial | Only `en` and `fr` — no other locales | `apps/web/messages/*.json` |
| 2FA | Exists | TOTP + backup codes + OTP, passwordless-account-compatible | Better Auth `twoFactor` plugin | | 2FA | Exists | TOTP + backup codes + OTP, passwordless-account-compatible | Better Auth `twoFactor` plugin |
+7 -2
View File
@@ -6,6 +6,7 @@ import { UNLIMITED, getRecipeCount, getStorageUsedMb } from "@/lib/tiers";
import { ByokManager } from "@/components/settings/byok-manager"; import { ByokManager } from "@/components/settings/byok-manager";
import { ModelPrefsForm } from "@/components/settings/model-prefs-form"; import { ModelPrefsForm } from "@/components/settings/model-prefs-form";
import { UsageQuotaSection } from "@/components/settings/usage-quota-section"; import { UsageQuotaSection } from "@/components/settings/usage-quota-section";
import { DeveloperLockedNotice } from "@/components/settings/developer-locked-notice";
import { getMessages, formatMessage } from "@/lib/i18n/server"; import { getMessages, formatMessage } from "@/lib/i18n/server";
export const metadata: Metadata = {}; 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 // 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. // 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([ const [tierDef, usage, recipeCount, storageUsedMb] = await Promise.all([
@@ -80,7 +81,11 @@ export default async function AiSettingsPage() {
{m.settings.byok.description} {m.settings.byok.description}
</p> </p>
</div> </div>
<ByokManager initialKeys={aiKeys.map((k) => k.provider)} /> {dbUser?.isDeveloper ? (
<ByokManager initialKeys={aiKeys.map((k) => k.provider)} />
) : (
<DeveloperLockedNotice message={m.settings.developerLockedNotice} />
)}
</section> </section>
<section className="rounded-xl border p-6 space-y-4"> <section className="rounded-xl border p-6 space-y-4">
+28 -20
View File
@@ -3,8 +3,9 @@ import { headers } from "next/headers";
import Link from "next/link"; import Link from "next/link";
import { ExternalLink } from "lucide-react"; import { ExternalLink } from "lucide-react";
import { auth } from "@/lib/auth/server"; 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 { ApiKeysManager } from "@/components/settings/api-keys-manager";
import { DeveloperLockedNotice } from "@/components/settings/developer-locked-notice";
import { getMessages } from "@/lib/i18n/server"; import { getMessages } from "@/lib/i18n/server";
export const metadata: Metadata = {}; export const metadata: Metadata = {};
@@ -14,16 +15,20 @@ export default async function ApiKeysPage() {
if (!session) return null; if (!session) return null;
const m = getMessages((session.user as { locale?: string }).locale); const m = getMessages((session.user as { locale?: string }).locale);
const keys = await db const dbUser = (await db.select({ isDeveloper: users.isDeveloper }).from(users).where(eq(users.id, session.user.id)).limit(1))[0];
.select({
id: apiKeys.id, const keys = dbUser?.isDeveloper
name: apiKeys.name, ? await db
scope: apiKeys.scope, .select({
lastUsedAt: apiKeys.lastUsedAt, id: apiKeys.id,
createdAt: apiKeys.createdAt, name: apiKeys.name,
}) scope: apiKeys.scope,
.from(apiKeys) lastUsedAt: apiKeys.lastUsedAt,
.where(eq(apiKeys.userId, session.user.id)); createdAt: apiKeys.createdAt,
})
.from(apiKeys)
.where(eq(apiKeys.userId, session.user.id))
: [];
return ( return (
<div className="space-y-8"> <div className="space-y-8">
@@ -42,15 +47,18 @@ export default async function ApiKeysPage() {
{m.settings.apiKeysPage.docsLink} {m.settings.apiKeysPage.docsLink}
</Link> </Link>
</div> </div>
<ApiKeysManager {!dbUser?.isDeveloper && <DeveloperLockedNotice message={m.settings.developerLockedNotice} />}
initialKeys={keys.map((k) => ({ {dbUser?.isDeveloper && (
id: k.id, <ApiKeysManager
name: k.name, initialKeys={keys.map((k) => ({
scope: k.scope, id: k.id,
lastUsedAt: k.lastUsedAt ? k.lastUsedAt.toISOString() : null, name: k.name,
createdAt: k.createdAt.toISOString(), scope: k.scope,
}))} lastUsedAt: k.lastUsedAt ? k.lastUsedAt.toISOString() : null,
/> createdAt: k.createdAt.toISOString(),
}))}
/>
)}
</section> </section>
</div> </div>
); );
+6 -1
View File
@@ -1,5 +1,6 @@
import { headers } from "next/headers"; import { headers } from "next/headers";
import { auth } from "@/lib/auth/server"; import { auth } from "@/lib/auth/server";
import { db, users, eq } from "@epicure/db";
import { SettingsSidebar } from "@/components/settings/settings-sidebar"; import { SettingsSidebar } from "@/components/settings/settings-sidebar";
import { getMessages } from "@/lib/i18n/server"; 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 session = await auth.api.getSession({ headers: await headers() });
const m = getMessages((session?.user as { locale?: string })?.locale); 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 ( return (
<div className="max-w-5xl mx-auto"> <div className="max-w-5xl mx-auto">
<div className="mb-8"> <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> <p className="text-muted-foreground mt-1">{m.settings.subtitle}</p>
</div> </div>
<div className="flex flex-col md:flex-row gap-4 md:gap-8 md:items-start"> <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> <main className="flex-1 min-w-0 space-y-6">{children}</main>
</div> </div>
</div> </div>
+28 -20
View File
@@ -1,8 +1,9 @@
import type { Metadata } from "next"; import type { Metadata } from "next";
import { headers } from "next/headers"; import { headers } from "next/headers";
import { auth } from "@/lib/auth/server"; 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 { WebhooksManager } from "@/components/settings/webhooks-manager";
import { DeveloperLockedNotice } from "@/components/settings/developer-locked-notice";
import { getMessages } from "@/lib/i18n/server"; import { getMessages } from "@/lib/i18n/server";
export const metadata: Metadata = {}; export const metadata: Metadata = {};
@@ -12,16 +13,20 @@ export default async function WebhooksPage() {
if (!session) return null; if (!session) return null;
const m = getMessages((session.user as { locale?: string }).locale); const m = getMessages((session.user as { locale?: string }).locale);
const rows = await db const dbUser = (await db.select({ isDeveloper: users.isDeveloper }).from(users).where(eq(users.id, session.user.id)).limit(1))[0];
.select({
id: webhooks.id, const rows = dbUser?.isDeveloper
url: webhooks.url, ? await db
events: webhooks.events, .select({
active: webhooks.active, id: webhooks.id,
createdAt: webhooks.createdAt, url: webhooks.url,
}) events: webhooks.events,
.from(webhooks) active: webhooks.active,
.where(eq(webhooks.userId, session.user.id)); createdAt: webhooks.createdAt,
})
.from(webhooks)
.where(eq(webhooks.userId, session.user.id))
: [];
return ( return (
<div className="space-y-8"> <div className="space-y-8">
@@ -32,15 +37,18 @@ export default async function WebhooksPage() {
{m.settings.webhooksPage.description} {m.settings.webhooksPage.description}
</p> </p>
</div> </div>
<WebhooksManager {!dbUser?.isDeveloper && <DeveloperLockedNotice message={m.settings.developerLockedNotice} />}
initialWebhooks={rows.map((w) => ({ {dbUser?.isDeveloper && (
id: w.id, <WebhooksManager
url: w.url, initialWebhooks={rows.map((w) => ({
events: w.events, id: w.id,
active: w.active, url: w.url,
createdAt: w.createdAt.toISOString(), events: w.events,
}))} active: w.active,
/> createdAt: w.createdAt.toISOString(),
}))}
/>
)}
</section> </section>
</div> </div>
); );
+1 -1
View File
@@ -102,7 +102,7 @@ export default async function AdminUserDetailPage({ params }: PageProps) {
<CardTitle className="text-base">Edit Role &amp; Tier</CardTitle> <CardTitle className="text-base">Edit Role &amp; Tier</CardTitle>
</CardHeader> </CardHeader>
<CardContent> <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> </CardContent>
</Card> </Card>
@@ -12,8 +12,8 @@ export async function PATCH(req: NextRequest, { params }: RouteContext) {
if (response) return response; if (response) return response;
const { id } = await params; const { id } = await params;
const body = await req.json() as { role?: string; tier?: string }; const body = await req.json() as { role?: string; tier?: string; isDeveloper?: boolean };
const { role, tier } = body; const { role, tier, isDeveloper } = body;
const validRoles = ["user", "moderator", "admin"] as const; const validRoles = ["user", "moderator", "admin"] as const;
const validTiers = ["free", "pro", "family"] 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])) { if (tier !== undefined && !validTiers.includes(tier as typeof validTiers[number])) {
return NextResponse.json({ error: "Invalid tier" }, { status: 400 }); 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(), updatedAt: new Date(),
}; };
if (role) updateData.role = role as "user" | "moderator" | "admin"; if (role) updateData.role = role as "user" | "moderator" | "admin";
if (tier) updateData.tier = tier as "free" | "pro" | "family"; if (tier) updateData.tier = tier as "free" | "pro" | "family";
if (isDeveloper !== undefined) updateData.isDeveloper = isDeveloper;
const [updated] = await db const [updated] = await db
.update(users) .update(users)
.set(updateData) .set(updateData)
.where(eq(users.id, id)) .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) { if (!updated) {
return NextResponse.json({ error: "User not found" }, { status: 404 }); 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", action: "admin.user.update",
targetType: "user", targetType: "user",
targetId: id, targetId: id,
metadata: JSON.stringify({ role, tier }), metadata: JSON.stringify({ role, tier, isDeveloper }),
createdAt: new Date(), createdAt: new Date(),
}); });
@@ -1,11 +1,11 @@
import { NextResponse } from "next/server"; import { NextResponse } from "next/server";
import { db, userAiKeys, eq, and } from "@epicure/db"; 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 }> }; type Params = { params: Promise<{ provider: string }> };
export async function DELETE(_req: Request, { params }: Params) { export async function DELETE(_req: Request, { params }: Params) {
const { session, response } = await requireSession(); const { session, response } = await requireDeveloper();
if (response) return response; if (response) return response;
const { provider } = await params; const { provider } = await params;
+3 -3
View File
@@ -1,7 +1,7 @@
import { NextResponse } from "next/server"; import { NextResponse } from "next/server";
import { z } from "zod"; import { z } from "zod";
import { db, userAiKeys, eq, and } from "@epicure/db"; 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 { encrypt } from "@/lib/encrypt";
import { applyRateLimit } from "@/lib/rate-limit"; import { applyRateLimit } from "@/lib/rate-limit";
@@ -13,7 +13,7 @@ const PostSchema = z.object({
}); });
export async function GET() { export async function GET() {
const { session, response } = await requireSession(); const { session, response } = await requireDeveloper();
if (response) return response; if (response) return response;
const keys = await db.query.userAiKeys.findMany({ const keys = await db.query.userAiKeys.findMany({
@@ -25,7 +25,7 @@ export async function GET() {
} }
export async function POST(req: Request) { export async function POST(req: Request) {
const { session, response } = await requireSession(); const { session, response } = await requireDeveloper();
if (response) return response; if (response) return response;
const limited = await applyRateLimit(`rl:ai-keys:${session!.user.id}`, 5, 3600); const limited = await applyRateLimit(`rl:ai-keys:${session!.user.id}`, 5, 3600);
+2 -2
View File
@@ -1,12 +1,12 @@
import { NextRequest, NextResponse } from "next/server"; import { NextRequest, NextResponse } from "next/server";
import { db, apiKeys, eq, and } from "@epicure/db"; import { db, apiKeys, eq, and } from "@epicure/db";
import { requireSession } from "@/lib/api-auth"; import { requireDeveloper } from "@/lib/api-auth";
export async function DELETE( export async function DELETE(
_req: NextRequest, _req: NextRequest,
{ params }: { params: Promise<{ id: string }> } { params }: { params: Promise<{ id: string }> }
) { ) {
const { session, response } = await requireSession(); const { session, response } = await requireDeveloper();
if (response) return response; if (response) return response;
const { id } = await params; const { id } = await params;
+3 -3
View File
@@ -2,7 +2,7 @@ import { NextRequest, NextResponse } from "next/server";
import crypto from "node:crypto"; import crypto from "node:crypto";
import { z } from "zod"; import { z } from "zod";
import { db, apiKeys, eq, sql } from "@epicure/db"; import { db, apiKeys, eq, sql } from "@epicure/db";
import { requireSession } from "@/lib/api-auth"; import { requireDeveloper } from "@/lib/api-auth";
const CreateApiKeyBody = z.object({ const CreateApiKeyBody = z.object({
name: z.string().min(1).max(100), name: z.string().min(1).max(100),
@@ -10,7 +10,7 @@ const CreateApiKeyBody = z.object({
}); });
export async function GET() { export async function GET() {
const { session, response } = await requireSession(); const { session, response } = await requireDeveloper();
if (response) return response; if (response) return response;
const rows = await db const rows = await db
@@ -28,7 +28,7 @@ export async function GET() {
} }
export async function POST(req: NextRequest) { export async function POST(req: NextRequest) {
const { session, response } = await requireSession(); const { session, response } = await requireDeveloper();
if (response) return response; if (response) return response;
const body = await req.json() as unknown; const body = await req.json() as unknown;
@@ -4,7 +4,7 @@ import { NextRequest } from "next/server";
const mockSession = { user: { id: "user-1" } }; const mockSession = { user: { id: "user-1" } };
vi.mock("@/lib/api-auth", () => ({ vi.mock("@/lib/api-auth", () => ({
requireSession: vi.fn(), requireDeveloper: vi.fn(),
})); }));
vi.mock("@/lib/validate-webhook-url", () => ({ vi.mock("@/lib/validate-webhook-url", () => ({
@@ -33,7 +33,7 @@ vi.mock("@epicure/db", () => ({
and: vi.fn((...args) => ({ args, op: "and" })), 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"); const { validateWebhookUrl } = await import("@/lib/validate-webhook-url");
import { DELETE, PATCH } from "../route"; import { DELETE, PATCH } from "../route";
@@ -49,7 +49,7 @@ const ctx = { params: Promise.resolve({ id: "wh-1" }) };
beforeEach(() => { beforeEach(() => {
vi.clearAllMocks(); 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); vi.mocked(validateWebhookUrl).mockResolvedValue(null);
mockSelectChain.limit.mockResolvedValue([{ id: "wh-1" }]); mockSelectChain.limit.mockResolvedValue([{ id: "wh-1" }]);
}); });
@@ -4,7 +4,7 @@ import { NextRequest } from "next/server";
const mockSession = { user: { id: "user-1" } }; const mockSession = { user: { id: "user-1" } };
vi.mock("@/lib/api-auth", () => ({ vi.mock("@/lib/api-auth", () => ({
requireSession: vi.fn(), requireDeveloper: vi.fn(),
})); }));
const { mockFindFirst, mockSelectChain } = vi.hoisted(() => { const { mockFindFirst, mockSelectChain } = vi.hoisted(() => {
@@ -29,21 +29,21 @@ vi.mock("@epicure/db", () => ({
desc: vi.fn((a) => ({ a, op: "desc" })), 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"; import { GET } from "../route";
const ctx = { params: Promise.resolve({ id: "wh-1" }) }; const ctx = { params: Promise.resolve({ id: "wh-1" }) };
beforeEach(() => { beforeEach(() => {
vi.clearAllMocks(); 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" }); mockFindFirst.mockResolvedValue({ id: "wh-1" });
mockSelectChain.limit.mockResolvedValue([]); mockSelectChain.limit.mockResolvedValue([]);
}); });
describe("GET /api/v1/webhooks/[id]/deliveries", () => { describe("GET /api/v1/webhooks/[id]/deliveries", () => {
it("returns 401 when not authenticated", async () => { it("returns 401 when not authenticated", async () => {
vi.mocked(requireSession).mockResolvedValue({ vi.mocked(requireDeveloper).mockResolvedValue({
session: null, session: null,
response: new Response(JSON.stringify({ error: "Unauthorized" }), { status: 401 }), response: new Response(JSON.stringify({ error: "Unauthorized" }), { status: 401 }),
} as never); } as never);
@@ -1,11 +1,11 @@
import { NextRequest, NextResponse } from "next/server"; import { NextRequest, NextResponse } from "next/server";
import { db, webhooks, webhookDeliveries, eq, and, desc } from "@epicure/db"; 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 }> }; type Params = { params: Promise<{ id: string }> };
export async function GET(_req: NextRequest, { params }: Params) { export async function GET(_req: NextRequest, { params }: Params) {
const { session, response } = await requireSession(); const { session, response } = await requireDeveloper();
if (response) return response; if (response) return response;
const { id } = await params; const { id } = await params;
@@ -4,7 +4,7 @@ import { NextRequest } from "next/server";
const mockSession = { user: { id: "user-1" } }; const mockSession = { user: { id: "user-1" } };
vi.mock("@/lib/api-auth", () => ({ vi.mock("@/lib/api-auth", () => ({
requireSession: vi.fn(), requireDeveloper: vi.fn(),
})); }));
vi.mock("@/lib/webhooks", () => ({ vi.mock("@/lib/webhooks", () => ({
@@ -29,7 +29,7 @@ vi.mock("@epicure/db", () => ({
and: vi.fn((...args) => ({ args, op: "and" })), 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"); const { dispatchWebhook } = await import("@/lib/webhooks");
import { POST } from "../route"; import { POST } from "../route";
@@ -47,7 +47,7 @@ const ctx = { params: Promise.resolve({ id: "wh-1" }) };
beforeEach(() => { beforeEach(() => {
vi.clearAllMocks(); 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" }); mockWebhookFindFirst.mockResolvedValue({ id: "wh-1" });
mockDeliveryFindFirst.mockResolvedValue({ mockDeliveryFindFirst.mockResolvedValue({
id: VALID_DELIVERY_ID, id: VALID_DELIVERY_ID,
@@ -58,7 +58,7 @@ beforeEach(() => {
describe("POST /api/v1/webhooks/[id]/redeliver", () => { describe("POST /api/v1/webhooks/[id]/redeliver", () => {
it("returns 401 when not authenticated", async () => { it("returns 401 when not authenticated", async () => {
vi.mocked(requireSession).mockResolvedValue({ vi.mocked(requireDeveloper).mockResolvedValue({
session: null, session: null,
response: new Response(JSON.stringify({ error: "Unauthorized" }), { status: 401 }), response: new Response(JSON.stringify({ error: "Unauthorized" }), { status: 401 }),
} as never); } as never);
@@ -1,7 +1,7 @@
import { NextRequest, NextResponse } from "next/server"; import { NextRequest, NextResponse } from "next/server";
import { z } from "zod"; import { z } from "zod";
import { db, webhooks, webhookDeliveries, eq, and } from "@epicure/db"; 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"; import { dispatchWebhook, type WebhookEvent } from "@/lib/webhooks";
const Schema = z.object({ deliveryId: z.string().uuid() }); 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 }> }; type Params = { params: Promise<{ id: string }> };
export async function POST(req: NextRequest, { params }: Params) { export async function POST(req: NextRequest, { params }: Params) {
const { session, response } = await requireSession(); const { session, response } = await requireDeveloper();
if (response) return response; if (response) return response;
const { id } = await params; const { id } = await params;
+3 -3
View File
@@ -1,7 +1,7 @@
import { NextRequest, NextResponse } from "next/server"; import { NextRequest, NextResponse } from "next/server";
import { z } from "zod"; import { z } from "zod";
import { db, webhooks, eq, and } from "@epicure/db"; 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 { validateWebhookUrl } from "@/lib/validate-webhook-url";
import { WEBHOOK_EVENTS } from "@/lib/webhooks"; import { WEBHOOK_EVENTS } from "@/lib/webhooks";
@@ -15,7 +15,7 @@ export async function DELETE(
_req: NextRequest, _req: NextRequest,
{ params }: { params: Promise<{ id: string }> } { params }: { params: Promise<{ id: string }> }
) { ) {
const { session, response } = await requireSession(); const { session, response } = await requireDeveloper();
if (response) return response; if (response) return response;
const { id } = await params; const { id } = await params;
@@ -41,7 +41,7 @@ export async function PATCH(
req: NextRequest, req: NextRequest,
{ params }: { params: Promise<{ id: string }> } { params }: { params: Promise<{ id: string }> }
) { ) {
const { session, response } = await requireSession(); const { session, response } = await requireDeveloper();
if (response) return response; if (response) return response;
const { id } = await params; const { id } = await params;
@@ -4,7 +4,7 @@ import { NextRequest } from "next/server";
const mockSession = { user: { id: "user-1" } }; const mockSession = { user: { id: "user-1" } };
vi.mock("@/lib/api-auth", () => ({ vi.mock("@/lib/api-auth", () => ({
requireSession: vi.fn(), requireDeveloper: vi.fn(),
})); }));
vi.mock("@/lib/validate-webhook-url", () => ({ vi.mock("@/lib/validate-webhook-url", () => ({
@@ -28,7 +28,7 @@ vi.mock("@epicure/db", () => ({
eq: vi.fn((a, b) => ({ a, b, op: "eq" })), 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"); const { validateWebhookUrl } = await import("@/lib/validate-webhook-url");
import { GET, POST } from "../route"; import { GET, POST } from "../route";
@@ -42,14 +42,14 @@ function makeRequest(method: string, body?: unknown) {
beforeEach(() => { beforeEach(() => {
vi.clearAllMocks(); 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); vi.mocked(validateWebhookUrl).mockResolvedValue(null);
mockSelectChain.where.mockResolvedValue([]); mockSelectChain.where.mockResolvedValue([]);
}); });
describe("GET /api/v1/webhooks", () => { describe("GET /api/v1/webhooks", () => {
it("returns 401 when not authenticated", async () => { it("returns 401 when not authenticated", async () => {
vi.mocked(requireSession).mockResolvedValue({ vi.mocked(requireDeveloper).mockResolvedValue({
session: null, session: null,
response: new Response(JSON.stringify({ error: "Unauthorized" }), { status: 401 }), response: new Response(JSON.stringify({ error: "Unauthorized" }), { status: 401 }),
} as never); } as never);
@@ -82,7 +82,7 @@ describe("POST /api/v1/webhooks", () => {
}); });
it("returns 401 when not authenticated", async () => { it("returns 401 when not authenticated", async () => {
vi.mocked(requireSession).mockResolvedValue({ vi.mocked(requireDeveloper).mockResolvedValue({
session: null, session: null,
response: new Response(JSON.stringify({ error: "Unauthorized" }), { status: 401 }), response: new Response(JSON.stringify({ error: "Unauthorized" }), { status: 401 }),
} as never); } as never);
+3 -3
View File
@@ -2,7 +2,7 @@ import { NextRequest, NextResponse } from "next/server";
import crypto from "node:crypto"; import crypto from "node:crypto";
import { z } from "zod"; import { z } from "zod";
import { db, webhooks, eq } from "@epicure/db"; 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 { validateWebhookUrl } from "@/lib/validate-webhook-url";
import { WEBHOOK_EVENTS } from "@/lib/webhooks"; import { WEBHOOK_EVENTS } from "@/lib/webhooks";
import { encrypt } from "@/lib/encrypt"; import { encrypt } from "@/lib/encrypt";
@@ -19,7 +19,7 @@ const UpdateWebhookBody = z.object({
}); });
export async function GET() { export async function GET() {
const { session, response } = await requireSession(); const { session, response } = await requireDeveloper();
if (response) return response; if (response) return response;
const rows = await db const rows = await db
@@ -38,7 +38,7 @@ export async function GET() {
} }
export async function POST(req: NextRequest) { export async function POST(req: NextRequest) {
const { session, response } = await requireSession(); const { session, response } = await requireDeveloper();
if (response) return response; if (response) return response;
const body = await req.json() as unknown; const body = await req.json() as unknown;
+12 -2
View File
@@ -11,16 +11,19 @@ import {
SelectValue, SelectValue,
} from "@/components/ui/select"; } from "@/components/ui/select";
import { Label } from "@/components/ui/label"; import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
interface UserEditorProps { interface UserEditorProps {
userId: string; userId: string;
currentRole: "user" | "moderator" | "admin"; currentRole: "user" | "moderator" | "admin";
currentTier: "free" | "pro" | "family"; 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 [role, setRole] = useState<"user" | "moderator" | "admin">(currentRole);
const [tier, setTier] = useState<"free" | "pro" | "family">(currentTier); const [tier, setTier] = useState<"free" | "pro" | "family">(currentTier);
const [isDeveloper, setIsDeveloper] = useState(currentIsDeveloper);
const [saving, setSaving] = useState(false); const [saving, setSaving] = useState(false);
async function handleSave() { async function handleSave() {
@@ -29,7 +32,7 @@ export function UserEditor({ userId, currentRole, currentTier }: UserEditorProps
const res = await fetch(`/api/v1/admin/users/${userId}`, { const res = await fetch(`/api/v1/admin/users/${userId}`, {
method: "PATCH", method: "PATCH",
headers: { "Content-Type": "application/json" }, headers: { "Content-Type": "application/json" },
body: JSON.stringify({ role, tier }), body: JSON.stringify({ role, tier, isDeveloper }),
}); });
if (!res.ok) { if (!res.ok) {
const data = await res.json().catch(() => ({})); const data = await res.json().catch(() => ({}));
@@ -73,6 +76,13 @@ export function UserEditor({ userId, currentRole, currentTier }: UserEditorProps
</Select> </Select>
</div> </div>
</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> <div>
<Button onClick={handleSave} disabled={saving}> <Button onClick={handleSave} disabled={saving}>
{saving ? "Saving…" : "Save Changes"} {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 }, { href: "/settings/webhooks", key: "webhooks", icon: Webhook, exact: false },
] as const; ] as const;
export function SettingsSidebar() { const DEVELOPER_ONLY_KEYS = new Set(["apiKeys", "webhooks"]);
export function SettingsSidebar({ isDeveloper }: { isDeveloper: boolean }) {
const pathname = usePathname(); const pathname = usePathname();
const t = useTranslations("settings"); const t = useTranslations("settings");
const visibleItems = NAV_ITEMS.filter((item) => isDeveloper || !DEVELOPER_ONLY_KEYS.has(item.key));
return ( return (
<nav className="w-full md:w-48 md:shrink-0 md:sticky md:top-6"> <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"> <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); const active = exact ? pathname === href : pathname.startsWith(href);
return ( return (
<li key={href} className="shrink-0 md:shrink"> <li key={href} className="shrink-0 md:shrink">
+24
View File
@@ -4,6 +4,7 @@ import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/lib/auth/server"; import { auth } from "@/lib/auth/server";
import { db, apiKeys, users, eq } from "@epicure/db"; import { db, apiKeys, users, eq } from "@epicure/db";
import { applyRateLimit } from "@/lib/rate-limit"; import { applyRateLimit } from "@/lib/rate-limit";
import { hasDeveloperAccess } from "@/lib/permissions";
export async function requireSession() { export async function requireSession() {
const session = await auth.api.getSession({ headers: await headers() }); const session = await auth.api.getSession({ headers: await headers() });
@@ -39,6 +40,29 @@ export async function requireAdmin(opts?: { allowModerator?: boolean }) {
return { session, response: null }; 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 = { type SessionLike = {
user: { user: {
id: string; id: string;
+8 -1
View File
@@ -1,5 +1,5 @@
// Mirrors CHANGELOG.md at the repo root — update both together. // 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 = { export type ChangelogEntry = {
version: string; version: string;
@@ -11,6 +11,13 @@ export type ChangelogEntry = {
}; };
export const CHANGELOG: 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", version: "0.70.0",
date: "2026-07-22 09:30", date: "2026-07-22 09:30",
+15 -14
View File
@@ -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: "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: "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: "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: "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", 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: "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", 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: "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 --- // --- AI keys: users' own third-party provider keys (BYOK), used instead of app-wide AI credentials ---
const AiKeyRef = registry.register("AiKey", z.object({ const AiKeyRef = registry.register("AiKey", z.object({
provider: z.enum(["openai", "anthropic", "openrouter", "ollama"]), createdAt: z.string().datetime(), provider: z.enum(["openai", "anthropic", "openrouter", "ollama"]), createdAt: z.string().datetime(),
}).describe("Never includes the encrypted key value itself — only which providers are configured.")); }).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: "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.", 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: "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", 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: "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 --- // --- 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"]); 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(), 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: "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.", 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: "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.", 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: "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", security, request: { params: idParam }, responses: { 204: { description: "Deleted" }, 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)", 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: "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", 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: "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 AdminWebhookEventEnum = z.enum(["user.signed_up", "support_ticket.created", "report.filed"]);
const AdminWebhookRef = registry.register("AdminWebhook", z.object({ const AdminWebhookRef = registry.register("AdminWebhook", z.object({
@@ -879,9 +879,10 @@ export function generateOpenApiSpec(): object {
const AdminUpdateUserBodyRef = registry.register("AdminUpdateUserBody", z.object({ const AdminUpdateUserBodyRef = registry.register("AdminUpdateUserBody", z.object({
role: z.enum(["user", "moderator", "admin"]).optional(), tier: z.enum(["free", "pro", "family"]).optional(), 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({ 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({ 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: "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: "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 } } } } }); 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); const generator = new OpenApiGeneratorV31(registry.definitions);
+8
View File
@@ -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;
}
+1
View File
@@ -420,6 +420,7 @@
"nutrition": "Nutrition", "nutrition": "Nutrition",
"apiKeys": "API Keys", "apiKeys": "API Keys",
"webhooks": "Webhooks", "webhooks": "Webhooks",
"developerLockedNotice": "Developer access required. Ask an admin to enable it for your account.",
"usage": { "usage": {
"title": "Usage & limits", "title": "Usage & limits",
"description": "AI calls reset monthly ({month}). Recipes and storage are lifetime totals.", "description": "AI calls reset monthly ({month}). Recipes and storage are lifetime totals.",
+1
View File
@@ -420,6 +420,7 @@
"nutrition": "Nutrition", "nutrition": "Nutrition",
"apiKeys": "Clés API", "apiKeys": "Clés API",
"webhooks": "Webhooks", "webhooks": "Webhooks",
"developerLockedNotice": "Accès développeur requis. Demandez à un administrateur de l'activer pour votre compte.",
"usage": { "usage": {
"title": "Utilisation et limites", "title": "Utilisation et limites",
"description": "Les appels IA se réinitialisent chaque mois ({month}). Les recettes et le stockage sont des totaux à vie.", "description": "Les appels IA se réinitialisent chaque mois ({month}). Les recettes et le stockage sont des totaux à vie.",
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@epicure/web", "name": "@epicure/web",
"version": "0.70.0", "version": "0.71.0",
"private": true, "private": true,
"scripts": { "scripts": {
"dev": "next dev", "dev": "next dev",
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "epicure", "name": "epicure",
"version": "0.70.0", "version": "0.71.0",
"private": true, "private": true,
"scripts": { "scripts": {
"dev": "pnpm --filter web dev", "dev": "pnpm --filter web dev",
@@ -0,0 +1,13 @@
ALTER TABLE "users" ADD COLUMN "is_developer" boolean DEFAULT false NOT NULL;
--> statement-breakpoint
-- Grandfather in anyone who already has a webhook, API key, or BYOK AI
-- key configured -- this column ships as a new access gate on those three
-- features, and without this backfill every existing integration would
-- silently break the moment this migration runs.
UPDATE "users" SET "is_developer" = true WHERE "id" IN (
SELECT "user_id" FROM "webhooks"
UNION
SELECT "user_id" FROM "api_keys"
UNION
SELECT "user_id" FROM "user_ai_keys"
);
File diff suppressed because it is too large Load Diff
@@ -421,6 +421,13 @@
"when": 1784670176130, "when": 1784670176130,
"tag": "0059_pink_doctor_faustus", "tag": "0059_pink_doctor_faustus",
"breakpoints": true "breakpoints": true
},
{
"idx": 60,
"version": "7",
"when": 1784706150797,
"tag": "0060_wandering_mongoose",
"breakpoints": true
} }
] ]
} }
+5
View File
@@ -32,6 +32,11 @@ export const users = pgTable("users", {
username: text("username").unique(), username: text("username").unique(),
role: userRoleEnum("role").notNull().default("user"), role: userRoleEnum("role").notNull().default("user"),
tier: tierEnum("tier").notNull().default("free"), tier: tierEnum("tier").notNull().default("free"),
// Orthogonal to both role (staff hierarchy) and tier (billing plan) —
// gates webhooks, self-serve API keys, and BYOK AI provider keys.
// Admin-granted only for now; hasDeveloperAccess() in lib/permissions.ts
// is the single place a future tier-based auto-grant would be added.
isDeveloper: boolean("is_developer").notNull().default(false),
stripeCustomerId: text("stripe_customer_id").unique(), stripeCustomerId: text("stripe_customer_id").unique(),
unitPref: unitPrefEnum("unit_pref").notNull().default("metric"), unitPref: unitPrefEnum("unit_pref").notNull().default("metric"),
locale: text("locale").notNull().default("en"), locale: text("locale").notNull().default("en"),