1use std::sync::Arc;
2use std::time::Duration;
3
4use anyhow::anyhow;
5use serde_json::{json, Value};
6
7use super::client::CdpClient;
8
9pub struct CdpSession {
10 client: Arc<CdpClient>,
11 pub target_id: String,
12 session_id: String,
13 command_timeout: Duration,
14}
15
16impl CdpSession {
17 pub fn client(&self) -> Arc<CdpClient> {
18 Arc::clone(&self.client)
19 }
20
21 pub async fn new(
22 client: Arc<CdpClient>,
23 target_id: &str,
24 command_timeout_ms: u64,
25 ) -> anyhow::Result<Self> {
26 let result = client
27 .send(
28 "Target.attachToTarget",
29 json!({ "targetId": target_id, "flatten": true }),
30 )
31 .await?;
32
33 let session_id = result
34 .get("sessionId")
35 .and_then(|v| v.as_str())
36 .ok_or_else(|| anyhow!("no sessionId in Target.attachToTarget response"))?
37 .to_string();
38
39 Ok(Self {
40 client,
41 target_id: target_id.to_string(),
42 session_id,
43 command_timeout: Duration::from_millis(command_timeout_ms),
44 })
45 }
46
47 async fn cdp(&self, method: &str, params: Value) -> anyhow::Result<Value> {
48 tokio::time::timeout(
49 self.command_timeout,
50 self.client
51 .send_with_session(method, params, Some(self.session_id.clone())),
52 )
53 .await
54 .map_err(|_| anyhow!("CDP command '{method}' timed out"))?
55 }
56
57 pub async fn navigate(&mut self, url: &str) -> anyhow::Result<()> {
58 let trimmed = url.trim();
65 let lower = trimmed.to_ascii_lowercase();
66 if !(lower.starts_with("http://") || lower.starts_with("https://")) {
67 anyhow::bail!(
68 "navigate rejected: only http:// and https:// URLs are allowed, got `{url}`"
69 );
70 }
71 self.cdp("Page.enable", json!({})).await?;
72 let mut events = self.client.subscribe_session_events(&self.session_id);
74 self.cdp("Page.navigate", json!({ "url": trimmed })).await?;
75
76 let wait = async {
79 loop {
80 match events.recv().await {
81 Ok(ev) if ev.method == "Page.loadEventFired" => return Ok(()),
82 Ok(_) => continue,
83 Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => continue,
84 Err(tokio::sync::broadcast::error::RecvError::Closed) => {
85 return Err(anyhow!(
86 "CDP event stream closed before Page.loadEventFired"
87 ));
88 }
89 }
90 }
91 };
92 tokio::time::timeout(self.command_timeout, wait)
93 .await
94 .map_err(|_| anyhow!("navigate timed out waiting for Page.loadEventFired"))?
95 }
96
97 pub async fn screenshot(&self) -> anyhow::Result<Vec<u8>> {
98 let result = self
99 .cdp("Page.captureScreenshot", json!({ "format": "png" }))
100 .await?;
101 let b64 = result
102 .get("data")
103 .and_then(|v| v.as_str())
104 .ok_or_else(|| anyhow!("no data in screenshot response"))?;
105 use base64::Engine;
106 base64::engine::general_purpose::STANDARD
107 .decode(b64)
108 .map_err(|e| anyhow!("base64 decode failed: {e}"))
109 }
110
111 pub async fn evaluate(&self, script: &str) -> anyhow::Result<Value> {
112 let result = self
113 .cdp(
114 "Runtime.evaluate",
115 json!({
116 "expression": script,
117 "returnByValue": true,
118 "awaitPromise": true,
119 }),
120 )
121 .await?;
122 if let Some(exc) = result.get("exceptionDetails") {
123 return Err(anyhow!("JS exception: {exc}"));
124 }
125 Ok(result
126 .get("result")
127 .and_then(|r| r.get("value"))
128 .cloned()
129 .unwrap_or(Value::Null))
130 }
131
132 pub async fn snapshot(&mut self) -> anyhow::Result<String> {
133 let result = self.cdp("Runtime.evaluate", json!({
134 "expression": r#"
135 (function() {
136 const tags = ['a','button','input','select','textarea','[role="button"]','[role="link"]'];
137 const elements = document.querySelectorAll(tags.join(','));
138 const refs = [];
139 elements.forEach((el, i) => {
140 const ref_id = '@e' + (i + 1);
141 el.setAttribute('data-agent-ref', ref_id);
142 refs.push({
143 ref_id,
144 tag: el.tagName.toLowerCase(),
145 text: (el.innerText || el.value || el.getAttribute('placeholder') || '').trim().slice(0, 80),
146 type: el.getAttribute('type') || '',
147 });
148 });
149 return JSON.stringify(refs);
150 })()
151 "#,
152 "returnByValue": true,
153 })).await?;
154
155 let refs_json = result
156 .get("result")
157 .and_then(|r| r.get("value"))
158 .and_then(|v| v.as_str())
159 .unwrap_or("[]");
160
161 let refs: Vec<Value> = serde_json::from_str(refs_json)?;
162 let mut lines = vec!["# Page snapshot".to_string()];
163
164 for r in &refs {
165 let ref_id = r["ref_id"].as_str().unwrap_or("");
166 let tag = r["tag"].as_str().unwrap_or("");
167 let text = r["text"].as_str().unwrap_or("");
168 let typ = r["type"].as_str().unwrap_or("");
169
170 let label = if typ.is_empty() {
171 format!("[{tag}] {text} — {ref_id}")
172 } else {
173 format!("[{tag}:{typ}] {text} — {ref_id}")
174 };
175 lines.push(label);
176 }
177
178 Ok(lines.join("\n"))
179 }
180
181 pub async fn click(&self, target: &str) -> anyhow::Result<()> {
182 let script = if let Some(ref_id) = validate_element_ref(target) {
183 format!(r#"document.querySelector('[data-agent-ref="{ref_id}"]')?.click()"#)
184 } else {
185 format!(r#"document.querySelector({:?})?.click()"#, target)
186 };
187 self.evaluate(&script).await?;
188 Ok(())
189 }
190
191 pub async fn fill(&self, target: &str, value: &str) -> anyhow::Result<()> {
192 let escaped_value = value.replace('\\', "\\\\").replace('"', "\\\"");
193 let script = if let Some(ref_id) = validate_element_ref(target) {
194 format!(
195 r#"
196 var el = document.querySelector('[data-agent-ref="{ref_id}"]');
197 if (el) {{ el.focus(); el.value = "{escaped_value}"; el.dispatchEvent(new Event('input', {{bubbles:true}})); el.dispatchEvent(new Event('change', {{bubbles:true}})); }}
198 "#
199 )
200 } else {
201 format!(
202 r#"
203 var el = document.querySelector({:?});
204 if (el) {{ el.focus(); el.value = "{escaped_value}"; el.dispatchEvent(new Event('input', {{bubbles:true}})); el.dispatchEvent(new Event('change', {{bubbles:true}})); }}
205 "#,
206 target
207 )
208 };
209 self.evaluate(&script).await?;
210 Ok(())
211 }
212
213 pub async fn scroll_to(&self, target: &str) -> anyhow::Result<()> {
214 let script = if let Some(ref_id) = validate_element_ref(target) {
215 format!(
216 r#"document.querySelector('[data-agent-ref="{ref_id}"]')?.scrollIntoView({{behavior:'smooth',block:'center'}})"#
217 )
218 } else {
219 format!(
220 r#"document.querySelector({:?})?.scrollIntoView({{behavior:'smooth',block:'center'}})"#,
221 target
222 )
223 };
224 self.evaluate(&script).await?;
225 Ok(())
226 }
227}
228
229pub(crate) fn validate_element_ref(target: &str) -> Option<&str> {
236 let stripped = target.strip_prefix('@')?;
237 if stripped.is_empty()
238 || !stripped
239 .bytes()
240 .all(|b| b.is_ascii_alphanumeric() || b == b'_')
241 {
242 return None;
243 }
244 Some(target)
245}
246
247#[cfg(test)]
248mod validation_tests {
249 use super::validate_element_ref;
250
251 #[test]
252 fn accepts_well_formed_refs() {
253 assert_eq!(validate_element_ref("@e1"), Some("@e1"));
254 assert_eq!(validate_element_ref("@e42"), Some("@e42"));
255 assert_eq!(validate_element_ref("@e_x"), Some("@e_x"));
256 }
257
258 #[test]
259 fn rejects_injection_shapes() {
260 assert!(validate_element_ref("@e1\"]").is_none());
261 assert!(validate_element_ref("@e1 or 1=1").is_none());
262 assert!(validate_element_ref("@").is_none());
263 assert!(validate_element_ref("@e1;alert(1)").is_none());
264 }
265
266 #[test]
267 fn passes_through_css_selectors() {
268 assert!(validate_element_ref("#id").is_none());
270 assert!(validate_element_ref(".cls").is_none());
271 assert!(validate_element_ref("button[type=submit]").is_none());
272 }
273}