diff --git a/CHANGELOG.md b/CHANGELOG.md
index a168c67..b3b0c2a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,19 @@
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.60.0 — 2026-07-20 22:15
+
+### Security
+- Closed a race in recipe/storage tier-limit checks — two concurrent requests near the cap could both pass a live count check and both write, exceeding the lifetime limit. Now locked per-user inside the same transaction as the write.
+- Fixed four AI recipe-creation routes (photo import, idea generation, batch-cook, translate-to-new-draft) that had no recipe-limit check at all, letting any tier create unlimited recipes through them.
+- Added missing per-user rate limits to 5 AI endpoints (adapt, drinks, pairings, translate, variations).
+- Search page now checks for a session server-side, matching every other page (defense-in-depth — the underlying API was already public by design and the edge proxy already blocked unauthenticated access).
+- Upgraded drizzle-orm to fix a SQL-identifier-escaping vulnerability, and overrode two transitive dependencies (esbuild, postcss) with known CVEs — `pnpm audit` is now clean.
+
+### Fixed
+- Admin settings endpoint now uses the shared admin-auth check instead of a local duplicate.
+- Documented two admin support-ticket endpoints that were missing from the OpenAPI spec.
+
## 0.59.0 — 2026-07-20 21:15
### Added
diff --git a/CLAUDE.md b/CLAUDE.md
index 02f2382..bb8d644 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -44,7 +44,7 @@ pnpm db:studio # open Drizzle Studio
- `api/v1/` — REST API endpoints
- `api/auth/[...all]/` — Better Auth handler
-**Auth**: Better Auth with Drizzle adapter. Server: `lib/auth/server.ts`. Client: `lib/auth/client.ts`. Middleware at `middleware.ts` guards all routes.
+**Auth**: Better Auth with Drizzle adapter. Server: `lib/auth/server.ts`. Client: `lib/auth/client.ts`. Edge-level guard is `proxy.ts` (not `middleware.ts`, which was removed) — it checks for a session cookie and redirects to `/login` for non-public paths, and additionally gates `/admin` paths. Per-route/per-page checks (`auth.api.getSession` in server components, `requireSession`/`requireSessionOrApiKey`/`requireAdmin` in API routes) are still required as defense-in-depth — don't rely on `proxy.ts` alone when adding a page or route under `(app)/` or `admin/`.
**DB**: Drizzle ORM on Postgres. Schema in `packages/db/src/schema/` split by domain: `users`, `recipes`, `social`, `meal-planning`, `tiers`. Import from `@epicure/db`.
diff --git a/SECURITY_AUDIT.md b/SECURITY_AUDIT.md
new file mode 100644
index 0000000..a1f04e8
--- /dev/null
+++ b/SECURITY_AUDIT.md
@@ -0,0 +1,60 @@
+# Epicure Security Audit
+
+Two-round audit: round 1 = 5 parallel domain sweeps (auth, API routes, DB/tier-limits, storage, AI/chatbot); round 2 = independent adversarial verification of every finding that survived round 1. Date: 2026-07-20.
+
+**Status: all findings below fixed and re-verified by a fresh adversarial pass (2026-07-20, later same day) — see "Fix verification" under each.**
+
+## Confirmed findings
+
+### 1. TOCTOU race in recipe/storage tier-limit enforcement — Medium — FIXED
+**File:** `apps/web/lib/tiers.ts` (recipe/storage branches of `checkAndIncrementTierLimit`)
+**Call sites:** `apps/web/app/api/v1/recipes/route.ts`, `apps/web/app/api/v1/upload/presign/route.ts`, and (found during fix-verification, see below) several AI recipe-creation routes that had no check at all.
+
+Check did a live `SELECT COUNT`/`SUM`, compared to limit, returned — no transaction or lock tied it to the later insert. Two concurrent requests near the cap could both read the pre-insert count, both pass, both write — exceeding lifetime `maxRecipes`/`storageMb` via a trivial `Promise.all` script.
+
+**Fix:** added `checkTierLimitInTransaction(tx, userId, fallbackTier, key, amount)` to `lib/tiers.ts` — runs `pg_advisory_xact_lock(hashtext(userId))` as the first statement inside the caller's `db.transaction`, then re-checks the live count/sum against that same transaction, before the insert/update runs. A concurrent request for the same user blocks on the lock until the first commits/rolls back, then sees its committed row. Applied as the first statement inside the write transaction in:
+- `recipes/route.ts` (POST — recipe count + photo storage)
+- `recipes/[id]/route.ts` (PUT — storage delta on photo add/remove)
+- `recipes/[id]/fork/route.ts`, `recipes/[id]/rate/route.ts`, `users/me/route.ts` (avatar)
+- `ai/adapt/[id]/route.ts`, `ai/generate-meal/route.ts`, `ai/meal-plan/generate/route.ts`, `ai/translate/[id]/route.ts`, `ai/import-photo/route.ts`, `ai/generate-from-idea/route.ts`, `ai/batch-cook/generate/route.ts`
+
+**Fix verification:** a fresh adversarial pass confirmed the lock+check+write are genuinely atomic per-user in every listed call site, and also caught that four AI recipe-creation routes (`import-photo`, `generate-from-idea`, `batch-cook/generate`, `translate/[id]`) had **no tier check at all** (not even the old unlocked pre-flight) — an unconditional bypass of `maxRecipes`, broader than the original race. All four now call `checkTierLimitInTransaction` inside their insert transaction. Presign routes (`upload/presign`, `upload/avatar-presign`) still only do the old unlocked pre-flight check — this is fine, since storage is derived live from real rows (not a counter), so presigning alone never moves the accounted total; the authoritative, locked check now happens at write time (recipe save, rating save, avatar save) instead.
+
+### 2. No rate limit on 5 AI endpoints, bypassable further by BYOK — Medium — FIXED
+**Files:** `apps/web/app/api/v1/ai/adapt/[id]/route.ts`, `ai/drinks/[id]/route.ts`, `ai/pairings/[id]/route.ts`, `ai/translate/[id]/route.ts`, `ai/variations/[id]/route.ts`
+
+None of these called `applyRateLimit`, unlike siblings `ai/generate`, `ai/scale`, `ai/substitute`, `ai/recipe-chat`, `ai/import-url`, which all throttle per-user via Redis.
+
+**Fix:** added `applyRateLimit(\`rl:ai:${userId}\`, 10, 60)` to all 5, placed immediately after the session check, matching the sibling routes' convention and rate class (one-shot single-recipe AI transforms).
+
+**Fix verification:** confirmed correct placement (before any DB/AI work), correct per-user keying, and consistent limit choice against siblings. Re-swept the entire `ai/` route tree — no other endpoint is missing a rate limit. BYOK still bypasses the usage quota (`skipQuota: isByok`) but not the rate limit itself — same behavior as every other AI route in the codebase, not a gap introduced or left open by this fix.
+
+### 3. `search` page has no server-side session check — Low — FIXED
+**File:** `apps/web/app/(app)/search/page.tsx`
+
+Rendered `SearchPageContent` with zero session check, unlike sibling pages. Low-impact even before the fix: the underlying API route is intentionally public (query hard-filtered to public recipes regardless of session), and `proxy.ts` (the actual edge guard — `middleware.ts` was removed in an earlier commit, contrary to what `CLAUDE.md` claimed at audit time) already redirects unauthenticated requests to `/login` for non-public paths. The missing page-level check was a defense-in-depth/consistency gap, not a live data-leak.
+
+**Fix:** added the same `auth.api.getSession` / `if (!session) return null;` check used by every sibling page. Also corrected `CLAUDE.md`'s stale auth section to describe `proxy.ts` (not the removed `middleware.ts`) plus the per-route checks as defense-in-depth.
+
+**Fix verification:** confirmed the added check matches the established convention exactly (checked against 9 sibling pages). No regression.
+
+## Minor / non-blocking — FIXED
+
+- `apps/web/app/api/v1/admin/settings/route.ts` reimplemented `requireAdmin()` locally instead of importing the shared `lib/api-auth.ts` version. **Fixed**: now imports and uses the shared `requireAdmin`. Response code for the no-session case changed from 403 to 401 (shared helper's behavior) — verified this is a correctness improvement, not a breaking change: no frontend caller branches on that specific status code, and `/admin/*` is already gated upstream by `proxy.ts`. Updated `lib/openapi.ts`'s documented responses to include 401. Swept all other admin routes — none hand-roll their own admin check; this was the only duplicate.
+- `apps/web/lib/ai/user-bio.ts`'s `buildUserBioContext` interpolates the user's own `privateBio` directly into the system prompt — self-injection only, not a cross-user vector. Flagged for completeness only, no fix needed.
+
+## Clean (checked, no issues found)
+
+- **Auth/authz:** role/tier always re-read from DB (`requireAdmin`, `checkAndIncrementTierLimit`, moderator-delete branch), never trusted from session cookie cache. No IDOR, no open redirect, no hardcoded secrets, no timing-attack-relevant comparisons.
+- **API routes:** ownership scoping consistent across recipes, meal-plans, shopping-lists, collections, comments, webhooks. No mass assignment (explicit field allowlists). SSRF closed via IP-pinning + redirect re-validation in `safeFetch`/`validate-webhook-url.ts` (covers RFC1918/loopback/link-local/multicast, IPv4 + IPv6). File uploads validate content-type/size server-side, server-generated keys (no path traversal). Auth rate limiter backed by Redis (not per-replica in-memory). Error responses sanitized, no stack-trace leakage.
+- **DB/SQL:** all raw `sql\`\`` usage is parameter-bound, not string-concatenated. `search` route explicitly escapes `%`/`_`/`\` before `ilike`. ~30 spot-checked update/delete sites all scope by owner or a pre-verified `findFirst`. Stripe webhook updates `users.tier` keyed by webhook-verified identifiers, not client input.
+- **Storage/S3:** keys always server-built (UUID-based, never from client filenames). Presigned POST (not bare PUT) with signed `content-length-range`/`Content-Type` conditions, 300s expiry, single-key scope. Ownership re-checked via `isOwned*Key` helpers before any writeback of a client-submitted key. Deletes only ever use DB-read-back keys after owner-scoped fetch. Secrets never reach the client bundle.
+- **AI/chatbot:** tool-calls (`create-recipe-tool`, `add-to-shopping-list-tool`) don't write to the DB directly — persistence goes through normal authz-checked API routes after user confirmation. No "fetch/modify by ID" tool exists to exploit. Admin AI settings allowlisted + audit-logged. Secrets masked in `site-settings.ts`. Non-BYOK AI calls are quota-checked and rate-limited (all AI routes, after finding #2's fix). Model output rendered as plain React text (no `dangerouslySetInnerHTML` in chat paths) — no XSS via model output.
+
+## Round-2 verification notes
+
+All three confirmed findings were independently re-verified by a second agent reading the code fresh, with one correction: the original search-page write-up attributed the low severity to the API route being "auth-protected" — round 2 found that's wrong, the API is intentionally public by design, not gated. Net severity assessment unchanged.
+
+## Fix-verification round (2026-07-20, later same day)
+
+After implementing fixes for all three confirmed findings plus the minor `requireAdmin` duplication, ran a second independent adversarial pass specifically against the fix diff (two parallel reviewers, one per fix area). Outcome: findings #2, #3, and the minor `requireAdmin` item confirmed cleanly fixed with no regressions. Finding #1's fix was confirmed correct for every call site it touched, but the same pass caught a **broader pre-existing gap** in the same area — four AI recipe-creation routes with no tier-limit check whatsoever — which has since also been fixed and included in the "Fix" description above. No further issues found; typecheck, lint, full test suite (191/193 passing — the 2 failures are pre-existing and unrelated to this session, see git history), and production build all pass clean.
diff --git a/SECURITY_AUDIT_2026-07-20_followup.md b/SECURITY_AUDIT_2026-07-20_followup.md
new file mode 100644
index 0000000..4b38008
--- /dev/null
+++ b/SECURITY_AUDIT_2026-07-20_followup.md
@@ -0,0 +1,37 @@
+# Follow-up: dependency CVEs + OpenAPI coverage
+
+Companion to `SECURITY_AUDIT.md` (same day, same session). Two additional checks requested after the tier-limit/rate-limit fixes shipped.
+
+## 1. Dependency vulnerabilities (`pnpm audit`)
+
+**Before:**
+
+| Severity | Package | Issue | Fixed in |
+|---|---|---|---|
+| High | `drizzle-orm@0.44.7` | SQL injection via improperly escaped SQL identifiers ([GHSA-gpj5-g38j-94v9](https://github.com/advisories/GHSA-gpj5-g38j-94v9)) | `>=0.45.2` |
+| Moderate | `esbuild@0.18.20` (transitive, via `drizzle-kit` → `@esbuild-kit/esm-loader`, dev-only) | esbuild dev server accepts requests from any origin ([GHSA-67mh-4wv8-2f99](https://github.com/advisories/GHSA-67mh-4wv8-2f99)) | `>=0.24.3` |
+| Moderate | `postcss@8.4.31` (transitive, via `next@16.2.9`) | XSS via unescaped `` in CSS stringify output ([GHSA-qx2v-qp2m-jg93](https://github.com/advisories/GHSA-qx2v-qp2m-jg93)) | `>=8.5.10` |
+
+**Fix:**
+- Bumped `drizzle-orm` to `^0.45.2` directly in `apps/web/package.json` and `packages/db/package.json` (it was a top-level dependency in both, not just transitive — straightforward version bump, no breaking API changes hit typecheck/tests/build).
+- Added `overrides` in `pnpm-workspace.yaml` (pnpm 11 moved this out of `package.json`'s `pnpm.overrides`, which is silently ignored — that field was removed) forcing `esbuild: ">=0.24.3"` and `postcss: ">=8.5.10"` across the whole dependency tree, collapsing the vulnerable transitive copies into already-present patched versions (both packages already had a patched instance installed for other consumers — this just eliminates the vulnerable *second* copy rather than introducing a new major version).
+
+**After:** `pnpm audit` → `No known vulnerabilities found`.
+
+**Verification:** full re-run of `pnpm typecheck`, `pnpm exec vitest run` (191/193 passing — the 2 failures are the same pre-existing, unrelated baseline failures noted throughout this session), and `pnpm build` (production build succeeds, including the Tailwind/PostCSS pipeline under the new override) — all clean after the bump + overrides.
+
+## 2. OpenAPI documentation coverage
+
+Cross-referenced every `route.ts` under `apps/web/app/api/v1/**` (which HTTP methods each file exports) against every `registry.registerPath({ method, path, ... })` call in `apps/web/lib/openapi.ts`.
+
+**Before:** two endpoints existed with zero OpenAPI documentation:
+- `GET /api/v1/admin/support` — list all support tickets (admin only)
+- `PATCH /api/v1/admin/support/{id}` — update a ticket's status, or retry its Gitea issue creation (admin only)
+
+Everything else (109 other route/method pairs) was already documented, and there were no stale entries (documented paths with no matching route file).
+
+**Fix:** added `AdminSupportTicketRef` / `UpdateAdminSupportTicketRef` schemas and both `registerPath` entries to `lib/openapi.ts`, next to the existing `admin/reports` entry, matching the response/error shapes actually returned by the two route handlers.
+
+**After:** re-ran the cross-reference — full parity. The only "missing" entry is `GET /api/v1/openapi.json` itself, which doesn't need to self-document.
+
+**Verification:** `pnpm typecheck` and `pnpm exec vitest run` clean after the addition (the new refs slot into the existing Zod-based OpenAPI registry with no schema conflicts).
diff --git a/apps/web/app/(app)/search/page.tsx b/apps/web/app/(app)/search/page.tsx
index e5b9d12..76b8425 100644
--- a/apps/web/app/(app)/search/page.tsx
+++ b/apps/web/app/(app)/search/page.tsx
@@ -1,8 +1,13 @@
+import { headers } from "next/headers";
+import { auth } from "@/lib/auth/server";
import { SearchPageContent } from "@/components/search/search-page-content";
type Params = { searchParams: Promise<{ q?: string; difficulty?: string; dietary?: string }> };
export default async function SearchPage({ searchParams }: Params) {
+ const session = await auth.api.getSession({ headers: await headers() });
+ if (!session) return null;
+
const { q } = await searchParams;
return ;
}
diff --git a/apps/web/app/api/v1/admin/settings/__tests__/route.test.ts b/apps/web/app/api/v1/admin/settings/__tests__/route.test.ts
index 82bc6d7..a3121c8 100644
--- a/apps/web/app/api/v1/admin/settings/__tests__/route.test.ts
+++ b/apps/web/app/api/v1/admin/settings/__tests__/route.test.ts
@@ -1,39 +1,28 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
-import { NextRequest } from "next/server";
+import { NextRequest, NextResponse } from "next/server";
const mockAdminSession = { user: { id: "admin-1", role: "admin" } };
-vi.mock("next/headers", () => ({
- headers: vi.fn().mockResolvedValue(new Headers()),
-}));
-
-vi.mock("@/lib/auth/server", () => ({
- auth: { api: { getSession: vi.fn() } },
+vi.mock("@/lib/api-auth", () => ({
+ requireAdmin: vi.fn(),
}));
vi.mock("@/lib/site-settings", () => ({
setSiteSetting: vi.fn().mockResolvedValue(undefined),
}));
-const { mockSelectChain, mockInsertValues } = vi.hoisted(() => {
- const mockSelectChain = {
- from: vi.fn().mockReturnThis(),
- where: vi.fn().mockResolvedValue([{ role: "admin" }]),
- };
- return { mockSelectChain, mockInsertValues: vi.fn().mockResolvedValue(undefined) };
-});
+const { mockInsertValues } = vi.hoisted(() => ({
+ mockInsertValues: vi.fn().mockResolvedValue(undefined),
+}));
vi.mock("@epicure/db", () => ({
db: {
- select: vi.fn(() => mockSelectChain),
insert: vi.fn(() => ({ values: mockInsertValues })),
},
- users: { id: "id", role: "role" },
auditLogs: {},
- eq: vi.fn((a, b) => ({ a, b, op: "eq" })),
}));
-const { auth } = await import("@/lib/auth/server");
+const { requireAdmin } = await import("@/lib/api-auth");
const { setSiteSetting } = await import("@/lib/site-settings");
import { PUT } from "../route";
@@ -47,21 +36,26 @@ function makeRequest(body: unknown) {
beforeEach(() => {
vi.clearAllMocks();
- vi.mocked(auth.api.getSession).mockResolvedValue(mockAdminSession as never);
- mockSelectChain.where.mockResolvedValue([{ role: "admin" }]);
+ vi.mocked(requireAdmin).mockResolvedValue({ session: mockAdminSession as never, response: null });
});
describe("PUT /api/v1/admin/settings", () => {
it("returns 403 when caller is not an admin", async () => {
- mockSelectChain.where.mockResolvedValue([{ role: "user" }]);
+ vi.mocked(requireAdmin).mockResolvedValue({
+ session: null,
+ response: NextResponse.json({ error: "Forbidden" }, { status: 403 }),
+ } as never);
const res = await PUT(makeRequest({ OPENAI_API_KEY: "sk-1" }));
expect(res.status).toBe(403);
});
- it("returns 403 when there is no session", async () => {
- vi.mocked(auth.api.getSession).mockResolvedValue(null as never);
+ it("returns 401 when there is no session", async () => {
+ vi.mocked(requireAdmin).mockResolvedValue({
+ session: null,
+ response: NextResponse.json({ error: "Unauthorized" }, { status: 401 }),
+ } as never);
const res = await PUT(makeRequest({ OPENAI_API_KEY: "sk-1" }));
- expect(res.status).toBe(403);
+ expect(res.status).toBe(401);
});
it("updates allowed keys and writes an audit log", async () => {
diff --git a/apps/web/app/api/v1/admin/settings/route.ts b/apps/web/app/api/v1/admin/settings/route.ts
index c5b52f2..cc9b0ed 100644
--- a/apps/web/app/api/v1/admin/settings/route.ts
+++ b/apps/web/app/api/v1/admin/settings/route.ts
@@ -1,7 +1,6 @@
import { type NextRequest, NextResponse } from "next/server";
-import { headers } from "next/headers";
-import { auth } from "@/lib/auth/server";
-import { db, users, auditLogs, eq } from "@epicure/db";
+import { db, auditLogs } from "@epicure/db";
+import { requireAdmin } from "@/lib/api-auth";
import { setSiteSetting, type SiteSettingKey } from "@/lib/site-settings";
import { randomUUID } from "crypto";
@@ -28,31 +27,23 @@ const ALLOWED_KEYS: SiteSettingKey[] = [
"GITEA_REPO",
];
-async function requireAdmin() {
- const session = await auth.api.getSession({ headers: await headers() });
- if (!session) return null;
- const [dbUser] = await db.select({ role: users.role }).from(users).where(eq(users.id, session.user.id));
- if (dbUser?.role !== "admin") return null;
- return session;
-}
-
export async function PUT(req: NextRequest) {
- const session = await requireAdmin();
- if (!session) return NextResponse.json({ error: "Forbidden" }, { status: 403 });
+ const { session, response } = await requireAdmin();
+ if (response) return response;
const body = (await req.json()) as Record;
const changed: string[] = [];
for (const [key, value] of Object.entries(body)) {
if (!ALLOWED_KEYS.includes(key as SiteSettingKey)) continue;
- await setSiteSetting(key as SiteSettingKey, value, session.user.id);
+ await setSiteSetting(key as SiteSettingKey, value, session!.user.id);
changed.push(key);
}
if (changed.length > 0) {
await db.insert(auditLogs).values({
id: randomUUID(),
- userId: session.user.id,
+ userId: session!.user.id,
action: "admin.settings.update",
targetType: "site_settings",
metadata: JSON.stringify({ keys: changed }),
diff --git a/apps/web/app/api/v1/ai/adapt/[id]/route.ts b/apps/web/app/api/v1/ai/adapt/[id]/route.ts
index 51904b1..5a0819e 100644
--- a/apps/web/app/api/v1/ai/adapt/[id]/route.ts
+++ b/apps/web/app/api/v1/ai/adapt/[id]/route.ts
@@ -3,11 +3,12 @@ import { z } from "zod";
import { and, eq } from "@epicure/db";
import { db, recipes, recipeIngredients, recipeSteps, recipeVariations } from "@epicure/db";
import { requireSessionOrApiKey } from "@/lib/api-auth";
+import { applyRateLimit } from "@/lib/rate-limit";
import { withAiQuota, resolveAiConfigOrError } from "@/lib/ai/ai-error";
import { adaptRecipe } from "@/lib/ai/features/adapt-recipe";
import { withUserKey } from "@/lib/ai/resolve-user-key";
import { getUserPrivateBio } from "@/lib/ai/user-bio";
-import { checkAndIncrementTierLimit, TierLimitError } from "@/lib/tiers";
+import { checkTierLimitInTransaction, TierLimitError } from "@/lib/tiers";
import { isRecipeUnchanged } from "@/lib/recipe-diff";
const Schema = z.object({
@@ -23,8 +24,11 @@ export async function POST(req: NextRequest, { params }: Params) {
const { session, response } = await requireSessionOrApiKey(req);
if (response) return response;
- const { id } = await params;
const userId = session!.user.id;
+ const limited = await applyRateLimit(`rl:ai:${userId}`, 10, 60);
+ if (limited) return limited;
+
+ const { id } = await params;
const recipe = await db.query.recipes.findFirst({
where: and(eq(recipes.id, id)),
@@ -81,20 +85,12 @@ export async function POST(req: NextRequest, { params }: Params) {
return NextResponse.json({ id: recipe.id, adaptationNotes: adapted.adaptationNotes, unchanged: true });
}
- try {
- await checkAndIncrementTierLimit(userId, session!.user.tier as "free" | "pro" | "family", "recipe");
- } catch (err) {
- if (err instanceof TierLimitError) {
- return NextResponse.json({ error: "Recipe limit reached for your tier" }, { status: 403 });
- }
- throw err;
- }
-
const newId = crypto.randomUUID();
const now = new Date();
try {
await db.transaction(async (tx) => {
+ await checkTierLimitInTransaction(tx, userId, session!.user.tier as "free" | "pro" | "family", "recipe");
await tx.insert(recipes).values({
id: newId,
authorId: userId,
@@ -147,7 +143,10 @@ export async function POST(req: NextRequest, { params }: Params) {
createdAt: now,
});
});
- } catch {
+ } catch (err) {
+ if (err instanceof TierLimitError) {
+ return NextResponse.json({ error: "Recipe limit reached for your tier" }, { status: 403 });
+ }
return NextResponse.json({ error: "Failed to save the adapted recipe. Please try again." }, { status: 500 });
}
diff --git a/apps/web/app/api/v1/ai/batch-cook/generate/route.ts b/apps/web/app/api/v1/ai/batch-cook/generate/route.ts
index 66fb712..61cdb75 100644
--- a/apps/web/app/api/v1/ai/batch-cook/generate/route.ts
+++ b/apps/web/app/api/v1/ai/batch-cook/generate/route.ts
@@ -8,6 +8,7 @@ import { withAiQuota, resolveAiConfigOrError } from "@/lib/ai/ai-error";
import { generateBatchCook } from "@/lib/ai/features/generate-batch-cook";
import { getUserPrivateBio } from "@/lib/ai/user-bio";
import { parseQuantity } from "@/lib/parse-quantity";
+import { checkTierLimitInTransaction, TierLimitError } from "@/lib/tiers";
const Schema = z.object({
dinners: z.number().int().min(0).max(6).default(4),
@@ -62,7 +63,9 @@ export async function POST(req: NextRequest) {
const recipeId = crypto.randomUUID();
- await db.transaction(async (tx) => {
+ try {
+ await db.transaction(async (tx) => {
+ await checkTierLimitInTransaction(tx, userId, session!.user.tier as "free" | "pro" | "family", "recipe");
await tx.insert(recipes).values({
id: recipeId,
authorId: userId,
@@ -117,7 +120,13 @@ export async function POST(req: NextRequest) {
}))
);
}
- });
+ });
+ } catch (err) {
+ if (err instanceof TierLimitError) {
+ return NextResponse.json({ error: "Recipe limit reached for your tier" }, { status: 403 });
+ }
+ throw err;
+ }
return NextResponse.json({ id: recipeId });
}
diff --git a/apps/web/app/api/v1/ai/drinks/[id]/route.ts b/apps/web/app/api/v1/ai/drinks/[id]/route.ts
index afc355b..006a7bc 100644
--- a/apps/web/app/api/v1/ai/drinks/[id]/route.ts
+++ b/apps/web/app/api/v1/ai/drinks/[id]/route.ts
@@ -3,6 +3,7 @@ import { z } from "zod";
import { and, eq } from "@epicure/db";
import { db, recipes } from "@epicure/db";
import { requireSessionOrApiKey } from "@/lib/api-auth";
+import { applyRateLimit } from "@/lib/rate-limit";
import { withAiQuota, resolveAiConfigOrError } from "@/lib/ai/ai-error";
import { suggestDrinks } from "@/lib/ai/features/suggest-drinks";
import { withUserKey } from "@/lib/ai/resolve-user-key";
@@ -21,6 +22,9 @@ export async function POST(req: NextRequest, { params }: Params) {
const { session, response } = await requireSessionOrApiKey(req);
if (response) return response;
+ const limited = await applyRateLimit(`rl:ai:${session!.user.id}`, 10, 60);
+ if (limited) return limited;
+
try {
await requireFeatureEnabled(session!.user.id, "drink_pairing");
} catch (err) {
diff --git a/apps/web/app/api/v1/ai/generate-from-idea/route.ts b/apps/web/app/api/v1/ai/generate-from-idea/route.ts
index fa5db63..197d16b 100644
--- a/apps/web/app/api/v1/ai/generate-from-idea/route.ts
+++ b/apps/web/app/api/v1/ai/generate-from-idea/route.ts
@@ -8,6 +8,7 @@ import { getUserPrivateBio } from "@/lib/ai/user-bio";
import { withUserKey } from "@/lib/ai/resolve-user-key";
import { db, recipes, recipeIngredients, recipeSteps } from "@epicure/db";
import { parseQuantity } from "@/lib/parse-quantity";
+import { checkTierLimitInTransaction, TierLimitError } from "@/lib/tiers";
const Schema = z.object({
title: z.string().min(1).max(200),
@@ -51,47 +52,58 @@ export async function POST(req: NextRequest) {
const recipeId = crypto.randomUUID();
- await db.insert(recipes).values({
- id: recipeId,
- authorId: session!.user.id,
- title: recipe.title,
- description: recipe.description ?? null,
- baseServings: recipe.baseServings,
- recipeType: recipe.recipeType,
- prepMins: recipe.prepMins ?? null,
- cookMins: recipe.cookMins ?? null,
- difficulty: recipe.difficulty ?? null,
- visibility: "private",
- aiGenerated: true,
- language: locale,
- dietaryTags: recipe.dietaryTags ?? {},
- tags: [],
- });
+ try {
+ await db.transaction(async (tx) => {
+ await checkTierLimitInTransaction(tx, session!.user.id, session!.user.tier as "free" | "pro" | "family", "recipe");
- if (recipe.ingredients?.length) {
- await db.insert(recipeIngredients).values(
- recipe.ingredients.map((ing, i) => ({
- id: crypto.randomUUID(),
- recipeId,
- rawName: ing.rawName,
- quantity: parseQuantity(ing.quantity) ?? null,
- unit: ing.unit ?? null,
- note: ing.note ?? null,
- order: i,
- }))
- );
- }
+ await tx.insert(recipes).values({
+ id: recipeId,
+ authorId: session!.user.id,
+ title: recipe.title,
+ description: recipe.description ?? null,
+ baseServings: recipe.baseServings,
+ recipeType: recipe.recipeType,
+ prepMins: recipe.prepMins ?? null,
+ cookMins: recipe.cookMins ?? null,
+ difficulty: recipe.difficulty ?? null,
+ visibility: "private",
+ aiGenerated: true,
+ language: locale,
+ dietaryTags: recipe.dietaryTags ?? {},
+ tags: [],
+ });
- if (recipe.steps?.length) {
- await db.insert(recipeSteps).values(
- recipe.steps.map((step, i) => ({
- id: crypto.randomUUID(),
- recipeId,
- instruction: step.instruction,
- timerSeconds: step.timerSeconds ?? null,
- order: i,
- }))
- );
+ if (recipe.ingredients?.length) {
+ await tx.insert(recipeIngredients).values(
+ recipe.ingredients.map((ing, i) => ({
+ id: crypto.randomUUID(),
+ recipeId,
+ rawName: ing.rawName,
+ quantity: parseQuantity(ing.quantity) ?? null,
+ unit: ing.unit ?? null,
+ note: ing.note ?? null,
+ order: i,
+ }))
+ );
+ }
+
+ if (recipe.steps?.length) {
+ await tx.insert(recipeSteps).values(
+ recipe.steps.map((step, i) => ({
+ id: crypto.randomUUID(),
+ recipeId,
+ instruction: step.instruction,
+ timerSeconds: step.timerSeconds ?? null,
+ order: i,
+ }))
+ );
+ }
+ });
+ } catch (err) {
+ if (err instanceof TierLimitError) {
+ return NextResponse.json({ error: "Recipe limit reached for your tier" }, { status: 403 });
+ }
+ throw err;
}
return NextResponse.json({ id: recipeId });
diff --git a/apps/web/app/api/v1/ai/generate-meal/route.ts b/apps/web/app/api/v1/ai/generate-meal/route.ts
index 34f8634..8656e14 100644
--- a/apps/web/app/api/v1/ai/generate-meal/route.ts
+++ b/apps/web/app/api/v1/ai/generate-meal/route.ts
@@ -5,7 +5,7 @@ import { requireSessionOrApiKey } from "@/lib/api-auth";
import { applyRateLimit } from "@/lib/rate-limit";
import { getDefaultProviderWithKey } from "@/lib/ai/resolve-user-key";
import { withAiQuota, resolveAiConfigOrError } from "@/lib/ai/ai-error";
-import { checkAndIncrementTierLimit, TierLimitError } from "@/lib/tiers";
+import { checkTierLimitInTransaction, TierLimitError } from "@/lib/tiers";
import { generateMeal, MEAL_COURSES } from "@/lib/ai/features/generate-meal";
import { getUserPrivateBio } from "@/lib/ai/user-bio";
import { getMessages } from "@/lib/i18n/server";
@@ -59,20 +59,13 @@ export async function POST(req: NextRequest) {
if (!result.ok) return result.response;
const meal = result.data;
- // Each recipe in the meal creates a real recipe row — check the recipe
- // limit covers all of them before inserting anything.
- try {
- await checkAndIncrementTierLimit(userId, tier, "recipe", meal.recipes.length);
- } catch (err) {
- if (err instanceof TierLimitError) {
- return NextResponse.json({ error: "Recipe limit reached for your tier" }, { status: 403 });
- }
- throw err;
- }
-
const created: Array<{ id: string; title: string; course: string }> = [];
- await db.transaction(async (tx) => {
+ try {
+ await db.transaction(async (tx) => {
+ // Each recipe in the meal creates a real recipe row — check the recipe
+ // limit covers all of them before inserting anything.
+ await checkTierLimitInTransaction(tx, userId, tier, "recipe", meal.recipes.length);
for (const recipe of meal.recipes) {
const recipeId = crypto.randomUUID();
await tx.insert(recipes).values({
@@ -122,7 +115,13 @@ export async function POST(req: NextRequest) {
created.push({ id: recipeId, title: recipe.title, course: recipe.course });
}
- });
+ });
+ } catch (err) {
+ if (err instanceof TierLimitError) {
+ return NextResponse.json({ error: "Recipe limit reached for your tier" }, { status: 403 });
+ }
+ throw err;
+ }
return NextResponse.json({ collectionId, recipes: created });
}
diff --git a/apps/web/app/api/v1/ai/import-photo/route.ts b/apps/web/app/api/v1/ai/import-photo/route.ts
index 313687c..7d4f6e8 100644
--- a/apps/web/app/api/v1/ai/import-photo/route.ts
+++ b/apps/web/app/api/v1/ai/import-photo/route.ts
@@ -6,6 +6,7 @@ import { applyRateLimit } from "@/lib/rate-limit";
import { withAiQuota, resolveAiConfigOrError } from "@/lib/ai/ai-error";
import { importFromPhoto } from "@/lib/ai/features/import-photo";
import { getModelConfigForUseCase } from "@/lib/ai/resolve-user-key";
+import { checkTierLimitInTransaction, TierLimitError } from "@/lib/tiers";
const Schema = z.object({
imageBase64: z.string().max(14_000_000),
@@ -56,7 +57,9 @@ export async function POST(req: NextRequest) {
const newRecipeId = crypto.randomUUID();
const now = new Date();
- await db.transaction(async (tx) => {
+ try {
+ await db.transaction(async (tx) => {
+ await checkTierLimitInTransaction(tx, userId, session!.user.tier as "free" | "pro" | "family", "recipe");
await tx.insert(recipes).values({
id: newRecipeId,
authorId: userId,
@@ -105,7 +108,13 @@ export async function POST(req: NextRequest) {
}))
);
}
- });
+ });
+ } catch (err) {
+ if (err instanceof TierLimitError) {
+ return NextResponse.json({ error: "Recipe limit reached for your tier" }, { status: 403 });
+ }
+ throw err;
+ }
return NextResponse.json({ id: newRecipeId });
}
diff --git a/apps/web/app/api/v1/ai/meal-plan/generate/route.ts b/apps/web/app/api/v1/ai/meal-plan/generate/route.ts
index 67edf40..4e9085e 100644
--- a/apps/web/app/api/v1/ai/meal-plan/generate/route.ts
+++ b/apps/web/app/api/v1/ai/meal-plan/generate/route.ts
@@ -5,7 +5,7 @@ import { requireSessionOrApiKey } from "@/lib/api-auth";
import { applyRateLimit } from "@/lib/rate-limit";
import { getDefaultProviderWithKey } from "@/lib/ai/resolve-user-key";
import { withAiQuota, resolveAiConfigOrError } from "@/lib/ai/ai-error";
-import { checkAndIncrementTierLimit, TierLimitError } from "@/lib/tiers";
+import { checkTierLimitInTransaction, TierLimitError } from "@/lib/tiers";
import { generateMealPlan } from "@/lib/ai/features/generate-meal-plan";
import { getUserPrivateBio } from "@/lib/ai/user-bio";
@@ -93,17 +93,6 @@ export async function POST(req: NextRequest) {
if (!result.ok) return result.response;
const plan = result.data;
- // Each plan entry creates a draft recipe — check the recipe limit covers
- // all of them before inserting anything.
- try {
- await checkAndIncrementTierLimit(userId, session!.user.tier as "free" | "pro" | "family", "recipe", plan.entries.length);
- } catch (err) {
- if (err instanceof TierLimitError) {
- return NextResponse.json({ error: "Recipe limit reached for your tier" }, { status: 403 });
- }
- throw err;
- }
-
// Ensure meal plan row exists for the week
let mealPlan = await db.query.mealPlans.findFirst({
where: and(eq(mealPlans.userId, userId), eq(mealPlans.weekStart, parsed.data.weekStart)),
@@ -117,7 +106,11 @@ export async function POST(req: NextRequest) {
const createdEntries: Array<{ id: string; day: string; mealType: string; recipeId: string; recipeTitle: string }> = [];
- await db.transaction(async (tx) => {
+ try {
+ await db.transaction(async (tx) => {
+ // Each plan entry creates a draft recipe — check the recipe limit covers
+ // all of them before inserting anything.
+ await checkTierLimitInTransaction(tx, userId, session!.user.tier as "free" | "pro" | "family", "recipe", plan.entries.length);
for (const entry of plan.entries) {
// Create draft recipe
const recipeId = crypto.randomUUID();
@@ -184,7 +177,13 @@ export async function POST(req: NextRequest) {
createdEntries.push({ id: entryId, day: entry.day, mealType: entry.mealType, recipeId, recipeTitle: entry.recipe.title });
}
- });
+ });
+ } catch (err) {
+ if (err instanceof TierLimitError) {
+ return NextResponse.json({ error: "Recipe limit reached for your tier" }, { status: 403 });
+ }
+ throw err;
+ }
return NextResponse.json({ weekStart: parsed.data.weekStart, entries: createdEntries });
}
diff --git a/apps/web/app/api/v1/ai/pairings/[id]/route.ts b/apps/web/app/api/v1/ai/pairings/[id]/route.ts
index 9844d34..aaf64f9 100644
--- a/apps/web/app/api/v1/ai/pairings/[id]/route.ts
+++ b/apps/web/app/api/v1/ai/pairings/[id]/route.ts
@@ -3,6 +3,7 @@ import { z } from "zod";
import { and, eq } from "@epicure/db";
import { db, recipes } from "@epicure/db";
import { requireSessionOrApiKey } from "@/lib/api-auth";
+import { applyRateLimit } from "@/lib/rate-limit";
import { withAiQuota, resolveAiConfigOrError } from "@/lib/ai/ai-error";
import { suggestPairings } from "@/lib/ai/features/suggest-pairings";
import { withUserKey } from "@/lib/ai/resolve-user-key";
@@ -21,6 +22,9 @@ export async function POST(req: NextRequest, { params }: Params) {
const { session, response } = await requireSessionOrApiKey(req);
if (response) return response;
+ const limited = await applyRateLimit(`rl:ai:${session!.user.id}`, 10, 60);
+ if (limited) return limited;
+
try {
await requireFeatureEnabled(session!.user.id, "meal_pairing");
} catch (err) {
diff --git a/apps/web/app/api/v1/ai/translate/[id]/route.ts b/apps/web/app/api/v1/ai/translate/[id]/route.ts
index d498e49..32fac63 100644
--- a/apps/web/app/api/v1/ai/translate/[id]/route.ts
+++ b/apps/web/app/api/v1/ai/translate/[id]/route.ts
@@ -3,9 +3,11 @@ import { z } from "zod";
import { and, eq } from "@epicure/db";
import { db, recipes, recipeIngredients, recipeSteps } from "@epicure/db";
import { requireSessionOrApiKey } from "@/lib/api-auth";
+import { applyRateLimit } from "@/lib/rate-limit";
import { withAiQuota, resolveAiConfigOrError } from "@/lib/ai/ai-error";
import { translateRecipe } from "@/lib/ai/features/translate-recipe";
import { withUserKey } from "@/lib/ai/resolve-user-key";
+import { checkTierLimitInTransaction, TierLimitError } from "@/lib/tiers";
const Schema = z.object({
targetLanguage: z.string().min(2).max(50),
@@ -19,6 +21,9 @@ export async function POST(req: NextRequest, { params }: Params) {
const { session, response } = await requireSessionOrApiKey(req);
if (response) return response;
+ const limited = await applyRateLimit(`rl:ai:${session!.user.id}`, 10, 60);
+ if (limited) return limited;
+
const { id } = await params;
const recipe = await db.query.recipes.findFirst({
where: and(eq(recipes.id, id), eq(recipes.authorId, session!.user.id)),
@@ -61,7 +66,9 @@ export async function POST(req: NextRequest, { params }: Params) {
const newId = crypto.randomUUID();
const now = new Date();
- await db.transaction(async (tx) => {
+ try {
+ await db.transaction(async (tx) => {
+ await checkTierLimitInTransaction(tx, session!.user.id, session!.user.tier as "free" | "pro" | "family", "recipe");
await tx.insert(recipes).values({
id: newId,
authorId: session!.user.id,
@@ -103,7 +110,13 @@ export async function POST(req: NextRequest, { params }: Params) {
}))
);
}
- });
+ });
+ } catch (err) {
+ if (err instanceof TierLimitError) {
+ return NextResponse.json({ error: "Recipe limit reached for your tier" }, { status: 403 });
+ }
+ throw err;
+ }
return NextResponse.json({ id: newId });
}
diff --git a/apps/web/app/api/v1/ai/variations/[id]/route.ts b/apps/web/app/api/v1/ai/variations/[id]/route.ts
index 00189a9..fa2f377 100644
--- a/apps/web/app/api/v1/ai/variations/[id]/route.ts
+++ b/apps/web/app/api/v1/ai/variations/[id]/route.ts
@@ -3,6 +3,7 @@ import { z } from "zod";
import { and, eq } from "@epicure/db";
import { db, recipes } from "@epicure/db";
import { requireSessionOrApiKey } from "@/lib/api-auth";
+import { applyRateLimit } from "@/lib/rate-limit";
import { withAiQuota, resolveAiConfigOrError } from "@/lib/ai/ai-error";
import { suggestVariations } from "@/lib/ai/features/suggest-variations";
import { withUserKey } from "@/lib/ai/resolve-user-key";
@@ -22,6 +23,9 @@ export async function POST(req: NextRequest, { params }: Params) {
const { session, response } = await requireSessionOrApiKey(req);
if (response) return response;
+ const limited = await applyRateLimit(`rl:ai:${session!.user.id}`, 10, 60);
+ if (limited) return limited;
+
try {
await requireFeatureEnabled(session!.user.id, "recipe_variations");
} catch (err) {
diff --git a/apps/web/app/api/v1/recipes/[id]/fork/route.ts b/apps/web/app/api/v1/recipes/[id]/fork/route.ts
index 7d79799..dd5655f 100644
--- a/apps/web/app/api/v1/recipes/[id]/fork/route.ts
+++ b/apps/web/app/api/v1/recipes/[id]/fork/route.ts
@@ -2,7 +2,7 @@ import { NextRequest, NextResponse } from "next/server";
import { db, recipes, recipeIngredients, recipeSteps, recipeVariations } from "@epicure/db";
import { eq, and, or, inArray } from "@epicure/db";
import { requireSessionOrApiKey } from "@/lib/api-auth";
-import { checkAndIncrementTierLimit, TierLimitError } from "@/lib/tiers";
+import { checkTierLimitInTransaction, TierLimitError } from "@/lib/tiers";
type Params = { params: Promise<{ id: string }> };
@@ -23,8 +23,65 @@ export async function POST(req: NextRequest, { params }: Params) {
});
if (!source) return NextResponse.json({ error: "Not found" }, { status: 404 });
+ const newId = crypto.randomUUID();
+ const now = new Date();
+
try {
- await checkAndIncrementTierLimit(session!.user.id, session!.user.tier as "free" | "pro" | "family", "recipe");
+ await db.transaction(async (tx) => {
+ await checkTierLimitInTransaction(tx, session!.user.id, session!.user.tier as "free" | "pro" | "family", "recipe");
+ await tx.insert(recipes).values({
+ id: newId,
+ authorId: session!.user.id,
+ title: source.title,
+ description: source.description,
+ baseServings: source.baseServings,
+ visibility: "private",
+ difficulty: source.difficulty,
+ prepMins: source.prepMins,
+ cookMins: source.cookMins,
+ tags: source.tags,
+ dietaryTags: source.dietaryTags ?? {},
+ aiGenerated: false,
+ language: source.language,
+ createdAt: now,
+ updatedAt: now,
+ });
+
+ if (source.ingredients.length > 0) {
+ await tx.insert(recipeIngredients).values(
+ source.ingredients.map((ing) => ({
+ id: crypto.randomUUID(),
+ recipeId: newId,
+ rawName: ing.rawName,
+ quantity: ing.quantity,
+ unit: ing.unit,
+ note: ing.note,
+ order: ing.order,
+ }))
+ );
+ }
+
+ if (source.steps.length > 0) {
+ await tx.insert(recipeSteps).values(
+ source.steps.map((step) => ({
+ id: crypto.randomUUID(),
+ recipeId: newId,
+ instruction: step.instruction,
+ timerSeconds: step.timerSeconds,
+ order: step.order,
+ }))
+ );
+ }
+
+ await tx.insert(recipeVariations).values({
+ id: crypto.randomUUID(),
+ parentRecipeId: source.id,
+ childRecipeId: newId,
+ description: null,
+ aiGenerated: false,
+ createdAt: now,
+ });
+ });
} catch (err) {
if (err instanceof TierLimitError) {
return NextResponse.json({ error: "Recipe limit reached for your tier" }, { status: 403 });
@@ -32,63 +89,5 @@ export async function POST(req: NextRequest, { params }: Params) {
throw err;
}
- const newId = crypto.randomUUID();
- const now = new Date();
-
- await db.transaction(async (tx) => {
- await tx.insert(recipes).values({
- id: newId,
- authorId: session!.user.id,
- title: source.title,
- description: source.description,
- baseServings: source.baseServings,
- visibility: "private",
- difficulty: source.difficulty,
- prepMins: source.prepMins,
- cookMins: source.cookMins,
- tags: source.tags,
- dietaryTags: source.dietaryTags ?? {},
- aiGenerated: false,
- language: source.language,
- createdAt: now,
- updatedAt: now,
- });
-
- if (source.ingredients.length > 0) {
- await tx.insert(recipeIngredients).values(
- source.ingredients.map((ing) => ({
- id: crypto.randomUUID(),
- recipeId: newId,
- rawName: ing.rawName,
- quantity: ing.quantity,
- unit: ing.unit,
- note: ing.note,
- order: ing.order,
- }))
- );
- }
-
- if (source.steps.length > 0) {
- await tx.insert(recipeSteps).values(
- source.steps.map((step) => ({
- id: crypto.randomUUID(),
- recipeId: newId,
- instruction: step.instruction,
- timerSeconds: step.timerSeconds,
- order: step.order,
- }))
- );
- }
-
- await tx.insert(recipeVariations).values({
- id: crypto.randomUUID(),
- parentRecipeId: source.id,
- childRecipeId: newId,
- description: null,
- aiGenerated: false,
- createdAt: now,
- });
- });
-
return NextResponse.json({ id: newId }, { status: 201 });
}
diff --git a/apps/web/app/api/v1/recipes/[id]/rate/route.ts b/apps/web/app/api/v1/recipes/[id]/rate/route.ts
index 950a68c..5778985 100644
--- a/apps/web/app/api/v1/recipes/[id]/rate/route.ts
+++ b/apps/web/app/api/v1/recipes/[id]/rate/route.ts
@@ -4,6 +4,7 @@ import { db, recipes, ratings, eq, and } from "@epicure/db";
import { requireSessionOrApiKey } from "@/lib/api-auth";
import { createNotification } from "@/lib/notifications";
import { isOwnedReviewPhotoKey } from "@/lib/storage";
+import { checkTierLimitInTransaction, TierLimitError } from "@/lib/tiers";
const Schema = z.object({
score: z.number().int().min(1).max(5),
@@ -39,28 +40,49 @@ export async function POST(req: NextRequest, { params }: Params) {
where: and(eq(ratings.recipeId, id), eq(ratings.userId, session!.user.id)),
});
- if (existing) {
- await db.update(ratings)
- .set({
+ const newPhotoSizeMb = parsed.data.photoKey ? parsed.data.photoSizeMb : 0;
+ const photoSizeDeltaMb = newPhotoSizeMb - (existing?.photoSizeMb ?? 0);
+
+ try {
+ if (existing) {
+ await db.transaction(async (tx) => {
+ if (photoSizeDeltaMb > 0) {
+ await checkTierLimitInTransaction(tx, session!.user.id, session!.user.tier as "free" | "pro" | "family", "storage", photoSizeDeltaMb);
+ }
+ await tx.update(ratings)
+ .set({
+ score: parsed.data.score,
+ reviewText: parsed.data.reviewText,
+ photoKey: parsed.data.photoKey,
+ photoSizeMb: newPhotoSizeMb,
+ updatedAt: new Date(),
+ })
+ .where(eq(ratings.id, existing.id));
+ });
+ return NextResponse.json({ updated: true });
+ }
+
+ await db.transaction(async (tx) => {
+ if (photoSizeDeltaMb > 0) {
+ await checkTierLimitInTransaction(tx, session!.user.id, session!.user.tier as "free" | "pro" | "family", "storage", photoSizeDeltaMb);
+ }
+ await tx.insert(ratings).values({
+ id: crypto.randomUUID(),
+ recipeId: id,
+ userId: session!.user.id,
score: parsed.data.score,
reviewText: parsed.data.reviewText,
photoKey: parsed.data.photoKey,
- photoSizeMb: parsed.data.photoKey ? parsed.data.photoSizeMb : 0,
- updatedAt: new Date(),
- })
- .where(eq(ratings.id, existing.id));
- return NextResponse.json({ updated: true });
+ photoSizeMb: newPhotoSizeMb,
+ });
+ });
+ } catch (err) {
+ if (err instanceof TierLimitError) {
+ return NextResponse.json({ error: "Storage limit reached for your tier" }, { status: 403 });
+ }
+ throw err;
}
- await db.insert(ratings).values({
- id: crypto.randomUUID(),
- recipeId: id,
- userId: session!.user.id,
- score: parsed.data.score,
- reviewText: parsed.data.reviewText,
- photoKey: parsed.data.photoKey,
- photoSizeMb: parsed.data.photoKey ? parsed.data.photoSizeMb : 0,
- });
void createNotification({ userId: recipe.authorId, type: "rating", actorId: session!.user.id, recipeId: id, score: parsed.data.score });
return NextResponse.json({ created: true }, { status: 201 });
}
diff --git a/apps/web/app/api/v1/recipes/[id]/route.ts b/apps/web/app/api/v1/recipes/[id]/route.ts
index f9f2a39..12fb073 100644
--- a/apps/web/app/api/v1/recipes/[id]/route.ts
+++ b/apps/web/app/api/v1/recipes/[id]/route.ts
@@ -3,6 +3,7 @@ import { db, recipes, recipeIngredients, recipeSteps, recipePhotos, recipeBatchD
import { eq, and, max, isNotNull } from "@epicure/db";
import { z } from "zod";
import { requireSessionOrApiKey } from "@/lib/api-auth";
+import { checkTierLimitInTransaction, TierLimitError } from "@/lib/tiers";
import { deleteObject, isOwnedRecipePhotoKey } from "@/lib/storage";
import { dispatchWebhook } from "@/lib/webhooks";
import { parseQuantity } from "@/lib/parse-quantity";
@@ -124,7 +125,15 @@ export async function PUT(req: NextRequest, { params }: Params) {
return NextResponse.json({ error: "Validation error", issues: [{ path: ["photos"], message: "Photo key not issued for this recipe" }] }, { status: 400 });
}
- await db.transaction(async (tx) => {
+ const photosSizeDeltaMb = data.photos !== undefined
+ ? data.photos.reduce((sum, p) => sum + p.sizeMb, 0) - existing.photos.reduce((sum, p) => sum + p.sizeMb, 0)
+ : 0;
+
+ try {
+ await db.transaction(async (tx) => {
+ if (photosSizeDeltaMb > 0) {
+ await checkTierLimitInTransaction(tx, session!.user.id, session!.user.tier as "free" | "pro" | "family", "storage", photosSizeDeltaMb);
+ }
// Create a snapshot of the current state before updating
const [maxVersionRow] = await tx
.select({ v: max(recipeSnapshots.version) })
@@ -248,7 +257,13 @@ export async function PUT(req: NextRequest, { params }: Params) {
);
}
}
- });
+ });
+ } catch (err) {
+ if (err instanceof TierLimitError) {
+ return NextResponse.json({ error: "Storage limit reached for your tier" }, { status: 403 });
+ }
+ throw err;
+ }
if (data.photos !== undefined) {
const newKeys = new Set(data.photos.map((p) => p.key));
diff --git a/apps/web/app/api/v1/recipes/__tests__/route.test.ts b/apps/web/app/api/v1/recipes/__tests__/route.test.ts
index 2f5af56..b9388cf 100644
--- a/apps/web/app/api/v1/recipes/__tests__/route.test.ts
+++ b/apps/web/app/api/v1/recipes/__tests__/route.test.ts
@@ -12,8 +12,7 @@ vi.mock("@/lib/api-auth", () => ({
}));
vi.mock("@/lib/tiers", () => ({
- checkAndIncrementTierLimit: vi.fn(),
- incrementUsage: vi.fn(),
+ checkTierLimitInTransaction: vi.fn(),
TierLimitError: class TierLimitError extends Error {},
}));
@@ -134,9 +133,8 @@ describe("POST /api/v1/recipes", () => {
});
it("returns 403 when tier limit reached", async () => {
- const { checkAndIncrementTierLimit } = await import("@/lib/tiers");
- const { TierLimitError } = await import("@/lib/tiers");
- vi.mocked(checkAndIncrementTierLimit).mockRejectedValue(new TierLimitError("recipe", "free"));
+ const { checkTierLimitInTransaction, TierLimitError } = await import("@/lib/tiers");
+ vi.mocked(checkTierLimitInTransaction).mockRejectedValue(new TierLimitError("recipe", "free"));
const res = await POST(makeRequest("POST", validRecipe));
expect(res.status).toBe(403);
diff --git a/apps/web/app/api/v1/recipes/route.ts b/apps/web/app/api/v1/recipes/route.ts
index ef14845..ebb1986 100644
--- a/apps/web/app/api/v1/recipes/route.ts
+++ b/apps/web/app/api/v1/recipes/route.ts
@@ -4,7 +4,7 @@ import { eq, desc, and } from "@epicure/db";
import { z } from "zod";
import { requireSessionOrApiKey } from "@/lib/api-auth";
import { isOwnedRecipePhotoKey } from "@/lib/storage";
-import { checkAndIncrementTierLimit, TierLimitError } from "@/lib/tiers";
+import { checkTierLimitInTransaction, TierLimitError } from "@/lib/tiers";
import { dispatchWebhook } from "@/lib/webhooks";
import { parseQuantity } from "@/lib/parse-quantity";
import { extractIngredientQuantity } from "@/lib/extract-ingredient-quantity";
@@ -119,16 +119,14 @@ export async function POST(req: NextRequest) {
return NextResponse.json({ error: "Validation error", issues: [{ path: ["photos"], message: "Photo key not issued for this recipe" }] }, { status: 400 });
}
- try {
- await checkAndIncrementTierLimit(session!.user.id, session!.user.tier as "free" | "pro" | "family", "recipe");
- } catch (err) {
- if (err instanceof TierLimitError) {
- return NextResponse.json({ error: "Recipe limit reached for your tier" }, { status: 403 });
- }
- throw err;
- }
+ const photosSizeMb = data.photos.reduce((sum, p) => sum + p.sizeMb, 0);
- await db.transaction(async (tx) => {
+ try {
+ await db.transaction(async (tx) => {
+ await checkTierLimitInTransaction(tx, session!.user.id, session!.user.tier as "free" | "pro" | "family", "recipe");
+ if (photosSizeMb > 0) {
+ await checkTierLimitInTransaction(tx, session!.user.id, session!.user.tier as "free" | "pro" | "family", "storage", photosSizeMb);
+ }
await tx.insert(recipes).values({
id,
authorId: session!.user.id,
@@ -209,7 +207,13 @@ export async function POST(req: NextRequest) {
}))
);
}
- });
+ });
+ } catch (err) {
+ if (err instanceof TierLimitError) {
+ return NextResponse.json({ error: `${err.limit === "storage" ? "Storage" : "Recipe"} limit reached for your tier` }, { status: 403 });
+ }
+ throw err;
+ }
const recipe = await db.query.recipes.findFirst({ where: eq(recipes.id, id) });
void dispatchWebhook(session!.user.id, "recipe.created", { id, title: data.title });
diff --git a/apps/web/app/api/v1/users/me/route.ts b/apps/web/app/api/v1/users/me/route.ts
index 41ff8dd..1a675e5 100644
--- a/apps/web/app/api/v1/users/me/route.ts
+++ b/apps/web/app/api/v1/users/me/route.ts
@@ -6,6 +6,7 @@ import { z } from "zod";
import { gravatarUrl } from "@/lib/gravatar";
import { USERNAME_PATTERN, isUsernameTaken } from "@/lib/username";
import { isOwnedAvatarKey, getPublicUrl } from "@/lib/storage";
+import { checkTierLimitInTransaction, TierLimitError } from "@/lib/tiers";
const PatchSchema = z.object({
name: z.string().min(1).max(100).optional(),
@@ -52,6 +53,7 @@ export async function PATCH(req: Request) {
}
}
+ let avatarSizeDeltaMb = 0;
if (avatarKey !== undefined) {
if (avatarKey === null) {
const gravatarOptedIn = useGravatar ?? (await getUseGravatar(session.user.id));
@@ -62,13 +64,28 @@ export async function PATCH(req: Request) {
if (!isOwnedAvatarKey(avatarKey, session.user.id)) {
return NextResponse.json({ error: "Invalid avatar key" }, { status: 400 });
}
+ const currentAvatarSizeMb = await getAvatarSizeMb(session.user.id);
+ avatarSizeDeltaMb = avatarSizeMb - currentAvatarSizeMb;
updates.avatarUrl = getPublicUrl(avatarKey);
updates.hasCustomAvatar = true;
updates.avatarSizeMb = avatarSizeMb;
}
}
- await db.update(users).set(updates).where(eq(users.id, session.user.id));
+ try {
+ await db.transaction(async (tx) => {
+ if (avatarSizeDeltaMb > 0) {
+ await checkTierLimitInTransaction(tx, session.user.id, session.user.tier as "free" | "pro" | "family", "storage", avatarSizeDeltaMb);
+ }
+ await tx.update(users).set(updates).where(eq(users.id, session.user.id));
+ });
+ } catch (err) {
+ if (err instanceof TierLimitError) {
+ return NextResponse.json({ error: "Storage limit reached for your tier" }, { status: 403 });
+ }
+ throw err;
+ }
+
return NextResponse.json({ ok: true, avatarUrl: updates.avatarUrl });
}
@@ -81,3 +98,8 @@ async function getUseGravatar(userId: string): Promise {
const row = await db.query.users.findFirst({ where: eq(users.id, userId), columns: { useGravatar: true } });
return row?.useGravatar ?? false;
}
+
+async function getAvatarSizeMb(userId: string): Promise {
+ const row = await db.query.users.findFirst({ where: eq(users.id, userId), columns: { avatarSizeMb: true } });
+ return row?.avatarSizeMb ?? 0;
+}
diff --git a/apps/web/lib/changelog.ts b/apps/web/lib/changelog.ts
index 75bec71..0ecfe85 100644
--- a/apps/web/lib/changelog.ts
+++ b/apps/web/lib/changelog.ts
@@ -1,5 +1,5 @@
// Mirrors CHANGELOG.md at the repo root — update both together.
-export const APP_VERSION = "0.59.0";
+export const APP_VERSION = "0.60.0";
export type ChangelogEntry = {
version: string;
@@ -11,6 +11,21 @@ export type ChangelogEntry = {
};
export const CHANGELOG: ChangelogEntry[] = [
+ {
+ version: "0.60.0",
+ date: "2026-07-20 22:15",
+ security: [
+ "Closed a race in recipe/storage tier-limit checks — two concurrent requests near the cap could both pass a live count check and both write, exceeding the lifetime limit. Now locked per-user inside the same transaction as the write.",
+ "Fixed four AI recipe-creation routes (photo import, idea generation, batch-cook, translate-to-new-draft) that had no recipe-limit check at all, letting any tier create unlimited recipes through them.",
+ "Added missing per-user rate limits to 5 AI endpoints (adapt, drinks, pairings, translate, variations).",
+ "Search page now checks for a session server-side, matching every other page (defense-in-depth — the underlying API was already public by design and the edge proxy already blocked unauthenticated access).",
+ "Upgraded drizzle-orm to fix a SQL-identifier-escaping vulnerability, and overrode two transitive dependencies (esbuild, postcss) with known CVEs — pnpm audit is now clean.",
+ ],
+ fixed: [
+ "Admin settings endpoint now uses the shared admin-auth check instead of a local duplicate.",
+ "Documented two admin support-ticket endpoints that were missing from the OpenAPI spec.",
+ ],
+ },
{
version: "0.59.0",
date: "2026-07-20 21:15",
diff --git a/apps/web/lib/openapi.ts b/apps/web/lib/openapi.ts
index c4f1ade..668ba7a 100644
--- a/apps/web/lib/openapi.ts
+++ b/apps/web/lib/openapi.ts
@@ -630,6 +630,18 @@ export function generateOpenApiSpec(): object {
registry.registerPath({ method: "post", path: "/api/v1/support", summary: "Submit a bug report, suggestion, or question", description: "Best-effort opens a matching issue on the configured Gitea repo (see giteaIssueUrl/giteaError) — this never blocks ticket creation. Sends a confirmation email. Attach files by presigning each one first via POST /api/v1/support/attachments/presign, uploading to the returned URL, then passing the keys here.", security, request: { body: { content: { "application/json": { schema: CreateSupportTicketRef } }, required: true } }, responses: { 201: { description: "Created", content: { "application/json": { schema: SupportTicketRef } } }, 400: { description: "Validation error", content: { "application/json": { schema: ApiErrorRef } } }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } } } });
registry.registerPath({ method: "post", path: "/api/v1/support/attachments/presign", summary: "Get a presigned upload URL for a support ticket attachment", description: "Rate-limited: 20 req/hour. Accepts images, PDF, plain text, JSON, or zip, up to 10MB. Upload the file as multipart form data to the returned url+fields, then include the returned key when submitting the ticket.", security, request: { body: { content: { "application/json": { schema: PresignSupportAttachmentRef } }, required: true } }, responses: { 200: { description: "Presigned upload", content: { "application/json": { schema: PresignedPostRef } } }, 400: { description: "Validation error", content: { "application/json": { schema: ApiErrorRef } } }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } }, 429: { description: "Rate limited", content: { "application/json": { schema: ApiErrorRef } } } } });
+ const AdminSupportTicketRef = registry.register("AdminSupportTicket", z.object({
+ id: z.string(), userId: z.string(), userEmail: z.string(), username: z.string().nullable(),
+ type: SupportTicketTypeEnum, title: z.string(), description: z.string(),
+ status: SupportTicketStatusEnum, giteaIssueUrl: z.string().nullable(), giteaError: z.string().nullable(),
+ createdAt: z.string().datetime(), updatedAt: z.string().datetime(),
+ attachments: z.array(z.object({ id: z.string(), contentType: z.string(), storageKey: z.string(), url: z.string() })),
+ }));
+ const UpdateAdminSupportTicketRef = registry.register("UpdateAdminSupportTicket", z.object({
+ status: SupportTicketStatusEnum.optional(),
+ retryGitea: z.boolean().optional().describe("Re-attempts opening a Gitea issue for this ticket (e.g. after a prior giteaError)."),
+ }));
+
// --- Conversations: 1:1 direct messages ---
const ConversationSummaryRef = registry.register("ConversationSummary", z.object({
id: z.string(),
@@ -827,9 +839,12 @@ export function generateOpenApiSpec(): object {
registry.registerPath({ method: "delete", path: "/api/v1/admin/invites/{id}", summary: "Revoke an invite", description: "Admin only.", security: adminSecurity, request: { params: idParam }, responses: { 200: { description: "Revoked", content: { "application/json": { schema: z.object({ ok: z.boolean() }) } } }, 403: { description: "Forbidden", content: { "application/json": { schema: ApiErrorRef } } }, 404: { description: "Invite not found", content: { "application/json": { schema: ApiErrorRef } } } } });
registry.registerPath({ method: "get", path: "/api/v1/admin/reports", summary: "List pending reports (up to 100, newest first)", description: "Admin only.", security: adminSecurity, responses: { 200: { description: "Reports", content: { "application/json": { schema: z.object({ reports: z.array(AdminReportRef) }) } } }, 403: { description: "Forbidden", content: { "application/json": { schema: ApiErrorRef } } } } });
+
+ registry.registerPath({ method: "get", path: "/api/v1/admin/support", summary: "List all support tickets, newest first", description: "Admin only.", security: adminSecurity, responses: { 200: { description: "Tickets", content: { "application/json": { schema: z.array(AdminSupportTicketRef) } } }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } }, 403: { description: "Forbidden", content: { "application/json": { schema: ApiErrorRef } } } } });
+ registry.registerPath({ method: "patch", path: "/api/v1/admin/support/{id}", summary: "Update a support ticket's status, or retry opening its Gitea issue", description: "Admin only.", security: adminSecurity, request: { params: idParam, body: { content: { "application/json": { schema: UpdateAdminSupportTicketRef } }, required: true } }, responses: { 200: { description: "Updated", 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: "Forbidden", content: { "application/json": { schema: ApiErrorRef } } }, 404: { description: "Not found", content: { "application/json": { schema: ApiErrorRef } } } } });
registry.registerPath({ method: "patch", path: "/api/v1/admin/reports/{id}", summary: "Resolve a report (mark reviewed or dismissed)", description: "Admin only.", security: adminSecurity, request: { params: idParam, body: { content: { "application/json": { schema: ResolveReportBodyRef } }, required: true } }, responses: { 200: { description: "Updated", content: { "application/json": { schema: z.object({ report: ResolvedReportRef }) } } }, 400: { description: "Invalid status", content: { "application/json": { schema: ApiErrorRef } } }, 403: { description: "Forbidden", content: { "application/json": { schema: ApiErrorRef } } }, 404: { description: "Not found", content: { "application/json": { schema: ApiErrorRef } } } } });
- registry.registerPath({ method: "put", path: "/api/v1/admin/settings", summary: "Update site settings (AI provider keys, VAPID keys, signups toggle)", description: "Admin only. Secret-flagged keys are encrypted at rest and never echoed back by any endpoint; this route only accepts new values, it does not return current ones.", security: adminSecurity, request: { body: { content: { "application/json": { schema: UpdateSiteSettingsRef } }, required: true } }, responses: { 200: { description: "Saved", content: { "application/json": { schema: z.object({ ok: z.boolean() }) } } }, 403: { description: "Forbidden", content: { "application/json": { schema: ApiErrorRef } } } } });
+ registry.registerPath({ method: "put", path: "/api/v1/admin/settings", summary: "Update site settings (AI provider keys, VAPID keys, signups toggle)", description: "Admin only. Secret-flagged keys are encrypted at rest and never echoed back by any endpoint; this route only accepts new values, it does not return current ones.", security: adminSecurity, request: { body: { content: { "application/json": { schema: UpdateSiteSettingsRef } }, required: true } }, responses: { 200: { description: "Saved", content: { "application/json": { schema: z.object({ ok: z.boolean() }) } } }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } }, 403: { description: "Forbidden", content: { "application/json": { schema: ApiErrorRef } } } } });
registry.registerPath({ method: "post", path: "/api/v1/admin/test-email", summary: "Send a test verification-style email to a given address", description: "Admin only.", security: adminSecurity, request: { body: { content: { "application/json": { schema: TestEmailBodyRef } }, required: true } }, responses: { 200: { description: "Sent", content: { "application/json": { schema: z.object({ ok: z.boolean() }) } } }, 400: { description: "Missing 'to'", content: { "application/json": { schema: ApiErrorRef } } }, 403: { description: "Forbidden", content: { "application/json": { schema: ApiErrorRef } } }, 500: { description: "BETTER_AUTH_URL not configured, or send failed", content: { "application/json": { schema: ApiErrorRef } } } } });
diff --git a/apps/web/lib/tiers.ts b/apps/web/lib/tiers.ts
index 8aa75c8..6222c11 100644
--- a/apps/web/lib/tiers.ts
+++ b/apps/web/lib/tiers.ts
@@ -19,9 +19,14 @@ export class TierLimitError extends Error {
}
}
+/** Either the top-level db client or a transaction handle — both expose the
+ * same query-builder surface, so live-derivation helpers and the limit check
+ * can run against whichever one the caller is holding a lock in. */
+type DbOrTx = typeof db | Parameters[0]>[0];
+
/** Live count of a user's recipes — lifetime total, not a monthly counter. */
-export async function getRecipeCount(userId: string): Promise {
- const [row] = await db
+export async function getRecipeCount(userId: string, dbOrTx: DbOrTx = db): Promise {
+ const [row] = await dbOrTx
.select({ n: sql`count(*)::int` })
.from(recipes)
.where(eq(recipes.authorId, userId));
@@ -29,22 +34,42 @@ export async function getRecipeCount(userId: string): Promise {
}
/** Live sum of a user's storage usage (recipe photos + review photos + avatar) — lifetime total, not a monthly counter. */
-export async function getStorageUsedMb(userId: string): Promise {
+export async function getStorageUsedMb(userId: string, dbOrTx: DbOrTx = db): Promise {
const [[photoRow], [reviewRow], [userRow]] = await Promise.all([
- db
+ dbOrTx
.select({ total: sql`coalesce(sum(${recipePhotos.sizeMb}), 0)::int` })
.from(recipePhotos)
.innerJoin(recipes, eq(recipePhotos.recipeId, recipes.id))
.where(eq(recipes.authorId, userId)),
- db
+ dbOrTx
.select({ total: sql`coalesce(sum(${ratings.photoSizeMb}), 0)::int` })
.from(ratings)
.where(eq(ratings.userId, userId)),
- db.select({ avatarSizeMb: users.avatarSizeMb }).from(users).where(eq(users.id, userId)),
+ dbOrTx.select({ avatarSizeMb: users.avatarSizeMb }).from(users).where(eq(users.id, userId)),
]);
return (photoRow?.total ?? 0) + (reviewRow?.total ?? 0) + (userRow?.avatarSizeMb ?? 0);
}
+async function checkLiveLimit(
+ dbOrTx: DbOrTx,
+ userId: string,
+ fallbackTier: "free" | "pro" | "family",
+ key: "recipe" | "storage",
+ amount: number
+): Promise {
+ const [dbUser] = await dbOrTx.select({ tier: users.tier }).from(users).where(eq(users.id, userId));
+ const userTier = (dbUser?.tier as "free" | "pro" | "family" | undefined) ?? fallbackTier;
+
+ const [tierDef] = await dbOrTx.select().from(tierDefinitions).where(eq(tierDefinitions.tier, userTier));
+ if (!tierDef) throw new TierLimitError(key, userTier);
+
+ const limit = key === "recipe" ? tierDef.maxRecipes : tierDef.storageMb;
+ if (limit === UNLIMITED) return;
+
+ const current = key === "recipe" ? await getRecipeCount(userId, dbOrTx) : await getStorageUsedMb(userId, dbOrTx);
+ if (current + amount > limit) throw new TierLimitError(key, userTier);
+}
+
/**
* Checks the tier limit for the given key, throwing TierLimitError if it's
* already been reached (or would be exceeded by `amount`).
@@ -59,6 +84,11 @@ export async function getStorageUsedMb(userId: string): Promise {
* "recipe" and "storage" are lifetime totals derived live from real data
* (recipes/photos/avatar rows), so they're pure checks with no counter to
* increment — deleting a recipe/photo/avatar is itself the "decrement".
+ *
+ * This plain (unlocked) check is a fast pre-flight only — two concurrent
+ * calls can both read the pre-write count and both pass. Anywhere the actual
+ * write happens in the same request, use checkTierLimitInTransaction instead
+ * so the check and the write are atomic together.
*/
export async function checkAndIncrementTierLimit(
userId: string,
@@ -66,17 +96,13 @@ export async function checkAndIncrementTierLimit(
key: "recipe" | "aiCall" | "storage",
amount = 1
): Promise {
- const [dbUser] = await db.select({ tier: users.tier }).from(users).where(eq(users.id, userId));
- const userTier = (dbUser?.tier as "free" | "pro" | "family" | undefined) ?? fallbackTier;
-
- const [tierDef] = await db
- .select()
- .from(tierDefinitions)
- .where(eq(tierDefinitions.tier, userTier));
-
- if (!tierDef) throw new TierLimitError(key, userTier);
-
if (key === "aiCall") {
+ const [dbUser] = await db.select({ tier: users.tier }).from(users).where(eq(users.id, userId));
+ const userTier = (dbUser?.tier as "free" | "pro" | "family" | undefined) ?? fallbackTier;
+
+ const [tierDef] = await db.select().from(tierDefinitions).where(eq(tierDefinitions.tier, userTier));
+ if (!tierDef) throw new TierLimitError(key, userTier);
+
const month = currentMonth();
const id = `${userId}-${month}`;
const limit = tierDef.aiCallsPerMonth;
@@ -92,19 +118,34 @@ export async function checkAndIncrementTierLimit(
if (result.length === 0) {
throw new TierLimitError("aiCall", userTier);
}
- } else if (key === "recipe") {
- const limit = tierDef.maxRecipes;
- if (limit !== UNLIMITED) {
- const current = await getRecipeCount(userId);
- if (current + amount > limit) throw new TierLimitError("recipe", userTier);
- }
- } else {
- const limit = tierDef.storageMb;
- if (limit !== UNLIMITED) {
- const current = await getStorageUsedMb(userId);
- if (current + amount > limit) throw new TierLimitError("storage", userTier);
- }
+ return;
}
+
+ await checkLiveLimit(db, userId, fallbackTier, key, amount);
+}
+
+/**
+ * Same check as checkAndIncrementTierLimit's "recipe"/"storage" branches, but
+ * takes a transaction and holds a per-user Postgres advisory lock for its
+ * duration — so a concurrent call for the same user blocks until this one
+ * commits (or rolls back), instead of racing to read the same pre-write
+ * count. The lock auto-releases at transaction end (pg_advisory_xact_lock),
+ * so there's no separate unlock step and no risk of a leaked lock.
+ *
+ * Call this as the first statement inside the same db.transaction that
+ * performs the write the check is gating — checking and inserting in
+ * different transactions (or different requests, like a presign-time check
+ * for a row written later) leaves the same TOCTOU gap this closes.
+ */
+export async function checkTierLimitInTransaction(
+ tx: DbOrTx,
+ userId: string,
+ fallbackTier: "free" | "pro" | "family",
+ key: "recipe" | "storage",
+ amount = 1
+): Promise {
+ await tx.execute(sql`SELECT pg_advisory_xact_lock(hashtext(${userId}))`);
+ await checkLiveLimit(tx, userId, fallbackTier, key, amount);
}
/**
diff --git a/apps/web/package.json b/apps/web/package.json
index bb27401..94d8f70 100644
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@ -1,6 +1,6 @@
{
"name": "@epicure/web",
- "version": "0.57.2",
+ "version": "0.60.0",
"private": true,
"scripts": {
"dev": "next dev",
@@ -31,7 +31,7 @@
"clsx": "^2.1.1",
"cmdk": "^1.1.1",
"diff": "^9.0.0",
- "drizzle-orm": "^0.44.7",
+ "drizzle-orm": "^0.45.2",
"ioredis": "^5.11.1",
"lucide-react": "^1.21.0",
"next": "16.2.9",
diff --git a/package.json b/package.json
index e03ea19..b6726e8 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "epicure",
- "version": "0.57.2",
+ "version": "0.60.0",
"private": true,
"scripts": {
"dev": "pnpm --filter web dev",
diff --git a/packages/db/package.json b/packages/db/package.json
index 659d204..4d9df2b 100644
--- a/packages/db/package.json
+++ b/packages/db/package.json
@@ -17,7 +17,7 @@
"typecheck": "tsc --noEmit"
},
"dependencies": {
- "drizzle-orm": "^0.44.7",
+ "drizzle-orm": "^0.45.2",
"postgres": "^3.4.7"
},
"devDependencies": {
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index ac7c93d..b1e3cb1 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -4,6 +4,10 @@ settings:
autoInstallPeers: true
excludeLinksFromLockfile: false
+overrides:
+ esbuild: '>=0.24.3'
+ postcss: '>=8.5.10'
+
importers:
.:
@@ -55,7 +59,7 @@ importers:
version: 6.0.209(zod@3.25.76)
better-auth:
specifier: ^1.6.20
- version: 1.6.20(@opentelemetry/api@1.9.1)(drizzle-kit@0.31.10)(drizzle-orm@0.44.7(@opentelemetry/api@1.9.1)(kysely@0.29.2)(postgres@3.4.9))(next@16.2.9(@babel/core@7.29.7)(@opentelemetry/api@1.9.1)(react-dom@19.2.4(react@19.2.4))(react@19.2.4))(react-dom@19.2.4(react@19.2.4))(react@19.2.4)(vitest@4.1.9)
+ version: 1.6.20(@opentelemetry/api@1.9.1)(drizzle-kit@0.31.10)(drizzle-orm@0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.2)(postgres@3.4.9))(next@16.2.9(@babel/core@7.29.7)(@opentelemetry/api@1.9.1)(react-dom@19.2.4(react@19.2.4))(react@19.2.4))(react-dom@19.2.4(react@19.2.4))(react@19.2.4)(vitest@4.1.9)
class-variance-authority:
specifier: ^0.7.1
version: 0.7.1
@@ -69,8 +73,8 @@ importers:
specifier: ^9.0.0
version: 9.0.0
drizzle-orm:
- specifier: ^0.44.7
- version: 0.44.7(@opentelemetry/api@1.9.1)(kysely@0.29.2)(postgres@3.4.9)
+ specifier: ^0.45.2
+ version: 0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.2)(postgres@3.4.9)
ioredis:
specifier: ^5.11.1
version: 5.11.1
@@ -181,8 +185,8 @@ importers:
packages/db:
dependencies:
drizzle-orm:
- specifier: ^0.44.7
- version: 0.44.7(@opentelemetry/api@1.9.1)(kysely@0.29.2)(postgres@3.4.9)
+ specifier: ^0.45.2
+ version: 0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.2)(postgres@3.4.9)
postgres:
specifier: ^3.4.7
version: 3.4.9
@@ -686,12 +690,6 @@ packages:
cpu: [ppc64]
os: [aix]
- '@esbuild/android-arm64@0.18.20':
- resolution: {integrity: sha512-Nz4rJcchGDtENV0eMKUNa6L12zz2zBDXuhj/Vjh18zGqB44Bi7MBMSXjgunJgjRhCmKOjnPuZp4Mb6OKqtMHLQ==}
- engines: {node: '>=12'}
- cpu: [arm64]
- os: [android]
-
'@esbuild/android-arm64@0.25.12':
resolution: {integrity: sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg==}
engines: {node: '>=18'}
@@ -704,12 +702,6 @@ packages:
cpu: [arm64]
os: [android]
- '@esbuild/android-arm@0.18.20':
- resolution: {integrity: sha512-fyi7TDI/ijKKNZTUJAQqiG5T7YjJXgnzkURqmGj13C6dCqckZBLdl4h7bkhHt/t0WP+zO9/zwroDvANaOqO5Sw==}
- engines: {node: '>=12'}
- cpu: [arm]
- os: [android]
-
'@esbuild/android-arm@0.25.12':
resolution: {integrity: sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg==}
engines: {node: '>=18'}
@@ -722,12 +714,6 @@ packages:
cpu: [arm]
os: [android]
- '@esbuild/android-x64@0.18.20':
- resolution: {integrity: sha512-8GDdlePJA8D6zlZYJV/jnrRAi6rOiNaCC/JclcXpB+KIuvfBN4owLtgzY2bsxnx666XjJx2kDPUmnTtR8qKQUg==}
- engines: {node: '>=12'}
- cpu: [x64]
- os: [android]
-
'@esbuild/android-x64@0.25.12':
resolution: {integrity: sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg==}
engines: {node: '>=18'}
@@ -740,12 +726,6 @@ packages:
cpu: [x64]
os: [android]
- '@esbuild/darwin-arm64@0.18.20':
- resolution: {integrity: sha512-bxRHW5kHU38zS2lPTPOyuyTm+S+eobPUnTNkdJEfAddYgEcll4xkT8DB9d2008DtTbl7uJag2HuE5NZAZgnNEA==}
- engines: {node: '>=12'}
- cpu: [arm64]
- os: [darwin]
-
'@esbuild/darwin-arm64@0.25.12':
resolution: {integrity: sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg==}
engines: {node: '>=18'}
@@ -758,12 +738,6 @@ packages:
cpu: [arm64]
os: [darwin]
- '@esbuild/darwin-x64@0.18.20':
- resolution: {integrity: sha512-pc5gxlMDxzm513qPGbCbDukOdsGtKhfxD1zJKXjCCcU7ju50O7MeAZ8c4krSJcOIJGFR+qx21yMMVYwiQvyTyQ==}
- engines: {node: '>=12'}
- cpu: [x64]
- os: [darwin]
-
'@esbuild/darwin-x64@0.25.12':
resolution: {integrity: sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA==}
engines: {node: '>=18'}
@@ -776,12 +750,6 @@ packages:
cpu: [x64]
os: [darwin]
- '@esbuild/freebsd-arm64@0.18.20':
- resolution: {integrity: sha512-yqDQHy4QHevpMAaxhhIwYPMv1NECwOvIpGCZkECn8w2WFHXjEwrBn3CeNIYsibZ/iZEUemj++M26W3cNR5h+Tw==}
- engines: {node: '>=12'}
- cpu: [arm64]
- os: [freebsd]
-
'@esbuild/freebsd-arm64@0.25.12':
resolution: {integrity: sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg==}
engines: {node: '>=18'}
@@ -794,12 +762,6 @@ packages:
cpu: [arm64]
os: [freebsd]
- '@esbuild/freebsd-x64@0.18.20':
- resolution: {integrity: sha512-tgWRPPuQsd3RmBZwarGVHZQvtzfEBOreNuxEMKFcd5DaDn2PbBxfwLcj4+aenoh7ctXcbXmOQIn8HI6mCSw5MQ==}
- engines: {node: '>=12'}
- cpu: [x64]
- os: [freebsd]
-
'@esbuild/freebsd-x64@0.25.12':
resolution: {integrity: sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ==}
engines: {node: '>=18'}
@@ -812,12 +774,6 @@ packages:
cpu: [x64]
os: [freebsd]
- '@esbuild/linux-arm64@0.18.20':
- resolution: {integrity: sha512-2YbscF+UL7SQAVIpnWvYwM+3LskyDmPhe31pE7/aoTMFKKzIc9lLbyGUpmmb8a8AixOL61sQ/mFh3jEjHYFvdA==}
- engines: {node: '>=12'}
- cpu: [arm64]
- os: [linux]
-
'@esbuild/linux-arm64@0.25.12':
resolution: {integrity: sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ==}
engines: {node: '>=18'}
@@ -830,12 +786,6 @@ packages:
cpu: [arm64]
os: [linux]
- '@esbuild/linux-arm@0.18.20':
- resolution: {integrity: sha512-/5bHkMWnq1EgKr1V+Ybz3s1hWXok7mDFUMQ4cG10AfW3wL02PSZi5kFpYKrptDsgb2WAJIvRcDm+qIvXf/apvg==}
- engines: {node: '>=12'}
- cpu: [arm]
- os: [linux]
-
'@esbuild/linux-arm@0.25.12':
resolution: {integrity: sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw==}
engines: {node: '>=18'}
@@ -848,12 +798,6 @@ packages:
cpu: [arm]
os: [linux]
- '@esbuild/linux-ia32@0.18.20':
- resolution: {integrity: sha512-P4etWwq6IsReT0E1KHU40bOnzMHoH73aXp96Fs8TIT6z9Hu8G6+0SHSw9i2isWrD2nbx2qo5yUqACgdfVGx7TA==}
- engines: {node: '>=12'}
- cpu: [ia32]
- os: [linux]
-
'@esbuild/linux-ia32@0.25.12':
resolution: {integrity: sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA==}
engines: {node: '>=18'}
@@ -866,12 +810,6 @@ packages:
cpu: [ia32]
os: [linux]
- '@esbuild/linux-loong64@0.18.20':
- resolution: {integrity: sha512-nXW8nqBTrOpDLPgPY9uV+/1DjxoQ7DoB2N8eocyq8I9XuqJ7BiAMDMf9n1xZM9TgW0J8zrquIb/A7s3BJv7rjg==}
- engines: {node: '>=12'}
- cpu: [loong64]
- os: [linux]
-
'@esbuild/linux-loong64@0.25.12':
resolution: {integrity: sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng==}
engines: {node: '>=18'}
@@ -884,12 +822,6 @@ packages:
cpu: [loong64]
os: [linux]
- '@esbuild/linux-mips64el@0.18.20':
- resolution: {integrity: sha512-d5NeaXZcHp8PzYy5VnXV3VSd2D328Zb+9dEq5HE6bw6+N86JVPExrA6O68OPwobntbNJ0pzCpUFZTo3w0GyetQ==}
- engines: {node: '>=12'}
- cpu: [mips64el]
- os: [linux]
-
'@esbuild/linux-mips64el@0.25.12':
resolution: {integrity: sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw==}
engines: {node: '>=18'}
@@ -902,12 +834,6 @@ packages:
cpu: [mips64el]
os: [linux]
- '@esbuild/linux-ppc64@0.18.20':
- resolution: {integrity: sha512-WHPyeScRNcmANnLQkq6AfyXRFr5D6N2sKgkFo2FqguP44Nw2eyDlbTdZwd9GYk98DZG9QItIiTlFLHJHjxP3FA==}
- engines: {node: '>=12'}
- cpu: [ppc64]
- os: [linux]
-
'@esbuild/linux-ppc64@0.25.12':
resolution: {integrity: sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA==}
engines: {node: '>=18'}
@@ -920,12 +846,6 @@ packages:
cpu: [ppc64]
os: [linux]
- '@esbuild/linux-riscv64@0.18.20':
- resolution: {integrity: sha512-WSxo6h5ecI5XH34KC7w5veNnKkju3zBRLEQNY7mv5mtBmrP/MjNBCAlsM2u5hDBlS3NGcTQpoBvRzqBcRtpq1A==}
- engines: {node: '>=12'}
- cpu: [riscv64]
- os: [linux]
-
'@esbuild/linux-riscv64@0.25.12':
resolution: {integrity: sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w==}
engines: {node: '>=18'}
@@ -938,12 +858,6 @@ packages:
cpu: [riscv64]
os: [linux]
- '@esbuild/linux-s390x@0.18.20':
- resolution: {integrity: sha512-+8231GMs3mAEth6Ja1iK0a1sQ3ohfcpzpRLH8uuc5/KVDFneH6jtAJLFGafpzpMRO6DzJ6AvXKze9LfFMrIHVQ==}
- engines: {node: '>=12'}
- cpu: [s390x]
- os: [linux]
-
'@esbuild/linux-s390x@0.25.12':
resolution: {integrity: sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg==}
engines: {node: '>=18'}
@@ -956,12 +870,6 @@ packages:
cpu: [s390x]
os: [linux]
- '@esbuild/linux-x64@0.18.20':
- resolution: {integrity: sha512-UYqiqemphJcNsFEskc73jQ7B9jgwjWrSayxawS6UVFZGWrAAtkzjxSqnoclCXxWtfwLdzU+vTpcNYhpn43uP1w==}
- engines: {node: '>=12'}
- cpu: [x64]
- os: [linux]
-
'@esbuild/linux-x64@0.25.12':
resolution: {integrity: sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw==}
engines: {node: '>=18'}
@@ -986,12 +894,6 @@ packages:
cpu: [arm64]
os: [netbsd]
- '@esbuild/netbsd-x64@0.18.20':
- resolution: {integrity: sha512-iO1c++VP6xUBUmltHZoMtCUdPlnPGdBom6IrO4gyKPFFVBKioIImVooR5I83nTew5UOYrk3gIJhbZh8X44y06A==}
- engines: {node: '>=12'}
- cpu: [x64]
- os: [netbsd]
-
'@esbuild/netbsd-x64@0.25.12':
resolution: {integrity: sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ==}
engines: {node: '>=18'}
@@ -1016,12 +918,6 @@ packages:
cpu: [arm64]
os: [openbsd]
- '@esbuild/openbsd-x64@0.18.20':
- resolution: {integrity: sha512-e5e4YSsuQfX4cxcygw/UCPIEP6wbIL+se3sxPdCiMbFLBWu0eiZOJ7WoD+ptCLrmjZBK1Wk7I6D/I3NglUGOxg==}
- engines: {node: '>=12'}
- cpu: [x64]
- os: [openbsd]
-
'@esbuild/openbsd-x64@0.25.12':
resolution: {integrity: sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw==}
engines: {node: '>=18'}
@@ -1046,12 +942,6 @@ packages:
cpu: [arm64]
os: [openharmony]
- '@esbuild/sunos-x64@0.18.20':
- resolution: {integrity: sha512-kDbFRFp0YpTQVVrqUd5FTYmWo45zGaXe0X8E1G/LKFC0v8x0vWrhOWSLITcCn63lmZIxfOMXtCfti/RxN/0wnQ==}
- engines: {node: '>=12'}
- cpu: [x64]
- os: [sunos]
-
'@esbuild/sunos-x64@0.25.12':
resolution: {integrity: sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w==}
engines: {node: '>=18'}
@@ -1064,12 +954,6 @@ packages:
cpu: [x64]
os: [sunos]
- '@esbuild/win32-arm64@0.18.20':
- resolution: {integrity: sha512-ddYFR6ItYgoaq4v4JmQQaAI5s7npztfV4Ag6NrhiaW0RrnOXqBkgwZLofVTlq1daVTQNhtI5oieTvkRPfZrePg==}
- engines: {node: '>=12'}
- cpu: [arm64]
- os: [win32]
-
'@esbuild/win32-arm64@0.25.12':
resolution: {integrity: sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg==}
engines: {node: '>=18'}
@@ -1082,12 +966,6 @@ packages:
cpu: [arm64]
os: [win32]
- '@esbuild/win32-ia32@0.18.20':
- resolution: {integrity: sha512-Wv7QBi3ID/rROT08SABTS7eV4hX26sVduqDOTe1MvGMjNd3EjOz4b7zeexIR62GTIEKrfJXKL9LFxTYgkyeu7g==}
- engines: {node: '>=12'}
- cpu: [ia32]
- os: [win32]
-
'@esbuild/win32-ia32@0.25.12':
resolution: {integrity: sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ==}
engines: {node: '>=18'}
@@ -1100,12 +978,6 @@ packages:
cpu: [ia32]
os: [win32]
- '@esbuild/win32-x64@0.18.20':
- resolution: {integrity: sha512-kTdfRcSiDfQca/y9QIkng02avJ+NCaQvrMejlsB3RRv5sE9rRoeBPISaZpKxHELzRxZyLvNts1P27W3wV+8geQ==}
- engines: {node: '>=12'}
- cpu: [x64]
- os: [win32]
-
'@esbuild/win32-x64@0.25.12':
resolution: {integrity: sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA==}
engines: {node: '>=18'}
@@ -3030,8 +2902,8 @@ packages:
resolution: {integrity: sha512-7OZcmQUrdGI+DUNNsKBn1aW8qSoKuTH7d0mYgSP8bAzdFzKoovxEFnoGQp2dVs82EOJeYycqRtciopszwUf8bw==}
hasBin: true
- drizzle-orm@0.44.7:
- resolution: {integrity: sha512-quIpnYznjU9lHshEOAYLoZ9s3jweleHlZIAWR/jX9gAWNg/JhQ1wj0KGRf7/Zm+obRrYd9GjPVJg790QY9N5AQ==}
+ drizzle-orm@0.45.2:
+ resolution: {integrity: sha512-kY0BSaTNYWnoDMVoyY8uxmyHjpJW1geOmBMdSSicKo9CIIWkSxMIj2rkeSR51b8KAPB7m+qysjuHme5nKP+E5Q==}
peerDependencies:
'@aws-sdk/client-rds-data': '>=3'
'@cloudflare/workers-types': '>=4'
@@ -3206,11 +3078,6 @@ packages:
resolution: {integrity: sha512-CxN9N56HYfd2m/acc/NOFrZQsN9kU4eh+2kk6A707Kz1krH8tKmfrs5RnftB8WNX80T0NS7vSQsDOlg23diR2g==}
engines: {node: '>= 0.4'}
- esbuild@0.18.20:
- resolution: {integrity: sha512-ceqxoedUrcayh7Y7ZX6NdbbDzGROiyVBgC4PriJThBKSVPWnnFHZAkfI1lJT8QFkOwH4qOS2SJkS4wvpGl8BpA==}
- engines: {node: '>=12'}
- hasBin: true
-
esbuild@0.25.12:
resolution: {integrity: sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==}
engines: {node: '>=18'}
@@ -4593,10 +4460,6 @@ packages:
resolution: {integrity: sha512-HeP7D2wyhkR+XaK6v4W8oRF62Dsz4flyuczALJp61GckGm42u1saSSJ/0auvcBqxs3jMRFEcPK34At/0JBKdOg==}
engines: {node: '>=4'}
- postcss@8.4.31:
- resolution: {integrity: sha512-PS08Iboia9mts/2ygV3eLpY5ghnUcfLV/EXTOW1E2qYxJKGGBUtNjN76FYHnMs36RmARn41bC0AZmn+rR0OVpQ==}
- engines: {node: ^10 || ^12 || >=14}
-
postcss@8.5.15:
resolution: {integrity: sha512-FfR8sjd4em2T6fb3I2MwAJU7HWVMr9zba+enmQeeWFfCbm+UOC/0X4DS8XtpUTMwWMGbjKYP7xjfNekzyGmB3A==}
engines: {node: ^10 || ^12 || >=14}
@@ -5284,7 +5147,7 @@ packages:
peerDependencies:
'@types/node': ^20.19.0 || >=22.12.0
'@vitejs/devtools': ^0.3.0
- esbuild: ^0.27.0 || ^0.28.0
+ esbuild: '>=0.24.3'
jiti: '>=1.21.0'
less: ^4.0.0
sass: ^1.70.0
@@ -5956,12 +5819,12 @@ snapshots:
optionalDependencies:
'@opentelemetry/api': 1.9.1
- '@better-auth/drizzle-adapter@1.6.20(@better-auth/core@1.6.20(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.1)(@opentelemetry/api@1.9.1)(better-call@1.3.6(zod@3.25.76))(jose@6.2.3)(kysely@0.29.2)(nanostores@1.3.0))(@better-auth/utils@0.4.2)(drizzle-orm@0.44.7(@opentelemetry/api@1.9.1)(kysely@0.29.2)(postgres@3.4.9))':
+ '@better-auth/drizzle-adapter@1.6.20(@better-auth/core@1.6.20(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.1)(@opentelemetry/api@1.9.1)(better-call@1.3.6(zod@3.25.76))(jose@6.2.3)(kysely@0.29.2)(nanostores@1.3.0))(@better-auth/utils@0.4.2)(drizzle-orm@0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.2)(postgres@3.4.9))':
dependencies:
'@better-auth/core': 1.6.20(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.1)(@opentelemetry/api@1.9.1)(better-call@1.3.6(zod@3.25.76))(jose@6.2.3)(kysely@0.29.2)(nanostores@1.3.0)
'@better-auth/utils': 0.4.2
optionalDependencies:
- drizzle-orm: 0.44.7(@opentelemetry/api@1.9.1)(kysely@0.29.2)(postgres@3.4.9)
+ drizzle-orm: 0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.2)(postgres@3.4.9)
'@better-auth/kysely-adapter@1.6.20(@better-auth/core@1.6.20(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.1)(@opentelemetry/api@1.9.1)(better-call@1.3.6(zod@3.25.76))(jose@6.2.3)(kysely@0.29.2)(nanostores@1.3.0))(@better-auth/utils@0.4.2)(kysely@0.29.2)':
dependencies:
@@ -6107,7 +5970,7 @@ snapshots:
'@esbuild-kit/core-utils@3.3.2':
dependencies:
- esbuild: 0.18.20
+ esbuild: 0.28.1
source-map-support: 0.5.21
'@esbuild-kit/esm-loader@2.6.5':
@@ -6121,144 +5984,96 @@ snapshots:
'@esbuild/aix-ppc64@0.28.1':
optional: true
- '@esbuild/android-arm64@0.18.20':
- optional: true
-
'@esbuild/android-arm64@0.25.12':
optional: true
'@esbuild/android-arm64@0.28.1':
optional: true
- '@esbuild/android-arm@0.18.20':
- optional: true
-
'@esbuild/android-arm@0.25.12':
optional: true
'@esbuild/android-arm@0.28.1':
optional: true
- '@esbuild/android-x64@0.18.20':
- optional: true
-
'@esbuild/android-x64@0.25.12':
optional: true
'@esbuild/android-x64@0.28.1':
optional: true
- '@esbuild/darwin-arm64@0.18.20':
- optional: true
-
'@esbuild/darwin-arm64@0.25.12':
optional: true
'@esbuild/darwin-arm64@0.28.1':
optional: true
- '@esbuild/darwin-x64@0.18.20':
- optional: true
-
'@esbuild/darwin-x64@0.25.12':
optional: true
'@esbuild/darwin-x64@0.28.1':
optional: true
- '@esbuild/freebsd-arm64@0.18.20':
- optional: true
-
'@esbuild/freebsd-arm64@0.25.12':
optional: true
'@esbuild/freebsd-arm64@0.28.1':
optional: true
- '@esbuild/freebsd-x64@0.18.20':
- optional: true
-
'@esbuild/freebsd-x64@0.25.12':
optional: true
'@esbuild/freebsd-x64@0.28.1':
optional: true
- '@esbuild/linux-arm64@0.18.20':
- optional: true
-
'@esbuild/linux-arm64@0.25.12':
optional: true
'@esbuild/linux-arm64@0.28.1':
optional: true
- '@esbuild/linux-arm@0.18.20':
- optional: true
-
'@esbuild/linux-arm@0.25.12':
optional: true
'@esbuild/linux-arm@0.28.1':
optional: true
- '@esbuild/linux-ia32@0.18.20':
- optional: true
-
'@esbuild/linux-ia32@0.25.12':
optional: true
'@esbuild/linux-ia32@0.28.1':
optional: true
- '@esbuild/linux-loong64@0.18.20':
- optional: true
-
'@esbuild/linux-loong64@0.25.12':
optional: true
'@esbuild/linux-loong64@0.28.1':
optional: true
- '@esbuild/linux-mips64el@0.18.20':
- optional: true
-
'@esbuild/linux-mips64el@0.25.12':
optional: true
'@esbuild/linux-mips64el@0.28.1':
optional: true
- '@esbuild/linux-ppc64@0.18.20':
- optional: true
-
'@esbuild/linux-ppc64@0.25.12':
optional: true
'@esbuild/linux-ppc64@0.28.1':
optional: true
- '@esbuild/linux-riscv64@0.18.20':
- optional: true
-
'@esbuild/linux-riscv64@0.25.12':
optional: true
'@esbuild/linux-riscv64@0.28.1':
optional: true
- '@esbuild/linux-s390x@0.18.20':
- optional: true
-
'@esbuild/linux-s390x@0.25.12':
optional: true
'@esbuild/linux-s390x@0.28.1':
optional: true
- '@esbuild/linux-x64@0.18.20':
- optional: true
-
'@esbuild/linux-x64@0.25.12':
optional: true
@@ -6271,9 +6086,6 @@ snapshots:
'@esbuild/netbsd-arm64@0.28.1':
optional: true
- '@esbuild/netbsd-x64@0.18.20':
- optional: true
-
'@esbuild/netbsd-x64@0.25.12':
optional: true
@@ -6286,9 +6098,6 @@ snapshots:
'@esbuild/openbsd-arm64@0.28.1':
optional: true
- '@esbuild/openbsd-x64@0.18.20':
- optional: true
-
'@esbuild/openbsd-x64@0.25.12':
optional: true
@@ -6301,36 +6110,24 @@ snapshots:
'@esbuild/openharmony-arm64@0.28.1':
optional: true
- '@esbuild/sunos-x64@0.18.20':
- optional: true
-
'@esbuild/sunos-x64@0.25.12':
optional: true
'@esbuild/sunos-x64@0.28.1':
optional: true
- '@esbuild/win32-arm64@0.18.20':
- optional: true
-
'@esbuild/win32-arm64@0.25.12':
optional: true
'@esbuild/win32-arm64@0.28.1':
optional: true
- '@esbuild/win32-ia32@0.18.20':
- optional: true
-
'@esbuild/win32-ia32@0.25.12':
optional: true
'@esbuild/win32-ia32@0.28.1':
optional: true
- '@esbuild/win32-x64@0.18.20':
- optional: true
-
'@esbuild/win32-x64@0.25.12':
optional: true
@@ -7599,10 +7396,10 @@ snapshots:
baseline-browser-mapping@2.10.38: {}
- better-auth@1.6.20(@opentelemetry/api@1.9.1)(drizzle-kit@0.31.10)(drizzle-orm@0.44.7(@opentelemetry/api@1.9.1)(kysely@0.29.2)(postgres@3.4.9))(next@16.2.9(@babel/core@7.29.7)(@opentelemetry/api@1.9.1)(react-dom@19.2.4(react@19.2.4))(react@19.2.4))(react-dom@19.2.4(react@19.2.4))(react@19.2.4)(vitest@4.1.9):
+ better-auth@1.6.20(@opentelemetry/api@1.9.1)(drizzle-kit@0.31.10)(drizzle-orm@0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.2)(postgres@3.4.9))(next@16.2.9(@babel/core@7.29.7)(@opentelemetry/api@1.9.1)(react-dom@19.2.4(react@19.2.4))(react@19.2.4))(react-dom@19.2.4(react@19.2.4))(react@19.2.4)(vitest@4.1.9):
dependencies:
'@better-auth/core': 1.6.20(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.1)(@opentelemetry/api@1.9.1)(better-call@1.3.6(zod@3.25.76))(jose@6.2.3)(kysely@0.29.2)(nanostores@1.3.0)
- '@better-auth/drizzle-adapter': 1.6.20(@better-auth/core@1.6.20(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.1)(@opentelemetry/api@1.9.1)(better-call@1.3.6(zod@3.25.76))(jose@6.2.3)(kysely@0.29.2)(nanostores@1.3.0))(@better-auth/utils@0.4.2)(drizzle-orm@0.44.7(@opentelemetry/api@1.9.1)(kysely@0.29.2)(postgres@3.4.9))
+ '@better-auth/drizzle-adapter': 1.6.20(@better-auth/core@1.6.20(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.1)(@opentelemetry/api@1.9.1)(better-call@1.3.6(zod@3.25.76))(jose@6.2.3)(kysely@0.29.2)(nanostores@1.3.0))(@better-auth/utils@0.4.2)(drizzle-orm@0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.2)(postgres@3.4.9))
'@better-auth/kysely-adapter': 1.6.20(@better-auth/core@1.6.20(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.1)(@opentelemetry/api@1.9.1)(better-call@1.3.6(zod@3.25.76))(jose@6.2.3)(kysely@0.29.2)(nanostores@1.3.0))(@better-auth/utils@0.4.2)(kysely@0.29.2)
'@better-auth/memory-adapter': 1.6.20(@better-auth/core@1.6.20(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.1)(@opentelemetry/api@1.9.1)(better-call@1.3.6(zod@3.25.76))(jose@6.2.3)(kysely@0.29.2)(nanostores@1.3.0))(@better-auth/utils@0.4.2)
'@better-auth/mongo-adapter': 1.6.20(@better-auth/core@1.6.20(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.1)(@opentelemetry/api@1.9.1)(better-call@1.3.6(zod@3.25.76))(jose@6.2.3)(kysely@0.29.2)(nanostores@1.3.0))(@better-auth/utils@0.4.2)
@@ -7620,7 +7417,7 @@ snapshots:
zod: 4.4.3
optionalDependencies:
drizzle-kit: 0.31.10
- drizzle-orm: 0.44.7(@opentelemetry/api@1.9.1)(kysely@0.29.2)(postgres@3.4.9)
+ drizzle-orm: 0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.2)(postgres@3.4.9)
next: 16.2.9(@babel/core@7.29.7)(@opentelemetry/api@1.9.1)(react-dom@19.2.4(react@19.2.4))(react@19.2.4)
react: 19.2.4
react-dom: 19.2.4(react@19.2.4)
@@ -7960,7 +7757,7 @@ snapshots:
esbuild: 0.25.12
tsx: 4.22.4
- drizzle-orm@0.44.7(@opentelemetry/api@1.9.1)(kysely@0.29.2)(postgres@3.4.9):
+ drizzle-orm@0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.2)(postgres@3.4.9):
optionalDependencies:
'@opentelemetry/api': 1.9.1
kysely: 0.29.2
@@ -8118,31 +7915,6 @@ snapshots:
is-date-object: 1.1.0
is-symbol: 1.1.1
- esbuild@0.18.20:
- optionalDependencies:
- '@esbuild/android-arm': 0.18.20
- '@esbuild/android-arm64': 0.18.20
- '@esbuild/android-x64': 0.18.20
- '@esbuild/darwin-arm64': 0.18.20
- '@esbuild/darwin-x64': 0.18.20
- '@esbuild/freebsd-arm64': 0.18.20
- '@esbuild/freebsd-x64': 0.18.20
- '@esbuild/linux-arm': 0.18.20
- '@esbuild/linux-arm64': 0.18.20
- '@esbuild/linux-ia32': 0.18.20
- '@esbuild/linux-loong64': 0.18.20
- '@esbuild/linux-mips64el': 0.18.20
- '@esbuild/linux-ppc64': 0.18.20
- '@esbuild/linux-riscv64': 0.18.20
- '@esbuild/linux-s390x': 0.18.20
- '@esbuild/linux-x64': 0.18.20
- '@esbuild/netbsd-x64': 0.18.20
- '@esbuild/openbsd-x64': 0.18.20
- '@esbuild/sunos-x64': 0.18.20
- '@esbuild/win32-arm64': 0.18.20
- '@esbuild/win32-ia32': 0.18.20
- '@esbuild/win32-x64': 0.18.20
-
esbuild@0.25.12:
optionalDependencies:
'@esbuild/aix-ppc64': 0.25.12
@@ -9538,7 +9310,7 @@ snapshots:
'@swc/helpers': 0.5.15
baseline-browser-mapping: 2.10.38
caniuse-lite: 1.0.30001799
- postcss: 8.4.31
+ postcss: 8.5.15
react: 19.2.4
react-dom: 19.2.4(react@19.2.4)
styled-jsx: 5.1.6(@babel/core@7.29.7)(react@19.2.4)
@@ -9785,12 +9557,6 @@ snapshots:
cssesc: 3.0.0
util-deprecate: 1.0.2
- postcss@8.4.31:
- dependencies:
- nanoid: 3.3.15
- picocolors: 1.1.1
- source-map-js: 1.2.1
-
postcss@8.5.15:
dependencies:
nanoid: 3.3.15
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index 0d5fc7e..100cd1b 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -7,3 +7,6 @@ allowBuilds:
esbuild: true
sharp: true
unrs-resolver: true
+overrides:
+ esbuild: ">=0.24.3"
+ postcss: ">=8.5.10"