Skip to content
This repository was archived by the owner on Feb 3, 2025. It is now read-only.

Commit

Permalink
Start fetching auth JWT immediately
Browse files Browse the repository at this point in the history
  • Loading branch information
benthecarman committed Feb 6, 2024
1 parent 66f0474 commit 63e515c
Show file tree
Hide file tree
Showing 4 changed files with 42 additions and 20 deletions.
20 changes: 13 additions & 7 deletions mutiny-core/src/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,17 @@ use crate::{
networking::websocket::{SimpleWebSocket, WebSocketImpl},
utils,
};
use async_lock::RwLock;
use jwt_compact::UntrustedToken;
use lightning::util::logger::*;
use lightning::{log_error, log_info};
use lightning::{log_debug, log_error, log_info};
use lnurl::{lnurl::LnUrl, AsyncClient as LnUrlClient};
use reqwest::Client;
use reqwest::{Method, StatusCode, Url};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::str::FromStr;
use std::sync::{Arc, RwLock};
use std::sync::Arc;

#[derive(Debug, PartialEq, Serialize, Deserialize)]
struct CustomClaims {
Expand Down Expand Up @@ -54,8 +55,9 @@ impl MutinyAuthClient {
Ok(())
}

pub fn is_authenticated(&self) -> Option<String> {
if let Some(ref jwt) = *self.jwt.try_read().unwrap() {
pub async fn is_authenticated(&self) -> Option<String> {
let lock = self.jwt.read().await;
if let Some(jwt) = lock.as_ref() {
return Some(jwt.to_string()); // TODO parse and make sure still valid
}
None
Expand Down Expand Up @@ -92,7 +94,7 @@ impl MutinyAuthClient {
) -> Result<reqwest::Response, MutinyError> {
let mut request = self.http_client.request(method, url);

let mut jwt = self.is_authenticated();
let mut jwt = self.is_authenticated().await;
if jwt.is_none() {
jwt = Some(self.retrieve_new_jwt().await?);
}
Expand All @@ -110,6 +112,10 @@ impl MutinyAuthClient {
}

async fn retrieve_new_jwt(&self) -> Result<String, MutinyError> {
// get lock so we don't make multiple requests for the same token
let mut lock = self.jwt.write().await;
log_debug!(self.logger, "Retrieving new JWT token");

let mut url = Url::parse(&self.url).map_err(|_| MutinyError::LnUrlFailure)?;
let ws_scheme = match url.scheme() {
"http" => "ws",
Expand Down Expand Up @@ -165,7 +171,7 @@ impl MutinyAuthClient {
};

log_info!(self.logger, "Retrieved new JWT token");
*self.jwt.try_write()? = Some(jwt.clone());
*lock = Some(jwt.clone());
Ok(jwt)
}
}
Expand Down Expand Up @@ -201,7 +207,7 @@ mod tests {

// Test authenticate method
match auth_client.authenticate().await {
Ok(_) => assert!(auth_client.is_authenticated().is_some()),
Ok(_) => assert!(auth_client.is_authenticated().await.is_some()),
Err(e) => panic!("Authentication failed with error: {:?}", e),
};

Expand Down
2 changes: 1 addition & 1 deletion mutiny-core/src/test_utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ pub async fn create_vss_client() -> MutinyVssClient {

// Test authenticate method
match auth_client.authenticate().await {
Ok(_) => assert!(auth_client.is_authenticated().is_some()),
Ok(_) => assert!(auth_client.is_authenticated().await.is_some()),
Err(e) => panic!("Authentication failed with error: {:?}", e),
};

Expand Down
31 changes: 20 additions & 11 deletions mutiny-wasm/src/indexed_db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use bip39::Mnemonic;
use futures::lock::Mutex;
use gloo_utils::format::JsValueSerdeExt;
use lightning::util::logger::Logger;
use lightning::{log_debug, log_error};
use lightning::{log_debug, log_error, log_info, log_trace};
use log::error;
use mutiny_core::storage::*;
use mutiny_core::vss::*;
Expand Down Expand Up @@ -260,6 +260,7 @@ impl IndexedDbStorage {
})?
};

let start = instant::Instant::now();
// use a memory storage to handle encryption and decryption
let map = MemoryStorage::new(password, cipher, None);

Expand All @@ -283,33 +284,41 @@ impl IndexedDbStorage {
let json: Value = value.into_serde()?;
map.set(vec![(key, json)])?;
}
log_trace!(
logger,
"Reading browser storage took {}ms",
start.elapsed().as_millis()
);

match vss {
None => {
let final_map = map.memory.read().unwrap();
Ok(final_map.clone())
}
Some(vss) => {
log_debug!(logger, "Reading from vss");
log_trace!(logger, "Reading from vss");
let start = instant::Instant::now();
let keys = vss.list_key_versions(None).await?;
let mut futs = vec![];
let mut futs = Vec::with_capacity(keys.len());
for kv in keys {
futs.push(Self::handle_vss_key(kv, vss, &map, logger));
}
let results = futures::future::join_all(futs).await;
let mut items_vector = Vec::new();
for result in results {
if let Some((key, value)) = result? {
// save to memory and batch the write to local storage
map.set_data(key.clone(), value.clone(), None)?;
items_vector.push((key, value));
}
let results = futures::future::try_join_all(futs).await?;

let mut items_vector = Vec::with_capacity(results.len());
for (key, value) in results.into_iter().flatten() {
// save to memory and batch the write to local storage
map.set_data(key.clone(), value.clone(), None)?;
items_vector.push((key, value));
}
if !items_vector.is_empty() {
// write them so we don't have to pull them down again
Self::save_to_indexed_db(indexed_db, &items_vector).await?;
}
let final_map = map.memory.read().unwrap();

log_trace!(logger, "Reading VSS took {}ms", start.elapsed().as_millis());

Ok(final_map.clone())
}
}
Expand Down
9 changes: 8 additions & 1 deletion mutiny-wasm/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ use mutiny_core::nostr::nip49::NIP49URI;
use mutiny_core::nostr::nwc::{BudgetedSpendingConditions, NwcProfileTag, SpendingConditions};
use mutiny_core::nostr::NostrKeySource;
use mutiny_core::storage::{DeviceLock, MutinyStorage, DEVICE_LOCK_KEY};
use mutiny_core::utils::{now, parse_npub, parse_npub_or_nip05, sleep};
use mutiny_core::utils::{now, parse_npub, parse_npub_or_nip05, sleep, spawn};
use mutiny_core::vss::MutinyVssClient;
use mutiny_core::{encrypt::encryption_key_from_pass, InvoiceHandler, MutinyWalletConfigBuilder};
use mutiny_core::{labels::Contact, MutinyWalletBuilder};
Expand Down Expand Up @@ -215,6 +215,13 @@ impl MutinyWallet {
auth_url,
));

// immediately start fetching JWT
let auth = auth_client.clone();
spawn(async move {
// if this errors, it's okay, we'll call it again when we fetch vss
let _ = auth.authenticate().await;
});

let vss = storage_url.map(|url| {
Arc::new(MutinyVssClient::new_authenticated(
auth_client.clone(),
Expand Down

0 comments on commit 63e515c

Please sign in to comment.