diff --git a/Cargo.lock b/Cargo.lock index 6d86b9563..5bfbfc85f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4269,6 +4269,7 @@ dependencies = [ name = "ide-dap" version = "0.1.45" dependencies = [ + "base64 0.22.1", "futures", "ide-core", "ide-heap", @@ -4287,6 +4288,7 @@ dependencies = [ "specta", "tempfile", "tokio", + "tokio-tungstenite", "tracing", "tracing-subscriber", "windows-sys 0.61.2", diff --git a/crates/ide-dap/Cargo.toml b/crates/ide-dap/Cargo.toml index 85e1f560a..42836a707 100644 --- a/crates/ide-dap/Cargo.toml +++ b/crates/ide-dap/Cargo.toml @@ -7,6 +7,8 @@ license.workspace = true [dependencies] futures.workspace = true +tokio-tungstenite.workspace = true +base64.workspace = true tempfile.workspace = true ide-core.workspace = true ide-language.workspace = true diff --git a/crates/ide-dap/src/js_cdp.rs b/crates/ide-dap/src/js_cdp.rs new file mode 100644 index 000000000..f326a5985 --- /dev/null +++ b/crates/ide-dap/src/js_cdp.rs @@ -0,0 +1,528 @@ +//! Replacing the responses a debugged page receives. js-debug hands out a WebSocket that +//! speaks the browser's own protocol (`requestCDPProxy`); over it the browser is told to hold +//! the requests whose URL matches a rule (`Fetch.enable`) and each held request is answered +//! here, with the rule's response or by letting it through. +//! +//! A held request stays held until it is answered, so interception is always switched off +//! (`Fetch.disable`) before the connection is given up: a page whose requests nobody answers hangs. + +use crate::{DebugManager, DebugSessionId, REQUEST_TIMEOUT, js_debug}; +use base64::Engine; +use futures::{SinkExt, StreamExt}; +use ide_core::{IdeError, IdeResult}; +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; +use specta::Type; +use std::collections::HashMap; +use tokio::sync::{oneshot, watch}; +use tokio_tungstenite::tungstenite::{Message, http::StatusCode}; + +/// A response given in place of the server's to every request whose URL contains `url_contains`. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct JsResponseRule { + pub url_contains: String, + pub status: u16, + pub content_type: String, + pub body: String, +} + +/// The browser's URL pattern (`*` any text, `?` one character, `\` escapes) for "contains `part`". +pub(crate) fn url_pattern(part: &str) -> String { + let mut pattern = String::with_capacity(part.len() + 2); + pattern.push('*'); + for c in part.chars() { + if matches!(c, '*' | '?' | '\\') { + pattern.push('\\'); + } + pattern.push(c); + } + pattern.push('*'); + pattern +} + +pub(crate) fn rule_for<'a>(rules: &'a [JsResponseRule], url: &str) -> Option<&'a JsResponseRule> { + rules.iter().find(|rule| url.contains(&rule.url_contains)) +} + +/// What to tell the browser about a request it holds: the first matching rule's response, or +/// to send the request on. Every held request gets one of the two. +pub(crate) fn answer(held: &Value, rules: &[JsResponseRule]) -> (&'static str, Value) { + let request_id = held.get("requestId").and_then(Value::as_str).unwrap_or_default(); + let url = held.pointer("/request/url").and_then(Value::as_str).unwrap_or_default(); + let Some(rule) = rule_for(rules, url) else { + return ("Fetch.continueRequest", json!({ "requestId": request_id })); + }; + let header = |name: &str, value: &str| json!({ "name": name, "value": value }); + // A page on another origin only reads a response that names its origin. The server would + // say so; the response given in its place has to. + let mut cross_origin = Vec::new(); + if let Some(origin) = request_header(held, "Origin") { + cross_origin.push(header("Access-Control-Allow-Origin", origin)); + cross_origin.push(header("Access-Control-Allow-Credentials", "true")); + } + let method = held.pointer("/request/method").and_then(Value::as_str).unwrap_or_default(); + // The browser's question before such a request: allowed here, the server may not exist. + if method == "OPTIONS" + && let Some(asked) = request_header(held, "Access-Control-Request-Method") + { + cross_origin.push(header("Access-Control-Allow-Methods", asked)); + if let Some(asked) = request_header(held, "Access-Control-Request-Headers") { + cross_origin.push(header("Access-Control-Allow-Headers", asked)); + } + let allowed = json!({ + "requestId": request_id, + "responseCode": 204, + "responsePhrase": phrase(204), + "responseHeaders": cross_origin, + }); + return ("Fetch.fulfillRequest", allowed); + } + let mut headers = vec![header("Content-Type", &rule.content_type)]; + headers.extend(cross_origin); + let replaced = json!({ + "requestId": request_id, + "responseCode": rule.status, + "responsePhrase": phrase(rule.status), + "responseHeaders": headers, + "body": base64::engine::general_purpose::STANDARD.encode(rule.body.as_bytes()), + }); + ("Fetch.fulfillRequest", replaced) +} + +/// A header of the held request; the browser reports names as the page wrote them. +fn request_header<'a>(held: &'a Value, name: &str) -> Option<&'a str> { + held.pointer("/request/headers")?.as_object()?.iter().find(|(key, _)| key.eq_ignore_ascii_case(name))?.1.as_str() +} + +/// The browser refuses a response without a phrase when it has none of its own for the status. +fn phrase(status: u16) -> &'static str { + StatusCode::from_u16(status).ok().and_then(|status| status.canonical_reason()).unwrap_or("Unknown") +} + +fn interception(rules: &[JsResponseRule]) -> Value { + let patterns: Vec = rules + .iter() + .map(|rule| json!({ "urlPattern": url_pattern(&rule.url_contains), "requestStage": "Request" })) + .collect(); + json!({ "patterns": patterns }) +} + +/// Applies `rules` to the page behind js-debug's CDP proxy at `ws_url` until their sender is +/// dropped (the session is gone) or the proxy closes the connection. The browser holds +/// requests only while there are rules. `ready` hears whether the proxy reports held +/// requests at all; nothing is held before it has agreed to. +pub(crate) async fn serve( + ws_url: String, + mut rules: watch::Receiver>, + ready: oneshot::Sender>, +) { + let socket = match tokio_tungstenite::connect_async(ws_url.as_str()).await { + Ok((socket, _)) => socket, + Err(e) => { + let _ = ready.send(Err(e.to_string())); + return; + } + }; + let (mut write, mut read) = socket.split(); + let mut last_id = 0u64; + let mut call = |method: &str, params: Value| { + last_id += 1; + (last_id, Message::text(json!({ "id": last_id, "method": method, "params": params }).to_string())) + }; + + let (subscription, subscribe) = call("JsDebug.subscribe", json!({ "events": ["Fetch.requestPaused"] })); + let subscribed = tokio::time::timeout(REQUEST_TIMEOUT, async { + write.send(subscribe).await.map_err(|e| e.to_string())?; + loop { + let reply = read.next().await.ok_or("the connection closed")?.map_err(|e| e.to_string())?; + let Some(reply) = reply.to_text().ok().and_then(|text| serde_json::from_str::(text).ok()) else { + continue; + }; + if reply.get("id").and_then(Value::as_u64) != Some(subscription) { + continue; + } + break match reply.get("error") { + Some(error) => Err(error.get("message").and_then(Value::as_str).unwrap_or("refused").to_owned()), + None => Ok(()), + }; + } + }) + .await + .unwrap_or_else(|_| Err("no answer".to_owned())); + if let Err(why) = subscribed { + let _ = ready.send(Err(why)); + let _ = write.close().await; + return; + } + let _ = ready.send(Ok(())); + + let mut current = rules.borrow_and_update().clone(); + let mut holding = !current.is_empty(); + if holding && write.send(call("Fetch.enable", interception(¤t)).1).await.is_err() { + return; + } + // The request each sent replacement is for, by command id, until the browser has taken it. + let mut replacing: HashMap = HashMap::new(); + loop { + tokio::select! { + changed = rules.changed() => { + if changed.is_err() { + break; + } + current = rules.borrow_and_update().clone(); + let (_, command) = match (current.is_empty(), holding) { + (true, false) => continue, + (true, true) => call("Fetch.disable", json!({})), + (false, _) => call("Fetch.enable", interception(¤t)), + }; + holding = !current.is_empty(); + if write.send(command).await.is_err() { + return; + } + } + message = read.next() => { + // The proxy closed (the page or the session ended): nothing is held any more. + let Some(Ok(message)) = message else { return }; + let Ok(text) = message.to_text() else { continue }; + let Ok(message) = serde_json::from_str::(text) else { continue }; + if let Some(id) = message.get("id").and_then(Value::as_u64) { + // The browser did not take the replacement: let the request through, or + // it stays held and the page waits for it. + if let Some(request_id) = replacing.remove(&id) + && message.get("error").is_some() + { + let (_, go_on) = call("Fetch.continueRequest", json!({ "requestId": request_id })); + if write.send(go_on).await.is_err() { + return; + } + } + continue; + } + if message.get("method").and_then(Value::as_str) != Some("Fetch.requestPaused") { + continue; + } + let Some(held) = message.get("params") else { continue }; + let Some(request_id) = held.get("requestId").and_then(Value::as_str) else { continue }; + let (method, params) = answer(held, ¤t); + let (id, command) = call(method, params); + if method == "Fetch.fulfillRequest" { + replacing.insert(id, request_id.to_owned()); + } + if write.send(command).await.is_err() { + return; + } + } + } + } + if holding { + let _ = write.send(call("Fetch.disable", json!({})).1).await; + } + let _ = write.close().await; +} + +impl DebugManager { + /// Makes `rules` the page's response rules; none switches the replacing off. The first + /// rules of a session open the connection to js-debug's CDP proxy, later ones go over it. + /// An error means the rules are not applied. + pub async fn js_set_response_overrides(&self, s: DebugSessionId, rules: Vec) -> IdeResult<()> { + let session = self.session(s)?; + if !js_debug::is_page(&session) { + return Err(IdeError::unavailable("this debug session is not a page in a browser")); + } + // Held to the end: two callers at once would each open a connection. + let mut applied = session.js_overrides.lock().await; + if applied.as_ref().is_some_and(|sender| sender.send(rules.clone()).is_ok()) { + return Ok(()); + } + // No connection yet, or the proxy closed it. + applied.take(); + if rules.is_empty() { + return Ok(()); + } + let refused = + |why: String| IdeError::unavailable(format!("the JavaScript debugger has no browser connection: {why}")); + if !js_debug::launched(&session).await { + return Err(refused("the page's debug session did not finish starting".into())); + } + let proxy = session + .conn + .request_timeout("requestCDPProxy", json!({}), REQUEST_TIMEOUT) + .await + .map_err(|e| refused(e.to_string()))?; + let (Some(host), Some(port)) = + (proxy.get("host").and_then(Value::as_str), proxy.get("port").and_then(Value::as_u64)) + else { + return Err(refused("no address".into())); + }; + let path = proxy.get("path").and_then(Value::as_str).unwrap_or_default(); + let (sender, receiver) = watch::channel(rules); + let (ready, is_ready) = oneshot::channel(); + tokio::spawn(serve(format!("ws://{host}:{port}{path}"), receiver, ready)); + match is_ready.await { + Ok(Ok(())) => { + *applied = Some(sender); + Ok(()) + } + Ok(Err(why)) => Err(refused(why)), + Err(_) => Err(refused("no answer".into())), + } + } +} + +#[cfg(test)] +pub(crate) mod tests { + use super::*; + use futures::{SinkExt, StreamExt}; + use serde_json::json; + use tokio::sync::mpsc; + use tokio_tungstenite::tungstenite::Message; + + pub(crate) fn rule(url_contains: &str, status: u16, body: &str) -> JsResponseRule { + JsResponseRule { + url_contains: url_contains.into(), + status, + content_type: "application/json".into(), + body: body.into(), + } + } + + #[test] + fn a_part_of_a_url_becomes_a_pattern_that_matches_it_anywhere() { + assert_eq!(url_pattern("api/items"), "*api/items*"); + // The pattern's own wildcards and escape character are taken literally. + assert_eq!(url_pattern(r"a*b?c\d"), r"*a\*b\?c\\d*"); + } + + #[test] + fn the_first_rule_whose_text_is_in_the_url_answers() { + let rules = [rule("api/items", 201, "{\"a\":\"é\"}"), rule("api", 500, "later")]; + assert_eq!(rule_for(&rules, "http://h/api/items?x=1").map(|r| r.status), Some(201)); + assert_eq!(rule_for(&rules, "http://h/api/users").map(|r| r.status), Some(500)); + assert!(rule_for(&rules, "http://h/logo.png").is_none()); + + let (command, params) = answer(&held("7", "http://h/api/items")["params"], &rules); + assert_eq!(command, "Fetch.fulfillRequest"); + assert_eq!( + params, + json!({ + "requestId": "7", + "responseCode": 201, + "responsePhrase": "Created", + "responseHeaders": [{ "name": "Content-Type", "value": "application/json" }], + // base64 of the UTF-8 text `{"a":"é"}` + "body": "eyJhIjoiw6kifQ==", + }) + ); + // A request the browser held that no rule is for goes on to the network. + assert_eq!( + answer(&held("8", "http://h/logo.png")["params"], &rules), + ("Fetch.continueRequest", json!({ "requestId": "8" })) + ); + } + + #[test] + fn a_status_the_browser_has_no_phrase_for_is_given_one() { + // The browser refuses a response whose status it cannot name. + let (_, params) = answer(&held("1", "http://h/api")["params"], &[rule("api", 419, "")]); + assert_eq!((¶ms["responseCode"], ¶ms["responsePhrase"]), (&json!(419), &json!("Unknown"))); + } + + fn header<'a>(params: &'a Value, name: &str) -> Option<&'a str> { + params["responseHeaders"].as_array()?.iter().find(|h| h["name"] == name)?["value"].as_str() + } + + #[test] + fn a_replaced_response_passes_the_pages_cross_origin_check() { + let rules = [rule("api/items", 200, "[]")]; + let from_page = |method: &str, headers: Value| json!({ "requestId": "3", "request": { "url": "http://localhost:8080/api/items", "method": method, "headers": headers } }); + // A page on another origin: the response names that origin, as the real server would. + let (_, params) = answer(&from_page("GET", json!({ "origin": "http://localhost:5173" })), &rules); + assert_eq!(header(¶ms, "Access-Control-Allow-Origin"), Some("http://localhost:5173")); + assert_eq!(header(¶ms, "Access-Control-Allow-Credentials"), Some("true")); + assert_eq!(params["body"], "W10="); + + // The browser's question before such a request is answered too: the server may not exist. + let preflight = from_page( + "OPTIONS", + json!({ + "Origin": "http://localhost:5173", + "Access-Control-Request-Method": "PUT", + "Access-Control-Request-Headers": "content-type,x-token", + }), + ); + let (command, params) = answer(&preflight, &rules); + assert_eq!((command, ¶ms["responseCode"]), ("Fetch.fulfillRequest", &json!(204))); + assert_eq!(header(¶ms, "Access-Control-Allow-Origin"), Some("http://localhost:5173")); + assert_eq!(header(¶ms, "Access-Control-Allow-Methods"), Some("PUT")); + assert_eq!(header(¶ms, "Access-Control-Allow-Headers"), Some("content-type,x-token")); + assert_eq!(params.get("body"), None); + + // Same origin: nothing but the rule's own header. + let (_, params) = answer(&from_page("GET", json!({})), &rules); + assert_eq!(params["responseHeaders"], json!([{ "name": "Content-Type", "value": "application/json" }])); + } + + /// A stand-in for js-debug's CDP proxy: what it receives, and a way to send it events. + pub(crate) async fn proxy() -> (String, mpsc::UnboundedReceiver, mpsc::UnboundedSender) { + proxy_refusing(|_| false).await + } + + /// A proxy that answers the commands `refused` picks with an error, like the real one does + /// for what it or the browser does not accept. + pub(crate) async fn proxy_refusing( + refused: fn(&Value) -> bool, + ) -> (String, mpsc::UnboundedReceiver, mpsc::UnboundedSender) { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("ws://127.0.0.1:{}/session", listener.local_addr().unwrap().port()); + let (received_tx, received) = mpsc::unbounded_channel(); + let (events, mut events_rx) = mpsc::unbounded_channel::(); + tokio::spawn(async move { + let (stream, _) = listener.accept().await.unwrap(); + let (mut write, mut read) = tokio_tungstenite::accept_async(stream).await.unwrap().split(); + loop { + tokio::select! { + message = read.next() => { + let Some(Ok(message)) = message else { break }; + let Ok(text) = message.to_text() else { continue }; + let Ok(request) = serde_json::from_str::(text) else { continue }; + let reply = if refused(&request) { + json!({ "id": request["id"], "error": { "code": -32602, "message": "refused" } }) + } else { + json!({ "id": request["id"], "result": {} }) + }; + let _ = write.send(Message::text(reply.to_string())).await; + let _ = received_tx.send(request); + } + Some(event) = events_rx.recv() => { + let _ = write.send(Message::text(event.to_string())).await; + } + } + } + }); + (url, received, events) + } + + pub(crate) async fn next(received: &mut mpsc::UnboundedReceiver) -> (String, Value) { + let request = tokio::time::timeout(std::time::Duration::from_secs(5), received.recv()) + .await + .expect("the proxy got a request in time") + .expect("the connection is open"); + (request["method"].as_str().unwrap().to_owned(), request["params"].clone()) + } + + /// The browser's event for a request it holds. + fn held(request_id: &str, url: &str) -> Value { + json!({ "method": "Fetch.requestPaused", "params": { "requestId": request_id, "request": { "url": url } } }) + } + + type Serving = (tokio::task::JoinHandle<()>, oneshot::Receiver>); + + fn serving(url: String, rules: watch::Receiver>) -> Serving { + let (ready, is_ready) = oneshot::channel(); + (tokio::spawn(serve(url, rules, ready)), is_ready) + } + + async fn ended(task: tokio::task::JoinHandle<()>) { + tokio::time::timeout(std::time::Duration::from_secs(5), task).await.unwrap().unwrap(); + } + + #[tokio::test] + async fn held_requests_are_answered_and_interception_ends_before_the_connection() { + let (url, mut received, events) = proxy().await; + let (rules, watched) = tokio::sync::watch::channel(vec![rule("api/items", 200, "[]")]); + let (serving, ready) = serving(url, watched); + assert_eq!(ready.await.unwrap(), Ok(())); + + assert_eq!( + next(&mut received).await, + ("JsDebug.subscribe".into(), json!({ "events": ["Fetch.requestPaused"] })) + ); + assert_eq!( + next(&mut received).await, + ( + "Fetch.enable".into(), + json!({ "patterns": [{ "urlPattern": "*api/items*", "requestStage": "Request" }] }) + ) + ); + + events.send(held("1", "http://h/api/items")).unwrap(); + let (command, params) = next(&mut received).await; + assert_eq!( + (command.as_str(), ¶ms["requestId"], ¶ms["responseCode"]), + ("Fetch.fulfillRequest", &json!("1"), &json!(200)) + ); + events.send(held("2", "http://h/other")).unwrap(); + assert_eq!(next(&mut received).await, ("Fetch.continueRequest".into(), json!({ "requestId": "2" }))); + + // New rules replace the browser's patterns. + rules.send(vec![rule("api/users", 404, "{}")]).unwrap(); + assert_eq!( + next(&mut received).await, + ( + "Fetch.enable".into(), + json!({ "patterns": [{ "urlPattern": "*api/users*", "requestStage": "Request" }] }) + ) + ); + + // No rules left: the browser stops holding requests. The connection stays for the + // rules that come next, and goes with the session. + rules.send(Vec::new()).unwrap(); + assert_eq!(next(&mut received).await.0, "Fetch.disable"); + rules.send(vec![rule("api/items", 200, "[]")]).unwrap(); + assert_eq!(next(&mut received).await.0, "Fetch.enable"); + rules.send(Vec::new()).unwrap(); + assert_eq!(next(&mut received).await.0, "Fetch.disable"); + drop(rules); + ended(serving).await; + // Already off: not switched off a second time. + assert!(received.try_recv().is_err()); + } + + #[tokio::test] + async fn a_session_that_goes_away_switches_interception_off() { + let (url, mut received, _events) = proxy().await; + let (rules, watched) = tokio::sync::watch::channel(vec![rule("api", 200, "[]")]); + let (serving, _ready) = serving(url, watched); + assert_eq!(next(&mut received).await.0, "JsDebug.subscribe"); + assert_eq!(next(&mut received).await.0, "Fetch.enable"); + drop(rules); + assert_eq!(next(&mut received).await.0, "Fetch.disable"); + ended(serving).await; + } + + #[tokio::test] + async fn a_response_the_browser_refuses_lets_the_request_through() { + let (url, mut received, events) = proxy_refusing(|request| request["method"] == "Fetch.fulfillRequest").await; + let (_rules, watched) = tokio::sync::watch::channel(vec![rule("api", 200, "[]")]); + let (_serving, _ready) = serving(url, watched); + assert_eq!(next(&mut received).await.0, "JsDebug.subscribe"); + assert_eq!(next(&mut received).await.0, "Fetch.enable"); + events.send(held("9", "http://h/api")).unwrap(); + assert_eq!(next(&mut received).await.0, "Fetch.fulfillRequest"); + // Unanswered, the request would hang the page. + assert_eq!(next(&mut received).await, ("Fetch.continueRequest".into(), json!({ "requestId": "9" }))); + } + + #[tokio::test] + async fn a_proxy_that_does_not_report_held_requests_is_not_asked_to_hold_any() { + let (url, mut received, _events) = proxy_refusing(|request| request["method"] == "JsDebug.subscribe").await; + let (_rules, watched) = tokio::sync::watch::channel(vec![rule("api", 200, "[]")]); + let (serving, ready) = serving(url, watched); + assert_eq!(next(&mut received).await.0, "JsDebug.subscribe"); + assert_eq!(ready.await.unwrap(), Err("refused".to_owned())); + ended(serving).await; + assert!(received.try_recv().is_err()); + } + + #[tokio::test] + async fn no_connection_to_the_proxy_is_reported() { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("ws://127.0.0.1:{}/session", listener.local_addr().unwrap().port()); + drop(listener); + let (_rules, watched) = tokio::sync::watch::channel(vec![rule("api", 200, "[]")]); + let (serving, ready) = serving(url, watched); + assert!(ready.await.unwrap().is_err()); + ended(serving).await; + } +} diff --git a/crates/ide-dap/src/js_debug.rs b/crates/ide-dap/src/js_debug.rs index d51e8ff07..b87541e58 100644 --- a/crates/ide-dap/src/js_debug.rs +++ b/crates/ide-dap/src/js_debug.rs @@ -27,7 +27,7 @@ pub(crate) fn is_page(session: &Session) -> bool { /// Waits until the adapter answered the `launch` of `session`. js-debug sets a page's session /// up between `configurationDone` and that answer; a request of its own that arrives then is /// answered and has no effect. -async fn launched(session: &Session) -> bool { +pub(crate) async fn launched(session: &Session) -> bool { let mut launched = session.launched.subscribe(); let answered = tokio::time::timeout(REQUEST_TIMEOUT, launched.wait_for(|answered| *answered)).await; matches!(answered, Ok(Ok(_))) diff --git a/crates/ide-dap/src/lib.rs b/crates/ide-dap/src/lib.rs index 5deb6dc59..18f05ca43 100644 --- a/crates/ide-dap/src/lib.rs +++ b/crates/ide-dap/src/lib.rs @@ -13,6 +13,7 @@ pub mod attach; mod cargo; pub mod connection; pub mod jdwp; +mod js_cdp; mod js_debug; mod jvm_memory; pub mod kotlin; @@ -24,6 +25,7 @@ use connection::{Connection, DapError}; use futures::future::join_all; use ide_core::{DebugSessionId, IdeError, IdeResult, SharedSink}; use ide_language::LanguageRegistry; +pub use js_cdp::JsResponseRule; pub use js_debug::JsResponseBody; pub use jvm_memory::*; use parking_lot::Mutex; diff --git a/crates/ide-dap/src/session.rs b/crates/ide-dap/src/session.rs index a83b32077..8855cedb3 100644 --- a/crates/ide-dap/src/session.rs +++ b/crates/ide-dap/src/session.rs @@ -94,6 +94,9 @@ pub(crate) struct Session { /// The `type` of the launch or attach request (js-debug's `pwa-node`, `pwa-chrome`); a child /// session's comes from the configuration the adapter started it with. pub launch_type: std::sync::OnceLock, + /// The response rules of a page once a connection applies them (`js_cdp::serve`). + /// Dropped with the session, which switches the browser's interception off. + pub js_overrides: tokio::sync::Mutex>>>, /// The file js-debug records the page's CPU profile into, while one is being recorded. pub js_profile: parking_lot::Mutex>, pub jvm_inspector: parking_lot::Mutex>>, @@ -257,6 +260,7 @@ impl Session { progress: Mutex::new(HashMap::new()), jdwp_link: parking_lot::Mutex::new(None), launch_type: std::sync::OnceLock::new(), + js_overrides: tokio::sync::Mutex::new(None), js_profile: parking_lot::Mutex::new(None), jvm_inspector: parking_lot::Mutex::new(None), inspect_lock: tokio::sync::Mutex::default(), diff --git a/crates/ide-dap/src/tests.rs b/crates/ide-dap/src/tests.rs index c7bc3e305..d40fcace1 100644 --- a/crates/ide-dap/src/tests.rs +++ b/crates/ide-dap/src/tests.rs @@ -1104,6 +1104,96 @@ async fn a_page_whose_requests_the_adapter_does_not_report_says_so() { h.wait_event(|e| matches!(e, DebugEvent::JsNetworkUnavailable)).await; } +/// Where the fake adapter says its CDP proxy listens (`requestCDPProxy`). +static CDP_PROXY_PORT: std::sync::atomic::AtomicU16 = std::sync::atomic::AtomicU16::new(0); + +fn proxy_adapter(msg: &Value) -> Option { + let port = CDP_PROXY_PORT.load(std::sync::atomic::Ordering::Relaxed); + (msg["command"] == "requestCDPProxy") + .then(|| (json!({ "host": "127.0.0.1", "port": port, "path": "/session" }), Vec::new())) +} + +#[tokio::test] +async fn response_overrides_reach_the_page_through_the_adapters_proxy() { + use crate::js_cdp::tests::{next, proxy, rule}; + let (url, mut received, _events) = proxy().await; + let port: u16 = url.trim_start_matches("ws://127.0.0.1:").trim_end_matches("/session").parse().unwrap(); + CDP_PROXY_PORT.store(port, std::sync::atomic::Ordering::Relaxed); + + let h = harness(Script { + start_debugging: true, + custom: Some(proxy_adapter), + child_launch_delay: Duration::from_millis(150), + ..Script::default() + }); + let browser = h.start(js_config("pwa-chrome")).await.unwrap(); + let page = child_of(&h, browser).await; + + // Rules that are there as the page starts wait until its session takes requests. + tokio::time::sleep(Duration::from_millis(50)).await; + h.manager.js_set_response_overrides(page, vec![rule("api/items", 200, "[]")]).await.unwrap(); + let dropped = h.log.lock().iter().filter(|m| m["type"] == "dropped").count(); + assert_eq!(dropped, 0, "the proxy was asked for before the page took requests"); + assert_eq!(next(&mut received).await.0, "JsDebug.subscribe"); + assert_eq!( + next(&mut received).await, + ("Fetch.enable".into(), json!({ "patterns": [{ "urlPattern": "*api/items*", "requestStage": "Request" }] })) + ); + // Changed rules go over the connection that is open: the proxy is asked for once. + h.manager.js_set_response_overrides(page, vec![rule("api/users", 200, "[]")]).await.unwrap(); + assert_eq!(next(&mut received).await.1["patterns"][0]["urlPattern"], "*api/users*"); + assert_eq!(requests(&h, "requestCDPProxy").len(), 1); + + h.manager.js_set_response_overrides(page, Vec::new()).await.unwrap(); + assert_eq!(next(&mut received).await.0, "Fetch.disable"); + // A rule switched back on. + h.manager.js_set_response_overrides(page, vec![rule("api/items", 200, "[]")]).await.unwrap(); + assert_eq!(next(&mut received).await.0, "Fetch.enable"); + assert_eq!(requests(&h, "requestCDPProxy").len(), 1); + + let not_a_page = h.manager.js_set_response_overrides(browser, vec![rule("api", 200, "")]).await.unwrap_err(); + assert_eq!(not_a_page.kind, ide_core::error::ErrorKind::Unavailable); +} + +#[tokio::test] +async fn response_overrides_are_unavailable_without_the_adapters_proxy() { + use crate::js_cdp::tests::rule; + let h = harness(Script { start_debugging: true, ..Script::default() }); + let browser = h.start(js_config("pwa-chrome")).await.unwrap(); + let page = child_of(&h, browser).await; + let refused = h.manager.js_set_response_overrides(page, vec![rule("api", 200, "")]).await.unwrap_err(); + assert_eq!(refused.kind, ide_core::error::ErrorKind::Unavailable); + // Nothing to switch off is not an error. + h.manager.js_set_response_overrides(page, Vec::new()).await.unwrap(); +} + +/// A port nothing listens on, which the fake adapter gives as its CDP proxy. +static DEAD_PROXY_PORT: std::sync::atomic::AtomicU16 = std::sync::atomic::AtomicU16::new(0); + +fn dead_proxy_adapter(msg: &Value) -> Option { + let port = DEAD_PROXY_PORT.load(std::sync::atomic::Ordering::Relaxed); + (msg["command"] == "requestCDPProxy") + .then(|| (json!({ "host": "127.0.0.1", "port": port, "path": "/session" }), Vec::new())) +} + +#[tokio::test] +async fn response_overrides_that_cannot_reach_the_browser_are_an_error() { + use crate::js_cdp::tests::rule; + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + DEAD_PROXY_PORT.store(listener.local_addr().unwrap().port(), std::sync::atomic::Ordering::Relaxed); + drop(listener); + + let h = harness(Script { start_debugging: true, custom: Some(dead_proxy_adapter), ..Script::default() }); + let browser = h.start(js_config("pwa-chrome")).await.unwrap(); + let page = child_of(&h, browser).await; + let unreachable = h.manager.js_set_response_overrides(page, vec![rule("api", 200, "")]).await.unwrap_err(); + assert_eq!(unreachable.kind, ide_core::error::ErrorKind::Unavailable); + // The next rules try again instead of going to a connection that never was. + let again = h.manager.js_set_response_overrides(page, vec![rule("api", 200, "")]).await.unwrap_err(); + assert_eq!(again.kind, ide_core::error::ErrorKind::Unavailable); + assert_eq!(requests(&h, "requestCDPProxy").len(), 2); +} + /// The file the fake adapter says it records a CPU profile into (`profileStarted`). static PROFILE_FILE: parking_lot::Mutex = parking_lot::Mutex::new(String::new()); diff --git a/crates/ide-host/src/ops/debug.rs b/crates/ide-host/src/ops/debug.rs index 66987b267..885a6223c 100644 --- a/crates/ide-host/src/ops/debug.rs +++ b/crates/ide-host/src/ops/debug.rs @@ -382,6 +382,15 @@ pub async fn debug_js_custom_breakpoints( host.debugger.js_set_custom_breakpoints(session, ids, xhr).await } +pub async fn debug_js_response_overrides( + host: &Host, + _window: &str, + session: DebugSessionId, + rules: Vec, +) -> IdeResult<()> { + host.debugger.js_set_response_overrides(session, rules).await +} + pub async fn debug_js_response_body( host: &Host, _window: &str, @@ -619,6 +628,9 @@ pub(crate) fn register(d: &mut Dispatcher) { debug_restart_frame(&c.host, &c.window, c.arg("session")?, c.arg("frameId")?).await }); d.add("debug_capabilities", |c| async move { debug_capabilities(&c.host, &c.window, c.arg("session")?) }); + d.add("debug_js_response_overrides", |c| async move { + debug_js_response_overrides(&c.host, &c.window, c.arg("session")?, c.arg("rules")?).await + }); d.add("debug_js_response_body", |c| async move { debug_js_response_body(&c.host, &c.window, c.arg("session")?, c.arg("requestId")?).await }); diff --git a/src-tauri/src/commands/debug.rs b/src-tauri/src/commands/debug.rs index b15e500a1..c0630906d 100644 --- a/src-tauri/src/commands/debug.rs +++ b/src-tauri/src/commands/debug.rs @@ -244,6 +244,18 @@ pub async fn debug_restart_frame(state: State<'_, AppState>, session: DebugSessi ide_host::ops::debug::debug_restart_frame(&state.host, "", session, frame_id).await } +/// The responses a debugged page gets in place of the server's, by a part of the URL; none +/// switches the replacing off. +#[tauri::command] +#[specta::specta] +pub async fn debug_js_response_overrides( + state: State<'_, AppState>, + session: DebugSessionId, + rules: Vec, +) -> IdeResult<()> { + ide_host::ops::debug::debug_js_response_overrides(&state.host, "", session, rules).await +} + /// The body of a response a debugged page received. #[tauri::command] #[specta::specta] diff --git a/src-tauri/src/commands/mod.rs b/src-tauri/src/commands/mod.rs index f89ae0a2f..516b77fd7 100644 --- a/src-tauri/src/commands/mod.rs +++ b/src-tauri/src/commands/mod.rs @@ -533,6 +533,7 @@ pub fn builder() -> tauri_specta::Builder { debug::debug_capabilities, debug::debug_js_custom_breakpoints, debug::debug_js_response_body, + debug::debug_js_response_overrides, debug::debug_js_start_profile, debug::debug_js_stop_profile, debug::debug_set_function_breakpoints, diff --git a/src/bindings.ts b/src/bindings.ts index 68ad26e80..d999141b7 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -1259,6 +1259,11 @@ export const commands = { debugJsCustomBreakpoints: (session: DebugSessionId, ids: string[], xhr: string[]) => typedError(__TAURI_INVOKE("debug_js_custom_breakpoints", { session, ids, xhr })), /** The body of a response a debugged page received. */ debugJsResponseBody: (session: DebugSessionId, requestId: string) => typedError(__TAURI_INVOKE("debug_js_response_body", { session, requestId })), + /** + * The responses a debugged page gets in place of the server's, by a part of the URL; none + * switches the replacing off. + */ + debugJsResponseOverrides: (session: DebugSessionId, rules: JsResponseRule[]) => typedError(__TAURI_INVOKE("debug_js_response_overrides", { session, rules })), /** Starts recording a debugged page's CPU profile. */ debugJsStartProfile: (session: DebugSessionId) => typedError(__TAURI_INVOKE("debug_js_start_profile", { session })), /** Ends the recording: a directory holding the profile as `page.cpuprofile`. */ @@ -6571,6 +6576,14 @@ export type JsResponseBody = { truncated: boolean, }; +/** A response given in place of the server's to every request whose URL contains `url_contains`. */ +export type JsResponseRule = { + urlContains: string, + status: number, + contentType: string, + body: string, +}; + /** The backend that reads a debugged JVM's objects (instances, fields, referrers). */ export type JvmBackendState = { kind: "ready" } | /** Turned off for the rest of the session: the debug adapter lacks what it needs. */ diff --git a/src/features/debugger/__tests__/NetworkView.test.tsx b/src/features/debugger/__tests__/NetworkView.test.tsx index 37a7c34c1..1189c75e6 100644 --- a/src/features/debugger/__tests__/NetworkView.test.tsx +++ b/src/features/debugger/__tests__/NetworkView.test.tsx @@ -19,6 +19,7 @@ vi.mock("@/platform/ipc", async (orig) => { evaluated.push(args); return Promise.resolve({ status: "ok", data: { value: "", variablesReference: 0 } }); }, + debugJsResponseOverrides: () => Promise.resolve({ status: "ok", data: null }), }, }; }); @@ -26,6 +27,7 @@ vi.mock("@/platform/ipc", async (orig) => { const { applyNetworkEvents, useJsNetwork } = await import("../js/network"); const { NetworkView } = await import("../js/NetworkView"); const { useJsBreakpoints } = await import("../js/eventBreakpoints"); +const { loadResponseOverrides, saveOverride } = await import("../js/responseOverrides"); const { setRefused } = await import("../js/refusals"); const { handleDebugEvent, useDebug } = await import("../state"); @@ -66,6 +68,8 @@ function load() { } beforeEach(() => { + localStorage.clear(); + loadResponseOverrides(null); useJsNetwork.setState({ rows: {} }); asked.length = 0; evaluated.length = 0; @@ -197,4 +201,58 @@ describe("Network view", () => { ).toBeInTheDocument(); setRefused(7, "network", null); }); + + it("marks the requests whose response a rule replaces", () => { + loadResponseOverrides("/p"); + saveOverride({ pattern: "/api/items", status: 200, contentType: "application/json", body: "[]", enabled: true }); + load(); + render(); + const rows = screen.getAllByRole("row").slice(1); + expect(rows[0]).toHaveTextContent("overridden"); + expect(rows[1]).not.toHaveTextContent("overridden"); + expect(screen.getByRole("button", { name: "Overrides (1)" })).toBeInTheDocument(); + }); + + it("does not mark a request as overridden when the page's debugger refused the rules, and says why", () => { + loadResponseOverrides("/p"); + saveOverride({ pattern: "/api/items", status: 200, contentType: "application/json", body: "[]", enabled: true }); + load(); + setRefused(7, "overrides", "no browser connection"); + render(); + expect(screen.getAllByRole("row")[1]).not.toHaveTextContent("overridden"); + expect(screen.getByRole("alert")).toHaveTextContent( + "Responses are not replaced in this page: no browser connection", + ); + setRefused(7, "overrides", null); + }); + + it("opens the override editor on a request, filled with its response", async () => { + loadResponseOverrides("/p"); + load(); + render(); + fireEvent.click(screen.getAllByRole("row")[1]!); + fireEvent.click(screen.getByRole("button", { name: "Override Response…" })); + await waitFor(() => expect(screen.getByLabelText("Part of the URL")).toHaveValue("/api/items")); + expect(screen.getByLabelText("Status")).toHaveValue("200"); + expect(screen.getByLabelText("Content type")).toHaveValue("application/json"); + expect(screen.getByLabelText("Response body")).toHaveValue('{"items":[]}'); + }); + + it("starts from an empty body when the request's own can't be read", async () => { + loadResponseOverrides("/p"); + load(); + answer = { status: "error", error: { kind: "unavailable", message: "gone" } }; + render(); + fireEvent.click(screen.getAllByRole("row")[1]!); + fireEvent.click(screen.getByRole("button", { name: "Override Response…" })); + await waitFor(() => expect(screen.getByLabelText("Part of the URL")).toHaveValue("/api/items")); + expect(screen.getByLabelText("Response body")).toHaveValue(""); + }); + + it("opens the list of overrides from the toolbar", () => { + loadResponseOverrides("/p"); + render(); + fireEvent.click(screen.getByRole("button", { name: "Overrides" })); + expect(screen.getByText("No overrides yet")).toBeInTheDocument(); + }); }); diff --git a/src/features/debugger/__tests__/OverridesDialog.test.tsx b/src/features/debugger/__tests__/OverridesDialog.test.tsx new file mode 100644 index 000000000..93a0738aa --- /dev/null +++ b/src/features/debugger/__tests__/OverridesDialog.test.tsx @@ -0,0 +1,94 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { fireEvent, render, screen, within } from "@testing-library/react"; + +vi.mock("@/platform/ipc", async (orig) => { + const real = await orig(); + return { + ...real, + commands: { ...real.commands, debugJsResponseOverrides: () => Promise.resolve({ status: "ok", data: null }) }, + }; +}); + +const { loadResponseOverrides, saveOverride, useResponseOverrides } = await import("../js/responseOverrides"); +const { OverridesDialog } = await import("../js/OverridesDialog"); + +const draft = { pattern: "/api/items", status: 200, contentType: "application/json", body: '{"items":[]}' }; +const rules = () => useResponseOverrides.getState().rules; +const field = (label: string) => screen.getByLabelText(label) as HTMLInputElement | HTMLTextAreaElement; + +beforeEach(() => { + localStorage.clear(); + loadResponseOverrides("/p"); +}); + +describe("Response Overrides dialog", () => { + it("opens on a request with its address, status, type and body filled in", () => { + render( {}} draft={draft} />); + expect(field("Part of the URL").value).toBe("/api/items"); + expect(field("Status").value).toBe("200"); + expect(field("Content type").value).toBe("application/json"); + expect(field("Response body").value).toBe('{"items":[]}'); + expect(rules()).toEqual([]); + }); + + it("saves the edited response as a rule that is on", () => { + render( {}} draft={draft} />); + fireEvent.change(field("Response body"), { target: { value: '{"items":["from the IDE"]}' } }); + fireEvent.change(field("Status"), { target: { value: "201" } }); + fireEvent.click(screen.getByRole("button", { name: "Save" })); + expect(rules()).toMatchObject([ + { + pattern: "/api/items", + status: 201, + contentType: "application/json", + body: '{"items":["from the IDE"]}', + enabled: true, + }, + ]); + // Saved once more, it is the same rule. + fireEvent.change(field("Response body"), { target: { value: "[]" } }); + fireEvent.click(screen.getByRole("button", { name: "Save" })); + expect(rules()).toHaveLength(1); + expect(rules()[0]!.body).toBe("[]"); + }); + + it("edits the rule a request already has instead of adding a second one", () => { + const id = saveOverride({ ...draft, body: "old", enabled: true }); + render( {}} draft={draft} />); + expect(field("Response body").value).toBe("old"); + fireEvent.change(field("Response body"), { target: { value: "new" } }); + fireEvent.click(screen.getByRole("button", { name: "Save" })); + expect(rules()).toMatchObject([{ id, body: "new" }]); + }); + + it("warns that a very short text replaces many responses, and saves nothing without one", () => { + render( {}} draft={{ ...draft, pattern: "/" }} />); + expect(screen.getByText("This also replaces every other response whose URL contains it")).toBeInTheDocument(); + fireEvent.change(field("Part of the URL"), { target: { value: " " } }); + expect(screen.getByRole("button", { name: "Save" })).toBeDisabled(); + }); + + it("lists the rules, switches them on and off, and removes the selected one", () => { + saveOverride({ ...draft, enabled: true }); + saveOverride({ ...draft, pattern: "/api/users", enabled: true }); + render( {}} />); + const list = screen.getByRole("list", { name: "Overrides" }); + expect(within(list).getAllByRole("listitem")).toHaveLength(2); + fireEvent.click(within(list).getByLabelText("/api/users")); + expect(rules().map((r) => r.enabled)).toEqual([true, false]); + + fireEvent.click(within(list).getByText("/api/items")); + expect(field("Part of the URL").value).toBe("/api/items"); + fireEvent.click(screen.getByRole("button", { name: "Remove" })); + expect(rules().map((r) => r.pattern)).toEqual(["/api/users"]); + }); + + it("starts an empty rule from the list", () => { + render( {}} />); + expect(screen.getByText("No overrides yet")).toBeInTheDocument(); + fireEvent.click(screen.getByRole("button", { name: "Add Override" })); + fireEvent.change(field("Part of the URL"), { target: { value: "/api/new" } }); + fireEvent.click(screen.getByRole("button", { name: "Save" })); + expect(rules()).toMatchObject([{ pattern: "/api/new", status: 200, contentType: "application/json", body: "" }]); + }); +}); diff --git a/src/features/debugger/__tests__/responseOverrides.test.ts b/src/features/debugger/__tests__/responseOverrides.test.ts new file mode 100644 index 000000000..a0d65d987 --- /dev/null +++ b/src/features/debugger/__tests__/responseOverrides.test.ts @@ -0,0 +1,191 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; +import type { JsResponseRule } from "@/platform/ipc"; + +const sent: Array<[number, JsResponseRule[]]> = []; +let refuse: number | null = null; +vi.mock("@/platform/ipc", async (orig) => { + const real = await orig(); + return { + ...real, + commands: { + ...real.commands, + debugJsResponseOverrides: (session: number, rules: JsResponseRule[]) => { + sent.push([session, rules]); + return Promise.resolve( + session === refuse + ? { status: "error", error: { kind: "unavailable", message: "refused" } } + : { status: "ok", data: null }, + ); + }, + }, + }; +}); + +const { useDebug } = await import("../state"); +const { + activeRules, + answeredBy, + loadResponseOverrides, + overriddenBy, + removeOverride, + saveOverride, + syncResponseOverrides, + toggleOverride, + useResponseOverrides, + watchOverrideSessions, +} = await import("../js/responseOverrides"); + +const { refusedIn } = await import("../js/refusals"); + +type Sessions = ReturnType["sessions"]; +function sessions(list: Array<{ id: number; page: boolean; status?: string }>) { + const out: Record = {}; + for (const s of list) + out[s.id] = { id: s.id, name: `s${s.id}`, status: s.status ?? "running", caps: { jsPage: s.page } }; + useDebug.setState({ sessions: out as Sessions }); +} +const rules = () => useResponseOverrides.getState().rules; +const items = { pattern: "/api/items", status: 200, contentType: "application/json", body: "[]", enabled: true }; + +beforeEach(async () => { + localStorage.clear(); + sessions([]); + loadResponseOverrides(null); + await Promise.resolve(); + sent.length = 0; + refuse = null; +}); + +describe("response overrides", () => { + it("sends the rules that are on and name a part of a URL", () => { + const sentRules = activeRules([ + { id: "a", ...items }, + { id: "b", ...items, pattern: "/api/off", enabled: false }, + { id: "c", ...items, pattern: " " }, + ]); + expect(sentRules).toEqual([ + { urlContains: "/api/items", status: 200, contentType: "application/json", body: "[]" }, + ]); + }); + + it("adds a rule, and updates it under the same id", () => { + loadResponseOverrides("/a"); + const id = saveOverride({ ...items, pattern: " /api/items " }); + expect(rules()).toEqual([{ id, ...items }]); + expect(saveOverride({ ...items, id, body: "[1]" })).toBe(id); + expect(rules()).toEqual([{ id, ...items, body: "[1]" }]); + toggleOverride(id, false); + expect(rules()[0]!.enabled).toBe(false); + removeOverride(id); + expect(rules()).toEqual([]); + }); + + it("answers 200 when the status is not an HTTP status", () => { + loadResponseOverrides("/a"); + saveOverride({ ...items, status: 99 }); + saveOverride({ ...items, pattern: "/b", status: 600 }); + saveOverride({ ...items, pattern: "/c", status: Number.NaN }); + saveOverride({ ...items, pattern: "/d", status: 404 }); + expect(rules().map((r) => r.status)).toEqual([200, 200, 200, 404]); + }); + + it("is stored per project", () => { + loadResponseOverrides("/a"); + saveOverride(items); + loadResponseOverrides("/b"); + expect(rules()).toEqual([]); + loadResponseOverrides("/a"); + expect(rules().map((r) => r.pattern)).toEqual(["/api/items"]); + }); + + it("tells which rule replaces a URL's response", () => { + const list = [ + { id: "off", ...items, pattern: "/api", enabled: false }, + { id: "on", ...items }, + ]; + expect(overriddenBy("http://h/api/items?x=1", list)?.id).toBe("on"); + expect(overriddenBy("http://h/api/users", list)).toBeNull(); + }); + + it("marks only the requests sent after a rule came into force", async () => { + const { networkSerial } = await import("../js/network"); + const before = { url: "http://x/api/items?page=1", seq: networkSerial() - 1 }; + const id = saveOverride({ + pattern: "/api/items", + status: 200, + contentType: "application/json", + body: "[]", + enabled: true, + }); + const rules = useResponseOverrides.getState().rules; + const after = { url: "http://x/api/items?page=2", seq: networkSerial() }; + expect(answeredBy(before, rules)).toBe(false); + expect(answeredBy(after, rules)).toBe(true); + // Rules the project has when it opens answer every request of its sessions. + loadResponseOverrides(useResponseOverrides.getState().root); + const loaded = useResponseOverrides.getState().rules; + expect(answeredBy(before, loaded)).toBe(loaded.some((r) => r.id === id)); + }); + + it("syncs every live page session and swallows a refusal", async () => { + sessions([ + { id: 1, page: true }, + { id: 2, page: false }, + { id: 3, page: true }, + { id: 4, page: true, status: "terminated" }, + ]); + loadResponseOverrides("/a"); + useResponseOverrides.setState({ rules: [{ id: "a", ...items }] }); + await Promise.resolve(); + sent.length = 0; + refuse = 1; + await expect(syncResponseOverrides()).resolves.toBeUndefined(); + expect(sent.map(([id, r]) => [id, r.length])).toEqual([ + [1, 1], + [3, 1], + ]); + // The page whose responses are not replaced is remembered, with the reason. + expect([1, 3].map((id) => refusedIn(id, "overrides"))).toEqual(["refused", undefined]); + refuse = null; + await syncResponseOverrides(); + expect(refusedIn(1, "overrides")).toBeUndefined(); + }); + + it("gives a page that starts later the rules, once, and nothing when none is on", async () => { + loadResponseOverrides("/a"); + const stop = watchOverrideSessions(); + sessions([{ id: 5, page: true }]); + await Promise.resolve(); + expect(sent).toEqual([]); + + saveOverride(items); + await Promise.resolve(); + sent.length = 0; + sessions([ + { id: 5, page: true }, + { id: 7, page: true }, + ]); + sessions([ + { id: 5, page: true }, + { id: 7, page: true }, + ]); + await Promise.resolve(); + expect(sent.map(([id]) => id)).toEqual([7]); + stop(); + }); + + it("gives a new page the rules when its session id was used before", async () => { + loadResponseOverrides("/a"); + saveOverride(items); + const stop = watchOverrideSessions(); + sessions([{ id: 1, page: true }]); + await Promise.resolve(); + // Ids start over after the backend restarts. + sessions([]); + sent.length = 0; + sessions([{ id: 1, page: true }]); + await Promise.resolve(); + expect(sent.map(([id]) => id)).toEqual([1]); + stop(); + }); +}); diff --git a/src/features/debugger/index.ts b/src/features/debugger/index.ts index a43d081b1..1467efbf3 100644 --- a/src/features/debugger/index.ts +++ b/src/features/debugger/index.ts @@ -22,6 +22,7 @@ import { loadBreakpoints } from "./breakpoints/store"; import { loadExceptionBreakpoints } from "./breakpoints/exceptions"; import { loadJsBreakpoints, watchPageSessions } from "./js/eventBreakpoints"; import { watchNetworkSessions } from "./js/networkSessions"; +import { loadResponseOverrides, watchOverrideSessions } from "./js/responseOverrides"; import { watchProfiledSessions } from "./js/profile"; import { loadSpecialBreakpoints } from "./breakpoints/special"; import { breakpointGutter } from "./editor/breakpointGutter"; @@ -67,6 +68,7 @@ export function activate(): () => void { loadExceptionBreakpoints(useProject.getState().project?.root ?? null); loadSpecialBreakpoints(useProject.getState().project?.root ?? null); loadJsBreakpoints(useProject.getState().project?.root ?? null); + loadResponseOverrides(useProject.getState().project?.root ?? null); const disposers = [ () => useDebugRunSessions.setState({ sessions: [], serviceSessions: [], Console: null }), registerDebugActions(), @@ -147,10 +149,12 @@ export function activate(): () => void { loadExceptionBreakpoints(root); loadSpecialBreakpoints(root); loadJsBreakpoints(root); + loadResponseOverrides(root); } }), watchPageSessions(), watchNetworkSessions(), + watchOverrideSessions(), watchProfiledSessions(), ]; return () => disposers.reverse().forEach((d) => d()); diff --git a/src/features/debugger/js/Network.module.css b/src/features/debugger/js/Network.module.css index 0feb40833..e01a32e2a 100644 --- a/src/features/debugger/js/Network.module.css +++ b/src/features/debugger/js/Network.module.css @@ -48,9 +48,20 @@ } .actions { + display: flex; + gap: 4px; padding-top: 6px; } +.badge { + margin-left: 6px; + border-radius: 3px; + padding: 0 4px; + background: var(--bg-selected); + color: var(--fg-muted); + font-size: var(--fs-small); +} + .split { display: flex; flex: 1; diff --git a/src/features/debugger/js/NetworkView.tsx b/src/features/debugger/js/NetworkView.tsx index a643c7278..176586edf 100644 --- a/src/features/debugger/js/NetworkView.tsx +++ b/src/features/debugger/js/NetworkView.tsx @@ -11,7 +11,9 @@ import { type NetworkCategory, type NetworkRow, } from "./network"; +import { OverridesDialog, type OverrideDraft } from "./OverridesDialog"; import { useRefused } from "./refusals"; +import { answeredBy, useResponseOverrides } from "./responseOverrides"; import styles from "./Network.module.css"; const NO_ROWS: NetworkRow[] = []; @@ -39,10 +41,13 @@ export function formatDuration(ms: number | null): string { const Row = memo(function Row({ row, selected, + overridden, onSelect, }: { row: NetworkRow; selected: boolean; + /** A response override applies to requests to this URL. */ + overridden: boolean; onSelect: (key: string) => void; }) { return ( @@ -56,7 +61,14 @@ const Row = memo(function Row({ {row.name} - {row.error ?? row.status ?? ""} + + {row.error ?? row.status ?? ""} + {overridden && ( + + overridden + + )} + {row.method} {row.type} @@ -126,7 +138,15 @@ function ResponseBody({ session, requestId }: { session: number; requestId: stri ); } -function Detail({ session, row }: { session: number; row: NetworkRow }) { +function Detail({ + session, + row, + onOverride, +}: { + session: number; + row: NetworkRow; + onOverride: (row: NetworkRow) => void; +}) { const tx = useTx(); return (
@@ -144,6 +164,9 @@ function Detail({ session, row }: { session: number; row: NetworkRow }) { +
@@ -176,6 +199,23 @@ export function NetworkView({ session }: { session: number }) { const shown = useMemo(() => filterRows(rows, query, category, mine), [rows, query, category, mine]); const selected = rows.find((r) => r.key === selectedKey) ?? null; const notReported = useRefused(session, "network") != null; + const overrides = useResponseOverrides((s) => s.rules); + const overridesOn = overrides.filter((r) => r.enabled).length; + const notReplaced = useRefused(session, "overrides"); + // The override editor: open on the list (`draft` null) or on a request's response. + const [editing, setEditing] = useState<{ draft: OverrideDraft | null } | null>(null); + const overrideResponse = async (row: NetworkRow) => { + // The request's own body is where the edit starts; one that can't be read as text starts empty. + const own = await call(commands.debugJsResponseBody(session, row.requestId)).catch(() => null); + setEditing({ + draft: { + pattern: requestPattern(row.url), + status: row.status ?? 200, + contentType: row.mimeType ?? "application/json", + body: own && !own.base64Encoded ? own.body : "", + }, + }); + }; return (
@@ -199,12 +239,21 @@ export function NetworkView({ session }: { session: number }) { ))}
+ reloadPage(session)} /> clearNetwork(session)} /> {shown.length === rows.length ? rows.length : `${shown.length} / ${rows.length}`}
+ {notReplaced != null && overridesOn > 0 && ( +
+ {tx`Responses are not replaced in this page: ${notReplaced}`} +
+ )}
@@ -225,11 +274,18 @@ export function NetworkView({ session }: { session: number }) {
)} {shown.map((row) => ( - + ))}
- {selected && } + {selected && void overrideResponse(row)} />}
+ setEditing(null)} draft={editing?.draft} /> ); } diff --git a/src/features/debugger/js/Overrides.module.css b/src/features/debugger/js/Overrides.module.css new file mode 100644 index 000000000..e358361b9 --- /dev/null +++ b/src/features/debugger/js/Overrides.module.css @@ -0,0 +1,135 @@ +.root { + display: flex; + height: 420px; + min-height: 0; + font-size: var(--fs-ui); +} + +.side { + flex: 0 0 240px; + display: flex; + flex-direction: column; + min-width: 0; + border-right: 1px solid var(--border-popup); +} + +.sideHead { + display: flex; + align-items: center; + justify-content: space-between; + padding: 6px 8px 4px 12px; +} + +.sideTitle { + font-size: var(--fs-small); + font-weight: 600; + color: var(--fg-muted); +} + +.list { + list-style: none; + margin: 0; + padding: 0; + overflow: auto; +} + +.item { + display: flex; + align-items: center; + gap: 6px; + min-height: 24px; + padding: 0 8px 0 12px; +} + +.item:hover { + background: var(--bg-hover); +} + +.itemOn, +.itemOn:hover { + background: var(--bg-list-selected); +} + +.itemName { + flex: 1; + min-width: 0; + border: 0; + padding: 0; + background: transparent; + color: inherit; + font-family: var(--font-mono); + font-size: var(--fs-small); + text-align: left; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + cursor: default; +} + +.itemStatus { + color: var(--fg-subtle); + font-size: var(--fs-small); +} + +.editor { + flex: 1; + min-width: 0; + display: flex; + flex-direction: column; + gap: 8px; + padding: 10px 12px; +} + +.row { + display: flex; + gap: 10px; +} + +.field { + display: flex; + flex-direction: column; + gap: 3px; + min-height: 0; +} + +.grow { + flex: 1; +} + +.label { + font-size: var(--fs-small); + color: var(--fg-muted); +} + +.body { + flex: 1; + min-height: 120px; + resize: none; + border: 1px solid var(--border); + border-radius: 4px; + padding: 6px 8px; + background: transparent; + color: inherit; + font-family: var(--font-mono); + font-size: var(--fs-small); + outline: none; +} + +.body:focus { + border-color: var(--border-popup); +} + +.warning { + color: var(--danger); + font-size: var(--fs-small); +} + +.actions { + display: flex; + gap: 8px; +} + +.note { + padding: 8px 12px; + color: var(--fg-subtle); +} diff --git a/src/features/debugger/js/OverridesDialog.tsx b/src/features/debugger/js/OverridesDialog.tsx new file mode 100644 index 000000000..4c19c6c09 --- /dev/null +++ b/src/features/debugger/js/OverridesDialog.tsx @@ -0,0 +1,201 @@ +import { useState } from "react"; +import { useTx } from "@/platform/i18n"; +import { Button, Checkbox, Dialog, IconButton, Input, T } from "@/ui"; +import { + removeOverride, + saveOverride, + toggleOverride, + useResponseOverrides, + type ResponseOverride, +} from "./responseOverrides"; +import styles from "./Overrides.module.css"; + +/** A response to start a rule from: a request's own, as the Network tab shows it. */ +export interface OverrideDraft { + pattern: string; + status: number; + contentType: string; + body: string; +} + +interface Form { + /** The rule being edited; absent for one not saved yet. */ + id?: string; + pattern: string; + status: string; + contentType: string; + body: string; +} + +const EMPTY: Form = { pattern: "", status: "200", contentType: "application/json", body: "" }; + +const formOf = (rule: ResponseOverride): Form => ({ + id: rule.id, + pattern: rule.pattern, + status: String(rule.status), + contentType: rule.contentType, + body: rule.body, +}); + +/** The rule a request already has is edited; otherwise the request's response starts a new one. */ +function initialForm(draft: OverrideDraft | null | undefined, rules: readonly ResponseOverride[]): Form | null { + if (!draft) return null; + const pattern = draft.pattern.trim(); + const existing = rules.find((r) => r.pattern === pattern); + return existing + ? formOf(existing) + : { pattern, status: String(draft.status), contentType: draft.contentType, body: draft.body }; +} + +function OverridesBody({ onClose, draft }: { onClose: () => void; draft?: OverrideDraft | null }) { + const tx = useTx(); + const rules = useResponseOverrides((s) => s.rules); + const [form, setForm] = useState
(() => initialForm(draft, useResponseOverrides.getState().rules)); + const set = (patch: Partial) => setForm((f) => (f ? { ...f, ...patch } : f)); + const pattern = form?.pattern.trim() ?? ""; + const save = () => { + if (!form || !pattern) return; + const enabled = rules.find((r) => r.id === form.id)?.enabled ?? true; + const id = saveOverride({ + id: form.id, + pattern, + status: Number(form.status), + contentType: form.contentType.trim() || "text/plain", + body: form.body, + enabled, + }); + setForm({ ...form, id, pattern }); + }; + return ( + +
+
+
+ + Overrides + + setForm({ ...EMPTY })} /> +
+ {rules.length === 0 ? ( +
+ No overrides yet +
+ ) : ( +
    + {rules.map((rule) => ( +
  • + toggleOverride(rule.id, on)} + aria-label={rule.pattern} + /> + + {rule.status} +
  • + ))} +
+ )} +
+ {form ? ( +
+ + {pattern.length > 0 && pattern.length < 3 && ( +
+ This also replaces every other response whose URL contains it +
+ )} +
+ + +
+