Supercharge your AI agents with data from the web and beyond. Building the library for superintelligence. 🔥
TypeScript aiai-agentsai-crawlerai-scrapingai-searchcrawlerdata-extractionhtml-to-markdownllmmarkdownscraperscrapingweb-crawlerweb-dataweb-data-extractionweb-scraperweb-scrapingweb-searchwebscraping
fix(api): name the limit that refused a request in the 402 body (#5527)
Gaurav Chadha073ae485b1f0
diff --git a/apps/api/src/__tests__/routes/check-credits-middleware.test.ts b/apps/api/src/__tests__/routes/check-credits-middleware.test.tsindex a7fbbbc83..422327af0 100644--- a/apps/api/src/__tests__/routes/check-credits-middleware.test.ts+++ b/apps/api/src/__tests__/routes/check-credits-middleware.test.ts@@ -24,6 +24,10 @@ vi.mock("../../services/autumn/usage", () => ({getTeamBalance: vi.fn(),}));+vi.mock("../../lib/api-key-spend-limit", () => ({+ getApiKeySpendLimit: vi.fn(),+}));+vi.mock("../../lib/http-metrics", () => ({httpRequestDurationSeconds: { observe: vi.fn() },getRoutePattern: vi.fn(() => "/v1/crawl"),@@ -46,6 +50,7 @@ vi.mock("geoip-country", () => ({ lookup: vi.fn(() => null) }));import { checkCreditsMiddleware } from "../../routes/shared";import { autumnService } from "../../services/autumn/autumn.service";import { getTeamBalance } from "../../services/autumn/usage";+import { getApiKeySpendLimit } from "../../lib/api-key-spend-limit";const checkCreditsMock = autumnService.checkCredits as MockedFunction<typeof autumnService.checkCredits@@ -53,6 +58,9 @@ const checkCreditsMock = autumnService.checkCredits as MockedFunction<const getTeamBalanceMock = getTeamBalance as MockedFunction<typeof getTeamBalance>;+const getApiKeySpendLimitMock = getApiKeySpendLimit as MockedFunction<+ typeof getApiKeySpendLimit+>;function buildReq(overrides: any = {}): any {return {@@ -499,3 +507,116 @@ describe("checkCreditsMiddleware – MCP credits", () => {);});});++describe("checkCreditsMiddleware – 402 names the limit", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ function body(res: any) {+ return res.json.mock.calls[0][0];+ }++ it("names a per-key spend limit when the team balance covers the request", async () => {+ checkCreditsMock.mockResolvedValue({ allowed: false, remaining: 2500 });+ getApiKeySpendLimitMock.mockResolvedValue({+ credits: 2000,+ interval: "month",+ });++ const req = buildReq({+ path: "/v2/scrape",+ body: {},+ acuc: { api_key_id: 42 },+ });+ const { res } = await runMiddleware(req);++ expect(res.status).toHaveBeenCalledWith(402);+ expect(getApiKeySpendLimitMock).toHaveBeenCalledWith(42);+ expect(body(res)).toMatchObject({+ success: false,+ code: "api_key_spend_limit",+ requested_credits: 1,+ remaining_credits: 2500,+ limit: { type: "api_key", credits: 2000, interval: "month" },+ });+ expect(body(res).error).toContain("spend limit of 2000 credits per month");+ });++ it("says when a request asks for more than the key's whole limit", async () => {+ checkCreditsMock.mockResolvedValue({ allowed: false, remaining: 600 });+ getApiKeySpendLimitMock.mockResolvedValue({ credits: 9, interval: "day" });++ const req = buildReq({+ path: "/v2/search",+ body: { limit: 10 },+ acuc: { api_key_id: 42 },+ });+ const { res } = await runMiddleware(req, checkCreditsMiddleware(10));++ expect(body(res).code).toBe("api_key_spend_limit");+ expect(body(res).error).toContain("more than the key's whole limit");+ });++ it("reports the plan balance and its reset when the team is short", async () => {+ checkCreditsMock.mockResolvedValue({+ allowed: false,+ remaining: 0,+ resetsAt: Date.UTC(2026, 11, 1),+ });++ const req = buildReq({+ path: "/v2/scrape",+ body: {},+ acuc: { api_key_id: 42 },+ });+ const { res } = await runMiddleware(req);++ expect(getApiKeySpendLimitMock).not.toHaveBeenCalled();+ expect(body(res)).toMatchObject({+ code: "insufficient_credits",+ requested_credits: 1,+ remaining_credits: 0,+ resets_at: "2026-12-01T00:00:00.000Z",+ });+ });++ it("falls back to the plan message when a covered refusal has no key limit", async () => {+ checkCreditsMock.mockResolvedValue({ allowed: false, remaining: 500 });+ getApiKeySpendLimitMock.mockResolvedValue(null);++ const req = buildReq({+ path: "/v2/scrape",+ body: {},+ acuc: { api_key_id: 42 },+ });+ const { res } = await runMiddleware(req);++ expect(body(res).code).toBe("insufficient_credits");+ });++ it("names the hosted MCP allowance on a connected-app refusal", async () => {+ checkCreditsMock.mockResolvedValue({+ allowed: false,+ remaining: 0,+ resetsAt: Date.UTC(2026, 10, 2, 12),+ });++ const req = buildReq({+ path: "/v2/scrape",+ body: {},+ auth: { team_id: "team_test", org_id: "org_test", hostedMcp: true },+ acuc: { api_key_id: 7 },+ });+ const { res } = await runMiddleware(+ req,+ checkCreditsMiddleware(undefined, undefined, { mcpCredits: true }),+ );++ expect(getApiKeySpendLimitMock).not.toHaveBeenCalled();+ expect(body(res)).toMatchObject({+ code: "mcp_credits_exhausted",+ resets_at: "2026-11-02T12:00:00.000Z",+ });+ });+});diff --git a/apps/api/src/db/schema/public.ts b/apps/api/src/db/schema/public.tsindex 0eacb9f01..43d20b846 100644--- a/apps/api/src/db/schema/public.ts+++ b/apps/api/src/db/schema/public.ts@@ -76,6 +76,8 @@ export const api_keys = pgTable(agent_provisioned: boolean("agent_provisioned").default(false),// API-key-scoped concurrency limit; null = key inherits the team limit onlyconcurrency: integer("concurrency"),+ credit_limit: integer("credit_limit"),+ credit_limit_interval: text("credit_limit_interval"),},table => [// Target of key_restriction_config's composite FK, which pins adiff --git a/apps/api/src/lib/api-key-spend-limit.ts b/apps/api/src/lib/api-key-spend-limit.tsnew file mode 100644index 000000000..834ca6029--- /dev/null+++ b/apps/api/src/lib/api-key-spend-limit.ts@@ -0,0 +1,30 @@+import { eq } from "drizzle-orm";+import { dbRr } from "../db/connection";+import * as schema from "../db/schema";+import { logger } from "./logger";++export type ApiKeySpendLimit = { credits: number; interval: string };++/**+ * The per-API-key spend limit set in the dashboard, or null when the key has+ * none or it can't be read. Only used to explain a refusal, so it fails soft.+ */+export async function getApiKeySpendLimit(+ apiKeyId: number,+): Promise<ApiKeySpendLimit | null> {+ try {+ const [row] = await dbRr+ .select({+ credits: schema.api_keys.credit_limit,+ interval: schema.api_keys.credit_limit_interval,+ })+ .from(schema.api_keys)+ .where(eq(schema.api_keys.id, apiKeyId))+ .limit(1);+ if (typeof row?.credits !== "number" || !row.interval) return null;+ return { credits: row.credits, interval: row.interval };+ } catch (error) {+ logger.warn("Failed to load API key spend limit", { apiKeyId, error });+ return null;+ }+}diff --git a/apps/api/src/routes/shared.ts b/apps/api/src/routes/shared.tsindex 2ff4eb5b1..be87e95b2 100644--- a/apps/api/src/routes/shared.ts+++ b/apps/api/src/routes/shared.ts@@ -30,6 +30,7 @@ import {CREDITS_FEATURE_ID,} from "../services/autumn/autumn.service";import { getTeamBalance } from "../services/autumn/usage";+import { getApiKeySpendLimit } from "../lib/api-key-spend-limit";import {ThirdPartyDataTermsRequiredError,ThirdPartyDataUnsupportedOptionError,@@ -266,20 +267,65 @@ export function checkCreditsMiddleware(}if (!res.headersSent &&- req.auth.team_id !== CREDIT_CHECK_EXEMPT_TEAM_ID+ req.auth.team_id !== CREDIT_CHECK_EXEMPT_TEAM_ID &&+ currencyName === "tokens") {return res.status(402).json({success: false,error:- "Insufficient " +- currencyName +- " to perform this request. For more " +- currencyName +- ", you can upgrade your plan at " +- (currencyName === "credits"- ? "https://firecrawl.dev/pricing or try changing the request limit to a lower value"- : "https://www.firecrawl.dev/extract#pricing") +- ".",+ "Insufficient tokens to perform this request. For more tokens, you can upgrade your plan at https://www.firecrawl.dev/extract#pricing.",+ });+ }+ if (+ !res.headersSent &&+ req.auth.team_id !== CREDIT_CHECK_EXEMPT_TEAM_ID+ ) {+ // Name the limit that refused the request: the balance alone can't+ // explain a refusal that leaves credits on the dashboard.+ const resetsAt = autumnResult.resetsAt+ ? new Date(autumnResult.resetsAt).toISOString()+ : undefined;+ if (gateFeatureId !== featureId) {+ return res.status(402).json({+ success: false,+ code: "mcp_credits_exhausted",+ requested_credits: requestedCredits,+ ...(resetsAt ? { resets_at: resetsAt } : {}),+ error: `Insufficient credits for this connected-app request. Hosted MCP calls (from apps such as ChatGPT, Claude or Codex) spend a daily MCP credit allowance before your plan credits, and together they can't cover this request${resetsAt ? `; it resets at ${resetsAt}` : ""}. To continue now, use the Firecrawl MCP server with an API key, which bills your team's credits directly, or upgrade your plan at https://firecrawl.dev/pricing.`,+ });+ }++ const apiKeyId = req.acuc?.api_key_id;+ const keyLimit =+ apiKeyId && autumnResult.remaining >= requestedCredits+ ? await getApiKeySpendLimit(apiKeyId)+ : null;+ if (keyLimit) {+ return res.status(402).json({+ success: false,+ code: "api_key_spend_limit",+ requested_credits: requestedCredits,+ remaining_credits: autumnResult.remaining,+ limit: {+ type: "api_key",+ credits: keyLimit.credits,+ interval: keyLimit.interval,+ },+ error:+ `This API key has reached its spend limit of ${keyLimit.credits} credits per ${keyLimit.interval}, while your team still has ${autumnResult.remaining} credits. ` ++ (requestedCredits > keyLimit.credits+ ? `This request can use up to ${requestedCredits} credits, more than the key's whole limit, so lower the request's limit or raise the key's limit on the API Keys page at https://www.firecrawl.dev/app/api-keys.`+ : `Raise or remove the key's limit on the API Keys page at https://www.firecrawl.dev/app/api-keys, use another key, or wait for the limit to reset next ${keyLimit.interval}.`),+ });+ }++ return res.status(402).json({+ success: false,+ code: "insufficient_credits",+ requested_credits: requestedCredits,+ remaining_credits: autumnResult.remaining,+ ...(resetsAt ? { resets_at: resetsAt } : {}),+ error: `Insufficient credits to perform this request: it can use up to ${requestedCredits} credits and your team has ${autumnResult.remaining} left${resetsAt ? `, with plan credits resetting at ${resetsAt}` : ""}. For more credits, you can upgrade your plan at https://firecrawl.dev/pricing or try changing the request limit to a lower value.`,});}}diff --git a/apps/api/src/services/autumn/autumn.service.ts b/apps/api/src/services/autumn/autumn.service.tsindex f9877eea6..ae6610b50 100644--- a/apps/api/src/services/autumn/autumn.service.ts+++ b/apps/api/src/services/autumn/autumn.service.ts@@ -520,6 +520,8 @@ export class AutumnService {}: TrackCreditsParams): Promise<{allowed: boolean;remaining: number;+ /** When the checked balance next resets, in epoch ms; absent when unknown. */+ resetsAt?: number;/** Set only for a Gateway account, funded by the platform that created it. */gatewayProvisioned?: boolean;} | null> {@@ -571,6 +573,7 @@ export class AutumnService {});const remaining = balance?.remaining ?? 0;+ const resetsAt = balance?.nextResetAt ?? undefined;logger.debug("Autumn checkCredits completed", {customerId,@@ -583,6 +586,7 @@ export class AutumnService {return {allowed,remaining,+ ...(resetsAt ? { resetsAt } : {}),...(gatewayProvisioned ? { gatewayProvisioned } : {}),};} catch (error) {