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): forward caller location on Alexandria terms checks (#5471)
Developers Digest7272453aed0f
diff --git a/apps/api/src/__tests__/routes/exchange-agent-managed-key.routes.test.ts b/apps/api/src/__tests__/routes/exchange-agent-managed-key.routes.test.tsindex 4ceddcd46..84f57f0b3 100644--- a/apps/api/src/__tests__/routes/exchange-agent-managed-key.routes.test.ts+++ b/apps/api/src/__tests__/routes/exchange-agent-managed-key.routes.test.ts@@ -321,10 +321,12 @@ describe("hosted MCP keys on the Exchange routes the agent calls", () => {expect(mocks.exchangeRequest.mock.calls.map(([arg]) => arg.path)).toEqual(["/v1/provider-terms/requirements"],);- expect(mocks.acceptedProviders).toHaveBeenCalledWith(- "team-mcp",- "org-mcp",- );+ const ledgerCall = mocks.acceptedProviders.mock.calls[0];+ expect(ledgerCall.slice(0, 2)).toEqual(["team-mcp", "org-mcp"]);+ expect(ledgerCall[3]).toEqual({+ clientIp: expect.any(String),+ billingCountry: undefined,+ });});it("blocks retrieve when access is disabled for the key's organization", async () => {diff --git a/apps/api/src/routes/exchange.ts b/apps/api/src/routes/exchange.tsindex 2fccecd0e..208c75a1f 100644--- a/apps/api/src/routes/exchange.ts+++ b/apps/api/src/routes/exchange.ts@@ -266,6 +266,8 @@ async function providerTermsAcceptController(req: Request, res: Response) {? null: String(authedReq.acuc.api_key_id)),body: body.data,+ clientIp: authedReq.ip,+ billingCountry: await billingCountryForTeam(authedReq.auth.team_id),});return res.status(response.status).json(response.body);}diff --git a/apps/api/src/services/alexandria/access.test.ts b/apps/api/src/services/alexandria/access.test.tsindex e3a320b16..2b5a9b713 100644--- a/apps/api/src/services/alexandria/access.test.ts+++ b/apps/api/src/services/alexandria/access.test.ts@@ -33,6 +33,44 @@ it("refuses a provider the Exchange does not know before any quote or execution");});+it("forwards caller location when the ledger shows the current agreement", async () => {+ mocks.request.mockImplementation(async ({ path }) =>+ String(path).includes("requirements")+ ? requirement(true)+ : {+ status: 200,+ body: {+ providers: [+ {+ provider: "fred",+ revoked: false,+ version: "2026-01",+ textHash: null,+ acceptedAt: "2026-10-08T12:00:00Z",+ },+ ],+ },+ },+ );+ expect(+ await authorizeProviders("team", calls, {}, "org", "203.0.113.7", "DE"),+ ).toBeUndefined();+ expect(mocks.request).toHaveBeenCalledWith(+ expect.objectContaining({+ path: "/v1/provider-terms/requirements",+ clientIp: "203.0.113.7",+ billingCountry: "DE",+ }),+ );+ expect(mocks.request).toHaveBeenCalledWith(+ expect.objectContaining({+ path: "/v1/provider-terms/status?organizationId=org",+ clientIp: "203.0.113.7",+ billingCountry: "DE",+ }),+ );+});+it("requires the organization to hold the current agreement when terms are required", async () => {mocks.request.mockResolvedValue(requirement(true));const stale = {diff --git a/apps/api/src/services/alexandria/access.ts b/apps/api/src/services/alexandria/access.tsindex 960831a3e..6adfd742e 100644--- a/apps/api/src/services/alexandria/access.ts+++ b/apps/api/src/services/alexandria/access.ts@@ -87,7 +87,10 @@ export async function authorizeProviders(item.terms &&orgId !== null) {- ledger ??= await acceptedProviders(teamId, orgId);+ ledger ??= await acceptedProviders(teamId, orgId, undefined, {+ clientIp,+ billingCountry,+ });const accepted = ledger.get(item.provider);if (matchesAcceptance(accepted, item.terms) &&@@ -111,7 +114,10 @@ export async function authorizeProviders()continue;if (orgId !== null) {- ledger ??= await acceptedProviders(teamId, orgId);+ ledger ??= await acceptedProviders(teamId, orgId, undefined, {+ clientIp,+ billingCountry,+ });const accepted = ledger.get(item.provider);if (matchesAcceptance(accepted, item.terms)) continue;}diff --git a/apps/api/src/services/alexandria/terms.test.ts b/apps/api/src/services/alexandria/terms.test.tsindex bdc6ea63b..8da8b4dc1 100644--- a/apps/api/src/services/alexandria/terms.test.ts+++ b/apps/api/src/services/alexandria/terms.test.ts@@ -1,6 +1,12 @@-const mocks = vi.hoisted(() => ({ request: vi.fn() }));+const mocks = vi.hoisted(() => ({+ request: vi.fn(),+ billingCountry: vi.fn(async (): Promise<string | undefined> => undefined),+}));vi.mock("./client", () => ({ exchangeRequest: mocks.request }));-import { acceptProviderTerms } from "./terms";+vi.mock("../../lib/billing-country", () => ({+ billingCountryForTeam: mocks.billingCountry,+}));+import { acceptProviderTerms, hasLedgerAcceptance } from "./terms";const terms = { key: "shopify", version: "2026-01", digest: "a".repeat(64) };const input = {@@ -74,3 +80,201 @@ it("still rejects stale explicit acceptance when Exchange terms are optional", a).toBe(409);expect(mocks.request).toHaveBeenCalledTimes(1);});++const peopleDataLabs = {+ ...input,+ clientIp: "203.0.113.7",+ billingCountry: "DE",+ body: { ...input.body, provider: "peopledatalabs" },+};++it("accepts country-scoped terms when the caller's location makes them required", async () => {+ mocks.request+ .mockResolvedValueOnce({+ status: 200,+ body: {+ providers: [+ {+ provider: "peopledatalabs",+ required: true,+ exchangeRequired: false,+ terms,+ },+ ],+ },+ })+ .mockResolvedValueOnce({+ status: 201,+ body: { id: "event", occurred_at: "2026-10-08T12:00:00Z" },+ });++ expect((await acceptProviderTerms(peopleDataLabs)).status).toBe(200);+ expect(mocks.request).toHaveBeenNthCalledWith(+ 1,+ expect.objectContaining({+ path: "/v1/provider-terms/requirements",+ clientIp: "203.0.113.7",+ billingCountry: "DE",+ }),+ );+ expect(mocks.request).toHaveBeenNthCalledWith(+ 2,+ expect.objectContaining({+ path: "/v1/provider-terms/events",+ clientIp: "203.0.113.7",+ billingCountry: "DE",+ }),+ );+});++it("rejects acceptance when the caller's country requires no agreement", async () => {+ mocks.request.mockResolvedValueOnce({+ status: 200,+ body: {+ providers: [+ {+ provider: "peopledatalabs",+ required: false,+ exchangeRequired: false,+ terms: null,+ },+ ],+ },+ });++ const response = await acceptProviderTerms({+ ...peopleDataLabs,+ clientIp: "198.51.100.8",+ billingCountry: "US",+ });+ expect(response.status).toBe(400);+ expect(response.body).toMatchObject({+ error: "peopledatalabs requires no agreement.",+ });+ expect(mocks.request).toHaveBeenCalledTimes(1);+ expect(mocks.request).toHaveBeenCalledWith(+ expect.objectContaining({+ path: "/v1/provider-terms/requirements",+ clientIp: "198.51.100.8",+ billingCountry: "US",+ }),+ );+});++const statusPath = "/v1/provider-terms/status?organizationId=org";++function ledgerExchange(requirements: {+ required: boolean;+ terms: typeof terms | null;+}) {+ return async ({ path }: { path: string }) => {+ if (path === "/v1/provider-terms/requirements") {+ return {+ status: 200,+ body: {+ providers: [{ provider: "peopledatalabs", ...requirements }],+ },+ };+ }+ if (path === statusPath) {+ return {+ status: 200,+ body: {+ providers: [+ {+ provider: "peopledatalabs",+ revoked: false,+ version: terms.version,+ textHash: terms.digest,+ acceptedAt: "2026-10-08T12:00:00Z",+ },+ ],+ },+ };+ }+ throw new Error(`unexpected Exchange path ${path}`);+ };+}++it("reads the ledger for the caller's country", async () => {+ mocks.request.mockImplementation(ledgerExchange({ required: true, terms }));++ await expect(+ hasLedgerAcceptance({+ teamId: "team",+ orgId: "org",+ provider: "peopledatalabs",+ timeoutMs: 1000,+ clientIp: "203.0.113.7",+ billingCountry: "DE",+ }),+ ).resolves.toBe(true);+ expect(mocks.request).toHaveBeenCalledWith(+ expect.objectContaining({+ path: "/v1/provider-terms/requirements",+ clientIp: "203.0.113.7",+ billingCountry: "DE",+ }),+ );+ expect(mocks.request).toHaveBeenCalledWith(+ expect.objectContaining({+ path: statusPath,+ clientIp: "203.0.113.7",+ billingCountry: "DE",+ }),+ );+});++it("resolves the team's billing country when the caller does not pass one", async () => {+ mocks.billingCountry.mockResolvedValueOnce("DE");+ mocks.request.mockImplementation(ledgerExchange({ required: true, terms }));++ await expect(+ hasLedgerAcceptance({+ teamId: "team",+ orgId: "org",+ provider: "peopledatalabs",+ timeoutMs: 1000,+ clientIp: "203.0.113.7",+ }),+ ).resolves.toBe(true);+ expect(mocks.billingCountry).toHaveBeenCalledWith("team");+ expect(mocks.request).toHaveBeenCalledWith(+ expect.objectContaining({+ path: "/v1/provider-terms/requirements",+ clientIp: "203.0.113.7",+ billingCountry: "DE",+ }),+ );+ expect(mocks.request).toHaveBeenCalledWith(+ expect.objectContaining({+ path: statusPath,+ clientIp: "203.0.113.7",+ billingCountry: "DE",+ }),+ );+});++it("does not treat missing country-scoped terms as accepted", async () => {+ mocks.request.mockImplementation(+ ledgerExchange({ required: false, terms: null }),+ );++ await expect(+ hasLedgerAcceptance({+ teamId: "team",+ orgId: "org",+ provider: "peopledatalabs",+ timeoutMs: 1000,+ clientIp: "198.51.100.8",+ billingCountry: "US",+ }),+ ).resolves.toBe(false);+ expect(mocks.request).toHaveBeenCalledWith(+ expect.objectContaining({+ path: statusPath,+ clientIp: "198.51.100.8",+ billingCountry: "US",+ }),+ );+});diff --git a/apps/api/src/services/alexandria/terms.ts b/apps/api/src/services/alexandria/terms.tsindex b15afc60b..ea2d07f9a 100644--- a/apps/api/src/services/alexandria/terms.ts+++ b/apps/api/src/services/alexandria/terms.ts@@ -1,4 +1,5 @@import { z } from "zod";+import { billingCountryForTeam } from "../../lib/billing-country";import { exchangeRequest } from "./client";import { refusal, type ExchangeResponse } from "./contracts";@@ -89,15 +90,34 @@ export function acceptedAfter();}+type CallerLocation = { clientIp?: string; billingCountry?: string };++// IP is forwarded only when the caller already has it. Billing country is per+// team, so it can be resolved here when the caller did not supply one.+async function callerLocation(input: {+ teamId: string;+ clientIp?: string;+ billingCountry?: string;+}): Promise<CallerLocation> {+ return {+ clientIp: input.clientIp,+ billingCountry:+ input.billingCountry ?? (await billingCountryForTeam(input.teamId)),+ };+}+export async function acceptedProviders(teamId: string,orgId: string,timeoutMs = TIMEOUT_MS,+ location?: CallerLocation,): Promise<Map<string, LedgerAcceptance>> {const response = await exchangeRequest({teamId,path: `/v1/provider-terms/status?organizationId=${encodeURIComponent(orgId)}`,timeoutMs,+ clientIp: location?.clientIp,+ billingCountry: location?.billingCountry,}).catch(() => undefined);const parsed =response?.status === 200@@ -122,6 +142,10 @@ export async function acceptedProviders(* provider's current terms, recorded after `revocation.disabledAt` when an* admin revocation has to be lifted. The API's accept route records* acceptance only there. Any failure reads as not accepted.+ *+ * Country-scoped terms (required only in some countries) are decided from the+ * caller's IP, when the caller has one, and the team's billing country.+ * Without them the Exchange treats the caller as outside every required country.*/export async function hasLedgerAcceptance(input: {teamId: string;@@ -129,15 +153,22 @@ export async function hasLedgerAcceptance(input: {provider: string;revocation?: { disabledAt: unknown };timeoutMs: number;+ /** Caller's IP as the API sees it; Exchange resolves the country from it. */+ clientIp?: string;+ /** Country on the team's billing address, when the caller already has it. */+ billingCountry?: string;}): Promise<boolean> {+ const location = await callerLocation(input);const [requirements, ledger] = await Promise.all([exchangeRequest({teamId: input.teamId,path: "/v1/provider-terms/requirements",body: { providers: [input.provider] },timeoutMs: input.timeoutMs,+ clientIp: location.clientIp,+ billingCountry: location.billingCountry,}).catch(() => undefined),- acceptedProviders(input.teamId, input.orgId, input.timeoutMs),+ acceptedProviders(input.teamId, input.orgId, input.timeoutMs, location),]);const parsed =requirements?.status === 200@@ -161,13 +192,20 @@ export async function acceptProviderTerms(input: {orgId: string;apiKeyId: string | null;body: AcceptTerms;+ /** Caller's IP as the API sees it; Exchange resolves the country from it. */+ clientIp?: string;+ /** Country on the team's billing address, when it has one. */+ billingCountry?: string;}): Promise<ExchangeResponse> {const { provider, version, digest, agent } = input.body;+ const location = await callerLocation(input);const requirements = await exchangeRequest({teamId: input.teamId,path: "/v1/provider-terms/requirements",body: { providers: [provider] },timeoutMs: TIMEOUT_MS,+ clientIp: location.clientIp,+ billingCountry: location.billingCountry,}).catch(() => undefined);if (requirements?.status === 404)return refusal(404, "Unknown provider.", { code: "unknown_provider" });@@ -213,6 +251,8 @@ export async function acceptProviderTerms(input: {surface: "api",},timeoutMs: TIMEOUT_MS,+ clientIp: location.clientIp,+ billingCountry: location.billingCountry,}).catch(() => undefined);const recorded = z.object({ id: z.string(), occurred_at: z.string() })