feat: per-tier feature toggles for recipe variations/pairings (v0.50.0)

Admins can now disable specific AI features per tier from Admin > Tier
Limits — new feature_flags table (feature x tier -> enabled, defaulting
to true so adding a new gated feature never needs a backfill).

Covers recipe variations, drink pairing, and meal pairing to start.
When disabled for a user's tier, the button stays visible (with a small
lock badge) but opens an upgrade dialog instead of running; the API
route rejects the call server-side either way (requireFeatureEnabled,
re-reads tier from the DB rather than trusting the session's cache,
same rationale as checkAndIncrementTierLimit).

The upgrade dialog is informational only — no Stripe checkout exists
yet (STRIPE_PLAN.md is still just a plan) — its CTA links to /support
prefilled as an upgrade-interest suggestion.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
Arnaud
2026-07-18 23:35:12 +02:00
parent 12c2ec213a
commit 2f3ba14093
24 changed files with 5945 additions and 19 deletions
+13 -3
View File
@@ -41,6 +41,7 @@ import { KeepScreenAwake } from "@/components/recipe/keep-screen-awake";
import { ExportMarkdownButton } from "@/components/shared/export-markdown-button";
import { recipeToMarkdown } from "@/lib/markdown/recipe";
import { getMessages, formatMessage } from "@/lib/i18n/server";
import { getFeatureFlagMatrix, type Tier } from "@/lib/feature-flags";
type Params = { params: Promise<{ id: string }> };
@@ -70,7 +71,7 @@ export default async function RecipePage({ params }: Params) {
const DIETARY_LABELS = m.recipe.dietary;
const unitPref = (session.user as { unitPref?: string }).unitPref === "imperial" ? "imperial" : "metric";
const [recipe, ratingData, favoriteData, myRating, forkedFrom, myNote, dishCookLog] = await Promise.all([
const [recipe, ratingData, favoriteData, myRating, forkedFrom, myNote, dishCookLog, featureFlags] = await Promise.all([
db.query.recipes.findFirst({
where: and(
eq(recipes.id, id),
@@ -100,10 +101,18 @@ export default async function RecipePage({ params }: Params) {
orderBy: desc(cookingHistory.cookedAt),
columns: { batchDishId: true, cookedAt: true },
}),
getFeatureFlagMatrix(),
]);
if (!recipe) notFound();
const viewerTier = (session.user as { tier?: string }).tier as Tier | undefined ?? "free";
const locked = {
variations: !featureFlags.recipe_variations[viewerTier],
drinkPairing: !featureFlags.drink_pairing[viewerTier],
mealPairing: !featureFlags.meal_pairing[viewerTier],
};
const isOwner = recipe.authorId === session.user.id;
const dishCookedAtMap = new Map<string, string>();
@@ -176,8 +185,8 @@ export default async function RecipePage({ params }: Params) {
<FavoriteButton recipeId={id} initialFavorited={isFavorited} />
{!recipe.isBatchCook && recipe.recipeType !== "drink" && (
<>
<MealPairingButton recipeId={id} />
<DrinkPairingButton recipeId={id} />
<MealPairingButton recipeId={id} locked={locked.mealPairing} />
<DrinkPairingButton recipeId={id} locked={locked.drinkPairing} />
</>
)}
{recipe.visibility === "public" && (
@@ -229,6 +238,7 @@ export default async function RecipePage({ params }: Params) {
timerSeconds: s.timerSeconds,
order: s.order,
}))}
locked={locked.variations}
/>
<ForkRecipeButton recipeId={id} variant={isOwner ? "duplicate" : "fork"} />
<ShareRecipeButton recipeId={id} visibility={recipe.visibility} />
+13 -1
View File
@@ -5,14 +5,25 @@ import { db, supportTickets, eq, desc } from "@epicure/db";
import { SupportManager } from "@/components/support/support-manager";
import { getMessages } from "@/lib/i18n/server";
import { getPublicUrl } from "@/lib/storage";
import { FEATURE_DEFINITIONS } from "@/lib/feature-flags";
export const metadata: Metadata = {};
export default async function SupportPage() {
export default async function SupportPage({
searchParams,
}: {
searchParams: Promise<{ upgrade?: string }>;
}) {
const session = await auth.api.getSession({ headers: await headers() });
if (!session) return null;
const m = getMessages((session.user as { locale?: string }).locale);
const { upgrade } = await searchParams;
const upgradeFeature = FEATURE_DEFINITIONS.find((f) => f.key === upgrade);
const prefill = upgradeFeature
? { type: "suggestion" as const, title: `Interested in upgrading for: ${upgradeFeature.label}` }
: undefined;
const rows = await db.query.supportTickets.findMany({
where: eq(supportTickets.userId, session.user.id),
orderBy: desc(supportTickets.createdAt),
@@ -26,6 +37,7 @@ export default async function SupportPage() {
<p className="text-muted-foreground text-sm mt-1">{m.support.subtitle}</p>
</div>
<SupportManager
prefill={prefill}
initialTickets={rows.map((r) => ({
id: r.id,
type: r.type,
+11 -1
View File
@@ -1,11 +1,16 @@
import type { Metadata } from "next";
import { db, tierDefinitions } from "@epicure/db";
import { TierLimitsForm } from "@/components/admin/tier-limits-form";
import { FeatureFlagsForm } from "@/components/admin/feature-flags-form";
import { getFeatureFlagMatrix, FEATURE_DEFINITIONS } from "@/lib/feature-flags";
export const metadata: Metadata = {};
export default async function AdminTiersPage() {
const tiers = await db.select().from(tierDefinitions);
const [tiers, featureFlagMatrix] = await Promise.all([
db.select().from(tierDefinitions),
getFeatureFlagMatrix(),
]);
return (
<div className="space-y-8">
@@ -19,6 +24,11 @@ export default async function AdminTiersPage() {
{tiers.map((tierDefinition) => (
<TierLimitsForm key={tierDefinition.tier} tierDefinition={tierDefinition} />
))}
<FeatureFlagsForm
features={FEATURE_DEFINITIONS.map((f) => ({ key: f.key, label: f.label, description: f.description }))}
initialMatrix={featureFlagMatrix}
/>
</div>
);
}
@@ -0,0 +1,38 @@
import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { requireAdmin } from "@/lib/api-auth";
import { getFeatureFlagMatrix, setFeatureFlag, FEATURE_KEYS, TIERS } from "@/lib/feature-flags";
export async function GET() {
const { response } = await requireAdmin();
if (response) return response;
const matrix = await getFeatureFlagMatrix();
return NextResponse.json(matrix);
}
const UpdateBody = z.object({
featureKey: z.enum(FEATURE_KEYS as [string, ...string[]]),
tier: z.enum(TIERS as [string, ...string[]]),
enabled: z.boolean(),
});
export async function PATCH(req: NextRequest) {
const { session, response } = await requireAdmin();
if (response) return response;
const body = (await req.json()) as unknown;
const parsed = UpdateBody.safeParse(body);
if (!parsed.success) {
return NextResponse.json({ error: "Validation error", issues: parsed.error.issues }, { status: 400 });
}
await setFeatureFlag(
parsed.data.featureKey as (typeof FEATURE_KEYS)[number],
parsed.data.tier as (typeof TIERS)[number],
parsed.data.enabled,
session!.user.id
);
return NextResponse.json({ ok: true });
}
@@ -7,6 +7,7 @@ import { withAiQuota, resolveAiConfigOrError } from "@/lib/ai/ai-error";
import { suggestDrinks } from "@/lib/ai/features/suggest-drinks";
import { withUserKey } from "@/lib/ai/resolve-user-key";
import { getUserPrivateBio } from "@/lib/ai/user-bio";
import { requireFeatureEnabled, FeatureDisabledError } from "@/lib/feature-flags";
const Schema = z.object({
count: z.number().int().min(1).max(6).default(4),
@@ -20,6 +21,18 @@ export async function POST(req: NextRequest, { params }: Params) {
const { session, response } = await requireSessionOrApiKey(req);
if (response) return response;
try {
await requireFeatureEnabled(session!.user.id, "drink_pairing");
} catch (err) {
if (err instanceof FeatureDisabledError) {
return NextResponse.json(
{ error: "This feature isn't available on your plan", code: "FEATURE_DISABLED", featureKey: err.featureKey },
{ status: 403 }
);
}
throw err;
}
const { id } = await params;
const recipe = await db.query.recipes.findFirst({
@@ -7,6 +7,7 @@ import { withAiQuota, resolveAiConfigOrError } from "@/lib/ai/ai-error";
import { suggestPairings } from "@/lib/ai/features/suggest-pairings";
import { withUserKey } from "@/lib/ai/resolve-user-key";
import { getUserPrivateBio } from "@/lib/ai/user-bio";
import { requireFeatureEnabled, FeatureDisabledError } from "@/lib/feature-flags";
const Schema = z.object({
count: z.number().int().min(1).max(6).default(4),
@@ -20,6 +21,18 @@ export async function POST(req: NextRequest, { params }: Params) {
const { session, response } = await requireSessionOrApiKey(req);
if (response) return response;
try {
await requireFeatureEnabled(session!.user.id, "meal_pairing");
} catch (err) {
if (err instanceof FeatureDisabledError) {
return NextResponse.json(
{ error: "This feature isn't available on your plan", code: "FEATURE_DISABLED", featureKey: err.featureKey },
{ status: 403 }
);
}
throw err;
}
const { id } = await params;
// Allow pairings for own recipes or public recipes
@@ -7,6 +7,7 @@ import { withAiQuota, resolveAiConfigOrError } from "@/lib/ai/ai-error";
import { suggestVariations } from "@/lib/ai/features/suggest-variations";
import { withUserKey } from "@/lib/ai/resolve-user-key";
import { getUserPrivateBio } from "@/lib/ai/user-bio";
import { requireFeatureEnabled, FeatureDisabledError } from "@/lib/feature-flags";
const Schema = z.object({
count: z.number().int().min(1).max(5).default(3),
@@ -21,6 +22,18 @@ export async function POST(req: NextRequest, { params }: Params) {
const { session, response } = await requireSessionOrApiKey(req);
if (response) return response;
try {
await requireFeatureEnabled(session!.user.id, "recipe_variations");
} catch (err) {
if (err instanceof FeatureDisabledError) {
return NextResponse.json(
{ error: "This feature isn't available on your plan", code: "FEATURE_DISABLED", featureKey: err.featureKey },
{ status: 403 }
);
}
throw err;
}
const { id } = await params;
const recipe = await db.query.recipes.findFirst({
where: and(eq(recipes.id, id), eq(recipes.authorId, session!.user.id)),
@@ -0,0 +1,88 @@
"use client";
import { useState } from "react";
import { toast } from "sonner";
import { Switch } from "@/components/ui/switch";
type Tier = "free" | "pro" | "family";
type FeatureDef = { key: string; label: string; description: string };
type Matrix = Record<string, Record<Tier, boolean>>;
const TIER_LABELS: Record<Tier, string> = { free: "Free", pro: "Pro", family: "Family" };
const TIERS: Tier[] = ["free", "pro", "family"];
export function FeatureFlagsForm({
features,
initialMatrix,
}: {
features: FeatureDef[];
initialMatrix: Matrix;
}) {
const [matrix, setMatrix] = useState<Matrix>(initialMatrix);
const [saving, setSaving] = useState<string | null>(null);
async function toggle(featureKey: string, tier: Tier, enabled: boolean) {
const cellKey = `${featureKey}:${tier}`;
setSaving(cellKey);
const prev = matrix[featureKey]![tier];
setMatrix((m) => ({ ...m, [featureKey]: { ...m[featureKey]!, [tier]: enabled } }));
try {
const res = await fetch("/api/v1/admin/feature-flags", {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ featureKey, tier, enabled }),
});
if (!res.ok) throw new Error();
} catch {
setMatrix((m) => ({ ...m, [featureKey]: { ...m[featureKey]!, [tier]: prev } }));
toast.error("Failed to update feature flag");
} finally {
setSaving(null);
}
}
return (
<section className="rounded-xl border p-6 space-y-4">
<div>
<h2 className="font-semibold text-lg">Feature Toggles</h2>
<p className="text-sm text-muted-foreground mt-1">
Disable a feature for a tier to keep its button visible but gated clicking it shows an upgrade prompt instead of running.
</p>
</div>
<div className="overflow-x-auto">
<table className="w-full text-sm">
<thead>
<tr className="text-left border-b">
<th className="py-2 pr-4 font-medium text-muted-foreground">Feature</th>
{TIERS.map((tier) => (
<th key={tier} className="py-2 px-4 font-medium text-muted-foreground text-center">{TIER_LABELS[tier]}</th>
))}
</tr>
</thead>
<tbody>
{features.map((f) => (
<tr key={f.key} className="border-b last:border-0">
<td className="py-3 pr-4">
<p className="font-medium">{f.label}</p>
<p className="text-xs text-muted-foreground">{f.description}</p>
</td>
{TIERS.map((tier) => (
<td key={tier} className="py-3 px-4 text-center">
<Switch
checked={matrix[f.key]?.[tier] ?? true}
disabled={saving === `${f.key}:${tier}`}
onCheckedChange={(checked) => { void toggle(f.key, tier, checked); }}
/>
</td>
))}
</tr>
))}
</tbody>
</table>
</div>
</section>
);
}
@@ -0,0 +1,50 @@
"use client";
import Link from "next/link";
import { Sparkles } from "lucide-react";
import { buttonVariants } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogDescription,
DialogFooter,
} from "@/components/ui/dialog";
export function UpgradeDialog({
open,
onOpenChange,
featureKey,
featureLabel,
}: {
open: boolean;
onOpenChange: (open: boolean) => void;
featureKey: string;
featureLabel: string;
}) {
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-sm">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<Sparkles className="h-5 w-5 text-primary" />
A Pro feature
</DialogTitle>
<DialogDescription>
{featureLabel} is available on the Pro plan (4.99/mo). Free accounts don&apos;t include it.
</DialogDescription>
</DialogHeader>
<DialogFooter className="sm:justify-start">
<Link
href={`/support?upgrade=${encodeURIComponent(featureKey)}`}
className={cn(buttonVariants({ variant: "default" }))}
>
I&apos;m interested let us know
</Link>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
@@ -2,7 +2,7 @@
import { useState } from "react";
import { useTranslations } from "next-intl";
import { Wine, Sparkles, Loader2, Coffee, Beer, GlassWater, Leaf } from "lucide-react";
import { Wine, Sparkles, Loader2, Coffee, Beer, GlassWater, Leaf, Lock } from "lucide-react";
import { FakeProgressBar } from "@/components/ui/fake-progress-bar";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
@@ -16,6 +16,7 @@ import {
} from "@/components/ui/dialog";
import { Badge } from "@/components/ui/badge";
import { Separator } from "@/components/ui/separator";
import { UpgradeDialog } from "@/components/premium/upgrade-dialog";
type Drink = {
name: string;
@@ -45,9 +46,10 @@ const TYPE_LABEL_KEY: Record<Drink["type"], string> = {
hot: "drinksTypeHot",
};
export function DrinkPairingButton({ recipeId }: { recipeId: string }) {
export function DrinkPairingButton({ recipeId, locked = false }: { recipeId: string; locked?: boolean }) {
const t = useTranslations("recipe");
const [open, setOpen] = useState(false);
const [upgradeOpen, setUpgradeOpen] = useState(false);
const [loading, setLoading] = useState(false);
const [drinks, setDrinks] = useState<Drink[]>([]);
@@ -72,6 +74,10 @@ export function DrinkPairingButton({ recipeId }: { recipeId: string }) {
}
function handleOpen() {
if (locked) {
setUpgradeOpen(true);
return;
}
setOpen(true);
if (drinks.length === 0) suggest();
}
@@ -81,14 +87,22 @@ export function DrinkPairingButton({ recipeId }: { recipeId: string }) {
<TooltipProvider>
<Tooltip>
<TooltipTrigger render={
<Button variant="ghost" size="icon" onClick={handleOpen} aria-label={t("drinksTooltip")}>
<Button variant="ghost" size="icon" onClick={handleOpen} aria-label={t("drinksTooltip")} className="relative">
<Wine className="h-4 w-4" />
{locked && <Lock className="h-2.5 w-2.5 absolute bottom-1 right-1 text-muted-foreground" />}
</Button>
} />
<TooltipContent>{t("drinksTooltip")}</TooltipContent>
</Tooltip>
</TooltipProvider>
<UpgradeDialog
open={upgradeOpen}
onOpenChange={setUpgradeOpen}
featureKey="drink_pairing"
featureLabel="Drink pairing"
/>
<Dialog open={open} onOpenChange={setOpen}>
<DialogContent className="max-w-2xl max-h-[80vh] overflow-y-auto">
<DialogHeader>
@@ -4,7 +4,8 @@ import { useState } from "react";
import { useTranslations } from "next-intl";
import { useRouter } from "next/navigation";
import { FakeProgressBar } from "@/components/ui/fake-progress-bar";
import { UtensilsCrossed, Sparkles, Loader2, ChefHat, Salad, Wine, Cake, Sandwich, Soup, Check } from "lucide-react";
import { UtensilsCrossed, Sparkles, Loader2, ChefHat, Salad, Wine, Cake, Sandwich, Soup, Check, Lock } from "lucide-react";
import { UpgradeDialog } from "@/components/premium/upgrade-dialog";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
@@ -54,10 +55,11 @@ const DIFFICULTY_VARIANT = {
hard: "destructive",
} as const;
export function MealPairingButton({ recipeId }: { recipeId: string }) {
export function MealPairingButton({ recipeId, locked = false }: { recipeId: string; locked?: boolean }) {
const t = useTranslations("recipe");
const router = useRouter();
const [open, setOpen] = useState(false);
const [upgradeOpen, setUpgradeOpen] = useState(false);
const [loading, setLoading] = useState(false);
const [selected, setSelected] = useState<Set<number>>(new Set());
const [generatingProgress, setGeneratingProgress] = useState<{ current: number; total: number } | null>(null);
@@ -141,14 +143,32 @@ export function MealPairingButton({ recipeId }: { recipeId: string }) {
<TooltipProvider>
<Tooltip>
<TooltipTrigger render={
<Button variant="ghost" size="icon" onClick={() => { setOpen(true); if (pairings.length === 0) suggest(); }} aria-label={t("pairMealTooltip")}>
<Button
variant="ghost"
size="icon"
onClick={() => {
if (locked) { setUpgradeOpen(true); return; }
setOpen(true);
if (pairings.length === 0) suggest();
}}
aria-label={t("pairMealTooltip")}
className="relative"
>
<UtensilsCrossed className="h-4 w-4" />
{locked && <Lock className="h-2.5 w-2.5 absolute bottom-1 right-1 text-muted-foreground" />}
</Button>
} />
<TooltipContent>{t("pairMealTooltip")}</TooltipContent>
</Tooltip>
</TooltipProvider>
<UpgradeDialog
open={upgradeOpen}
onOpenChange={setUpgradeOpen}
featureKey="meal_pairing"
featureLabel="Meal pairing"
/>
<Dialog open={open} onOpenChange={setOpen}>
<DialogContent className="max-w-5xl max-h-[80vh] overflow-y-auto">
<DialogHeader>
@@ -2,10 +2,11 @@
import { useState } from "react";
import { useTranslations } from "next-intl";
import { GitBranch } from "lucide-react";
import { GitBranch, Lock } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
import { VariationsDialog } from "./variations-dialog";
import { UpgradeDialog } from "@/components/premium/upgrade-dialog";
export function VariationsButton({
recipeId,
@@ -15,6 +16,7 @@ export function VariationsButton({
cookMins,
ingredients,
steps,
locked = false,
}: {
recipeId: string;
baseServings: number;
@@ -23,17 +25,26 @@ export function VariationsButton({
cookMins?: number | null;
ingredients: Array<{ rawName: string; quantity?: string | number | null; unit?: string | null; note?: string | null; order: number }>;
steps: Array<{ instruction: string; timerSeconds?: number | null; order: number }>;
locked?: boolean;
}) {
const t = useTranslations("recipe");
const [open, setOpen] = useState(false);
const [upgradeOpen, setUpgradeOpen] = useState(false);
return (
<>
<TooltipProvider>
<Tooltip>
<TooltipTrigger render={
<Button variant="ghost" size="icon" onClick={() => setOpen(true)} aria-label={t("variationsTooltip")}>
<Button
variant="ghost"
size="icon"
onClick={() => (locked ? setUpgradeOpen(true) : setOpen(true))}
aria-label={t("variationsTooltip")}
className="relative"
>
<GitBranch className="h-4 w-4" />
{locked && <Lock className="h-2.5 w-2.5 absolute bottom-1 right-1 text-muted-foreground" />}
</Button>
} />
<TooltipContent>{t("variationsTooltip")}</TooltipContent>
@@ -50,6 +61,12 @@ export function VariationsButton({
open={open}
onOpenChange={setOpen}
/>
<UpgradeDialog
open={upgradeOpen}
onOpenChange={setUpgradeOpen}
featureKey="recipe_variations"
featureLabel="Recipe variations"
/>
</>
);
}
@@ -60,11 +60,17 @@ function isImage(contentType: string) {
return contentType.startsWith("image/");
}
export function SupportManager({ initialTickets }: { initialTickets: Ticket[] }) {
export function SupportManager({
initialTickets,
prefill,
}: {
initialTickets: Ticket[];
prefill?: { type: TicketType; title: string };
}) {
const t = useTranslations("support");
const [tickets, setTickets] = useState<Ticket[]>(initialTickets);
const [type, setType] = useState<TicketType>("bug");
const [title, setTitle] = useState("");
const [type, setType] = useState<TicketType>(prefill?.type ?? "bug");
const [title, setTitle] = useState(prefill?.title ?? "");
const [description, setDescription] = useState("");
const [submitting, setSubmitting] = useState(false);
const [pendingAttachments, setPendingAttachments] = useState<PendingAttachment[]>([]);
+8 -1
View File
@@ -1,5 +1,5 @@
// Mirrors CHANGELOG.md at the repo root — update both together.
export const APP_VERSION = "0.49.1";
export const APP_VERSION = "0.50.0";
export type ChangelogEntry = {
version: string;
@@ -11,6 +11,13 @@ export type ChangelogEntry = {
};
export const CHANGELOG: ChangelogEntry[] = [
{
version: "0.50.0",
date: "2026-07-18 14:20",
added: [
"Per-tier feature toggles, managed from Admin > Tier Limits. Recipe variations, drink pairing, and meal pairing can each be disabled for a tier (e.g. Free) — the buttons stay visible but show an upgrade prompt instead of running, and the API rejects the call server-side either way.",
],
},
{
version: "0.49.1",
date: "2026-07-18 13:10",
+83
View File
@@ -0,0 +1,83 @@
import { db, featureFlags, users, eq, and } from "@epicure/db";
export type Tier = "free" | "pro" | "family";
export const TIERS: Tier[] = ["free", "pro", "family"];
export const FEATURE_DEFINITIONS = [
{
key: "recipe_variations",
label: "Recipe variations",
description: "AI-generated variations of a recipe (dietary swaps, flavor twists, etc.).",
},
{
key: "drink_pairing",
label: "Drink pairing",
description: "AI-suggested drink pairings for a recipe.",
},
{
key: "meal_pairing",
label: "Meal pairing",
description: "AI-suggested side dish / meal pairings for a recipe.",
},
] as const;
export type FeatureKey = (typeof FEATURE_DEFINITIONS)[number]["key"];
export const FEATURE_KEYS = FEATURE_DEFINITIONS.map((f) => f.key) as FeatureKey[];
export class FeatureDisabledError extends Error {
constructor(public readonly featureKey: FeatureKey) {
super(`Feature disabled for your tier: ${featureKey}`);
this.name = "FeatureDisabledError";
}
}
/** Full (feature x tier) matrix, defaulting every cell to enabled=true unless
* a row overrides it. Used by the admin toggle UI. */
export async function getFeatureFlagMatrix(): Promise<Record<FeatureKey, Record<Tier, boolean>>> {
const rows = await db.select().from(featureFlags);
const overrides = new Map(rows.map((r) => [`${r.featureKey}:${r.tier}`, r.enabled]));
const matrix = {} as Record<FeatureKey, Record<Tier, boolean>>;
for (const key of FEATURE_KEYS) {
matrix[key] = {} as Record<Tier, boolean>;
for (const tier of TIERS) {
matrix[key][tier] = overrides.get(`${key}:${tier}`) ?? true;
}
}
return matrix;
}
export async function setFeatureFlag(
featureKey: FeatureKey,
tier: Tier,
enabled: boolean,
updatedById: string
): Promise<void> {
await db
.insert(featureFlags)
.values({ featureKey, tier, enabled, updatedAt: new Date(), updatedById })
.onConflictDoUpdate({
target: [featureFlags.featureKey, featureFlags.tier],
set: { enabled, updatedAt: new Date(), updatedById },
});
}
export async function isFeatureEnabledForTier(featureKey: FeatureKey, tier: Tier): Promise<boolean> {
const [row] = await db
.select({ enabled: featureFlags.enabled })
.from(featureFlags)
.where(and(eq(featureFlags.featureKey, featureKey), eq(featureFlags.tier, tier)));
return row ? row.enabled : true;
}
/**
* Server-side enforcement for API routes — never trust the session's tier
* (5-minute cookieCache, see lib/auth/server.ts), re-read it from the DB,
* same rationale as checkAndIncrementTierLimit.
*/
export async function requireFeatureEnabled(userId: string, featureKey: FeatureKey): Promise<void> {
const [dbUser] = await db.select({ tier: users.tier }).from(users).where(eq(users.id, userId));
const tier = (dbUser?.tier ?? "free") as Tier;
const enabled = await isFeatureEnabledForTier(featureKey, tier);
if (!enabled) throw new FeatureDisabledError(featureKey);
}
+13
View File
@@ -814,6 +814,19 @@ export function generateOpenApiSpec(): object {
registry.registerPath({ method: "patch", path: "/api/v1/admin/tiers/{tier}", summary: "Update numeric limits for a tier definition", description: "Admin only.", security: adminSecurity, request: { params: tierParam, body: { content: { "application/json": { schema: UpdateTierDefinitionBodyRef } }, required: true } }, responses: { 200: { description: "Updated", content: { "application/json": { schema: z.object({ tierDefinition: TierDefinitionRef }) } } }, 400: { description: "Invalid tier or field value", content: { "application/json": { schema: ApiErrorRef } } }, 403: { description: "Forbidden", content: { "application/json": { schema: ApiErrorRef } } }, 404: { description: "Tier not found", content: { "application/json": { schema: ApiErrorRef } } } } });
const FeatureFlagMatrixRef = registry.register("FeatureFlagMatrix", z.record(
z.string(),
z.object({ free: z.boolean(), pro: z.boolean(), family: z.boolean() })
).describe("Feature key -> per-tier enabled state. A feature/tier pair defaults to enabled=true until explicitly disabled."));
const UpdateFeatureFlagRef = registry.register("UpdateFeatureFlag", z.object({
featureKey: z.enum(["recipe_variations", "drink_pairing", "meal_pairing"]),
tier: z.enum(["free", "pro", "family"]),
enabled: z.boolean(),
}));
registry.registerPath({ method: "get", path: "/api/v1/admin/feature-flags", summary: "Get the full feature x tier toggle matrix", description: "Admin only.", security: adminSecurity, responses: { 200: { description: "Matrix", content: { "application/json": { schema: FeatureFlagMatrixRef } } }, 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: "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}/usage", summary: "Reset a user's usage counters for the current month", description: "Admin only.", 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 } } } } });
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@epicure/web",
"version": "0.49.1",
"version": "0.50.0",
"private": true,
"scripts": {
"dev": "next dev",