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)]
90pub struct MethodSpec {
91 pub name: &'static str,
92 pub params_schema: fn() -> Value,
93 pub result_schema: fn() -> Value,
94 pub validate: fn(&Value) -> Result<(), ServerError>,
95}
96
97macro_rules! methods {
98 ($($name:literal => $params:ty $(, $check:expr)? => $result:ty),* $(,)?) => {
99 pub const METHODS: &[MethodSpec] = &[$(MethodSpec {
100 name: $name,
101 params_schema: schema::<$params>,
102 result_schema: schema::<$result>,
103 validate: |params| {
104 let _params = <$params>::deserialize(params)
105 .map_err(|error| ServerError::invalid_params(error.to_string()))?;
106 $(($check)(&_params)?;)?
107 Ok(())
108 },
109 }),*];
110 };
111}
112
113methods! {
114 "server.hello" => HelloParams => HelloResult,
115 "server.shutdown" => Empty => Empty,
116 "browser.launch" => LaunchParams, LaunchParams::validate => BrowserSessionResult,
117 "browser.connect" => ConnectParams, ConnectParams::validate => BrowserSessionResult,
118 "browser.new_page" => NewPageParams => NewPageResult,
119 "browser.tabs" => Empty => TabsResult,
120 "browser.close_tab" => PageIdParams => CloseTabResult,
121 "browser.close" => Empty => Empty,
122 "actions.perform" => ActionPerformParams => crate::OperationRecord,
123 "operations.get" => OperationIdArgs => crate::OperationRecord,
124 "operations.list" => OperationListArgs => Vec<crate::OperationRecord>,
125 "operations.wait" => OperationWaitArgs => crate::OperationRecord,
126 "operations.cancel" => OperationIdArgs => crate::OperationRecord,
127 "agent.observe" => AgentObserveParams => crate::AgentObservation,
128 "agent.step" => AgentStepParams => crate::AgentStepResult,
129 "page.capture_state" => PageIdParams => CaptureStateResult,
130 "page.restore_state" => RestoreStateParams => Empty,
131 "recording.start" => RecordingStartParams, RecordingStartParams::validate => RecordingRecord,
132 "recording.get" => RecordingIdParams, RecordingIdParams::validate => RecordingRecord,
133 "recording.stop" => RecordingIdParams, RecordingIdParams::validate => RecordingRecord,
134 "recording.cancel" => RecordingIdParams, RecordingIdParams::validate => RecordingRecord,
135 "page.solve_captcha" => SolveCaptchaParams => SolveCaptchaResult,
136}
137
138#[derive(Debug, Clone, Copy, PartialEq, Eq)]
139pub enum MethodRole {
140 Lifecycle,
141 Shared,
142 Distinct(&'static str),
143}
144
145pub fn method_role(method: &str) -> Option<MethodRole> {
146 use MethodRole::*;
147 Some(match method {
148 "server.hello" | "server.shutdown" | "browser.launch" | "browser.connect"
149 | "browser.new_page" | "browser.tabs" | "browser.close_tab" | "browser.close" => Lifecycle,
150 "actions.perform" | "operations.get" | "operations.list" | "operations.wait"
151 | "operations.cancel" | "agent.observe" | "agent.step" | "recording.start"
152 | "recording.get" | "recording.stop" | "recording.cancel" => Shared,
153 "page.capture_state" | "page.restore_state" => {
154 Distinct("in-memory state; catalog save_state and load_state use a file")
155 }
156 "page.solve_captcha" => Distinct("provider solving runs client-side in the CLI"),
157 _ => return None,
158 })
159}
160
161pub fn catalog_operations() -> impl Iterator<Item = &'static crate::OperationSpec> {
162 page_operations()
163 .filter(|operation| !METHODS.iter().any(|method| method.name == operation.path))
164}
165
166pub fn page_operations() -> impl Iterator<Item = &'static crate::OperationSpec> {
167 crate::all_operations().iter().filter(|operation| {
168 operation.exposure != crate::OperationExposure::Lifecycle
169 && !operation.path.starts_with("tab.")
170 && !matches!(operation.path, "close" | "shutdown")
171 })
172}
173
174pub fn catalog_operation(method: &str) -> Option<&'static crate::OperationSpec> {
175 catalog_operations().find(|operation| operation.path == method)
176}
177
178pub fn catalog_request(
179 operation: &crate::OperationSpec,
180 params: &Value,
181) -> Result<(String, crate::Request), ServerError> {
182 let mut input = params.clone();
183 let page_id = input
184 .as_object_mut()
185 .and_then(|object| object.remove("pageId"))
186 .and_then(|value| value.as_str().map(str::to_owned))
187 .ok_or_else(|| ServerError::invalid_params("missing string field `pageId`"))?;
188 let schema = crate::input_schema_for_operation(operation);
189 if let (Some(known), Some(given)) = (schema["properties"].as_object(), input.as_object()) {
190 if let Some(unknown) = given.keys().find(|key| !known.contains_key(*key)) {
191 return Err(ServerError::invalid_params(format!(
192 "unknown field `{unknown}` for {}",
193 operation.path
194 )));
195 }
196 }
197 let request =
198 crate::request_from_cmd(operation.cmd, input).map_err(ServerError::invalid_params)?;
199 Ok((page_id, request))
200}
201
202fn catalog_params_schema(operation: &crate::OperationSpec) -> Value {
203 let page_id = json!({
204 "type": "object",
205 "properties": {"pageId": {"type": "string"}},
206 "required": ["pageId"],
207 });
208 let mut input = crate::input_schema_for_operation(operation);
209 constrain_integers(&mut input);
210 let plain_object = input["type"] == "object"
211 && ["oneOf", "anyOf", "allOf", "$ref"]
212 .iter()
213 .all(|key| input.get(key).is_none());
214 if !plain_object {
215 return json!({"allOf": [input, page_id]});
216 }
217 let object = input.as_object_mut().expect("checked above");
218 let properties = object.entry("properties").or_insert_with(|| json!({}));
219 properties["pageId"] = page_id["properties"]["pageId"].clone();
220 match object.entry("required").or_insert_with(|| json!([])) {
221 Value::Array(required) => required.push(json!("pageId")),
222 _ => unreachable!("JSON schema `required` is an array"),
223 }
224 input
225}
226
227pub fn method_feature(method: &str) -> Option<&'static str> {
228 match method {
229 "page.solve_captcha" => Some("anti-captcha"),
230 _ => catalog_operation(method).and_then(|operation| operation.feature),
231 }
232}
233
234pub fn method_names() -> Vec<&'static str> {
235 METHODS
236 .iter()
237 .map(|method| method.name)
238 .chain(catalog_operations().map(|operation| operation.path))
239 .collect()
240}
241
242pub fn validate_params(method: &str, params: &Value) -> Result<(), ServerError> {
243 validate_safe_numbers(params)?;
244 if let Some(operation) = catalog_operation(method) {
245 return catalog_request(operation, params).map(|_| ());
246 }
247 let spec = METHODS
248 .iter()
249 .find(|spec| spec.name == method)
250 .ok_or_else(|| ServerError::unknown_method(method))?;
251 (spec.validate)(params)
252}
253
254pub fn schema_bundle() -> Value {
255 let methods: BTreeMap<_, _> = METHODS
256 .iter()
257 .map(|method| {
258 (
259 method.name,
260 json!({"params": (method.params_schema)(), "result": (method.result_schema)()}),
261 )
262 })
263 .chain(catalog_operations().map(|operation| {
264 (
265 operation.path,
266 json!({"params": catalog_params_schema(operation), "result": crate::result_schema_for_cmd(operation.cmd)}),
267 )
268 }))
269 .collect();
270 let mut bundle = json!({
271 "protocolVersion": PROTOCOL_VERSION,
272 "methods": methods,
273 "types": {
274 "Request": schema::<Request>(), "Response": schema::<Response>(),
275 "ServerError": schema::<ServerError>(), "ErrorData": schema::<ErrorData>(),
276 "ErrorDetail": schema::<crate::ErrorDetail>(), "HelloResult": schema::<HelloResult>(),
277 "ProtocolVersion": schema::<ProtocolVersion>(), "HelloParams": schema::<HelloParams>(),
278 "TransportLimits": schema::<TransportLimits>(), "ErrorCode": schema::<ErrorCode>(),
279 "CdpErrorDetail": schema::<CdpErrorDetail>(),
280 "Action": schema::<crate::Action>(), "ActionOptions": schema::<crate::ActionOptions>(),
281 "ActionReceipt": schema::<crate::ActionReceipt>(), "LocatorSpec": schema::<crate::LocatorSpec>(),
282 "ActionOutcome": schema::<crate::ActionOutcome>(), "DispatchState": schema::<crate::DispatchState>(),
283 "LocatorQuery": schema::<crate::LocatorQuery>(),
284 "Expectation": schema::<crate::Expectation>(), "OperationRecord": schema::<crate::OperationRecord>(),
285 "OperationState": schema::<crate::OperationState>(), "AgentObservation": schema::<crate::AgentObservation>(),
286 "AgentStepResult": schema::<crate::AgentStepResult>(), "BrowserState": schema::<BrowserState>(),
287 "AgentAction": schema::<crate::AgentAction>(), "AgentMode": schema::<crate::AgentMode>(),
288 "ScreenshotFormat": schema::<ScreenshotFormat>(), "ScreenshotClip": schema::<ScreenshotClip>(),
289 "Artifact": schema::<Artifact>(), "ArtifactContainer": schema::<ArtifactContainer>(),
290 "RecordingStartParams": schema::<RecordingStartParams>(), "RecordingIdParams": schema::<RecordingIdParams>(),
291 "RecordingRecord": schema::<RecordingRecord>(), "RecordingState": schema::<RecordingState>(),
292 "RecordingFailure": schema::<RecordingFailure>(), "RecordingFailureStage": schema::<RecordingFailureStage>()
293 }
294 });
295 bundle["catalogMethods"] = catalog_operations()
296 .map(|operation| operation.path)
297 .collect();
298 bundle["types"]["InputMode"] = schema::<crate::InputMode>();
299 bundle["types"]["Destination"] = schema::<crate::Destination>();
300 bundle["types"]["CloudflareAutoSolve"] = schema::<CloudflareAutoSolve>();
301 bundle["types"]["PageBlocker"] = schema::<PageBlocker>();
302 bundle
303}