feat: add JavaScript/TypeScript wrapper with Playwright + Puppeteer support

Adds js/ package mirroring the Python wrapper architecture:
- Dual API: import from 'cloakbrowser' (Playwright) or 'cloakbrowser/puppeteer'
- TypeScript with full type definitions
- Same binary download/cache logic, same stealth args, same env vars
- Optional peer deps: users install only the runtime they need
- Full 6-site stealth test suite (sannysoft, incolumitas, BrowserScan, deviceandbrowserinfo, FingerprintJS, reCAPTCHA v3)
- Published to npm as cloakbrowser@0.1.2
This commit is contained in:
CloakHQ
2026-02-24 07:33:18 +01:00
parent 23ae521832
commit 4e809b9678
17 changed files with 4260 additions and 9 deletions
+98
View File
@@ -0,0 +1,98 @@
/**
* Stealth configuration and platform detection for cloakbrowser.
* Mirrors Python cloakbrowser/config.py.
*/
import os from "node:os";
import path from "node:path";
// ---------------------------------------------------------------------------
// Chromium version shipped with this release
// ---------------------------------------------------------------------------
export const CHROMIUM_VERSION = "142.0.7444.175";
// ---------------------------------------------------------------------------
// Platform detection
// ---------------------------------------------------------------------------
const SUPPORTED_PLATFORMS: Record<string, string> = {
"linux-x64": "linux-x64",
"linux-arm64": "linux-arm64",
"darwin-arm64": "darwin-arm64",
"darwin-x64": "darwin-x64",
};
export function getPlatformTag(): string {
const platform = process.platform;
const arch = process.arch;
// Map Node.js platform/arch to our tag format
let key: string;
if (platform === "linux" && arch === "x64") key = "linux-x64";
else if (platform === "linux" && arch === "arm64") key = "linux-arm64";
else if (platform === "darwin" && arch === "arm64") key = "darwin-arm64";
else if (platform === "darwin" && arch === "x64") key = "darwin-x64";
else {
const supported = Object.values(SUPPORTED_PLATFORMS).join(", ");
throw new Error(
`Unsupported platform: ${platform} ${arch}. Supported: ${supported}`
);
}
return SUPPORTED_PLATFORMS[key]!;
}
// ---------------------------------------------------------------------------
// Binary cache paths
// ---------------------------------------------------------------------------
export function getCacheDir(): string {
const custom = process.env.CLOAKBROWSER_CACHE_DIR;
if (custom) return custom;
return path.join(os.homedir(), ".cloakbrowser");
}
export function getBinaryDir(): string {
return path.join(getCacheDir(), `chromium-${CHROMIUM_VERSION}`);
}
export function getBinaryPath(): string {
const binaryDir = getBinaryDir();
if (process.platform === "darwin") {
return path.join(binaryDir, "Chromium.app", "Contents", "MacOS", "Chromium");
}
return path.join(binaryDir, "chrome");
}
// ---------------------------------------------------------------------------
// Download URL
// ---------------------------------------------------------------------------
const DOWNLOAD_BASE_URL =
process.env.CLOAKBROWSER_DOWNLOAD_URL ||
"https://github.com/CloakHQ/chromium-stealth-builds/releases/download";
export function getDownloadUrl(): string {
const tag = getPlatformTag();
return `${DOWNLOAD_BASE_URL}/v${CHROMIUM_VERSION}/cloakbrowser-${tag}.tar.gz`;
}
// ---------------------------------------------------------------------------
// Local binary override
// ---------------------------------------------------------------------------
export function getLocalBinaryOverride(): string | undefined {
return process.env.CLOAKBROWSER_BINARY_PATH || undefined;
}
// ---------------------------------------------------------------------------
// Default stealth arguments
// ---------------------------------------------------------------------------
export function getDefaultStealthArgs(): string[] {
const seed = Math.floor(Math.random() * 90000) + 10000; // 10000-99999
return [
"--no-sandbox",
"--disable-blink-features=AutomationControlled",
`--fingerprint=${seed}`,
"--fingerprint-platform=windows",
"--fingerprint-hardware-concurrency=8",
"--fingerprint-gpu-vendor=NVIDIA Corporation",
"--fingerprint-gpu-renderer=NVIDIA GeForce RTX 3070",
];
}
+250
View File
@@ -0,0 +1,250 @@
/**
* Binary download and cache management for cloakbrowser.
* Downloads the patched Chromium binary on first use, caches it locally.
* Mirrors Python cloakbrowser/download.py.
*/
import fs from "node:fs";
import path from "node:path";
import { pipeline } from "node:stream/promises";
import { createWriteStream } from "node:fs";
import { extract as tarExtract } from "tar";
import type { BinaryInfo } from "./types.js";
import {
CHROMIUM_VERSION,
getBinaryDir,
getBinaryPath,
getDownloadUrl,
getLocalBinaryOverride,
getPlatformTag,
getCacheDir,
} from "./config.js";
const DOWNLOAD_TIMEOUT_MS = 600_000; // 10 minutes
// ---------------------------------------------------------------------------
// Public API
// ---------------------------------------------------------------------------
/**
* Ensure the stealth Chromium binary is available. Download if needed.
* Returns the path to the chrome executable.
*/
export async function ensureBinary(): Promise<string> {
// Check for local override
const localOverride = getLocalBinaryOverride();
if (localOverride) {
if (!fs.existsSync(localOverride)) {
throw new Error(
`CLOAKBROWSER_BINARY_PATH set to '${localOverride}' but file does not exist`
);
}
console.log(`[cloakbrowser] Using local binary override: ${localOverride}`);
return localOverride;
}
// Check if binary is cached
const binaryPath = getBinaryPath();
if (fs.existsSync(binaryPath) && isExecutable(binaryPath)) {
return binaryPath;
}
// Download
console.log(
`[cloakbrowser] Stealth Chromium ${CHROMIUM_VERSION} not found. Downloading for ${getPlatformTag()}...`
);
await downloadAndExtract();
if (!fs.existsSync(binaryPath)) {
throw new Error(
`Download completed but binary not found at expected path: ${binaryPath}. ` +
`This may indicate a packaging issue. Please report at ` +
`https://github.com/CloakHQ/cloakbrowser/issues`
);
}
return binaryPath;
}
/** Remove all cached binaries. Forces re-download on next launch. */
export function clearCache(): void {
const cacheDir = getCacheDir();
if (fs.existsSync(cacheDir)) {
fs.rmSync(cacheDir, { recursive: true, force: true });
console.log(`[cloakbrowser] Cache cleared: ${cacheDir}`);
}
}
/** Return info about the current binary installation. */
export function binaryInfo(): BinaryInfo {
const binaryPath = getBinaryPath();
return {
version: CHROMIUM_VERSION,
platform: getPlatformTag(),
binaryPath,
installed: fs.existsSync(binaryPath),
cacheDir: getBinaryDir(),
downloadUrl: getDownloadUrl(),
};
}
// ---------------------------------------------------------------------------
// Internal helpers
// ---------------------------------------------------------------------------
async function downloadAndExtract(): Promise<void> {
const url = getDownloadUrl();
const binaryDir = getBinaryDir();
// Create cache dir
fs.mkdirSync(path.dirname(binaryDir), { recursive: true });
// Download to temp file (atomic — no partial downloads in cache)
const tmpPath = path.join(
path.dirname(binaryDir),
`_download_${Date.now()}.tar.gz`
);
try {
await downloadFile(url, tmpPath);
await extractArchive(tmpPath, binaryDir);
} finally {
// Clean up temp file
if (fs.existsSync(tmpPath)) {
fs.unlinkSync(tmpPath);
}
}
}
async function downloadFile(url: string, dest: string): Promise<void> {
console.log(`[cloakbrowser] Downloading from ${url}`);
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), DOWNLOAD_TIMEOUT_MS);
try {
const response = await fetch(url, {
signal: controller.signal,
redirect: "follow",
});
if (!response.ok) {
throw new Error(`Download failed: HTTP ${response.status} ${response.statusText}`);
}
if (!response.body) {
throw new Error("Download failed: empty response body");
}
const total = Number(response.headers.get("content-length") || 0);
let downloaded = 0;
let lastLoggedPct = -1;
const fileStream = createWriteStream(dest);
const reader = response.body.getReader();
// Stream chunks to file with progress logging
while (true) {
const { done, value } = await reader.read();
if (done) break;
fileStream.write(value);
downloaded += value.length;
if (total > 0) {
const pct = Math.floor((downloaded / total) * 100);
if (pct >= lastLoggedPct + 10) {
lastLoggedPct = pct;
const dlMB = Math.floor(downloaded / (1024 * 1024));
const totalMB = Math.floor(total / (1024 * 1024));
console.log(
`[cloakbrowser] Download progress: ${pct}% (${dlMB}/${totalMB} MB)`
);
}
}
}
// Wait for file stream to finish
await new Promise<void>((resolve, reject) => {
fileStream.end(() => resolve());
fileStream.on("error", reject);
});
const sizeMB = Math.floor(fs.statSync(dest).size / (1024 * 1024));
console.log(`[cloakbrowser] Download complete: ${sizeMB} MB`);
} finally {
clearTimeout(timeout);
}
}
async function extractArchive(
archivePath: string,
destDir: string
): Promise<void> {
console.log(`[cloakbrowser] Extracting to ${destDir}`);
// Clean existing dir if partial download existed
if (fs.existsSync(destDir)) {
fs.rmSync(destDir, { recursive: true, force: true });
}
fs.mkdirSync(destDir, { recursive: true });
// Extract with tar — the 'tar' package handles symlink/traversal safety
await tarExtract({
file: archivePath,
cwd: destDir,
// Security: strip leading path components and reject absolute paths
strip: 0,
filter: (entryPath: string) => {
// Reject absolute paths and path traversal
if (path.isAbsolute(entryPath) || entryPath.includes("..")) {
console.warn(
`[cloakbrowser] Skipping suspicious archive entry: ${entryPath}`
);
return false;
}
return true;
},
});
// Flatten single subdirectory if needed
flattenSingleSubdir(destDir);
// Make binary executable
const binaryPath = getBinaryPath();
if (fs.existsSync(binaryPath)) {
fs.chmodSync(binaryPath, 0o755);
console.log(`[cloakbrowser] Binary ready: ${binaryPath}`);
}
}
/**
* If extraction created a single subdirectory, move its contents up.
* Many tarballs wrap files in a top-level directory.
*/
function flattenSingleSubdir(destDir: string): void {
const entries = fs.readdirSync(destDir);
if (entries.length === 1) {
const subdir = path.join(destDir, entries[0]!);
if (fs.statSync(subdir).isDirectory()) {
const children = fs.readdirSync(subdir);
for (const child of children) {
fs.renameSync(
path.join(subdir, child),
path.join(destDir, child)
);
}
fs.rmdirSync(subdir);
}
}
}
function isExecutable(filePath: string): boolean {
try {
fs.accessSync(filePath, fs.constants.X_OK);
return true;
} catch {
return false;
}
}
+28
View File
@@ -0,0 +1,28 @@
/**
* CloakBrowser — Stealth Chromium for Node.js
*
* Default export uses Playwright. For Puppeteer, import from 'cloakbrowser/puppeteer'.
*
* @example
* ```ts
* // Playwright (default)
* import { launch } from 'cloakbrowser';
* const browser = await launch();
*
* // Puppeteer
* import { launch } from 'cloakbrowser/puppeteer';
* const browser = await launch();
* ```
*/
// Launch functions (Playwright API)
export { launch, launchContext } from "./playwright.js";
// Binary management
export { ensureBinary, clearCache, binaryInfo } from "./download.js";
// Config
export { CHROMIUM_VERSION, getDefaultStealthArgs } from "./config.js";
// Types
export type { LaunchOptions, LaunchContextOptions, BinaryInfo } from "./types.js";
+99
View File
@@ -0,0 +1,99 @@
/**
* Playwright launch wrapper for cloakbrowser.
* Mirrors Python cloakbrowser/browser.py.
*/
import type { Browser, BrowserContext } from "playwright-core";
import type { LaunchOptions, LaunchContextOptions } from "./types.js";
import { getDefaultStealthArgs } from "./config.js";
import { ensureBinary } from "./download.js";
/**
* 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");
const binaryPath = process.env.CLOAKBROWSER_BINARY_PATH || (await ensureBinary());
const args = buildArgs(options);
const browser = await chromium.launch({
executablePath: binaryPath,
headless: options.headless ?? true,
args,
ignoreDefaultArgs: ["--enable-automation"],
...(options.proxy ? { proxy: { server: options.proxy } } : {}),
...options.launchOptions,
});
return browser;
}
/**
* 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...',
* viewport: { width: 1920, height: 1080 },
* });
* 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> {
const browser = await launch(options);
let context: BrowserContext;
try {
context = await browser.newContext({
...(options.userAgent ? { userAgent: options.userAgent } : {}),
...(options.viewport ? { viewport: options.viewport } : {}),
...(options.locale ? { locale: options.locale } : {}),
...(options.timezoneId ? { timezoneId: options.timezoneId } : {}),
});
} catch (err) {
await browser.close();
throw err;
}
// Patch close() to also close the browser
const origClose = context.close.bind(context);
context.close = async () => {
await origClose();
await browser.close();
};
return context;
}
// ---------------------------------------------------------------------------
// Internal
// ---------------------------------------------------------------------------
function buildArgs(options: LaunchOptions): string[] {
const args: string[] = [];
if (options.stealthArgs !== false) {
args.push(...getDefaultStealthArgs());
}
if (options.args) {
args.push(...options.args);
}
return args;
}
+59
View File
@@ -0,0 +1,59 @@
/**
* Puppeteer launch wrapper for cloakbrowser.
* Alternative to the Playwright wrapper for users who prefer Puppeteer.
*/
import type { Browser } from "puppeteer-core";
import type { LaunchOptions } from "./types.js";
import { getDefaultStealthArgs } from "./config.js";
import { ensureBinary } from "./download.js";
/**
* Launch stealth Chromium browser via Puppeteer.
*
* @example
* ```ts
* import { launch } from 'cloakbrowser/puppeteer';
* 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 puppeteer = await import("puppeteer-core");
const binaryPath = process.env.CLOAKBROWSER_BINARY_PATH || (await ensureBinary());
const args = buildArgs(options);
// Puppeteer handles proxy via CLI args, not a separate option
if (options.proxy) {
args.push(`--proxy-server=${options.proxy}`);
}
const browser = await puppeteer.default.launch({
executablePath: binaryPath,
headless: options.headless ?? true,
args,
ignoreDefaultArgs: ["--enable-automation"],
...options.launchOptions,
});
return browser;
}
// ---------------------------------------------------------------------------
// Internal
// ---------------------------------------------------------------------------
function buildArgs(options: LaunchOptions): string[] {
const args: string[] = [];
if (options.stealthArgs !== false) {
args.push(...getDefaultStealthArgs());
}
if (options.args) {
args.push(...options.args);
}
return args;
}
+36
View File
@@ -0,0 +1,36 @@
/**
* Shared types for cloakbrowser launch wrappers.
*/
export interface LaunchOptions {
/** Run in headless mode (default: true). */
headless?: boolean;
/** Proxy server URL, e.g. 'http://proxy:8080' or 'socks5://proxy:1080'. */
proxy?: string;
/** Additional Chromium CLI arguments. */
args?: string[];
/** Include default stealth fingerprint args (default: true). Set false to use custom --fingerprint flags. */
stealthArgs?: boolean;
/** Raw options passed directly to playwright/puppeteer launch(). */
launchOptions?: Record<string, unknown>;
}
export interface LaunchContextOptions extends LaunchOptions {
/** Custom user agent string. */
userAgent?: string;
/** Viewport size. */
viewport?: { width: number; height: number };
/** Browser locale, e.g. "en-US". */
locale?: string;
/** Timezone, e.g. "America/New_York". */
timezoneId?: string;
}
export interface BinaryInfo {
version: string;
platform: string;
binaryPath: string;
installed: boolean;
cacheDir: string;
downloadUrl: string;
}