Skip to main content

eoka_protocol/sidecar/
methods.rs

1use super::*;
2
3pub fn validate_safe_numbers(value: &Value) -> Result<(), ServerError> {
4    match value {
5        Value::Number(number) => {
6            let unsafe_integer = number.as_u64().is_some_and(|n| n > MAX_SAFE_INTEGER)
7                || number
8                    .as_i64()
9                    .is_some_and(|n| n < -(MAX_SAFE_INTEGER as i64))
10                || number
11                    .as_f64()
12                    .is_some_and(|n| n.fract() == 0.0 && n.abs() > MAX_SAFE_INTEGER as f64);
13            if unsafe_integer {
14                return Err(ServerError::invalid_params(
15                    "integer exceeds JavaScript's exact safe integer range",
16                ));
17            }
18        }
19        Value::Array(values) => {
20            for value in values {
21                validate_safe_numbers(value)?;
22            }
23        }
24        Value::Object(values) => {
25            for value in values.values() {
26                validate_safe_numbers(value)?;
27            }
28        }
29        _ => {}
30    }
31    Ok(())
32}
33
34fn constrain_integers(value: &mut Value) {
35    match value {
36        Value::Object(object) => {
37            let integer = object.get("type").is_some_and(|ty| {
38                ty == "integer"
39                    || ty
40                        .as_array()
41                        .is_some_and(|types| types.iter().any(|ty| ty == "integer"))
42            });
43            if integer {
44                let (rust_minimum, rust_maximum) =
45                    match object.get("format").and_then(Value::as_str) {
46                        Some("int8") => (i8::MIN as f64, i8::MAX as f64),
47                        Some("int16") => (i16::MIN as f64, i16::MAX as f64),
48                        Some("int32") => (i32::MIN as f64, i32::MAX as f64),
49                        Some("uint8") => (0.0, u8::MAX as f64),
50                        Some("uint16") => (0.0, u16::MAX as f64),
51                        Some("uint32") => (0.0, u32::MAX as f64),
52                        Some("uint") => (0.0, (usize::MAX as f64).min(MAX_SAFE_INTEGER as f64)),
53                        Some("uint64" | "uint128") => (0.0, MAX_SAFE_INTEGER as f64),
54                        _ => (-(MAX_SAFE_INTEGER as f64), MAX_SAFE_INTEGER as f64),
55                    };
56                let maximum = object
57                    .get("maximum")
58                    .and_then(Value::as_f64)
59                    .unwrap_or(f64::INFINITY)
60                    .min(rust_maximum);
61                let minimum = object
62                    .get("minimum")
63                    .and_then(Value::as_f64)
64                    .unwrap_or(f64::NEG_INFINITY)
65                    .max(rust_minimum);
66                object.insert("maximum".into(), json!(maximum));
67                object.insert("minimum".into(), json!(minimum));
68            }
69            for child in object.values_mut() {
70                constrain_integers(child);
71            }
72        }
73        Value::Array(values) => {
74            for child in values {
75                constrain_integers(child);
76            }
77        }
78        _ => {}
79    }
80}
81
82pub(super) fn schema<T: JsonSchema>() -> Value {
83    let mut value =
84        serde_json::to_value(schemars::schema_for!(T)).expect("JSON schemas are serializable");
85    constrain_integers(&mut value);
86    value
87}
88
89#[derive(Debug, Clone, Copy, PartialEq, Eq)]
90pub enum MethodRole {
91    Lifecycle,
92    Shared,
93    Distinct(&'static str),
94}
95
96macro_rules! define_sidecar_methods {
97    (@feature) => { None };
98    (@feature $feature:literal) => { Some($feature) };
99    ($($variant:ident $name:literal: $params:ty $(, $check:expr)? => $result:ty, $role:ident $(($reason:literal))? $(, feature $feature:literal)?;)*) => {
100        #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
101        pub enum Method { $($variant),* }
102
103        impl Method {
104            pub const ALL: &'static [Method] = &[$(Method::$variant),*];
105
106            pub fn parse(name: &str) -> Option<Self> {
107                match name {
108                    $($name => Some(Self::$variant),)*
109                    _ => None,
110                }
111            }
112
113            pub fn name(self) -> &'static str {
114                match self { $(Self::$variant => $name),* }
115            }
116
117            pub fn role(self) -> MethodRole {
118                match self { $(Self::$variant => MethodRole::$role $(($reason))?),* }
119            }
120
121            pub fn feature(self) -> Option<&'static str> {
122                match self { $(Self::$variant => define_sidecar_methods!(@feature $($feature)?)),* }
123            }
124
125            pub fn params_schema(self) -> Value {
126                match self { $(Self::$variant => schema::<$params>()),* }
127            }
128
129            pub fn result_schema(self) -> Value {
130                match self { $(Self::$variant => schema::<$result>()),* }
131            }
132
133            pub fn validate(self, params: &Value) -> Result<(), ServerError> {
134                match self {
135                    $(Self::$variant => {
136                        let _params = <$params>::deserialize(params)
137                            .map_err(|error| ServerError::invalid_params(error.to_string()))?;
138                        $(($check)(&_params)?;)?
139                        Ok(())
140                    }),*
141                }
142            }
143        }
144    };
145}
146
147define_sidecar_methods! {
148    ServerHello "server.hello": HelloParams => HelloResult, Lifecycle;
149    ServerShutdown "server.shutdown": Empty => Empty, Lifecycle;
150    BrowserLaunch "browser.launch": LaunchParams, LaunchParams::validate => BrowserSessionResult, Lifecycle;
151    BrowserConnect "browser.connect": ConnectParams, ConnectParams::validate => BrowserSessionResult, Lifecycle;
152    BrowserNewPage "browser.new_page": NewPageParams => NewPageResult, Lifecycle;
153    BrowserTabs "browser.tabs": Empty => TabsResult, Lifecycle;
154    BrowserCloseTab "browser.close_tab": PageIdParams => CloseTabResult, Lifecycle;
155    BrowserClose "browser.close": Empty => Empty, Lifecycle;
156    ActionsPerform "actions.perform": ActionPerformParams => crate::OperationRecord, Shared;
157    OperationsGet "operations.get": OperationIdArgs => crate::OperationRecord, Shared;
158    OperationsList "operations.list": OperationListArgs => Vec<crate::OperationRecord>, Shared;
159    OperationsWait "operations.wait": OperationWaitArgs => crate::OperationRecord, Shared;
160    OperationsCancel "operations.cancel": OperationIdArgs => crate::OperationRecord, Shared;
161    AgentObserve "agent.observe": AgentObserveParams => crate::AgentObservation, Shared;
162    AgentStep "agent.step": AgentStepParams => crate::AgentStepResult, Shared;
163    PageCaptureState "page.capture_state": PageIdParams => CaptureStateResult,
164        Distinct("in-memory state; catalog save_state and load_state use a file");
165    PageRestoreState "page.restore_state": RestoreStateParams => Empty,
166        Distinct("in-memory state; catalog save_state and load_state use a file");
167    RecordingStart "recording.start": RecordingStartParams, RecordingStartParams::validate => RecordingRecord, Shared;
168    RecordingGet "recording.get": RecordingIdParams, RecordingIdParams::validate => RecordingRecord, Shared;
169    RecordingStop "recording.stop": RecordingIdParams, RecordingIdParams::validate => RecordingRecord, Shared;
170    RecordingCancel "recording.cancel": RecordingIdParams, RecordingIdParams::validate => RecordingRecord, Shared;
171    PageSolveCaptcha "page.solve_captcha": SolveCaptchaParams => SolveCaptchaResult,
172        Distinct("provider solving runs client-side in the CLI"), feature "anti-captcha";
173}
174
175pub fn catalog_operations() -> impl Iterator<Item = &'static crate::OperationSpec> {
176    page_operations().filter(|operation| Method::parse(operation.path).is_none())
177}
178
179pub fn page_operations() -> impl Iterator<Item = &'static crate::OperationSpec> {
180    crate::all_operations().iter().filter(|operation| {
181        operation.exposure != crate::OperationExposure::Lifecycle
182            && !operation.path.starts_with("tab.")
183            && !matches!(operation.path, "close" | "shutdown")
184    })
185}
186
187pub fn catalog_operation(method: &str) -> Option<&'static crate::OperationSpec> {
188    catalog_operations().find(|operation| operation.path == method)
189}
190
191pub fn catalog_request(
192    operation: &crate::OperationSpec,
193    params: &Value,
194) -> Result<(String, crate::Request), ServerError> {
195    let mut input = params.clone();
196    let page_id = input
197        .as_object_mut()
198        .and_then(|object| object.remove("pageId"))
199        .and_then(|value| value.as_str().map(str::to_owned))
200        .ok_or_else(|| ServerError::invalid_params("missing string field `pageId`"))?;
201    let schema = crate::input_schema_for_operation(operation);
202    if let (Some(known), Some(given)) = (schema["properties"].as_object(), input.as_object()) {
203        if let Some(unknown) = given.keys().find(|key| !known.contains_key(*key)) {
204            return Err(ServerError::invalid_params(format!(
205                "unknown field `{unknown}` for {}",
206                operation.path
207            )));
208        }
209    }
210    let request =
211        crate::request_from_cmd(operation.cmd, input).map_err(ServerError::invalid_params)?;
212    Ok((page_id, request))
213}
214
215fn catalog_params_schema(operation: &crate::OperationSpec) -> Value {
216    let page_id = json!({
217        "type": "object",
218        "properties": {"pageId": {"type": "string"}},
219        "required": ["pageId"],
220    });
221    let mut input = crate::input_schema_for_operation(operation);
222    constrain_integers(&mut input);
223    let plain_object = input["type"] == "object"
224        && ["oneOf", "anyOf", "allOf", "$ref"]
225            .iter()
226            .all(|key| input.get(key).is_none());
227    if !plain_object {
228        return json!({"allOf": [input, page_id]});
229    }
230    let object = input.as_object_mut().expect("checked above");
231    let properties = object.entry("properties").or_insert_with(|| json!({}));
232    properties["pageId"] = page_id["properties"]["pageId"].clone();
233    match object.entry("required").or_insert_with(|| json!([])) {
234        Value::Array(required) => required.push(json!("pageId")),
235        _ => unreachable!("JSON schema `required` is an array"),
236    }
237    input
238}
239
240fn catalog_result_schema(operation: &crate::OperationSpec) -> Value {
241    let mut result = crate::result_schema_for_cmd(operation.cmd)
242        .expect("every catalog operation declares a result");
243    constrain_integers(&mut result);
244    result
245}
246
247pub fn method_feature(method: &str) -> Option<&'static str> {
248    match Method::parse(method) {
249        Some(method) => method.feature(),
250        None => catalog_operation(method).and_then(|operation| operation.feature),
251    }
252}
253
254pub fn method_names() -> Vec<&'static str> {
255    Method::ALL
256        .iter()
257        .map(|method| method.name())
258        .chain(catalog_operations().map(|operation| operation.path))
259        .collect()
260}
261
262pub fn validate_params(method: &str, params: &Value) -> Result<(), ServerError> {
263    validate_safe_numbers(params)?;
264    if let Some(operation) = catalog_operation(method) {
265        return catalog_request(operation, params).map(|_| ());
266    }
267    Method::parse(method)
268        .ok_or_else(|| ServerError::unknown_method(method))?
269        .validate(params)
270}
271
272pub fn schema_bundle() -> Value {
273    let methods: BTreeMap<_, _> = Method::ALL
274        .iter()
275        .map(|method| {
276            (
277                method.name(),
278                json!({"params": method.params_schema(), "result": method.result_schema()}),
279            )
280        })
281        .chain(catalog_operations().map(|operation| {
282            (
283                operation.path,
284                json!({"params": catalog_params_schema(operation), "result": catalog_result_schema(operation)}),
285            )
286        }))
287        .collect();
288    let mut bundle = json!({
289        "protocolVersion": PROTOCOL_VERSION,
290        "methods": methods,
291        "types": {
292            "Request": schema::<Request>(), "Response": schema::<Response>(),
293            "ServerError": schema::<ServerError>(), "ErrorData": schema::<ErrorData>(),
294            "ErrorDetail": schema::<crate::ErrorDetail>(), "HelloResult": schema::<HelloResult>(),
295            "ProtocolVersion": schema::<ProtocolVersion>(), "HelloParams": schema::<HelloParams>(),
296            "TransportLimits": schema::<TransportLimits>(), "ErrorCode": schema::<ErrorCode>(),
297            "CdpErrorDetail": schema::<CdpErrorDetail>(),
298            "Action": schema::<crate::Action>(), "ActionOptions": schema::<crate::ActionOptions>(),
299            "ActionReceipt": schema::<crate::ActionReceipt>(), "LocatorSpec": schema::<crate::LocatorSpec>(),
300            "ActionOutcome": schema::<crate::ActionOutcome>(), "DispatchState": schema::<crate::DispatchState>(),
301            "LocatorQuery": schema::<crate::LocatorQuery>(),
302            "Expectation": schema::<crate::Expectation>(), "OperationRecord": schema::<crate::OperationRecord>(),
303            "OperationState": schema::<crate::OperationState>(), "AgentObservation": schema::<crate::AgentObservation>(),
304            "AgentStepResult": schema::<crate::AgentStepResult>(), "BrowserState": schema::<BrowserState>(),
305            "AgentAction": schema::<crate::AgentAction>(), "AgentMode": schema::<crate::AgentMode>(),
306            "ScreenshotFormat": schema::<ScreenshotFormat>(), "ScreenshotClip": schema::<ScreenshotClip>(),
307            "Artifact": schema::<Artifact>(), "ArtifactContainer": schema::<ArtifactContainer>(),
308            "RecordingStartParams": schema::<RecordingStartParams>(), "RecordingIdParams": schema::<RecordingIdParams>(),
309            "RecordingRecord": schema::<RecordingRecord>(), "RecordingState": schema::<RecordingState>(),
310            "RecordingFailure": schema::<RecordingFailure>(), "RecordingFailureStage": schema::<RecordingFailureStage>()
311        }
312    });
313    bundle["catalogMethods"] = catalog_operations()
314        .map(|operation| operation.path)
315        .collect();
316    bundle["types"]["InputMode"] = schema::<crate::InputMode>();
317    bundle["types"]["Destination"] = schema::<crate::Destination>();
318    bundle["types"]["CloudflareAutoSolve"] = schema::<CloudflareAutoSolve>();
319    bundle["types"]["PageBlocker"] = schema::<PageBlocker>();
320    bundle
321}