Skip to main content

cosmic_applet_avestruz/handlers/
auth.rs

1// SPDX-License-Identifier: MIT
2
3//! Authentication message handlers for Avestruz.
4//!
5//! Signing in with a key is offline: it is read from the sign-in field, and
6//! a secret key is handed to the system keyring. Signing in with a bunker
7//! address waits on its remote signer, which may wait on a person, and can
8//! be called off meanwhile. A signer that turns it down is shown with the
9//! key it would have to know this client by. Which account is signed in is
10//! remembered in the config by its `npub`.
11
12use cosmic::Application;
13use cosmic::cosmic_config::CosmicConfigEntry;
14use cosmic::iced::clipboard;
15use cosmic::prelude::*;
16
17use crate::config::Config;
18use crate::fl;
19use crate::messages::{Message, SecretInput};
20use crate::nostr::account::{self, Account, Credential, SignError, SignInError};
21use crate::state::{AppModel, BunkerRefusal, LoginProgress, ViewState};
22
23/// Why an event was not signed, in the user's language.
24pub(crate) fn sign_error_text(error: SignError) -> String {
25    match error {
26        SignError::Keyring(error) => fl!("error-keyring", error = error),
27        SignError::Remote(error) => fl!("error-remote-signer", error = error),
28        SignError::Cipher(error) => fl!("error-cipher", error = error),
29    }
30}
31
32impl AppModel {
33    /// Write the whole config to COSMIC's config store, logging (not
34    /// failing) if that doesn't work. `what` names the change, for the log.
35    pub(crate) fn save_config(&self, what: &str) {
36        if let Ok(config_context) = cosmic::cosmic_config::Config::new(Self::APP_ID, Config::VERSION)
37            && let Err(e) = self.config.write_entry(&config_context)
38        {
39            tracing::error!("Failed to save {what} config: {e}");
40        }
41    }
42
43    /// Empty the sign-in field and forget its error. The field may hold a
44    /// secret key, so it is not left lying around once it has served. A
45    /// sign-in still waiting on a remote signer is called off: whoever left
46    /// the sign-in view is not to be signed in a minute later.
47    pub(crate) fn clear_login(&mut self) {
48        self.login_input.clear();
49        self.login_input_hidden = true;
50        self.login_error = None;
51        self.login_refusal = None;
52        self.signer.cancel_sign_in();
53        self.login_progress = LoginProgress::Idle;
54    }
55
56    /// The user edited the sign-in field.
57    pub fn handle_login_input_changed(&mut self, input: SecretInput) {
58        self.login_input = input.0;
59        self.login_error = None;
60        // The key shown is the one for the signer that was in the field.
61        self.login_refusal = None;
62    }
63
64    /// Sign in with what is in the sign-in field.
65    pub fn handle_submit_login(&mut self) -> Task<cosmic::Action<Message>> {
66        if self.login_progress != LoginProgress::Idle {
67            return Task::none();
68        }
69        match account::parse_credential(&self.login_input) {
70            Ok(credential) => {
71                self.login_error = None;
72                self.login_refusal = None;
73                self.login_progress = match credential {
74                    Credential::Bunker(_) => LoginProgress::Connecting,
75                    Credential::Secret(_) | Credential::Public(_) => LoginProgress::Storing,
76                };
77                let signer = self.signer.clone();
78                Task::perform(async move { signer.sign_in(credential).await }, |result| {
79                    cosmic::Action::App(Message::LoginComplete(result))
80                })
81            }
82            Err(error) => {
83                self.login_error = Some(error);
84                Task::none()
85            }
86        }
87    }
88
89    /// `account` is the one in use from now on: who it follows, which
90    /// fills its feed, is found out.
91    fn enter_account(&mut self, account: Account) -> Task<cosmic::Action<Message>> {
92        self.reset_following();
93        self.reset_engagement();
94        self.reset_bookmarks();
95        self.reset_relays();
96        self.reset_media();
97        self.reset_kept_drafts();
98        self.reset_notifications();
99        self.account = Some(account);
100        self.load_account()
101    }
102
103    /// Signing in finished. On success the account is remembered and its
104    /// feed shows; if the keyring refused, or the remote signer did, nobody
105    /// is signed in.
106    pub fn handle_login_complete(&mut self, result: Result<Account, SignInError>) -> Task<cosmic::Action<Message>> {
107        self.login_progress = LoginProgress::Idle;
108        match result {
109            Ok(account) => {
110                tracing::info!(
111                    "signed in as {} ({})",
112                    account.npub(),
113                    if account.can_sign { "full access" } else { "read-only" }
114                );
115                self.config.account = Some(account.npub());
116                self.save_config("account");
117                self.clear_login();
118                self.view_state = ViewState::Feed;
119                self.enter_account(account)
120            }
121            // Called off: what was typed is still in the field.
122            Err(SignInError::Cancelled) => Task::none(),
123            Err(SignInError::Keyring(e)) => {
124                tracing::error!("sign-in failed at the keyring: {e}");
125                self.error_message = Some(fl!("error-keyring", error = e));
126                Task::none()
127            }
128            // Shown in the sign-in view, with the key to authorize at the
129            // signer: what was typed is still in the field, to try again.
130            Err(SignInError::Bunker { reason, client, with_secret }) => {
131                tracing::error!("sign-in failed at the remote signer: {reason}");
132                self.login_refusal = Some(BunkerRefusal { reason, client, with_secret, copied: false });
133                Task::none()
134            }
135        }
136    }
137
138    /// Copy the key the signer that turned the sign-in down would have to
139    /// know this client by.
140    pub fn handle_copy_client_key(&mut self) -> Task<cosmic::Action<Message>> {
141        let Some(refusal) = &mut self.login_refusal else {
142            return Task::none();
143        };
144        let Some(client) = refusal.client else {
145            return Task::none();
146        };
147        refusal.copied = true;
148        clipboard::write(client.to_hex())
149    }
150
151    /// The account named in the config was looked up at startup.
152    pub fn handle_account_restored(&mut self, result: Result<Account, String>) -> Task<cosmic::Action<Message>> {
153        match result {
154            Ok(account) => {
155                tracing::info!("account {} ({})", account.npub(), if account.can_sign { "full access" } else { "read-only" });
156                self.enter_account(account)
157            }
158            Err(e) => {
159                // The config names something that isn't an npub. Nobody is
160                // signed in; say so by asking again.
161                tracing::error!("the saved account could not be read: {e}");
162                self.config.account = None;
163                self.save_config("account");
164                self.view_state = ViewState::Login;
165                Task::none()
166            }
167        }
168    }
169
170    /// Sign the account out: forget it, take what it signs with out of the
171    /// keyring, and let go of its remote signer.
172    pub fn handle_sign_out(&mut self) -> Task<cosmic::Action<Message>> {
173        self.config.account = None;
174        self.save_config("account");
175        self.clear_login();
176        self.view_state = ViewState::Login;
177        // Nobody's follows are anybody's now, and nothing stays open over
178        // the feed. What was being written stays a draft: it is the text
179        // of whoever sits here, not the key's.
180        let kept = self.keep_draft();
181        self.composer = None;
182        self.zap = None;
183        self.pages.clear();
184        self.videos.stop();
185        self.reset_following();
186        self.reset_engagement();
187        self.reset_bookmarks();
188        self.reset_relays();
189        self.reset_media();
190        self.reset_kept_drafts();
191        self.reset_notifications();
192        let account = self.account.take();
193        let signed_out = match account {
194            Some(account) => {
195                tracing::info!("signed out of {}", account.npub());
196                let (signer, service) = (self.signer.clone(), self.nostr.clone());
197                let leaving = async move {
198                    // The relays its relay list named were its own, and
199                    // are nobody's now.
200                    if let Some(service) = service {
201                        service.use_relays_of(None).await;
202                    }
203                    signer.sign_out(account.public_key).await
204                };
205                Task::perform(leaving, |result| cosmic::Action::App(Message::SignedOut(result)))
206            }
207            None => Task::none(),
208        };
209        Task::batch([kept, signed_out])
210    }
211
212    /// The secret key left the keyring, or the keyring refused. A key that
213    /// is still there is worth knowing about.
214    pub fn handle_signed_out(&mut self, result: Result<(), String>) {
215        if let Err(e) = result {
216            tracing::error!("the secret key could not be removed from the keyring: {e}");
217            self.error_message = Some(fl!("error-keyring", error = e));
218        }
219    }
220}