Skip to content

Stealth Chromium that passes every bot detection test. Drop-in Playwright replacement with source-level fingerprint patches. 50+ tests passed.

15.7 KB
Raw Blame
/**
 * Playwright launch wrapper for cloakbrowser.
 * Mirrors Python cloakbrowser/browser.py.
 */

import type { Browser, BrowserContext, BrowserContextOptions, LaunchOptions as PlaywrightLaunchOptions } from "playwright-core";
import type { LaunchOptions, LaunchContextOptions, LaunchPersistentContextOptions } from "./types.js";
import { IGNORE_DEFAULT_ARGS } from "./config.js";
import { buildArgs } from "./args.js";
import { maybeWarnWindowsFonts } from "./fonts.js";
import { ensureBinary } from "./download.js";
import { resolveProxyConfig, warnOnRequestClientUse } from "./proxy.js";
import { maybeResolveGeoip, resolveWebrtcArgs, appendWebrtcExitIp } from "./geoip.js";
import {
  LICENSE_STATUS_FILE_ENV,
  buildLaunchEnv,
  installLicenseGuard,
  licenseErrorFrom,
  mintDenialFile,
  resolveLicenseKey,
} from "./license.js";
import { seedWidevineHint } from "./widevine.js";
import { persistentSeedArgs } from "./profile-seed.js";

/** @internal Accept both timezone and timezoneId — either works, no warning. Exported for testing. */
export function resolveTimezone<T extends { timezone?: string; timezoneId?: string }>(options: T): T {
  if (options.timezoneId != null) {
    const merged = { ...options, timezone: options.timezone ?? options.timezoneId };
    delete (merged as any).timezoneId;
    return merged;
  }
  return options;
}

/**
 * Strip `locale` and `timezoneId` from user-provided contextOptions — both route
 * through detectable CDP emulation. The wrapper's top-level `locale`/`timezone`
 * fields use binary flags instead (undetectable). Warn so users notice.
 */
function filterStealthCtxOptions(ctx?: BrowserContextOptions): Partial<BrowserContextOptions> {
  if (!ctx) return {};
  const { locale, timezoneId, ...rest } = ctx;
  if (locale !== undefined) {
    console.warn(
      "[cloakbrowser] contextOptions.locale ignored — use top-level `locale` " +
      "instead (routes through binary flag, avoids detectable CDP emulation)."
    );
  }
  if (timezoneId !== undefined) {
    console.warn(
      "[cloakbrowser] contextOptions.timezoneId ignored — use top-level `timezone` " +
      "instead (routes through binary flag, avoids detectable CDP emulation)."
    );
  }
  return rest;
}

/** A viewport size was removed: throw before anything launches. Plain JS callers
 * bypass the `viewport?: null` type, and `contextOptions` / `launchOptions` reach
 * Playwright as is (the persistent launch spreads both into one options object). */
function rejectViewport(options: LaunchContextOptions): void {
  const ctx = options.contextOptions as { viewport?: unknown } | undefined;
  const launch = options.launchOptions as { viewport?: unknown } | undefined;
  for (const v of [(options as { viewport?: unknown }).viewport, ctx?.viewport, launch?.viewport]) {
    if (v != null) {
      throw new TypeError(
        "The 'viewport' option has been removed: the page follows the browser window, " +
        "which opens maximized to the screen. For a custom size pass args: ['--window-size=W,H']."
      );
    }
  }
}

/**
 * Build Playwright BrowserContext options for CloakBrowser without launching a browser
 * or creating a context.
 *
 * Useful when integrating CloakBrowser with an existing Playwright Browser while
 * keeping the wrapper's stealth-safe defaults for `newContext()`.
 */
export function buildContextOptions(
  options: LaunchContextOptions = {}
): BrowserContextOptions {
  rejectViewport(options);
  return {
    // contextOptions first — explicit wrapper fields below override it.
    // filterStealthCtxOptions strips locale/timezoneId to prevent CDP detection.
    ...filterStealthCtxOptions(options.contextOptions),
    ...(options.userAgent ? { userAgent: options.userAgent } : {}),
    // No emulation: headed, the page tracks the real window; headless, the
    // binary reports coherent dimensions itself.
    viewport: null,
    ...(options.colorScheme ? { colorScheme: options.colorScheme } : {}),
  } as BrowserContextOptions;
}

/**
 * Build Playwright launch options for CloakBrowser without starting Chromium.
 *
 * Useful when integrating CloakBrowser with a custom Playwright build or another
 * wrapper that needs to call `chromium.launch()` itself.
 *
 * @param statusFile No longer needed: the denial file is created automatically.
 *   Kept for compatibility.
 */
export async function buildLaunchOptions(
  options: LaunchOptions = {},
  statusFile?: string,
): Promise<PlaywrightLaunchOptions> {
  const binaryPath =
    process.env.CLOAKBROWSER_BINARY_PATH ||
    (await ensureBinary(
      options.licenseKey,
      options.browserVersion,
      options.releaseChannel,
    ));
  const { exitIp, ...resolved } = await maybeResolveGeoip(options);
  const { proxyOption, proxyArgs } = resolveProxyConfig(options.proxy);
  let resolvedArgs = await resolveWebrtcArgs(options);
  resolvedArgs = appendWebrtcExitIp(resolvedArgs, exitIp);
  const args = buildArgs({ ...options, ...resolved, args: [...(resolvedArgs ?? []), ...proxyArgs] });
  maybeWarnWindowsFonts(args);

  // Resolve env for the browser process (license key injection, if needed).
  const { env: userEnv, ...restLaunchOptions } = options.launchOptions ?? {};
  // Standalone callers get a denial file too, so guardBrowser() can turn a
  // license denial into a clear error. Minted after ensureBinary: with no key,
  // its claim menu is what creates one.
  if (statusFile === undefined && resolveLicenseKey(options.licenseKey)) {
    statusFile = mintDenialFile();
  }
  const launchEnv = buildLaunchEnv(
    options.licenseKey,
    userEnv as Record<string, string | undefined> | undefined,
    statusFile,
  );
  const envResult = launchEnv !== undefined ? { env: launchEnv } : {};

  return {
    executablePath: binaryPath,
    headless: options.headless ?? true,
    args,
    ignoreDefaultArgs: IGNORE_DEFAULT_ARGS,
    ...(proxyOption ? { proxy: proxyOption } : {}),
    ...restLaunchOptions,
    ...envResult,
  } as PlaywrightLaunchOptions;
}

/**
 * Make a license denial (e.g. over the session cap) on a browser you launched
 * yourself throw CloakBrowserLicenseError instead of a bare "Target closed"
 * error. Pass the options buildLaunchOptions() returned; call it before
 * humanizeBrowser(). No-op when no license key was in play.
 *
 * A denial can also land during launch, before this runs. Map that one too:
 * ```ts
 * const opts = await buildLaunchOptions();
 * const browser = await chromium.launch(opts).catch((e) => {
 *   throw licenseErrorFrom(e) ?? e;
 * });
 * guardBrowser(browser, opts);
 * ```
 */
export function guardBrowser(browser: Browser, launchOptions: PlaywrightLaunchOptions): void {
  const denialPath = launchOptions.env?.[LICENSE_STATUS_FILE_ENV];
  if (!denialPath) return;
  (browser as any).__cloakDenialPath = denialPath;
  installLicenseGuard(browser, denialPath);
}

/**
 * Apply CloakBrowser's human-like behavioral layer to an existing Playwright browser.
 */
export async function humanizeBrowser(
  browser: Browser,
  options: LaunchOptions = {}
): Promise<void> {
  if (!options.humanize) return;

  const { patchBrowser } = await import('./human/index.js');
  const { resolveConfig } = await import('./human/config.js');
  const cfg = resolveConfig(
    options.humanPreset ?? 'default',
    options.humanConfig,
  );
  patchBrowser(browser, cfg);
}

/**
 * Launch stealth Chromium browser via Playwright.
 *
 * @example
 * ```ts
 * import { launch } from 'cloakbrowser';
 * const browser = await launch();
 * const page = await browser.newPage();
 * await page.goto('https://bot.incolumitas.com');
 * console.log(await page.title());
 * await browser.close();
 * ```
 */
export async function launch(options: LaunchOptions = {}): Promise<Browser> {
  const { chromium } = await import("playwright-core");
  // Mints the denial file (after ensureBinary, so a key the claim menu just
  // created is covered too).
  const launchOptions = await buildLaunchOptions(options);
  let browser: Browser;
  try {
    browser = await chromium.launch(launchOptions);
  } catch (err) {
    throw licenseErrorFrom(err, launchOptions.env?.[LICENSE_STATUS_FILE_ENV]) ?? err;
  }
  // Convert a post-handshake license denial into a clear error on first use.
  // Installed before the wraps below so it sits closest to the real call. Stashes
  // the path so launchContext() can guard its context too. Mirrors Python launch().
  guardBrowser(browser, launchOptions);
  // Proxy went to Chrome as --proxy-server, so Playwright's request client has no
  // proxy (#579). browser.newPage() and launchContext() both go through newContext.
  if (options.proxy && !launchOptions.proxy) {
    const origNewContext = browser.newContext.bind(browser);
    (browser as any).newContext = async (opts?: Parameters<typeof origNewContext>[0]) => {
      const context = await origNewContext(opts);
      warnOnRequestClientUse(context);
      return context;
    };
  }
  // Headed: a bare browser.newPage() would inherit Playwright's emulated 1280x720
  // viewport -> outerWidth < innerWidth (impossible window = bot tell). Default
  // newPage()/newContext() to viewport:null so the page tracks the real window.
  // Headless qualifies too (coherent dimensions natively). Mirrors Python launch().
  applyDefaultNoViewport(browser);
  await humanizeBrowser(browser, options);
  return browser;
}

/**
 * Wrap a Browser's newContext()/newPage() to default to viewport:null (no
 * emulation) when the caller didn't specify a viewport. setdefault-style: an
 * explicit viewport (including null) is always honored. Apply before humanize's
 * patchBrowser so the wraps compose.
 */
function applyDefaultNoViewport(browser: Browser): void {
  const origNewContext = browser.newContext.bind(browser);
  (browser as any).newContext = (options?: Parameters<typeof origNewContext>[0]) =>
    origNewContext(options?.viewport === undefined ? { ...options, viewport: null } : options);

  const origNewPage = browser.newPage.bind(browser);
  (browser as any).newPage = (options?: Parameters<typeof origNewPage>[0]) =>
    origNewPage(options?.viewport === undefined ? { ...options, viewport: null } : options);
}

/**
 * Launch stealth browser and return a BrowserContext with common options pre-set.
 * Closing the context also closes the browser.
 *
 * @example
 * ```ts
 * import { launchContext } from 'cloakbrowser';
 * const context = await launchContext({
 *   userAgent: 'Mozilla/5.0...',
 * });
 * const page = await context.newPage();
 * await page.goto('https://example.com');
 * await context.close(); // also closes browser
 * ```
 */
export async function launchContext(
  options: LaunchContextOptions = {}
): Promise<BrowserContext> {
  rejectViewport(options);
  options = resolveTimezone(options);
  // Resolve geoip BEFORE launch() to avoid double-resolution
  const { exitIp, ...resolved } = await maybeResolveGeoip(options);
  let launchArgs = await resolveWebrtcArgs(options);
  // Inject geoip exit IP for WebRTC spoofing (free — no extra HTTP call)
  launchArgs = appendWebrtcExitIp(launchArgs, exitIp);
  // --fingerprint-timezone is process-wide (reads CommandLine in renderer),
  // so it applies to ALL contexts, not just the default one.
  // locale and timezone are set via binary flags only — no CDP emulation.
  // humanize:false on the inner launch — patchContext below applies humanize
  // exactly once (else launch()'s humanizeBrowser would patch it a second time).
  const browser = await launch({ ...options, ...resolved, args: launchArgs, geoip: false, humanize: false });

  let context: BrowserContext;
  try {
    context = await browser.newContext(buildContextOptions(options));
  } catch (err) {
    await browser.close();
    throw err;
  }

  // Patch close() to also close the browser
  const origClose = context.close.bind(context);
  context.close = async (closeOptions?: { reason?: string }) => {
    try {
      await origClose(closeOptions);
    } finally {
      await browser.close();
    }
  };

  // launch() guards browser.newContext deeply, so this context is already
  // guarded; only store the path for licenseDenial().
  const denialPath = (browser as any).__cloakDenialPath as string | undefined;
  if (denialPath) (context as any).__cloakDenialPath = denialPath;

  // Human-like behavioral patching
  if (options.humanize) {
    const { patchContext } = await import('./human/index.js');
    const { resolveConfig } = await import('./human/config.js');
    const cfg = resolveConfig(
      options.humanPreset ?? 'default',
      options.humanConfig,
    );
    patchContext(context, cfg);
  }

  return context;
}

/**
 * Launch stealth browser with a persistent user profile (non-incognito).
 * Uses Playwright's chromium.launchPersistentContext() under the hood.
 *
 * This avoids incognito detection by services like BrowserScan (-10% penalty)
 * and enables session persistence (cookies, localStorage) across launches.
 *
 * @example
 * ```ts
 * import { launchPersistentContext } from 'cloakbrowser';
 * const context = await launchPersistentContext({
 *   userDataDir: './chrome-profile',
 *   headless: false,
 *   proxy: 'http://user:pass@host:port',
 *   geoip: true,
 * });
 * const page = context.pages()[0] || await context.newPage();
 * await page.goto('https://example.com');
 * await context.close();
 * ```
 */
export async function launchPersistentContext(
  options: LaunchPersistentContextOptions
): Promise<BrowserContext> {
  rejectViewport(options);
  options = resolveTimezone(options);
  const { chromium } = await import("playwright-core");

  const launchOptions = await buildLaunchOptions({
    ...options,
    args: persistentSeedArgs(options.userDataDir, options.stealthArgs, options.args),
  });
  seedWidevineHint(options.userDataDir, launchOptions.executablePath!);
  const denialPath = launchOptions.env?.[LICENSE_STATUS_FILE_ENV];

  // locale and timezone are set via binary flags (--lang, --fingerprint-timezone)
  // — NOT via Playwright context kwargs which use detectable CDP emulation.
  let context: BrowserContext;
  try {
    context = await chromium.launchPersistentContext(options.userDataDir, {
      ...buildContextOptions(options),
      ...launchOptions,
      // Last, so a raw launchOptions.viewport (even undefined) can't restore emulation.
      viewport: null,
    });
  } catch (err) {
    throw licenseErrorFrom(err, denialPath) ?? err;
  }

  if (options.proxy && !launchOptions.proxy) warnOnRequestClientUse(context);

  // Human-like behavioral patching. Applied BEFORE the license guard: the guard
  // stores its wrapper on the page/context object (it carries this launch's denial
  // path), and an own property shadows the prototype method humanize patches. Guarding
  // first would capture Playwright's own methods and silently disable humanize.
  if (options.humanize) {
    const { patchContext } = await import('./human/index.js');
    const { resolveConfig } = await import('./human/config.js');
    const cfg = resolveConfig(
      options.humanPreset ?? 'default',
      options.humanConfig,
    );
    patchContext(context, cfg);
  }

  // The persistent path hands back a context, so guard its newPage (see launch()).
  if (denialPath) {
    (context as any).__cloakDenialPath = denialPath; // for licenseDenial()
    installLicenseGuard(context, denialPath);
    // A persistent context arrives with a page already open, so the user
    // navigates pages()[0] directly and never calls newPage. Guard the existing
    // pages' navigation entry points too, or a post-handshake denial surfaces as
    // a bare TargetClosedError on that first navigation. Mirrors Python.
    for (const pg of context.pages()) {
      installLicenseGuard(pg, denialPath);
    }
  }

  return context;
}

// ---------------------------------------------------------------------------
// Internal
// ---------------------------------------------------------------------------

/** @internal Exposed for unit tests only. */
export { buildArgs as _buildArgsForTest } from "./args.js";