SPFsmartGATE / src /browser.rs
JosephStoneCellAI's picture
Upload 45 files
1269259 verified
// SPF Smart Gateway - Reverse Proxy Browser Engine
// Copyright 2026 Joseph Stone - All Rights Reserved
//
// Reverse proxy web engine for agent browser interaction.
// SPF serves proxied pages on localhost with injected control JavaScript.
// Browser connects TO SPF via WebSocket — no ADB, no CDP, no Android socket isolation.
// All target URLs validated through web::validate_url() for SSRF protection.
//
// Architecture:
// 1. Agent calls spf_web_navigate(url)
// 2. Browser opens http://127.0.0.1:PORT/proxy?url=TARGET
// 3. http.rs route fetches page via ProxyEngine, injects control JS, serves it
// 4. Injected JS opens WebSocket to ws://127.0.0.1:PORT/ws/browser
// 5. Agent sends commands (click/fill/eval/etc) through BrowserSession → channel → WS → JS
// 6. JS executes commands, returns results via same path in reverse
//
// WB-2b: ProxyEngine + BrowserSession + data types
// WB-2c: Control JavaScript (CONTROL_JS const)
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::sync::mpsc;
use std::time::Duration;
// ============================================================================
// PROXY ENGINE — Fetch pages, inject control JS, strip CSP
// ============================================================================
/// Reverse proxy engine — fetches external pages and prepares them for
/// local serving with injected control JavaScript.
pub struct ProxyEngine {
client: reqwest::blocking::Client,
}
impl ProxyEngine {
pub fn new() -> Result<Self, String> {
let client = reqwest::blocking::Client::builder()
.user_agent("Mozilla/5.0 (Linux; Android 13) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Mobile Safari/537.36")
.timeout(Duration::from_secs(30))
.redirect(reqwest::redirect::Policy::limited(10))
.build()
.map_err(|e| format!("Failed to create proxy client: {}", e))?;
Ok(Self { client })
}
/// Fetch a page, set `<base href>`, inject control JS, strip CSP.
/// The `<base href>` tag makes the browser resolve all relative URLs
/// (images, CSS, JS) against the original domain — no URL rewriting needed.
pub fn proxy_page(&self, url: &str, ws_port: u16) -> Result<ProxiedPage, String> {
crate::web::validate_url(url)?;
let resp = self.client.get(url).send()
.map_err(|e| format!("Proxy fetch failed: {}", e))?;
if !resp.status().is_success() {
return Err(format!("HTTP {}: {}", resp.status().as_u16(), url));
}
let content_type = resp.headers()
.get("content-type")
.and_then(|v| v.to_str().ok())
.unwrap_or("text/html")
.to_string();
let body = resp.text()
.map_err(|e| format!("Read body failed: {}", e))?;
let title = extract_title(&body);
// Non-HTML content — return as-is
if !content_type.contains("html") && !body.trim_start().starts_with('<') {
return Ok(ProxiedPage { html: body, content_type, title, original_url: url.to_string() });
}
let base_tag = format!("<base href=\"{}\">", html_escape(url));
let control_js = control_script(ws_port);
let mut html = body;
// Insert <base> after <head>
let lower = html.to_lowercase();
if let Some(pos) = lower.find("<head>") {
html.insert_str(pos + 6, &format!("\n{}\n", base_tag));
} else if let Some(pos) = lower.find("<head ") {
if let Some(close) = html[pos..].find('>') {
html.insert_str(pos + close + 1, &format!("\n{}\n", base_tag));
}
} else if let Some(pos) = lower.find("<html") {
if let Some(close) = html[pos..].find('>') {
html.insert_str(pos + close + 1, &format!("\n<head>{}</head>\n", base_tag));
}
} else {
html = format!("<head>{}</head>\n{}", base_tag, html);
}
// Insert control JS before </body>
let lower = html.to_lowercase();
if let Some(pos) = lower.rfind("</body>") {
html.insert_str(pos, &control_js);
} else {
html.push_str(&control_js);
}
// Strip CSP meta tags that would block our injected JS
html = strip_csp_meta(&html);
Ok(ProxiedPage { html, content_type, title, original_url: url.to_string() })
}
/// Fetch a raw asset (CSS, JS, images) — passthrough proxy for pages
/// that need cross-origin resources routed through localhost.
pub fn proxy_asset(&self, url: &str) -> Result<AssetResponse, String> {
crate::web::validate_url(url)?;
let resp = self.client.get(url).send()
.map_err(|e| format!("Asset fetch failed: {}", e))?;
let content_type = resp.headers()
.get("content-type")
.and_then(|v| v.to_str().ok())
.unwrap_or("application/octet-stream")
.to_string();
let data = resp.bytes()
.map_err(|e| format!("Asset read failed: {}", e))?
.to_vec();
Ok(AssetResponse { data, content_type })
}
}
/// Processed page ready for serving on localhost.
pub struct ProxiedPage {
pub html: String,
pub content_type: String,
pub title: String,
pub original_url: String,
}
/// Raw asset fetched for passthrough proxy.
pub struct AssetResponse {
pub data: Vec<u8>,
pub content_type: String,
}
// ============================================================================
// CHANNEL TYPES — Bridge between BrowserSession (sync) and WS handler (async)
// ============================================================================
/// Channel endpoints for the WebSocket handler in http.rs.
/// Created by BrowserSession::connect(), consumed by the /ws/browser handler.
/// Uses std::sync::mpsc — works across sync/async boundaries.
pub struct WsBrowserChannels {
/// Receives commands from BrowserSession to forward to browser JS
pub cmd_rx: mpsc::Receiver<String>,
/// Sends responses from browser JS back to BrowserSession
pub resp_tx: mpsc::Sender<String>,
}
// ============================================================================
// BROWSER SESSION — Stateful wrapper for MCP tool handlers
// ============================================================================
/// Persistent browser session for agent interaction.
/// Held in ServerState behind Mutex — same pattern as old CDP session.
/// Commands flow: session → cmd_tx → WS handler → browser JS
/// Responses flow: browser JS → WS handler → resp_tx → resp_rx → session
pub struct BrowserSession {
engine: Option<ProxyEngine>,
current_url: String,
history: Vec<String>,
screenshots_dir: String,
screenshot_count: u32,
proxy_port: u16,
next_cmd_id: u32,
cmd_tx: Option<mpsc::Sender<String>>,
resp_rx: Option<mpsc::Receiver<String>>,
}
impl BrowserSession {
pub fn new() -> Self {
let screenshots_dir = format!(
"{}/LIVE/TMP/screenshots",
crate::paths::spf_root().display()
);
Self {
engine: None,
current_url: String::new(),
history: Vec::new(),
screenshots_dir,
screenshot_count: 0,
proxy_port: 0,
next_cmd_id: 0,
cmd_tx: None,
resp_rx: None,
}
}
/// Initialize proxy engine and create communication channels.
/// Returns WsBrowserChannels for the http.rs WebSocket handler to consume.
pub fn connect(&mut self, proxy_port: u16) -> Result<(String, WsBrowserChannels), String> {
let engine = ProxyEngine::new()?;
let (cmd_tx, cmd_rx) = mpsc::channel();
let (resp_tx, resp_rx) = mpsc::channel();
self.engine = Some(engine);
self.cmd_tx = Some(cmd_tx);
self.resp_rx = Some(resp_rx);
self.proxy_port = proxy_port;
self.next_cmd_id = 0;
Ok((
format!("Proxy engine ready on port {}. Browser tools active.", proxy_port),
WsBrowserChannels { cmd_rx, resp_tx },
))
}
/// Navigate to URL — opens browser to proxied page, waits for WS connection.
pub fn navigate(&mut self, url: &str) -> Result<String, String> {
crate::web::validate_url(url)?;
if self.engine.is_none() {
return Err("Not connected. Run spf_web_connect first.".to_string());
}
if !self.current_url.is_empty() {
self.history.push(self.current_url.clone());
}
self.current_url = url.to_string();
// Build proxy URL for browser
let proxy_url = format!(
"http://127.0.0.1:{}/proxy?url={}",
self.proxy_port,
percent_encode(url),
);
// Open browser to proxy URL
open_browser(&proxy_url)?;
// Wait for control JS to connect and send "connected" message
if let Some(ref resp_rx) = self.resp_rx {
match resp_rx.recv_timeout(Duration::from_secs(15)) {
Ok(msg) => {
let parsed: Value = serde_json::from_str(&msg).unwrap_or(json!({}));
let title = parsed.get("title").and_then(|v| v.as_str()).unwrap_or("");
Ok(format!("Navigated to: {} | Title: {}", url, title))
}
Err(_) => Ok(format!(
"Navigated to: {} | Browser opened (page may still be loading)", url
)),
}
} else {
Ok(format!("Navigated to: {} | No WebSocket channel", url))
}
}
/// Send a command to browser JS and wait for matching response.
fn send_command(&mut self, cmd: &str, extra: Value) -> Result<Value, String> {
let cmd_tx = self.cmd_tx.as_ref()
.ok_or("Not connected. Run spf_web_connect first.")?;
let resp_rx = self.resp_rx.as_ref()
.ok_or("Not connected. Run spf_web_connect first.")?;
self.next_cmd_id += 1;
let id = self.next_cmd_id;
let mut msg = extra;
if let Some(obj) = msg.as_object_mut() {
obj.insert("id".to_string(), json!(id));
obj.insert("cmd".to_string(), json!(cmd));
}
cmd_tx.send(msg.to_string())
.map_err(|_| "Browser connection lost. Navigate to a page first.".to_string())?;
// Wait for response with matching ID
let deadline = std::time::Instant::now() + Duration::from_secs(15);
loop {
let remaining = deadline.saturating_duration_since(std::time::Instant::now());
if remaining.is_zero() {
return Err(format!("Timeout waiting for '{}' response", cmd));
}
match resp_rx.recv_timeout(remaining) {
Ok(resp_str) => {
let parsed: Value = serde_json::from_str(&resp_str).unwrap_or(json!({}));
if parsed.get("id").and_then(|v| v.as_u64()) == Some(id as u64) {
let ok = parsed.get("ok").and_then(|v| v.as_bool()).unwrap_or(false);
let result = parsed.get("result").cloned().unwrap_or(json!(null));
return if ok { Ok(result) } else {
Err(result.as_str().unwrap_or("Command failed").to_string())
};
}
// Not our response — skip (could be "connected" event or stale)
}
Err(mpsc::RecvTimeoutError::Timeout) => {
return Err(format!("Timeout waiting for '{}' response", cmd));
}
Err(mpsc::RecvTimeoutError::Disconnected) => {
return Err("Browser connection lost".to_string());
}
}
}
}
/// Click element by CSS selector.
pub fn click(&mut self, selector: &str) -> Result<String, String> {
let result = self.send_command("click", json!({"selector": selector}))?;
Ok(result.as_str().unwrap_or("Clicked").to_string())
}
/// Fill form field by CSS selector.
pub fn fill(&mut self, selector: &str, text: &str) -> Result<String, String> {
let result = self.send_command("fill", json!({"selector": selector, "text": text}))?;
Ok(result.as_str().unwrap_or("Filled").to_string())
}
/// Query elements by CSS selector.
pub fn select(&mut self, selector: &str) -> Result<Vec<ElementInfo>, String> {
let result = self.send_command("select", json!({"selector": selector}))?;
serde_json::from_value(result)
.map_err(|e| format!("Parse element info failed: {}", e))
}
/// Execute JavaScript on the current page.
pub fn eval(&mut self, expression: &str) -> Result<Value, String> {
self.send_command("eval", json!({"expression": expression}))
}
/// Get design brief from current page.
pub fn design(&mut self) -> Result<DesignBrief, String> {
let result = self.send_command("design", json!({}))?;
serde_json::from_value(result)
.map_err(|e| format!("Parse design brief failed: {}", e))
}
/// Capture DOM state and save as HTML file. Returns file path.
pub fn screenshot(&mut self) -> Result<String, String> {
let result = self.send_command("screenshot", json!({}))?;
let html = result.get("html").and_then(|v| v.as_str()).unwrap_or("<html></html>");
self.screenshot_count += 1;
let path = format!("{}/screenshot_{}.html", self.screenshots_dir, self.screenshot_count);
if let Some(parent) = std::path::Path::new(&path).parent() {
let _ = std::fs::create_dir_all(parent);
}
std::fs::write(&path, html)
.map_err(|e| format!("Screenshot write failed: {}", e))?;
Ok(path)
}
/// Get structured page overview (headings, forms, buttons, links, images).
pub fn page_info(&mut self) -> Result<String, String> {
let r = self.send_command("page", json!({}))?;
let mut out = String::new();
out.push_str(&format!("URL: {}\nTITLE: {}\n\n",
r.get("url").and_then(|v| v.as_str()).unwrap_or(""),
r.get("title").and_then(|v| v.as_str()).unwrap_or(""),
));
if let Some(arr) = r.get("headings").and_then(|v| v.as_array()) {
if !arr.is_empty() {
out.push_str("=== HEADINGS ===\n");
for h in arr {
out.push_str(&format!("[{}] {}\n",
h.get("tag").and_then(|v| v.as_str()).unwrap_or("?"),
h.get("text").and_then(|v| v.as_str()).unwrap_or(""),
));
}
out.push('\n');
}
}
if let Some(arr) = r.get("forms").and_then(|v| v.as_array()) {
if !arr.is_empty() {
out.push_str("=== FORMS ===\n");
for (i, f) in arr.iter().enumerate() {
out.push_str(&format!("[FORM {}] {} {} ({} fields)\n", i,
f.get("method").and_then(|v| v.as_str()).unwrap_or("get").to_uppercase(),
f.get("action").and_then(|v| v.as_str()).unwrap_or(""),
f.get("fields").and_then(|v| v.as_u64()).unwrap_or(0),
));
}
out.push('\n');
}
}
if let Some(arr) = r.get("buttons").and_then(|v| v.as_array()) {
if !arr.is_empty() {
out.push_str("=== BUTTONS ===\n");
for (i, b) in arr.iter().enumerate() {
out.push_str(&format!("[{}] {}\n", i,
b.get("text").and_then(|v| v.as_str()).unwrap_or(""),
));
}
out.push('\n');
}
}
if let Some(arr) = r.get("links").and_then(|v| v.as_array()) {
if !arr.is_empty() {
out.push_str("=== LINKS ===\n");
for (i, l) in arr.iter().enumerate() {
out.push_str(&format!("[{}] \"{}\" -> {}\n", i,
l.get("text").and_then(|v| v.as_str()).unwrap_or(""),
l.get("href").and_then(|v| v.as_str()).unwrap_or(""),
));
}
if let Some(total) = r.get("links_total").and_then(|v| v.as_u64()) {
out.push_str(&format!("... +{} more links\n", total - arr.len() as u64));
}
out.push('\n');
}
}
if let Some(arr) = r.get("images").and_then(|v| v.as_array()) {
if !arr.is_empty() {
out.push_str("=== IMAGES ===\n");
for (i, img) in arr.iter().enumerate() {
out.push_str(&format!("[{}] {} (alt: \"{}\")\n", i,
img.get("src").and_then(|v| v.as_str()).unwrap_or(""),
img.get("alt").and_then(|v| v.as_str()).unwrap_or(""),
));
}
out.push('\n');
}
}
if let Some(n) = r.get("element_count").and_then(|v| v.as_u64()) {
out.push_str(&format!("Total elements: {}\n", n));
}
Ok(out)
}
/// Check if proxy engine is initialized.
pub fn is_connected(&self) -> bool {
self.engine.is_some()
}
/// Get current URL.
/// Serve a proxied page — called by http.rs /proxy route handler.
/// Returns None if proxy engine not initialised (spf_web_connect not called).
pub fn proxy_page(&self, url: &str, ws_port: u16) -> Result<ProxiedPage, String> {
match &self.engine {
Some(engine) => engine.proxy_page(url, ws_port),
None => Err("Browser not initialised. Call spf_web_connect first.".into()),
}
}
/// Serve a proxied asset — called by http.rs /proxy/asset route handler.
pub fn proxy_asset(&self, url: &str) -> Result<AssetResponse, String> {
match &self.engine {
Some(engine) => engine.proxy_asset(url),
None => Err("Browser not initialised. Call spf_web_connect first.".into()),
}
}
pub fn current_url(&self) -> &str {
&self.current_url
}
/// Get ProxyEngine reference for http.rs route handler.
pub fn engine(&self) -> Option<&ProxyEngine> {
self.engine.as_ref()
}
}
// ============================================================================
// DATA TYPES — Same API surface as old CDP module for MCP handler compat
// ============================================================================
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ElementInfo {
pub tag: String,
pub id: Option<String>,
pub class: Option<String>,
pub text: String,
pub href: Option<String>,
pub src: Option<String>,
pub attributes: Vec<(String, String)>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DesignBrief {
pub title: String,
pub url: String,
pub colors: Vec<String>,
pub fonts: Vec<String>,
pub body_font_size: String,
pub body_line_height: String,
pub container_width: String,
pub components: Vec<ComponentInfo>,
pub images: Vec<ImageInfo>,
pub forms: Vec<FormInfo>,
pub link_count: usize,
pub script_count: usize,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ComponentInfo {
pub component_type: String,
pub index: usize,
pub text: String,
pub classes: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ImageInfo {
pub src: String,
pub alt: String,
pub width: u32,
pub height: u32,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FormInfo {
pub action: String,
pub method: String,
pub fields: Vec<FieldInfo>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FieldInfo {
pub name: String,
pub field_type: String,
pub required: bool,
}
// ============================================================================
// BROWSER LAUNCH — Platform-specific browser opener
// ============================================================================
/// Open URL in default browser. Android: am start. Linux: xdg-open.
#[cfg(target_os = "android")]
fn open_browser(url: &str) -> Result<(), String> {
// Try Android activity manager first
let am = std::process::Command::new("am")
.args(["start", "-a", "android.intent.action.VIEW", "-d", url])
.output();
if let Ok(output) = am {
if output.status.success() {
return Ok(());
}
}
// Fallback: termux-open-url (requires termux-api)
let termux = std::process::Command::new("termux-open-url")
.arg(url)
.output();
match termux {
Ok(o) if o.status.success() => Ok(()),
_ => Err("Failed to open browser. Ensure termux-api is installed.".to_string()),
}
}
#[cfg(not(target_os = "android"))]
fn open_browser(url: &str) -> Result<(), String> {
let result = std::process::Command::new("xdg-open").arg(url).output()
.or_else(|_| std::process::Command::new("open").arg(url).output());
match result {
Ok(o) if o.status.success() => Ok(()),
_ => Err("Failed to open browser".to_string()),
}
}
// ============================================================================
// CONTROL JAVASCRIPT — Injected into proxied pages
// ============================================================================
/// Build the control script tag with the correct WebSocket port.
fn control_script(ws_port: u16) -> String {
format!("\n<script>{}</script>\n", CONTROL_JS.replace("{WS_PORT}", &ws_port.to_string()))
}
/// Control JavaScript injected into every proxied page.
/// Opens WebSocket back to SPF, handles agent commands, intercepts navigation.
const CONTROL_JS: &str = r#"
(function(){
var ws=null,reconn=null;
function connect(){
ws=new WebSocket('ws://127.0.0.1:{WS_PORT}/ws/browser');
ws.onopen=function(){
ws.send(JSON.stringify({type:'connected',url:location.href,title:document.title}));
};
ws.onmessage=function(e){
try{var m=JSON.parse(e.data);handle(m);}catch(err){respond(0,false,err.toString());}
};
ws.onclose=function(){reconn=setTimeout(connect,2000);};
ws.onerror=function(){};
}
function respond(id,ok,result){
if(ws&&ws.readyState===1)ws.send(JSON.stringify({id:id,ok:ok,result:result}));
}
function handle(m){
var id=m.id;
try{
switch(m.cmd){
case 'click':cmdClick(id,m.selector);break;
case 'fill':cmdFill(id,m.selector,m.text);break;
case 'select':cmdSelect(id,m.selector);break;
case 'eval':cmdEval(id,m.expression);break;
case 'screenshot':cmdScreenshot(id);break;
case 'design':cmdDesign(id);break;
case 'page':cmdPage(id);break;
default:respond(id,false,'Unknown command: '+m.cmd);
}
}catch(e){respond(id,false,e.toString());}
}
function cmdClick(id,sel){
var el=document.querySelector(sel);
if(!el){respond(id,false,'Element not found: '+sel);return;}
var r=el.getBoundingClientRect();
var x=r.left+r.width/2,y=r.top+r.height/2;
el.dispatchEvent(new MouseEvent('mousedown',{bubbles:true,clientX:x,clientY:y}));
el.dispatchEvent(new MouseEvent('mouseup',{bubbles:true,clientX:x,clientY:y}));
el.dispatchEvent(new MouseEvent('click',{bubbles:true,clientX:x,clientY:y}));
el.click();
respond(id,true,'Clicked '+sel+' at ('+Math.round(x)+','+Math.round(y)+')');
}
function cmdFill(id,sel,text){
var el=document.querySelector(sel);
if(!el){respond(id,false,'Element not found: '+sel);return;}
el.focus();el.value='';el.value=text;
el.dispatchEvent(new Event('input',{bubbles:true}));
el.dispatchEvent(new Event('change',{bubbles:true}));
respond(id,true,'Filled '+sel+' with '+text.length+' chars');
}
function cmdSelect(id,sel){
var els=document.querySelectorAll(sel);
var out=[];
for(var i=0;i<Math.min(els.length,100);i++){
var el=els[i],attrs=[];
for(var a=0;a<el.attributes.length;a++)
attrs.push([el.attributes[a].name,el.attributes[a].value]);
out.push({tag:el.tagName.toLowerCase(),id:el.id||null,
class:el.className||null,text:(el.textContent||'').substring(0,200).trim(),
href:el.getAttribute('href')||null,src:el.getAttribute('src')||null,
attributes:attrs});
}
respond(id,true,out);
}
function cmdEval(id,expr){
try{var r=eval(expr);respond(id,true,r);}
catch(e){respond(id,false,'JS error: '+e.toString());}
}
function cmdScreenshot(id){
respond(id,true,{type:'dom_capture',html:document.documentElement.outerHTML});
}
function cmdDesign(id){
var bd=document.body,cs=getComputedStyle(bd);
var colors={},fonts={};
var all=document.querySelectorAll('*');
for(var i=0;i<Math.min(all.length,500);i++){
var s=getComputedStyle(all[i]);
if(s.color&&s.color!=='rgba(0, 0, 0, 0)')colors[s.color]=(colors[s.color]||0)+1;
if(s.backgroundColor&&s.backgroundColor!=='rgba(0, 0, 0, 0)')
colors[s.backgroundColor]=(colors[s.backgroundColor]||0)+1;
if(s.fontFamily)fonts[s.fontFamily]=(fonts[s.fontFamily]||0)+1;
}
var sc=Object.entries(colors).sort(function(a,b){return b[1]-a[1]}).slice(0,20).map(function(e){return e[0]});
var sf=Object.entries(fonts).sort(function(a,b){return b[1]-a[1]}).slice(0,10).map(function(e){return e[0]});
var comps=[];
var tags=['nav','header','main','section','article','aside','footer','form'];
for(var t=0;t<tags.length;t++){
var te=document.querySelectorAll(tags[t]);
for(var j=0;j<te.length;j++)
comps.push({component_type:tags[t],index:j,
text:(te[j].textContent||'').substring(0,100).trim(),classes:te[j].className||''});
}
var imgs=[];
for(var k=0;k<Math.min(document.images.length,50);k++){
var im=document.images[k];
imgs.push({src:im.src,alt:im.alt||'',width:im.naturalWidth,height:im.naturalHeight});
}
var forms=[];
for(var f=0;f<document.forms.length;f++){
var flds=[];
var fe=document.forms[f].elements;
for(var e=0;e<fe.length;e++)
if(fe[e].name)flds.push({name:fe[e].name,field_type:fe[e].type||'text',required:fe[e].required||false});
forms.push({action:document.forms[f].action||'',method:document.forms[f].method||'get',fields:flds});
}
respond(id,true,{title:document.title||'',url:location.href,
colors:sc,fonts:sf,body_font_size:cs.fontSize||'',body_line_height:cs.lineHeight||'',
container_width:cs.maxWidth||'',components:comps,images:imgs,forms:forms,
link_count:document.links.length,script_count:document.scripts.length});
}
function cmdPage(id){
var hs=document.querySelectorAll('h1,h2,h3');
var fs=document.querySelectorAll('form');
var bs=document.querySelectorAll('button,input[type="submit"]');
var ls=document.querySelectorAll('a[href]');
var is=document.querySelectorAll('img');
var r={url:location.href,title:document.title||'',
headings:[],forms:[],buttons:[],links:[],images:[],
element_count:document.querySelectorAll('*').length};
for(var h=0;h<hs.length;h++)
r.headings.push({tag:hs[h].tagName,text:hs[h].textContent.trim().substring(0,200)});
for(var f=0;f<fs.length;f++)
r.forms.push({action:fs[f].action,method:fs[f].method,fields:fs[f].elements.length});
for(var b=0;b<bs.length;b++)
r.buttons.push({text:(bs[b].textContent||bs[b].value||'').trim().substring(0,100)});
var ml=Math.min(ls.length,30);
for(var l=0;l<ml;l++)
r.links.push({text:ls[l].textContent.trim().substring(0,100),href:ls[l].href});
if(ls.length>ml)r.links_total=ls.length;
var mi=Math.min(is.length,20);
for(var i=0;i<mi;i++)
r.images.push({src:is[i].src,alt:is[i].alt||''});
if(is.length>mi)r.images_total=is.length;
respond(id,true,r);
}
document.addEventListener('click',function(e){
var t=e.target;
while(t&&t.tagName!=='A')t=t.parentElement;
if(t&&t.href&&t.href.indexOf('127.0.0.1')===-1){
e.preventDefault();e.stopPropagation();
window.location='/proxy?url='+encodeURIComponent(t.href);
}
},true);
document.addEventListener('submit',function(e){
var f=e.target;
if(f.method&&f.method.toLowerCase()==='get'){
e.preventDefault();
var p=new URLSearchParams(new FormData(f)).toString();
var a=f.action||location.href;
window.location='/proxy?url='+encodeURIComponent(a+(a.indexOf('?')>=0?'&':'?')+p);
}
},true);
connect();
})();
"#;
// ============================================================================
// HELPERS
// ============================================================================
/// Extract <title> from HTML string.
fn extract_title(html: &str) -> String {
let lower = html.to_lowercase();
if let Some(start) = lower.find("<title") {
if let Some(open) = html[start..].find('>') {
let after = start + open + 1;
if let Some(end) = lower[after..].find("</title") {
return html[after..after + end].trim().to_string();
}
}
}
String::new()
}
/// Escape HTML special characters for attribute values.
fn html_escape(s: &str) -> String {
s.replace('&', "&amp;")
.replace('"', "&quot;")
.replace('<', "&lt;")
.replace('>', "&gt;")
}
/// Strip Content-Security-Policy meta tags from HTML.
fn strip_csp_meta(html: &str) -> String {
let mut result = html.to_string();
let lower = result.to_lowercase();
// Find and remove <meta http-equiv="content-security-policy" ...>
let mut search_from = 0;
loop {
let search_lower = result[search_from..].to_lowercase();
if let Some(pos) = search_lower.find("content-security-policy") {
let abs_pos = search_from + pos;
// Walk backward to find <meta
let before = &result[..abs_pos].to_lowercase();
if let Some(meta_start) = before.rfind("<meta") {
// Walk forward to find >
if let Some(end) = result[abs_pos..].find('>') {
let remove_end = abs_pos + end + 1;
result = format!("{}{}", &result[..meta_start], &result[remove_end..]);
search_from = meta_start;
continue;
}
}
search_from = abs_pos + 23; // skip past this occurrence
} else {
break;
}
}
let _ = lower; // suppress unused warning
result
}
/// Percent-encode a URL for use as a query parameter value.
fn percent_encode(url: &str) -> String {
let mut result = String::with_capacity(url.len() * 2);
for byte in url.bytes() {
match byte {
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9'
| b'-' | b'_' | b'.' | b'~' => result.push(byte as char),
_ => { result.push('%'); result.push_str(&format!("{:02X}", byte)); }
}
}
result
}
/// Strip HTML tags from a string — simple text extraction.
pub fn strip_html_tags(html: &str) -> String {
let mut result = String::new();
let mut in_tag = false;
for ch in html.chars() {
match ch {
'<' => in_tag = true,
'>' => in_tag = false,
_ if !in_tag => result.push(ch),
_ => {}
}
}
let mut collapsed = String::new();
let mut prev_space = false;
for ch in result.chars() {
if ch.is_whitespace() {
if !prev_space { collapsed.push(' '); prev_space = true; }
} else {
collapsed.push(ch); prev_space = false;
}
}
collapsed.trim().to_string()
}
// ============================================================================
// TESTS
// ============================================================================
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_extract_title() {
assert_eq!(extract_title("<html><head><title>Hello World</title></head></html>"), "Hello World");
assert_eq!(extract_title("<title>Test</title>"), "Test");
assert_eq!(extract_title("<html>no title here</html>"), "");
assert_eq!(extract_title("<head><title> Trimmed </title></head>"), "Trimmed");
}
#[test]
fn test_html_escape() {
assert_eq!(html_escape("https://example.com?a=1&b=2"), "https://example.com?a=1&amp;b=2");
assert_eq!(html_escape("he said \"hi\""), "he said &quot;hi&quot;");
}
#[test]
fn test_percent_encode() {
assert_eq!(percent_encode("https://example.com/path"), "https%3A%2F%2Fexample.com%2Fpath");
assert_eq!(percent_encode("hello world"), "hello%20world");
assert_eq!(percent_encode("safe-chars_here.txt"), "safe-chars_here.txt");
}
#[test]
fn test_strip_csp_meta() {
let html = r#"<head><meta http-equiv="Content-Security-Policy" content="default-src 'self'"><title>Test</title></head>"#;
let result = strip_csp_meta(html);
assert!(!result.contains("Content-Security-Policy"));
assert!(result.contains("<title>Test</title>"));
}
#[test]
fn test_strip_csp_meta_preserves_other_meta() {
let html = r#"<head><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="x"><meta name="viewport" content="width=device-width"></head>"#;
let result = strip_csp_meta(html);
assert!(result.contains("charset"));
assert!(result.contains("viewport"));
assert!(!result.contains("Content-Security-Policy"));
}
#[test]
fn test_strip_html_tags() {
assert_eq!(strip_html_tags("<b>hello</b> world"), "hello world");
assert_eq!(strip_html_tags("<div><p>nested</p></div>"), "nested");
assert_eq!(strip_html_tags("no tags here"), "no tags here");
assert_eq!(strip_html_tags("<a href=\"/test\">link text</a>"), "link text");
}
#[test]
fn test_strip_html_tags_whitespace() {
assert_eq!(strip_html_tags("<div> hello world </div>"), "hello world");
assert_eq!(strip_html_tags("<p>\n\n text \n</p>"), "text");
}
#[test]
fn test_element_info_serialize() {
let el = ElementInfo {
tag: "a".to_string(),
id: Some("link1".to_string()),
class: Some("nav-link".to_string()),
text: "Home".to_string(),
href: Some("/".to_string()),
src: None,
attributes: vec![("href".to_string(), "/".to_string())],
};
let json = serde_json::to_string(&el).unwrap();
assert!(json.contains("\"tag\":\"a\""));
assert!(json.contains("\"text\":\"Home\""));
}
#[test]
fn test_design_brief_deserialize() {
let json = r#"{
"title": "Test Page", "url": "https://example.com",
"colors": ["rgb(0, 0, 0)"], "fonts": ["Arial"],
"body_font_size": "16px", "body_line_height": "24px",
"container_width": "1200px", "components": [],
"images": [], "forms": [],
"link_count": 5, "script_count": 2
}"#;
let brief: DesignBrief = serde_json::from_str(json).unwrap();
assert_eq!(brief.title, "Test Page");
assert_eq!(brief.link_count, 5);
}
#[test]
fn test_browser_session_new() {
let session = BrowserSession::new();
assert!(!session.is_connected());
assert!(session.current_url().is_empty());
}
#[test]
fn test_control_script_port_injection() {
let script = control_script(8080);
assert!(script.contains("127.0.0.1:8080"));
assert!(script.contains("<script>"));
assert!(script.contains("</script>"));
assert!(!script.contains("{WS_PORT}"));
}
}