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
replace psl with tldts, fix multi-part tld handling (#4206)
rowinsg4b7a0ed7e8f0
diff --git a/apps/api/package.json b/apps/api/package.jsonindex 720e0c846..789a807b1 100644--- a/apps/api/package.json+++ b/apps/api/package.json@@ -132,7 +132,6 @@"pg": "^8.16.3","prettier": "^3.6.2","prom-client": "^15.1.3",- "psl": "^1.15.0","rate-limiter-flexible": "2.4.2","redlock": "5.0.0-beta.2","resend": "^3.5.0",@@ -140,7 +139,7 @@"robots-parser": "^3.0.1","stripe": "^16.1.0","systeminformation": "^5.31.17",- "tldts": "^6.1.75",+ "tldts": "^7.4.10","tough-cookie": "^4.1.4","turndown": "^7.1.3","typescript": "npm:@typescript/[email protected]",diff --git a/apps/api/pnpm-lock.yaml b/apps/api/pnpm-lock.yamlindex a8c5313ef..d6175c590 100644--- a/apps/api/pnpm-lock.yaml+++ b/apps/api/pnpm-lock.yaml@@ -222,9 +222,6 @@ importers:prom-client:specifier: ^15.1.3version: 15.1.3- psl:- specifier: ^1.15.0- version: 1.15.0rate-limiter-flexible:specifier: 2.4.2version: 2.4.2@@ -247,8 +244,8 @@ importers:specifier: ^5.31.17version: 5.31.17tldts:- specifier: ^6.1.75- version: 6.1.75+ specifier: ^7.4.10+ version: 7.4.10tough-cookie:specifier: ^4.1.4version: 4.1.4@@ -2431,6 +2428,7 @@ packages:resolution: {integrity: sha512-p0SaNjrHOnQeR8/VnfGbmg9te2kfyYSQ7Sc/j/6DtPL3JQvKxmjO9TSjNFpujqV3vEYYBvNNvXSxzyksBWAx1Q==}engines: {node: '>=12.0.0'}+ deprecated: v4 is no longer maintained, upgrade to v5resolution: {integrity: sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==}@@ -4186,14 +4184,14 @@ packages:resolution: {integrity: sha512-Bf+ILmBgretUrdJxzXM0SgXLZ3XfiaUuOj/IKQHuTXip+05Xn+uyEYdVg0kYDipTBcLrCVyUzAPz7QmArb0mmw==}engines: {node: '>=14.0.0'}- resolution: {integrity: sha512-AOvV5YYIAFFBfransBzSTyztkc3IMfz5Eq3YluaRiEu55nn43Fzaufx70UqEKYr8BoLCach4q8g/bg6e5+/aFw==}+ resolution: {integrity: sha512-KnQjp53ZekKgm/r3l+u8kJGGzYgrWdP8+Mql7a4vijh2WE0IrZWspQj/TpTxDho/YxO+AnOZnIjQcCD+q6iJsw==}resolution: {integrity: sha512-nwEyF4vl4RSJjwSjBUmOSxc3BFPoIFdlRthJ6e+5v9P3bHNsoD06UjuqMUspqp7vsEZ1beaHi1km+optiE17yA==}- resolution: {integrity: sha512-+lFzEXhpl7JXgWYaXcB6DqTYXbUArvrWAE/5ioq/X3CdWLbDjpPP4XTrQBmEJ91y3xbe4Fkw7Lxv4P3GWeJaNg==}+ resolution: {integrity: sha512-GgouD1B+sWwvkaEq8vXC15DjQitxbvs12oIXELpconwm+Tg3zfcEv4jgzq3vtKverDXsg3VI8aRgNL2Nra0Iog==}hasBin: true@@ -8040,13 +8038,13 @@ snapshots:- [email protected]: {}+ [email protected]: {}dependencies:- tldts-core: 6.1.75+ tldts-core: 7.4.10dependencies:diff --git a/apps/api/src/controllers/v1/types.ts b/apps/api/src/controllers/v1/types.tsindex 3b2dbb13c..027f982e5 100644--- a/apps/api/src/controllers/v1/types.ts+++ b/apps/api/src/controllers/v1/types.ts@@ -2,6 +2,7 @@ import { Request, Response } from "express";import { config } from "../../config";import { z } from "zod";import { protocolIncluded, checkUrl } from "../../lib/validateUrl";+import { hasReachableHost } from "../../lib/url-utils";import { countries } from "../../lib/validate-country";import {ExtractorOptions,@@ -68,10 +69,11 @@ export const url = z.preprocess(return true;}}- return /(\.[a-zA-Z0-9-\u0400-\u04FF\u0500-\u052F\u2DE0-\u2DFF\uA640-\uA69F]{2,}|\.xn--[a-zA-Z0-9-]{1,})(:\d+)?([\/?#]|$)/i.test(- x,- );- }, "URL must have a valid top-level domain or be a valid path")+ // Same TLD-shaped check as before, plus IP literals β which the old+ // inline regex accepted only when the last octet had 2+ digits, so+ // 8.8.8.8 was rejected while 169.254.169.254 passed.+ return hasReachableHost(x as string);+ }, "URL must have a valid top-level domain or be an IP address").refine(x => {try {checkUrl(x as string);diff --git a/apps/api/src/controllers/v2/types.ts b/apps/api/src/controllers/v2/types.tsindex 4da4f3ef0..a21a0d87f 100644--- a/apps/api/src/controllers/v2/types.ts+++ b/apps/api/src/controllers/v2/types.ts@@ -2,6 +2,7 @@ import { Request, Response } from "express";import { config } from "../../config";import { z } from "zod";import { protocolIncluded, checkUrl } from "../../lib/validateUrl";+import { hasReachableHost } from "../../lib/url-utils";import { countries } from "../../lib/validate-country";import { includesFormat } from "../../lib/format-utils";import {@@ -63,10 +64,11 @@ export const URL = z.preprocess(return true;}}- return /(\.[a-zA-Z0-9-\u0400-\u04FF\u0500-\u052F\u2DE0-\u2DFF\uA640-\uA69F]{2,}|\.xn--[a-zA-Z0-9-]{1,})(:\d+)?([\/?#]|$)/i.test(- x,- );- }, "URL must have a valid top-level domain or be a valid path")+ // Same TLD-shaped check as before, plus IP literals β which the old+ // inline regex accepted only when the last octet had 2+ digits, so+ // 8.8.8.8 was rejected while 169.254.169.254 passed.+ return hasReachableHost(x as string);+ }, "URL must have a valid top-level domain or be an IP address").refine(x => {try {checkUrl(x as string);diff --git a/apps/api/src/lib/__tests__/url-utils.test.ts b/apps/api/src/lib/__tests__/url-utils.test.tsindex 84130ea42..c5c1e9a01 100644--- a/apps/api/src/lib/__tests__/url-utils.test.ts+++ b/apps/api/src/lib/__tests__/url-utils.test.ts@@ -1,4 +1,8 @@-import { isBaseDomain, extractBaseDomain } from "../url-utils";+import {+ isBaseDomain,+ extractBaseDomain,+ hasReachableHost,+} from "../url-utils";describe("URL Utils", () => {describe("isBaseDomain", () => {@@ -56,4 +60,73 @@ describe("URL Utils", () => {expect(extractBaseDomain("")).toBe(null);});});++ describe("extractBaseDomain with multi-part suffixes", () => {+ it("uses the public suffix list, not the last two labels", () => {+ // slice(-2) produced "co.il" here, which cannot resolve+ expect(extractBaseDomain("https://crm.danetcomm.co.il/x")).toBe(+ "danetcomm.co.il",+ );+ expect(extractBaseDomain("https://jobs.example.co.uk")).toBe(+ "example.co.uk",+ );+ expect(extractBaseDomain("https://shop.example.com.au")).toBe(+ "example.com.au",+ );+ });++ it("treats hosting suffixes as public, so the host is its own base domain", () => {+ // requires allowPrivateDomains; otherwise this returns "vercel.app"+ expect(extractBaseDomain("https://hello.vercel.app")).toBe(+ "hello.vercel.app",+ );+ expect(extractBaseDomain("https://user.github.io")).toBe("user.github.io");+ });+ });++ describe("hasReachableHost", () => {+ it("accepts IP literals, which the old regex allowed only sometimes", () => {+ expect(hasReachableHost("https://8.8.8.8/")).toBe(true);+ expect(hasReachableHost("https://93.184.216.34/")).toBe(true);+ expect(hasReachableHost("http://[::1]/")).toBe(true);+ expect(hasReachableHost("https://1.1.1.10:8080/p")).toBe(true);+ });++ it("accepts real, private, punycode and special-use suffixes", () => {+ expect(hasReachableHost("https://example.com/")).toBe(true);+ expect(hasReachableHost("https://example.co.uk/")).toBe(true);+ expect(hasReachableHost("https://hello.vercel.app/")).toBe(true);+ expect(hasReachableHost("https://www.xn--fsq.xn--0zwm56d")).toBe(true);+ expect(hasReachableHost("https://foo.local/")).toBe(true);+ expect(hasReachableHost("https://foo.internal/")).toBe(true);+ expect(hasReachableHost("https://foo.lan/")).toBe(true);+ });++ it("rejects hosts with no TLD at all", () => {+ expect(hasReachableHost("https://example/")).toBe(false);+ expect(hasReachableHost("https://foo.c/")).toBe(false);+ });+ });+});++describe("parent-sitemap host filter", () => {+ // Mirrors the filter in crawler.ts tryFetchSitemapLinks: when a subdomain crawl+ // pulls the parent domain's sitemap, only the crawled host and its own children+ // may be kept. A bare endsWith would also admit sibling hosts sharing a suffix+ // of the final label.+ const keeps = (host: string, linkHost: string) =>+ linkHost === host || linkHost.endsWith(`.${host}`);++ const host = "crm.danetcomm.co.il";++ it("keeps the host itself and real child subdomains", () => {+ expect(keeps(host, "crm.danetcomm.co.il")).toBe(true);+ expect(keeps(host, "a.crm.danetcomm.co.il")).toBe(true);+ });++ it("rejects sibling hosts that merely end with the same string", () => {+ expect(keeps(host, "evilcrm.danetcomm.co.il")).toBe(false);+ expect(keeps(host, "xcrm.danetcomm.co.il")).toBe(false);+ expect(keeps(host, "other.danetcomm.co.il")).toBe(false);+ });});diff --git a/apps/api/src/lib/url-utils.ts b/apps/api/src/lib/url-utils.tsindex c5b3b5e1d..3086e30c0 100644--- a/apps/api/src/lib/url-utils.ts+++ b/apps/api/src/lib/url-utils.ts@@ -2,7 +2,68 @@* Utility functions for URL manipulation and analysis*/-import psl from "psl";+import { parse as parseTld } from "tldts";++/**+ * Options for resolving a REGISTRABLE DOMAIN.+ *+ * allowPrivateDomains is required: tldts defaults it off, which treats hosting+ * suffixes (vercel.app, github.io, pages.dev) as ordinary TLDs and reports+ * hello.vercel.app's registrable domain as "vercel.app" β someone else's site.+ * It is also what the tldts docs prescribe for matching psl, which this replaced.+ *+ * extractHostname is off because callers pass a bare hostname, not a URL.+ *+ * Route registrable-domain lookups through parseHostname rather than importing+ * tldts directly, so no call site can forget these. Note that suffix+ * CLASSIFICATION is a different question and wants different options β see+ * hasReachableHost.+ */+const REGISTRABLE_DOMAIN_OPTIONS = {+ allowPrivateDomains: true,+ extractHostname: false,+} as const;++/**+ * Parses a hostname against the public suffix list to find its registrable domain.+ * @param hostname - The hostname to parse (not a full URL)+ */+export function parseHostname(+ hostname: string,+): ReturnType<typeof parseTld> {+ return parseTld(hostname, REGISTRABLE_DOMAIN_OPTIONS);+}++/**+ * The historic "looks like it has a TLD" test: a final label of 2+ alphanumerics+ * (incl. the Cyrillic ranges) or an xn-- punycode label, optionally with a port.+ */+const LOOKS_LIKE_TLD =+ /(\.[a-zA-Z0-9-Π-ΣΏΤ-Τ―β· -β·Ώκ-κ]{2,}|\.xn--[a-zA-Z0-9-]{1,})(:\d+)?([\/?#]|$)/i;++/**+ * Whether a URL's host is plausibly reachable. Used only for request validation.+ *+ * Accepts IP literals. The previous regex rejected these only when the final octet+ * was a single digit, so 93.184.216.34 was allowed while 8.8.8.8 was not β an+ * accident of `[a-zA-Z0-9]{2,}` matching digits, not a policy. Which addresses are+ * actually reachable is enforced downstream (safeFetch's connect-time check, and+ * the scraping proxy), not here.+ *+ * Everything else falls through to the historic pattern. Requiring a known public+ * suffix instead would reject .local / .lan / .internal hosts that self-hosted+ * deployments legitimately use, and any TLD delegated after the pinned tldts+ * release; the public suffix list deliberately contains no private-network TLDs,+ * so there is no maintained list to check them against. The cost of keeping the+ * pattern is that a typo'd TLD such as example.invalidtld still passes, exactly as+ * it did before.+ *+ * @param url - A full URL string; tldts extracts the host itself.+ */+export function hasReachableHost(url: string): boolean {+ if (parseTld(url).isIp === true) return true;+ return LOOKS_LIKE_TLD.test(url);+}/*** Determines if a URL is a base domain (e.g., example.com vs blog.example.com or example.com/path)@@ -15,8 +76,7 @@ export function isBaseDomain(url: string): boolean {const urlObj = new URL(url);const hostname = urlObj.hostname;- // Parse the domain using psl- const parsed = psl.parse(hostname);+ const parsed = parseHostname(hostname);if (!parsed.domain) {return false;}@@ -57,7 +117,7 @@ export function extractBaseDomain(url: string): string | null {const urlObj = new URL(url);const hostname = urlObj.hostname;- const parsed = psl.parse(hostname);+ const parsed = parseHostname(hostname);return parsed.domain || null;} catch (error) {diff --git a/apps/api/src/scraper/WebScraper/crawler.ts b/apps/api/src/scraper/WebScraper/crawler.tsindex 3eb1b7b89..cbb27ff07 100644--- a/apps/api/src/scraper/WebScraper/crawler.ts+++ b/apps/api/src/scraper/WebScraper/crawler.ts@@ -16,6 +16,7 @@ import {import { ScrapeJobTimeoutError } from "../../lib/error";import { ScrapeOptions } from "../../controllers/v2/types";import { filterLinks, filterUrl } from "@mendable/firecrawl-rs";+import { extractBaseDomain } from "../../lib/url-utils";export const SITEMAP_LIMIT = 25;const SITEMAP_MAX_AGE = 7 * 24 * 60 * 60 * 1000;@@ -875,12 +876,20 @@ export class WebCrawler {if (isIPv4 || isIPv6) {// IP addresses don't have subdomains, skip this logic} else {- const domainParts = hostname.split(".");-- // Check if this is a subdomain (has more than 2 parts and not www)- if (domainParts.length > 2 && domainParts[0] !== "www") {- // Get the main domain by taking the last two parts- const mainDomain = domainParts.slice(-2).join(".");+ // Resolve the registrable domain via the public suffix list rather than+ // taking the last two labels: multi-part suffixes (co.uk, co.il, co.jp,+ // com.au) have three labels, so slicing produced the bare suffix and we+ // ended up requesting https://co.il/sitemap.xml, which cannot resolve.+ // Returns null for hosts with no registrable domain (e.g. localhost).+ const mainDomain = extractBaseDomain(url);++ // Only worth a second fetch when the host actually *is* a subdomain of+ // that domain; skip www, which serves the same sitemap.+ if (+ mainDomain &&+ mainDomain !== hostname &&+ hostname !== `www.${mainDomain}`+ ) {const mainDomainUrl = `${urlObj.protocol}//${mainDomain}`;const mainDomainSitemapUrl = `${mainDomainUrl}/sitemap.xml`;@@ -894,7 +903,15 @@ export class WebCrawler {urls.filter(link => {try {const linkUrl = new URL(link);- return linkUrl.hostname.endsWith(hostname);+ // Match on a DNS-label boundary. A bare endsWith also+ // accepts sibling hosts that merely share a suffix of the+ // final label β evilcrm.danetcomm.co.il "ends with"+ // crm.danetcomm.co.il β which would pull an unrelated+ // host into this crawl. Real child subdomains still pass.+ return (+ linkUrl.hostname === hostname ||+ linkUrl.hostname.endsWith(`.${hostname}`)+ );} catch {}}),);diff --git a/apps/api/src/services/index.ts b/apps/api/src/services/index.tsindex 9e090d819..ceef42295 100644--- a/apps/api/src/services/index.ts+++ b/apps/api/src/services/index.ts@@ -22,7 +22,7 @@ import {type IndexCacheEntry,} from "./index-cache";import type { Logger } from "winston";-import psl from "psl";+import { parseHostname } from "../lib/url-utils";import { MapDocument } from "../controllers/v2/types";import type { PdfMetadata } from "../scraper/scrapeURL/engines/pdf/types";import { storage } from "../lib/gcs-jobs";@@ -239,11 +239,8 @@ export function generateDomainSplits(fakeDomain?: string,): string[] {if (fakeDomain) {- const parsed = psl.parse(hostname);- if (parsed === null) return [fakeDomain];-- const fakeParsed = psl.parse(fakeDomain);- if (fakeParsed === null || fakeParsed.domain === null) return [fakeDomain];+ const fakeParsed = parseHostname(fakeDomain);+ if (fakeParsed.domain === null) return [fakeDomain];const subdomains: string[] = (fakeParsed.subdomain ?? "").split(".")@@ -260,8 +257,12 @@ export function generateDomainSplits(return domains;}- const parsed = psl.parse(hostname);- if (parsed === null) {+ const parsed = parseHostname(hostname);+ // No registrable domain (IP literal, or a single label such as localhost) means+ // there are no domain splits to generate. Note an unrecognised suffix still+ // yields one β tldts reports domain.unknown as its own registrable domain.+ const domain = parsed.domain;+ if (domain === null) {return [];}@@ -269,12 +270,12 @@ export function generateDomainSplits(.split(".").filter(x => x !== "");if (subdomains.length === 1 && subdomains[0] === "www") {- return [parsed.domain];+ return [domain];}const domains: string[] = [];for (let i = subdomains.length; i >= 0; i--) {- domains.push(subdomains.slice(i).concat([parsed.domain]).join("."));+ domains.push(subdomains.slice(i).concat([domain]).join("."));}return domains;diff --git a/apps/api/src/services/worker/scrape-worker.ts b/apps/api/src/services/worker/scrape-worker.tsindex fb62e9d90..8657077ad 100644--- a/apps/api/src/services/worker/scrape-worker.ts+++ b/apps/api/src/services/worker/scrape-worker.ts@@ -47,7 +47,7 @@ import {addScrapeJob,addScrapeJobs,} from "../queue-jobs";-import psl from "psl";+import { parseHostname } from "../../lib/url-utils";import { getJobPriority } from "../../lib/job-priority";import { Document, scrapeOptions, TeamFlags } from "../../controllers/v2/types";import { hasFormatOfType } from "../../lib/format-utils";@@ -1242,10 +1242,15 @@ async function processKickoffJob(job: NuQJob<ScrapeJobKickoff>) {// Base sitemap.xmlattempts.push(new URL("/sitemap.xml", urlObj.href).href);- // Root domain sitemap.xml- const urlRootSitemap = new URL("/sitemap.xml", urlObj.href);- urlRootSitemap.hostname = psl.parse(urlObj.hostname).domain;- attempts.push(urlRootSitemap.href);+ // Root domain sitemap.xml. Skipped when the host has no registrable domain+ // (IP literals, localhost): assigning a null domain would stringify to the+ // literal hostname "null" and produce https://null/sitemap.xml.+ const rootDomain = parseHostname(urlObj.hostname).domain;+ if (rootDomain && rootDomain !== urlObj.hostname) {+ const urlRootSitemap = new URL("/sitemap.xml", urlObj.href);+ urlRootSitemap.hostname = rootDomain;+ attempts.push(urlRootSitemap.href);+ }for (const attempt of attempts) {await addKickoffSitemapJob(attempt, job, sc, logger);