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
feat(api): refuse free-plan teams on paid-plan-only Exchange capabilities (#4716)
mrod9997504905318fe8
diff --git a/apps/api/src/services/alexandria/README.md b/apps/api/src/services/alexandria/README.mdindex ae5d257ba..da1bccead 100644--- a/apps/api/src/services/alexandria/README.md+++ b/apps/api/src/services/alexandria/README.md@@ -39,7 +39,13 @@ shape relays a provider error with the Exchange's status and `code`.Inline in the request (`retrieve.ts`): authorize through the Exchange(`/v1/provider-terms/requirements`, which refuses unknown providers) against-the organization's `organizationDataSourceAccess` flags, quote+the organization's `organizationDataSourceAccess` flags, then refuse a+free-plan team (Autumn rate-limit multiplier below the hobby floor) calling a+capability the Exchange lists in `paidPlanOnlyCapabilities` with 403+`paid_plan_required`, or with 503 `plan_verification_unavailable` when the plan+cannot be known (no org, preview team, Autumn error): this read fails closed+where the rate limiter fails open (Benzinga Schedule C.4: full text, WIIM,+analyst ratings), quote(`/v1/retrieve/quote`), reserve with Autumn (`lockCredits`, lock`alexandria_<chargeId>`), execute `/v1/retrieve` with the budget and deadlineheaders, settle the receipt (`finalizeCreditsLock`), enqueue the ledger writediff --git a/apps/api/src/services/alexandria/access.test.ts b/apps/api/src/services/alexandria/access.test.tsindex 8c847ed3c..4fa79ca59 100644--- a/apps/api/src/services/alexandria/access.test.ts+++ b/apps/api/src/services/alexandria/access.test.ts@@ -1,8 +1,11 @@-const mocks = vi.hoisted(() => ({ request: vi.fn() }));+const mocks = vi.hoisted(() => ({ request: vi.fn(), multiplier: vi.fn() }));vi.mock("../../config", () => ({config: { USE_DB_AUTHENTICATION: true, FIRECRAWL_DASHBOARD_URL: "https://d" },}));vi.mock("./client", () => ({ exchangeRequest: mocks.request }));+vi.mock("../autumn/autumn.service", () => ({+ autumnService: { getKnownRateLimitMultiplier: mocks.multiplier },+}));import { authorizeProviders } from "./access";const calls = [@@ -319,3 +322,132 @@ it("does not discard other acceptances when a timestamp has an unexpected shape");expect(await authorizeProviders("team", calls, {}, "org")).toBeUndefined();});++describe("paid-plan-only capabilities", () => {+ const enabled = {+ organizationDataSourceAccess: {+ benzinga: {+ status: "enabled",+ termsKey: "benzinga",+ termsVersion: "C-1",+ },+ },+ };+ const wiim = [+ { provider: "benzinga", capability: "news/wiims", options: {} },+ ];+ const pressReleases = [+ { provider: "benzinga", capability: "news/press-releases", options: {} },+ ];+ const requirements = (paidPlanOnlyCapabilities?: string[]) => ({+ status: 200,+ body: {+ providers: [+ {+ provider: "benzinga",+ required: true,+ terms: { key: "benzinga", version: "C-1" },+ ...(paidPlanOnlyCapabilities ? { paidPlanOnlyCapabilities } : {}),+ },+ ],+ },+ });++ it("refuses a free-plan team calling a paid-plan-only capability, before any quote", async () => {+ mocks.request.mockResolvedValue(+ requirements(["news/wiims", "news/search"]),+ );+ mocks.multiplier.mockResolvedValue(1);+ const denied = await authorizeProviders("team", wiim, enabled, "org");+ expect(denied?.status).toBe(403);+ expect(denied?.body).toEqual(+ expect.objectContaining({ code: "paid_plan_required" }),+ );+ expect(String((denied?.body as { error: string }).error)).toContain(+ "benzinga/news/wiims",+ );+ expect(mocks.multiplier).toHaveBeenCalledWith("team", "org");+ // One requirements read, and nothing else: no quote, no execution.+ expect(mocks.request).toHaveBeenCalledTimes(1);+ });++ it("admits a paid-plan team, and does not consult the plan for an ungated capability", async () => {+ mocks.request.mockResolvedValue(requirements(["news/wiims"]));+ mocks.multiplier.mockResolvedValue(10);+ expect(+ await authorizeProviders("team", wiim, enabled, "org"),+ ).toBeUndefined();+ mocks.multiplier.mockClear();+ mocks.multiplier.mockResolvedValue(1);+ expect(+ await authorizeProviders("team", pressReleases, enabled, "org"),+ ).toBeUndefined();+ expect(mocks.multiplier).not.toHaveBeenCalled();+ });++ it("lets a team that bypasses credit checks through, and treats a missing field as ungated", async () => {+ mocks.request.mockResolvedValue(requirements(["news/wiims"]));+ mocks.multiplier.mockResolvedValue(1);+ expect(+ await authorizeProviders(+ "team",+ wiim,+ { ...enabled, bypassCreditChecks: true },+ "org",+ ),+ ).toBeUndefined();+ // An Exchange deployed before it published the field: nothing to gate on.+ mocks.request.mockResolvedValue(requirements());+ expect(+ await authorizeProviders("team", wiim, enabled, "org"),+ ).toBeUndefined();+ });++ it("still requires the agreement first: an unaccepted paid team is refused on terms, not plan", async () => {+ mocks.request.mockResolvedValue(requirements(["news/wiims"]));+ mocks.multiplier.mockResolvedValue(10);+ const denied = await authorizeProviders("team", wiim, {}, null);+ expect(denied?.status).toBe(403);+ expect(denied?.body).not.toEqual(+ expect.objectContaining({ code: "paid_plan_required" }),+ );+ });+});++it("fails closed when the plan cannot be known: no org, a preview team or an Autumn error", async () => {+ mocks.request.mockResolvedValue({+ status: 200,+ body: {+ providers: [+ {+ provider: "benzinga",+ required: true,+ terms: { key: "benzinga", version: "C-1" },+ paidPlanOnlyCapabilities: ["news/wiims"],+ },+ ],+ },+ });+ const enabled = {+ organizationDataSourceAccess: {+ benzinga: {+ status: "enabled",+ termsKey: "benzinga",+ termsVersion: "C-1",+ },+ },+ };+ const wiim = [+ { provider: "benzinga", capability: "news/wiims", options: {} },+ ];+ // The service answers null for every "cannot know" case; the gate never+ // treats that as paid.+ mocks.multiplier.mockResolvedValue(null);+ const denied = await authorizeProviders("team", wiim, enabled, null);+ expect(denied?.status).toBe(503);+ expect(denied?.body).toEqual(+ expect.objectContaining({ code: "plan_verification_unavailable" }),+ );+ expect(mocks.multiplier).toHaveBeenCalledWith("team", null);+ expect(mocks.request).toHaveBeenCalledTimes(1);+});diff --git a/apps/api/src/services/alexandria/access.ts b/apps/api/src/services/alexandria/access.tsindex 3f75f2956..c4f8c50b4 100644--- a/apps/api/src/services/alexandria/access.ts+++ b/apps/api/src/services/alexandria/access.ts@@ -5,6 +5,8 @@ import { getThirdPartyDataTermsRequiredResponse } from "../../lib/exchange";import { exchangeRequest } from "./client";import { refusal, type ExchangeResponse, type ProviderCall } from "./contracts";import { acceptedProviders, type LedgerAcceptance } from "./terms";+import { autumnService } from "../autumn/autumn.service";+import { HOBBY_RATE_LIMIT_MULTIPLIER } from "../rate-limiter";const requirementsSchema = z.object({providers: z.array(@@ -19,6 +21,10 @@ const requirementsSchema = z.object({}).passthrough().nullable(),+ // Capabilities whose licence allows the payload only on a paid request+ // (Exchange Capability.paidPlanOnly). Optional so an Exchange deployed+ // before it published the field still authorizes.+ paidPlanOnlyCapabilities: z.array(z.string()).optional(),}),),});@@ -121,5 +127,50 @@ export async function authorizeProviders(body: getThirdPartyDataTermsRequiredResponse(item.terms),};}++ const paidPlanOnly = new Set(+ parsed.data.providers.flatMap(item =>+ (item.paidPlanOnlyCapabilities ?? []).map(+ capability => `${item.provider}/${capability}`,+ ),+ ),+ );+ const gated = calls.filter(call =>+ paidPlanOnly.has(`${call.provider}/${call.capability}`),+ );+ // A licence that permits the payload only in response to a paid request+ // (Benzinga Schedule C.4: full text, WIIM, analyst ratings). Credits alone+ // do not prove payment, because a free team spends signup credits; the plan+ // does. Autumn's rate-limit multiplier is 1 on the free plan and at least the+ // hobby floor on every paid one. It comes from the entity read the rate+ // limiter caches per team, so a warm cache costs nothing and a cold one+ // costs the fetch the limiter would have made anyway. This gate fails+ // closed: a team whose plan cannot be known (no org to bill, a preview team,+ // an Autumn error) is refused, where the rate limiter would fail open, since+ // delivering licensed content to a possibly free team is the mistake the+ // licence forbids. Internal teams that bypass credit checks are not+ // customers and pass.+ if (gated.length > 0 && flags?.bypassCreditChecks !== true) {+ const multiplier = await autumnService.getKnownRateLimitMultiplier(+ teamId,+ orgId,+ );+ if (multiplier === null)+ return refusal(+ 503,+ "Your plan could not be verified for a paid-plan-only capability. No provider was executed.",+ { code: "plan_verification_unavailable" },+ );+ if (multiplier < HOBBY_RATE_LIMIT_MULTIPLIER) {+ const addresses = [+ ...new Set(gated.map(call => `${call.provider}/${call.capability}`)),+ ].join(", ");+ return refusal(+ 403,+ `${addresses} ${gated.length === 1 ? "is" : "are"} available on paid plans only. Upgrade at ${config.FIRECRAWL_DASHBOARD_URL ?? "https://www.firecrawl.dev"} to use ${gated.length === 1 ? "it" : "them"}. No provider was executed.`,+ { code: "paid_plan_required" },+ );+ }+ }return undefined;}diff --git a/apps/api/src/services/autumn/__tests__/autumn.service.test.ts b/apps/api/src/services/autumn/__tests__/autumn.service.test.tsindex d6a514f15..327d7b9fa 100644--- a/apps/api/src/services/autumn/__tests__/autumn.service.test.ts+++ b/apps/api/src/services/autumn/__tests__/autumn.service.test.ts@@ -2293,3 +2293,62 @@ describe("provisioning by route", () => {},);});++describe("getKnownRateLimitMultiplier (fail-closed plan reads)", () => {+ it("isolates cached entitlements by organization while sharing reads within an organization", async () => {+ const svc = makeService();+ mockEntityGet+ .mockResolvedValueOnce({ balances: { rate_limits: { granted: 25 } } })+ .mockResolvedValueOnce({ balances: { rate_limits: { granted: 1 } } });+ expect(await svc.getRateLimitMultiplier("team-1", "org-a")).toBe(25);+ expect(await svc.getKnownRateLimitMultiplier("team-1", "org-b")).toBe(1);+ expect(await svc.getKnownRateLimitMultiplier("team-1", "org-a")).toBe(25);+ expect(await svc.getRateLimitMultiplier("team-1", "org-b")).toBe(1);+ expect(mockEntityGet).toHaveBeenCalledTimes(2);+ expect(mockEntityGet).toHaveBeenNthCalledWith(1, { customerId: "org-a", entityId: "team-1" });+ expect(mockEntityGet).toHaveBeenNthCalledWith(2, { customerId: "org-b", entityId: "team-1" });+ });++ it("refuses a missing organization even after caching a paid entitlement", async () => {+ const svc = makeService();+ mockEntityGet.mockResolvedValue({ balances: { rate_limits: { granted: 25 } } });+ expect(await svc.getKnownRateLimitMultiplier("team-1", "org-1")).toBe(25);+ expect(await svc.getKnownRateLimitMultiplier("team-1", null)).toBeNull();+ expect(mockEntityGet).toHaveBeenCalledTimes(1);+ });++ it("answers the entitled multiplier, and 1 when the entity is missing or has no balance", async () => {+ const svc = makeService();+ mockEntityGet.mockResolvedValue({+ balances: { rate_limits: { granted: 25 } },+ });+ expect(await svc.getKnownRateLimitMultiplier("team-1", "org-1")).toBe(25);++ const missing = makeService();+ mockEntityGet.mockRejectedValue({ statusCode: 404 });+ expect(await missing.getKnownRateLimitMultiplier("team-2", "org-1")).toBe(+ 1,+ );++ const bare = makeService();+ mockEntityGet.mockResolvedValue({ balances: {} });+ expect(await bare.getKnownRateLimitMultiplier("team-3", "org-1")).toBe(1);+ });++ it("answers null, never the fail-open fallback, when Autumn errors, when there is no org, or for a preview team", async () => {+ const svc = makeService();+ mockEntityGet.mockRejectedValue({ statusCode: 500 });+ expect(await svc.getKnownRateLimitMultiplier("team-1", "org-1")).toBeNull();+ // The throttling read still fails open on the same outage: the two callers+ // want opposite failure directions from one entity read.+ expect(await svc.getRateLimitMultiplier("team-1", "org-1")).toBe(2500);++ mockEntityGet.mockResolvedValue({+ balances: { rate_limits: { granted: 25 } },+ });+ expect(await svc.getKnownRateLimitMultiplier("team-4", null)).toBeNull();+ expect(+ await svc.getKnownRateLimitMultiplier("preview_x", "org-1"),+ ).toBeNull();+ });+});diff --git a/apps/api/src/services/autumn/autumn.service.ts b/apps/api/src/services/autumn/autumn.service.tsindex 522a437c4..1ad5109b2 100644--- a/apps/api/src/services/autumn/autumn.service.ts+++ b/apps/api/src/services/autumn/autumn.service.ts@@ -810,7 +810,7 @@ export class AutumnService {// and rate-limit gating on every scrape/crawl/browser request don't fan out// to Autumn each time. Both the CONCURRENCY limit and the rate-limit// multiplier come from a single entity.get, so one cache entry (and one- // Autumn round-trip per team per TTL window) serves both callers.+ // Autumn round-trip per organization/team per TTL window) serves both callers.private entityLimitsCache = new BoundedMap<string,{@@ -851,14 +851,96 @@ export class AutumnService {concurrency: number | null;rateLimitMultiplier: number | null;}> {+ const read = await this.readEntityLimits(teamId, orgId);+ switch (read.outcome) {+ case "unconfigured":+ return { concurrency: null, rateLimitMultiplier: null };+ case "known":+ return {+ concurrency: read.concurrency,+ rateLimitMultiplier: read.rateLimitMultiplier,+ };+ case "no_org":+ // No org means no Autumn entity to ask about. Fail OPEN on the high+ // limits, the same answer this method already gives when it cannot+ // reach Autumn β and the same one the service's own org lookup+ // produced by throwing into the catch below. Not cached, for the same+ // reason.+ logger.error(+ "Autumn getEntityLimits has no org for the team, falling back to high limits",+ { teamId },+ );+ return {+ concurrency: AutumnService.ERROR_FALLBACK_CONCURRENCY,+ rateLimitMultiplier: AutumnService.ERROR_FALLBACK_RATE_MULTIPLIER,+ };+ case "error":+ // Any other failure means we couldn't reach Autumn / it errored. Fail+ // OPEN with high limits rather than throttling the team to the low+ // defaults. Deliberately not cached, so we retry Autumn on the next+ // request instead of pinning the team to the fallback for the TTL+ // window.+ logger.error(+ "Autumn getEntityLimits failed β billing API may be unavailable, falling back to high limits",+ { teamId, error: read.error },+ );+ return {+ concurrency: AutumnService.ERROR_FALLBACK_CONCURRENCY,+ rateLimitMultiplier: AutumnService.ERROR_FALLBACK_RATE_MULTIPLIER,+ };+ }+ }++ /**+ * The team's entitled rate-limit multiplier when Autumn can actually answer,+ * or null when it cannot: no Autumn client, a preview team, a team with no+ * org to bill against, or an Autumn error. For a gate that must fail closed,+ * such as a licence that permits a payload only in response to a paid+ * request; getRateLimitMultiplier fails open because throttling a real team+ * during a billing outage is the worse mistake there. A missing entity or an+ * absent balance is a real answer, 1: the free plan.+ */+ async getKnownRateLimitMultiplier(+ teamId: string,+ orgId: string | null,+ ): Promise<number | null> {+ if (!orgId) return null;+ const read = await this.readEntityLimits(teamId, orgId);+ return read.outcome === "known" ? (read.rateLimitMultiplier ?? 1) : null;+ }++ /**+ * One entity read behind both getEntityLimits and+ * getKnownRateLimitMultiplier. It reports what happened rather than picking+ * a fallback, so each caller can fail in its own direction. Only "known" is+ * an answer (an entity, or a 404 meaning no elevated entitlement) and only+ * "known" is cached; the other outcomes are retried on the next request.+ */+ private async readEntityLimits(+ teamId: string,+ orgId: string | null,+ ): Promise<+ | { outcome: "unconfigured" }+ | { outcome: "no_org" }+ | { outcome: "error"; error: unknown }+ | {+ outcome: "known";+ concurrency: number | null;+ rateLimitMultiplier: number | null;+ }+ > {if (!autumnClient || this.isPreviewTeam(teamId)) {- return { concurrency: null, rateLimitMultiplier: null };+ return { outcome: "unconfigured" };}+ if (!orgId) return { outcome: "no_org" };++ const cacheKey = `${orgId}:${teamId}`;const now = Date.now();- const cached = this.entityLimitsCache.get(teamId);+ const cached = this.entityLimitsCache.get(cacheKey);if (cached && cached.expiresAt > now) {return {+ outcome: "known",concurrency: cached.concurrency,rateLimitMultiplier: cached.rateLimitMultiplier,};@@ -868,29 +950,14 @@ export class AutumnService {concurrency: number | null,rateLimitMultiplier: number | null,) => {- this.entityLimitsCache.set(teamId, {+ this.entityLimitsCache.set(cacheKey, {concurrency,rateLimitMultiplier,expiresAt: now + AutumnService.ENTITY_LIMITS_TTL_MS,});- return { concurrency, rateLimitMultiplier };+ return { outcome: "known" as const, concurrency, rateLimitMultiplier };};- // No org means no Autumn entity to ask about. Fail OPEN on the high- // limits, the same answer this method already gives when it cannot reach- // Autumn β and the same one the service's own org lookup produced by- // throwing into the catch below. Not cached, for the same reason.- if (!orgId) {- logger.error(- "Autumn getEntityLimits has no org for the team, falling back to high limits",- { teamId },- );- return {- concurrency: AutumnService.ERROR_FALLBACK_CONCURRENCY,- rateLimitMultiplier: AutumnService.ERROR_FALLBACK_RATE_MULTIPLIER,- };- }-try {const entity: any = await autumnClient.entities.get({customerId: orgId,@@ -912,23 +979,11 @@ export class AutumnService {return store(concurrency, rateLimitMultiplier);} catch (error) {- const status = this.getErrorStatus(error);// 404 = the entity genuinely doesn't exist in Autumn (not an error):// fall back low, and cache it so we don't re-query for a team we know is// absent.- if (status === 404) return store(null, null);- // Any other failure means we couldn't reach Autumn / it errored. Fail- // OPEN with high limits rather than throttling the team to the low- // defaults. Deliberately not cached, so we retry Autumn on the next- // request instead of pinning the team to the fallback for the TTL window.- logger.error(- "Autumn getEntityLimits failed β billing API may be unavailable, falling back to high limits",- { teamId, error },- );- return {- concurrency: AutumnService.ERROR_FALLBACK_CONCURRENCY,- rateLimitMultiplier: AutumnService.ERROR_FALLBACK_RATE_MULTIPLIER,- };+ if (this.getErrorStatus(error) === 404) return store(null, null);+ return { outcome: "error", error };}}