/** * Copyright 2026 aphrody-code * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Auto-escalation: attempt profile chain static → http → render → fast → stealth → max * on detecting escape signals (403, Cloudflare, empty body, soft blocks, etc.). * * bxc is Lightpanda-only; the escalation never falls into * Chromium/Firefox/Edge/Safari. `ghost` = Lightpanda + CDP stealth injects. * * Without `startProfile`, the ladder starts at the tier learned for the URL's * registrable domain (see `DomainMemory`), and every attempt is recorded so * later URLs on the same site skip tiers that are known to fail. * * Usage: * const { profile, page, attempts } = await autoEscalate( * "https://google.com", * { startProfile: "static", maxAttempts: 3 } * ); */ import type { GotoOptions, Page } from "../api/browser.ts"; import { type AttemptOutcome, type AttemptRecord, DomainMemory, parseRetryAfter, } from "./domain-memory.ts"; import { detectSoftBlock, type HeadersInput, headerLookup } from "./soft-block.ts"; /** * Escalation step in the profile hierarchy. */ export type EscalationStep = "static" | "http" | "render" | "fast" | "stealth" | "max"; /** * Order of escalation: start with the fastest, escalate to slower profiles on failure. * `render` (in-process V8, no spawned browser) sits between `http` and the * Chrome-backed tiers and is skipped when libbxc_render is not installed. */ export const ESCALATION_ORDER: readonly EscalationStep[] = [ "static", "http", "render", "fast", "stealth", "max", ]; /** * Signals that trigger escalation to the next profile. */ export type EscalationReason = | "empty_body" | "spa_placeholder" | "status_403" | "transient_status" | "cloudflare" | "datadome" | "turnstile" | "captcha" /** 200 with an empty client-side app shell (soft block). */ | "js_required" /** WAF / bot-manager interstitial (Akamai, Imperva, PerimeterX, Kasada, AWS WAF, Sucuri). */ | "waf_block" /** Meta refresh into a challenge URL or onto itself (soft block). */ | "challenge_redirect" /** Denial / human-verification text on a near-empty page (soft block). */ | "access_denied" | "success"; /** * Result of escalation signal detection. */ export interface EscalationSignal { reason: EscalationReason; detectedFromBody?: string; detectedFromStatus?: number; /** Anti-bot vendor, when a soft-block detector identified one. */ provider?: string; /** Detector confidence (0..1) for soft-block signals. */ confidence?: number; } /** Optional response context for {@link detectEscalationSignal}. */ export interface EscalationSignalContext { url?: string; headers?: HeadersInput; } export interface AutoEscalationOptions { /** Explicit first profile; bypasses domain memory for the start tier. */ startProfile?: EscalationStep; maxAttempts?: number; /** TTL of the in-process host memory (compatibility layer). */ memoryTtlMs?: number; /** `false` disables all memory writes (in-process and domain memory). */ rememberProfile?: boolean; goto?: GotoOptions; log?: (msg: string) => void; /** * Persistent per-eTLD+1 memory. Default `DomainMemory.shared()` (honours * `BXC_DOMAIN_MEMORY_PATH`); pass an instance to inject one, `false` to disable. */ domainMemory?: DomainMemory | false; /** Page factory (tests, pools). Default `Browser.newPage({ profile })`. */ launch?: (profile: EscalationStep) => Promise; /** * Whether a tier can run in this process; unavailable tiers are skipped * without counting as an attempt. Default: every tier when `launch` is * injected, otherwise `render` requires libbxc_render. */ tierAvailable?: (profile: EscalationStep) => boolean | Promise; } export interface AutoEscalationResult { profile: EscalationStep; page: Page; attempts: EscalationStep[]; /** True when the successful profile is the one memory suggested. */ remembered: boolean; /** Where the first attempted profile came from. */ startedFrom: "domain-memory" | "option" | "default"; } const profileMemory = new Map< string, { profile: EscalationStep; expiresAt: number } >(); function hostKey(url: string): string | null { try { return new URL(url).host.toLowerCase(); } catch { return null; } } export function clearProfileMemory(): void { profileMemory.clear(); } export function rememberedProfile(url: string): EscalationStep | null { const key = hostKey(url); if (!key) return null; const remembered = profileMemory.get(key); if (!remembered) return null; if (remembered.expiresAt <= Date.now()) { profileMemory.delete(key); return null; } return remembered.profile; } export function profilePlan(start: EscalationStep): EscalationStep[] { const index = ESCALATION_ORDER.indexOf(start); return index < 0 ? [...ESCALATION_ORDER] : ESCALATION_ORDER.slice(index); } /** Visible-text budget under which body substring markers are trusted. */ const INTERSTITIAL_TEXT_MAX = 2000; /** * Detect if a response indicates the need to escalate to a more capable profile. * * `context` (URL, response headers) enables header-based soft-block checks * such as `cf-mitigated: challenge` and same-URL meta refresh loops. */ export function detectEscalationSignal( body: string, status: number, context: EscalationSignalContext = {}, ): EscalationSignal | null { // HTTP 403 Forbidden — likely protection if (status === 403) { return { reason: "status_403", detectedFromStatus: status }; } // Soft-block analysis (visible text is computed once, after stripping // script/style/noscript): vendor interstitials, challenge refreshes, denial // pages and JS-only app shells. const soft = detectSoftBlock({ status, html: body, url: context.url, headers: context.headers, }); // Interstitials are small. The substring markers below only count on pages // with little visible text, so an article that merely mentions "Just a // moment", DataDome or a CAPTCHA is not mistaken for a wall. const interstitialSized = soft.visibleTextLength < INTERSTITIAL_TEXT_MAX; if (interstitialSized) { // Cloudflare Managed Challenge if (/Just a moment/i.test(body)) { return { reason: "cloudflare", detectedFromBody: "Just a moment" }; } if (/Checking your browser/i.test(body)) { return { reason: "cloudflare", detectedFromBody: "Checking your browser" }; } if (/cf-mitigated/i.test(body)) { return { reason: "cloudflare", detectedFromBody: "cf-mitigated" }; } // Cloudflare at HTTP 503 if (status === 503 && /cloudflare/i.test(body)) { return { reason: "cloudflare", detectedFromBody: "Cloudflare @ 503", detectedFromStatus: status, }; } // DataDome protection if (/Access Denied/i.test(body) && /datadome/i.test(body)) { return { reason: "datadome", detectedFromBody: "DataDome Access Denied" }; } // Turnstile CAPTCHA if (/turnstile/i.test(body) && /captcha/i.test(body)) { return { reason: "turnstile", detectedFromBody: "Turnstile CAPTCHA" }; } } // Generic CAPTCHA widget. Only conclusive on a page with no real content: // a contact form carrying a reCAPTCHA is a delivered page, not a wall, and // escalating on it throws away a body that was already fetched. if (/(recaptcha|hcaptcha)/i.test(body)) { const text = body.replace(/<[^>]*>/g, " ").trim(); if (text.length < 2000) { return { reason: "captcha", detectedFromBody: "CAPTCHA widget detected" }; } } if (soft.blocked && soft.reason !== "js_required") { let reason: EscalationReason; if (soft.provider === "cloudflare") reason = "cloudflare"; else if (soft.provider === "datadome") reason = "datadome"; else if (soft.reason === "waf_block") reason = "waf_block"; else if (soft.reason === "challenge_redirect") reason = "challenge_redirect"; else reason = "access_denied"; return { reason, detectedFromBody: soft.evidence, detectedFromStatus: status, ...(soft.provider ? { provider: soft.provider } : {}), confidence: soft.confidence, }; } if ([408, 425, 429, 500, 502, 503, 504].includes(status)) { return { reason: "transient_status", detectedFromStatus: status }; } // SPA placeholder: