21 / server.js
senku21230's picture
Update server.js
29f38ad verified
/**
* ============================================================================
* ULTIMATE AI BROWSER ENGINE (GOD-MODE) - ESM VERSION
* Status: Fixed ReferenceError: require is not defined
* ============================================================================
*/
import express from 'express';
import http from 'http';
import { WebSocketServer } from 'ws';
import puppeteer from 'puppeteer-extra';
import StealthPlugin from 'puppeteer-extra-plugin-stealth';
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import { execSync } from 'child_process';
// ESM-এ __dirname এবং __filename ডিফাইন করার প্রফেশনাল উপায়
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
// Apply Stealth Plugin
puppeteer.use(StealthPlugin());
const app = express();
const server = http.createServer(app);
const wss = new WebSocketServer({ server });
const PORT = process.env.PORT || 3000;
const DATASET_REPO = "Senku21230/Browser-Extensions";
const EXTENSION_PATH = '/tmp/extensions';
// Global State Management
let browser = null;
let pages = [];
let activePageIndex = 0;
let cdpSession = null;
/**
* ============================================================================
* 1. MAGIC DATASET SYNC MECHANISM
* ============================================================================
*/
function syncExtensionsFromDataset() {
console.log("[SYSTEM] Initializing Persistent Extension Storage...");
const hfToken = process.env.HF_TOKEN;
if (!hfToken) {
console.error("[CRITICAL WARNING] HF_TOKEN missing!");
if (!fs.existsSync(EXTENSION_PATH)) fs.mkdirSync(EXTENSION_PATH, { recursive: true });
return;
}
try {
if (fs.existsSync(EXTENSION_PATH)) {
fs.rmSync(EXTENSION_PATH, { recursive: true, force: true });
}
console.log(`[STORAGE] Syncing: ${DATASET_REPO}...`);
const cloneCmd = `git clone https://oauth2:${hfToken}@huggingface.co/datasets/${DATASET_REPO} ${EXTENSION_PATH}`;
execSync(cloneCmd, { stdio: 'ignore' });
console.log("[STORAGE] Sync Complete!");
} catch (error) {
console.error("[ERROR] Sync Failed.");
if (!fs.existsSync(EXTENSION_PATH)) fs.mkdirSync(EXTENSION_PATH, { recursive: true });
}
}
/**
* ============================================================================
* 2. AI TOOL REGISTRY (THE MASTER BRAIN - PART A)
* ============================================================================
*/
const ai_tools = [
// --- 1. CORE MASTER TOOL ---
{
name: "basic_navigation_controller",
description: "CORE INTERACTION MASTER: Handles navigate, click, type, scroll, and extract actions. Parameters: 'action_type', 'url', 'selector', 'text_to_type', 'direction'. Returns fully rendered DOM converted to clean markdown for 'extract'."
},
// --- 2. CYBER & HACKING TOOLS ---
{
name: "deep_network_v8_interceptor",
description: "CRITICAL NETWORK HACK: Hooks into V8 memory via CDP to intercept encrypted payloads (Authorization Bearer Tokens, Refresh Cookies) before hitting the cloud. Returns a ready-to-execute cURL command."
},
{
name: "visual_ocr_canvas_piercer",
description: "ADVANCED VISION ENGINE: Captures 4K screenshots, runs deep OCR to calculate X/Y coordinates of text hidden in WebGL/Canvas, and executes hardware-level mouse clicks."
},
{
name: "deep_shadow_dom_piercer",
description: "DOM PENETRATION PROTOCOL: Overwrites 'attachShadow' to force all Closed Shadow Roots open. Recursively extracts deeply nested HTML and JSON data invisible to standard scrapers."
},
{
name: "auto_api_reverse_engineering",
description: "BACKGROUND API SCANNER: Passively monitors XHR/Fetch calls, deduces pagination logic, and returns a JSON map of unauthenticated backend API endpoints."
},
{
name: "network_payload_modifier",
description: "REAL-TIME TRAFFIC MUTATION: Intercepts and rewrites HTTP responses before rendering. Parameter: 'target_url_pattern' and 'mutation_json'. Useful for unlocking client-side premium states."
},
{
name: "custom_extension_loader",
description: "PERSISTENT STORAGE INJECTOR: Dynamically loads extensions from /tmp/extensions and relaunches the browser engine seamlessly."
},
{
name: "start_recording",
description: "MEDIA ENGINE (START): Initializes an FFMPEG stream bound to the CDP screencast to record a 1080p .mp4 video of the browser session."
},
{
name: "stop_recording",
description: "MEDIA ENGINE (STOP): Safely terminates the FFMPEG stream and returns the absolute download URL of the recorded session."
},
{
name: "auto_captcha_solver",
description: "SECURITY BYPASS: Autonomous bypass sequence for Cloudflare Turnstile, hCaptcha, or reCAPTCHA using audio-payloads and vision models."
},
{
name: "file_manager_io",
description: "STORAGE I/O: Intercepts native downloads to save files to the server, or uses CDP to force local server files into secure file upload inputs."
},
{
name: "media_inventory",
description: "SYSTEM MANAGEMENT: Recursively scans the server's output directories and returns a JSON inventory of all generated .mp4 videos and .png screenshots."
},
{
name: "smart_cleanup",
description: "SYSTEM MANAGEMENT: Executes permanent deletion of server files based on URL or file name commands."
},
// --- 3. CORE EXTRACTION & SCRIPTING ---
{
name: "evaluate_javascript",
description: "BROWSER CONSOLE: Injects and executes raw JavaScript code within the active page's context. Parameter: 'js_code_string'."
},
{
name: "inject_custom_cookies",
description: "SESSION HIJACKING: Injects predefined session cookies into the browser context to bypass login screens. Parameter: 'cookie_json_array'."
},
{
name: "take_screenshot",
description: "VISUAL CAPTURE: Captures a high-resolution .png screenshot of the current tab. Parameter optional: 'full_page' (boolean)."
},
{
name: "hover_element",
description: "UI INTERACTION: Simulates physical mouse hover over an element to trigger dropdowns or lazy-loads. Parameter: 'selector'."
},
{
name: "wait_for_selector",
description: "EXECUTION DELAY: Pauses AI execution until a specific DOM element appears. Parameters: 'selector' and optional 'timeout_ms'."
},
{
name: "get_element_attributes",
description: "DATA EXTRACTION: Retrieves all HTML attributes (href, src, class, id) of a specific element without extracting inner text. Parameter: 'selector'."
},
{
name: "switch_to_iframe",
description: "CONTEXT SWITCHING: Shifts Puppeteer execution context into a nested iframe to interact with embedded widgets. Parameter: 'iframe_selector'."
},
{
name: "exit_iframe",
description: "CONTEXT SWITCHING: Returns the execution context from a nested iframe back to the main document."
},
{
name: "emulate_device_viewport",
description: "DEVICE SPOOFING: Alters viewport dimensions and User-Agent to emulate a specific device. Parameter: 'device_name'."
},
{
name: "set_geolocation",
description: "HARDWARE SPOOFING: Overrides HTML5 Geolocation API with fake GPS coordinates. Parameters: 'latitude', 'longitude'."
},
// --- 4. ADVANCED DOM & EXTRACTION ---
{
name: "extract_table_data",
description: "DATA EXTRACTION: Extracts an HTML <table> into a structured JSON array of objects mapping headers to row values. Parameter: 'selector'."
},
{
name: "extract_list_data",
description: "DATA EXTRACTION: Targets a <ul> or <ol> list and extracts <li> items into a clean array of strings. Parameter: 'selector'."
},
{
name: "extract_image_sources",
description: "DATA EXTRACTION: Scans the entire active page or container and extracts all 'src' URLs from <img> tags."
},
{
name: "extract_all_links",
description: "DATA EXTRACTION: Scans the active DOM and extracts all 'href' URLs from <a> tags."
},
{
name: "extract_metadata",
description: "DATA EXTRACTION: Extracts SEO and Social Media metadata from the <head> tag (OpenGraph, Twitter cards)."
},
{
name: "extract_json_ld",
description: "DATA EXTRACTION: Parses <script type='application/ld+json'> tags to extract high-value SEO microdata without parsing the visible DOM."
},
{
name: "extract_regex_matches",
description: "DATA EXTRACTION: Executes a raw Regular Expression pattern against the outerHTML to find hidden API keys or UUIDs. Parameter: 'regex_pattern'."
},
{
name: "get_raw_page_source",
description: "DATA EXTRACTION: Returns the absolute, unmodified HTML source code of the current page as a raw string."
},
// --- 5. NETWORK OPTIMIZATION & OVERRIDES ---
{
name: "set_user_agent",
description: "NETWORK OVERRIDE: Completely replaces the browser's User-Agent string. Parameter: 'user_agent_string'."
},
{
name: "set_extra_http_headers",
description: "NETWORK OVERRIDE: Injects custom HTTP headers into every outgoing request. Parameter: 'headers_json'."
},
{
name: "bypass_basic_auth",
description: "SECURITY OVERRIDE: Injects username and password to automatically bypass HTTP Basic Authentication popups."
},
{
name: "block_urls",
description: "NETWORK EFFICIENCY: Forcefully aborts network requests matching a specific URL pattern. Parameter: 'url_patterns_array'."
},
{
name: "disable_javascript",
description: "NETWORK EFFICIENCY: Temporarily disables JavaScript execution for lightning-fast scraping of static sites."
},
{
name: "enable_javascript",
description: "NETWORK EFFICIENCY: Re-enables JavaScript execution for the active tab."
},
{
name: "intercept_and_abort_images",
description: "NETWORK EFFICIENCY: Installs a CDP interceptor to block all image requests (.jpg, .png, .webp) to save RAM."
},
{
name: "intercept_and_abort_css",
description: "NETWORK EFFICIENCY: Blocks all stylesheet (.css) requests for faster unstyled DOM parsing."
},
// --- 6. TAB & WINDOW MANAGEMENT ---
{
name: "open_new_tab",
description: "TAB MANAGEMENT: Opens a completely new, blank browser tab and sets it as the active context."
},
{
name: "close_current_tab",
description: "TAB MANAGEMENT: Safely closes the currently active browser tab and shifts focus to the adjacent tab."
},
{
name: "get_all_tabs",
description: "TAB MANAGEMENT: Retrieves a JSON array of all currently open tabs with their URLs and Titles."
},
{
name: "bring_page_to_front",
description: "WINDOW MANAGEMENT: Forces the current Puppeteer page instance to the absolute front of the OS window stack."
},
{
name: "get_window_metrics",
description: "VIEWPORT ANALYSIS: Returns window.innerWidth, window.innerHeight, and standard scroll heights."
},
// --- 7. ADVANCED INPUT (KEYBOARD & MOUSE) ---
{
name: "press_key",
description: "HARDWARE INPUT: Simulates the physical pressing of a single keyboard key (e.g., 'Enter', 'Escape'). Parameter: 'key_name'."
},
{
name: "hold_key",
description: "HARDWARE INPUT: Simulates holding down a modifier key ('Shift', 'Control') for multi-selection. Parameter: 'key_name'."
},
{
name: "mouse_drag_and_drop",
description: "HARDWARE INPUT: Moves mouse to source, clicks and holds, drags to target, and releases. Parameters: 'source_selector', 'target_selector'."
},
{
name: "right_click",
description: "HARDWARE INPUT: Simulates a physical right-click on a specific DOM element. Parameter: 'selector'."
},
{
name: "double_click",
description: "HARDWARE INPUT: Simulates a rapid double left-click on an element. Parameter: 'selector'."
},
{
name: "mouse_move_human_path",
description: "ANTI-BOT BYPASS: Moves cursor using generated Bezier curves and variable speeds to bypass Datadome. Parameters: 'target_x', 'target_y'."
},
{
name: "mouse_scroll_hardware",
description: "ANTI-BOT BYPASS: Simulates physical hardware ticks of a mouse scroll wheel. Parameters: 'delta_x', 'delta_y'."
},
{
name: "type_text_human_like",
description: "ANTI-BOT BYPASS: Types string with randomized delays between keystrokes to mimic human rhythms. Parameters: 'selector', 'text_to_type'."
},
{
name: "press_keyboard_shortcut",
description: "HARDWARE INPUT: Executes multi-key combination shortcuts (e.g., ['Control', 'C']). Parameter: 'keys_array'."
},
// ============================================================================
// CONTINUED IN PART 2 (DO NOT CLOSE THE ARRAY YET)
// ============================================================================
// --- 8. FORM & VALIDATION CONTROL ---
{
name: "select_dropdown_option",
description: "FORM CONTROL: Selects a specific <option> inside a native <select> dropdown element. Parameters: 'selector' and 'value_or_text'."
},
{
name: "check_checkbox",
description: "FORM CONTROL: Forces a checkbox or radio button into a 'checked' state. Parameter: 'selector'."
},
{
name: "uncheck_checkbox",
description: "FORM CONTROL: Forces a checkbox or radio button into an 'unchecked' state. Parameter: 'selector'."
},
{
name: "clear_input_field",
description: "FORM CONTROL: Forcefully deletes all existing text inside an <input> or <textarea> element before typing new data. Parameter: 'selector'."
},
{
name: "submit_form_event",
description: "FORM CONTROL: Triggers the native HTML5 'submit' event directly on a <form> element. Parameter: 'form_selector'."
},
{
name: "native_file_upload",
description: "STORAGE I/O: Attaches an array of absolute local server file paths directly to a standard <input type='file'> element. Parameters: 'selector', 'file_paths_array'."
},
{
name: "check_element_exists",
description: "DOM VALIDATION: Silently verifies if a specific CSS/XPath selector exists in the DOM structure. Returns boolean. Parameter: 'selector'."
},
{
name: "check_element_visible",
description: "DOM VALIDATION: Determines if an existing element is actually visible on the screen (not hidden by CSS). Returns boolean. Parameter: 'selector'."
},
{
name: "get_element_text",
description: "DATA EXTRACTION: Extracts and returns the clean, trimmed 'innerText' of a specific HTML element. Parameter: 'selector'."
},
{
name: "get_element_html",
description: "DATA EXTRACTION: Extracts and returns the raw 'outerHTML' string of a specific HTML element. Parameter: 'selector'."
},
// --- 9. WAIT & SYNC EVENTS ---
{
name: "wait_for_network_idle",
description: "EXECUTION SYNC: Pauses AI script execution until all background network activity (XHR, Fetch) is idle for at least 500ms."
},
{
name: "wait_for_text_content",
description: "EXECUTION SYNC: Pauses execution until a specific text string dynamically appears inside a designated DOM element. Parameters: 'selector', 'expected_text'."
},
{
name: "wait_for_iframe",
description: "EXECUTION SYNC: Pauses AI execution until a specific iframe dynamically loads. Parameter: 'iframe_selector'."
},
{
name: "sleep",
description: "EXECUTION SYNC: Forces a hard, unconditional pause in execution. Parameter: 'milliseconds'."
},
// --- 10. STORAGE & CACHE HACKING ---
{
name: "get_cookies",
description: "SESSION THEFT: Retrieves all active cookies currently accessible by the browser for the current domain."
},
{
name: "delete_cookie",
description: "STATE MANIPULATION: Forcefully deletes a specific cookie by its name. Parameter: 'cookie_name'."
},
{
name: "clear_local_storage",
description: "STATE MANIPULATION: Executes 'localStorage.clear()' to wipe all persistent frontend data."
},
{
name: "clear_session_storage",
description: "STATE MANIPULATION: Executes 'sessionStorage.clear()' to wipe temporary frontend data."
},
{
name: "set_local_storage_item",
description: "STATE INJECTION: Forcefully injects a key-value pair directly into the browser's LocalStorage. Parameters: 'key', 'value'."
},
{
name: "set_session_storage_item",
description: "STATE INJECTION: Forcefully injects a key-value pair directly into the browser's SessionStorage. Parameters: 'key', 'value'."
},
{
name: "get_local_storage_item",
description: "STATE THEFT: Reads and returns the value of a specific key from the browser's LocalStorage. Parameter: 'key'."
},
{
name: "clear_cache_and_cookies",
description: "BROWSER STATE: Completely wipes all active cookies, LocalStorage, and SessionStorage for the current domain."
},
// --- 11. MEDIA & DOM MUTATION ---
{
name: "extract_audio_video_sources",
description: "DATA EXTRACTION: Scans the live DOM specifically for <audio> and <video> tags and returns 'src' URLs."
},
{
name: "play_media",
description: "MEDIA CONTROL: Forces a specific HTML5 media element to start playing. Parameter: 'selector'."
},
{
name: "pause_media",
description: "MEDIA CONTROL: Forces a specific media element to pause. Parameter: 'selector'."
},
{
name: "mute_media",
description: "MEDIA CONTROL: Sets the 'muted' property of a media element to true. Parameter: 'selector'."
},
{
name: "set_media_playback_rate",
description: "MEDIA CONTROL: Modifies the playback speed of a media element. Parameters: 'selector', 'rate'."
},
{
name: "remove_element",
description: "DOM MUTATION: Completely rips a specific HTML element out of the live DOM using '.remove()'. Parameter: 'selector'."
},
{
name: "inject_custom_css",
description: "DOM MUTATION: Injects a raw block of CSS rules directly into the page's <head>. Parameter: 'css_string'."
},
{
name: "change_element_text",
description: "DOM MUTATION: Overwrites the innerText of a specific element dynamically. Parameters: 'selector', 'new_text'."
},
{
name: "set_element_attribute",
description: "DOM MUTATION: Forces a new value into a specific HTML attribute. Parameters: 'selector', 'attribute_name', 'value'."
},
{
name: "remove_element_attribute",
description: "DOM MUTATION: Strips an attribute entirely from an element. Parameters: 'selector', 'attribute_name'."
},
// --- 12. ENVIRONMENT SPOOFING ---
{
name: "spoof_timezone",
description: "ENVIRONMENT SPOOFING: Overrides the browser's native timezone ID. Parameter: 'timezone_id' (e.g., 'America/New_York')."
},
{
name: "spoof_language",
description: "ENVIRONMENT SPOOFING: Modifies the navigator.language and Accept-Language headers. Parameter: 'locale'."
},
{
name: "override_permissions",
description: "ENVIRONMENT SPOOFING: Automatically grants critical browser permissions for a specific origin. Parameters: 'origin_url', 'permissions_array'."
},
{
name: "emulate_network_conditions",
description: "ENVIRONMENT SPOOFING: Forces the browser to simulate specific network speeds (e.g., Slow 3G, Offline). Parameters: 'download_throughput', 'upload_throughput', 'latency'."
},
{
name: "set_cpu_throttling",
description: "ENVIRONMENT SPOOFING: Artificially slows down the V8 JavaScript engine execution speed. Parameter: 'rate'."
},
{
name: "emulate_color_scheme",
description: "ENVIRONMENT SPOOFING: Forces the browser to request 'dark' or 'light' CSS media feature. Parameter: 'scheme'."
},
{
name: "emulate_media_type",
description: "ENVIRONMENT SPOOFING: Changes the CSS media type of the page (e.g., 'print', 'screen'). Parameter: 'type'."
},
{
name: "emulate_touch_device",
description: "ENVIRONMENT SPOOFING: Converts all physical mouse events into native mobile Touch events."
},
// --- 13. DIALOGS & SECURITY OVERRIDES ---
{
name: "accept_browser_alert",
description: "DIALOG CONTROL: Pre-configures the browser to automatically click 'OK' or 'Accept' on JavaScript alerts."
},
{
name: "dismiss_browser_alert",
description: "DIALOG CONTROL: Pre-configures the browser to automatically click 'Cancel' or dismiss JavaScript dialogs."
},
{
name: "answer_browser_prompt",
description: "DIALOG CONTROL: Pre-configures the browser to type a specific string into a prompt() dialog and accept. Parameter: 'prompt_text'."
},
{
name: "get_dialog_message",
description: "DIALOG CONTROL: Extracts and returns the text message displayed inside the currently active JavaScript popup dialog."
},
{
name: "strip_anti_copy_listeners",
description: "SECURITY OVERRIDE: Recursively removes 'contextmenu', 'copy', 'paste' listeners to allow right-clicking and highlighting."
},
{
name: "ignore_https_errors",
description: "SECURITY OVERRIDE: Bypasses 'NET::ERR_CERT_AUTHORITY_INVALID' or expired SSL certificate warnings."
},
// --- 14. MISCELLANEOUS & DEBUGGING ---
{
name: "get_current_url",
description: "NAVIGATION STATE: Instantly retrieves and returns the absolute URL currently loaded in the active tab."
},
{
name: "reload_page",
description: "NAVIGATION STATE: Triggers a reload of the active document. Parameter optional: 'ignore_cache'."
},
{
name: "navigate_back",
description: "NAVIGATION STATE: Simulates clicking the browser's native 'Back' button."
},
{
name: "navigate_forward",
description: "NAVIGATION STATE: Simulates clicking the browser's native 'Forward' button."
},
{
name: "get_page_title",
description: "DATA EXTRACTION: Retrieves the current <title> string of the active document."
},
{
name: "focus_element",
description: "DOM MANIPULATION: Calls the native '.focus()' method on a specific input or button. Parameter: 'selector'."
},
{
name: "blur_element",
description: "DOM MANIPULATION: Calls the native '.blur()' method to remove focus."
},
{
name: "scroll_to_bottom",
description: "VIEWPORT CONTROL: Instantly or smoothly scrolls to the absolute bottom of the document. Parameter: 'smooth'."
},
{
name: "scroll_to_top",
description: "VIEWPORT CONTROL: Scrolls back to the absolute top of the document. Parameter: 'smooth'."
},
{
name: "get_element_bounding_box",
description: "UI ANALYSIS: Calculates physical coordinates and dimensions of an element relative to the viewport. Parameter: 'selector'."
},
{
name: "evaluate_xpath_expression",
description: "ADVANCED QUERYING: Executes an XPath 1.0 expression and returns matched nodes. Parameter: 'xpath_expression'."
},
{
name: "listen_for_console_logs",
description: "DEBUGGING: Attaches a persistent event listener to capture all frontend 'console.log' outputs."
},
{
name: "intercept_websocket_frames",
description: "NETWORK HACKING: Monitors and captures raw WebSocket message frames transmitted by the active tab."
},
{
name: "highlight_element",
description: "VISUAL DEBUGGING: Injects inline CSS to draw a glowing red border around an element. Parameter: 'selector'."
}
]; // <--- ARRAY PROPERLY CLOSED HERE
/**
* ============================================================================
* 3. BROWSER INITIALIZATION & CONTEXT MANAGEMENT
* ============================================================================
*/
async function initBrowser() {
console.log("[SYSTEM] Booting God-Mode Stealth Engine...");
// Auto-Sync extensions before launching
syncExtensionsFromDataset();
const launchArgs = [
'--no-sandbox',
'--disable-setuid-sandbox',
'--disable-dev-shm-usage',
'--disable-blink-features=AutomationControlled',
'--window-size=1280,800',
'--disable-web-security',
'--disable-features=IsolateOrigins,site-per-process'
];
if (fs.existsSync(EXTENSION_PATH) && fs.readdirSync(EXTENSION_PATH).length > 0) {
launchArgs.push(`--disable-extensions-except=${EXTENSION_PATH}`);
launchArgs.push(`--load-extension=${EXTENSION_PATH}`);
console.log("[SYSTEM] Extensions injected into launch arguments.");
}
try {
browser = await puppeteer.launch({
headless: 'new',
args: launchArgs,
ignoreDefaultArgs: ["--enable-automation"]
});
const defaultPage = await browser.newPage();
await defaultPage.setViewport({ width: 1280, height: 800 });
await defaultPage.evaluateOnNewDocument(() => {
Object.defineProperty(navigator, 'webdriver', { get: () => undefined });
});
pages.push({ id: Date.now(), page: defaultPage, title: "New Tab" });
console.log("[SYSTEM] Browser Engine Online. Core Stealth Active.");
} catch (error) {
console.error("[CRITICAL] Failed to launch browser engine:", error);
}
}
/**
* ============================================================================
* 4. CDP ZERO-LATENCY WEBSOCKET STREAMING
* ============================================================================
*/
async function startRealTimeStream(page, ws) {
try {
if (cdpSession) {
await cdpSession.detach();
}
cdpSession = await page.target().createCDPSession();
console.log("[STREAM] CDP Session attached. Initiating Screencast...");
await cdpSession.send('Page.startScreencast', {
format: 'jpeg',
quality: 65,
everyNthFrame: 1
});
cdpSession.on('Page.screencastFrame', async (frameObject) => {
if (ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({
type: 'stream_frame',
data: frameObject.data,
sessionId: frameObject.sessionId
}));
await cdpSession.send('Page.screencastFrameAck', {
sessionId: frameObject.sessionId
}).catch(() => {});
}
});
} catch (err) {
console.error("[STREAM ERROR] Failed to start screencast:", err.message);
}
}
/**
* ============================================================================
* 5. THE MASTER TOOL DISPATCHER (EXECUTING COMMANDS)
* ============================================================================
*/
async function executeAITool(toolName, parameters) {
if (!browser || pages.length === 0) {
return { status: "error", message: "Engine not running." };
}
const activePage = pages[activePageIndex].page;
console.log(`[EXECUTE] Tool: ${toolName} | Params:`, JSON.stringify(parameters));
try {
switch (toolName) {
case "basic_navigation_controller":
const { action_type, url, selector, text_to_type } = parameters;
if (action_type === "navigate") {
await activePage.goto(url, { waitUntil: 'domcontentloaded', timeout: 30000 });
return { status: "success", url: activePage.url() };
} else if (action_type === "click") {
await activePage.waitForSelector(selector, { visible: true, timeout: 5000 });
await activePage.click(selector);
return { status: "success", action: "clicked" };
} else if (action_type === "type") {
await activePage.waitForSelector(selector, { visible: true });
await activePage.type(selector, text_to_type, { delay: 50 });
return { status: "success", action: "typed" };
} else if (action_type === "extract") {
const html = await activePage.content();
return { status: "success", data: html.substring(0, 5000) + "...[truncated]" };
}
break;
case "deep_shadow_dom_piercer":
console.log("[HACK] Injecting Shadow DOM override script...");
const shadowData = await activePage.evaluate(() => {
function traverseShadows(node) {
let content = node.outerHTML || '';
if (node.shadowRoot) content += traverseShadows(node.shadowRoot);
node.childNodes.forEach(child => content += traverseShadows(child));
return content;
}
return traverseShadows(document.body);
});
return { status: "success", data: shadowData.substring(0, 5000) };
case "deep_network_v8_interceptor":
console.log("[HACK] Hooking into CDP Network domain...");
const session = await activePage.target().createCDPSession();
await session.send('Network.enable');
return new Promise((resolve) => {
session.on('Network.requestWillBeSent', (params) => {
if (params.request.headers['Authorization'] || params.request.headers['authorization']) {
resolve({
status: "success",
url: params.request.url,
raw_curl: `curl -X ${params.request.method} '${params.request.url}' -H 'Authorization: ${params.request.headers['Authorization'] || params.request.headers['authorization']}'`
});
}
});
setTimeout(() => resolve({ status: "timeout", message: "No secure tokens found." }), 10000);
});
case "take_screenshot":
const screenshotPath = path.join(__dirname, 'public', `screenshot_${Date.now()}.png`);
await activePage.screenshot({ path: screenshotPath, fullPage: parameters.full_page || false });
return { status: "success", url: `/public/${path.basename(screenshotPath)}` };
case "open_new_tab":
const newPage = await browser.newPage();
await newPage.setViewport({ width: 1280, height: 800 });
const tabId = Date.now();
pages.push({ id: tabId, page: newPage, title: "New Tab" });
activePageIndex = pages.length - 1;
return { status: "success", tab_id: tabId };
// Default fallback for dynamic execution
default:
console.warn(`[WARNING] Tool '${toolName}' dispatched but requires explicit Puppeteer implementation logic.`);
return { status: "pending", message: `Tool ${toolName} registered and received successfully.` };
}
} catch (error) {
console.error(`[TOOL ERROR] ${toolName} Failed:`, error.message);
return { status: "error", message: error.message };
}
}
/**
* ============================================================================
* ULTIMATE AI BROWSER ENGINE (GOD-MODE) - PART 3
* WebSocket Bridge, Express API, /live Route & Ignition Sequence
* ============================================================================
*/
/**
* ============================================================================
* 6. WEBSOCKET COMMUNICATION (ZERO-LAG BRIDGE)
* ============================================================================
*/
wss.on('connection', async (ws) => {
console.log("[WS] Secure Connection Established with Client UI.");
// Auto-initiate stream for the first available tab
if (pages.length > 0 && pages[activePageIndex]) {
await startRealTimeStream(pages[activePageIndex].page, ws);
}
ws.on('message', async (message) => {
try {
const payload = JSON.parse(message);
// Switching tabs from the Sleek Tab Manager UI
if (payload.type === 'switch_tab') {
const targetIndex = pages.findIndex(p => p.id === payload.tabId);
if (targetIndex !== -1) {
activePageIndex = targetIndex;
await pages[activePageIndex].page.bringToFront();
await startRealTimeStream(pages[activePageIndex].page, ws);
console.log(`[WS] Engine focus shifted to Tab ID: ${payload.tabId}`);
}
}
// Spawning new tabs from the UI button
if (payload.type === 'new_tab') {
const newPage = await browser.newPage();
await newPage.setViewport({ width: 1280, height: 800 });
const tabId = payload.tabId || Date.now();
pages.push({ id: tabId, page: newPage, title: "Target Payload" });
activePageIndex = pages.length - 1;
await newPage.goto('https://www.google.com', { waitUntil: 'domcontentloaded' });
await startRealTimeStream(newPage, ws);
console.log(`[WS] New tab initialized and streamed. ID: ${tabId}`);
}
} catch (error) {
console.error("[WS ERROR] Messaging Failure:", error.message);
}
});
ws.on('close', () => {
console.log("[WS] Session Terminated. Stream paused.");
if (cdpSession) cdpSession.detach().catch(() => {});
});
});
/**
* ============================================================================
* 7. EXPRESS ROUTES (THE API LAYER)
* ============================================================================
*/
// Global Middleware for JSON payloads
app.use(express.json());
// Serving Static Files (Screenshots, etc.)
app.use('/public', express.static(path.join(__dirname, 'public')));
/**
* @route GET /live
* @desc Serves the Sleek Glassmorphism Dashboard
*/
app.get('/live', (req, res) => {
const dashboard = path.join(__dirname, 'public', 'index.html');
if (fs.existsSync(dashboard)) {
res.sendFile(dashboard);
} else {
res.status(404).send("<h2>[ERROR 404] UI Dashboard Not Found.</h2><p>Please ensure 'public/index.html' exists.</p>");
}
});
/**
* @route POST /api/execute
* @desc Primary Endpoint for AI Agents to trigger any of the 113 tools
*/
app.post('/api/execute', async (req, res) => {
const { tool_name, parameters } = req.body;
if (!tool_name) {
return res.status(400).json({ error: "No tool name provided." });
}
const output = await executeAITool(tool_name, parameters || {});
res.json(output);
});
/**
* @route GET /status
* @desc System Health & Metric Monitoring
*/
app.get('/status', (req, res) => {
res.json({
engine: "God-Mode v3.0",
online: true,
active_tabs: pages.length,
tools_available: ai_tools.length,
memory_usage: `${(process.memoryUsage().heapUsed / 1024 / 1024).toFixed(2)} MB`
});
});
/**
* ============================================================================
* 8. IGNITION (SERVER START)
* ============================================================================
*/
server.listen(PORT, async () => {
console.log(`\n--- ENGINE IGNITION SUCCESSFUL ---`);
console.log(`[SERVER] Listening on Port: ${PORT}`);
console.log(`[CORE] Total Tools Loaded: ${ai_tools.length}`);
console.log(`[UI] Live Dashboard: http://localhost:${PORT}/live`);
console.log(`----------------------------------\n`);
// Boot the browser engine immediately
await initBrowser();
});