Skip to main content

bitwarden_wasm_internal/
client.rs

1extern crate console_error_panic_hook;
2use std::{fmt::Display, sync::Arc};
3
4use bitwarden_core::{ClientSettings, key_management::state_bridge::StateBridgeClient};
5use bitwarden_crypto_sync_handler::CryptoSyncHandlerClient;
6use bitwarden_error::bitwarden_error;
7use bitwarden_managed_settings::ManagedSettingsClient;
8use bitwarden_pm::{PasswordManagerClient as InnerPasswordManagerClient, clients::*};
9use bitwarden_policies::PolicyClient;
10use bitwarden_user_crypto_management::{UserCryptoManagementClient, UserCryptoManagementClientExt};
11use wasm_bindgen::prelude::*;
12
13use crate::platform::{
14    PlatformClient,
15    token_provider::{JsTokenProvider, WasmClientManagedTokens},
16};
17
18#[wasm_bindgen(typescript_custom_section)]
19const TOKEN_CUSTOM_TS_TYPE: &'static str = r#"
20/**
21 * @deprecated Use PasswordManagerClient instead
22 */
23export type BitwardenClient = PasswordManagerClient;
24"#;
25
26/// The main entry point for the Bitwarden SDK in WebAssembly environments
27#[wasm_bindgen]
28pub struct PasswordManagerClient(pub(crate) InnerPasswordManagerClient);
29
30#[wasm_bindgen]
31impl PasswordManagerClient {
32    /// Initialize a new instance of the SDK client
33    ///
34    /// `managed_settings` is the host-owned handle onto the operating system's Unified Endpoint
35    /// Management profile. The client shares its profile, so profiles pushed after construction
36    /// are visible here. Pass a fresh `ManagedSettingsClient` where the host has no UEM source.
37    #[wasm_bindgen(constructor)]
38    pub fn new(
39        token_provider: JsTokenProvider,
40        settings: Option<ClientSettings>,
41        managed_settings: &ManagedSettingsClient,
42    ) -> Self {
43        let tokens = Arc::new(WasmClientManagedTokens::new(token_provider));
44        Self(InnerPasswordManagerClient::new_with_client_tokens(
45            settings,
46            tokens,
47            managed_settings,
48        ))
49    }
50
51    /// Administrator-enforced settings operations.
52    pub fn managed_settings(&self) -> ManagedSettingsClient {
53        self.0.managed_settings()
54    }
55
56    /// Test method, echoes back the input
57    pub fn echo(&self, msg: String) -> String {
58        msg
59    }
60
61    /// Returns the current SDK version
62    pub fn version(&self) -> String {
63        #[cfg(feature = "bitwarden-license")]
64        return format!("COMMERCIAL-{}", env!("SDK_VERSION"));
65        #[cfg(not(feature = "bitwarden-license"))]
66        return env!("SDK_VERSION").to_owned();
67    }
68
69    /// Test method, always throws an error
70    pub fn throw(&self, msg: String) -> Result<(), TestError> {
71        Err(TestError(msg))
72    }
73
74    /// Test method, calls http endpoint
75    pub async fn http_get(&self, url: String) -> Result<String, String> {
76        let client = self.0.0.internal.get_http_client();
77        let res = client.get(&url).send().await.map_err(|e| e.to_string())?;
78
79        res.text().await.map_err(|e| e.to_string())
80    }
81
82    /// Auth related operations.
83    pub fn auth(&self) -> AuthClient {
84        self.0.auth()
85    }
86
87    /// Bitwarden licensed operations.
88    #[cfg(feature = "bitwarden-license")]
89    pub fn commercial(&self) -> bitwarden_pm::CommercialPasswordManagerClient {
90        self.0.commercial()
91    }
92
93    /// Crypto related operations.
94    pub fn crypto(&self) -> CryptoClient {
95        self.0.0.crypto()
96    }
97
98    /// Key management operations that run on every sync.
99    pub fn crypto_sync_handler(&self) -> CryptoSyncHandlerClient {
100        self.0.crypto_sync_handler()
101    }
102
103    /// Key management state bridge operations.
104    pub fn km_state_bridge(&self) -> StateBridgeClient {
105        self.0.0.km_state_bridge()
106    }
107
108    /// User crypto management related operations.
109    pub fn user_crypto_management(&self) -> UserCryptoManagementClient {
110        self.0.0.user_crypto_management()
111    }
112
113    /// Vault item related operations.
114    pub fn vault(&self) -> VaultClient {
115        self.0.vault()
116    }
117
118    /// Collection related operations.
119    ///
120    /// This is registered directly on the top-level client in addition to being nested under
121    /// [`vault`](Self::vault). Once consumers have migrated to this accessor, the nested one will
122    /// be removed.
123    pub fn collections(&self) -> CollectionsClient {
124        self.0.collections()
125    }
126
127    /// Constructs a specific client for platform-specific functionality
128    pub fn platform(&self) -> PlatformClient {
129        PlatformClient::new(self.0.0.clone())
130    }
131
132    /// Constructs a specific client for generating passwords and passphrases
133    pub fn generator(&self) -> GeneratorClient {
134        self.0.generator()
135    }
136
137    /// Exporter related operations.
138    pub fn exporters(&self) -> ExporterClient {
139        self.0.exporters()
140    }
141
142    /// Importer related operations.
143    pub fn importers(&self) -> ImporterClient {
144        self.0.importers()
145    }
146
147    /// Policy related operations.
148    pub fn policies(&self) -> PolicyClient {
149        self.0.policies()
150    }
151
152    /// Send related operations.
153    pub fn sends(&self) -> SendClient {
154        self.0.sends()
155    }
156
157    /// Send sync handler operations.
158    pub fn send_sync_handler(&self) -> SendSyncHandlerClient {
159        self.0.send_sync_handler()
160    }
161
162    /// Organization invite link operations.
163    pub fn invite_link(&self) -> InviteLinkClient {
164        self.0.invite_link()
165    }
166
167    /// Organization member administration operations.
168    pub fn organization_users_management(&self) -> OrganizationUsersManagementClient {
169        self.0.organization_users_management()
170    }
171
172    /// Crypto cipher suite operations.
173    pub fn crypto_cipher_suite(&self) -> CryptoCipherSuiteClient {
174        self.0.crypto_cipher_suite()
175    }
176
177    /// Whether the client is in Gov Mode.
178    pub fn gov_mode(&self) -> bool {
179        self.0.0.gov_mode()
180    }
181}
182
183#[bitwarden_error(basic)]
184pub struct TestError(String);
185
186impl Display for TestError {
187    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
188        write!(f, "{}", self.0)
189    }
190}