Skip to main content

bitwarden_shared_unlock/wasm/
peer.rs

1use bitwarden_core::UserId;
2use bitwarden_threading::cancellation_token::wasm::{AbortController, AbortControllerExt};
3use wasm_bindgen::prelude::wasm_bindgen;
4
5use super::drivers::{JsSharedUnlockDriver, RawJsSharedUnlockDriver};
6use crate::{DeviceEvent, PeerStartError, SharedUnlockClient, SharedUnlockPeer as Peer};
7
8/// Shared-unlock peer for WASM clients.
9#[wasm_bindgen]
10pub struct SharedUnlockPeer {
11    peer: Peer<JsSharedUnlockDriver>,
12}
13
14#[wasm_bindgen]
15impl SharedUnlockPeer {
16    /// Creates a new shared-unlock peer
17    #[wasm_bindgen(constructor)]
18    pub fn new(
19        ipc_client: &bitwarden_ipc::wasm::JsIpcClient,
20        driver: RawJsSharedUnlockDriver,
21    ) -> Self {
22        let driver = JsSharedUnlockDriver::new(driver);
23        let peer = Peer::create(driver, ipc_client.client.clone());
24        Self { peer }
25    }
26
27    /// Sets which clients this peer shares one user's unlock state with. Defaults to none.
28    #[wasm_bindgen]
29    pub fn set_destinations(&self, user_id: UserId, destinations: Vec<SharedUnlockClient>) {
30        self.peer.set_destinations(user_id, destinations);
31    }
32
33    /// Starts the shared-unlock peer
34    #[wasm_bindgen]
35    pub async fn start(
36        &self,
37        abort_controller: Option<AbortController>,
38    ) -> Result<(), PeerStartError> {
39        self.peer
40            .start(abort_controller.map(|abort| abort.to_cancellation_token()))
41            .await
42    }
43
44    /// Forwards a device event to the shared-unlock peer state machine.
45    #[wasm_bindgen]
46    pub async fn handle_device_event(&self, event: DeviceEvent) {
47        if let Err(error) = self.peer.handle_device_event(event).await {
48            tracing::error!(?error, "Failed to handle shared unlock device event");
49        }
50    }
51}