feat: self-serve developer access for paid tiers, split BYOK into its own permission (v0.72.0)

Splits what was one isDeveloper flag (gating webhooks, API keys, AND
BYOK together) into two independent permissions:

- isDeveloper (webhooks + self-serve API keys): admin-toggled as
  before, but now ALSO self-serve -- PATCH /api/v1/users/me/developer-access
  lets any paid-tier (tier !== "free") user turn it on themselves, no
  added fee. Free tier still needs an admin grant. Turning it off is
  always self-serve regardless of tier, since revoking your own
  access needs no gatekeeping. canSelfServeDeveloperAccess() in
  lib/permissions.ts is the single check for "is this tier eligible."

- isByokEnabled (BYOK AI provider keys): new column, admin-only, no
  self-serve path at all -- routing real AI provider spend through
  Epicure on the user's own key warrants a manual admin check-in that
  webhooks/API access don't need. requireByok() replaces
  requireDeveloper() on the three ai-keys routes.

Migration adds is_byok_enabled and grandfathers in anyone who already
has a BYOK key configured (the earlier grandfather migration only
covered the combined isDeveloper flag, which BYOK no longer reads).

Settings UI: webhooks/API-keys pages show a self-serve "Enable"
toggle for paid-tier non-developers instead of the locked notice
(still shown to free-tier users), plus a "Disable developer access"
link once enabled. Settings -> AI's BYOK section now checks
isByokEnabled instead of isDeveloper -- unaffected by the self-serve
change, still fully admin-gated.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
Arnaud
2026-07-23 09:31:04 +02:00
parent eb99faf655
commit 8d5787e56e
27 changed files with 6338 additions and 68 deletions
+27 -6
View File
@@ -4,7 +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";
import { hasDeveloperAccess, hasByokAccess } from "@/lib/permissions";
export async function requireSession() {
const session = await auth.api.getSession({ headers: await headers() });
@@ -40,10 +40,10 @@ 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). */
/** Gates webhooks and self-serve API keys 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 a grant). */
export async function requireDeveloper() {
const { session, response } = await requireSession();
if (response) return { session: null, response };
@@ -57,7 +57,28 @@ export async function requireDeveloper() {
if (!dbUser || !hasDeveloperAccess(dbUser)) {
return {
session: null,
response: NextResponse.json({ error: "Developer access required — ask an admin to enable it" }, { status: 403 }),
response: NextResponse.json({ error: "Developer access required — ask an admin to enable it, or self-enable it in Settings if you're on a paid plan" }, { status: 403 }),
};
}
return { session, response: null };
}
/** Gates BYOK AI provider key routes behind users.isByokEnabled — admin-only,
* no self-serve path (see lib/permissions.ts's hasByokAccess doc comment). */
export async function requireByok() {
const { session, response } = await requireSession();
if (response) return { session: null, response };
const [dbUser] = await db
.select({ isByokEnabled: users.isByokEnabled })
.from(users)
.where(eq(users.id, session!.user.id))
.limit(1);
if (!dbUser || !hasByokAccess(dbUser)) {
return {
session: null,
response: NextResponse.json({ error: "BYOK access required — ask an admin to enable it" }, { status: 403 }),
};
}
return { session, response: null };
+8 -1
View File
@@ -1,5 +1,5 @@
// Mirrors CHANGELOG.md at the repo root — update both together.
export const APP_VERSION = "0.71.0";
export const APP_VERSION = "0.72.0";
export type ChangelogEntry = {
version: string;
@@ -11,6 +11,13 @@ export type ChangelogEntry = {
};
export const CHANGELOG: ChangelogEntry[] = [
{
version: "0.72.0",
date: "2026-07-23 09:30",
added: [
"Developer access (webhooks + API keys) is now self-serve for any paid-tier user, free of charge — enable it yourself in Settings instead of waiting on an admin. Free tier still needs an admin grant. BYOK is now a fully separate permission, admin-only, unaffected by the self-serve change.",
],
},
{
version: "0.71.0",
date: "2026-07-22 10:00",
+7 -5
View File
@@ -534,6 +534,7 @@ export function generateOpenApiSpec(): object {
registry.registerPath({ method: "put", path: "/api/v1/users/me/notification-prefs", summary: "Set your notification category preferences", security, request: { body: { content: { "application/json": { schema: UpdateNotificationPrefsRef } }, required: true } }, responses: { 200: { description: "Saved", content: { "application/json": { schema: z.object({ ok: z.boolean() }) } } }, 400: { description: "Invalid request", content: { "application/json": { schema: ApiErrorRef } } }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } } } });
registry.registerPath({ method: "get", path: "/api/v1/users/me/feature-prefs", summary: "Get your feature visibility preferences", description: "Features with no saved row default to visible.", security, responses: { 200: { description: "Preferences", content: { "application/json": { schema: z.object({ data: FeaturePrefsRef }) } } }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } } } });
registry.registerPath({ method: "put", path: "/api/v1/users/me/feature-prefs", summary: "Set your feature visibility preferences", description: "Purely cosmetic (hides nav items) — does not restrict access to the underlying pages.", security, request: { body: { content: { "application/json": { schema: UpdateFeaturePrefsRef } }, required: true } }, responses: { 200: { description: "Saved", content: { "application/json": { schema: z.object({ ok: z.boolean() }) } } }, 400: { description: "Invalid request", content: { "application/json": { schema: ApiErrorRef } } }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } } } });
registry.registerPath({ method: "patch", path: "/api/v1/users/me/developer-access", summary: "Self-serve enable or disable developer access", description: "Enabling requires a paid tier (free at no extra charge) — free-tier users need an admin grant instead. Disabling is always allowed, regardless of tier or who originally granted it. Only covers webhooks/API keys — BYOK is a separate, admin-only permission.", security, request: { body: { content: { "application/json": { schema: z.object({ enabled: z.boolean() }) } }, required: true } }, responses: { 200: { description: "Updated", content: { "application/json": { schema: z.object({ ok: z.boolean(), isDeveloper: z.boolean() }) } } }, 400: { description: "Validation error", content: { "application/json": { schema: ApiErrorRef } } }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } }, 403: { description: "Free tier — upgrade or ask an admin", content: { "application/json": { schema: ApiErrorRef } } } } });
registry.registerPath({ method: "get", path: "/api/v1/users/me/nutrition-diary", summary: "Get a day's cooked-recipe nutrition totals vs. your goals, or a multi-day trend", description: "Pass `range` (7, 30, or 90) instead of `date` for a daily calorie/macro trend over that many days — days with nothing cooked appear with zero totals.", security, request: { query: z.object({ date: z.string().optional().describe("ISO date YYYY-MM-DD, defaults to today (UTC). Ignored if range is set."), range: z.enum(["7", "30", "90"]).optional().describe("Switches to trend mode: returns { range, days: [{date, calories, proteinG, carbsG, fatG}], goalCalories } instead of the single-day shape.") }) }, responses: { 200: { description: "Diary or trend", content: { "application/json": { schema: z.union([NutritionDiaryRef, NutritionTrendRef]) } } }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } } } });
registry.registerPath({ method: "get", path: "/api/v1/users/me/nutrition-goals", summary: "Get your daily nutrition goals", security, responses: { 200: { description: "Goals", content: { "application/json": { schema: z.object({ data: NutritionGoalsRef2 }) } } }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } } } });
registry.registerPath({ method: "put", path: "/api/v1/users/me/nutrition-goals", summary: "Set your daily nutrition goals", security, request: { body: { content: { "application/json": { schema: UpdateNutritionGoalsRef } }, required: true } }, responses: { 200: { description: "Saved", content: { "application/json": { schema: z.object({ ok: z.boolean() }) } } }, 400: { description: "Invalid request", content: { "application/json": { schema: ApiErrorRef } } }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } } } });
@@ -593,9 +594,9 @@ export function generateOpenApiSpec(): 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. 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 } } } } });
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 BYOK access (an admin must enable it for your account) — separate from developer access, which only covers webhooks/API keys.", 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: "BYOK 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 BYOK 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: "BYOK 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 BYOK 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: "BYOK 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"]);
@@ -879,10 +880,11 @@ 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."),
isDeveloper: z.boolean().optional().describe("Gates webhooks and self-serve API keys. Paid-tier users can also self-enable this (PATCH /api/v1/users/me/developer-access)."),
isByokEnabled: z.boolean().optional().describe("Gates BYOK AI provider keys. Admin-only, no self-serve path."),
}));
const AdminUpdatedUserRef = registry.register("AdminUpdatedUser", z.object({
user: z.object({ id: z.string(), role: z.string(), tier: z.string(), isDeveloper: z.boolean() }),
user: z.object({ id: z.string(), role: z.string(), tier: z.string(), isDeveloper: z.boolean(), isByokEnabled: z.boolean() }),
}));
const AdminUserUsageRef = registry.register("AdminUserUsage", z.object({
+19 -5
View File
@@ -1,8 +1,22 @@
/** 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. */
/** Gates webhooks and self-serve API keys. Admin-settable always
* (users.isDeveloper, toggled in admin/users/[id]); also self-serve
* toggleable by the user themselves once on a paid tier, no added fee —
* see PATCH /api/v1/users/me/developer-access. Both paths write the same
* column, so this check doesn't need to know which one granted it. */
export function hasDeveloperAccess(user: { isDeveloper: boolean }): boolean {
return user.isDeveloper;
}
/** Gates BYOK AI provider keys — deliberately separate from
* hasDeveloperAccess: routing real AI provider spend through Epicure on
* the user's own key warrants a manual admin check-in, not blanket
* self-serve like webhooks/API keys get. Admin-only, no self-serve path. */
export function hasByokAccess(user: { isByokEnabled: boolean }): boolean {
return user.isByokEnabled;
}
/** Self-serve developer-access opt-in (webhooks + API keys) is only open
* to paid tiers — free-tier users still need an admin grant. */
export function canSelfServeDeveloperAccess(user: { tier: string }): boolean {
return user.tier !== "free";
}