/** * 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. */ /** * @module bxc/profiles/ghost * * `ghost` profile — Lightpanda-backed anti-detection automation for servers. * * Why Lightpanda : * - 80 ms cold start vs 800 ms (Chromium) / 1500 ms (Camoufox) * - 40 MB idle RSS vs 200-400 MB * - No display required (true headless, no Xvfb) * - Same V8 as Chrome → all stealth patches written for Chromium apply * * Lightpanda alone, however, ships with `navigator.webdriver === true` * and an empty `navigator.plugins` array — instant tells. `ghost` solves * this by injecting a complete stealth patch suite via CDP * `Page.addScriptToEvaluateOnNewDocument` BEFORE the first navigation, * combined with a coherent fingerprint (UA, viewport, locale, timezone, * WebGL vendor/renderer) generated by `fingerprint.ts`. * * Coverage matrix vs the existing profiles : * * - `static` / `fast` : minimal anti-detection, 0 ms / 80 ms cold start * - `http` : TLS-fingerprint only (curl-impersonate JA4) * - `stealth` : patchright Chromium, 800 ms cold, 200 MB RSS * - `max` : Camoufox FF + CapSolver, 1.5 s cold, 400 MB RSS * - `ghost` : Lightpanda + custom stealth, 80 ms cold, 40 MB RSS * * On a Linux VPS where neither patchright Chromium nor Camoufox can be * installed (no display, RAM-constrained), `ghost` is the only option * that beats CF Managed Challenge with a sub-100 ms cold start. * * Usage : * * ```ts * import { launchGhostBrowser } from "@aphrody/bxc/profiles/ghost"; * * const ghost = await launchGhostBrowser({ * fingerprint: { os: "linux", browser: "chrome" }, * locale: "fr-FR", * timezone: "Europe/Paris", * cookies: "./cookies/private/example.json", * }); * * await ghost.page.goto("https://example.com"); * console.log(await ghost.page.content()); * await ghost.close(); * ``` */ import { Browser, type Page } from "../../api/browser.ts"; import { type BrowserFingerprint, type FingerprintOptions, generateFingerprint, } from "../fingerprint.ts"; import { moveMouse, randomWait, scrollHuman, typeNatural, } from "../humanize.ts"; import { buildStealthScript } from "./stealth-patches.ts"; // --------------------------------------------------------------------------- // Options // --------------------------------------------------------------------------- export interface GhostOptions { /** Override fingerprint generation (OS / browser family / version / seed). */ fingerprint?: FingerprintOptions; /** Locale used for `Accept-Language` and `navigator.languages`. */ locale?: string; /** IANA timezone used for the rendering context. */ timezone?: string; /** Pre-validated cookie jar — JSON path or `Cookie[]` array. */ cookies?: string; /** Lightpanda binary override. */ binaryPath?: string; /** Lightpanda log level. Default `"error"`. */ logLevel?: "debug" | "info" | "warn" | "error"; /** Verbose logger (defaults to silent). */ log?: (msg: string) => void; /** Disable canvas / WebGL / chrome.runtime patches (useful when an upstream * framework like patchright already injects them). */ skipStealthInject?: boolean; } export interface GhostBrowser { /** Page handle (CDP-connected via SocketPairTransport). */ page: Page; /** Negotiated coherent fingerprint. */ fingerprint: BrowserFingerprint; /** Closes the page + the underlying Lightpanda subprocess. */ close(): Promise; [Symbol.asyncDispose](): Promise; } // --------------------------------------------------------------------------- // Launch // --------------------------------------------------------------------------- export async function launchGhostBrowser( options: GhostOptions = {}, ): Promise { const log = options.log ?? (() => {}); // 1. Coherent fingerprint generation (defaults : Linux + Chrome 131) const fingerprint = generateFingerprint({ os: options.fingerprint?.os ?? "linux", browser: options.fingerprint?.browser ?? "chrome", version: options.fingerprint?.version, seed: options.fingerprint?.seed, }); log( `[ghost] ua="${fingerprint.userAgent.slice(0, 60)}…" viewport=${fingerprint.screen.width}x${fingerprint.screen.height} platform=${fingerprint.platform}`, ); // 2. Open Lightpanda (profile=fast under the hood) const page = (await Browser.newPage({ profile: "fast", userAgent: fingerprint.userAgent, viewport: { width: fingerprint.screen.width, height: fingerprint.screen.height, }, cookies: options.cookies, spawnOpts: { logLevel: options.logLevel ?? "error", readyTimeoutMs: 10_000, binaryPath: options.binaryPath, }, })) as Page; // 3. Inject the stealth patch suite — runs before every navigation. // `Page.addScriptToEvaluateOnNewDocument` is the canonical hook for // injecting JS that must execute prior to any site script. if (!options.skipStealthInject) { const script = buildStealthScript({ userAgent: fingerprint.userAgent, platform: fingerprint.platform, languages: options.locale ? [options.locale, ...fingerprint.languages] : fingerprint.languages, hardwareConcurrency: fingerprint.hardwareConcurrency, deviceMemory: fingerprint.deviceMemory, webglVendor: fingerprint.webglVendor, webglRenderer: fingerprint.webglRenderer, devicePixelRatio: fingerprint.devicePixelRatio, screen: fingerprint.screen, }); try { await sendCdp(page, "Page.addScriptToEvaluateOnNewDocument", { source: script, }); log(`[ghost] stealth script injected (${script.length} bytes)`); } catch (err) { const msg = err instanceof Error ? err.message : String(err); log( `[ghost] stealth inject failed (${msg.slice(0, 80)}); continuing without`, ); } } // 4. Apply Emulation overrides — locale + timezone affect Accept-Language // + Date.prototype.toLocaleString + Intl.DateTimeFormat. Without these // the geo IP / locale mismatch is itself an anti-bot signal. if (options.locale) { await sendCdp(page, "Emulation.setLocaleOverride", { locale: options.locale, }).catch(() => {}); await sendCdp(page, "Network.setExtraHTTPHeaders", { headers: { "Accept-Language": `${options.locale},en-US;q=0.9,en;q=0.8` }, }).catch(() => {}); } if (options.timezone) { await sendCdp(page, "Emulation.setTimezoneOverride", { timezoneId: options.timezone, }).catch(() => {}); } // 5. Override User Agent since Page.create currently ignores opts.userAgent await sendCdp(page, "Emulation.setUserAgentOverride", { userAgent: fingerprint.userAgent, acceptLanguage: fingerprint.acceptLanguage, platform: fingerprint.platform, }).catch(() => {}); const close = async () => { try { await page.close(); } catch { // ignore } await Browser.close().catch(() => {}); }; return { page, fingerprint, close, [Symbol.asyncDispose]: close, }; } // --------------------------------------------------------------------------- // Internals // --------------------------------------------------------------------------- /** Bxc `Page` exposes `_internalTransport`/`_internalSessionId` for direct CDP calls. */ async function sendCdp( page: Page, method: string, params: Record, ): Promise { const transport = ( page as unknown as { _internalTransport: { send: (raw: string) => void; onmessage?: (raw: string) => void; }; } )._internalTransport; const sessionId = (page as unknown as { _internalSessionId: string }) ._internalSessionId; const id = Math.floor(Math.random() * 1_000_000_000); return new Promise((resolve, reject) => { const prev = transport.onmessage; const timeout = setTimeout(() => { transport.onmessage = prev; reject(new Error(`CDP ${method} timed out`)); }, 10_000); transport.onmessage = (raw: string) => { prev?.call(transport, raw); let msg: { id?: number; result?: unknown; error?: { message: string } }; try { msg = JSON.parse(raw); } catch { return; } if (msg.id !== id) return; clearTimeout(timeout); transport.onmessage = prev; if (msg.error) reject(new Error(`CDP ${method} failed: ${msg.error.message}`)); else resolve(msg.result); }; transport.send(JSON.stringify({ id, method, params, sessionId })); }); } // --------------------------------------------------------------------------- // Realistic interaction helpers (re-exported for ergonomy) // --------------------------------------------------------------------------- /** Bezier-curved mouse path to a target (x, y). */ /** Per-keystroke typing with realistic per-character delay distribution. */ /** Smooth scroll a given number of pixels with eased steps. */ /** Pacing helper — call between steps to avoid robotic regularity. */ export { moveMouse, randomWait, scrollHuman, typeNatural };