//! Device identity ("chip"), pairing by setup code, and sync. use reqwest::Method; use secrecy::{ExposeSecret, SecretString}; use serde::Deserialize; use super::Client; use super::Identity; use super::http::{Body, Idempotency, SentryCall}; use crate::error::{Error, Result, Service}; use crate::models::{CloneCode, SyncState}; const CHIP: &[&str] = &["chip"]; const CHIP_QUERY: &[(&str, &str)] = &[("client", "dewey")]; const CLONE_CODE: &[&str] = &["chip", "clone", "code"]; const SYNC: &[&str] = &["chip", "sync"]; /// `POST /chip` answer. #[derive(Deserialize)] struct ChipResponse { identity: String, chip: String, } impl Client { /// Obtains a new anonymous device identity (`POST /chip`, no bearer) and /// makes it current. The previous identity, if any, is replaced. /// /// # Errors /// /// Transport, status and decode errors. pub async fn chip(&self) -> Result { let reply = self.sentry_raw(chip_call(), None, "chip").await?; let fresh: ChipResponse = reply.json(Service::Sentry, "chip")?; let identity = Identity::new(fresh.identity, fresh.chip); self.publish_identity(identity.clone()); Ok(identity) } /// Refreshes the identity token (`POST /chip` with the bearer) and /// publishes the new one. /// /// # Errors /// /// [`Error::Unlinked`] when there is no identity, the server rejects it, /// or the refresh comes back with a different chip id (the server's way /// of saying the link is gone; the stored identity is left untouched so /// the caller can decide what to do with it). pub async fn refresh(&self) -> Result { let _single_flight = self.inner.refresh.lock().await; let current = self.identity().ok_or(Error::Unlinked)?; self.refresh_locked(¤t).await } /// The refresh itself; the caller holds the refresh lock. pub(super) async fn refresh_locked(&self, current: &Identity) -> Result { let fresh = self.post_chip(current).await?; if fresh.chip != current.chip() { tracing::warn!("identity refresh returned a different chip; the device was unlinked"); return Err(Error::Unlinked); } let identity = Identity::new(fresh.identity, fresh.chip); self.publish_identity(identity.clone()); Ok(identity) } /// Renews the current device for an explicitly requested reader session. /// The account gate serializes and paces this just like every other /// account request. The server must keep the same device id. pub(super) async fn renew_reader_identity(&self) -> Result<()> { let _single_flight = self.inner.refresh.lock().await; let current = self.identity().ok_or(Error::Unlinked)?; let language = reader_renewal_header(current.token().expose_secret())?; let prefix = current .chip() .split('-') .next() .filter(|s| !s.is_empty()) .ok_or_else(|| Error::InvalidInput("reader device id is empty".into()))?; let query = [("c", "d:22.2.1"), ("s", "0"), ("v", prefix)]; let call = SentryCall { method: Method::POST, query: &query, accept_language: Some(language), ..SentryCall::get(CHIP) }; let reply = self .sentry_raw(call, Some(current.token()), "reader device renewal") .await?; let fresh: ChipResponse = reply.json(Service::Sentry, "reader device renewal")?; if fresh.chip != current.chip() { return Err(Error::Unlinked); } self.publish_identity(Identity::new(fresh.identity, fresh.chip)); Ok(()) } async fn post_chip(&self, current: &Identity) -> Result { let reply = self .sentry_raw(chip_call(), Some(current.token()), "refresh") .await?; reply.json(Service::Sentry, "refresh") } /// Fetches a setup code to show the user (`GET /chip/clone/code`). They /// enter it on a signed-in Libby; poll [`Client::sync`] (no more often /// than every 2 s) until it reports linked, and fetch a new code when /// this one is about to expire. Creates an anonymous identity first when /// there is none. /// /// # Errors /// /// Transport, status and decode errors. pub async fn clone_code(&self) -> Result { if self.identity().is_none() { self.chip().await?; } let reply = self .sentry(SentryCall::get(CLONE_CODE), "setup code") .await?; reply.json(Service::Sentry, "setup code") } /// Pairs this device by entering a setup code shown on a signed-in Libby /// (`POST /chip/clone/code`), then refreshes the identity (accepting the /// new chip the clone produces) and syncs. /// /// Whitespace in `code` is ignored, so `"1234 5678"` works. Creates an /// anonymous identity first when there is none. /// /// # Errors /// /// [`Error::InvalidInput`] unless the code is eight digits; /// [`Error::Refused`] when the server rejects the code; /// [`Error::Unlinked`] when the code was accepted but the account still /// has no card. pub async fn redeem_code(&self, code: &str) -> Result { let code: String = code.chars().filter(|c| !c.is_whitespace()).collect(); if code.len() != 8 || !code.bytes().all(|b| b.is_ascii_digit()) { return Err(Error::InvalidInput( "a setup code is eight digits".to_owned(), )); } if self.identity().is_none() { self.chip().await?; } let call = SentryCall { method: Method::POST, body: Body::Form(vec![("code", code)]), idempotency: Idempotency::NotIdempotent, ..SentryCall::get(CLONE_CODE) }; self.sentry(call, "setup code").await?; { let _single_flight = self.inner.refresh.lock().await; let current = self.identity().ok_or(Error::Unlinked)?; let fresh = self.post_chip(¤t).await?; self.publish_identity(Identity::new(fresh.identity, fresh.chip)); } let state = self.sync().await?; if state.is_linked() { Ok(state) } else { Err(Error::Unlinked) } } /// Everything on the account (`GET /chip/sync`): cards, loans, holds. /// /// # Errors /// /// [`Error::Unlinked`] when the identity is dead; transport, status and /// decode errors. pub async fn sync(&self) -> Result { let reply = self.sentry(SentryCall::get(SYNC), "sync").await?; reply.json(Service::Sentry, "sync") } } /// Computes the reader device's renewal value without exposing the identity. fn reader_renewal_header(identity: &str) -> Result { let letters: String = identity .chars() .rev() .filter(|c| c.is_ascii_lowercase()) .skip(4) .take(2) .collect(); if letters.len() != 2 { return Err(Error::InvalidInput( "reader device identity is invalid".into(), )); } Ok(SecretString::from(letters)) } fn chip_call() -> SentryCall<'static> { SentryCall { method: Method::POST, query: CHIP_QUERY, // Minting or refreshing a chip has no effect worth protecting from a // repeat: the newest answer simply wins. idempotency: Idempotency::Idempotent, ..SentryCall::get(CHIP) } }