1use serde::{Deserialize, Serialize};
8use serde_json::Value;
9use std::collections::HashSet;
10
11#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
13#[serde(rename_all = "camelCase")]
14pub struct TargetEvidence {
15 pub platform: String,
17 pub app_id: String,
19 #[serde(skip_serializing_if = "Option::is_none")]
21 pub pid: Option<u32>,
22 #[serde(skip_serializing_if = "Option::is_none")]
24 pub window_id: Option<Value>,
25 #[serde(skip_serializing_if = "Option::is_none")]
27 pub window_title_digest: Option<String>,
28 #[serde(skip_serializing_if = "Option::is_none")]
30 pub display_id: Option<String>,
31 #[serde(skip_serializing_if = "Option::is_none")]
33 pub role: Option<String>,
34 #[serde(skip_serializing_if = "Option::is_none")]
36 pub label_digest: Option<String>,
37 #[serde(skip_serializing_if = "Option::is_none")]
39 pub bounds: Option<Bounds>,
40 pub observation_id: String,
42 #[serde(skip_serializing_if = "Option::is_none")]
44 pub screenshot_hash: Option<String>,
45 #[serde(default, skip_serializing_if = "Option::is_none")]
48 pub device_pixel_ratio: Option<f64>,
49 #[serde(skip_serializing_if = "Option::is_none")]
51 pub ui_tree_revision: Option<String>,
52 pub confidence: f64,
54 pub captured_at: String,
56}
57
58impl TargetEvidence {
59 pub fn check_screen_binding(&self) -> Result<(), String> {
94 let Some(bounds) = &self.bounds else { return Ok(()) };
95 bounds.validate()?;
96 if self.screenshot_hash.is_none() {
97 return Ok(());
98 }
99 let Some(ratio) = self.device_pixel_ratio else {
100 return Err(
101 "target bounds from a screenshot must state the screenshot's devicePixelRatio"
102 .into(),
103 );
104 };
105 if !(ratio.is_finite() && ratio > 0.0) {
106 return Err(format!("devicePixelRatio must be a positive number, not {ratio}"));
107 }
108 if (ratio - bounds.device_pixel_ratio).abs() > f64::EPSILON {
109 return Err(format!(
110 "target bounds are at device pixel ratio {} but the screenshot is at {ratio}",
111 bounds.device_pixel_ratio
112 ));
113 }
114 Ok(())
115 }
116}
117
118#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
120#[serde(rename_all = "snake_case")]
121pub enum CoordinateSpace {
122 #[default]
125 LogicalPoints,
126 ScreenshotPixels,
128}
129
130fn unit_ratio() -> f64 {
131 1.0
132}
133
134#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
151#[serde(rename_all = "camelCase")]
152pub struct Bounds {
153 pub x: f64,
155 pub y: f64,
157 pub width: f64,
159 pub height: f64,
161 #[serde(default)]
163 pub space: CoordinateSpace,
164 #[serde(default = "unit_ratio")]
166 pub device_pixel_ratio: f64,
167}
168
169impl Bounds {
170 pub fn points(x: f64, y: f64, width: f64, height: f64, device_pixel_ratio: f64) -> Self {
172 Self { x, y, width, height, space: CoordinateSpace::LogicalPoints, device_pixel_ratio }
173 }
174
175 pub fn pixels(x: f64, y: f64, width: f64, height: f64, device_pixel_ratio: f64) -> Self {
177 Self { x, y, width, height, space: CoordinateSpace::ScreenshotPixels, device_pixel_ratio }
178 }
179
180 fn ratio(&self) -> f64 {
181 if self.device_pixel_ratio.is_finite() && self.device_pixel_ratio > 0.0 {
182 self.device_pixel_ratio
183 } else {
184 1.0
185 }
186 }
187
188 fn scaled(&self, factor: f64, space: CoordinateSpace) -> Self {
189 Self {
190 x: self.x * factor,
191 y: self.y * factor,
192 width: self.width * factor,
193 height: self.height * factor,
194 space,
195 device_pixel_ratio: self.device_pixel_ratio,
196 }
197 }
198
199 pub fn to_points(&self) -> Self {
201 match self.space {
202 CoordinateSpace::LogicalPoints => self.clone(),
203 CoordinateSpace::ScreenshotPixels => {
204 self.scaled(1.0 / self.ratio(), CoordinateSpace::LogicalPoints)
205 }
206 }
207 }
208
209 pub fn to_pixels(&self) -> Self {
211 match self.space {
212 CoordinateSpace::ScreenshotPixels => self.clone(),
213 CoordinateSpace::LogicalPoints => {
214 self.scaled(self.ratio(), CoordinateSpace::ScreenshotPixels)
215 }
216 }
217 }
218
219 pub fn center(&self) -> [f64; 2] {
221 [self.x + self.width / 2.0, self.y + self.height / 2.0]
222 }
223
224 pub fn contains(&self, point: [f64; 2]) -> bool {
227 point[0] >= self.x
228 && point[1] >= self.y
229 && point[0] < self.x + self.width
230 && point[1] < self.y + self.height
231 }
232
233 fn validate(&self) -> Result<(), String> {
234 let values = [self.x, self.y, self.width, self.height, self.device_pixel_ratio];
235 if values.iter().any(|value| !value.is_finite()) {
236 return Err("target bounds must be finite numbers".into());
237 }
238 if self.width < 0.0 || self.height < 0.0 {
239 return Err("target bounds must not have a negative width or height".into());
240 }
241 if self.device_pixel_ratio <= 0.0 {
242 return Err("target bounds must have a positive devicePixelRatio".into());
243 }
244 Ok(())
245 }
246}
247
248#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
250#[serde(rename_all = "snake_case")]
251pub enum TargetSensitivityAssessment {
252 Sensitive,
254 NonSensitive,
256 Unknown,
258}
259
260#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
262#[serde(rename_all = "snake_case")]
263pub enum TargetSensitivitySource {
264 Accessibility,
266 Unavailable,
268}
269
270#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
272#[serde(rename_all = "snake_case")]
273pub enum TargetSensitivitySignal {
274 SecureRole,
276 SecureSubrole,
278 ProtectedContent,
280 UiaIsPassword,
282 SensitiveLabel,
284 AmbiguousMatch,
286 ElementNotFound,
288 InspectionError,
290 InvalidField,
292 NativeSignalUnavailable,
294}
295
296#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
302#[serde(try_from = "RawTargetSensitivityEvidence", into = "RawTargetSensitivityEvidence")]
303pub struct TargetSensitivityEvidence {
304 assessment: TargetSensitivityAssessment,
305 source: TargetSensitivitySource,
306 signals: Vec<TargetSensitivitySignal>,
307 fields_checked: u32,
308 observed_at: String,
309}
310
311#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
312#[serde(rename_all = "camelCase", deny_unknown_fields)]
313struct RawTargetSensitivityEvidence {
314 assessment: TargetSensitivityAssessment,
315 source: TargetSensitivitySource,
316 signals: Vec<TargetSensitivitySignal>,
317 fields_checked: u32,
318 observed_at: String,
319}
320
321impl TargetSensitivityEvidence {
322 pub fn try_new(
350 assessment: TargetSensitivityAssessment,
351 source: TargetSensitivitySource,
352 signals: Vec<TargetSensitivitySignal>,
353 fields_checked: u32,
354 observed_at: impl Into<String>,
355 ) -> Result<Self, String> {
356 RawTargetSensitivityEvidence {
357 assessment,
358 source,
359 signals,
360 fields_checked,
361 observed_at: observed_at.into(),
362 }
363 .try_into()
364 }
365
366 pub fn assessment(&self) -> TargetSensitivityAssessment {
368 self.assessment
369 }
370
371 pub fn source(&self) -> TargetSensitivitySource {
373 self.source
374 }
375
376 pub fn signals(&self) -> &[TargetSensitivitySignal] {
378 &self.signals
379 }
380
381 pub fn fields_checked(&self) -> u32 {
383 self.fields_checked
384 }
385
386 pub fn observed_at(&self) -> &str {
388 &self.observed_at
389 }
390}
391
392impl TryFrom<RawTargetSensitivityEvidence> for TargetSensitivityEvidence {
393 type Error = String;
394
395 fn try_from(raw: RawTargetSensitivityEvidence) -> Result<Self, Self::Error> {
396 if raw.signals.len() > 10 {
397 return Err("target sensitivity supports at most 10 signals".into());
398 }
399 if raw.signals.iter().copied().collect::<HashSet<_>>().len() != raw.signals.len() {
400 return Err("target sensitivity signals must be unique".into());
401 }
402 if raw.fields_checked > 100 {
403 return Err("target sensitivity supports at most 100 checked fields".into());
404 }
405 if matches!(
406 raw.assessment,
407 TargetSensitivityAssessment::Sensitive | TargetSensitivityAssessment::NonSensitive
408 ) && (raw.source != TargetSensitivitySource::Accessibility || raw.fields_checked == 0)
409 {
410 return Err(
411 "conclusive target sensitivity requires accessibility evidence for a checked field"
412 .into(),
413 );
414 }
415 if raw.assessment == TargetSensitivityAssessment::Sensitive && raw.signals.is_empty() {
416 return Err("sensitive target evidence requires at least one signal".into());
417 }
418 if raw.observed_at.trim().is_empty() {
419 return Err("target sensitivity observedAt must not be empty".into());
420 }
421 Ok(Self {
422 assessment: raw.assessment,
423 source: raw.source,
424 signals: raw.signals,
425 fields_checked: raw.fields_checked,
426 observed_at: raw.observed_at,
427 })
428 }
429}
430
431impl From<TargetSensitivityEvidence> for RawTargetSensitivityEvidence {
432 fn from(value: TargetSensitivityEvidence) -> Self {
433 Self {
434 assessment: value.assessment,
435 source: value.source,
436 signals: value.signals,
437 fields_checked: value.fields_checked,
438 observed_at: value.observed_at,
439 }
440 }
441}
442
443#[cfg(test)]
444mod tests {
445 use super::*;
446
447 fn evidence(bounds: Option<Bounds>, hash: Option<&str>, ratio: Option<f64>) -> TargetEvidence {
448 TargetEvidence {
449 platform: "darwin".into(),
450 app_id: "com.example.form".into(),
451 pid: None,
452 window_id: None,
453 window_title_digest: None,
454 display_id: None,
455 role: None,
456 label_digest: None,
457 bounds,
458 observation_id: "observation-1".into(),
459 screenshot_hash: hash.map(str::to_string),
460 device_pixel_ratio: ratio,
461 ui_tree_revision: None,
462 confidence: 1.0,
463 captured_at: "2026-11-22T10:00:00Z".into(),
464 }
465 }
466
467 #[test]
468 fn screen_binding_requires_a_matching_ratio() {
469 let points = Bounds::points(960.0, 590.0, 90.0, 40.0, 2.0);
470 assert!(evidence(None, None, None).check_screen_binding().is_ok());
471 assert!(evidence(Some(points.clone()), None, None).check_screen_binding().is_ok());
472 assert!(
473 evidence(Some(points.clone()), Some("sha256:1"), Some(2.0))
474 .check_screen_binding()
475 .is_ok()
476 );
477 let missing = evidence(Some(points.clone()), Some("sha256:1"), None);
478 assert!(missing.check_screen_binding().unwrap_err().contains("devicePixelRatio"));
479 let mismatched = evidence(Some(points), Some("sha256:1"), Some(1.0));
480 assert!(mismatched.check_screen_binding().unwrap_err().contains("device pixel ratio 2"));
481 let inverted =
482 evidence(Some(Bounds::points(0.0, 0.0, -1.0, 4.0, 1.0)), Some("sha256:1"), Some(1.0));
483 assert!(inverted.check_screen_binding().is_err());
484 }
485
486 #[test]
487 fn evidence_without_a_ratio_serializes_as_before() {
488 let value = serde_json::to_value(evidence(None, None, None)).unwrap();
489 assert!(value.get("devicePixelRatio").is_none());
490 }
491}