grokbot_api 1.2.0

Unofficial async client for the (undocumented) Grok Bot gateway API
Documentation
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
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
//! Read and decrypt the Grok Bot **desktop app's** saved gateway session.
//!
//! Enabled by the `desktop-session` feature. Nothing here runs unless you call it; only
//! read the desktop session when the user explicitly asks you to.
//!
//! Mirrors grok-bot-cli's `src/core/app-session.js`. The app stores
//! `gateway-descriptor.json` in its data dir; the payload is encrypted with the Chromium
//! "Safe Storage" (OSCrypt) scheme:
//! - **Linux v11**: key from the Secret Service password (`secret-tool`), PBKDF2-HMAC-SHA1,
//!   salt `saltysalt`, 1 iteration, 16-byte AES-128-CBC key, IV = 16 spaces.
//! - **Linux v10**: keyring-less "basic text" backend, password `peanuts`, otherwise as v11.
//! - **macOS v10**: key from the login Keychain item `Grok Bot Safe Storage`, 1003 iterations.
//! - **Windows v10** (compiled in only on Windows): AES-256-GCM with a DPAPI-wrapped key
//!   from `Local State`.
//!
//! If `gateway-descriptor.json` is missing, [`DesktopConfig::load_credential`] falls back to
//! the Cursor access token in `sand-secrets.json` (exchange it with
//! [`ensure_sandbox`](crate::ensure_sandbox)). [`detect_app_version`] reads the installed
//! app's version for the `x-cursor-client-version` header. See the `DESKTOP.md` guide.
//!
//! ```no_run
//! use grokbot_api::desktop::{DesktopConfig, DesktopCredential, Platform};
//! use grokbot_api::{Client, ClientOptions, Policy};
//!
//! # async fn demo() -> grokbot_api::Result<()> {
//! let platform = Platform::current().expect("supported OS");
//! let cfg = DesktopConfig::new(platform);
//! let client = match cfg.load_credential(None, &Policy::default())? {
//!     DesktopCredential::Session(session) => Client::new(session, ClientOptions::default())?,
//!     DesktopCredential::CursorToken(token) => {
//!         Client::connect_cursor(&token, ClientOptions::default()).await?
//!     }
//! };
//! # let _ = client; Ok(()) }
//! ```
use crate::error::Error;
use crate::policy::Policy;
use crate::types::{Session, normalize_headers};
use serde_json::Value;
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};

const PEANUTS: &str = "peanuts";

/// The OS whose desktop-app layout and encryption scheme to use.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Platform {
    /// `~/.config/Grok Bot` (or `$XDG_CONFIG_HOME`), Secret Service / basic-text keys.
    Linux,
    /// `~/Library/Application Support/Grok Bot`, login Keychain.
    Macos,
    /// `%APPDATA%\Grok Bot`, DPAPI + AES-256-GCM.
    Windows,
}

impl Platform {
    /// The platform this program is running on, or `None` on other OSes.
    pub fn current() -> Option<Platform> {
        match std::env::consts::OS {
            "linux" => Some(Platform::Linux),
            "macos" => Some(Platform::Macos),
            "windows" => Some(Platform::Windows),
            _ => None,
        }
    }
}

fn desktop_err(code: &str, msg: impl Into<String>) -> Error {
    Error::Desktop {
        code: code.into(),
        message: msg.into(),
    }
}

/// The app data directory ("Grok Bot") for a platform.
pub fn app_data_dir(
    home: &Path,
    platform: Platform,
    env: &dyn Fn(&str) -> Option<String>,
) -> PathBuf {
    match platform {
        Platform::Windows => {
            let appdata = env("APPDATA")
                .filter(|s| !s.is_empty())
                .map(PathBuf::from)
                .unwrap_or_else(|| home.join("AppData/Roaming"));
            appdata.join("Grok Bot")
        }
        Platform::Linux => {
            let config = env("XDG_CONFIG_HOME")
                .filter(|s| !s.is_empty())
                .map(PathBuf::from)
                .unwrap_or_else(|| home.join(".config"));
            config.join("Grok Bot")
        }
        Platform::Macos => home.join("Library/Application Support/Grok Bot"),
    }
}

/// Path to `gateway-descriptor.json`.
pub fn descriptor_path(
    home: &Path,
    platform: Platform,
    env: &dyn Fn(&str) -> Option<String>,
) -> PathBuf {
    app_data_dir(home, platform, env).join("gateway-descriptor.json")
}

/// Path to `sand-secrets.json` (the fallback source of a Cursor access token).
pub fn sand_secrets_path(
    home: &Path,
    platform: Platform,
    env: &dyn Fn(&str) -> Option<String>,
) -> PathBuf {
    app_data_dir(home, platform, env).join("sand-secrets.json")
}

/// One saved entry's ciphertext (base64). `key` is `"default"` for the v1 single-entry format.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DesktopEntry {
    /// The entry name (`"default"` for v1 descriptors).
    pub key: String,
    /// The encrypted payload, base64.
    pub encrypted: String,
}

/// What [`DesktopConfig::load_credential`] resolved to. `Debug` redacts the secrets.
pub enum DesktopCredential {
    /// A ready gateway session, decrypted from `gateway-descriptor.json`.
    Session(Session),
    /// A Cursor access token from `sand-secrets.json`, to exchange via EnsureSandBox.
    CursorToken(String),
}

impl std::fmt::Debug for DesktopCredential {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            DesktopCredential::Session(s) => f.debug_tuple("Session").field(s).finish(),
            DesktopCredential::CursorToken(_) => {
                f.debug_tuple("CursorToken").field(&"<redacted>").finish()
            }
        }
    }
}

type SandAccountsRaw = (String, Vec<(String, serde_json::Map<String, Value>)>);

/// A Cursor account found in `sand-secrets.json`, labeled for selection.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SandAccount {
    /// The opaque account id used as the stored entry key.
    pub key: String,
    /// A display label, `"<n>) <first 8 key characters>…"`. Nothing is decrypted to build it.
    pub label: String,
    /// Whether this is the app's active account.
    pub active: bool,
}

/// Parse a descriptor's JSON into the list of encrypted entries (v1 → one, v2 → many).
pub fn parse_entries(descriptor_json: &str) -> Result<Vec<DesktopEntry>, Error> {
    let w: Value = serde_json::from_str(descriptor_json).map_err(|e| {
        desktop_err(
            "INVALID_DESCRIPTOR",
            format!("gateway-descriptor.json is not valid JSON: {e}"),
        )
    })?;
    if let Some(v) = w.get("version").and_then(Value::as_i64)
        && v != 1
        && v != 2
    {
        return Err(desktop_err(
            "UNSUPPORTED_VERSION",
            format!("Unsupported Grok Bot gateway descriptor version {v}."),
        ));
    }
    let enc = |v: &Value| v.as_str().filter(|s| !s.is_empty()).map(str::to_string);
    if w.get("version").and_then(Value::as_i64) == Some(2) {
        let obj = w.get("entries").and_then(Value::as_object);
        let mut out = vec![];
        if let Some(obj) = obj {
            for (k, v) in obj {
                if let Some(e) = enc(v.get("encrypted").unwrap_or(&Value::Null)) {
                    out.push(DesktopEntry {
                        key: k.clone(),
                        encrypted: e,
                    });
                }
            }
        }
        if out.is_empty() {
            return Err(desktop_err(
                "EMPTY_ENTRIES",
                "Grok Bot gateway descriptor has no saved gateway entries. Sign in from the desktop app first.",
            ));
        }
        out.sort_by(|a, b| a.key.cmp(&b.key));
        Ok(out)
    } else {
        match enc(w.get("encrypted").unwrap_or(&Value::Null)) {
            Some(e) => Ok(vec![DesktopEntry {
                key: "default".into(),
                encrypted: e,
            }]),
            None => Err(desktop_err(
                "MISSING_ENCRYPTED_PAYLOAD",
                "Grok Bot gateway descriptor is missing an encrypted payload.",
            )),
        }
    }
}

fn b64(s: &str) -> Result<Vec<u8>, Error> {
    use base64::Engine;
    base64::engine::general_purpose::STANDARD
        .decode(s.trim())
        .map_err(|e| {
            desktop_err(
                "INVALID_PAYLOAD",
                format!("payload is not valid base64: {e}"),
            )
        })
}

fn prefix3(bytes: &[u8]) -> String {
    String::from_utf8_lossy(&bytes[..bytes.len().min(3)]).into_owned()
}

fn safe_storage_key(password: &str, platform: Platform) -> [u8; 16] {
    use hmac::Hmac;
    use sha1::Sha1;
    let iterations: u32 = if platform == Platform::Linux { 1 } else { 1003 };
    let mut key = [0u8; 16];
    pbkdf2::pbkdf2::<Hmac<Sha1>>(password.as_bytes(), b"saltysalt", iterations, &mut key)
        .expect("HMAC accepts any key length");
    key
}

/// Does this ciphertext need the OS keychain password? (Linux v10 "basic text" does not.)
pub fn needs_keychain(encrypted_b64: &str, platform: Platform) -> Result<bool, Error> {
    let bytes = b64(encrypted_b64)?;
    let p = prefix3(&bytes);
    Ok(!(platform == Platform::Linux && p == "v10"))
}

/// Decrypt a Safe Storage string (Linux/macOS). `password` is the keychain password; it is
/// ignored for the Linux v10 basic-text backend (which uses `peanuts`).
pub fn decrypt_safe_storage(
    encrypted_b64: &str,
    password: Option<&str>,
    platform: Platform,
) -> Result<String, Error> {
    use aes::Aes128;
    use cbc::Decryptor;
    use cbc::cipher::{BlockModeDecrypt, KeyIvInit, block_padding::Pkcs7};

    let encrypted = b64(encrypted_b64)?;
    let prefix = prefix3(&encrypted);
    let linux_basic = platform == Platform::Linux && prefix == "v10";
    let supported = prefix == "v10" || (platform == Platform::Linux && prefix == "v11");
    if !supported {
        return Err(desktop_err(
            "UNSUPPORTED_FORMAT",
            format!("Unsupported Grok Bot Safe Storage format (prefix {prefix:?})."),
        ));
    }
    let pw = if linux_basic {
        PEANUTS.to_string()
    } else {
        password
            .ok_or_else(|| {
                desktop_err("NO_KEYCHAIN_PASSWORD", "No OS keychain password available.")
            })?
            .to_string()
    };
    let key = safe_storage_key(&pw, platform);
    let iv = [0x20u8; 16];
    let mut buf = encrypted[3..].to_vec();
    let out = Decryptor::<Aes128>::new(&key.into(), &iv.into())
        .decrypt_padded::<Pkcs7>(&mut buf)
        .map_err(|_| {
            desktop_err(
                "DECRYPT_FAILED",
                "Could not decrypt the desktop session (wrong keychain password or corrupt data).",
            )
        })?;
    String::from_utf8(out.to_vec()).map_err(|_| {
        desktop_err(
            "DECRYPT_FAILED",
            "Decrypted desktop session was not valid UTF-8.",
        )
    })
}

/// Decrypt a Windows Safe Storage string: `v10` + 12-byte nonce + AES-256-GCM + 16-byte tag.
/// `key` is the DPAPI-unwrapped Local State key.
#[cfg(any(target_os = "windows", test))]
pub fn decrypt_windows(encrypted_b64: &str, key: &[u8]) -> Result<String, Error> {
    use aes_gcm::aead::{Aead, KeyInit, Payload};
    use aes_gcm::{Aes256Gcm, Nonce};
    let encrypted = b64(encrypted_b64)?;
    if prefix3(&encrypted) != "v10" || encrypted.len() < 15 + 16 {
        return Err(desktop_err(
            "UNSUPPORTED_FORMAT",
            "Unsupported Grok Bot Safe Storage format.",
        ));
    }
    let cipher = Aes256Gcm::new_from_slice(key)
        .map_err(|_| desktop_err("DECRYPT_FAILED", "Bad Safe Storage key length."))?;
    let nonce = Nonce::try_from(&encrypted[3..15])
        .map_err(|_| desktop_err("DECRYPT_FAILED", "Bad Safe Storage nonce."))?;
    let out = cipher
        .decrypt(
            &nonce,
            Payload {
                msg: &encrypted[15..],
                aad: b"",
            },
        )
        .map_err(|_| desktop_err("DECRYPT_FAILED", "Could not decrypt the desktop session."))?;
    String::from_utf8(out).map_err(|_| {
        desktop_err(
            "DECRYPT_FAILED",
            "Decrypted desktop session was not valid UTF-8.",
        )
    })
}

/// Turn a decrypted inner descriptor (`{baseUrl, token, headers?}`) into a validated [`Session`].
pub fn session_from_clear(clear: &str, policy: &Policy) -> Result<Session, Error> {
    let d: Value = serde_json::from_str(clear).map_err(|_| {
        desktop_err(
            "INCOMPLETE_DESCRIPTOR",
            "Decrypted desktop session is not valid JSON.",
        )
    })?;
    let base = d
        .get("baseUrl")
        .and_then(Value::as_str)
        .filter(|s| !s.is_empty());
    let token = d
        .get("token")
        .and_then(Value::as_str)
        .filter(|s| !s.is_empty());
    let (Some(base), Some(token)) = (base, token) else {
        return Err(desktop_err(
            "INCOMPLETE_DESCRIPTOR",
            "Decrypted Grok Bot gateway descriptor is incomplete (no baseUrl/token).",
        ));
    };
    let gateway_url = policy.check_gateway(base).map_err(Error::Policy)?;
    let mut headers = BTreeMap::new();
    if let Some(Value::Object(m)) = d.get("headers") {
        headers = normalize_headers(
            m.iter()
                .filter(|(_, v)| v.is_string())
                .map(|(k, v)| (k.clone(), v.as_str().unwrap().to_string())),
        );
    }
    Ok(Session {
        gateway_url,
        gateway_token: token.to_string(),
        headers,
    })
}

/// Environment-variable lookup (injectable for tests).
pub type EnvLookup = Box<dyn Fn(&str) -> Option<String> + Send + Sync>;

/// How to locate and unlock the desktop session. Every field can be overridden (tests do).
///
/// `Debug` omits the environment lookup and redacts the keychain password.
pub struct DesktopConfig {
    /// Which layout and encryption scheme to use.
    pub platform: Platform,
    /// The user's home directory (default `$HOME`).
    pub home: PathBuf,
    /// Env lookup (defaults to `std::env::var`).
    pub env: EnvLookup,
    /// Supply the OS keychain password instead of running `secret-tool` / `security`.
    pub os_password: Option<String>,
    /// Program that prints the keychain password, instead of `secret-tool` (Linux) or
    /// `/usr/bin/security` (macOS). It gets the same arguments those tools would.
    pub keychain_program: Option<PathBuf>,
}

impl std::fmt::Debug for DesktopConfig {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("DesktopConfig")
            .field("platform", &self.platform)
            .field("home", &self.home)
            .field(
                "os_password",
                &self.os_password.as_ref().map(|_| "<redacted>"),
            )
            .field("keychain_program", &self.keychain_program)
            .finish_non_exhaustive()
    }
}

impl DesktopConfig {
    /// The real locations for `platform`: `$HOME`, the process environment and the OS keychain.
    pub fn new(platform: Platform) -> Self {
        Self {
            platform,
            home: dirs_home(),
            env: Box::new(|k| std::env::var(k).ok()),
            os_password: None,
            keychain_program: None,
        }
    }

    /// Path to `gateway-descriptor.json` for this config.
    pub fn descriptor_path(&self) -> PathBuf {
        descriptor_path(&self.home, self.platform, &self.env)
    }

    /// Whether `gateway-descriptor.json` exists.
    pub fn present(&self) -> bool {
        self.descriptor_path().exists()
    }

    /// The saved entries, or a clear error if the app/session is missing.
    pub fn entries(&self) -> Result<Vec<DesktopEntry>, Error> {
        let path = self.descriptor_path();
        if !path.exists() {
            let dir = app_data_dir(&self.home, self.platform, &self.env);
            return Err(if dir.exists() {
                desktop_err(
                    "NOT_SIGNED_IN",
                    format!(
                        "The Grok Bot desktop app is installed but has no saved gateway session ({}). Sign in from the desktop app first.",
                        path.display()
                    ),
                )
            } else {
                desktop_err(
                    "APP_NOT_FOUND",
                    format!(
                        "The Grok Bot desktop app data was not found at {}.",
                        dir.display()
                    ),
                )
            });
        }
        let json = std::fs::read_to_string(&path).map_err(|e| {
            desktop_err(
                "READ_FAILED",
                format!("Could not read {}: {e}", path.display()),
            )
        })?;
        parse_entries(&json)
    }

    /// Resolve one entry (by key, or the only one) to a validated [`Session`].
    pub fn load_entry(&self, key: Option<&str>, policy: &Policy) -> Result<Session, Error> {
        let entries = self.entries()?;
        let entry = match key {
            Some(k) => entries.iter().find(|e| e.key == k).ok_or_else(|| {
                desktop_err(
                    "NO_SUCH_ENTRY",
                    format!("No desktop session entry named '{k}'."),
                )
            })?,
            None if entries.len() == 1 => &entries[0],
            None => {
                let names = entries
                    .iter()
                    .map(|e| e.key.clone())
                    .collect::<Vec<_>>()
                    .join(", ");
                return Err(desktop_err(
                    "AMBIGUOUS_ENTRIES",
                    format!(
                        "The desktop app has several saved sessions ({names}). Specify which one to load by its entry name."
                    ),
                ));
            }
        };
        let clear = self.decrypt(&entry.encrypted)?;
        session_from_clear(&clear, policy)
    }

    /// Path to `sand-secrets.json` in the app data dir.
    pub fn sand_secrets_path(&self) -> PathBuf {
        sand_secrets_path(&self.home, self.platform, &self.env)
    }

    /// Whether the `sand-secrets.json` fallback exists.
    pub fn sand_present(&self) -> bool {
        self.sand_secrets_path().exists()
    }

    /// The decrypted `(active_key, [(account_key, fields)])` from `sand-secrets.json`.
    /// The field values stay encrypted here; only the outer structure is parsed.
    fn read_sand_accounts(&self) -> Result<SandAccountsRaw, Error> {
        let path = self.sand_secrets_path();
        let json = std::fs::read_to_string(&path).map_err(|e| {
            desktop_err(
                "READ_FAILED",
                format!("Could not read {}: {e}", path.display()),
            )
        })?;
        let top: Value = serde_json::from_str(&json).map_err(|e| {
            desktop_err(
                "INVALID_SAND",
                format!("sand-secrets.json is not valid JSON: {e}"),
            )
        })?;
        let ca_str = top
            .get("cursor-accounts")
            .and_then(Value::as_str)
            .filter(|s| !s.is_empty())
            .ok_or_else(|| {
                desktop_err(
                    "NOT_SIGNED_IN",
                    "sand-secrets.json has no cursor-accounts; sign in from the desktop app first.",
                )
            })?;
        let ca: Value = serde_json::from_str(ca_str).map_err(|e| {
            desktop_err(
                "INVALID_SAND",
                format!("sand-secrets.json cursor-accounts is not valid JSON: {e}"),
            )
        })?;
        let active = ca
            .get("active")
            .and_then(Value::as_str)
            .unwrap_or("")
            .to_string();
        let accounts = ca
            .get("accounts")
            .and_then(Value::as_object)
            .filter(|m| !m.is_empty())
            .ok_or_else(|| desktop_err("NOT_SIGNED_IN", "The desktop app has no saved Cursor accounts; sign in from the desktop app first."))?;
        let mut out = vec![];
        for (k, v) in accounts {
            if let Value::Object(m) = v {
                out.push((k.clone(), m.clone()));
            }
        }
        Ok((active, out))
    }

    /// The Cursor accounts in `sand-secrets.json`, sorted by key. Built from plaintext
    /// metadata only (opaque account id, `active` marker): nothing is decrypted to list them,
    /// so no decrypted value (email, token) is ever shown.
    pub fn sand_accounts(&self) -> Result<Vec<SandAccount>, Error> {
        let (active, mut accts) = self.read_sand_accounts()?;
        accts.sort_by(|a, b| a.0.cmp(&b.0));
        Ok(accts
            .into_iter()
            .enumerate()
            .map(|(i, (key, _))| SandAccount {
                label: format!("{}) {}…", i + 1, &key[..key.len().min(8)]),
                active: key == active,
                key,
            })
            .collect())
    }

    /// Resolve and decrypt the Cursor access token for one account in `sand-secrets.json`.
    /// `choice` is a 1-based number, a full account key, or a unique key prefix (4+ chars);
    /// `None` picks the only account. Only the chosen account's access token is decrypted.
    fn load_sand_token(&self, choice: Option<&str>) -> Result<String, Error> {
        let (_, mut accts) = self.read_sand_accounts()?;
        accts.sort_by(|a, b| a.0.cmp(&b.0));
        let listing = || {
            self.sand_accounts()
                .map(|sa| {
                    sa.into_iter()
                        .map(|s| {
                            if s.active {
                                format!("{} (active)", s.label)
                            } else {
                                s.label
                            }
                        })
                        .collect::<Vec<_>>()
                        .join(", ")
                })
                .unwrap_or_default()
        };
        let idx = match choice {
            None if accts.len() == 1 => 0,
            None => {
                return Err(desktop_err(
                    "AMBIGUOUS_ENTRIES",
                    format!(
                        "The desktop app has several Cursor accounts ({}). Specify which one to use by its number, its full account key, or a unique key prefix of at least 4 characters.",
                        listing()
                    ),
                ));
            }
            Some(c) => {
                let c = c.trim();
                let by_num = c
                    .parse::<usize>()
                    .ok()
                    .filter(|n| (1..=accts.len()).contains(n))
                    .map(|n| n - 1);
                let by_key = accts.iter().position(|(k, _)| k == c);
                let by_prefix = || {
                    let m: Vec<usize> = accts
                        .iter()
                        .enumerate()
                        .filter(|(_, (k, _))| c.len() >= 4 && k.starts_with(c))
                        .map(|(i, _)| i)
                        .collect();
                    (m.len() == 1).then(|| m[0])
                };
                by_key.or(by_num).or_else(by_prefix).ok_or_else(|| {
                    desktop_err(
                        "NO_SUCH_ENTRY",
                        format!("No desktop Cursor account '{c}'. Available: {}", listing()),
                    )
                })?
            }
        };
        let enc = accts[idx]
            .1
            .get("cursor-access-token")
            .and_then(Value::as_str)
            .filter(|s| !s.is_empty())
            .ok_or_else(|| {
                desktop_err(
                    "INCOMPLETE_DESCRIPTOR",
                    "sand-secrets.json account has no cursor-access-token.",
                )
            })?;
        self.decrypt(enc)
    }

    /// The stable stored key for a sand choice (so a 401 re-read picks the same account).
    pub fn sand_key_for(&self, choice: Option<&str>) -> Result<Option<String>, Error> {
        let accts = self.sand_accounts()?;
        Ok(match choice {
            None if accts.len() == 1 => Some(accts[0].key.clone()),
            None => None,
            Some(c) => {
                let c = c.trim();
                accts
                    .iter()
                    .position(|a| a.key == c)
                    .or_else(|| {
                        c.parse::<usize>()
                            .ok()
                            .filter(|n| (1..=accts.len()).contains(n))
                            .map(|n| n - 1)
                    })
                    .or_else(|| {
                        let m: Vec<usize> = accts
                            .iter()
                            .enumerate()
                            .filter(|(_, a)| c.len() >= 4 && a.key.starts_with(c))
                            .map(|(i, _)| i)
                            .collect();
                        (m.len() == 1).then(|| m[0])
                    })
                    .map(|i| accts[i].key.clone())
            }
        })
    }

    /// Resolve a desktop credential: `gateway-descriptor.json` first, then the
    /// `sand-secrets.json` Cursor-token fallback. Call this only on an explicit user request.
    pub fn load_credential(
        &self,
        key: Option<&str>,
        policy: &Policy,
    ) -> Result<DesktopCredential, Error> {
        if self.descriptor_path().exists() {
            return self.load_entry(key, policy).map(DesktopCredential::Session);
        }
        if self.sand_present() {
            return self
                .load_sand_token(key)
                .map(DesktopCredential::CursorToken);
        }
        let dir = app_data_dir(&self.home, self.platform, &self.env);
        Err(if dir.exists() {
            desktop_err(
                "NOT_SIGNED_IN",
                format!(
                    "The Grok Bot desktop app is installed but has no saved session (no gateway-descriptor.json or sand-secrets.json in {}). Sign in from the desktop app first.",
                    dir.display()
                ),
            )
        } else {
            desktop_err(
                "APP_NOT_FOUND",
                format!(
                    "The Grok Bot desktop app data was not found at {}.",
                    dir.display()
                ),
            )
        })
    }

    fn decrypt(&self, encrypted: &str) -> Result<String, Error> {
        match self.platform {
            Platform::Windows => self.decrypt_windows_entry(encrypted),
            _ => {
                let password = if needs_keychain(encrypted, self.platform)? {
                    Some(match &self.os_password {
                        Some(p) => p.clone(),
                        None => self.read_os_password()?,
                    })
                } else {
                    None
                };
                decrypt_safe_storage(encrypted, password.as_deref(), self.platform)
            }
        }
    }

    #[cfg(not(target_os = "windows"))]
    fn decrypt_windows_entry(&self, _: &str) -> Result<String, Error> {
        Err(desktop_err(
            "UNSUPPORTED_PLATFORM",
            "Windows desktop sessions can only be read on Windows.",
        ))
    }

    #[cfg(target_os = "windows")]
    fn decrypt_windows_entry(&self, encrypted: &str) -> Result<String, Error> {
        let key =
            windows_impl::local_state_key(&app_data_dir(&self.home, self.platform, &self.env))?;
        decrypt_windows(encrypted, &key)
    }

    #[cfg(not(target_os = "windows"))]
    fn read_os_password(&self) -> Result<String, Error> {
        use std::process::Command;
        let program = |default: &str| {
            self.keychain_program
                .clone()
                .unwrap_or_else(|| PathBuf::from(default))
        };
        let out = match self.platform {
            Platform::Linux => Command::new(program("secret-tool"))
                .args([
                    "lookup",
                    "xdg:schema",
                    "chrome_libsecret_os_crypt_password_v2",
                    "application",
                    "Grok Bot",
                ])
                .output()
                .map_err(|e| {
                    desktop_err(
                        "SECRET_TOOL_MISSING",
                        format!("Could not run secret-tool (install libsecret-tools): {e}"),
                    )
                })?,
            Platform::Macos => Command::new(program("/usr/bin/security"))
                .args(["find-generic-password", "-w", "-s", "Grok Bot Safe Storage"])
                .output()
                .map_err(|e| {
                    desktop_err(
                        "KEYCHAIN_FAILED",
                        format!("Could not run /usr/bin/security: {e}"),
                    )
                })?,
            Platform::Windows => unreachable!(),
        };
        if !out.status.success() {
            return Err(desktop_err(
                "KEYCHAIN_LOCKED",
                "The OS keychain did not return the Grok Bot Safe Storage password (is the keyring unlocked and the app signed in?).",
            ));
        }
        Ok(String::from_utf8_lossy(&out.stdout).trim_end().to_string())
    }

    #[cfg(target_os = "windows")]
    fn read_os_password(&self) -> Result<String, Error> {
        unreachable!("windows uses DPAPI, not a keychain password")
    }
}

#[cfg(target_os = "windows")]
mod windows_impl {
    use super::{Error, desktop_err};
    use serde_json::Value;
    use std::io::Write;
    use std::path::Path;
    use std::process::{Command, Stdio};

    pub fn local_state_key(app_dir: &Path) -> Result<Vec<u8>, Error> {
        use base64::Engine;
        let path = app_dir.join("Local State");
        let json = std::fs::read_to_string(&path).map_err(|e| {
            desktop_err(
                "MISSING_SAFE_STORAGE_KEY",
                format!("Could not read {}: {e}", path.display()),
            )
        })?;
        let v: Value = serde_json::from_str(&json).map_err(|_| {
            desktop_err("MISSING_SAFE_STORAGE_KEY", "Local State is not valid JSON.")
        })?;
        let b64key = v
            .get("os_crypt")
            .and_then(|o| o.get("encrypted_key"))
            .and_then(Value::as_str)
            .unwrap_or("");
        let blob = base64::engine::general_purpose::STANDARD
            .decode(b64key)
            .map_err(|_| {
                desktop_err(
                    "MISSING_SAFE_STORAGE_KEY",
                    "Local State encrypted_key is not base64.",
                )
            })?;
        if blob.len() < 5 || &blob[..5] != b"DPAPI" {
            return Err(desktop_err(
                "MISSING_SAFE_STORAGE_KEY",
                "Grok Bot Local State has no Safe Storage key.",
            ));
        }
        unprotect_dpapi(&blob[5..])
    }

    fn unprotect_dpapi(blob: &[u8]) -> Result<Vec<u8>, Error> {
        use base64::Engine;
        let b64 = base64::engine::general_purpose::STANDARD.encode(blob);
        let script = "Add-Type -AssemblyName System.Security; $blob = [Convert]::FromBase64String([Console]::In.ReadToEnd().Trim()); [Convert]::ToBase64String([Security.Cryptography.ProtectedData]::Unprotect($blob, $null, 'CurrentUser'))";
        let root = std::env::var("SystemRoot").unwrap_or_else(|_| "C:\\Windows".into());
        let exe = Path::new(&root).join("System32/WindowsPowerShell/v1.0/powershell.exe");
        let mut child = Command::new(exe)
            .args(["-NoProfile", "-NonInteractive", "-Command", script])
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .spawn()
            .map_err(|e| {
                desktop_err(
                    "DPAPI_FAILED",
                    format!("Could not run PowerShell for DPAPI: {e}"),
                )
            })?;
        child
            .stdin
            .take()
            .unwrap()
            .write_all(b64.as_bytes())
            .map_err(|e| desktop_err("DPAPI_FAILED", e.to_string()))?;
        let out = child
            .wait_with_output()
            .map_err(|e| desktop_err("DPAPI_FAILED", e.to_string()))?;
        if !out.status.success() {
            return Err(desktop_err("DPAPI_FAILED", "DPAPI unprotect failed."));
        }
        base64::engine::general_purpose::STANDARD
            .decode(String::from_utf8_lossy(&out.stdout).trim())
            .map_err(|_| desktop_err("DPAPI_FAILED", "DPAPI output was not base64."))
    }
}

fn dirs_home() -> PathBuf {
    std::env::var("HOME")
        .ok()
        .map(PathBuf::from)
        .unwrap_or_default()
}

/// Semver-ish app version string (e.g. `"0.70.2"`), as used for `x-cursor-client-version`.
pub type AppVersion = String;

/// Locate the Grok Bot desktop install directory for this platform, if present.
///
/// `GROKBOT_APP_DIR` or `GROKBOT_INSTALL_DIR` (looked up through `env`) wins when it
/// names a directory; otherwise the platform's usual install locations are tried.
pub fn find_install_dir(
    platform: Platform,
    env: &dyn Fn(&str) -> Option<String>,
) -> Option<PathBuf> {
    // Highest priority: explicit override (also used by tests).
    for key in ["GROKBOT_APP_DIR", "GROKBOT_INSTALL_DIR"] {
        if let Some(p) = env(key).filter(|s| !s.is_empty()) {
            let pb = PathBuf::from(p);
            if pb.is_dir() {
                return Some(pb);
            }
        }
    }
    let candidates: Vec<PathBuf> = match platform {
        Platform::Linux => {
            let mut v = Vec::new();
            // Prefer the user's desktop file / symlink before hard-coded system paths.
            if let Some(home) = env("HOME") {
                let desk = PathBuf::from(&home).join(".local/share/applications/grok-bot.desktop");
                if let Some(exec) = read_desktop_exec(&desk)
                    && let Some(parent) = PathBuf::from(&exec).parent()
                {
                    v.push(parent.to_path_buf());
                }
                v.push(PathBuf::from(&home).join(".local/share/grok-bot"));
                v.push(PathBuf::from(&home).join(".local/opt/grokbot-linux-port-bin"));
            }
            if let Ok(p) = std::fs::canonicalize("/bin/grok-bot")
                && let Some(parent) = p.parent()
            {
                v.push(parent.to_path_buf());
            }
            let desk = PathBuf::from("/usr/share/applications/grok-bot.desktop");
            if let Some(exec) = read_desktop_exec(&desk)
                && let Some(parent) = PathBuf::from(&exec).parent()
            {
                v.push(parent.to_path_buf());
            }
            v.extend([
                PathBuf::from("/opt/grokbot-linux-port-bin"),
                PathBuf::from("/opt/Grok Bot"),
                PathBuf::from("/usr/lib/grok-bot"),
            ]);
            v
        }
        Platform::Macos => {
            let mut v = vec![PathBuf::from("/Applications/Grok Bot.app")];
            if let Some(home) = env("HOME") {
                v.push(PathBuf::from(home).join("Applications/Grok Bot.app"));
            }
            v
        }
        Platform::Windows => {
            let mut v = vec![];
            for key in ["LOCALAPPDATA", "PROGRAMFILES", "PROGRAMFILES(X86)"] {
                if let Some(base) = env(key) {
                    v.push(PathBuf::from(base).join("Grok Bot"));
                }
            }
            v
        }
    };
    candidates.into_iter().find(|p| p.is_dir())
}

fn read_desktop_exec(path: &Path) -> Option<String> {
    let text = std::fs::read_to_string(path).ok()?;
    for line in text.lines() {
        let line = line.trim();
        if let Some(rest) = line.strip_prefix("Exec=") {
            let bin = rest.split_whitespace().next()?.to_string();
            return Some(bin);
        }
    }
    None
}

fn resources_dir(install: &Path, platform: Platform) -> PathBuf {
    match platform {
        Platform::Macos => install.join("Contents/Resources"),
        _ => install.join("resources"),
    }
}

fn version_from_package_json(bytes: &[u8]) -> Option<AppVersion> {
    let v: Value = serde_json::from_slice(bytes).ok()?;
    let ver = v.get("version")?.as_str()?.trim();
    normalize_semver(ver)
}

/// Strip a leading `v` and keep `MAJOR.MINOR.PATCH` (desktop app does the same).
pub fn normalize_semver(s: &str) -> Option<AppVersion> {
    let s = s.trim().trim_start_matches('v');
    let re_ok = s.split_once('-').map(|(a, _)| a).unwrap_or(s);
    let mut parts = re_ok.split('.');
    let (Some(a), Some(b), Some(c)) = (parts.next(), parts.next(), parts.next()) else {
        return None;
    };
    if a.chars().all(|c| c.is_ascii_digit())
        && b.chars().all(|c| c.is_ascii_digit())
        && c.chars().all(|c| c.is_ascii_digit())
    {
        Some(format!("{a}.{b}.{c}"))
    } else {
        None
    }
}

/// Read `package.json` (or `product.json`) `version` out of an Electron `.asar`.
pub fn version_from_asar(asar: &Path) -> Option<AppVersion> {
    let data = std::fs::read(asar).ok()?;
    if data.len() < 16 {
        return None;
    }
    // sizePickle: uint32 payload_size(=4) + uint32 header_len
    let header_len = u32::from_le_bytes(data[4..8].try_into().ok()?) as usize;
    if data.len() < 8 + header_len {
        return None;
    }
    let header = &data[8..8 + header_len];
    if header.len() < 8 {
        return None;
    }
    let str_len = u32::from_le_bytes(header[4..8].try_into().ok()?) as usize;
    if header.len() < 8 + str_len {
        return None;
    }
    let meta: Value = serde_json::from_slice(&header[8..8 + str_len]).ok()?;
    let files = meta.get("files")?.as_object()?;
    for name in ["package.json", "product.json"] {
        let node = match files.get(name) {
            Some(n) => n,
            None => continue,
        };
        let off = node.get("offset")?.as_str()?.parse::<usize>().ok()?;
        let size = node.get("size")?.as_u64()? as usize;
        let data_start = 8 + header_len;
        let start = data_start.checked_add(off)?;
        let end = start.checked_add(size)?;
        if end > data.len() {
            continue;
        }
        if let Some(v) = version_from_package_json(&data[start..end]) {
            return Some(v);
        }
    }
    None
}

fn version_from_status_json(path: &Path) -> Option<AppVersion> {
    let v: Value = serde_json::from_slice(&std::fs::read(path).ok()?).ok()?;
    normalize_semver(v.get("appVersion")?.as_str()?)
}

/// Detect the installed Grok Bot desktop app version (e.g. `"0.70.2"`).
///
/// Looks in the install dir's `resources/app/package.json`, `product.json`,
/// `resources/app.asar`, then (as a last resort) `desktop-status.json` in the
/// app data dir. Returns `None` when nothing is installed or readable.
pub fn detect_app_version(
    platform: Platform,
    home: &Path,
    env: &dyn Fn(&str) -> Option<String>,
) -> Option<AppVersion> {
    if let Some(install) = find_install_dir(platform, env) {
        let res = resources_dir(&install, platform);
        for rel in [
            "app/package.json",
            "app/product.json",
            "package.json",
            "product.json",
        ] {
            let p = res.join(rel);
            if let Ok(bytes) = std::fs::read(&p)
                && let Some(v) = version_from_package_json(&bytes)
            {
                return Some(v);
            }
        }
        let asar = res.join("app.asar");
        if let Some(v) = version_from_asar(&asar) {
            return Some(v);
        }
    }
    // Last resort: the running app writes appVersion into its config dir.
    let status = app_data_dir(home, platform, env).join("desktop-status.json");
    version_from_status_json(&status)
}

impl DesktopConfig {
    /// Detect the installed desktop app version using this config's platform/home/env.
    pub fn detect_app_version(&self) -> Option<AppVersion> {
        detect_app_version(self.platform, &self.home, &self.env)
    }
}

#[cfg(test)]
mod tests;