Skip to main content

capsule_sdk/cohort/
devices.rs

1//! The devices-grouping view model and the one-tap support bundle.
2//!
3//! Consumes the server's `GET /devices` `{devices, cohorts}` body
4//! into [`DevicesView`] — the session ledger grouped by device cohort so one physical
5//! device's re-enrollments collapse into a single row the UI renders. The copy is
6//! **assert-don't-litigate**: a group is labelled "a device you've used before (last
7//! seen …)" with no "this isn't my device" toggle, because the user cannot adjudicate
8//! an advisory hash. The only dispute path is [`SupportBundle`] — the exact hash and
9//! device/session map, bundled for a support report.
10//!
11//! All copy lives as `locales/` catalog **keys** ([`keys`]); the view model exposes
12//! the key plus the structured data (timestamps), and the platform app resolves the
13//! key through `capsule-i18n`. This module never formats a human string.
14
15use std::collections::BTreeMap;
16
17use serde::{Deserialize, Serialize};
18
19/// Catalog keys for the devices-grouping UI (namespace `device.cohort.*`). Assert,
20/// do not litigate — the copy states recognition, it never asks the user to arbitrate.
21pub mod keys {
22    /// Label for a cohort seen before this session (reinstall / an earlier expired
23    /// session). Takes a formatted `{last_seen}` date the app supplies.
24    pub const LABEL_PREVIOUSLY_USED: &str = "device.cohort.label.previously_used";
25    /// Label for the session currently making the request.
26    pub const LABEL_THIS_DEVICE: &str = "device.cohort.label.this_device";
27    /// Label for a device newly seen on this account.
28    pub const LABEL_NEW_DEVICE: &str = "device.cohort.label.new_device";
29    /// The one-tap support action that emits a [`super::SupportBundle`].
30    pub const SUPPORT_REPORT: &str = "device.cohort.support.report";
31}
32
33// ─── Wire types (GET /devices) ───────────────────────────────────────────────
34
35/// One active session ("device") from the session listing. Mirrors the server's
36/// `Device`; `id` is the session id, `cohort_hash` its advisory
37/// grouping value (absent when the client asserted none).
38#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
39pub struct DeviceEntry {
40    /// The session id.
41    pub id: String,
42    /// Session creation time (Unix seconds).
43    pub created_at: i64,
44    /// Last activity time (Unix seconds).
45    pub last_active_at: i64,
46    /// Reported user agent, if any.
47    #[serde(default)]
48    pub user_agent: Option<String>,
49    /// Reported source IP, if any.
50    #[serde(default)]
51    pub ip_address: Option<String>,
52    /// Whether this is the session making the current request.
53    pub is_current: bool,
54    /// The advisory device-cohort hash asserted at session creation, if any.
55    #[serde(default)]
56    pub cohort_hash: Option<String>,
57    /// The hardware device id asserted at session creation, if any.
58    ///
59    /// Client-asserted and unverified, like [`cohort_hash`](Self::cohort_hash) — it gates
60    /// nothing and is absent from the JWT claims. It exists so a support bundle can report
61    /// the `(device_id, session_id)` pair the authentication doc specifies; `id` above stays
62    /// the session id.
63    #[serde(default)]
64    pub device_id: Option<String>,
65}
66
67/// One entry of the durable cohort map (persists beyond session expiry). Mirrors the
68/// server's `DeviceCohort`.
69#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
70pub struct CohortMapEntry {
71    /// The advisory cohort hash.
72    pub cohort_hash: String,
73    /// First time this cohort was seen for the user (Unix seconds).
74    pub first_seen: i64,
75    /// Most recent time this cohort was seen for the user (Unix seconds).
76    pub last_seen: i64,
77}
78
79/// The `GET /devices` body: active sessions plus the durable cohort map.
80#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
81pub struct SessionListing {
82    /// Active sessions, each annotated with its per-session cohort.
83    pub devices: Vec<DeviceEntry>,
84    /// The durable cohort map.
85    pub cohorts: Vec<CohortMapEntry>,
86}
87
88// ─── View model ──────────────────────────────────────────────────────────────
89
90/// How the UI should recognize a cohort group.
91#[derive(Debug, Clone, Copy, PartialEq, Eq)]
92pub enum Recognition {
93    /// First appearance of this cohort on the account.
94    New,
95    /// Seen before — a reinstall (new `device_id`, same cohort) or an earlier session
96    /// that has since expired. The "previously used" state.
97    PreviouslyUsed,
98}
99
100impl Recognition {
101    /// The `locales/` catalog key for this recognition state.
102    pub fn label_key(self) -> &'static str {
103        match self {
104            Recognition::New => keys::LABEL_NEW_DEVICE,
105            Recognition::PreviouslyUsed => keys::LABEL_PREVIOUSLY_USED,
106        }
107    }
108}
109
110/// One grouped device: every session that shares a cohort hash, collapsed into a
111/// single row with its recognition state and the durable first/last-seen span.
112#[derive(Debug, Clone, PartialEq, Eq)]
113pub struct CohortGroup {
114    /// The shared cohort hash, or `None` for an ungrouped session (the client
115    /// asserted no cohort — it cannot be grouped and stands alone).
116    pub cohort_hash: Option<String>,
117    /// The sessions in this group, oldest first.
118    pub sessions: Vec<DeviceEntry>,
119    /// First time this cohort was seen (durable map, else derived from sessions).
120    pub first_seen: i64,
121    /// Most recent time this cohort was seen (durable map, else derived from sessions).
122    pub last_seen: i64,
123    /// The recognition state driving the group's label.
124    pub recognition: Recognition,
125    /// Whether the current session is in this group ("this device").
126    pub contains_current: bool,
127}
128
129impl CohortGroup {
130    /// The catalog key the UI renders for this group. The current device asserts
131    /// "this device"; otherwise the recognition state decides.
132    pub fn label_key(&self) -> &'static str {
133        if self.contains_current {
134            keys::LABEL_THIS_DEVICE
135        } else {
136            self.recognition.label_key()
137        }
138    }
139
140    /// Build the one-tap support bundle for this group: the exact cohort hash and the
141    /// per-session `(device_id, session_id, first_seen, last_seen)` map, for a support
142    /// report. The dispute path — the client asserts, it does not litigate.
143    pub fn support_bundle(&self) -> SupportBundle {
144        SupportBundle {
145            cohort_hash: self.cohort_hash.clone(),
146            sessions: self
147                .sessions
148                .iter()
149                .map(|d| SupportBundleEntry {
150                    // The listing surfaces only the session id; the hardware
151                    device_id: d.device_id.clone(),
152                    session_id: d.id.clone(),
153                    first_seen: d.created_at,
154                    last_seen: d.last_active_at,
155                })
156                .collect(),
157        }
158    }
159}
160
161/// The devices ledger grouped by cohort — what the devices screen renders.
162#[derive(Debug, Clone, PartialEq, Eq)]
163pub struct DevicesView {
164    /// The cohort groups, current device first, then most-recently-seen first.
165    pub groups: Vec<CohortGroup>,
166}
167
168impl DevicesView {
169    /// Group a `GET /devices` listing into the view model.
170    ///
171    /// Sessions sharing a cohort hash collapse into one group; a session with no
172    /// cohort stands alone (it cannot be grouped). A group is [`Recognition::PreviouslyUsed`]
173    /// when it holds more than one session (a reinstall re-enrolled) **or** the durable
174    /// map's `first_seen` predates its earliest current session (an earlier session has
175    /// since expired) — otherwise it is [`Recognition::New`].
176    pub fn from_listing(listing: &SessionListing) -> Self {
177        let durable: BTreeMap<&str, &CohortMapEntry> = listing
178            .cohorts
179            .iter()
180            .map(|c| (c.cohort_hash.as_str(), c))
181            .collect();
182
183        // Grouped sessions, keyed by hash for deterministic ordering.
184        let mut grouped: BTreeMap<String, Vec<DeviceEntry>> = BTreeMap::new();
185        let mut ungrouped: Vec<DeviceEntry> = Vec::new();
186        for device in &listing.devices {
187            match &device.cohort_hash {
188                Some(hash) => grouped
189                    .entry(hash.clone())
190                    .or_default()
191                    .push(device.clone()),
192                None => ungrouped.push(device.clone()),
193            }
194        }
195
196        let mut groups: Vec<CohortGroup> = Vec::new();
197
198        for (hash, mut sessions) in grouped {
199            sessions.sort_by_key(|d| (d.created_at, d.id.clone()));
200            let earliest_created = sessions.iter().map(|d| d.created_at).min().unwrap_or(0);
201            let contains_current = sessions.iter().any(|d| d.is_current);
202            let durable_entry = durable.get(hash.as_str());
203
204            let (first_seen, last_seen) = match durable_entry {
205                Some(e) => (e.first_seen, e.last_seen),
206                None => (
207                    earliest_created,
208                    sessions.iter().map(|d| d.last_active_at).max().unwrap_or(0),
209                ),
210            };
211
212            let previously_used = sessions.len() > 1
213                || durable_entry.is_some_and(|e| e.first_seen < earliest_created);
214            let recognition = if previously_used {
215                Recognition::PreviouslyUsed
216            } else {
217                Recognition::New
218            };
219
220            groups.push(CohortGroup {
221                cohort_hash: Some(hash),
222                sessions,
223                first_seen,
224                last_seen,
225                recognition,
226                contains_current,
227            });
228        }
229
230        // Each cohort-less session stands alone: New, never grouped.
231        for device in ungrouped {
232            groups.push(CohortGroup {
233                cohort_hash: None,
234                first_seen: device.created_at,
235                last_seen: device.last_active_at,
236                contains_current: device.is_current,
237                recognition: Recognition::New,
238                sessions: vec![device],
239            });
240        }
241
242        // Current device first, then most-recently-seen first; hash breaks ties.
243        groups.sort_by(|a, b| {
244            b.contains_current
245                .cmp(&a.contains_current)
246                .then(b.last_seen.cmp(&a.last_seen))
247                .then(a.cohort_hash.cmp(&b.cohort_hash))
248        });
249
250        Self { groups }
251    }
252
253    /// The group containing the current session, if any.
254    pub fn current(&self) -> Option<&CohortGroup> {
255        self.groups.iter().find(|g| g.contains_current)
256    }
257}
258
259// ─── Support bundle ──────────────────────────────────────────────────────────
260
261/// One session's row in a [`SupportBundle`].
262#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
263pub struct SupportBundleEntry {
264    /// The hardware `device_id` the session was created with, when the client asserted one. `None`
265    /// for a session opened by a client that sent no device id.
266    #[serde(default, skip_serializing_if = "Option::is_none")]
267    pub device_id: Option<String>,
268    /// The session id.
269    pub session_id: String,
270    /// This session's creation time (Unix seconds).
271    pub first_seen: i64,
272    /// This session's last activity time (Unix seconds).
273    pub last_seen: i64,
274}
275
276/// The one-tap dispute payload: the exact advisory cohort hash and the device/session
277/// map for a support report. Serializable and round-trippable so a client can attach
278/// it to a bug report verbatim.
279#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
280pub struct SupportBundle {
281    /// The advisory cohort hash under dispute (`None` for an ungrouped session).
282    #[serde(default, skip_serializing_if = "Option::is_none")]
283    pub cohort_hash: Option<String>,
284    /// The sessions attributed to this cohort.
285    pub sessions: Vec<SupportBundleEntry>,
286}
287
288#[cfg(test)]
289mod tests;