claudette 0.5.4

Local-first AI personal secretary for Ollama. Telegram bot, voice, persistent scheduler, Gmail and Calendar. Single-binary Rust.
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
//! Google OAuth 2.0 for installed / desktop apps — loopback flow.
//!
//! `claudette --auth-google [scope]` runs [`run_auth_flow`]. It opens the
//! user's browser to Google's authorize endpoint with
//! `redirect_uri=http://127.0.0.1:<port>/callback`, spins up a single-use
//! HTTP server that captures the `code` param, exchanges it for tokens,
//! and persists them to a **per-context** file under `~/.claudette/secrets/`.
//!
//! Per AD-6 we keep **separate token files** for each scope bundle so a
//! hostile email read with the Gmail-read token can't pivot into Calendar
//! writes. Calendar tools load only the calendar token; Gmail read tools
//! load only the gmail-read token; phase 5's Gmail write tools will use
//! a third.
//!
//! Storage:
//!   ~/.claudette/secrets/google_oauth_client.json        → { client_id, client_secret }
//!   ~/.claudette/secrets/google_oauth.json               → Calendar tokens
//!   ~/.claudette/secrets/google_oauth_gmail_read.json    → Gmail read-only tokens
//!
//! Env overrides (same shape as `secrets.rs`):
//!   CLAUDETTE_GOOGLE_CLIENT_ID  / GOOGLE_CLIENT_ID
//!   CLAUDETTE_GOOGLE_CLIENT_SECRET / GOOGLE_CLIENT_SECRET
//!
//! Threat model: plaintext on disk, mode 0600 on Unix. Same as the GitHub PAT
//! and Telegram token already in the secrets dir. See AD-3 in
//! docs/life_agent.md for the rationale.

use std::fmt::Write as _;
use std::io::{Read, Write};
use std::net::TcpListener;
use std::path::PathBuf;
use std::time::Duration;

use serde::{Deserialize, Serialize};
use serde_json::Value;

const AUTHORIZE_URL: &str = "https://accounts.google.com/o/oauth2/v2/auth";
const TOKEN_URL: &str = "https://oauth2.googleapis.com/token";
const REVOKE_URL: &str = "https://oauth2.googleapis.com/revoke";

/// Scope bundles we request at the OAuth consent screen. Each has its own
/// on-disk token file so a compromise of one context can't pivot to the
/// other (AD-6).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AuthContext {
    /// Read/write access to Calendar — used by `calendar_*` tools.
    Calendar,
    /// Read-only Gmail — used by `gmail_list`, `gmail_read`,
    /// `gmail_list_labels`, `gmail_search`. Never granted send/modify.
    GmailRead,
}

impl AuthContext {
    /// OAuth scope strings that go into the `scope=` query param.
    const fn scopes(self) -> &'static [&'static str] {
        match self {
            Self::Calendar => &["https://www.googleapis.com/auth/calendar"],
            Self::GmailRead => &["https://www.googleapis.com/auth/gmail.readonly"],
        }
    }

    /// Basename of the token file under `~/.claudette/secrets/`.
    const fn token_filename(self) -> &'static str {
        match self {
            Self::Calendar => "google_oauth.json",
            Self::GmailRead => "google_oauth_gmail_read.json",
        }
    }

    /// Human-readable label for CLI messages / errors.
    pub const fn label(self) -> &'static str {
        match self {
            Self::Calendar => "calendar",
            Self::GmailRead => "gmail-read",
        }
    }

    /// Parse from a CLI keyword (case-insensitive). Accepts the canonical
    /// label plus common aliases.
    pub fn parse(s: &str) -> Option<Self> {
        match s.trim().to_lowercase().as_str() {
            "calendar" | "cal" | "gcal" => Some(Self::Calendar),
            "gmail" | "gmail-read" | "gmail_read" | "mail" => Some(Self::GmailRead),
            _ => None,
        }
    }
}

/// On-disk token record. Shape mirrors Google's `/token` response plus a
/// computed absolute `expires_at` so we don't need to remember when we
/// fetched it.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GoogleTokens {
    pub access_token: String,
    pub refresh_token: String,
    /// Unix seconds. Refresh when within 60 s of this.
    pub expires_at: i64,
    pub scope: String,
    pub token_type: String,
}

/// Client credentials the user pastes in from Google Cloud Console.
#[derive(Debug, Clone, Serialize, Deserialize)]
struct ClientCreds {
    client_id: String,
    client_secret: String,
}

fn secrets_dir() -> PathBuf {
    let home = std::env::var("USERPROFILE")
        .or_else(|_| std::env::var("HOME"))
        .unwrap_or_else(|_| ".".to_string());
    PathBuf::from(home).join(".claudette").join("secrets")
}

fn tokens_path(ctx: AuthContext) -> PathBuf {
    secrets_dir().join(ctx.token_filename())
}

fn client_path() -> PathBuf {
    secrets_dir().join("google_oauth_client.json")
}

/// Load client_id + client_secret via the same env-then-file lookup order
/// as [`crate::secrets::read_secret`].
fn load_client_creds() -> Result<ClientCreds, String> {
    let id = lookup_env_or_file("CLIENT_ID").ok();
    let secret = lookup_env_or_file("CLIENT_SECRET").ok();
    if let (Some(client_id), Some(client_secret)) = (id, secret) {
        return Ok(ClientCreds {
            client_id,
            client_secret,
        });
    }

    let path = client_path();
    if path.exists() {
        let raw = std::fs::read_to_string(&path)
            .map_err(|e| format!("google_auth: read {}: {e}", path.display()))?;
        let creds: ClientCreds = serde_json::from_str(&raw).map_err(|e| {
            format!(
                "google_auth: parse {}: {e}. Expected JSON with 'client_id' and 'client_secret'.",
                path.display()
            )
        })?;
        return Ok(creds);
    }

    Err(format!(
        "google_auth: OAuth client not configured. Set CLAUDETTE_GOOGLE_CLIENT_ID + \
         CLAUDETTE_GOOGLE_CLIENT_SECRET env vars, or write JSON {{\"client_id\":\"...\",\
         \"client_secret\":\"...\"}} to {}. See docs/google_setup.md for how to create \
         the OAuth client in Google Cloud Console.",
        path.display()
    ))
}

/// Look up `CLAUDETTE_GOOGLE_<SUFFIX>` then `GOOGLE_<SUFFIX>`.
fn lookup_env_or_file(suffix: &str) -> Result<String, ()> {
    for var in [
        format!("CLAUDETTE_GOOGLE_{suffix}"),
        format!("GOOGLE_{suffix}"),
    ] {
        if let Ok(val) = std::env::var(&var) {
            let trimmed = val.trim();
            if !trimmed.is_empty() {
                return Ok(trimmed.to_string());
            }
        }
    }
    Err(())
}

fn save_tokens(ctx: AuthContext, tokens: &GoogleTokens) -> Result<(), String> {
    let path = tokens_path(ctx);
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)
            .map_err(|e| format!("google_auth: create {}: {e}", parent.display()))?;
    }
    let body = serde_json::to_string_pretty(tokens)
        .map_err(|e| format!("google_auth: serialize tokens: {e}"))?;

    // Atomic create-with-0600 on Unix (no write-then-chmod race); plain write
    // on Windows. Errors propagate through the normal Result chain so a
    // failed chmod is visible instead of being silently swallowed.
    crate::secrets::write_secret_file(&path, body.as_bytes())
        .map_err(|e| format!("google_auth: write {}: {e}", path.display()))?;

    Ok(())
}

fn load_tokens(ctx: AuthContext) -> Result<GoogleTokens, String> {
    let path = tokens_path(ctx);
    if !path.exists() {
        return Err(format!(
            "google_auth: not authenticated for {}. Run `claudette --auth-google {}` first. \
             (Expected tokens at {}.)",
            ctx.label(),
            ctx.label(),
            path.display()
        ));
    }
    let raw = std::fs::read_to_string(&path)
        .map_err(|e| format!("google_auth: read {}: {e}", path.display()))?;
    serde_json::from_str(&raw).map_err(|e| format!("google_auth: parse {}: {e}", path.display()))
}

fn now_unix() -> i64 {
    chrono::Utc::now().timestamp()
}

fn http_client() -> Result<reqwest::blocking::Client, String> {
    reqwest::blocking::Client::builder()
        .timeout(Duration::from_secs(30))
        .build()
        .map_err(|e| format!("google_auth: build http client: {e}"))
}

/// Entry point for tool handlers — returns a bearer token for the given
/// context, ready to drop into `Authorization: Bearer <token>`. Refreshes
/// automatically when close to expiry and persists the refreshed access
/// token to the per-context file.
pub fn access_token(ctx: AuthContext) -> Result<String, String> {
    let mut tokens = load_tokens(ctx)?;
    if tokens.expires_at - now_unix() < 60 {
        refresh_tokens(&mut tokens, Some(ctx))?;
        save_tokens(ctx, &tokens)?;
    }
    Ok(tokens.access_token)
}

/// Refresh `tokens` against Google's `/token` endpoint. The optional
/// [`AuthContext`] threads through to [`classify_refresh_failure`] so the
/// "run `claudette --auth-google <scope>`" recovery hint in error
/// messages can name the right scope; `None` falls back to a generic
/// "<scope>" placeholder.
fn refresh_tokens(tokens: &mut GoogleTokens, ctx: Option<AuthContext>) -> Result<(), String> {
    let creds = load_client_creds()?;
    let client = http_client()?;
    let params = [
        ("client_id", creds.client_id.as_str()),
        ("client_secret", creds.client_secret.as_str()),
        ("refresh_token", tokens.refresh_token.as_str()),
        ("grant_type", "refresh_token"),
    ];
    let resp = client
        .post(TOKEN_URL)
        .form(&params)
        .send()
        .map_err(|e| format!("google_auth: refresh request failed: {e}"))?;

    let status = resp.status();
    let body: Value = resp
        .json()
        .map_err(|e| format!("google_auth: refresh parse failed: {e}"))?;
    if !status.is_success() {
        return Err(classify_refresh_failure(status, &body, ctx));
    }

    let access = body
        .get("access_token")
        .and_then(Value::as_str)
        .ok_or("google_auth: refresh response missing access_token")?;
    let expires_in = body
        .get("expires_in")
        .and_then(Value::as_i64)
        .unwrap_or(3600);
    // Google may omit scope on refresh; keep the prior value in that case.
    if let Some(scope) = body.get("scope").and_then(Value::as_str) {
        tokens.scope = scope.to_string();
    }
    tokens.access_token = access.to_string();
    tokens.expires_at = now_unix() + expires_in;
    Ok(())
}

/// Branch on the body of a non-success refresh-token response to give the
/// user an actionable next step instead of the opaque `HTTP 400` we used
/// to emit for both invalid_grant (permanent — revoke + re-auth) and 5xx
/// (transient — retry).
///
/// Google's documented shape for invalid_grant:
/// `{"error":"invalid_grant","error_description":"Token has been expired or revoked."}`
fn classify_refresh_failure(
    status: reqwest::StatusCode,
    body: &Value,
    ctx: Option<AuthContext>,
) -> String {
    let error_code = body.get("error").and_then(Value::as_str).unwrap_or("");
    let description = body
        .get("error_description")
        .and_then(Value::as_str)
        .unwrap_or("");
    let scope_label = ctx.map_or("<scope>", AuthContext::label);

    if error_code == "invalid_grant" {
        return format!(
            "google_auth: refresh token rejected (invalid_grant — usually \
             revoked or expired). Recover with: \
             `claudette --auth-google {scope_label} --revoke` then \
             `claudette --auth-google {scope_label}`. \
             Google said: {description}"
        );
    }
    if status.is_server_error() {
        return format!(
            "google_auth: refresh HTTP {status} — Google's token endpoint \
             returned a transient server error. Retry in a moment; if it \
             keeps happening, check https://status.cloud.google.com/. \
             Body: {}",
            body.to_string().chars().take(200).collect::<String>()
        );
    }
    // Other 4xx — preserve the prior generic form but still include the
    // structured error code first if Google gave us one, so the user
    // can google the exact code.
    let error_prefix = if error_code.is_empty() {
        String::new()
    } else {
        format!("{error_code}: ")
    };
    format!(
        "google_auth: refresh HTTP {status}{error_prefix}{}",
        body.to_string().chars().take(300).collect::<String>()
    )
}

/// Live-verify access for `ctx` by issuing one cheap read call:
/// - `Calendar` → `events.list?maxResults=1` against `primary`.
/// - `GmailRead` → `users/me/messages?maxResults=1` so we can quote the
///   `resultSizeEstimate` count back to the user.
///
/// Returns a human-readable success line on success, an error string on
/// failure. Used by both `claudette --auth-google <scope>` (post-grant
/// confirmation) and `claudette --doctor` (token-staleness probe), so the
/// two callers stay in lockstep on what "access works" means.
pub fn verify_scope_live(ctx: AuthContext, token: &str) -> Result<String, String> {
    let client = reqwest::blocking::Client::builder()
        .timeout(Duration::from_secs(10))
        .build()
        .map_err(|e| format!("google_auth: http client: {e}"))?;
    let url = match ctx {
        AuthContext::Calendar => {
            "https://www.googleapis.com/calendar/v3/calendars/primary/events?maxResults=1"
        }
        AuthContext::GmailRead => {
            "https://gmail.googleapis.com/gmail/v1/users/me/messages?maxResults=1"
        }
    };
    let resp = client
        .get(url)
        .bearer_auth(token)
        .send()
        .map_err(|e| format!("google_auth: verify request: {e}"))?;
    let status = resp.status();
    if !status.is_success() {
        let body = resp.text().unwrap_or_default();
        return Err(format!(
            "google_auth: verify HTTP {}{}",
            status.as_u16(),
            body.chars().take(160).collect::<String>()
        ));
    }
    let body: Value = resp
        .json()
        .map_err(|e| format!("google_auth: verify parse: {e}"))?;
    match ctx {
        AuthContext::Calendar => Ok("calendar access verified".to_string()),
        AuthContext::GmailRead => {
            let n = body
                .get("resultSizeEstimate")
                .and_then(Value::as_u64)
                .unwrap_or(0);
            Ok(format!("gmail access verified ({n} messages visible)"))
        }
    }
}

/// Revoke the stored refresh token for `ctx` with Google and delete the
/// corresponding local file. Used by `claudette --auth-google [scope] --revoke`.
pub fn revoke(ctx: AuthContext) -> Result<(), String> {
    let tokens = load_tokens(ctx)?;
    let client = http_client()?;
    let resp = client
        .post(REVOKE_URL)
        .form(&[("token", tokens.refresh_token.as_str())])
        .send()
        .map_err(|e| format!("google_auth: revoke request failed: {e}"))?;
    // Google returns 200 for an already-invalid token too; we tolerate both.
    if !resp.status().is_success() {
        eprintln!(
            "google_auth: remote revoke returned HTTP {} — deleting local tokens anyway",
            resp.status()
        );
    }
    let path = tokens_path(ctx);
    if path.exists() {
        std::fs::remove_file(&path)
            .map_err(|e| format!("google_auth: delete {}: {e}", path.display()))?;
    }
    Ok(())
}

/// Interactive `claudette --auth-google [scope]` flow. Binds a loopback
/// listener, opens the browser, captures the `code`, exchanges it for
/// tokens, saves to the context-specific file.
pub fn run_auth_flow(ctx: AuthContext) -> Result<(), String> {
    let creds = load_client_creds()?;

    // Bind first so we know which port to put in the redirect URI.
    let listener =
        TcpListener::bind("127.0.0.1:0").map_err(|e| format!("google_auth: bind loopback: {e}"))?;
    let port = listener
        .local_addr()
        .map_err(|e| format!("google_auth: local_addr: {e}"))?
        .port();
    let redirect_uri = format!("http://127.0.0.1:{port}/callback");

    let state = random_state();
    let scopes = ctx.scopes().join(" ");
    let authorize = format!(
        "{AUTHORIZE_URL}?client_id={cid}&redirect_uri={redir}&response_type=code\
         &scope={scope}&access_type=offline&prompt=consent&state={state}",
        cid = url_encode(&creds.client_id),
        redir = url_encode(&redirect_uri),
        scope = url_encode(&scopes),
    );

    eprintln!(
        "Opening browser to authorize Claudette with Google ({scope})…",
        scope = ctx.label()
    );
    eprintln!("If it doesn't open, paste this URL manually:\n  {authorize}\n");
    let _ = open_browser(&authorize);

    let (code, returned_state) = accept_callback(&listener)?;
    if returned_state != state {
        return Err(format!(
            "google_auth: state mismatch (got '{returned_state}', expected '{state}') \
             — possible CSRF; aborting"
        ));
    }

    let tokens = exchange_code(&creds, &code, &redirect_uri)?;
    save_tokens(ctx, &tokens)?;
    eprintln!(
        "✔ Saved {} tokens to {}",
        ctx.label(),
        tokens_path(ctx).display()
    );

    // Confirm the granted scope actually works against the live API before
    // the user discovers a broken token mid-prompt. A failed verify here is
    // a warning, not a hard error: tokens did save successfully, and a
    // transient Google outage shouldn't make the user re-run the whole
    // consent flow. The user can re-verify later via `claudette --doctor`.
    match verify_scope_live(ctx, &tokens.access_token) {
        Ok(msg) => eprintln!("✔ OK: {msg}"),
        Err(e) => eprintln!(
            "⚠  saved tokens but live verify failed: {e}. \
             Re-run `claudette --doctor` after you fix it."
        ),
    }
    Ok(())
}

fn exchange_code(
    creds: &ClientCreds,
    code: &str,
    redirect_uri: &str,
) -> Result<GoogleTokens, String> {
    let client = http_client()?;
    let params = [
        ("code", code),
        ("client_id", creds.client_id.as_str()),
        ("client_secret", creds.client_secret.as_str()),
        ("redirect_uri", redirect_uri),
        ("grant_type", "authorization_code"),
    ];
    let resp = client
        .post(TOKEN_URL)
        .form(&params)
        .send()
        .map_err(|e| format!("google_auth: token exchange failed: {e}"))?;

    let status = resp.status();
    let body: Value = resp
        .json()
        .map_err(|e| format!("google_auth: token exchange parse: {e}"))?;
    if !status.is_success() {
        return Err(format!(
            "google_auth: token HTTP {status}: {}",
            body.to_string().chars().take(500).collect::<String>()
        ));
    }

    let access = body
        .get("access_token")
        .and_then(Value::as_str)
        .ok_or("google_auth: response missing access_token")?;
    let refresh = body
        .get("refresh_token")
        .and_then(Value::as_str)
        .ok_or("google_auth: response missing refresh_token — did you include access_type=offline and prompt=consent?")?;
    let expires_in = body
        .get("expires_in")
        .and_then(Value::as_i64)
        .unwrap_or(3600);
    let scope = body
        .get("scope")
        .and_then(Value::as_str)
        .unwrap_or("")
        .to_string();
    let token_type = body
        .get("token_type")
        .and_then(Value::as_str)
        .unwrap_or("Bearer")
        .to_string();

    Ok(GoogleTokens {
        access_token: access.to_string(),
        refresh_token: refresh.to_string(),
        expires_at: now_unix() + expires_in,
        scope,
        token_type,
    })
}

/// Accept a single HTTP GET on the loopback listener, parse the query string,
/// return (code, state). Writes a tiny HTML page back so the browser shows a
/// friendly "you can close this tab" message.
fn accept_callback(listener: &TcpListener) -> Result<(String, String), String> {
    listener
        .set_nonblocking(false)
        .map_err(|e| format!("google_auth: set_nonblocking: {e}"))?;

    // Single-shot: we only need one callback. If the user cancels, the
    // connection never arrives and `incoming().next()` is None, returning
    // the "listener closed" error below.
    if let Some(stream) = listener.incoming().next() {
        let mut stream = stream.map_err(|e| format!("google_auth: accept connection: {e}"))?;
        let _ = stream.set_read_timeout(Some(Duration::from_secs(30)));
        let _ = stream.set_write_timeout(Some(Duration::from_secs(5)));

        let mut buf = [0u8; 4096];
        let n = stream
            .read(&mut buf)
            .map_err(|e| format!("google_auth: read callback: {e}"))?;
        let req = String::from_utf8_lossy(&buf[..n]);

        // First line: "GET /callback?code=...&state=... HTTP/1.1"
        let first = req.lines().next().unwrap_or("");
        let mut parts = first.split_whitespace();
        let _method = parts.next().unwrap_or("");
        let target = parts.next().unwrap_or("");

        let query = target.split_once('?').map_or("", |(_, q)| q);
        let mut code = String::new();
        let mut state = String::new();
        let mut err = String::new();
        for kv in query.split('&') {
            let Some((k, v)) = kv.split_once('=') else {
                continue;
            };
            let decoded = url_decode(v);
            match k {
                "code" => code = decoded,
                "state" => state = decoded,
                "error" => err = decoded,
                _ => {}
            }
        }

        let body_html = if err.is_empty() && !code.is_empty() {
            "<html><body><h2>Claudette is authorized.</h2>\
             <p>You can close this tab.</p></body></html>"
        } else {
            "<html><body><h2>Authorization failed.</h2>\
             <p>Check the terminal for details.</p></body></html>"
        };
        let response = format!(
            "HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=utf-8\r\n\
             Content-Length: {}\r\nConnection: close\r\n\r\n{}",
            body_html.len(),
            body_html
        );
        let _ = stream.write_all(response.as_bytes());

        if !err.is_empty() {
            return Err(format!("google_auth: Google returned error='{err}'"));
        }
        if code.is_empty() {
            return Err(
                "google_auth: callback missing 'code' param — did you cancel the consent screen?"
                    .to_string(),
            );
        }
        return Ok((code, state));
    }
    Err("google_auth: listener closed before receiving callback".to_string())
}

fn open_browser(url: &str) -> std::io::Result<()> {
    #[cfg(target_os = "windows")]
    {
        // `cmd /C start "" <url>` re-parses the URL through cmd, which
        // treats `&` as a command-chain separator. OAuth URLs have
        // multiple `&` query params, so the URL gets truncated at the
        // first `&` and Google rejects it with "Required parameter is
        // missing: response_type". `rundll32 url.dll,FileProtocolHandler`
        // bypasses the shell entirely — Win32 hands the URL to the
        // default browser as a single string.
        std::process::Command::new("rundll32")
            .args(["url.dll,FileProtocolHandler", url])
            .spawn()
            .map(|_| ())
    }
    #[cfg(target_os = "macos")]
    {
        std::process::Command::new("open")
            .arg(url)
            .spawn()
            .map(|_| ())
    }
    #[cfg(all(not(target_os = "windows"), not(target_os = "macos")))]
    {
        std::process::Command::new("xdg-open")
            .arg(url)
            .spawn()
            .map(|_| ())
    }
}

/// 128-bit random hex from OS entropy (`/dev/urandom` on Unix,
/// `BCryptGenRandom` on Windows, `getentropy` on macOS/BSDs — all via
/// the `getrandom` crate).
///
/// The `state` parameter guards the OAuth loopback flow against CSRF:
/// an attacker on the same host who can predict `state` can race a
/// forged `code=…&state=<predicted>` to the loopback listener and
/// hijack the token exchange. Predictability matters for the full
/// lifetime of the consent window (minutes).
///
/// A previous version derived `state` from `SystemTime::now()` XOR'd
/// with `(pid × golden_ratio)`. Any co-tenant process could observe
/// the claudette PID + process start time to microsecond precision
/// (`/proc/<pid>/stat` on Linux, `QueryProcessCycleTime` on Windows)
/// and brute-force the resulting `state` in constant-time. Switching
/// to `getrandom` removes the attack.
///
/// On the (very rare) failure path — `getrandom` returning an error
/// means the kernel RNG is genuinely unavailable, not just slow — we
/// panic. Falling back to weaker entropy silently would reintroduce
/// the exact weakness this function was rewritten to fix.
fn random_state() -> String {
    let mut buf = [0u8; 16];
    getrandom::fill(&mut buf).expect("OS RNG failed — refusing to use weaker entropy");
    let mut out = String::with_capacity(32);
    for b in buf {
        use std::fmt::Write;
        write!(out, "{b:02x}").expect("writing to String never fails");
    }
    out
}

/// Percent-encode the subset of chars we actually emit in query strings.
fn url_encode(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for b in s.bytes() {
        match b {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
                out.push(b as char);
            }
            _ => {
                let _ = write!(out, "%{b:02X}");
            }
        }
    }
    out
}

fn url_decode(s: &str) -> String {
    let mut out = Vec::with_capacity(s.len());
    let bytes = s.as_bytes();
    let mut i = 0;
    while i < bytes.len() {
        match bytes[i] {
            b'+' => {
                out.push(b' ');
                i += 1;
            }
            b'%' if i + 2 < bytes.len() => {
                let hi = hex_nibble(bytes[i + 1]);
                let lo = hex_nibble(bytes[i + 2]);
                if let (Some(h), Some(l)) = (hi, lo) {
                    out.push((h << 4) | l);
                    i += 3;
                } else {
                    out.push(bytes[i]);
                    i += 1;
                }
            }
            b => {
                out.push(b);
                i += 1;
            }
        }
    }
    String::from_utf8_lossy(&out).into_owned()
}

fn hex_nibble(b: u8) -> Option<u8> {
    match b {
        b'0'..=b'9' => Some(b - b'0'),
        b'a'..=b'f' => Some(b - b'a' + 10),
        b'A'..=b'F' => Some(b - b'A' + 10),
        _ => None,
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn url_encode_leaves_unreserved() {
        assert_eq!(url_encode("abcXYZ-_.~09"), "abcXYZ-_.~09");
    }

    #[test]
    fn url_encode_percent_encodes_space_and_slash() {
        assert_eq!(url_encode("hello world"), "hello%20world");
        assert_eq!(url_encode("a/b"), "a%2Fb");
        assert_eq!(url_encode("a:b"), "a%3Ab");
    }

    #[test]
    fn url_decode_roundtrips_space_slash_colon() {
        assert_eq!(url_decode("hello%20world"), "hello world");
        assert_eq!(url_decode("a%2Fb"), "a/b");
        assert_eq!(url_decode("a%3Ab"), "a:b");
    }

    #[test]
    fn url_decode_handles_plus_as_space() {
        assert_eq!(url_decode("hello+world"), "hello world");
    }

    #[test]
    fn url_decode_keeps_unknown_escapes_literal() {
        // Malformed percent escape is surfaced literally rather than
        // panicking. Tools that receive the value upstream will then reject
        // it with their own "missing/invalid" error.
        assert_eq!(url_decode("%ZZ"), "%ZZ");
    }

    #[test]
    fn random_state_is_32_hex_chars() {
        let s = random_state();
        assert_eq!(s.len(), 32);
        assert!(s.chars().all(|c| c.is_ascii_hexdigit()));
    }

    #[test]
    fn random_state_changes_between_calls() {
        // Two OS-RNG draws in rapid succession must not collide. Previously
        // this needed a SystemTime::now nudge; with getrandom the distinct-
        // output guarantee is statistical (1 in 2^128).
        let a = random_state();
        let b = random_state();
        assert_ne!(a, b, "two state values should differ");
    }

    #[test]
    fn random_state_has_spread_across_many_calls() {
        // Sanity-check that we're not returning a near-constant value:
        // 100 draws should all be distinct and should cover >= 50 unique
        // first-byte values (256 possible, 100 draws → expectation is
        // ~99 unique first bytes by the birthday bound).
        let mut draws = std::collections::HashSet::new();
        let mut first_bytes = std::collections::HashSet::new();
        for _ in 0..100 {
            let s = random_state();
            assert_eq!(s.len(), 32);
            first_bytes.insert(s[..2].to_string());
            draws.insert(s);
        }
        assert_eq!(draws.len(), 100, "100 draws should all be distinct");
        assert!(
            first_bytes.len() >= 50,
            "first-byte spread should be ≥50 unique, got {}",
            first_bytes.len()
        );
    }

    #[test]
    fn tokens_path_under_secrets() {
        let p = tokens_path(AuthContext::Calendar);
        assert!(p.ends_with("google_oauth.json"));
        assert!(p.parent().unwrap().ends_with("secrets"));
    }

    #[test]
    fn gmail_tokens_path_differs_from_calendar() {
        let cal = tokens_path(AuthContext::Calendar);
        let gmail = tokens_path(AuthContext::GmailRead);
        assert_ne!(cal, gmail);
        assert!(gmail.ends_with("google_oauth_gmail_read.json"));
    }

    #[test]
    fn client_path_under_secrets() {
        let p = client_path();
        assert!(p.ends_with("google_oauth_client.json"));
    }

    #[test]
    fn auth_context_parse_accepts_canonical_and_aliases() {
        assert_eq!(AuthContext::parse("calendar"), Some(AuthContext::Calendar));
        assert_eq!(AuthContext::parse("cal"), Some(AuthContext::Calendar));
        assert_eq!(AuthContext::parse("gcal"), Some(AuthContext::Calendar));
        assert_eq!(AuthContext::parse("gmail"), Some(AuthContext::GmailRead));
        assert_eq!(
            AuthContext::parse("gmail-read"),
            Some(AuthContext::GmailRead)
        );
        assert_eq!(AuthContext::parse("GMAIL"), Some(AuthContext::GmailRead));
        assert_eq!(AuthContext::parse("unknown"), None);
        assert_eq!(AuthContext::parse(""), None);
    }

    #[test]
    fn auth_context_scopes_are_distinct() {
        let cal = AuthContext::Calendar.scopes();
        let gmail = AuthContext::GmailRead.scopes();
        assert!(!cal.is_empty());
        assert!(!gmail.is_empty());
        assert_ne!(cal, gmail);
        // Defence in depth: phase 4 must NOT request gmail.send.
        for s in gmail {
            assert!(
                !s.contains("gmail.send") && !s.contains("gmail.modify"),
                "gmail-read scope leaked a write permission: {s}"
            );
        }
    }

    #[test]
    fn load_client_creds_errors_when_missing() {
        // Only meaningful if the user running tests doesn't actually have
        // these env vars set. Guard with a check.
        if std::env::var("CLAUDETTE_GOOGLE_CLIENT_ID").is_ok()
            || std::env::var("GOOGLE_CLIENT_ID").is_ok()
        {
            return;
        }
        if client_path().exists() {
            return;
        }
        let err = load_client_creds().unwrap_err();
        assert!(err.contains("OAuth client not configured"), "got: {err}");
        assert!(err.contains("docs/google_setup.md"), "got: {err}");
    }

    #[test]
    fn classify_refresh_failure_invalid_grant_names_revoke_then_reauth() {
        let body = serde_json::json!({
            "error": "invalid_grant",
            "error_description": "Token has been expired or revoked."
        });
        let msg = classify_refresh_failure(
            reqwest::StatusCode::BAD_REQUEST,
            &body,
            Some(AuthContext::Calendar),
        );
        assert!(msg.contains("invalid_grant"), "got: {msg}");
        // Must literally name the recovery command so the user doesn't
        // have to read the source to figure out what to do.
        assert!(
            msg.contains("--auth-google calendar --revoke"),
            "got: {msg}"
        );
        assert!(msg.contains("--auth-google calendar"), "got: {msg}");
        assert!(msg.contains("revoked or expired"), "got: {msg}");
    }

    #[test]
    fn classify_refresh_failure_5xx_says_transient() {
        let body = serde_json::json!({"error": "internal_error"});
        let msg = classify_refresh_failure(
            reqwest::StatusCode::INTERNAL_SERVER_ERROR,
            &body,
            Some(AuthContext::GmailRead),
        );
        assert!(msg.contains("transient"), "got: {msg}");
        // Must NOT direct the user to revoke their token over a transient
        // server error — that's exactly the regression we're guarding
        // against.
        assert!(
            !msg.contains("--revoke"),
            "transient 5xx should not advise --revoke: {msg}"
        );
    }

    #[test]
    fn classify_refresh_failure_other_4xx_keeps_structured_error() {
        let body = serde_json::json!({
            "error": "unauthorized_client",
            "error_description": "..."
        });
        let msg = classify_refresh_failure(
            reqwest::StatusCode::UNAUTHORIZED,
            &body,
            Some(AuthContext::Calendar),
        );
        assert!(msg.contains("unauthorized_client"), "got: {msg}");
        // Should not recommend revoking — that's only the invalid_grant
        // path.
        assert!(!msg.contains("--revoke"), "got: {msg}");
    }

    #[test]
    fn classify_refresh_failure_handles_missing_context() {
        let body = serde_json::json!({"error": "invalid_grant"});
        let msg = classify_refresh_failure(reqwest::StatusCode::BAD_REQUEST, &body, None);
        // Falls back to a placeholder rather than panicking.
        assert!(msg.contains("<scope>"), "got: {msg}");
    }

    #[test]
    fn access_token_errors_without_tokens() {
        // If the user happens to have a real token file, skip.
        if tokens_path(AuthContext::Calendar).exists() {
            return;
        }
        let err = access_token(AuthContext::Calendar).unwrap_err();
        assert!(err.contains("not authenticated"), "got: {err}");
        assert!(err.contains("--auth-google"), "got: {err}");
    }
}