bitwarden_vault/
totp_client.rs

1use bitwarden_core::Client;
2use chrono::{DateTime, Utc};
3#[cfg(feature = "wasm")]
4use wasm_bindgen::prelude::*;
5
6use crate::{generate_totp, generate_totp_cipher_view, CipherListView, TotpError, TotpResponse};
7
8#[allow(missing_docs)]
9#[cfg_attr(feature = "wasm", wasm_bindgen)]
10pub struct TotpClient {
11    pub(crate) client: Client,
12}
13
14#[cfg(feature = "wasm")]
15#[wasm_bindgen]
16impl TotpClient {
17    /// Generates a TOTP code from a provided key
18    ///
19    /// # Arguments
20    /// - `key` - Can be:
21    ///     - A base32 encoded string
22    ///     - OTP Auth URI
23    ///     - Steam URI
24    /// - `time_ms` - Optional timestamp in milliseconds
25    #[wasm_bindgen(js_name = "generate_totp")]
26    pub fn generate_totp_wasm(
27        &self,
28        key: String,
29        time_ms: Option<f64>,
30    ) -> Result<TotpResponse, TotpError> {
31        let datetime = time_ms.and_then(|time| DateTime::<Utc>::from_timestamp_millis(time as i64));
32
33        self.generate_totp(key, datetime)
34    }
35}
36
37impl TotpClient {
38    /// Generate a TOTP code from a provided key.
39    ///
40    /// Key can be either:
41    /// - A base32 encoded string
42    /// - OTP Auth URI
43    /// - Steam URI
44    pub fn generate_totp(
45        &self,
46        key: String,
47        time: Option<DateTime<Utc>>,
48    ) -> Result<TotpResponse, TotpError> {
49        generate_totp(key, time)
50    }
51
52    /// Generate a TOTP code from a provided cipher list view.
53    pub fn generate_totp_cipher_view(
54        &self,
55        view: CipherListView,
56        time: Option<DateTime<Utc>>,
57    ) -> Result<TotpResponse, TotpError> {
58        let key_store = self.client.internal.get_key_store();
59
60        generate_totp_cipher_view(&mut key_store.context(), view, time)
61    }
62}