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:
@@ -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.72.0 — 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.
|
||||||
|
|
||||||
## 0.71.0 — 2026-07-22 10:00
|
## 0.71.0 — 2026-07-22 10:00
|
||||||
|
|
||||||
### Added
|
### Added
|
||||||
|
|||||||
+1
-1
@@ -105,7 +105,7 @@ 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` |
|
||||||
| **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`) |
|
| **Developer permission** (2026-07-22, split 2026-07-23) | Exists | Two separate, orthogonal permissions — not one. `users.isDeveloper` gates webhooks + self-serve API keys: admin-toggled always, *and* self-serve toggleable by the user themselves once on a paid tier (no added fee) via `PATCH /api/v1/users/me/developer-access`; free-tier users still need an admin grant. `users.isByokEnabled` gates BYOK separately, admin-only, no self-serve — routing real AI spend through Epicure on the user's own key warrants a manual check-in. Previously all three (webhooks/API keys/BYOK) shared one flag with zero self-serve path. Existing users with a webhook/API key were already grandfathered for `isDeveloper`; a second migration grandfathered existing BYOK users into `isByokEnabled` specifically. | `apps/web/lib/permissions.ts` (`hasDeveloperAccess`, `hasByokAccess`, `canSelfServeDeveloperAccess`), `apps/web/lib/api-auth.ts` (`requireDeveloper`, `requireByok`) |
|
||||||
| User webhooks (personal automation) | Exists | 7 events, Zapier-style, requires developer access | `apps/web/lib/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` |
|
| 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` |
|
||||||
|
|||||||
@@ -28,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, isDeveloper: true } }),
|
db.query.users.findFirst({ where: eq(users.id, session.user.id), columns: { tier: true, isByokEnabled: true } }),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
const [tierDef, usage, recipeCount, storageUsedMb] = await Promise.all([
|
const [tierDef, usage, recipeCount, storageUsedMb] = await Promise.all([
|
||||||
@@ -81,10 +81,10 @@ export default async function AiSettingsPage() {
|
|||||||
{m.settings.byok.description}
|
{m.settings.byok.description}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
{dbUser?.isDeveloper ? (
|
{dbUser?.isByokEnabled ? (
|
||||||
<ByokManager initialKeys={aiKeys.map((k) => k.provider)} />
|
<ByokManager initialKeys={aiKeys.map((k) => k.provider)} />
|
||||||
) : (
|
) : (
|
||||||
<DeveloperLockedNotice message={m.settings.developerLockedNotice} />
|
<DeveloperLockedNotice message={m.settings.byokLockedNotice} />
|
||||||
)}
|
)}
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
|
|||||||
@@ -6,6 +6,9 @@ import { auth } from "@/lib/auth/server";
|
|||||||
import { db, apiKeys, users, 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 { DeveloperLockedNotice } from "@/components/settings/developer-locked-notice";
|
||||||
|
import { DeveloperAccessToggle } from "@/components/settings/developer-access-toggle";
|
||||||
|
import { DisableDeveloperAccessButton } from "@/components/settings/disable-developer-access-button";
|
||||||
|
import { canSelfServeDeveloperAccess } from "@/lib/permissions";
|
||||||
import { getMessages } from "@/lib/i18n/server";
|
import { getMessages } from "@/lib/i18n/server";
|
||||||
|
|
||||||
export const metadata: Metadata = {};
|
export const metadata: Metadata = {};
|
||||||
@@ -15,7 +18,7 @@ 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 dbUser = (await db.select({ isDeveloper: users.isDeveloper }).from(users).where(eq(users.id, session.user.id)).limit(1))[0];
|
const dbUser = (await db.select({ isDeveloper: users.isDeveloper, tier: users.tier }).from(users).where(eq(users.id, session.user.id)).limit(1))[0];
|
||||||
|
|
||||||
const keys = dbUser?.isDeveloper
|
const keys = dbUser?.isDeveloper
|
||||||
? await db
|
? await db
|
||||||
@@ -47,17 +50,25 @@ export default async function ApiKeysPage() {
|
|||||||
{m.settings.apiKeysPage.docsLink}
|
{m.settings.apiKeysPage.docsLink}
|
||||||
</Link>
|
</Link>
|
||||||
</div>
|
</div>
|
||||||
{!dbUser?.isDeveloper && <DeveloperLockedNotice message={m.settings.developerLockedNotice} />}
|
{!dbUser?.isDeveloper && dbUser && canSelfServeDeveloperAccess(dbUser) && (
|
||||||
|
<DeveloperAccessToggle message={m.settings.developerSelfServeNotice} />
|
||||||
|
)}
|
||||||
|
{!dbUser?.isDeveloper && (!dbUser || !canSelfServeDeveloperAccess(dbUser)) && (
|
||||||
|
<DeveloperLockedNotice message={m.settings.developerLockedNotice} />
|
||||||
|
)}
|
||||||
{dbUser?.isDeveloper && (
|
{dbUser?.isDeveloper && (
|
||||||
<ApiKeysManager
|
<>
|
||||||
initialKeys={keys.map((k) => ({
|
<ApiKeysManager
|
||||||
id: k.id,
|
initialKeys={keys.map((k) => ({
|
||||||
name: k.name,
|
id: k.id,
|
||||||
scope: k.scope,
|
name: k.name,
|
||||||
lastUsedAt: k.lastUsedAt ? k.lastUsedAt.toISOString() : null,
|
scope: k.scope,
|
||||||
createdAt: k.createdAt.toISOString(),
|
lastUsedAt: k.lastUsedAt ? k.lastUsedAt.toISOString() : null,
|
||||||
}))}
|
createdAt: k.createdAt.toISOString(),
|
||||||
/>
|
}))}
|
||||||
|
/>
|
||||||
|
<DisableDeveloperAccessButton />
|
||||||
|
</>
|
||||||
)}
|
)}
|
||||||
</section>
|
</section>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -3,14 +3,16 @@ import { auth } from "@/lib/auth/server";
|
|||||||
import { db, users, eq } from "@epicure/db";
|
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";
|
||||||
|
import { canSelfServeDeveloperAccess } from "@/lib/permissions";
|
||||||
|
|
||||||
export default async function SettingsLayout({ children }: { children: React.ReactNode }) {
|
export default async function SettingsLayout({ children }: { children: React.ReactNode }) {
|
||||||
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
|
const dbUser = session
|
||||||
? (await db.select({ isDeveloper: users.isDeveloper }).from(users).where(eq(users.id, session.user.id)).limit(1))[0]
|
? (await db.select({ isDeveloper: users.isDeveloper, tier: users.tier }).from(users).where(eq(users.id, session.user.id)).limit(1))[0]
|
||||||
: undefined;
|
: undefined;
|
||||||
|
const showDeveloperNav = !!dbUser && (dbUser.isDeveloper || canSelfServeDeveloperAccess(dbUser));
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="max-w-5xl mx-auto">
|
<div className="max-w-5xl mx-auto">
|
||||||
@@ -19,7 +21,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 isDeveloper={dbUser?.isDeveloper ?? false} />
|
<SettingsSidebar showDeveloperNav={showDeveloperNav} />
|
||||||
<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>
|
||||||
|
|||||||
@@ -4,6 +4,9 @@ import { auth } from "@/lib/auth/server";
|
|||||||
import { db, webhooks, users, 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 { DeveloperLockedNotice } from "@/components/settings/developer-locked-notice";
|
||||||
|
import { DeveloperAccessToggle } from "@/components/settings/developer-access-toggle";
|
||||||
|
import { DisableDeveloperAccessButton } from "@/components/settings/disable-developer-access-button";
|
||||||
|
import { canSelfServeDeveloperAccess } from "@/lib/permissions";
|
||||||
import { getMessages } from "@/lib/i18n/server";
|
import { getMessages } from "@/lib/i18n/server";
|
||||||
|
|
||||||
export const metadata: Metadata = {};
|
export const metadata: Metadata = {};
|
||||||
@@ -13,7 +16,7 @@ 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 dbUser = (await db.select({ isDeveloper: users.isDeveloper }).from(users).where(eq(users.id, session.user.id)).limit(1))[0];
|
const dbUser = (await db.select({ isDeveloper: users.isDeveloper, tier: users.tier }).from(users).where(eq(users.id, session.user.id)).limit(1))[0];
|
||||||
|
|
||||||
const rows = dbUser?.isDeveloper
|
const rows = dbUser?.isDeveloper
|
||||||
? await db
|
? await db
|
||||||
@@ -37,17 +40,25 @@ export default async function WebhooksPage() {
|
|||||||
{m.settings.webhooksPage.description}
|
{m.settings.webhooksPage.description}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
{!dbUser?.isDeveloper && <DeveloperLockedNotice message={m.settings.developerLockedNotice} />}
|
{!dbUser?.isDeveloper && dbUser && canSelfServeDeveloperAccess(dbUser) && (
|
||||||
|
<DeveloperAccessToggle message={m.settings.developerSelfServeNotice} />
|
||||||
|
)}
|
||||||
|
{!dbUser?.isDeveloper && (!dbUser || !canSelfServeDeveloperAccess(dbUser)) && (
|
||||||
|
<DeveloperLockedNotice message={m.settings.developerLockedNotice} />
|
||||||
|
)}
|
||||||
{dbUser?.isDeveloper && (
|
{dbUser?.isDeveloper && (
|
||||||
<WebhooksManager
|
<>
|
||||||
initialWebhooks={rows.map((w) => ({
|
<WebhooksManager
|
||||||
id: w.id,
|
initialWebhooks={rows.map((w) => ({
|
||||||
url: w.url,
|
id: w.id,
|
||||||
events: w.events,
|
url: w.url,
|
||||||
active: w.active,
|
events: w.events,
|
||||||
createdAt: w.createdAt.toISOString(),
|
active: w.active,
|
||||||
}))}
|
createdAt: w.createdAt.toISOString(),
|
||||||
/>
|
}))}
|
||||||
|
/>
|
||||||
|
<DisableDeveloperAccessButton />
|
||||||
|
</>
|
||||||
)}
|
)}
|
||||||
</section>
|
</section>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -102,7 +102,7 @@ export default async function AdminUserDetailPage({ params }: PageProps) {
|
|||||||
<CardTitle className="text-base">Edit Role & Tier</CardTitle>
|
<CardTitle className="text-base">Edit Role & Tier</CardTitle>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent>
|
<CardContent>
|
||||||
<UserEditor userId={user.id} currentRole={user.role} currentTier={user.tier} currentIsDeveloper={user.isDeveloper} />
|
<UserEditor userId={user.id} currentRole={user.role} currentTier={user.tier} currentIsDeveloper={user.isDeveloper} currentIsByokEnabled={user.isByokEnabled} />
|
||||||
</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; isDeveloper?: boolean };
|
const body = await req.json() as { role?: string; tier?: string; isDeveloper?: boolean; isByokEnabled?: boolean };
|
||||||
const { role, tier, isDeveloper } = body;
|
const { role, tier, isDeveloper, isByokEnabled } = 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;
|
||||||
@@ -27,19 +27,23 @@ export async function PATCH(req: NextRequest, { params }: RouteContext) {
|
|||||||
if (isDeveloper !== undefined && typeof isDeveloper !== "boolean") {
|
if (isDeveloper !== undefined && typeof isDeveloper !== "boolean") {
|
||||||
return NextResponse.json({ error: "Invalid isDeveloper" }, { status: 400 });
|
return NextResponse.json({ error: "Invalid isDeveloper" }, { status: 400 });
|
||||||
}
|
}
|
||||||
|
if (isByokEnabled !== undefined && typeof isByokEnabled !== "boolean") {
|
||||||
|
return NextResponse.json({ error: "Invalid isByokEnabled" }, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
const updateData: Partial<{ role: "user" | "moderator" | "admin"; tier: "free" | "pro" | "family"; isDeveloper: boolean; updatedAt: Date }> = {
|
const updateData: Partial<{ role: "user" | "moderator" | "admin"; tier: "free" | "pro" | "family"; isDeveloper: boolean; isByokEnabled: 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;
|
if (isDeveloper !== undefined) updateData.isDeveloper = isDeveloper;
|
||||||
|
if (isByokEnabled !== undefined) updateData.isByokEnabled = isByokEnabled;
|
||||||
|
|
||||||
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, isDeveloper: users.isDeveloper });
|
.returning({ id: users.id, role: users.role, tier: users.tier, isDeveloper: users.isDeveloper, isByokEnabled: users.isByokEnabled });
|
||||||
|
|
||||||
if (!updated) {
|
if (!updated) {
|
||||||
return NextResponse.json({ error: "User not found" }, { status: 404 });
|
return NextResponse.json({ error: "User not found" }, { status: 404 });
|
||||||
@@ -52,7 +56,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, isDeveloper }),
|
metadata: JSON.stringify({ role, tier, isDeveloper, isByokEnabled }),
|
||||||
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 { requireDeveloper } from "@/lib/api-auth";
|
import { requireByok } 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 requireDeveloper();
|
const { session, response } = await requireByok();
|
||||||
if (response) return response;
|
if (response) return response;
|
||||||
|
|
||||||
const { provider } = await params;
|
const { provider } = await params;
|
||||||
|
|||||||
@@ -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 { requireDeveloper } from "@/lib/api-auth";
|
import { requireByok } 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 requireDeveloper();
|
const { session, response } = await requireByok();
|
||||||
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 requireDeveloper();
|
const { session, response } = await requireByok();
|
||||||
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);
|
||||||
|
|||||||
@@ -0,0 +1,35 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
import { z } from "zod";
|
||||||
|
import { db, users, eq } from "@epicure/db";
|
||||||
|
import { requireSession } from "@/lib/api-auth";
|
||||||
|
import { canSelfServeDeveloperAccess } from "@/lib/permissions";
|
||||||
|
|
||||||
|
const PatchSchema = z.object({ enabled: z.boolean() });
|
||||||
|
|
||||||
|
/** Self-serve on/off for the same isDeveloper flag admin/users/[id] can
|
||||||
|
* also set — open to any paid tier, no added fee. Free tier still needs
|
||||||
|
* an admin grant (requireAdmin's path, unchanged). */
|
||||||
|
export async function PATCH(req: NextRequest) {
|
||||||
|
const { session, response } = await requireSession();
|
||||||
|
if (response) return response;
|
||||||
|
|
||||||
|
const parsed = PatchSchema.safeParse(await req.json());
|
||||||
|
if (!parsed.success) {
|
||||||
|
return NextResponse.json({ error: "Validation error", issues: parsed.error.issues }, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Turning it off is always allowed, regardless of tier or who granted
|
||||||
|
// it — only turning it ON self-serve requires a paid tier.
|
||||||
|
if (parsed.data.enabled) {
|
||||||
|
// Don't trust session.user.tier — up to 5-minute-stale cookieCache,
|
||||||
|
// same reasoning as every other fresh-role/tier re-query in this codebase.
|
||||||
|
const [dbUser] = await db.select({ tier: users.tier }).from(users).where(eq(users.id, session!.user.id)).limit(1);
|
||||||
|
if (!dbUser || !canSelfServeDeveloperAccess(dbUser)) {
|
||||||
|
return NextResponse.json({ error: "Upgrade to a paid plan to enable developer access yourself, or ask an admin" }, { status: 403 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
await db.update(users).set({ isDeveloper: parsed.data.enabled, updatedAt: new Date() }).where(eq(users.id, session!.user.id));
|
||||||
|
|
||||||
|
return NextResponse.json({ ok: true, isDeveloper: parsed.data.enabled });
|
||||||
|
}
|
||||||
@@ -18,12 +18,14 @@ interface UserEditorProps {
|
|||||||
currentRole: "user" | "moderator" | "admin";
|
currentRole: "user" | "moderator" | "admin";
|
||||||
currentTier: "free" | "pro" | "family";
|
currentTier: "free" | "pro" | "family";
|
||||||
currentIsDeveloper: boolean;
|
currentIsDeveloper: boolean;
|
||||||
|
currentIsByokEnabled: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function UserEditor({ userId, currentRole, currentTier, currentIsDeveloper }: UserEditorProps) {
|
export function UserEditor({ userId, currentRole, currentTier, currentIsDeveloper, currentIsByokEnabled }: 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 [isDeveloper, setIsDeveloper] = useState(currentIsDeveloper);
|
||||||
|
const [isByokEnabled, setIsByokEnabled] = useState(currentIsByokEnabled);
|
||||||
const [saving, setSaving] = useState(false);
|
const [saving, setSaving] = useState(false);
|
||||||
|
|
||||||
async function handleSave() {
|
async function handleSave() {
|
||||||
@@ -32,7 +34,7 @@ export function UserEditor({ userId, currentRole, currentTier, currentIsDevelope
|
|||||||
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, isDeveloper }),
|
body: JSON.stringify({ role, tier, isDeveloper, isByokEnabled }),
|
||||||
});
|
});
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
const data = await res.json().catch(() => ({}));
|
const data = await res.json().catch(() => ({}));
|
||||||
@@ -79,10 +81,17 @@ export function UserEditor({ userId, currentRole, currentTier, currentIsDevelope
|
|||||||
<div className="flex items-center justify-between gap-3 rounded-lg border p-3 max-w-md">
|
<div className="flex items-center justify-between gap-3 rounded-lg border p-3 max-w-md">
|
||||||
<div>
|
<div>
|
||||||
<Label htmlFor="developer-switch">Developer access</Label>
|
<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>
|
<p className="text-xs text-muted-foreground">Enables webhooks and self-serve API keys. Users on a paid tier can also self-enable this.</p>
|
||||||
</div>
|
</div>
|
||||||
<Switch id="developer-switch" checked={isDeveloper} onCheckedChange={setIsDeveloper} />
|
<Switch id="developer-switch" checked={isDeveloper} onCheckedChange={setIsDeveloper} />
|
||||||
</div>
|
</div>
|
||||||
|
<div className="flex items-center justify-between gap-3 rounded-lg border p-3 max-w-md">
|
||||||
|
<div>
|
||||||
|
<Label htmlFor="byok-switch">BYOK access</Label>
|
||||||
|
<p className="text-xs text-muted-foreground">Enables bring-your-own AI provider keys. Admin-only, no self-serve.</p>
|
||||||
|
</div>
|
||||||
|
<Switch id="byok-switch" checked={isByokEnabled} onCheckedChange={setIsByokEnabled} />
|
||||||
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<Button onClick={handleSave} disabled={saving}>
|
<Button onClick={handleSave} disabled={saving}>
|
||||||
{saving ? "Saving…" : "Save Changes"}
|
{saving ? "Saving…" : "Save Changes"}
|
||||||
|
|||||||
@@ -0,0 +1,44 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState } from "react";
|
||||||
|
import { useRouter } from "next/navigation";
|
||||||
|
import { toast } from "sonner";
|
||||||
|
import { Code2 } from "lucide-react";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
|
||||||
|
/** Shown instead of the locked notice on the webhooks/API-keys settings
|
||||||
|
* pages when the user is on a paid tier — self-serve, no admin needed, no
|
||||||
|
* added fee. Reloads the page on success since the manager component
|
||||||
|
* needs its initial data fetched server-side. */
|
||||||
|
export function DeveloperAccessToggle({ message }: { message: string }) {
|
||||||
|
const router = useRouter();
|
||||||
|
const [enabling, setEnabling] = useState(false);
|
||||||
|
|
||||||
|
async function enable() {
|
||||||
|
setEnabling(true);
|
||||||
|
try {
|
||||||
|
const res = await fetch("/api/v1/users/me/developer-access", {
|
||||||
|
method: "PATCH",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ enabled: true }),
|
||||||
|
});
|
||||||
|
if (!res.ok) throw new Error();
|
||||||
|
router.refresh();
|
||||||
|
} catch {
|
||||||
|
toast.error("Couldn't enable developer access");
|
||||||
|
setEnabling(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex items-center justify-between gap-3 rounded-lg border bg-muted/30 p-4">
|
||||||
|
<div className="flex items-start gap-3 text-sm text-muted-foreground">
|
||||||
|
<Code2 className="h-4 w-4 shrink-0 mt-0.5" />
|
||||||
|
<p>{message}</p>
|
||||||
|
</div>
|
||||||
|
<Button type="button" size="sm" disabled={enabling} onClick={() => { void enable(); }}>
|
||||||
|
{enabling ? "Enabling…" : "Enable"}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState } from "react";
|
||||||
|
import { useRouter } from "next/navigation";
|
||||||
|
import { toast } from "sonner";
|
||||||
|
|
||||||
|
/** Turning developer access off is always self-serve regardless of tier
|
||||||
|
* or who granted it — only turning it back on (for a free-tier user)
|
||||||
|
* requires an admin. */
|
||||||
|
export function DisableDeveloperAccessButton() {
|
||||||
|
const router = useRouter();
|
||||||
|
const [disabling, setDisabling] = useState(false);
|
||||||
|
|
||||||
|
async function disable() {
|
||||||
|
setDisabling(true);
|
||||||
|
try {
|
||||||
|
const res = await fetch("/api/v1/users/me/developer-access", {
|
||||||
|
method: "PATCH",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ enabled: false }),
|
||||||
|
});
|
||||||
|
if (!res.ok) throw new Error();
|
||||||
|
router.refresh();
|
||||||
|
} catch {
|
||||||
|
toast.error("Couldn't disable developer access");
|
||||||
|
setDisabling(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
disabled={disabling}
|
||||||
|
onClick={() => { void disable(); }}
|
||||||
|
className="text-xs text-muted-foreground hover:text-destructive underline underline-offset-2"
|
||||||
|
>
|
||||||
|
{disabling ? "Disabling…" : "Disable developer access"}
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -19,11 +19,11 @@ const NAV_ITEMS = [
|
|||||||
|
|
||||||
const DEVELOPER_ONLY_KEYS = new Set(["apiKeys", "webhooks"]);
|
const DEVELOPER_ONLY_KEYS = new Set(["apiKeys", "webhooks"]);
|
||||||
|
|
||||||
export function SettingsSidebar({ isDeveloper }: { isDeveloper: boolean }) {
|
export function SettingsSidebar({ showDeveloperNav }: { showDeveloperNav: 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));
|
const visibleItems = NAV_ITEMS.filter((item) => showDeveloperNav || !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">
|
||||||
|
|||||||
@@ -4,7 +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";
|
import { hasDeveloperAccess, hasByokAccess } 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() });
|
||||||
@@ -40,10 +40,10 @@ 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
|
/** Gates webhooks and self-serve API keys behind users.isDeveloper —
|
||||||
* users.isDeveloper — re-queried fresh for the same reason requireAdmin
|
* re-queried fresh for the same reason requireAdmin re-queries role
|
||||||
* re-queries role (session.user's cookieCache can be up to 5 minutes
|
* (session.user's cookieCache can be up to 5 minutes stale, e.g. right
|
||||||
* stale, e.g. right after an admin grants access). */
|
* after a grant). */
|
||||||
export async function requireDeveloper() {
|
export async function requireDeveloper() {
|
||||||
const { session, response } = await requireSession();
|
const { session, response } = await requireSession();
|
||||||
if (response) return { session: null, response };
|
if (response) return { session: null, response };
|
||||||
@@ -57,7 +57,28 @@ export async function requireDeveloper() {
|
|||||||
if (!dbUser || !hasDeveloperAccess(dbUser)) {
|
if (!dbUser || !hasDeveloperAccess(dbUser)) {
|
||||||
return {
|
return {
|
||||||
session: null,
|
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 };
|
return { session, response: null };
|
||||||
|
|||||||
@@ -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.71.0";
|
export const APP_VERSION = "0.72.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.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",
|
version: "0.71.0",
|
||||||
date: "2026-07-22 10:00",
|
date: "2026-07-22 10:00",
|
||||||
|
|||||||
@@ -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: "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: "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: "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-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: "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 } } } } });
|
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(),
|
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. 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: "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 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: "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 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: "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 ---
|
// --- 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"]);
|
||||||
@@ -879,10 +880,11 @@ 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."),
|
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({
|
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({
|
const AdminUserUsageRef = registry.register("AdminUserUsage", z.object({
|
||||||
|
|||||||
@@ -1,8 +1,22 @@
|
|||||||
/** Gates webhooks, self-serve API keys, and BYOK AI provider keys.
|
/** Gates webhooks and self-serve API keys. Admin-settable always
|
||||||
* Admin-granted only for now (users.isDeveloper, toggled in
|
* (users.isDeveloper, toggled in admin/users/[id]); also self-serve
|
||||||
* admin/users/[id]) — kept as a single function so a future
|
* toggleable by the user themselves once on a paid tier, no added fee —
|
||||||
* subscription-based auto-grant (e.g. `|| tier !== "free"`) is a one-line
|
* see PATCH /api/v1/users/me/developer-access. Both paths write the same
|
||||||
* change here, not a redesign across every call site. */
|
* column, so this check doesn't need to know which one granted it. */
|
||||||
export function hasDeveloperAccess(user: { isDeveloper: boolean }): boolean {
|
export function hasDeveloperAccess(user: { isDeveloper: boolean }): boolean {
|
||||||
return user.isDeveloper;
|
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";
|
||||||
|
}
|
||||||
|
|||||||
@@ -420,7 +420,9 @@
|
|||||||
"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.",
|
"developerLockedNotice": "Developer access required. Ask an admin to enable it for your account, or upgrade to a paid plan to enable it yourself.",
|
||||||
|
"developerSelfServeNotice": "Enable developer access to use webhooks and API keys — included free with your plan, no extra charge.",
|
||||||
|
"byokLockedNotice": "BYOK 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.",
|
||||||
|
|||||||
@@ -420,7 +420,9 @@
|
|||||||
"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.",
|
"developerLockedNotice": "Accès développeur requis. Demandez à un administrateur de l'activer pour votre compte, ou passez à un forfait payant pour l'activer vous-même.",
|
||||||
|
"developerSelfServeNotice": "Activez l'accès développeur pour utiliser les webhooks et les clés API — inclus gratuitement avec votre forfait, sans frais supplémentaires.",
|
||||||
|
"byokLockedNotice": "Accès BYOK 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,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@epicure/web",
|
"name": "@epicure/web",
|
||||||
"version": "0.71.0",
|
"version": "0.72.0",
|
||||||
"private": true,
|
"private": true,
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "next dev",
|
"dev": "next dev",
|
||||||
|
|||||||
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "epicure",
|
"name": "epicure",
|
||||||
"version": "0.71.0",
|
"version": "0.72.0",
|
||||||
"private": true,
|
"private": true,
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "pnpm --filter web dev",
|
"dev": "pnpm --filter web dev",
|
||||||
|
|||||||
@@ -0,0 +1,9 @@
|
|||||||
|
ALTER TABLE "users" ADD COLUMN "is_byok_enabled" boolean DEFAULT false NOT NULL;
|
||||||
|
--> statement-breakpoint
|
||||||
|
-- Grandfather in anyone who already has a BYOK AI key configured -- BYOK
|
||||||
|
-- is now its own gate (previously covered by is_developer, per the
|
||||||
|
-- migration in 0060), so without this backfill every existing BYOK setup
|
||||||
|
-- would silently break the moment this migration runs.
|
||||||
|
UPDATE "users" SET "is_byok_enabled" = true WHERE "id" IN (
|
||||||
|
SELECT "user_id" FROM "user_ai_keys"
|
||||||
|
);
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -428,6 +428,13 @@
|
|||||||
"when": 1784706150797,
|
"when": 1784706150797,
|
||||||
"tag": "0060_wandering_mongoose",
|
"tag": "0060_wandering_mongoose",
|
||||||
"breakpoints": true
|
"breakpoints": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"idx": 61,
|
||||||
|
"version": "7",
|
||||||
|
"when": 1784791587563,
|
||||||
|
"tag": "0061_stormy_the_fallen",
|
||||||
|
"breakpoints": true
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
@@ -33,10 +33,16 @@ export const users = pgTable("users", {
|
|||||||
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) —
|
// Orthogonal to both role (staff hierarchy) and tier (billing plan) —
|
||||||
// gates webhooks, self-serve API keys, and BYOK AI provider keys.
|
// gates webhooks and self-serve API keys. Admin-settable always; also
|
||||||
// Admin-granted only for now; hasDeveloperAccess() in lib/permissions.ts
|
// self-serve toggleable by the user themselves once on a paid tier (no
|
||||||
// is the single place a future tier-based auto-grant would be added.
|
// added fee) via PATCH /api/v1/users/me/developer-access — see
|
||||||
|
// hasDeveloperAccess() in lib/permissions.ts.
|
||||||
isDeveloper: boolean("is_developer").notNull().default(false),
|
isDeveloper: boolean("is_developer").notNull().default(false),
|
||||||
|
// Separate from isDeveloper on purpose — BYOK means routing real AI
|
||||||
|
// provider spend through Epicure on the user's own key, which warrants a
|
||||||
|
// manual admin check-in rather than blanket self-serve. Admin-only, no
|
||||||
|
// self-serve path. See hasByokAccess() in lib/permissions.ts.
|
||||||
|
isByokEnabled: boolean("is_byok_enabled").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"),
|
||||||
|
|||||||
Reference in New Issue
Block a user