Skip to content

Supercharge your AI agents with data from the web and beyond. Building the library for superintelligence. 🔥

feat(api): infer integration from browser origin or User-Agent (#5216)

Erik Engervallc0ac4f0e6ee8
diff --git a/apps/api/src/config.ts b/apps/api/src/config.ts
index a9b8cecad..fbb683faa 100644
--- a/apps/api/src/config.ts
+++ b/apps/api/src/config.ts
@@ -673,6 +673,9 @@ const configSchema = z.object({
DISABLE_ENGPICKER: z.stringbool().optional(),
DISABLE_MONITORING: z.stringbool().default(false),
+ // Stamp an inferred `integration` on unlabelled direct callers.
+ INFER_INTEGRATION_ENABLED: z.stringbool().default(true),
+
EXTRACT_V3_BETA_URL: z.string().url().optional(),
AGENT_INTEROP_SECRET: z
.string()
diff --git a/apps/api/src/lib/infer-integration.test.ts b/apps/api/src/lib/infer-integration.test.ts
new file mode 100644
index 000000000..d35194d76
--- /dev/null
+++ b/apps/api/src/lib/infer-integration.test.ts
@@ -0,0 +1,128 @@
+import { describe, expect, it } from "vitest";
+import { inferIntegration } from "./infer-integration";
+
+describe("inferIntegration from a browser page", () => {
+ it("slugs the Origin host", () => {
+ expect(inferIntegration({ origin: "https://App.Example.com:8443" })).toBe(
+ "_ref.app-example-com",
+ );
+ });
+
+ it("drops a leading www.", () => {
+ expect(inferIntegration({ origin: "https://www.example.com" })).toBe(
+ "_ref.example-com",
+ );
+ });
+
+ it("falls back to the Referer host without path or query", () => {
+ expect(
+ inferIntegration({ referer: "https://example.org/a/b?token=1#x" }),
+ ).toBe("_ref.example-org");
+ });
+
+ it("prefers Origin over Referer", () => {
+ expect(
+ inferIntegration({
+ origin: "https://one.example.com",
+ referer: "https://two.example.com/page",
+ }),
+ ).toBe("_ref.one-example-com");
+ });
+
+ it("caps the slug at 48 characters", () => {
+ const slug = inferIntegration({
+ origin: `https://${"a".repeat(30)}.${"b".repeat(30)}.com`,
+ })!.slice("_ref.".length);
+ expect(slug.length).toBeLessThanOrEqual(48);
+ expect(slug).toMatch(/^[a-z0-9]+(-[a-z0-9]+)*$/);
+ });
+
+ it.each([
+ "null",
+ "http://localhost:3000",
+ "http://app.localhost",
+ "http://printer.local",
+ "http://local",
+ "http://127.0.0.1:8080",
+ "http://[::1]:8080",
+ "https://firecrawl.dev",
+ "https://www.firecrawl.dev",
+ "https://docs.firecrawl.dev",
+ "chrome-extension://abcdefghijklmnop",
+ ])("skips %s", origin => {
+ expect(inferIntegration({ origin })).toBeUndefined();
+ });
+
+ it("does not fall through to the User-Agent when the page host is skipped", () => {
+ expect(
+ inferIntegration({
+ origin: "https://www.firecrawl.dev",
+ userAgent: "SomeTool/1.0",
+ }),
+ ).toBeUndefined();
+ });
+
+ it("keeps a lookalike host", () => {
+ expect(inferIntegration({ origin: "https://notfirecrawl.dev" })).toBe(
+ "_ref.notfirecrawl-dev",
+ );
+ });
+});
+
+describe("inferIntegration from the User-Agent", () => {
+ it("slugs the first product token", () => {
+ expect(inferIntegration({ userAgent: "PostmanRuntime/7.39.0" })).toBe(
+ "_ua.postmanruntime",
+ );
+ expect(
+ inferIntegration({ userAgent: "Some_Tool/2.1 (linux; x64) extra/1" }),
+ ).toBe("_ua.some-tool");
+ });
+
+ it("accepts a product token with no version", () => {
+ expect(inferIntegration({ userAgent: "insomnia" })).toBe("_ua.insomnia");
+ });
+
+ it.each([
+ "curl/8.5.0",
+ "python-requests/2.31.0",
+ "Python-urllib/3.12",
+ "Go-http-client/2.0",
+ "node-fetch/1.0 (+https://github.com/bitinn/node-fetch)",
+ "Mozilla/5.0 (X11; Linux x86_64)",
+ "okhttp/4.12.0",
+ "Java/17.0.2",
+ "axios/1.6.0",
+ "undici",
+ ])("skips the generic runtime %s", userAgent => {
+ expect(inferIntegration({ userAgent })).toBeUndefined();
+ });
+
+ it.each(["firecrawl-go/1.0.0", "firecrawl-php/1.0", "firecrawl-cli/1.2"])(
+ "skips Firecrawl product %s",
+ userAgent => {
+ expect(inferIntegration({ userAgent })).toBeUndefined();
+ },
+ );
+
+ it("skips when the body already carries a non-default origin", () => {
+ expect(
+ inferIntegration({
+ userAgent: "SomeTool/1.0",
+ bodyOrigin: "[email protected]",
+ }),
+ ).toBeUndefined();
+ expect(
+ inferIntegration({ userAgent: "SomeTool/1.0", bodyOrigin: "api" }),
+ ).toBe("_ua.sometool");
+ expect(
+ inferIntegration({ userAgent: "SomeTool/1.0", bodyOrigin: " API " }),
+ ).toBe("_ua.sometool");
+ });
+
+ it("skips empty or unusable User-Agents", () => {
+ expect(inferIntegration({})).toBeUndefined();
+ expect(inferIntegration({ userAgent: " " })).toBeUndefined();
+ expect(inferIntegration({ userAgent: "(compatible; x)" })).toBeUndefined();
+ });
+});
diff --git a/apps/api/src/lib/infer-integration.ts b/apps/api/src/lib/infer-integration.ts
new file mode 100644
index 000000000..e06ff013f
--- /dev/null
+++ b/apps/api/src/lib/infer-integration.ts
@@ -0,0 +1,95 @@
+import { isIP } from "node:net";
+
+const RUNTIME_PRODUCTS = new Set([
+ "apache-httpasyncclient",
+ "apache-httpclient",
+ "aiohttp",
+ "axios",
+ "bun",
+ "curl",
+ "dart",
+ "deno",
+ "faraday",
+ "go-http-client",
+ "got",
+ "guzzlehttp",
+ "java",
+ "java-http-client",
+ "ktor-client",
+ "libcurl-agent",
+ "mozilla",
+ "node",
+ "node-fetch",
+ "okhttp",
+ "python",
+ "python-httpx",
+ "python-httpx2",
+ "python-requests",
+ "python-urllib",
+ "reqwest",
+ "ruby",
+ "undici",
+ "wget",
+]);
+
+const MAX_SLUG_LENGTH = 48;
+
+const slugify = (value: string): string =>
+ value
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, "-")
+ .slice(0, MAX_SLUG_LENGTH)
+ .replace(/^-+|-+$/g, "");
+
+function hostSlug(pageUrl: string): string | undefined {
+ let url: URL;
+ try {
+ url = new URL(pageUrl);
+ } catch {
+ return undefined;
+ }
+ if (url.protocol !== "http:" && url.protocol !== "https:") return undefined;
+
+ const host = url.hostname.toLowerCase().replace(/\.$/, "");
+ if (
+ !host ||
+ isIP(host.replace(/^\[|\]$/g, "")) ||
+ host === "localhost" ||
+ host === "local" ||
+ host.endsWith(".localhost") ||
+ host.endsWith(".local") ||
+ host === "firecrawl.dev" ||
+ host.endsWith(".firecrawl.dev")
+ ) {
+ return undefined;
+ }
+ return slugify(host.replace(/^www\./, "")) || undefined;
+}
+
+export function inferIntegration(request: {
+ origin?: string;
+ referer?: string;
+ userAgent?: string;
+ bodyOrigin?: unknown;
+}): string | undefined {
+ const pageUrl = request.origin || request.referer;
+ if (pageUrl) {
+ const slug = hostSlug(pageUrl);
+ return slug ? `_ref.${slug}` : undefined;
+ }
+
+ const bodyOrigin =
+ typeof request.bodyOrigin === "string"
+ ? request.bodyOrigin.trim().toLowerCase()
+ : "";
+ if (bodyOrigin !== "" && bodyOrigin !== "api") return undefined;
+
+ const product = request.userAgent?.trim().split(/\s+/)[0]?.split("/")[0];
+ if (!product || !/^[a-z0-9]/i.test(product)) return undefined;
+
+ const slug = slugify(product);
+ if (!slug || slug.startsWith("firecrawl") || RUNTIME_PRODUCTS.has(slug)) {
+ return undefined;
+ }
+ return `_ua.${slug}`;
+}
diff --git a/apps/api/src/routes/shared.ts b/apps/api/src/routes/shared.ts
index c45da32ea..ced568870 100644
--- a/apps/api/src/routes/shared.ts
+++ b/apps/api/src/routes/shared.ts
@@ -42,6 +42,7 @@ import {
agentInteropStatus,
isAgentInteropSecretValid,
} from "../lib/agent-interop";
+import { inferIntegration } from "../lib/infer-integration";
export function checkCreditsMiddleware(
_minimum?: number,
@@ -338,6 +339,30 @@ export function authMiddleware(
};
}
+export function inferIntegrationMiddleware(
+ req: Request,
+ _res: Response,
+ next: NextFunction,
+) {
+ const body = req.body;
+ if (
+ config.INFER_INTEGRATION_ENABLED &&
+ body &&
+ typeof body === "object" &&
+ !Array.isArray(body) &&
+ body.integration === undefined
+ ) {
+ const inferred = inferIntegration({
+ origin: req.get("origin"),
+ referer: req.get("referer"),
+ userAgent: req.get("user-agent"),
+ bodyOrigin: body.origin,
+ });
+ if (inferred) body.integration = inferred;
+ }
+ next();
+}
+
export function idempotencyMiddleware(
req: Request,
res: Response,
diff --git a/apps/api/src/routes/v1.ts b/apps/api/src/routes/v1.ts
index d2cdf6dff..bede8a778 100644
--- a/apps/api/src/routes/v1.ts
+++ b/apps/api/src/routes/v1.ts
@@ -34,6 +34,7 @@ import {
requestTimingMiddleware,
validateJobIdParam,
wrap,
+ inferIntegrationMiddleware,
} from "./shared";
import { queueStatusController } from "../controllers/v1/queue-status";
import { creditUsageHistoricalController } from "../controllers/v1/credit-usage-historical";
@@ -50,6 +51,7 @@ v1Router.use(requestTimingMiddleware("v1"));
v1Router.post(
"/scrape",
authMiddleware(RateLimiterMode.Scrape, { allowKeyless: true }),
+ inferIntegrationMiddleware,
countryCheck,
checkCreditsMiddleware(1),
scrapeBlocklistMiddleware,
@@ -59,6 +61,7 @@ v1Router.post(
v1Router.post(
"/crawl",
authMiddleware(RateLimiterMode.Crawl),
+ inferIntegrationMiddleware,
countryCheck,
checkCreditsMiddleware(),
scrapeBlocklistMiddleware,
@@ -69,6 +72,7 @@ v1Router.post(
v1Router.post(
"/batch/scrape",
authMiddleware(RateLimiterMode.Scrape),
+ inferIntegrationMiddleware,
countryCheck,
checkCreditsMiddleware(),
blocklistMiddleware,
@@ -79,6 +83,7 @@ v1Router.post(
v1Router.post(
"/search",
authMiddleware(RateLimiterMode.Search, { allowKeyless: true }),
+ inferIntegrationMiddleware,
countryCheck,
checkCreditsMiddleware(undefined, SEARCH_CREDITS_FEATURE_ID),
wrap(searchController),
@@ -87,6 +92,7 @@ v1Router.post(
v1Router.post(
"/map",
authMiddleware(RateLimiterMode.Map),
+ inferIntegrationMiddleware,
checkCreditsMiddleware(1),
blocklistMiddleware,
wrap(mapController),
@@ -149,6 +155,7 @@ v1Router.ws("/crawl/:jobId", crawlStatusWSController);
v1Router.post(
"/extract",
authMiddleware(RateLimiterMode.Extract),
+ inferIntegrationMiddleware,
deprecationMiddleware("v1_extract"),
countryCheck,
checkCreditsMiddleware(20),
diff --git a/apps/api/src/routes/v2.ts b/apps/api/src/routes/v2.ts
index 8da444756..526e1191c 100644
--- a/apps/api/src/routes/v2.ts
+++ b/apps/api/src/routes/v2.ts
@@ -50,6 +50,7 @@ import {
wrap,
isValidJobId,
validateJobIdParam,
+ inferIntegrationMiddleware,
} from "./shared";
import { queueStatusController } from "../controllers/v2/queue-status";
import { creditUsageHistoricalController } from "../controllers/v2/credit-usage-historical";
@@ -194,6 +195,7 @@ v2Router.post(
allowKeyless: true,
allowAgentManagedKey: true,
}),
+ inferIntegrationMiddleware,
countryCheck,
checkCreditsMiddleware(undefined, SEARCH_CREDITS_FEATURE_ID),
blocklistMiddleware,
@@ -239,6 +241,7 @@ v2Router.post(
countryCheck,
checkCreditsMiddleware(1),
parsePayloadMiddleware,
+ inferIntegrationMiddleware,
wrap(parseController),
);
@@ -248,6 +251,7 @@ v2Router.post(
allowKeyless: true,
allowAgentManagedKey: true,
}),
+ inferIntegrationMiddleware,
countryCheck,
checkCreditsMiddleware(1),
scrapeBlocklistMiddleware,
@@ -278,6 +282,7 @@ v2Router.delete(
v2Router.post(
"/batch/scrape",
authMiddleware(RateLimiterMode.Scrape, { allowAgentManagedKey: true }),
+ inferIntegrationMiddleware,
countryCheck,
checkCreditsMiddleware(),
blocklistMiddleware,
@@ -287,6 +292,7 @@ v2Router.post(
v2Router.post(
"/map",
authMiddleware(RateLimiterMode.Map),
+ inferIntegrationMiddleware,
checkCreditsMiddleware(1),
blocklistMiddleware,
wrap(mapController),
@@ -295,6 +301,7 @@ v2Router.post(
v2Router.post(
"/crawl",
authMiddleware(RateLimiterMode.Crawl),
+ inferIntegrationMiddleware,
countryCheck,
checkCreditsMiddleware(),
scrapeBlocklistMiddleware,
@@ -381,6 +388,7 @@ v2Router.get(
v2Router.post(
"/extract",
authMiddleware(RateLimiterMode.Extract),
+ inferIntegrationMiddleware,
deprecationMiddleware("v2_extract"),
countryCheck,
checkCreditsMiddleware(20),
@@ -412,6 +420,7 @@ v2Router.get(
v2Router.post(
"/agent",
authMiddleware(RateLimiterMode.Extract),
+ inferIntegrationMiddleware,
countryCheck,
checkCreditsMiddleware(20),
blocklistMiddleware,
@@ -638,6 +647,7 @@ v2Router.post("/slack/events", wrap(slackEventsController));
v2Router.post(
["/browser", "/interact"],
authMiddleware(RateLimiterMode.Browser, { allowAgentManagedKey: true }),
+ inferIntegrationMiddleware,
countryCheck,
checkCreditsMiddleware(2),
wrap(browserCreateController),