Skip to main content

lb_rs/service/
account.rs

1use crate::experiments::{WelcomeDoc, cohort};
2use crate::io::docs::LocalDocuments;
3use crate::io::server::Server;
4use crate::model::account::{Account, MAX_USERNAME_LENGTH};
5use crate::model::api::{
6    DeleteAccountRequest, GetPublicKeyRequest, GetUsernameRequest, NewAccountRequestV2,
7};
8use crate::model::errors::{LbErrKind, LbResult, core_err_unexpected};
9use crate::model::file_like::FileLike;
10use crate::model::file_metadata::{FileType, Owner};
11use crate::model::meta::Meta;
12use crate::service::events::Actor;
13use crate::{DEFAULT_API_LOCATION, Lb};
14use libsecp256k1::SecretKey;
15use qrcode_generator::QrCodeEcc;
16
17use crate::io::network::ApiError;
18
19/// A short introduction to writing in Markdown: the note one welcome cohort
20/// starts with, and the sample note a client can offer in an empty vault.
21pub const MARKDOWN_WELCOME: &str = include_str!("samples/markdown_welcome.md");
22
23impl<S: Server, D: LocalDocuments> Lb<S, D> {
24    /// CoreError::AccountExists,
25    /// CoreError::UsernameTaken,
26    /// CoreError::UsernameInvalid,
27    /// CoreError::ServerDisabled,
28    /// CoreError::ServerUnreachable,
29    /// CoreError::ClientUpdateRequired,
30    #[instrument(level = "debug", skip(self), err(Debug))]
31    pub async fn create_account(
32        &self, username: &str, api_url: &str, welcome_doc: bool,
33    ) -> LbResult<Account> {
34        self.create_account_with_key(username, api_url, self.entropy.secret_key(), welcome_doc)
35            .await
36    }
37
38    /// [Self::create_account] with the caller's key.
39    #[instrument(level = "debug", skip(self, key), err(Debug))]
40    pub async fn create_account_with_key(
41        &self, username: &str, api_url: &str, key: SecretKey, welcome_doc: bool,
42    ) -> LbResult<Account> {
43        let username = String::from(username).to_lowercase();
44
45        if username.len() > MAX_USERNAME_LENGTH {
46            return Err(LbErrKind::UsernameInvalid.into());
47        }
48
49        let mut tx = self.begin_tx().await;
50        let db = tx.db();
51
52        if db.account.as_ref().is_some() {
53            return Err(LbErrKind::AccountExists.into());
54        }
55
56        let account =
57            Account { username: username.clone(), api_url: api_url.to_string(), private_key: key };
58
59        let root = Meta::create_root(&account, &self.entropy)?.sign_with(&account)?;
60        let root_id = *root.id();
61
62        let last_synced = self
63            .client
64            .new_account_v2(&account, NewAccountRequestV2::new(&account, &root))
65            .await?
66            .last_synced;
67
68        db.account.replace(account.clone())?;
69        db.base_metadata.insert(root_id, root)?;
70        db.last_synced.replace(last_synced as i64)?;
71        db.root.replace(root_id)?;
72        db.pub_key_lookup
73            .insert(Owner(account.public_key()), account.username.clone())?;
74
75        self.keychain.cache_account(account.clone()).await?;
76
77        tx.end();
78
79        if welcome_doc {
80            let cohort: WelcomeDoc = cohort(&account.username);
81            match cohort {
82                WelcomeDoc::NoWelcomeDoc => {}
83                WelcomeDoc::OldWelcomeDoc => {
84                    let welcome_doc = self
85                        .create_file("welcome.md", &root_id, FileType::Document)
86                        .await?;
87                    self.write_document(welcome_doc.id, MARKDOWN_WELCOME.as_bytes())
88                        .await?;
89                    self.sync().await?;
90                }
91                WelcomeDoc::FramgentedArchetypes => {
92                    let samples = self
93                        .create_file("samples", &root_id, FileType::Folder)
94                        .await?;
95
96                    let todo = self
97                        .create_file("todo.md", &samples.id, FileType::Document)
98                        .await?;
99                    self.write_document(todo.id, include_bytes!("samples/todo.md"))
100                        .await?;
101
102                    let journal = self
103                        .create_file("journal.md", &samples.id, FileType::Document)
104                        .await?;
105                    let journal_content = include_str!("samples/journal.md")
106                        .replace("{date}", &chrono::Local::now().format("%y-%m-%d").to_string());
107                    self.write_document(journal.id, journal_content.as_bytes())
108                        .await?;
109
110                    let pdf = self
111                        .create_file("bitcoin.pdf", &samples.id, FileType::Document)
112                        .await?;
113                    self.write_document(pdf.id, include_bytes!("samples/bitcoin.pdf"))
114                        .await?;
115
116                    let drawing = self
117                        .create_file("drawing.svg", &samples.id, FileType::Document)
118                        .await?;
119                    self.write_document(drawing.id, include_bytes!("samples/drawing.svg"))
120                        .await?;
121
122                    let welcome = self
123                        .create_file("welcome.md", &root_id, FileType::Document)
124                        .await?;
125                    self.write_document(welcome.id, include_bytes!("samples/welcome.md"))
126                        .await?;
127
128                    self.sync().await?;
129                }
130                WelcomeDoc::HypeWelcomeDoc => {
131                    let welcome_doc = self
132                        .create_file("welcome.md", &root_id, FileType::Document)
133                        .await?;
134                    self.write_document(welcome_doc.id, include_bytes!("samples/hype_welcome.md"))
135                        .await?;
136                    self.sync().await?;
137                }
138            };
139        }
140
141        self.events.meta_changed(Actor::User(None));
142        self.events.signed_in();
143
144        Ok(account)
145    }
146
147    #[instrument(level = "debug", skip(self, key), err(Debug))]
148    pub async fn import_account(&self, key: &str, api_url: Option<&str>) -> LbResult<Account> {
149        if self.get_account().is_ok() {
150            warn!("tried to import an account, but account exists already.");
151            return Err(LbErrKind::AccountExists.into());
152        }
153
154        let key = key.trim();
155
156        if let Ok(key) = base64::decode(key) {
157            if let Ok(account) = bincode::deserialize(&key[..]) {
158                return self.import_account_private_key_v1(account).await;
159            } else if let Ok(key) = SecretKey::parse_slice(&key) {
160                return self
161                    .import_account_private_key_v2(key, api_url.unwrap_or(DEFAULT_API_LOCATION))
162                    .await;
163            }
164        }
165
166        let phrase: [&str; 24] = key
167            .split([' ', ','])
168            .filter(|maybe_word| !maybe_word.is_empty())
169            .collect::<Vec<_>>()
170            .try_into()
171            .map_err(|_| LbErrKind::AccountStringCorrupted)?;
172
173        self.import_account_phrase(phrase, api_url.unwrap_or(DEFAULT_API_LOCATION))
174            .await
175    }
176
177    pub async fn import_account_private_key_v1(&self, account: Account) -> LbResult<Account> {
178        let server_public_key = self
179            .client
180            .get_public_key(&account, GetPublicKeyRequest { username: account.username.clone() })
181            .await?
182            .key;
183
184        let account_public_key = account.public_key();
185
186        if account_public_key != server_public_key {
187            return Err(LbErrKind::UsernamePublicKeyMismatch.into());
188        }
189
190        let mut tx = self.begin_tx().await;
191        let db = tx.db();
192        db.account.replace(account.clone())?;
193        self.keychain.cache_account(account.clone()).await?;
194
195        Ok(account)
196    }
197
198    pub async fn import_account_private_key_v2(
199        &self, private_key: SecretKey, api_url: &str,
200    ) -> LbResult<Account> {
201        let mut account =
202            Account { username: "".to_string(), api_url: api_url.to_string(), private_key };
203        let public_key = account.public_key();
204
205        account.username = self
206            .client
207            .get_username(&account, GetUsernameRequest { key: public_key })
208            .await?
209            .username;
210
211        let mut tx = self.begin_tx().await;
212        let db = tx.db();
213        db.account.replace(account.clone())?;
214        self.keychain.cache_account(account.clone()).await?;
215
216        Ok(account)
217    }
218
219    pub async fn import_account_phrase(
220        &self, phrase: [&str; 24], api_url: &str,
221    ) -> LbResult<Account> {
222        let private_key = Account::phrase_to_private_key(phrase)?;
223        self.import_account_private_key_v2(private_key, api_url)
224            .await
225    }
226
227    #[instrument(level = "debug", skip(self), err(Debug))]
228    pub fn export_account_private_key(&self) -> LbResult<String> {
229        let account = self.get_account()?;
230        Ok(base64::encode(account.private_key.serialize()))
231    }
232
233    pub fn export_account_phrase(&self) -> LbResult<String> {
234        let account = self.get_account()?;
235        Ok(account.get_phrase()?.join(" "))
236    }
237
238    pub fn export_account_qr(&self) -> LbResult<Vec<u8>> {
239        let acct_secret = self.export_account_private_key()?;
240        qrcode_generator::to_png_to_vec(acct_secret, QrCodeEcc::Low, 1024)
241            .map_err(|err| core_err_unexpected(err).into())
242    }
243
244    #[instrument(level = "debug", skip(self), err(Debug))]
245    pub async fn delete_account(&self) -> LbResult<()> {
246        let account = self.get_account()?;
247
248        self.client
249            .delete_account(account, DeleteAccountRequest {})
250            .await
251            .map_err(|err| match err {
252                ApiError::SendFailed(_) => LbErrKind::ServerUnreachable,
253                ApiError::ClientUpdateRequired => LbErrKind::ClientUpdateRequired,
254                _ => core_err_unexpected(err),
255            })?;
256
257        let mut tx = self.begin_tx().await;
258        let db = tx.db();
259
260        db.account.take()?;
261        db.last_synced.take()?;
262        db.base_metadata.clear()?;
263        db.root.take()?;
264        db.local_metadata.clear()?;
265        db.pub_key_lookup.clear()?;
266
267        // todo: clear cache?
268
269        Ok(())
270    }
271}