use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::HashSet;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TargetEvidence {
pub platform: String,
pub app_id: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub pid: Option<u32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub window_id: Option<Value>,
#[serde(skip_serializing_if = "Option::is_none")]
pub window_title_digest: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub display_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub role: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub label_digest: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub bounds: Option<Bounds>,
pub observation_id: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub screenshot_hash: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub device_pixel_ratio: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub ui_tree_revision: Option<String>,
pub confidence: f64,
pub captured_at: String,
}
impl TargetEvidence {
pub fn check_screen_binding(&self) -> Result<(), String> {
let Some(bounds) = &self.bounds else { return Ok(()) };
bounds.validate()?;
if self.screenshot_hash.is_none() {
return Ok(());
}
let Some(ratio) = self.device_pixel_ratio else {
return Err(
"target bounds from a screenshot must state the screenshot's devicePixelRatio"
.into(),
);
};
if !(ratio.is_finite() && ratio > 0.0) {
return Err(format!("devicePixelRatio must be a positive number, not {ratio}"));
}
if (ratio - bounds.device_pixel_ratio).abs() > f64::EPSILON {
return Err(format!(
"target bounds are at device pixel ratio {} but the screenshot is at {ratio}",
bounds.device_pixel_ratio
));
}
Ok(())
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CoordinateSpace {
#[default]
LogicalPoints,
ScreenshotPixels,
}
fn unit_ratio() -> f64 {
1.0
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Bounds {
pub x: f64,
pub y: f64,
pub width: f64,
pub height: f64,
#[serde(default)]
pub space: CoordinateSpace,
#[serde(default = "unit_ratio")]
pub device_pixel_ratio: f64,
}
impl Bounds {
pub fn points(x: f64, y: f64, width: f64, height: f64, device_pixel_ratio: f64) -> Self {
Self { x, y, width, height, space: CoordinateSpace::LogicalPoints, device_pixel_ratio }
}
pub fn pixels(x: f64, y: f64, width: f64, height: f64, device_pixel_ratio: f64) -> Self {
Self { x, y, width, height, space: CoordinateSpace::ScreenshotPixels, device_pixel_ratio }
}
fn ratio(&self) -> f64 {
if self.device_pixel_ratio.is_finite() && self.device_pixel_ratio > 0.0 {
self.device_pixel_ratio
} else {
1.0
}
}
fn scaled(&self, factor: f64, space: CoordinateSpace) -> Self {
Self {
x: self.x * factor,
y: self.y * factor,
width: self.width * factor,
height: self.height * factor,
space,
device_pixel_ratio: self.device_pixel_ratio,
}
}
pub fn to_points(&self) -> Self {
match self.space {
CoordinateSpace::LogicalPoints => self.clone(),
CoordinateSpace::ScreenshotPixels => {
self.scaled(1.0 / self.ratio(), CoordinateSpace::LogicalPoints)
}
}
}
pub fn to_pixels(&self) -> Self {
match self.space {
CoordinateSpace::ScreenshotPixels => self.clone(),
CoordinateSpace::LogicalPoints => {
self.scaled(self.ratio(), CoordinateSpace::ScreenshotPixels)
}
}
}
pub fn center(&self) -> [f64; 2] {
[self.x + self.width / 2.0, self.y + self.height / 2.0]
}
pub fn contains(&self, point: [f64; 2]) -> bool {
point[0] >= self.x
&& point[1] >= self.y
&& point[0] < self.x + self.width
&& point[1] < self.y + self.height
}
fn validate(&self) -> Result<(), String> {
let values = [self.x, self.y, self.width, self.height, self.device_pixel_ratio];
if values.iter().any(|value| !value.is_finite()) {
return Err("target bounds must be finite numbers".into());
}
if self.width < 0.0 || self.height < 0.0 {
return Err("target bounds must not have a negative width or height".into());
}
if self.device_pixel_ratio <= 0.0 {
return Err("target bounds must have a positive devicePixelRatio".into());
}
Ok(())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TargetSensitivityAssessment {
Sensitive,
NonSensitive,
Unknown,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TargetSensitivitySource {
Accessibility,
Unavailable,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TargetSensitivitySignal {
SecureRole,
SecureSubrole,
ProtectedContent,
UiaIsPassword,
SensitiveLabel,
AmbiguousMatch,
ElementNotFound,
InspectionError,
InvalidField,
NativeSignalUnavailable,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(try_from = "RawTargetSensitivityEvidence", into = "RawTargetSensitivityEvidence")]
pub struct TargetSensitivityEvidence {
assessment: TargetSensitivityAssessment,
source: TargetSensitivitySource,
signals: Vec<TargetSensitivitySignal>,
fields_checked: u32,
observed_at: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct RawTargetSensitivityEvidence {
assessment: TargetSensitivityAssessment,
source: TargetSensitivitySource,
signals: Vec<TargetSensitivitySignal>,
fields_checked: u32,
observed_at: String,
}
impl TargetSensitivityEvidence {
pub fn try_new(
assessment: TargetSensitivityAssessment,
source: TargetSensitivitySource,
signals: Vec<TargetSensitivitySignal>,
fields_checked: u32,
observed_at: impl Into<String>,
) -> Result<Self, String> {
RawTargetSensitivityEvidence {
assessment,
source,
signals,
fields_checked,
observed_at: observed_at.into(),
}
.try_into()
}
pub fn assessment(&self) -> TargetSensitivityAssessment {
self.assessment
}
pub fn source(&self) -> TargetSensitivitySource {
self.source
}
pub fn signals(&self) -> &[TargetSensitivitySignal] {
&self.signals
}
pub fn fields_checked(&self) -> u32 {
self.fields_checked
}
pub fn observed_at(&self) -> &str {
&self.observed_at
}
}
impl TryFrom<RawTargetSensitivityEvidence> for TargetSensitivityEvidence {
type Error = String;
fn try_from(raw: RawTargetSensitivityEvidence) -> Result<Self, Self::Error> {
if raw.signals.len() > 10 {
return Err("target sensitivity supports at most 10 signals".into());
}
if raw.signals.iter().copied().collect::<HashSet<_>>().len() != raw.signals.len() {
return Err("target sensitivity signals must be unique".into());
}
if raw.fields_checked > 100 {
return Err("target sensitivity supports at most 100 checked fields".into());
}
if matches!(
raw.assessment,
TargetSensitivityAssessment::Sensitive | TargetSensitivityAssessment::NonSensitive
) && (raw.source != TargetSensitivitySource::Accessibility || raw.fields_checked == 0)
{
return Err(
"conclusive target sensitivity requires accessibility evidence for a checked field"
.into(),
);
}
if raw.assessment == TargetSensitivityAssessment::Sensitive && raw.signals.is_empty() {
return Err("sensitive target evidence requires at least one signal".into());
}
if raw.observed_at.trim().is_empty() {
return Err("target sensitivity observedAt must not be empty".into());
}
Ok(Self {
assessment: raw.assessment,
source: raw.source,
signals: raw.signals,
fields_checked: raw.fields_checked,
observed_at: raw.observed_at,
})
}
}
impl From<TargetSensitivityEvidence> for RawTargetSensitivityEvidence {
fn from(value: TargetSensitivityEvidence) -> Self {
Self {
assessment: value.assessment,
source: value.source,
signals: value.signals,
fields_checked: value.fields_checked,
observed_at: value.observed_at,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn evidence(bounds: Option<Bounds>, hash: Option<&str>, ratio: Option<f64>) -> TargetEvidence {
TargetEvidence {
platform: "darwin".into(),
app_id: "com.example.form".into(),
pid: None,
window_id: None,
window_title_digest: None,
display_id: None,
role: None,
label_digest: None,
bounds,
observation_id: "observation-1".into(),
screenshot_hash: hash.map(str::to_string),
device_pixel_ratio: ratio,
ui_tree_revision: None,
confidence: 1.0,
captured_at: "2026-11-22T10:00:00Z".into(),
}
}
#[test]
fn screen_binding_requires_a_matching_ratio() {
let points = Bounds::points(960.0, 590.0, 90.0, 40.0, 2.0);
assert!(evidence(None, None, None).check_screen_binding().is_ok());
assert!(evidence(Some(points.clone()), None, None).check_screen_binding().is_ok());
assert!(
evidence(Some(points.clone()), Some("sha256:1"), Some(2.0))
.check_screen_binding()
.is_ok()
);
let missing = evidence(Some(points.clone()), Some("sha256:1"), None);
assert!(missing.check_screen_binding().unwrap_err().contains("devicePixelRatio"));
let mismatched = evidence(Some(points), Some("sha256:1"), Some(1.0));
assert!(mismatched.check_screen_binding().unwrap_err().contains("device pixel ratio 2"));
let inverted =
evidence(Some(Bounds::points(0.0, 0.0, -1.0, 4.0, 1.0)), Some("sha256:1"), Some(1.0));
assert!(inverted.check_screen_binding().is_err());
}
#[test]
fn evidence_without_a_ratio_serializes_as_before() {
let value = serde_json::to_value(evidence(None, None, None)).unwrap();
assert!(value.get("devicePixelRatio").is_none());
}
}