openlogi-hid 0.8.5

HID++ device discovery for OpenLogi, wrapping the hidpp crate over async-hid.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
//! Strict cassette construction from one completed recorded channel.

use std::collections::{BTreeMap, BTreeSet};

use hidpp::channel::RequestOutcome;
use openlogi_fixture::{
    CassetteExchange, FIXTURE_SCHEMA_VERSION, HidCassette, ReportSupport, SyntheticIdentityKind,
    classify_synthetic_identity_bytes,
};
use thiserror::Error;

use super::{RecordedChannel, RecordedChannelOpenOutcome, RecordedRequest, RecordedRequestFact};

mod sanitizer;

use sanitizer::{ProtocolSanitizer, unassociated_rejection};

#[cfg(test)]
mod tests;

/// Human-owned cassette fields that cannot be inferred from transport evidence.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct HidCassetteMetadata {
    /// Human-readable operation name.
    pub name: String,
    /// Logical channel identifier used by the replay topology.
    pub channel: String,
}

/// A class of identity replaced by the protocol-aware sanitizer.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum SanitizedIdentityKind {
    /// Bolt receiver unique ID from long register `0xfb`.
    ReceiverUniqueId,
    /// Unifying receiver serial from long register `0xb5/0x03`.
    ReceiverSerialNumber,
    /// Device unit ID from a receiver slot or HID++ 2.0 DeviceInformation.
    DeviceUnitId,
    /// Device serial from HID++ 2.0 DeviceInformation function `2`.
    DeviceSerialNumber,
}

impl SanitizedIdentityKind {
    const ALL: [Self; 4] = [
        Self::ReceiverUniqueId,
        Self::ReceiverSerialNumber,
        Self::DeviceUnitId,
        Self::DeviceSerialNumber,
    ];

    const fn policy_kind(self) -> SyntheticIdentityKind {
        match self {
            Self::ReceiverUniqueId => SyntheticIdentityKind::BoltReceiverUid,
            Self::ReceiverSerialNumber => SyntheticIdentityKind::UnifyingReceiverSerial,
            Self::DeviceUnitId => SyntheticIdentityKind::DeviceUnitId,
            Self::DeviceSerialNumber => SyntheticIdentityKind::DeviceSerialNumber,
        }
    }
}

/// Preferred canonical identities for relation-preserving cassette sanitization.
///
/// Plans contain only synthetic bytes and are safe to retain in resumable
/// contribution state. The original captured identities are never exposed.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct HidCassetteIdentityPlan {
    replacements: BTreeMap<SanitizedIdentityKind, Vec<u8>>,
}

impl HidCassetteIdentityPlan {
    /// Add the canonical synthetic value to use for the first identity of `kind`.
    pub fn insert(
        &mut self,
        kind: SanitizedIdentityKind,
        synthetic_value: Vec<u8>,
    ) -> Result<(), HidCassetteIdentityPlanError> {
        classify_synthetic_identity_bytes(kind.policy_kind(), &synthetic_value)
            .map_err(|_| HidCassetteIdentityPlanError::InvalidValue { kind })?;
        if self.replacements.contains_key(&kind) {
            return Err(HidCassetteIdentityPlanError::DuplicateKind { kind });
        }
        self.replacements.insert(kind, synthetic_value);
        Ok(())
    }

    pub(super) fn replacement(&self, kind: SanitizedIdentityKind) -> Option<&[u8]> {
        self.replacements.get(&kind).map(Vec::as_slice)
    }
}

/// A preferred cassette identity is malformed or duplicated.
#[derive(Clone, Debug, Error, PartialEq, Eq)]
pub enum HidCassetteIdentityPlanError {
    /// The plan contains two preferred values for one protocol identity kind.
    #[error("identity plan repeats {kind:?}")]
    DuplicateKind {
        /// Repeated identity kind.
        kind: SanitizedIdentityKind,
    },
    /// The preferred bytes do not match the canonical synthetic policy.
    #[error("identity plan contains a noncanonical value for {kind:?}")]
    InvalidValue {
        /// Rejected identity kind.
        kind: SanitizedIdentityKind,
    },
}

/// One relation-preserving synthetic identity and its replacement count.
///
/// The original value is deliberately absent so audit output is safe to show
/// or serialize later. `synthetic_value` is generated sequentially, never by
/// hashing the source identity.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct IdentityReplacement {
    /// Protocol identity field that was replaced.
    pub kind: SanitizedIdentityKind,
    /// Length-preserving synthetic bytes written into the cassette.
    pub synthetic_value: Vec<u8>,
    /// Number of occurrences replaced with this value.
    pub occurrences: usize,
}

/// Privacy audit for a committable cassette candidate.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct HidCassetteAudit {
    /// Distinct relation-preserving identity replacements.
    pub replacements: Vec<IdentityReplacement>,
}

/// Why recorded evidence could not become a committable cassette.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum CassetteRejectionReason {
    /// The channel did not finish opening successfully.
    ChannelNotOpened,
    /// The opened channel exposes a report-width combination schema v1 cannot represent.
    UnsupportedReportSupport,
    /// The channel observer was still live when recording ended.
    IncompleteChannel,
    /// Two request records claimed the same channel request ID.
    DuplicateRequestId,
    /// A response-bearing request did not have exactly one outgoing report.
    OutgoingReportCount {
        /// Number of outgoing reports observed for the request.
        actual: usize,
    },
    /// A response-bearing request did not have exactly one terminal outcome.
    OutcomeCount {
        /// Number of terminal outcomes observed for the request.
        actual: usize,
    },
    /// A successful request did not have exactly one matched incoming report.
    IncomingReportCount {
        /// Number of matched incoming reports observed for the request.
        actual: usize,
    },
    /// The response-bearing request timed out.
    RequestTimedOut,
    /// The native transport rejected the request write.
    RequestWriteFailed,
    /// The request waiter disappeared without receiving a response.
    RequestLostResponse,
    /// The caller cancelled the in-flight request.
    RequestCancelled,
    /// A future request outcome is not classified by this builder.
    UnsupportedRequestOutcome,
    /// A fire-and-forget/raw channel write has no post-write success evidence.
    UnprovenFireAndForget,
    /// An incoming report was not matched to a response-bearing request.
    UnmatchedIncomingReport,
    /// Incoming bytes failed HID++ report parsing.
    MalformedIncomingReport,
    /// A future unassociated observation is not classified by this builder.
    UnsupportedObservation,
    /// A report has invalid or unsupported framing.
    MalformedReport,
    /// Recorded request and response headers do not correlate under their protocol.
    CorrelationMismatch,
    /// A HID++ 2.0 version ping received a HID++ 1.0 error response, which
    /// schema v1 cannot safely rebind to a different software ID.
    UnsupportedCrossVersionPing,
    /// HID++ 1.0 traffic is outside the supported receiver register layouts.
    UnsupportedHidpp10Register,
    /// A HID++ 2.0 runtime feature index was never learned from discovery traffic.
    UnknownFeatureIndex {
        /// Device index carried by the request.
        device_index: u8,
        /// Runtime feature index carried by the request.
        feature_index: u8,
    },
    /// A known feature can carry identity and has no safe sanitizer here.
    UnsupportedIdentityFeature {
        /// HID++ 2.0 feature ID.
        feature_id: u16,
    },
    /// A feature or function is outside the proven read-only classifier.
    UnsupportedHidpp20Function {
        /// HID++ 2.0 feature ID.
        feature_id: u16,
        /// HID++ 2.0 function ID.
        function_id: u8,
    },
    /// Feature discovery assigned one runtime index to conflicting feature IDs.
    AmbiguousFeatureMapping,
    /// An identity field did not satisfy its protocol-defined representation.
    MalformedIdentity,
    /// Sequential synthetic identifiers exhausted their fixed-width field.
    SyntheticIdentitySpaceExhausted,
    /// A preferred synthetic value exactly matched the captured original, so
    /// replacement could not be proven without retaining the original bytes.
    PlannedIdentityMatchesOriginal,
    /// Pairing, discovery-address, or passkey traffic is never retained.
    PairingTraffic,
    /// No complete exchange remained after validation.
    EmptyCassette,
    /// The produced cassette violated its strict schema invariant.
    InvalidCassette {
        /// Validation diagnostic. It contains cassette metadata, never native node data.
        message: String,
    },
}

/// One typed rejection, optionally associated with a channel request ID.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CassetteRejection {
    /// Request ID that supplied the rejected evidence, when one exists.
    pub request_id: Option<u64>,
    /// Privacy, lifecycle, or protocol reason conversion was refused.
    pub reason: CassetteRejectionReason,
}

/// Result of auditing and attempting to build one cassette candidate.
///
/// `cassette` is present only when every piece of evidence was classified and
/// the strict fixture validator accepted the complete result.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct HidCassetteBuildReport {
    /// Validated privacy-safe cassette, or `None` when any rejection occurred.
    pub cassette: Option<HidCassette>,
    /// Relation-preserving replacements made while classifying evidence.
    pub audit: HidCassetteAudit,
    /// Reasons the recording is not committable.
    pub rejections: Vec<CassetteRejection>,
}

impl HidCassetteBuildReport {
    /// Whether the report contains one validated cassette and no rejection.
    #[must_use]
    pub fn is_committable(&self) -> bool {
        self.cassette.is_some() && self.rejections.is_empty()
    }
}

impl RecordedChannel {
    /// Audit and convert this explicitly selected completed channel lifetime.
    ///
    /// Requests are associated only by their recorder-local request IDs. The
    /// resulting exchanges are ordered by those monotonically assigned IDs, so
    /// repeated normalized request keys retain deterministic FIFO responses
    /// without blessing callback scheduling as a global replay order.
    #[must_use]
    pub fn build_hid_cassette(&self, metadata: HidCassetteMetadata) -> HidCassetteBuildReport {
        self.build_hid_cassette_with_identity_plan(metadata, &HidCassetteIdentityPlan::default())
    }

    /// Audit and convert this channel while preferring profile-derived synthetic identities.
    #[must_use]
    pub fn build_hid_cassette_with_identity_plan(
        &self,
        metadata: HidCassetteMetadata,
        identity_plan: &HidCassetteIdentityPlan,
    ) -> HidCassetteBuildReport {
        CassetteBuilder::new(self, metadata, identity_plan).build()
    }
}

struct CassetteBuilder<'a> {
    channel: &'a RecordedChannel,
    metadata: HidCassetteMetadata,
    sanitizer: ProtocolSanitizer,
    rejections: Vec<CassetteRejection>,
}

impl<'a> CassetteBuilder<'a> {
    fn new(
        channel: &'a RecordedChannel,
        metadata: HidCassetteMetadata,
        identity_plan: &HidCassetteIdentityPlan,
    ) -> Self {
        Self {
            channel,
            metadata,
            sanitizer: ProtocolSanitizer::with_identity_plan(identity_plan),
            rejections: Vec::new(),
        }
    }

    fn build(mut self) -> HidCassetteBuildReport {
        let report_support = self.validate_channel();
        self.validate_unassociated();

        let mut requests: Vec<_> = self.channel.requests.iter().collect();
        requests.sort_by_key(|request| request.request_id);
        self.reject_duplicate_request_ids(&requests);

        let mut exchanges = Vec::with_capacity(requests.len());
        for request in requests {
            if let Some(exchange) = self.build_exchange(request) {
                exchanges.push(exchange);
            }
        }

        if exchanges.is_empty() {
            self.reject(None, CassetteRejectionReason::EmptyCassette);
        }

        let cassette = if self.rejections.is_empty() {
            if let Some(report_support) = report_support {
                let cassette = HidCassette {
                    schema_version: FIXTURE_SCHEMA_VERSION,
                    name: self.metadata.name.clone(),
                    channel: self.metadata.channel.clone(),
                    report_support,
                    exchanges,
                };
                match cassette.validate() {
                    Ok(()) => Some(cassette),
                    Err(error) => {
                        self.reject(
                            None,
                            CassetteRejectionReason::InvalidCassette {
                                message: error.to_string(),
                            },
                        );
                        None
                    }
                }
            } else {
                None
            }
        } else {
            None
        };
        let audit = self.sanitizer.finish();

        HidCassetteBuildReport {
            cassette,
            audit,
            rejections: self.rejections,
        }
    }

    fn validate_channel(&mut self) -> Option<ReportSupport> {
        let support = match self.channel.open_outcome {
            RecordedChannelOpenOutcome::Opened {
                supports_short: true,
                supports_long: true,
            } => Some(ReportSupport::ShortAndLong),
            RecordedChannelOpenOutcome::Opened {
                supports_short: false,
                supports_long: true,
            } => Some(ReportSupport::LongOnly),
            RecordedChannelOpenOutcome::Opened { .. } => {
                self.reject(None, CassetteRejectionReason::UnsupportedReportSupport);
                None
            }
            RecordedChannelOpenOutcome::NotHidpp
            | RecordedChannelOpenOutcome::Failed(_)
            | RecordedChannelOpenOutcome::Cancelled => {
                self.reject(None, CassetteRejectionReason::ChannelNotOpened);
                None
            }
        };
        if self.channel.closed_at.is_none() {
            self.reject(None, CassetteRejectionReason::IncompleteChannel);
        }
        support
    }

    fn validate_unassociated(&mut self) {
        for evidence in &self.channel.unassociated {
            self.reject(None, unassociated_rejection(&evidence.observation));
        }
    }

    fn reject_duplicate_request_ids(&mut self, requests: &[&RecordedRequest]) {
        let mut ids = BTreeSet::new();
        for request in requests {
            if !ids.insert(request.request_id) {
                self.reject(
                    Some(request.request_id),
                    CassetteRejectionReason::DuplicateRequestId,
                );
            }
        }
    }

    fn build_exchange(&mut self, request: &RecordedRequest) -> Option<CassetteExchange> {
        let mut outgoing = Vec::new();
        let mut incoming = Vec::new();
        let mut outcomes = Vec::new();
        for fact in &request.facts {
            match fact {
                RecordedRequestFact::OutgoingReport { report, .. } => outgoing.push(report),
                RecordedRequestFact::IncomingReport { report, .. } => incoming.push(report),
                RecordedRequestFact::Outcome { outcome, .. } => outcomes.push(*outcome),
            }
        }

        let mut valid = true;
        if outgoing.len() != 1 {
            self.reject(
                Some(request.request_id),
                CassetteRejectionReason::OutgoingReportCount {
                    actual: outgoing.len(),
                },
            );
            valid = false;
        }
        if outcomes.len() != 1 {
            self.reject(
                Some(request.request_id),
                CassetteRejectionReason::OutcomeCount {
                    actual: outcomes.len(),
                },
            );
            valid = false;
        }
        if !valid {
            return None;
        }

        match outcomes[0] {
            RequestOutcome::Succeeded => {}
            RequestOutcome::TimedOut => {
                self.reject(
                    Some(request.request_id),
                    CassetteRejectionReason::RequestTimedOut,
                );
                return None;
            }
            RequestOutcome::WriteFailed => {
                self.reject(
                    Some(request.request_id),
                    CassetteRejectionReason::RequestWriteFailed,
                );
                return None;
            }
            RequestOutcome::NoResponse => {
                self.reject(
                    Some(request.request_id),
                    CassetteRejectionReason::RequestLostResponse,
                );
                return None;
            }
            RequestOutcome::Cancelled => {
                self.reject(
                    Some(request.request_id),
                    CassetteRejectionReason::RequestCancelled,
                );
                return None;
            }
            _ => {
                self.reject(
                    Some(request.request_id),
                    CassetteRejectionReason::UnsupportedRequestOutcome,
                );
                return None;
            }
        }

        if incoming.len() != 1 {
            self.reject(
                Some(request.request_id),
                CassetteRejectionReason::IncomingReportCount {
                    actual: incoming.len(),
                },
            );
            return None;
        }

        match self
            .sanitizer
            .exchange(outgoing[0].as_bytes(), incoming[0].as_bytes())
        {
            Ok(exchange) => Some(exchange),
            Err(reason) => {
                self.reject(Some(request.request_id), reason);
                None
            }
        }
    }

    fn reject(&mut self, request_id: Option<u64>, reason: CassetteRejectionReason) {
        self.rejections
            .push(CassetteRejection { request_id, reason });
    }
}