webcrawl 1.2.5 → 1.2.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,59 @@
1
+ /**
2
+ * AWS WAF challenge handling (local prototype).
3
+ *
4
+ * `webcrawl`'s bot-check detector (`isAntiBotChallenge`) only matches
5
+ * Cloudflare and Vercel Security Checkpoint signatures. AWS WAF serves
6
+ * its invisible JS challenge as **HTTP 202** with an empty `<title>` and
7
+ * none of those markers, so such pages come back as
8
+ * `Empty page (HTTP 202)` with `blocked: false` and never reach the
9
+ * stealth browser. This module adds the missing detection plus a local
10
+ * stealth-routing path so those pages can be solved and read anyway.
11
+ *
12
+ * Detection markers are layered (no single one is proof):
13
+ * - status 202 (documented Challenge interstitial status)
14
+ * - `awsWafCookieDomainList` / `AwsWafIntegration` (documented JS API)
15
+ * - `aws-waf-token` cookie reference
16
+ * - `<div id="challenge-container">` + `/__challenge_<id>/.../challenge.js`
17
+ *
18
+ * The detection itself now lives in the shared detector
19
+ * (`isAwsWafChallenge` in `./fetcher.js`, also folded into
20
+ * `isAntiBotChallenge`); this module re-exports it and adds the local
21
+ * stealth-routing path so challenge pages can be solved and read anyway.
22
+ */
23
+ import { isAwsWafChallenge } from "./fetcher.js";
24
+ export { isAwsWafChallenge };
25
+ /** True when a fetch response is any known bot check (upstream detector + AWS WAF). */
26
+ export declare function isBlockedLike(html: string, status?: number): boolean;
27
+ export interface AwsWafPage {
28
+ url: string;
29
+ title: string;
30
+ markdown: string;
31
+ linksCount: number;
32
+ cached: false;
33
+ cacheLayer: "miss";
34
+ structuredData: null;
35
+ statusCode?: number;
36
+ blocked?: boolean;
37
+ error?: string;
38
+ awsWaf?: boolean;
39
+ stealth?: boolean;
40
+ }
41
+ /**
42
+ * Opens `url` in a real local Chromium, waits out the AWS WAF challenge
43
+ * (the interstitial reloads itself once `AwsWafIntegration.getToken()`
44
+ * resolves), then returns the rendered page as a CrawledPage-shaped result.
45
+ * Never fabricates content: a page still showing the challenge comes back
46
+ * `blocked: true` with an honest error.
47
+ */
48
+ export declare function awsWafStealthFetch(url: string, opts?: {
49
+ timeoutMs?: number;
50
+ }): Promise<AwsWafPage>;
51
+ /**
52
+ * Reads one page: plain TLS-impersonated fetch first; when the site answers
53
+ * with an AWS WAF challenge (which the upstream detector misses), routes
54
+ * through the local stealth browser instead.
55
+ */
56
+ export declare function crawlPageWithAwsWaf(url: string, opts?: {
57
+ bypassCache?: boolean;
58
+ stealthTimeoutMs?: number;
59
+ }): Promise<AwsWafPage>;
@@ -0,0 +1,164 @@
1
+ /**
2
+ * AWS WAF challenge handling (local prototype).
3
+ *
4
+ * `webcrawl`'s bot-check detector (`isAntiBotChallenge`) only matches
5
+ * Cloudflare and Vercel Security Checkpoint signatures. AWS WAF serves
6
+ * its invisible JS challenge as **HTTP 202** with an empty `<title>` and
7
+ * none of those markers, so such pages come back as
8
+ * `Empty page (HTTP 202)` with `blocked: false` and never reach the
9
+ * stealth browser. This module adds the missing detection plus a local
10
+ * stealth-routing path so those pages can be solved and read anyway.
11
+ *
12
+ * Detection markers are layered (no single one is proof):
13
+ * - status 202 (documented Challenge interstitial status)
14
+ * - `awsWafCookieDomainList` / `AwsWafIntegration` (documented JS API)
15
+ * - `aws-waf-token` cookie reference
16
+ * - `<div id="challenge-container">` + `/__challenge_<id>/.../challenge.js`
17
+ *
18
+ * The detection itself now lives in the shared detector
19
+ * (`isAwsWafChallenge` in `./fetcher.js`, also folded into
20
+ * `isAntiBotChallenge`); this module re-exports it and adds the local
21
+ * stealth-routing path so challenge pages can be solved and read anyway.
22
+ */
23
+ import { fetchWithTlsImpersonation, isAntiBotChallenge, isAwsWafChallenge } from "./fetcher.js";
24
+ import { fastHtmlToMarkdown } from "./markdown.js";
25
+ export { isAwsWafChallenge };
26
+ /** True when a fetch response is any known bot check (upstream detector + AWS WAF). */
27
+ export function isBlockedLike(html, status) {
28
+ return isAntiBotChallenge(html ?? "", status ?? 200) || isAwsWafChallenge(html ?? "", status);
29
+ }
30
+ const MAC_CHROME = "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome";
31
+ const CHALLENGE_TIMEOUT_MS = 45_000;
32
+ /** Waits for a dynamically-installed playwright-core (avoids a hard dep). */
33
+ async function loadPlaywrightCore() {
34
+ // Non-literal specifier: playwright-core stays a soft, runtime-only dependency
35
+ // so `tsc --noEmit` passes without the package installed.
36
+ const specifier = "playwright-core";
37
+ return (await import(specifier));
38
+ }
39
+ function chromePath() {
40
+ return process.env.INTERACT_CHROME_PATH || MAC_CHROME;
41
+ }
42
+ /**
43
+ * Opens `url` in a real local Chromium, waits out the AWS WAF challenge
44
+ * (the interstitial reloads itself once `AwsWafIntegration.getToken()`
45
+ * resolves), then returns the rendered page as a CrawledPage-shaped result.
46
+ * Never fabricates content: a page still showing the challenge comes back
47
+ * `blocked: true` with an honest error.
48
+ */
49
+ export async function awsWafStealthFetch(url, opts = {}) {
50
+ const fail = (error, blocked = true) => ({
51
+ url,
52
+ title: url,
53
+ markdown: "",
54
+ linksCount: 0,
55
+ cached: false,
56
+ cacheLayer: "miss",
57
+ structuredData: null,
58
+ blocked,
59
+ error,
60
+ awsWaf: true,
61
+ stealth: true,
62
+ });
63
+ const { chromium } = await loadPlaywrightCore();
64
+ const executablePath = chromePath();
65
+ const browser = await chromium.launch({
66
+ executablePath,
67
+ headless: true,
68
+ args: [
69
+ "--no-sandbox",
70
+ "--disable-gpu",
71
+ "--disable-dev-shm-usage",
72
+ "--no-first-run",
73
+ "--no-default-browser-check",
74
+ // Hide navigator.webdriver, which bot checks look for.
75
+ "--disable-blink-features=AutomationControlled",
76
+ `--window-size=1280,800`,
77
+ ],
78
+ });
79
+ try {
80
+ const ctx = await browser.newContext({
81
+ userAgent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
82
+ viewport: { width: 1280, height: 800 },
83
+ locale: "en-US",
84
+ });
85
+ await ctx.addInitScript("Object.defineProperty(Navigator.prototype,'webdriver',{get:()=>false});");
86
+ const page = await ctx.newPage();
87
+ let navStatus = null;
88
+ page.on("response", (r) => {
89
+ try {
90
+ if (r.request().isNavigationRequest() && r.frame() === page.mainFrame())
91
+ navStatus = r.status();
92
+ }
93
+ catch { }
94
+ });
95
+ // The interstitial reloads itself after getToken(); domcontentloaded +
96
+ // marker polling survives that reload race.
97
+ await page.goto(url, { waitUntil: "domcontentloaded", timeout: Math.min(30_000, opts.timeoutMs ?? 30_000) });
98
+ const deadline = Date.now() + (opts.timeoutMs ?? CHALLENGE_TIMEOUT_MS);
99
+ let html = "";
100
+ for (;;) {
101
+ html = await page.content().catch(() => "");
102
+ if (!isAwsWafChallenge(html) && !isAntiBotChallenge(html, 200))
103
+ break;
104
+ if (Date.now() > deadline)
105
+ break;
106
+ await page.waitForTimeout(700).catch(() => { });
107
+ }
108
+ try {
109
+ await page.waitForLoadState("networkidle", { timeout: 2500 });
110
+ }
111
+ catch { }
112
+ html = await page.content().catch(() => html);
113
+ if (isAwsWafChallenge(html) || isAntiBotChallenge(html, 200)) {
114
+ return { ...fail("Still blocked by the site's AWS WAF challenge in local stealth mode"), statusCode: navStatus ?? undefined };
115
+ }
116
+ const finalUrl = page.url();
117
+ const parsed = fastHtmlToMarkdown(html, finalUrl || url, { retainImages: "all" });
118
+ if (parsed.markdown.length === 0) {
119
+ return {
120
+ ...fail(`Empty page after challenge (HTTP ${navStatus ?? "?"})`, false),
121
+ statusCode: navStatus ?? undefined,
122
+ };
123
+ }
124
+ return {
125
+ url,
126
+ title: parsed.title || finalUrl || url,
127
+ markdown: parsed.markdown,
128
+ linksCount: parsed.links.length,
129
+ cached: false,
130
+ cacheLayer: "miss",
131
+ structuredData: null,
132
+ statusCode: navStatus ?? 200,
133
+ awsWaf: true,
134
+ stealth: true,
135
+ };
136
+ }
137
+ finally {
138
+ await browser.close().catch(() => { });
139
+ }
140
+ }
141
+ /**
142
+ * Reads one page: plain TLS-impersonated fetch first; when the site answers
143
+ * with an AWS WAF challenge (which the upstream detector misses), routes
144
+ * through the local stealth browser instead.
145
+ */
146
+ export async function crawlPageWithAwsWaf(url, opts = {}) {
147
+ const fetched = await fetchWithTlsImpersonation(url, 12_000);
148
+ if (!isAwsWafChallenge(fetched.html, fetched.status)) {
149
+ const parsed = fastHtmlToMarkdown(fetched.html, url, { retainImages: "all" });
150
+ return {
151
+ url,
152
+ title: parsed.title || url,
153
+ markdown: parsed.markdown,
154
+ linksCount: parsed.links.length,
155
+ cached: false,
156
+ cacheLayer: "miss",
157
+ structuredData: null,
158
+ statusCode: fetched.status,
159
+ ...(parsed.markdown.length === 0 ? { error: `Empty page (HTTP ${fetched.status})` } : {}),
160
+ };
161
+ }
162
+ console.info("[awswaf] challenge detected, routing through local stealth browser", { url, status: fetched.status });
163
+ return awsWafStealthFetch(url, { timeoutMs: opts.stealthTimeoutMs });
164
+ }
@@ -23,6 +23,13 @@ export interface ScrapeResult {
23
23
  }
24
24
  export declare function getBrowserHeaders(targetUrl: string, extraHeaders?: Record<string, string>): Record<string, string>;
25
25
  export declare function setDomainCookie(hostname: string, cookieHeader: string): void;
26
+ /**
27
+ * True when an HTML response (with optional status) is an AWS WAF challenge
28
+ * interstitial: a marker match proves it regardless of status; otherwise a
29
+ * documented HTTP 202 whose payload is a `<script>`-only HTML shell with zero
30
+ * visible text (APIs legitimately return 202 too, so status alone is not proof).
31
+ */
32
+ export declare function isAwsWafChallenge(html: string, status?: number): boolean;
26
33
  export declare function isAntiBotChallenge(html: string, status: number): boolean;
27
34
  /**
28
35
  * Fetches a URL using `impit` (BoringSSL Chrome 136 TLS JA3/JA4 + HTTP/2 fingerprint impersonation)
@@ -47,18 +47,55 @@ function hashCode(str) {
47
47
  }
48
48
  return hash;
49
49
  }
50
+ /** Markers that only appear on an AWS WAF challenge interstitial. */
51
+ const AWS_WAF_CHALLENGE_MARKERS = [
52
+ "awswafcookiedomainlist",
53
+ "awswafintegration",
54
+ "aws-waf-token",
55
+ 'id="challenge-container"',
56
+ "/__challenge_",
57
+ ];
58
+ /**
59
+ * True when an HTML response (with optional status) is an AWS WAF challenge
60
+ * interstitial: a marker match proves it regardless of status; otherwise a
61
+ * documented HTTP 202 whose payload is a `<script>`-only HTML shell with zero
62
+ * visible text (APIs legitimately return 202 too, so status alone is not proof).
63
+ */
64
+ export function isAwsWafChallenge(html, status) {
65
+ const lower = String(html ?? "").slice(0, 8000).toLowerCase();
66
+ if (AWS_WAF_CHALLENGE_MARKERS.some((m) => lower.includes(m)))
67
+ return true;
68
+ if (status === 202) {
69
+ if (!lower.includes("<html"))
70
+ return false;
71
+ const visibleText = lower
72
+ .slice(0, 8000)
73
+ .replace(/<script[\s\S]*?<\/script>/g, "")
74
+ .replace(/<noscript[\s\S]*?<\/noscript>/g, "")
75
+ .replace(/<style[\s\S]*?<\/style>/g, "")
76
+ .replace(/<[^>]+>/g, " ")
77
+ .trim();
78
+ return visibleText.length === 0;
79
+ }
80
+ return false;
81
+ }
50
82
  export function isAntiBotChallenge(html, status) {
51
83
  if (status === 403 || status === 429 || status === 503) {
52
84
  return true;
53
85
  }
54
86
  const lower = html.slice(0, 6000).toLowerCase();
55
- return (lower.includes("cf-browser-verification") ||
87
+ if (lower.includes("cf-browser-verification") ||
56
88
  lower.includes("challenge-platform") ||
57
89
  lower.includes("just a moment...") ||
58
90
  lower.includes("vercel security checkpoint") ||
59
91
  lower.includes("_vercel/security") ||
60
92
  lower.includes("enable javascript and cookies to continue") ||
61
- lower.includes("_cf_chl_opt"));
93
+ lower.includes("_cf_chl_opt")) {
94
+ return true;
95
+ }
96
+ // AWS WAF serves its invisible JS challenge as HTTP 202 with none of the
97
+ // Cloudflare/Vercel markers, so those pages used to pass as real content.
98
+ return isAwsWafChallenge(html, status);
62
99
  }
63
100
  let sharedImpit = null;
64
101
  /** One request, redirects NOT followed (callers validate each hop via followSafely). */
@@ -155,7 +155,7 @@ try {
155
155
  const PER_DOC = 1500000;
156
156
  const TOTAL = 10000000;
157
157
  const started = Date.now();
158
- const markers = ["vercel security checkpoint", "just a moment...", "cf-browser-verification", "challenge-platform", "_cf_chl_opt", "enable javascript and cookies to continue", "_vercel/security", "attention required! | cloudflare"];
158
+ const markers = ["vercel security checkpoint", "just a moment...", "cf-browser-verification", "challenge-platform", "_cf_chl_opt", "enable javascript and cookies to continue", "_vercel/security", "attention required! | cloudflare", "awswafcookiedomainlist", "awswafintegration", "aws-waf-token", 'id="challenge-container"', "/__challenge_"];
159
159
  const looksBlocked = (s) => { const l = String(s || "").slice(0, 8000).toLowerCase(); return markers.some((m) => l.includes(m)); };
160
160
  let ua = "";
161
161
  try {
@@ -122,18 +122,22 @@ export async function escalateToSandboxOrBrowser(url, options = {}) {
122
122
  // ignore cookie extraction failure
123
123
  }
124
124
  // A challenge page is not content: never return it as a successful escalation.
125
+ // An empty shell (e.g. an AWS WAF 202 interstitial) is not content either:
126
+ // parse first and fall through to the browser tier instead.
125
127
  if (html && html.length > 100 && !isAntiBotChallenge(html, 200)) {
126
128
  const parsed = fastHtmlToMarkdown(html, url, {
127
129
  retainImages: options.retainImages,
128
130
  });
129
- return {
130
- html,
131
- markdown: parsed.markdown,
132
- title: parsed.title,
133
- links: parsed.links,
134
- statusCode: 200,
135
- tier: "sandbox",
136
- };
131
+ if (parsed.markdown.trim().length > 0) {
132
+ return {
133
+ html,
134
+ markdown: parsed.markdown,
135
+ title: parsed.title,
136
+ links: parsed.links,
137
+ statusCode: 200,
138
+ tier: "sandbox",
139
+ };
140
+ }
137
141
  }
138
142
  }
139
143
  finally {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "webcrawl",
3
- "version": "1.2.5",
3
+ "version": "1.2.8",
4
4
  "description": "Webcrawl Anything CLI & Core Engine — crawl, search, and extract structured evidence from any website, SPA, PDF, Office file, YouTube video, GitHub repo, ArXiv paper, or CVE",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -127,7 +127,7 @@
127
127
  "@ai-sdk/gateway": "^4.0.123",
128
128
  "@firecrawl/pdf-inspector": "^1.25.2",
129
129
  "@vercel/sandbox": "^1.0.0",
130
- "@webcrawl/client": "^1.2.5",
130
+ "@webcrawl/client": "^1.2.8",
131
131
  "ai": "^7.0.150",
132
132
  "impit": "^0.14.7",
133
133
  "mammoth": "^1.13.0",