hy 0.18.1

HCLI - Hex-Rays CLI Utility
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
//! Central authentication service (singleton).

use std::sync::{Mutex, OnceLock};
use std::time::Duration;

use crate::auth::credentials::{CredentialType, Credentials, CredentialsConfig};
use crate::auth::oauth::OAuthServer;
use crate::config::{ConfigStore, Env};
use crate::error::{Error, Result};

const CONFIG_KEY: &str = "credentials";

/// Global auth service instance.
static AUTH: OnceLock<Mutex<AuthService>> = OnceLock::new();

/// Manages credentials, login flows, and token retrieval.
#[derive(Debug)]
pub struct AuthService {
    config: CredentialsConfig,
    current: Option<String>, // name of current credential
    forced: Option<String>,  // from --auth-credentials
    initialised: bool,
}

impl AuthService {
    // ── singleton ───────────────────────────────────────────────────────

    /// Get a locked reference to the global service.
    pub fn global() -> std::sync::MutexGuard<'static, Self> {
        AUTH.get_or_init(|| Mutex::new(Self::new()))
            .lock()
            .expect("auth service lock poisoned")
    }

    fn new() -> Self {
        Self {
            config: CredentialsConfig::default(),
            current: None,
            forced: None,
            initialised: false,
        }
    }

    // ── initialisation ──────────────────────────────────────────────────

    /// Load persisted credentials from the config store.
    pub fn init(&mut self, forced_credentials: Option<&str>) {
        if self.initialised {
            return;
        }
        self.forced = forced_credentials.map(String::from);
        self.load_config();
        self.resolve_current();
        self.initialised = true;
    }

    fn load_config(&mut self) {
        let store = ConfigStore::global();
        if let Some(val) = store.get_value(CONFIG_KEY)
            && let Ok(cfg) = serde_json::from_value::<CredentialsConfig>(val.clone()) {
                self.config = cfg;
            }
    }

    fn save_config(&self) {
        let mut store = ConfigStore::global();
        if let Ok(val) = serde_json::to_value(&self.config) {
            store.set_value(CONFIG_KEY, val);
        }
    }

    fn resolve_current(&mut self) {
        let env = Env::global();

        // Environment API key always wins.
        if env.api_key.is_some() {
            self.current = None;
            return;
        }

        if let Some(ref forced) = self.forced
            && self.config.credentials.contains_key(forced) {
                self.current = Some(forced.clone());
                return;
            }

        self.current = self.config.default.clone();
    }

    // ── queries ─────────────────────────────────────────────────────────

    pub fn is_logged_in(&self) -> bool {
        Env::global().api_key.is_some() || self.current_credentials().is_some()
    }

    pub fn current_credentials(&self) -> Option<&Credentials> {
        self.current
            .as_deref()
            .and_then(|name| self.config.credentials.get(name))
    }

    pub fn list_credentials(&self) -> Vec<&Credentials> {
        self.config.credentials.values().collect()
    }

    pub fn default_name(&self) -> Option<&str> {
        self.config.default.as_deref()
    }

    /// Determine the auth type in use.
    pub fn auth_type(&self) -> (CredentialType, &'static str) {
        if Env::global().api_key.is_some() {
            return (CredentialType::Key, "env");
        }
        match self.current_credentials() {
            Some(c) => {
                let origin = if self.forced.is_some() {
                    "forced"
                } else {
                    "default"
                };
                (c.cred_type, origin)
            }
            None => (CredentialType::Interactive, "none"),
        }
    }

    /// Get the API key to use for requests.
    pub fn api_key(&self) -> Option<String> {
        if let Some(ref key) = Env::global().api_key {
            return Some(key.clone());
        }
        self.current_credentials()
            .filter(|c| c.cred_type == CredentialType::Key)
            .and_then(|c| c.token.clone())
    }

    /// Get the bearer token for interactive sessions.
    ///
    /// If the stored token is expired, tries to refresh it via the Supabase
    /// session stored in `"supabase.auth.token"`.
    pub fn access_token(&mut self) -> Option<String> {
        let cred = self.current_credentials()?;
        if cred.cred_type != CredentialType::Interactive {
            return None;
        }

        // Try the stored token first — if it's not expired, use it directly.
        if let Some(ref tok) = cred.token
            && !crate::auth::session::is_token_expired_pub(tok) {
                return Some(tok.clone());
            }

        // Token missing or expired — try refreshing from the Supabase session.
        match crate::auth::session::ensure_fresh_token() {
            Ok((fresh_token, email)) => {
                // Update the credential in-memory and on disk.
                let name = self.current.clone()?;
                if let Some(c) = self.config.credentials.get_mut(&name) {
                    c.token = Some(fresh_token.clone());
                    if !email.is_empty() {
                        c.email = email;
                    }
                    c.touch();
                }
                self.save_config();
                Some(fresh_token)
            }
            Err(_) => {
                // Refresh failed — return whatever we have (may be expired).
                self.current_credentials().and_then(|c| c.token.clone())
            }
        }
    }

    /// Get user email for the current credential.
    pub fn user_email(&self) -> Option<&str> {
        if Env::global().api_key.is_some() {
            return Some("api-key-user");
        }
        self.current_credentials().map(|c| c.email.as_str())
    }

    // ── mutations ───────────────────────────────────────────────────────

    #[allow(dead_code)]
    pub fn add_credentials(&mut self, cred: Credentials) {
        self.config.add(cred);
        self.save_config();
    }

    pub fn remove_credentials(&mut self, name: &str) -> bool {
        let removed = self.config.remove(name);
        if removed {
            if self.current.as_deref() == Some(name) {
                self.resolve_current();
            }
            self.save_config();
        }
        removed
    }

    pub fn set_default(&mut self, name: &str) -> bool {
        let ok = self.config.set_default(name);
        if ok {
            self.current = Some(name.to_owned());
            self.save_config();
        }
        ok
    }

    /// Create or update interactive credentials after a successful OAuth flow.
    pub fn upsert_interactive(
        &mut self,
        email: &str,
        token: &str,
        name: Option<&str>,
    ) -> Credentials {
        // Check for existing interactive credential with same email.
        if let Some(existing) = self
            .config
            .find_by_email_and_type(email, CredentialType::Interactive)
            .cloned()
        {
            let cred = self.config.credentials.get_mut(&existing.name).unwrap();
            cred.token = Some(token.to_owned());
            cred.touch();
            let result = cred.clone();
            self.current = Some(result.name.clone());
            self.config.set_default(&result.name);
            self.save_config();
            return result;
        }

        let base_name = name.unwrap_or(email);
        let unique = self.config.unique_name(base_name);
        let cred = Credentials::new(&unique, CredentialType::Interactive, token, email);
        self.config.add(cred.clone());
        self.current = Some(unique.clone());
        self.config.set_default(&unique);
        self.save_config();
        cred
    }

    /// Add an API key credential (validates it by calling whoami).
    pub fn add_api_key_credential(&mut self, name: &str, token: &str, email: &str) -> Credentials {
        let _ = self.config.remove(name);
        let cred = Credentials::new(name, CredentialType::Key, token, email);
        self.config.add(cred.clone());
        self.save_config();
        cred
    }

    /// Logout: remove the named credential or just clear the current session.
    pub fn logout_current(&mut self) {
        if let Some(name) = self.current.take() {
            // For interactive credentials we clear the session but keep the
            // credential entry.  The Python version calls supabase sign_out;
            // in the Rust rewrite we simply clear the token.
            if let Some(c) = self.config.credentials.get_mut(&name)
                && c.cred_type == CredentialType::Interactive {
                    c.token = None;
                }
            self.save_config();
        }
    }

    // ── OAuth login flow ────────────────────────────────────────────────

    /// Perform an interactive OAuth login.  Returns the newly created credential
    /// on success.
    pub fn login_interactive_blocking(&mut self, name: Option<&str>) -> Result<Credentials> {
        let env = Env::global();

        // Build the OAuth URL via the Supabase auth endpoint.
        let oauth_url = format!(
            "{}/auth/v1/authorize?provider=google&redirect_to={}",
            env.supabase_url,
            env.oauth_redirect_url(),
        );

        eprintln!("Open this URL in your browser to continue login:\n  {oauth_url}");
        let _ = open::that(&oauth_url);

        // Start local server and wait for token.
        let server = OAuthServer::new(env.oauth_server_port());
        let tokens = server.run(Duration::from_secs(120))?;

        match tokens {
            Some(t) => {
                // Decode the JWT to extract the user's email.
                let email = crate::auth::session::email_from_jwt(&t.access_token)
                    .unwrap_or_else(|| "unknown".into());

                // Store the full Supabase session (with refresh token) so that
                // future runs can refresh the access token without re-login.
                if let Some(ref refresh) = t.refresh_token {
                    let session = crate::auth::session::SupabaseSession {
                        access_token: t.access_token.clone(),
                        refresh_token: refresh.clone(),
                        expires_in: 3600,
                        expires_at: chrono::Utc::now().timestamp() + 3600,
                        token_type: "bearer".into(),
                        provider_token: None,
                        provider_refresh_token: None,
                        user: None,
                    };
                    crate::auth::session::save_session_pub(&session);
                }

                let cred = self.upsert_interactive(&email, &t.access_token, name);
                Ok(cred)
            }
            None => Err(Error::OAuthFailed("Login timeout or cancelled".into())),
        }
    }

    // ── Email OTP login flow ──────────────────────────────────────────────

    /// Send an OTP code to the given email address.
    pub fn send_otp(&self, email: &str) -> Result<()> {
        let env = Env::global();
        let url = format!("{}/auth/v1/otp", env.supabase_url);

        let client = reqwest::blocking::Client::builder()
            .timeout(std::time::Duration::from_secs(15))
            .build()?;

        let resp = client
            .post(&url)
            .header("Content-Type", "application/json")
            .header("apiKey", &env.supabase_anon_key)
            .header(
                "Authorization",
                format!("Bearer {}", env.supabase_anon_key),
            )
            .json(&serde_json::json!({ "email": email }))
            .send()?;

        let status = resp.status();
        if !status.is_success() {
            let body = resp.text().unwrap_or_default();
            return Err(Error::Authentication(format!(
                "Failed to send OTP ({status}): {body}"
            )));
        }
        Ok(())
    }

    /// Verify an OTP code and create credentials on success.
    /// Returns the created/updated credential, or an error.
    pub fn verify_otp(
        &mut self,
        email: &str,
        otp: &str,
        name: Option<&str>,
    ) -> Result<Credentials> {
        let env = Env::global();
        let url = format!("{}/auth/v1/verify", env.supabase_url);

        let client = reqwest::blocking::Client::builder()
            .timeout(std::time::Duration::from_secs(15))
            .build()?;

        let resp = client
            .post(&url)
            .header("Content-Type", "application/json")
            .header("apiKey", &env.supabase_anon_key)
            .header(
                "Authorization",
                format!("Bearer {}", env.supabase_anon_key),
            )
            .json(&serde_json::json!({
                "email": email,
                "token": otp,
                "type": "email"
            }))
            .send()?;

        let status = resp.status();
        if !status.is_success() {
            let body = resp.text().unwrap_or_default();
            return Err(Error::Authentication(format!(
                "OTP verification failed ({status}): {body}"
            )));
        }

        let session: crate::auth::session::SupabaseSession = resp.json().map_err(|e| {
            Error::Authentication(format!("Failed to parse OTP response: {e}"))
        })?;

        // Save the full Supabase session for future token refresh.
        crate::auth::session::save_session_pub(&session);

        // Create or update interactive credentials.
        let cred = self.upsert_interactive(email, &session.access_token, name);

        // Persist the last-used email for convenience.
        {
            let mut store = ConfigStore::global();
            store.set_str("login.email", email);
        }

        Ok(cred)
    }

    /// Show current login status to the console.
    pub fn show_login_info(&self) {
        use console::style;

        if !self.is_logged_in() {
            eprintln!("You are not logged in.");
            return;
        }

        let env = Env::global();
        if env.api_key.is_some() {
            let email = self.user_email().unwrap_or("unknown");
            eprintln!(
                "You are logged in as {} using an API key from HCLI_API_KEY environment variable",
                style(email).green()
            );
            return;
        }

        if let Some(cred) = self.current_credentials() {
            if self.config.credentials.len() <= 1 {
                eprintln!("You are logged in as {}", style(&cred.email).green());
            } else {
                let kind = match cred.cred_type {
                    CredentialType::Key => format!("API key '{}'", cred.name),
                    CredentialType::Interactive => {
                        format!("interactive login '{}'", cred.name)
                    }
                };
                let suffix = if self.forced.is_some() {
                    " (forced via --auth-credentials)"
                } else if self.default_name() == Some(cred.name.as_str()) {
                    " (default)"
                } else {
                    ""
                };
                eprintln!(
                    "You are logged in as {} using {kind}{suffix}",
                    style(cred.label()).green()
                );
            }
        }
    }
}