oxibrowser-cdp 0.6.0

Chrome DevTools Protocol server for browser automation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
//! CDP Fetch domain handler.
//!
//! Handles network interception via Fetch.enable, Fetch.disable,
//! Fetch.continueRequest, Fetch.failRequest, Fetch.fulfillRequest, Fetch.continueResponse.
//!
//! Request interception works as follows:
//! 1. `Fetch.enable` registers patterns in EventSender
//! 2. `Session::navigate` calls `emit_request_paused` before fetching
//! 3. If pattern matches: request is stored in `PausedRequestRegistry`,
//!    `Fetch.requestPaused` event is emitted, and the decision is awaited
//! 4. CDP client responds with continue/fail/fulfill
//! 5. HTTP client applies the decision via `HttpClient::intercept`

use crate::domains::{DispatchContext, DomainResult};
use crate::event::EventSender;
use crate::protocol::CdpError;
use oxibrowser_core::network::InterceptAction;
use serde_json::{json, Value};

/// Dispatch Fetch domain methods.
pub async fn handle(method: &str, params: Option<Value>, ctx: &DispatchContext) -> DomainResult {
    match method {
        // --- Enable/disable ---
        "enable" => enable(params, ctx),
        "disable" => disable(ctx),

        // --- Request interception actions ---
        "continueRequest" => continue_request(params, ctx).await,
        "failRequest" => fail_request(params, ctx).await,
        "fulfillRequest" => fulfill_request(params, ctx).await,
        "continueResponse" => continue_response(params, ctx).await,
        "getResponseBody" => get_response_body(params, ctx).await,
        "takeResponseBodyAsStream" => Ok(Some(json!({"streamId": 0}))),
        "restoreResponseBodyAsStream" => Ok(Some(json!({}))),

        _ => Err(CdpError {
            code: -32601,
            message: format!("Fetch.{} not implemented", method),
        }),
    }
}

// ---------------------------------------------------------------------------
// Enable / Disable
// ---------------------------------------------------------------------------

/// Fetch.enable — enables request interception with optional patterns.
fn enable(params: Option<Value>, ctx: &DispatchContext) -> DomainResult {
    let mut patterns = vec![FetchPattern::default()];

    if let Some(p) = params {
        if let Some(arr) = p.get("patterns").and_then(|v| v.as_array()) {
            patterns.clear();
            for item in arr {
                if let Some(p) = parse_fetch_pattern(item) {
                    patterns.push(p);
                }
            }
        }
    }

    ctx.events.set_fetch_enabled(true);
    ctx.events.set_fetch_patterns(patterns.clone());
    tracing::info!("Fetch domain enabled with {} pattern(s)", patterns.len());
    Ok(Some(json!({})))
}

/// Fetch.disable — disables request interception.
fn disable(ctx: &DispatchContext) -> DomainResult {
    ctx.events.set_fetch_enabled(false);
    ctx.events.set_fetch_patterns(vec![]);
    tracing::info!("Fetch domain disabled");
    Ok(Some(json!({})))
}

// ---------------------------------------------------------------------------
// Request interception actions
// ---------------------------------------------------------------------------

/// Fetch.continueRequest — resume a paused request with modifications.
async fn continue_request(params: Option<Value>, ctx: &DispatchContext) -> DomainResult {
    let p = params.ok_or_else(|| CdpError {
        code: -32602,
        message: "continueRequest requires parameters".to_string(),
    })?;

    let request_id = p
        .get("requestId")
        .and_then(|v| v.as_str())
        .unwrap_or_default();

    // Look up in registry
    let request = ctx.fetch_registry.take(request_id);
    if request.is_none() {
        tracing::warn!("continueRequest: unknown requestId={}", request_id);
        return Err(CdpError {
            code: -32601,
            message: format!("requestId not found: {}", request_id),
        });
    };
    let request = request.unwrap();

    // Build headers
    let mut headers = request.headers.clone();
    if let Some(hdrs) = p.get("modifiedHeaders").and_then(|v| v.as_array()) {
        for item in hdrs {
            if let (Some(k), Some(v)) = (
                item.get("name").and_then(|x| x.as_str()),
                item.get("value").and_then(|x| x.as_str()),
            ) {
                if let Some((_, existing)) = headers
                    .iter_mut()
                    .find(|(k2, _)| k2.eq_ignore_ascii_case(k))
                {
                    *existing = v.to_string();
                } else {
                    headers.push((k.to_string(), v.to_string()));
                }
            }
        }
    }

    // Remove headers
    if let Some(names) = p.get("deletedHeaders").and_then(|v| v.as_array()) {
        for item in names {
            if let Some(name) = item.as_str() {
                headers.retain(|(k, _)| !k.eq_ignore_ascii_case(name));
            }
        }
    }

    let url = p.get("url").and_then(|v| v.as_str()).map(String::from);
    let method = p.get("method").and_then(|v| v.as_str()).map(String::from);
    let post_data = p.get("postData").and_then(|v| v.as_str()).map(String::from);

    let action = build_continue(url, method, headers, post_data);
    let _ = request.tx.send(action);

    tracing::debug!("Fetch.continueRequest: requestId={} resumed", request_id);
    Ok(Some(json!({})))
}

/// Fetch.failRequest — fail a paused request with an error.
async fn fail_request(params: Option<Value>, ctx: &DispatchContext) -> DomainResult {
    let p = params.ok_or_else(|| CdpError {
        code: -32602,
        message: "failRequest requires parameters".to_string(),
    })?;

    let request_id = p
        .get("requestId")
        .and_then(|v| v.as_str())
        .unwrap_or_default();
    let error_reason = p
        .get("errorReason")
        .and_then(|v| v.as_str())
        .unwrap_or("Failed");

    let request = ctx.fetch_registry.take(request_id);
    if request.is_none() {
        tracing::warn!("failRequest: unknown requestId={}", request_id);
        return Err(CdpError {
            code: -32601,
            message: format!("requestId not found: {}", request_id),
        });
    };
    let request = request.unwrap();

    let action = build_fail(error_reason.to_string());
    let _ = request.tx.send(action);

    tracing::debug!(
        "Fetch.failRequest: requestId={} failed ({})",
        request_id,
        error_reason
    );
    Ok(Some(json!({})))
}

/// Fetch.fulfillRequest — return a fake response for a paused request.
async fn fulfill_request(params: Option<Value>, ctx: &DispatchContext) -> DomainResult {
    let p = params.ok_or_else(|| CdpError {
        code: -32602,
        message: "fulfillRequest requires parameters".to_string(),
    })?;

    let request_id = p
        .get("requestId")
        .and_then(|v| v.as_str())
        .unwrap_or_default();
    let status_code = p
        .get("statusCode")
        .and_then(|v| v.as_i64())
        .unwrap_or(200) as u16;
    let status_text = p
        .get("statusText")
        .and_then(|v| v.as_str())
        .unwrap_or("OK");

    // Extract response headers
    let mut headers = Vec::new();
    if let Some(h) = p.get("responseHeaders").and_then(|v| v.as_array()) {
        for item in h {
            if let (Some(k), Some(v)) = (
                item.get("name").and_then(|x| x.as_str()),
                item.get("value").and_then(|x| x.as_str()),
            ) {
                headers.push((k.to_string(), v.to_string()));
            }
        }
    }

    // Body — decode from base64 if needed
    let raw_body = p.get("body").and_then(|v| v.as_str()).unwrap_or("");
    let body_bytes = if p
        .get("base64Encoded")
        .and_then(|v| v.as_bool())
        .unwrap_or(false)
    {
        use base64::Engine;
        base64::engine::general_purpose::STANDARD
            .decode(raw_body)
            .unwrap_or_else(|_| raw_body.as_bytes().to_vec())
    } else {
        raw_body.as_bytes().to_vec()
    };

    let body_size = body_bytes.len();
    let headers_count = headers.len();

    let request = ctx.fetch_registry.take(request_id);
    if request.is_none() {
        tracing::warn!("fulfillRequest: unknown requestId={}", request_id);
        return Err(CdpError {
            code: -32601,
            message: format!("requestId not found: {}", request_id),
        });
    };
    let request = request.unwrap();

    let action = build_fulfill(status_code, status_text.to_string(), headers, body_bytes);
    let _ = request.tx.send(action);

    tracing::debug!(
        "Fetch.fulfillRequest: requestId={}, status={}, body_size={}, headers={}",
        request_id,
        status_code,
        body_size,
        headers_count
    );
    Ok(Some(json!({
        "responseCode": status_code,
        "responsePhrase": status_text,
        "responseHeadersCount": headers_count,
        "binary": false,
    })))
}

/// Fetch.continueResponse — continue a paused response (same as continue for now).
async fn continue_response(params: Option<Value>, ctx: &DispatchContext) -> DomainResult {
    let p = params.unwrap_or_default();
    let request_id = p
        .get("requestId")
        .and_then(|v| v.as_str())
        .unwrap_or_default();

    let request = ctx.fetch_registry.take(request_id);
    if request.is_none() {
        return Err(CdpError {
            code: -32601,
            message: format!("requestId not found: {}", request_id),
        });
    };
    let request = request.unwrap();

    let action = InterceptAction::Continue {
        url: None,
        method: None,
        headers: Vec::new(),
        post_data: None,
    };
    let _ = request.tx.send(action);

    Ok(Some(json!({})))
}

/// Fetch.getResponseBody — returns body for an intercepted request.
async fn get_response_body(params: Option<Value>, ctx: &DispatchContext) -> DomainResult {
    let p = params.ok_or_else(|| CdpError {
        code: -32602,
        message: "getResponseBody requires parameters".to_string(),
    })?;

    let request_id = p
        .get("requestId")
        .and_then(|v| v.as_str())
        .unwrap_or_default();

    let guard = ctx.session.read().await;
    if let Some(body) = guard.get_response_body(request_id) {
        Ok(Some(json!({
            "body": body.body,
            "base64Encoded": body.base64,
        })))
    } else {
        Ok(Some(json!({
            "body": "",
            "base64Encoded": false,
        })))
    }
}

// ---------------------------------------------------------------------------
// Event emission helpers
// ---------------------------------------------------------------------------

/// Emit a `Fetch.requestPaused` event for an intercepted request.
///
/// Called from the network layer during navigation when a request matches a pattern.
/// The `PausedRequest` is inserted into the registry with a oneshot channel so the
/// CDP handler can deliver the client's decision back to the network layer.
///
/// Returns the `oneshot::Receiver<InterceptAction>` so the caller can await the decision.
pub fn emit_request_paused(
    request_id: &str,
    url: &str,
    method: &str,
    headers: &[(String, String)],
    resource_type: &str,
    registry: &oxibrowser_core::network::SharedRegistry,
    events: &EventSender,
) -> tokio::sync::oneshot::Receiver<InterceptAction> {
    use oxibrowser_core::network::PausedRequest;
    use tokio::sync::oneshot;

    let (tx, rx) = oneshot::channel();

    let request = PausedRequest {
        url: url.to_string(),
        method: method.to_string(),
        headers: headers.to_vec(),
        resource_type: resource_type.to_string(),
        tx,
    };

    let _ = registry.insert(request_id.to_string(), request);

    let headers_json: serde_json::Map<String, serde_json::Value> = headers
        .iter()
        .map(|(k, v)| (k.clone(), json!(v)))
        .collect();

    events.send_fetch_event(
        "Fetch.requestPaused",
        json!({
            "requestId": request_id,
            "request": {
                "url": url,
                "method": method,
                "headers": headers_json,
                "initialPriority": "VeryHigh",
                "urlFragment": "",
                "postData": serde_json::Value::Null,
            },
            "resourceType": resource_type,
            "frameId": "main",
            "networkIntercepted": true,
        }),
    );

    tracing::debug!(
        "Fetch.requestPaused: requestId={}, url={}, method={}",
        request_id,
        url,
        method
    );

    rx
}

// ---------------------------------------------------------------------------
// Pattern matching
// ---------------------------------------------------------------------------

/// A request interception pattern.
#[derive(Debug, Clone, Default)]
pub struct FetchPattern {
    pub url_pattern: String,
    pub resource_type: Option<String>,
    pub request_stage: Option<String>,
}

impl FetchPattern {
    /// Check if a URL matches this pattern.
    pub fn matches_url(&self, url: &str) -> bool {
        if self.url_pattern.is_empty() || self.url_pattern == "*" {
            return true;
        }
        let pattern = &self.url_pattern;
        if pattern.starts_with('*') && pattern.ends_with('*') {
            url.contains(&pattern[1..pattern.len() - 1])
        } else if pattern.ends_with('*') {
            url.starts_with(&pattern[..pattern.len() - 1])
        } else if let Some(suffix) = pattern.strip_prefix('*') {
            url.ends_with(suffix)
        } else {
            url == pattern
        }
    }
}

/// Parse a CDP FetchPattern JSON object.
fn parse_fetch_pattern(value: &serde_json::Value) -> Option<FetchPattern> {
    let obj = value.as_object()?;
    Some(FetchPattern {
        url_pattern: obj
            .get("urlPattern")
            .and_then(|v| v.as_str())
            .unwrap_or("*")
            .to_string(),
        resource_type: obj.get("resourceType").and_then(|v| v.as_str()).map(String::from),
        request_stage: obj.get("requestStage").and_then(|v| v.as_str()).map(String::from),
    })
}

/// Check if a request URL matches any enabled pattern.
pub fn matches_patterns(url: &str, patterns: &[FetchPattern]) -> bool {
    patterns.iter().any(|p| p.matches_url(url))
}

// ---------------------------------------------------------------------------
// InterceptAction builder helpers (mirrored from core network/intercept.rs)
// ---------------------------------------------------------------------------

/// Build an InterceptAction::Continue from CDP params.
fn build_continue(
    url: Option<String>,
    method: Option<String>,
    headers: Vec<(String, String)>,
    post_data: Option<String>,
) -> oxibrowser_core::network::InterceptAction {
    use oxibrowser_core::network::InterceptAction;
    InterceptAction::Continue {
        url,
        method,
        headers,
        post_data,
    }
}

/// Build an InterceptAction::Fail from CDP params.
fn build_fail(error_reason: String) -> oxibrowser_core::network::InterceptAction {
    use oxibrowser_core::network::InterceptAction;
    InterceptAction::Fail { error_reason }
}

/// Build an InterceptAction::Fulfill from CDP params.
fn build_fulfill(
    status_code: u16,
    status_text: String,
    headers: Vec<(String, String)>,
    body: Vec<u8>,
) -> oxibrowser_core::network::InterceptAction {
    use oxibrowser_core::network::InterceptAction;
    InterceptAction::Fulfill {
        status_code,
        status_text,
        headers,
        body,
    }
}