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): IP Restriction — per-team API key IP allowlist (#3952)
Gergő Móricz3d76890935a3
diff --git a/apps/api/src/__tests__/snips/v2/ip-restriction.test.ts b/apps/api/src/__tests__/snips/v2/ip-restriction.test.tsnew file mode 100644index 000000000..47f36aedc--- /dev/null+++ b/apps/api/src/__tests__/snips/v2/ip-restriction.test.ts@@ -0,0 +1,90 @@+import { eq } from "drizzle-orm";+import { idmux, scrape, scrapeRaw, scrapeTimeout } from "./lib";+import { createTestIdUrl, describeIf, TEST_PRODUCTION } from "../lib";+import { db } from "../../../db/connection";+import * as schema from "../../../db/schema";++// Needs idmux (to create teams with the ipRestriction flag) and direct DB+// access (to seed ip_restriction_config), so production-suite only.+describeIf(TEST_PRODUCTION)("IP restriction (ipRestriction team flag)", () => {+ const seededTeamIds: string[] = [];++ async function seedAllowlist(teamId: string, allowedIps: string[]) {+ await db.insert(schema.ip_restriction_config).values({+ team_id: teamId,+ allowed_ips: allowedIps,+ });+ seededTeamIds.push(teamId);+ }++ afterAll(async () => {+ for (const teamId of seededTeamIds) {+ await db+ .delete(schema.ip_restriction_config)+ .where(eq(schema.ip_restriction_config.team_id, teamId));+ }+ });++ it.concurrent(+ "allows requests when the client IP is on the allowlist",+ async () => {+ const identity = await idmux({+ name: "ip-restriction/allowed",+ credits: 10000,+ flags: { ipRestriction: true },+ });+ await seedAllowlist(identity.teamId, ["0.0.0.0/0", "::/0"]);++ await scrape({ url: createTestIdUrl() }, identity);+ },+ scrapeTimeout,+ );++ it.concurrent(+ "rejects requests from an IP that is not on the allowlist",+ async () => {+ const identity = await idmux({+ name: "ip-restriction/blocked",+ credits: 10000,+ flags: { ipRestriction: true },+ });+ // TEST-NET-3 address; the test runner's IP can never match it.+ await seedAllowlist(identity.teamId, ["203.0.113.7"]);++ const response = await scrapeRaw({ url: createTestIdUrl() }, identity);++ expect(response.statusCode).toBe(403);+ expect(response.body.success).toBe(false);+ expect(response.body.error).toContain("allowed IP list");+ },+ scrapeTimeout,+ );++ it.concurrent(+ "does not restrict a flagged team before it configures an allowlist",+ async () => {+ const identity = await idmux({+ name: "ip-restriction/no-config",+ credits: 10000,+ flags: { ipRestriction: true },+ });++ await scrape({ url: createTestIdUrl() }, identity);+ },+ scrapeTimeout,+ );++ it.concurrent(+ "does not restrict when the flag is off even if an allowlist exists",+ async () => {+ const identity = await idmux({+ name: "ip-restriction/no-flag",+ credits: 10000,+ });+ await seedAllowlist(identity.teamId, ["203.0.113.7"]);++ await scrape({ url: createTestIdUrl() }, identity);+ },+ scrapeTimeout,+ );+});diff --git a/apps/api/src/controllers/auth.ts b/apps/api/src/controllers/auth.tsindex 9cd1d5e22..9a82feb41 100644--- a/apps/api/src/controllers/auth.ts+++ b/apps/api/src/controllers/auth.ts@@ -16,6 +16,7 @@ import {keylessTeamId,} from "../lib/keyless";import { isKeylessIpSuspicious } from "../lib/spur";+import { checkIpRestriction } from "../lib/ip-restriction";import { deleteKey, getValue, setValue } from "../services/redis";import { redlock } from "../services/redlock";import { eq } from "drizzle-orm";@@ -801,6 +802,21 @@ async function supaAuthenticateUser();}+ if (chunk?.flags?.ipRestriction) {+ const ipCheck = await checkIpRestriction(+ req.ip ?? req.socket?.remoteAddress,+ chunk.team_id,+ chunk.flags,+ );+ if (!ipCheck.allowed) {+ return {+ success: false,+ error: ipCheck.error,+ status: ipCheck.status,+ };+ }+ }+const team_endpoint_token = token === config.PREVIEW_TOKEN ? iptoken : teamId;try {diff --git a/apps/api/src/controllers/v1/types.ts b/apps/api/src/controllers/v1/types.tsindex 5a2f0eb69..7530169d0 100644--- a/apps/api/src/controllers/v1/types.ts+++ b/apps/api/src/controllers/v1/types.ts@@ -1311,6 +1311,8 @@ export type TeamFlags = {checkRobotsOnScrape?: boolean;crawlTtlHours?: number;ipWhitelist?: boolean;+ // gates the per-team API key IP allowlist (ip_restriction_config table)+ ipRestriction?: boolean;skipCountryCheck?: boolean;browserBeta?: boolean;bypassCreditChecks?: boolean;diff --git a/apps/api/src/controllers/v2/types.ts b/apps/api/src/controllers/v2/types.tsindex 48894bd63..782decfe0 100644--- a/apps/api/src/controllers/v2/types.ts+++ b/apps/api/src/controllers/v2/types.ts@@ -1543,6 +1543,8 @@ export type TeamFlags = {checkRobotsOnScrape?: boolean;crawlTtlHours?: number;ipWhitelist?: boolean;+ // gates the per-team API key IP allowlist (ip_restriction_config table)+ ipRestriction?: boolean;bypassCreditChecks?: boolean;debugBranding?: boolean;maxBrowserSessions?: number;diff --git a/apps/api/src/db/schema/public.ts b/apps/api/src/db/schema/public.tsindex 1e42f8686..545e2926b 100644--- a/apps/api/src/db/schema/public.ts+++ b/apps/api/src/db/schema/public.ts@@ -242,6 +242,18 @@ export const idempotency_keys = pgTable("idempotency_keys", {created_at: ts("created_at").notNull().defaultNow(),});+// Per-team API key IP allowlist, gated by the ipRestriction team flag.+// Enforced only when allowed_ips is non-empty; entries are IPv4/IPv6/CIDR.+export const ip_restriction_config = pgTable("ip_restriction_config", {+ id: uuid("id").notNull().defaultRandom(),+ team_id: uuid("team_id").notNull().unique(),+ allowed_ips: jsonb("allowed_ips")+ .notNull()+ .default(sql`'[]'::jsonb`),+ created_at: ts("created_at").notNull().defaultNow(),+ updated_at: ts("updated_at").notNull().defaultNow(),+});+export const llm_texts = pgTable("llm_texts", {id: uuid("id").notNull().defaultRandom(),origin_url: text("origin_url").notNull(),diff --git a/apps/api/src/lib/ip-restriction.test.ts b/apps/api/src/lib/ip-restriction.test.tsnew file mode 100644index 000000000..65bdee655--- /dev/null+++ b/apps/api/src/lib/ip-restriction.test.ts@@ -0,0 +1,75 @@+import { isIpAllowed, normalizeIp } from "./ip-restriction";++describe("normalizeIp", () => {+ it("strips the IPv4-mapped IPv6 prefix", () => {+ expect(normalizeIp("::ffff:1.2.3.4")).toBe("1.2.3.4");+ expect(normalizeIp("::FFFF:1.2.3.4")).toBe("1.2.3.4");+ });++ it("leaves plain addresses untouched", () => {+ expect(normalizeIp("1.2.3.4")).toBe("1.2.3.4");+ expect(normalizeIp("2001:db8::1")).toBe("2001:db8::1");+ expect(normalizeIp(" 1.2.3.4 ")).toBe("1.2.3.4");+ });++ it("does not strip the prefix from non-IPv4 remainders", () => {+ expect(normalizeIp("::ffff:dead:beef")).toBe("::ffff:dead:beef");+ });+});++describe("isIpAllowed", () => {+ it("matches exact IPv4 addresses", () => {+ expect(isIpAllowed("1.2.3.4", ["1.2.3.4"])).toBe(true);+ expect(isIpAllowed("1.2.3.5", ["1.2.3.4"])).toBe(false);+ });++ it("matches IPv4 CIDR blocks", () => {+ expect(isIpAllowed("10.1.2.3", ["10.0.0.0/8"])).toBe(true);+ expect(isIpAllowed("11.1.2.3", ["10.0.0.0/8"])).toBe(false);+ expect(isIpAllowed("192.168.1.77", ["192.168.1.0/24"])).toBe(true);+ expect(isIpAllowed("192.168.2.77", ["192.168.1.0/24"])).toBe(false);+ });++ it("matches exact IPv6 addresses and CIDR blocks", () => {+ expect(isIpAllowed("2001:db8::1", ["2001:db8::1"])).toBe(true);+ expect(isIpAllowed("2001:db8::2", ["2001:db8::1"])).toBe(false);+ expect(isIpAllowed("2001:db8:1:2::3", ["2001:db8::/32"])).toBe(true);+ expect(isIpAllowed("2001:db9::1", ["2001:db8::/32"])).toBe(false);+ });++ it("matches IPv4-mapped IPv6 clients against IPv4 entries", () => {+ expect(isIpAllowed("::ffff:10.1.2.3", ["10.0.0.0/8"])).toBe(true);+ expect(isIpAllowed("::ffff:11.1.2.3", ["10.0.0.0/8"])).toBe(false);+ });++ it("supports match-all CIDR blocks", () => {+ expect(isIpAllowed("127.0.0.1", ["0.0.0.0/0"])).toBe(true);+ expect(isIpAllowed("::1", ["::/0"])).toBe(true);+ expect(isIpAllowed("::1", ["0.0.0.0/0"])).toBe(false);+ });++ it("checks against all entries", () => {+ const entries = ["1.2.3.4", "10.0.0.0/8", "2001:db8::/32"];+ expect(isIpAllowed("1.2.3.4", entries)).toBe(true);+ expect(isIpAllowed("10.9.9.9", entries)).toBe(true);+ expect(isIpAllowed("2001:db8::7", entries)).toBe(true);+ expect(isIpAllowed("8.8.8.8", entries)).toBe(false);+ });++ it("skips malformed entries without disabling valid ones", () => {+ const entries = [+ "not-an-ip",+ "10.0.0.0/33",+ "10.0.0.0/-1",+ "1.2.3.4/x",+ "1.2.3.4",+ ];+ expect(isIpAllowed("1.2.3.4", entries)).toBe(true);+ expect(isIpAllowed("10.0.0.1", entries)).toBe(false);+ });++ it("rejects malformed client IPs and empty allowlists", () => {+ expect(isIpAllowed("not-an-ip", ["0.0.0.0/0"])).toBe(false);+ expect(isIpAllowed("1.2.3.4", [])).toBe(false);+ });+});diff --git a/apps/api/src/lib/ip-restriction.ts b/apps/api/src/lib/ip-restriction.tsnew file mode 100644index 000000000..44423f74d--- /dev/null+++ b/apps/api/src/lib/ip-restriction.ts@@ -0,0 +1,155 @@+import { BlockList, isIP } from "node:net";+import { eq } from "drizzle-orm";+import { dbRr } from "../db/connection";+import * as schema from "../db/schema";+import { getValue, setValue } from "../services/redis";+import { logger } from "./logger";+import type { TeamFlags } from "../controllers/v1/types";++// Propagation delay for dashboard edits to ip_restriction_config.+const ALLOWLIST_CACHE_TTL_SECONDS = 60;++const allowlistCacheKey = (teamId: string) =>+ `ip-restriction-allowlist:${teamId}`;++// Express hands IPv4 clients back as IPv4-mapped IPv6 (::ffff:1.2.3.4) when+// the socket is dual-stack; compare in IPv4 form so allowlist entries match.+export function normalizeIp(ip: string): string {+ const trimmed = ip.trim();+ const lower = trimmed.toLowerCase();+ if (lower.startsWith("::ffff:") && isIP(trimmed.slice(7)) === 4) {+ return trimmed.slice(7);+ }+ return trimmed;+}++export function isIpAllowed(rawIp: string, allowedIps: string[]): boolean {+ const ip = normalizeIp(rawIp);+ const ipVersion = isIP(ip);+ if (ipVersion === 0) {+ return false;+ }++ const list = new BlockList();+ for (const rawEntry of allowedIps) {+ if (typeof rawEntry !== "string") continue;+ const entry = normalizeIp(rawEntry);+ const slash = entry.indexOf("/");+ // Malformed entries are skipped rather than thrown on: the list is+ // validated on write, but a bad entry must never disable the others.+ try {+ if (slash === -1) {+ const version = isIP(entry);+ if (version === 0) continue;+ list.addAddress(entry, version === 6 ? "ipv6" : "ipv4");+ } else {+ const address = entry.slice(0, slash);+ const prefix = Number(entry.slice(slash + 1));+ const version = isIP(address);+ if (version === 0 || !Number.isInteger(prefix)) continue;+ if (prefix < 0 || prefix > (version === 6 ? 128 : 32)) continue;+ list.addSubnet(address, prefix, version === 6 ? "ipv6" : "ipv4");+ }+ } catch {+ continue;+ }+ }++ return list.check(ip, ipVersion === 6 ? "ipv6" : "ipv4");+}++async function getTeamAllowedIps(teamId: string): Promise<string[]> {+ const cacheKey = allowlistCacheKey(teamId);++ try {+ const cached = await getValue(cacheKey);+ if (cached !== null) {+ const parsed = JSON.parse(cached);+ // A corrupted-but-parseable cache entry must not reach the matcher;+ // treat anything that isn't a string array as a cache miss.+ if (Array.isArray(parsed)) {+ return parsed.filter((x): x is string => typeof x === "string");+ }+ logger.warn("Ignoring malformed IP restriction allowlist cache entry", {+ teamId,+ });+ }+ } catch (error) {+ logger.warn("Failed to read IP restriction allowlist cache", {+ teamId,+ error,+ });+ }++ const [row] = await dbRr+ .select({ allowed_ips: schema.ip_restriction_config.allowed_ips })+ .from(schema.ip_restriction_config)+ .where(eq(schema.ip_restriction_config.team_id, teamId))+ .limit(1);++ const allowedIps = Array.isArray(row?.allowed_ips)+ ? (row.allowed_ips as unknown[]).filter(+ (x): x is string => typeof x === "string",+ )+ : [];++ try {+ await setValue(+ cacheKey,+ JSON.stringify(allowedIps),+ ALLOWLIST_CACHE_TTL_SECONDS,+ );+ } catch (error) {+ logger.warn("Failed to cache IP restriction allowlist", { teamId, error });+ }++ return allowedIps;+}++type IpRestrictionResult =+ | { allowed: true }+ | { allowed: false; error: string; status: number };++/**+ * Enforces the per-team API key IP allowlist (ip_restriction_config table),+ * gated by the ipRestriction team flag. An empty or missing allowlist means+ * no restriction, so a team can't lock itself out before configuring IPs.+ */+export async function checkIpRestriction(+ clientIp: string | undefined,+ teamId: string,+ flags: TeamFlags,+): Promise<IpRestrictionResult> {+ if (!flags?.ipRestriction) {+ return { allowed: true };+ }++ let allowedIps: string[];+ try {+ allowedIps = await getTeamAllowedIps(teamId);+ } catch (error) {+ logger.error("Failed to load IP restriction allowlist", { teamId, error });+ // Fail closed: the team explicitly opted into IP restriction, so an+ // unverifiable IP must not slip through.+ return {+ allowed: false,+ error:+ "Internal error while verifying this team's IP restriction. Please try again shortly.",+ status: 500,+ };+ }++ if (allowedIps.length === 0) {+ return { allowed: true };+ }++ if (clientIp && isIpAllowed(clientIp, allowedIps)) {+ return { allowed: true };+ }++ return {+ allowed: false,+ error: `Request blocked: IP address ${clientIp ? normalizeIp(clientIp) : "unknown"} is not on this team's allowed IP list. Team admins can manage allowed IPs in the dashboard settings.`,+ status: 403,+ };+}