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): admit Exchange-served blocklisted URLs in v2 batch scrape (#4999)
Gergő Móriczbd654c50719c
diff --git a/apps/api/src/__tests__/snips/v2/batch-scrape-exchange.test.ts b/apps/api/src/__tests__/snips/v2/batch-scrape-exchange.test.tsnew file mode 100644index 000000000..4906eb49a--- /dev/null+++ b/apps/api/src/__tests__/snips/v2/batch-scrape-exchange.test.ts@@ -0,0 +1,269 @@+/**+ * v2 batch scrape admits blocklisted URLs the Exchange can serve, the same+ * way single scrape does, and refuses the rest: with the terms error when+ * unaccepted terms are what keeps a URL out, else as an unsupported site.+ */++const mocks = vi.hoisted(() => ({+ isUrlBlocked: vi.fn((url: string) =>+ ["profiles.example", "blocked.example"].includes(new URL(url).hostname),+ ),+ exchangeRequest: vi.fn(),+ addScrapeJobs: vi.fn(),+ emitRejectedScrapeActivityEvents: vi.fn(),+}));++vi.mock(+ "../../../scraper/WebScraper/utils/blocklist",+ async importOriginal => ({+ ...(await importOriginal<+ typeof import("../../../scraper/WebScraper/utils/blocklist")+ >()),+ isUrlBlocked: mocks.isUrlBlocked,+ }),+);+vi.mock("../../../services/alexandria/client", async importOriginal => ({+ ...(await importOriginal<+ typeof import("../../../services/alexandria/client")+ >()),+ exchangeRequest: mocks.exchangeRequest,+}));+vi.mock("../../../services/queue-jobs", async importOriginal => ({+ ...(await importOriginal<typeof import("../../../services/queue-jobs")>()),+ addScrapeJobs: mocks.addScrapeJobs,+}));+vi.mock("../../../lib/siem-logging", async importOriginal => ({+ ...(await importOriginal<typeof import("../../../lib/siem-logging")>()),+ emitRejectedScrapeActivityEvents: mocks.emitRejectedScrapeActivityEvents,+}));+vi.mock("../../../lib/crawl-redis", async importOriginal => ({+ ...(await importOriginal<typeof import("../../../lib/crawl-redis")>()),+ saveCrawl: vi.fn(),+ markCrawlActive: vi.fn(),+ finishCrawlKickoff: vi.fn(),+ lockURLs: vi.fn().mockResolvedValue(true),+ addCrawlJobs: vi.fn(),+}));+vi.mock("../../../services/worker/nuq-router", async importOriginal => ({+ ...(await importOriginal<+ typeof import("../../../services/worker/nuq-router")+ >()),+ crawlGroup: { addGroup: vi.fn() },+ resolveNewGroupBackend: vi.fn().mockResolvedValue(undefined),+}));+vi.mock("../../../services/logging/log_job", async importOriginal => ({+ ...(await importOriginal<+ typeof import("../../../services/logging/log_job")+ >()),+ logRequest: vi.fn(),+}));++import { batchScrapeController } from "../../../controllers/v2/batch-scrape";+import { config } from "../../../config";+import {+ clearExchangeProvidersForTest,+ setExchangeProvidersForTest,+ ThirdPartyDataTermsRequiredError,+} from "../../../lib/exchange";+import { UnsupportedSiteError } from "../../../lib/error";+import { UNSUPPORTED_SITE_MESSAGE } from "../../../lib/strings";+import { buildFallbackList } from "../../../scraper/scrapeURL/engines";++describe("v2 batch scrape of blocklisted URLs", () => {+ const TERMS = { key: "acme", version: "2026-01-01" };+ const BLOCKED_URL = "https://profiles.example/person/example-person";+ const UNSERVED_URL = "https://blocked.example/person/example-person";+ const OPEN_URL = "https://open.example/page";++ const ACCEPTED_FLAGS = {+ organizationDataSourceAccess: {+ acme: {+ status: "enabled",+ termsKey: TERMS.key,+ termsVersion: TERMS.version,+ },+ },+ };+ const UNACCEPTED_FLAGS = {};++ const originalConfig = {+ USE_DB_AUTHENTICATION: config.USE_DB_AUTHENTICATION,+ FIRE_EXCHANGE_URL: config.FIRE_EXCHANGE_URL,+ };++ beforeEach(() => {+ config.USE_DB_AUTHENTICATION = true;+ config.FIRE_EXCHANGE_URL = "http://test-exchange";+ // The ledger is unreachable: only the flags can show acceptance.+ mocks.exchangeRequest.mockRejectedValue(new Error("offline"));+ mocks.addScrapeJobs.mockReset();+ mocks.emitRejectedScrapeActivityEvents.mockReset();+ setExchangeProvidersForTest([+ {+ id: "acme",+ creditsCost: 12,+ terms: TERMS,+ routes: [{ domains: ["profiles.example"] }],+ },+ ]);+ });++ afterEach(() => {+ config.USE_DB_AUTHENTICATION = originalConfig.USE_DB_AUTHENTICATION;+ config.FIRE_EXCHANGE_URL = originalConfig.FIRE_EXCHANGE_URL;+ clearExchangeProvidersForTest();+ });++ async function batchScrape(+ body: Record<string, unknown>,+ flags: Record<string, unknown>,+ ): Promise<{ status: number; body: any }> {+ let status = 200;+ let payload: any;+ const res: any = {+ headersSent: false,+ status(code: number) {+ status = code;+ return res;+ },+ json(value: unknown) {+ payload = value;+ return res;+ },+ };+ await batchScrapeController(+ {+ body,+ headers: {},+ protocol: "http",+ host: "api.test",+ auth: { team_id: "team-1" },+ acuc: { flags, team_id: "team-1", org_id: "org-1" },+ } as any,+ res,+ );+ return { status, body: payload };+ }++ const enqueuedJobs = (): any[] => mocks.addScrapeJobs.mock.calls.flat(2);++ const rejectedEvents = (): any[] =>+ mocks.emitRejectedScrapeActivityEvents.mock.calls.flat(2);++ describe("without ignoreInvalidURLs", () => {+ it("admits a blocked URL the Exchange can serve and routes its job to the Exchange", async () => {+ const result = await batchScrape(+ { urls: [BLOCKED_URL, OPEN_URL], ignoreInvalidURLs: false },+ ACCEPTED_FLAGS,+ );++ expect(result.status).toBe(200);+ expect(result.body.success).toBe(true);+ expect(rejectedEvents()).toEqual([]);++ const jobs = enqueuedJobs();+ expect(jobs.map(job => job.data.url)).toEqual([BLOCKED_URL, OPEN_URL]);++ const blockedJob = jobs[0];+ const fallback = await buildFallbackList({+ id: blockedJob.jobId,+ url: blockedJob.data.url,+ options: blockedJob.data.scrapeOptions,+ internalOptions: blockedJob.data.internalOptions,+ featureFlags: new Set(),+ mock: null,+ abort: { asSignal: () => undefined },+ logger: {+ info: vi.fn(),+ warn: vi.fn(),+ debug: vi.fn(),+ error: vi.fn(),+ child: vi.fn().mockReturnThis(),+ },+ } as any);+ expect(fallback.map(f => f.engine)).toEqual(["exchange"]);+ });++ it("asks for the terms when they keep a blocked URL out", async () => {+ const result = await batchScrape(+ { urls: [OPEN_URL, BLOCKED_URL], ignoreInvalidURLs: false },+ UNACCEPTED_FLAGS,+ );++ expect(result).toEqual({+ status: 403,+ body: new ThirdPartyDataTermsRequiredError(TERMS).response(),+ });+ expect(result.body.requiresAction).toMatchObject({+ type: "accept_terms",+ terms: TERMS.key,+ version: TERMS.version,+ });+ expect(enqueuedJobs()).toEqual([]);+ expect(rejectedEvents()).toEqual([+ expect.objectContaining({+ url: BLOCKED_URL,+ error: expect.any(ThirdPartyDataTermsRequiredError),+ }),+ ]);+ });++ it("rejects a blocked URL the Exchange cannot serve as an unsupported site", async () => {+ const result = await batchScrape(+ { urls: [OPEN_URL, UNSERVED_URL], ignoreInvalidURLs: false },+ ACCEPTED_FLAGS,+ );++ expect(result).toEqual({+ status: 403,+ body: { success: false, error: UNSUPPORTED_SITE_MESSAGE },+ });+ expect(enqueuedJobs()).toEqual([]);+ expect(rejectedEvents()).toEqual([+ expect.objectContaining({+ url: UNSERVED_URL,+ error: expect.any(UnsupportedSiteError),+ }),+ ]);+ });+ });++ describe("with ignoreInvalidURLs", () => {+ it("admits Exchange-served blocked URLs and lists the rest as invalid", async () => {+ const result = await batchScrape(+ { urls: [BLOCKED_URL, UNSERVED_URL, OPEN_URL] },+ ACCEPTED_FLAGS,+ );++ expect(result.status).toBe(200);+ expect(result.body.invalidURLs).toEqual([UNSERVED_URL]);+ expect(enqueuedJobs().map(job => job.data.url)).toEqual([+ BLOCKED_URL,+ OPEN_URL,+ ]);+ expect(rejectedEvents()).toEqual([+ expect.objectContaining({+ url: UNSERVED_URL,+ error: expect.any(UnsupportedSiteError),+ }),+ ]);+ });++ it("lists a blocked URL whose terms are unaccepted as invalid", async () => {+ const result = await batchScrape(+ { urls: [BLOCKED_URL, OPEN_URL], ignoreInvalidURLs: true },+ UNACCEPTED_FLAGS,+ );++ expect(result.status).toBe(200);+ expect(result.body.invalidURLs).toEqual([BLOCKED_URL]);+ expect(enqueuedJobs().map(job => job.data.url)).toEqual([OPEN_URL]);+ expect(rejectedEvents()).toEqual([+ expect.objectContaining({+ url: BLOCKED_URL,+ error: expect.any(ThirdPartyDataTermsRequiredError),+ }),+ ]);+ });+ });+});diff --git a/apps/api/src/controllers/v2/batch-scrape.ts b/apps/api/src/controllers/v2/batch-scrape.tsindex 61c03a9bb..d1cbc5069 100644--- a/apps/api/src/controllers/v2/batch-scrape.ts+++ b/apps/api/src/controllers/v2/batch-scrape.ts@@ -50,6 +50,8 @@ import { calculateThreatScanCredits } from "../../lib/scrape-billing";import { billTeam } from "../../services/billing/credit_billing";import { emitRejectedScrapeActivityEvents } from "../../lib/siem-logging";import { UnsupportedSiteError } from "../../lib/error";+import { ThirdPartyDataTermsRequiredError } from "../../lib/exchange";+import { getExchangeAccessForRequestBody } from "../../lib/exchange-request";import {AGENT_REQUEST_CREDITS_SHARDS,initializeRequestCredits,@@ -155,10 +157,42 @@ export async function batchScrapeController(zeroDataRetention,});+ // A blocklisted URL is admitted when the Exchange can serve it, as on+ // single scrape; null means the URL may be scraped.+ const blocklistRefusal = async (url: string) => {+ if (+ !isUrlBlocked(url, req.acuc?.flags ?? null, {+ team_id: req.auth.team_id,+ org_id: req.acuc?.org_id ?? null,+ origin: req.body.origin ?? null,+ })+ ) {+ return null;+ }+ const exchangeAccess = await getExchangeAccessForRequestBody({+ body: req.body,+ flags: req.acuc?.flags ?? null,+ url,+ blocked: true,+ zeroDataRetention,+ teamId: req.auth.team_id,+ orgId: req.acuc?.org_id ?? null,+ });+ if (exchangeAccess.allowed) {+ return null;+ }+ return exchangeAccess.termsRequired+ ? new ThirdPartyDataTermsRequiredError(exchangeAccess.terms)+ : new UnsupportedSiteError();+ };+let urls: string[] = req.body.urls;let unnormalizedURLs = preNormalizedBody.urls;let invalidURLs: string[] | undefined = undefined;- const locallyBlockedURLs: string[] = [];+ const refusedURLs: {+ url: string;+ error: UnsupportedSiteError | ThirdPartyDataTermsRequiredError;+ }[] = [];if (req.body.ignoreInvalidURLs) {invalidURLs = [];@@ -169,61 +203,29 @@ export async function batchScrapeController(for (const u of pendingURLs) {try {const nu = urlSchema.parse(u);- if (- !isUrlBlocked(nu, req.acuc?.flags ?? null, {- team_id: req.auth.team_id,- org_id: req.acuc?.org_id ?? null,- origin: req.body.origin ?? null,- })- ) {+ const refusal = await blocklistRefusal(nu);+ if (refusal === null) {urls.push(nu);unnormalizedURLs.push(u);} else {invalidURLs.push(u);- locallyBlockedURLs.push(nu);+ refusedURLs.push({ url: nu, error: refusal });}} catch (_) {invalidURLs.push(u);}}} else {- const blockedURLs =- req.body.urls?.filter((url: string) =>- isUrlBlocked(url, req.acuc?.flags ?? null, {- team_id: req.auth.team_id,- org_id: req.acuc?.org_id ?? null,- origin: req.body.origin ?? null,- }),- ) ?? [];- if (blockedURLs.length > 0) {- locallyBlockedURLs.push(...blockedURLs);- emitRejectedScrapeActivityEvents(- locallyBlockedURLs.map(url => ({- scrapeId: uuidv7(),- requestId: req.body.__agentInterop?.requestId ?? id,- endpoint: req.body.__agentInterop ? "agent" : "batch_scrape",- teamId: req.auth.team_id,- apiKeyId: req.acuc?.api_key_id ?? null,- auditMetadata: req.body.auditMetadata,- url,- error: new UnsupportedSiteError(),- origin: req.body.origin ?? "api",- integration: req.body.integration,- zeroDataRetention,- })),- );- locallyBlockedURLs.length = 0;- if (!res.headersSent) {- return res.status(403).json({- success: false,- error: UNSUPPORTED_SITE_MESSAGE,- });+ for (const url of urls) {+ const refusal = await blocklistRefusal(url);+ if (refusal !== null) {+ refusedURLs.push({ url, error: refusal });}}}emitRejectedScrapeActivityEvents(- locallyBlockedURLs.map(url => ({+ refusedURLs.map(({ url, error }) => ({scrapeId: uuidv7(),requestId: req.body.__agentInterop?.requestId ?? id,endpoint: req.body.__agentInterop ? "agent" : "batch_scrape",@@ -231,13 +233,26 @@ export async function batchScrapeController(apiKeyId: req.acuc?.api_key_id ?? null,auditMetadata: req.body.auditMetadata,url,- error: new UnsupportedSiteError(),+ error,origin: req.body.origin ?? "api",integration: req.body.integration,zeroDataRetention,})),);+ if (!req.body.ignoreInvalidURLs && refusedURLs.length > 0) {+ // Unaccepted terms are the one refusal the caller can fix, so they win.+ const termsRequired = refusedURLs+ .map(x => x.error)+ .find(error => error instanceof ThirdPartyDataTermsRequiredError);+ return res.status(403).json(+ termsRequired?.response() ?? {+ success: false,+ error: UNSUPPORTED_SITE_MESSAGE,+ },+ );+ }+// Threat protection: reject/report blocked URLs at enqueue time so they// never consume scrape slots. Mirrors the isUrlBlocked handling above:// with ignoreInvalidURLs they are reported in invalidURLs; without it thediff --git a/apps/api/src/routes/shared.ts b/apps/api/src/routes/shared.tsindex 8d4a05ec3..061107393 100644--- a/apps/api/src/routes/shared.ts+++ b/apps/api/src/routes/shared.ts@@ -368,9 +368,8 @@ export function blocklistMiddleware(* asks for the provider's terms when unaccepted terms are all that stands in* the way. Unblocked URLs never consult the Exchange here: engine selection* decides for them, identically on every route, and scrapes them normally- * when terms are missing. Everything else (map, search, batch scrape,- * monitors) keeps plain blocklist behavior - batch stays out until its jobs- * carry the access flags the worker-side recheck needs.+ * when terms are missing. v2 batch scrape runs the same check per URL in its+ * controller; map, search and monitors keep plain blocklist behavior.*/export function scrapeBlocklistMiddleware(req: RequestWithMaybeACUC<any, any, any>,diff --git a/apps/api/src/scraper/scrapeURL/engines/index.ts b/apps/api/src/scraper/scrapeURL/engines/index.tsindex fb38ebf31..f630fe6d6 100644--- a/apps/api/src/scraper/scrapeURL/engines/index.ts+++ b/apps/api/src/scraper/scrapeURL/engines/index.ts@@ -721,8 +721,8 @@ export async function buildFallbackList(meta: Meta): Promise<];}- // A blocked URL can only have been admitted by scrapeBlocklistMiddleware- // for the Exchange; if the Exchange can no longer serve it (catalog+ // A blocked URL can only have been admitted (by scrapeBlocklistMiddleware+ // or batch scrape) for the Exchange; if it can no longer serve it (catalog// changed, service down), fail closed rather than letting normal engines// scrape a blocklisted site. Unblocked URLs whose provider wants// unaccepted terms fall through and scrape normally.