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