aidaemon-tools 0.26.1

Ready-made tools for aidaemon agents (files, search, sandboxed shell, web, checklist); implementation crate of the aidaemon SDK, no stability promise (use it through aidaemon-sdk)
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
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
//! OAuth connections for tools: the gateway that runs authorization flows
//! (PKCE, authorization code, client credentials), stores the tokens in a
//! [`SecretStore`] and the connection rows in an [`OAuthGatewayStore`], and
//! keeps the matching bearer profile in the shared HTTP auth profiles. The
//! host serves the browser callback (`/oauth/callback` under its callback
//! base URL) and passes it to [`OAuthGateway::handle_callback`].

pub mod providers;

use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;

use base64::Engine;
use sha2::Digest;
use tokio::sync::{Mutex, RwLock, oneshot};
use tracing::{info, warn};

use aidaemon_secrets::{SecretStore, names};
use serde::Deserialize;

use crate::http_request::{HttpAuthProfile, HttpAuthType};
use crate::services::{OAuthConnection, OAuthGatewayStore, PendingOAuthFlow};

/// A custom OAuth provider as configured (`[oauth.providers.<name>]`).
#[derive(Debug, Deserialize, Clone)]
pub struct OAuthProviderConfig {
    #[serde(default)]
    pub display_name: Option<String>,
    pub auth_type: String,
    pub authorize_url: String,
    pub token_url: String,
    #[serde(default)]
    pub scopes: Vec<String>,
    #[serde(default)]
    pub allowed_domains: Vec<String>,
}

/// Timeout for OAuth flow completion (10 minutes).
const FLOW_TIMEOUT_SECS: u64 = 600;
const RECENT_FLOW_RESULT_TTL_SECS: i64 = 900;
const FLOW_EXPIRED_MESSAGE: &str = "OAuth flow expired (10 minutes). Please try again.";
const INVALID_OR_USED_FLOW_MESSAGE: &str =
    "OAuth flow expired or was already used. Please start a new connection attempt.";
const ACCESS_TOKEN_REFRESH_SKEW_SECS: i64 = 60;

fn access_token_needs_refresh(
    connection: &OAuthConnection,
    now: chrono::DateTime<chrono::Utc>,
) -> bool {
    let Some(expires_at) = connection.token_expires_at.as_deref() else {
        return false;
    };
    chrono::DateTime::parse_from_rfc3339(expires_at)
        .map(|expires_at| {
            expires_at.with_timezone(&chrono::Utc)
                <= now + chrono::Duration::seconds(ACCESS_TOKEN_REFRESH_SKEW_SECS)
        })
        // Corrupt expiry metadata must not cause an unknown-age bearer to be
        // loaded indefinitely. A bounded refresh either repairs it or leaves
        // the profile unavailable with a visible warning.
        .unwrap_or(true)
}

/// How an expired or missing bearer gets replaced without owner involvement.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CredentialRefreshPath {
    /// A stored refresh token plus client credentials.
    RefreshToken,
    /// The client-credentials grant; no user token is involved.
    ClientCredentials,
}

/// Durable readiness of an OAuth-managed credential, derived from the stored
/// connection row plus secret-store presence.
///
/// This is a read-only projection. An owner audit must never exchange a
/// refresh token to find out whether it works — providers such as X rotate
/// the refresh token on every use — so the projection states what the next
/// authenticated call (and daemon startup) will do instead of doing it.
/// Without it, list surfaces printed only a raw `expires:` timestamp, and a
/// two-hour bearer that had expired since the last call read as "missing"
/// even though `refresh_access_token_if_needed` mints a fresh one before use.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CredentialReadiness {
    /// A bearer is stored and stays valid past the refresh skew.
    Ready { valid_until: Option<String> },
    /// The bearer is expired or not stored, but a refresh path exists, so the
    /// next call mints a fresh one automatically.
    Refreshable {
        expired_at: Option<String>,
        path: CredentialRefreshPath,
    },
    /// No usable bearer and no refresh path: the owner must reconnect.
    ReauthRequired { missing: Vec<&'static str> },
}

impl CredentialReadiness {
    /// Compute readiness for a stored connection at `now` without touching
    /// the network.
    pub fn for_connection(
        connection: &OAuthConnection,
        now: chrono::DateTime<chrono::Utc>,
        secrets: &dyn SecretStore,
    ) -> Self {
        let service = connection.service.as_str();
        let stored = |suffix: &str| secrets.contains(&names::oauth(service, suffix));
        let has_access_token = stored("access_token");
        let has_refresh_token = stored("refresh_token");
        let has_client_id = stored("client_id");
        let has_client_secret = stored("client_secret");
        let client_credentials_grant = connection.auth_type == "oauth2_client_credentials";

        if has_access_token && !access_token_needs_refresh(connection, now) {
            return Self::Ready {
                valid_until: connection.token_expires_at.clone(),
            };
        }

        let expired_at = has_access_token
            .then(|| connection.token_expires_at.clone())
            .flatten();
        if has_client_id && has_client_secret {
            if client_credentials_grant {
                return Self::Refreshable {
                    expired_at,
                    path: CredentialRefreshPath::ClientCredentials,
                };
            }
            if has_refresh_token {
                return Self::Refreshable {
                    expired_at,
                    path: CredentialRefreshPath::RefreshToken,
                };
            }
        }

        let mut missing = Vec::new();
        if !has_access_token {
            missing.push("access token");
        }
        if !client_credentials_grant && !has_refresh_token {
            missing.push("refresh token");
        }
        if !has_client_id {
            missing.push("client id");
        }
        if !has_client_secret {
            missing.push("client secret");
        }
        Self::ReauthRequired { missing }
    }

    /// Stable machine-readable state name.
    pub fn state(&self) -> &'static str {
        match self {
            Self::Ready { .. } => "ready",
            Self::Refreshable { .. } => "ready-via-refresh",
            Self::ReauthRequired { .. } => "reauth-required",
        }
    }

    /// One-line readout shared by every credential list surface so an audit
    /// reads the same typed answer wherever it looks: `<state> (<detail>)`.
    pub fn describe(&self) -> String {
        let detail = match self {
            Self::Ready {
                valid_until: Some(valid_until),
            } => format!("bearer valid until {valid_until}"),
            Self::Ready { valid_until: None } => "bearer stored, no expiry recorded".to_string(),
            Self::Refreshable { expired_at, path } => {
                let bearer = match expired_at {
                    Some(expired_at) => format!("bearer expired at {expired_at}"),
                    None => "no bearer stored".to_string(),
                };
                let path = match path {
                    CredentialRefreshPath::RefreshToken => "refresh token stored",
                    CredentialRefreshPath::ClientCredentials => "client-credentials grant",
                };
                format!(
                    "{bearer}; {path}; refreshed automatically before the next authenticated call"
                )
            }
            Self::ReauthRequired { missing } if missing.is_empty() => {
                "stored bearer is expired and no refresh path exists".to_string()
            }
            Self::ReauthRequired { missing } => format!("missing: {}", missing.join(", ")),
        };
        format!("{} ({detail})", self.state())
    }
}

/// OAuth type enum.
#[derive(Debug, Clone, PartialEq)]
pub enum OAuthType {
    OAuth2Pkce,
    OAuth2AuthorizationCode,
    OAuth2ClientCredentials,
    OAuth1a,
}

/// Defines an OAuth provider's endpoints and configuration.
#[derive(Debug, Clone)]
pub struct OAuthProvider {
    pub name: String,
    pub display_name: String,
    pub auth_type: OAuthType,
    pub authorize_url: String,
    pub token_url: String,
    pub scopes: Vec<String>,
    pub allowed_domains: Vec<String>,
}

/// Result of a completed OAuth flow.
#[derive(Debug, Clone)]
#[allow(dead_code)]
pub struct OAuthFlowResult {
    pub service: String,
    pub username: Option<String>,
    pub message: String,
}

/// A pending OAuth flow awaiting callback.
struct PendingFlow {
    provider_name: String,
    code_verifier: Option<String>,
    #[allow(dead_code)]
    session_id: String,
    #[allow(dead_code)]
    created_at: chrono::DateTime<chrono::Utc>,
    result_tx: oneshot::Sender<OAuthFlowResult>,
}

/// How a browser OAuth callback ended. The callback page shows the message
/// and picks success or error styling from the variant.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum OAuthCallbackOutcome {
    /// Tokens were exchanged and stored.
    Connected { message: String },
    /// The provider denied access, the flow expired or was already used, or
    /// the token exchange failed.
    Failed { message: String },
}

impl OAuthCallbackOutcome {
    fn failed(message: impl Into<String>) -> Self {
        Self::Failed {
            message: message.into(),
        }
    }

    pub fn is_connected(&self) -> bool {
        matches!(self, Self::Connected { .. })
    }

    pub fn message(&self) -> &str {
        match self {
            Self::Connected { message } | Self::Failed { message } => message,
        }
    }
}

struct RecentFlowResult {
    outcome: OAuthCallbackOutcome,
    recorded_at: chrono::DateTime<chrono::Utc>,
}

struct ResolvedPendingFlow {
    state: String,
    provider_name: String,
    code_verifier: Option<String>,
    created_at: chrono::DateTime<chrono::Utc>,
    result_tx: Option<oneshot::Sender<OAuthFlowResult>>,
}

/// Shared HTTP auth profiles map type.
pub use crate::http_request::SharedHttpProfiles;

/// The OAuth gateway manages OAuth flows and stores tokens.
#[derive(Clone)]
pub struct OAuthGateway {
    providers: Arc<RwLock<HashMap<String, OAuthProvider>>>,
    pending_flows: Arc<RwLock<HashMap<String, PendingFlow>>>,
    recent_flow_results: Arc<RwLock<HashMap<String, RecentFlowResult>>>,
    state_store: Arc<dyn OAuthGatewayStore>,
    secrets: Arc<dyn SecretStore>,
    http_profiles: SharedHttpProfiles,
    callback_base_url: String,
    /// The command a host's owner runs to store a missing client secret,
    /// named in the error (`aidaemon keychain set`).
    secret_set_command: Option<String>,
    /// Serializes token exchanges so concurrent authenticated requests cannot
    /// race a rotating refresh token or overwrite a newer bearer with an older
    /// response.
    refresh_lock: Arc<Mutex<()>>,
}

impl OAuthGateway {
    /// A gateway keeping connections in `state_store` and tokens and client
    /// credentials in `secrets` (under [`names::oauth`]), with the browser
    /// callback at `{callback_base_url}/oauth/callback`.
    pub fn new(
        state_store: Arc<dyn OAuthGatewayStore>,
        secrets: Arc<dyn SecretStore>,
        http_profiles: SharedHttpProfiles,
        callback_base_url: String,
    ) -> Self {
        Self {
            providers: Arc::new(RwLock::new(HashMap::new())),
            pending_flows: Arc::new(RwLock::new(HashMap::new())),
            recent_flow_results: Arc::new(RwLock::new(HashMap::new())),
            state_store,
            secrets,
            http_profiles,
            callback_base_url,
            secret_set_command: None,
            refresh_lock: Arc::new(Mutex::new(())),
        }
    }

    /// Name the command that stores a missing client credential, so the error
    /// tells the owner how (`"aidaemon keychain set"`).
    pub fn with_secret_set_command(mut self, command: impl Into<String>) -> Self {
        self.secret_set_command = Some(command.into());
        self
    }

    /// Where the gateway keeps tokens and client credentials.
    pub fn secrets(&self) -> &Arc<dyn SecretStore> {
        &self.secrets
    }

    /// Register a built-in OAuth provider.
    pub async fn register_provider(&self, provider: OAuthProvider) {
        let mut providers = self.providers.write().await;
        providers.insert(provider.name.clone(), provider);
    }

    /// Register a custom provider from config.
    pub async fn register_config_provider(&self, name: &str, config: &OAuthProviderConfig) {
        let auth_type = match config.auth_type.as_str() {
            "oauth2_authorization_code" | "authorization_code" | "auth_code" => {
                OAuthType::OAuth2AuthorizationCode
            }
            "oauth2_client_credentials" | "client_credentials" => {
                OAuthType::OAuth2ClientCredentials
            }
            "oauth1a" => OAuthType::OAuth1a,
            _ => OAuthType::OAuth2Pkce,
        };
        let provider = OAuthProvider {
            name: name.to_string(),
            display_name: config
                .display_name
                .clone()
                .filter(|value| !value.trim().is_empty())
                .unwrap_or_else(|| name.to_string()),
            auth_type,
            authorize_url: config.authorize_url.clone(),
            token_url: config.token_url.clone(),
            scopes: config.scopes.clone(),
            allowed_domains: config.allowed_domains.clone(),
        };
        self.register_provider(provider).await;
    }

    /// Remove a registered OAuth provider definition from the live gateway.
    pub async fn unregister_provider(&self, name: &str) -> bool {
        let mut providers = self.providers.write().await;
        providers.remove(name).is_some()
    }

    /// List all registered providers.
    pub async fn list_providers(&self) -> Vec<(String, String)> {
        let providers = self.providers.read().await;
        providers
            .values()
            .map(|p| (p.name.clone(), p.display_name.clone()))
            .collect()
    }

    /// Get a provider by name.
    pub async fn get_provider(&self, name: &str) -> Option<OAuthProvider> {
        let providers = self.providers.read().await;
        providers.get(name).cloned()
    }

    pub fn callback_url(&self) -> String {
        Self::normalize_callback_url(&self.callback_base_url)
    }

    fn normalize_callback_url(callback_base_url: &str) -> String {
        let trimmed = callback_base_url.trim().trim_end_matches('/');
        if trimmed.ends_with("/oauth/callback") {
            trimmed.to_string()
        } else {
            format!("{trimmed}/oauth/callback")
        }
    }

    /// Generate a PKCE code verifier (43-128 chars, URL-safe).
    fn generate_code_verifier() -> String {
        use rand::RngExt;
        let mut rng = rand::rng();
        let bytes: Vec<u8> = (0..32).map(|_| rng.random()).collect();
        base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(&bytes)
    }

    /// Generate PKCE code challenge from verifier: BASE64URL(SHA256(verifier)).
    fn generate_code_challenge(verifier: &str) -> String {
        let hash = sha2::Sha256::digest(verifier.as_bytes());
        base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(hash)
    }

    /// Generate a random state parameter for CSRF protection.
    fn generate_state() -> String {
        uuid::Uuid::new_v4().to_string()
    }

    pub fn expired_flow_message() -> &'static str {
        FLOW_EXPIRED_MESSAGE
    }

    fn parse_pending_flow_created_at(raw: &str) -> Option<chrono::DateTime<chrono::Utc>> {
        chrono::DateTime::parse_from_rfc3339(raw)
            .ok()
            .map(|parsed| parsed.with_timezone(&chrono::Utc))
    }

    fn flow_cutoff() -> chrono::DateTime<chrono::Utc> {
        chrono::Utc::now() - chrono::Duration::seconds(FLOW_TIMEOUT_SECS as i64)
    }

    fn flow_is_expired(created_at: chrono::DateTime<chrono::Utc>) -> bool {
        created_at < Self::flow_cutoff()
    }

    async fn remember_recent_flow_result(&self, state: &str, outcome: OAuthCallbackOutcome) {
        let cutoff = chrono::Utc::now() - chrono::Duration::seconds(RECENT_FLOW_RESULT_TTL_SECS);
        let mut recent = self.recent_flow_results.write().await;
        recent.retain(|_, result| result.recorded_at >= cutoff);
        recent.insert(
            state.to_string(),
            RecentFlowResult {
                outcome,
                recorded_at: chrono::Utc::now(),
            },
        );
    }

    async fn recent_flow_result(&self, state: &str) -> Option<OAuthCallbackOutcome> {
        let cutoff = chrono::Utc::now() - chrono::Duration::seconds(RECENT_FLOW_RESULT_TTL_SECS);
        let mut recent = self.recent_flow_results.write().await;
        recent.retain(|_, result| result.recorded_at >= cutoff);
        recent.get(state).map(|result| result.outcome.clone())
    }

    async fn finalize_flow_result(
        &self,
        flow: ResolvedPendingFlow,
        outcome: OAuthCallbackOutcome,
    ) -> OAuthCallbackOutcome {
        self.remember_recent_flow_result(&flow.state, outcome.clone())
            .await;
        if let Some(result_tx) = flow.result_tx {
            let _ = result_tx.send(OAuthFlowResult {
                service: flow.provider_name,
                username: None,
                message: outcome.message().to_string(),
            });
        }
        outcome
    }

    async fn resolve_pending_flow(
        &self,
        state: &str,
    ) -> anyhow::Result<Option<ResolvedPendingFlow>> {
        if let Some(stored) = self.state_store.get_pending_oauth_flow(state).await? {
            self.state_store.delete_pending_oauth_flow(state).await?;
            let result_tx = {
                let mut flows = self.pending_flows.write().await;
                flows.remove(state).map(|flow| flow.result_tx)
            };
            let created_at = match Self::parse_pending_flow_created_at(&stored.created_at) {
                Some(created_at) => created_at,
                None => {
                    warn!(
                        state = %state,
                        stored_created_at = %stored.created_at,
                        "Pending OAuth flow has an invalid timestamp; treating it as expired"
                    );
                    chrono::Utc::now() - chrono::Duration::seconds((FLOW_TIMEOUT_SECS as i64) + 1)
                }
            };
            return Ok(Some(ResolvedPendingFlow {
                state: stored.state,
                provider_name: stored.service,
                code_verifier: stored.code_verifier,
                created_at,
                result_tx,
            }));
        }

        let flow = {
            let mut flows = self.pending_flows.write().await;
            flows.remove(state)
        };
        Ok(flow.map(|flow| ResolvedPendingFlow {
            state: state.to_string(),
            provider_name: flow.provider_name,
            code_verifier: flow.code_verifier,
            created_at: flow.created_at,
            result_tx: Some(flow.result_tx),
        }))
    }

    pub async fn expire_pending_flow(
        &self,
        state: &str,
        message: Option<String>,
    ) -> anyhow::Result<bool> {
        let Some(flow) = self.resolve_pending_flow(state).await? else {
            return Ok(false);
        };
        let service = flow.provider_name.clone();
        let message = message.unwrap_or_else(|| Self::expired_flow_message().to_string());
        let final_outcome = self
            .finalize_flow_result(flow, OAuthCallbackOutcome::failed(message))
            .await;
        info!(
            service = %service,
            state = %state,
            message = %final_outcome.message(),
            "Expired pending OAuth flow"
        );
        Ok(true)
    }

    /// Check if client credentials exist in the secret store for a service.
    pub fn has_credentials(&self, service: &str) -> bool {
        self.secrets.contains(&names::oauth(service, "client_id"))
    }

    fn missing_credential(&self, what: &str, key: &str) -> anyhow::Error {
        match self.secret_set_command.as_deref() {
            Some(command) => anyhow::anyhow!(
                "{} not found in keychain. Set it with: {} {}",
                what,
                command,
                key
            ),
            None => anyhow::anyhow!("{} not found in the secret store under '{}'", what, key),
        }
    }

    /// Get client credentials from the secret store.
    fn get_credentials(&self, service: &str) -> anyhow::Result<(String, String)> {
        let client_id_key = names::oauth(service, "client_id");
        let client_secret_key = names::oauth(service, "client_secret");
        let client_id = self
            .secrets
            .get(&client_id_key)
            .map_err(|_| self.missing_credential("Client ID", &client_id_key))?
            .into_exposed();
        let client_secret = self
            .secrets
            .get(&client_secret_key)
            .map_err(|_| self.missing_credential("Client secret", &client_secret_key))?
            .into_exposed();
        Ok((client_id, client_secret))
    }

    /// Start an interactive OAuth authorization flow.
    /// Returns the authorize URL and a receiver for the flow result.
    pub async fn start_oauth2_flow(
        &self,
        service: &str,
        session_id: &str,
    ) -> anyhow::Result<(String, oneshot::Receiver<OAuthFlowResult>)> {
        let provider = self
            .get_provider(service)
            .await
            .ok_or_else(|| anyhow::anyhow!("Unknown OAuth provider: {}", service))?;

        if !matches!(
            provider.auth_type,
            OAuthType::OAuth2Pkce | OAuthType::OAuth2AuthorizationCode
        ) {
            return Err(anyhow::anyhow!(
                "Provider '{}' does not support interactive OAuth authorization flows",
                service
            ));
        }

        let (client_id, _) = self.get_credentials(service)?;

        let state = Self::generate_state();
        let code_verifier = if provider.auth_type == OAuthType::OAuth2Pkce {
            Some(Self::generate_code_verifier())
        } else {
            None
        };

        let callback_url = self.callback_url();
        let scopes = provider.scopes.join(" ");

        let mut authorize_url = format!(
            "{}?response_type=code&client_id={}&redirect_uri={}&scope={}&state={}",
            provider.authorize_url,
            urlencoded(&client_id),
            urlencoded(&callback_url),
            urlencoded(&scopes),
            urlencoded(&state),
        );
        if let Some(ref verifier) = code_verifier {
            let code_challenge = Self::generate_code_challenge(verifier);
            authorize_url.push_str(&format!(
                "&code_challenge={}&code_challenge_method=S256",
                urlencoded(&code_challenge)
            ));
        }

        let (result_tx, result_rx) = oneshot::channel();
        let created_at = chrono::Utc::now();

        let flow = PendingFlow {
            provider_name: service.to_string(),
            code_verifier,
            session_id: session_id.to_string(),
            created_at,
            result_tx,
        };

        let pending_flow = PendingOAuthFlow {
            state: state.clone(),
            service: service.to_string(),
            code_verifier: flow.code_verifier.clone(),
            session_id: session_id.to_string(),
            created_at: created_at.to_rfc3339(),
        };
        self.state_store
            .save_pending_oauth_flow(&pending_flow)
            .await?;

        {
            let mut flows = self.pending_flows.write().await;
            flows.insert(state.clone(), flow);
        }

        Ok((authorize_url, result_rx))
    }

    fn oauth_type_label(auth_type: &OAuthType) -> &'static str {
        match auth_type {
            OAuthType::OAuth2Pkce => "oauth2_pkce",
            OAuthType::OAuth2AuthorizationCode => "oauth2_authorization_code",
            OAuthType::OAuth2ClientCredentials => "oauth2_client_credentials",
            OAuthType::OAuth1a => "oauth1a",
        }
    }

    async fn store_connected_bearer_profile(
        &self,
        service: &str,
        provider: &OAuthProvider,
        access_token: &str,
        refresh_token: Option<&str>,
        expires_in: Option<u64>,
        preserve_account_binding: bool,
    ) -> anyhow::Result<String> {
        let at_key = names::oauth(service, "access_token");
        self.secrets.set(&at_key, access_token)?;

        if let Some(rt) = refresh_token {
            let rt_key = names::oauth(service, "refresh_token");
            self.secrets.set(&rt_key, rt)?;
        }

        let expires_at = expires_in
            .map(|secs| (chrono::Utc::now() + chrono::Duration::seconds(secs as i64)).to_rfc3339());

        let account_id = if preserve_account_binding {
            self.state_store
                .get_oauth_connection(service)
                .await?
                .and_then(|connection| connection.account_id)
        } else {
            None
        };
        let conn = OAuthConnection {
            id: 0,
            service: service.to_string(),
            auth_type: Self::oauth_type_label(&provider.auth_type).to_string(),
            username: None,
            account_id: account_id.clone(),
            scopes: serde_json::to_string(&provider.scopes).unwrap_or_default(),
            token_expires_at: expires_at,
            created_at: chrono::Utc::now().to_rfc3339(),
            updated_at: chrono::Utc::now().to_rfc3339(),
        };
        self.state_store.save_oauth_connection(&conn).await?;

        let profile = HttpAuthProfile {
            auth_type: HttpAuthType::Bearer,
            allowed_domains: provider.allowed_domains.clone(),
            api_key: None,
            api_secret: None,
            access_token: None,
            access_token_secret: None,
            user_id: account_id,
            token: Some(access_token.to_string()),
            header_name: None,
            header_value: None,
            username: None,
            password: None,
        };
        {
            let mut profiles = self.http_profiles.write().await;
            profiles.insert(service.to_string(), profile);
        }

        Ok(format!(
            "Connected to {}! Use `http_request` with auth_profile=\"{}\" to make API calls.",
            provider.display_name, service
        ))
    }

    async fn exchange_client_credentials_token(
        &self,
        service: &str,
        provider: &OAuthProvider,
    ) -> anyhow::Result<(String, Option<String>, Option<u64>)> {
        let (client_id, client_secret) = self.get_credentials(service)?;

        let mut params = HashMap::new();
        params.insert("grant_type", "client_credentials".to_string());
        if !provider.scopes.is_empty() {
            params.insert("scope", provider.scopes.join(" "));
        }

        let client = reqwest::Client::new();
        let resp = client
            .post(&provider.token_url)
            .basic_auth(&client_id, Some(&client_secret))
            .form(&params)
            .timeout(Duration::from_secs(30))
            .send()
            .await
            .map_err(|e| anyhow::anyhow!("Client credentials token request failed: {}", e))?;

        if !resp.status().is_success() {
            let status = resp.status();
            let body = resp.text().await.unwrap_or_default();
            anyhow::bail!(
                "Client credentials token exchange failed (HTTP {}): {}",
                status,
                body
            );
        }

        let token_data: serde_json::Value = resp
            .json()
            .await
            .map_err(|e| anyhow::anyhow!("Failed to parse token response: {}", e))?;

        let access_token = token_data["access_token"]
            .as_str()
            .ok_or_else(|| anyhow::anyhow!("No access_token in response"))?
            .to_string();
        let refresh_token = token_data["refresh_token"]
            .as_str()
            .map(ToString::to_string);
        let expires_in = token_data["expires_in"].as_u64();
        Ok((access_token, refresh_token, expires_in))
    }

    pub async fn connect_client_credentials(&self, service: &str) -> anyhow::Result<String> {
        let provider = self
            .get_provider(service)
            .await
            .ok_or_else(|| anyhow::anyhow!("Unknown OAuth provider: {}", service))?;

        anyhow::ensure!(
            provider.auth_type == OAuthType::OAuth2ClientCredentials,
            "Provider '{}' is not configured for oauth2_client_credentials",
            service
        );

        let (access_token, refresh_token, expires_in) = self
            .exchange_client_credentials_token(service, &provider)
            .await?;
        self.store_connected_bearer_profile(
            service,
            &provider,
            &access_token,
            refresh_token.as_deref(),
            expires_in,
            false,
        )
        .await
    }

    /// Handle an OAuth callback from the browser redirect.
    pub async fn handle_callback(
        &self,
        state: &str,
        code: Option<&str>,
        error: Option<&str>,
    ) -> anyhow::Result<OAuthCallbackOutcome> {
        let Some(flow) = self.resolve_pending_flow(state).await? else {
            if let Some(outcome) = self.recent_flow_result(state).await {
                return Ok(outcome);
            }
            return Ok(OAuthCallbackOutcome::failed(INVALID_OR_USED_FLOW_MESSAGE));
        };

        if Self::flow_is_expired(flow.created_at) {
            return Ok(self
                .finalize_flow_result(
                    flow,
                    OAuthCallbackOutcome::failed(Self::expired_flow_message()),
                )
                .await);
        }

        // Check for error from provider
        if let Some(err) = error {
            let msg = format!("OAuth authorization denied: {}", err);
            return Ok(self
                .finalize_flow_result(flow, OAuthCallbackOutcome::failed(msg))
                .await);
        }

        let service = flow.provider_name.clone();
        let outcome = match async {
            let code = code.ok_or_else(|| anyhow::anyhow!("No authorization code in callback"))?;

            let provider = self
                .get_provider(&flow.provider_name)
                .await
                .ok_or_else(|| anyhow::anyhow!("Provider '{}' not found", flow.provider_name))?;

            let (client_id, client_secret) = self.get_credentials(&flow.provider_name)?;
            let callback_url = self.callback_url();

            let mut params = HashMap::new();
            params.insert("grant_type", "authorization_code".to_string());
            params.insert("code", code.to_string());
            params.insert("redirect_uri", callback_url);

            if let Some(ref verifier) = flow.code_verifier {
                params.insert("code_verifier", verifier.clone());
            }

            let client = reqwest::Client::new();
            let resp = client
                .post(&provider.token_url)
                .basic_auth(&client_id, Some(&client_secret))
                .form(&params)
                .timeout(Duration::from_secs(30))
                .send()
                .await
                .map_err(|e| anyhow::anyhow!("Token exchange request failed: {}", e))?;

            if !resp.status().is_success() {
                let status = resp.status();
                let body = resp.text().await.unwrap_or_default();
                anyhow::bail!("Token exchange failed (HTTP {}): {}", status, body);
            }

            let token_data: serde_json::Value = resp
                .json()
                .await
                .map_err(|e| anyhow::anyhow!("Failed to parse token response: {}", e))?;

            let access_token = token_data["access_token"]
                .as_str()
                .ok_or_else(|| anyhow::anyhow!("No access_token in response"))?;
            let refresh_token = token_data["refresh_token"].as_str();
            let expires_in = token_data["expires_in"].as_u64();

            self.store_connected_bearer_profile(
                &flow.provider_name,
                &provider,
                access_token,
                refresh_token,
                expires_in,
                false,
            )
            .await
        }
        .await
        {
            Ok(message) => {
                info!(service = %service, "OAuth connection established");
                OAuthCallbackOutcome::Connected { message }
            }
            Err(err) => {
                warn!(
                    service = %service,
                    state = %state,
                    error = %err,
                    "OAuth callback failed"
                );
                OAuthCallbackOutcome::failed(err.to_string())
            }
        };

        Ok(self.finalize_flow_result(flow, outcome).await)
    }

    /// Remove expired pending flows (older than 10 minutes).
    pub async fn cleanup_expired_flows(&self) {
        let cutoff = Self::flow_cutoff();
        let mut expired_states = Vec::new();
        match self.state_store.list_pending_oauth_flows().await {
            Ok(flows) => {
                for flow in flows {
                    let created_at = Self::parse_pending_flow_created_at(&flow.created_at)
                        .unwrap_or_else(|| {
                            warn!(
                                state = %flow.state,
                                stored_created_at = %flow.created_at,
                                "Pending OAuth flow has an invalid timestamp; expiring it"
                            );
                            chrono::Utc::now()
                                - chrono::Duration::seconds((FLOW_TIMEOUT_SECS as i64) + 1)
                        });
                    if created_at < cutoff {
                        expired_states.push(flow.state);
                    }
                }
            }
            Err(err) => {
                warn!(error = %err, "Failed to enumerate pending OAuth flows for cleanup");
            }
        }

        let in_memory_expired: Vec<String> = {
            let flows = self.pending_flows.read().await;
            flows
                .iter()
                .filter(|(_, flow)| flow.created_at < cutoff)
                .map(|(state, _)| state.clone())
                .collect()
        };
        for state in in_memory_expired {
            if !expired_states.contains(&state) {
                expired_states.push(state);
            }
        }

        for state in &expired_states {
            if let Err(err) = self
                .expire_pending_flow(state, Some(Self::expired_flow_message().to_string()))
                .await
            {
                warn!(state = %state, error = %err, "Failed to expire pending OAuth flow");
            }
        }

        if !expired_states.is_empty() {
            info!(
                count = expired_states.len(),
                "Cleaned up expired OAuth flows"
            );
        }
    }

    /// Restore connections from DB + keychain on startup.
    pub async fn restore_connections(&self) {
        match self.state_store.list_oauth_connections().await {
            Ok(connections) => {
                for conn in connections {
                    if access_token_needs_refresh(&conn, chrono::Utc::now()) {
                        match self.refresh_token(&conn.service).await {
                            Ok(_) => {
                                info!(
                                    service = %conn.service,
                                    "Restored OAuth connection via proactive token refresh"
                                );
                            }
                            Err(error) => {
                                warn!(
                                    service = %conn.service,
                                    %error,
                                    "Expired OAuth connection could not be refreshed; stale access token was not loaded"
                                );
                            }
                        }
                        continue;
                    }
                    let at_key = names::oauth(&conn.service, "access_token");
                    match self.secrets.get(&at_key) {
                        Ok(token) => {
                            // Look up provider for allowed_domains
                            let allowed_domains = self
                                .get_provider(&conn.service)
                                .await
                                .map(|p| p.allowed_domains.clone())
                                .unwrap_or_default();

                            let profile = HttpAuthProfile {
                                auth_type: HttpAuthType::Bearer,
                                allowed_domains,
                                api_key: None,
                                api_secret: None,
                                access_token: None,
                                access_token_secret: None,
                                user_id: conn.account_id.clone(),
                                token: Some(token.into_exposed()),
                                header_name: None,
                                header_value: None,
                                username: None,
                                password: None,
                            };
                            {
                                let mut profiles = self.http_profiles.write().await;
                                profiles.insert(conn.service.clone(), profile);
                            }
                            info!(service = %conn.service, "Restored OAuth connection");
                        }
                        Err(_) => {
                            // The stored access token is unavailable — e.g.
                            // NO_KEYCHAIN mode reading a .env that only carries
                            // the refresh token + client creds, or an
                            // expired/missing bearer. Mint a fresh one from the
                            // refresh token instead of giving up;
                            // refresh_token() populates the in-memory http
                            // profile on success.
                            match self.refresh_token(&conn.service).await {
                                Ok(_) => {
                                    info!(
                                        service = %conn.service,
                                        "Restored OAuth connection via token refresh (access token was unavailable)"
                                    );
                                }
                                Err(e) => {
                                    warn!(
                                        service = %conn.service,
                                        error = %e,
                                        "OAuth connection in DB but access token unavailable and refresh failed"
                                    );
                                }
                            }
                        }
                    }
                }
            }
            Err(e) => {
                warn!("Failed to restore OAuth connections: {}", e);
            }
        }
    }

    /// Refresh the bearer only when its durable expiry is inside the safety
    /// window. The expiry is re-read while holding the refresh lock so a burst
    /// of requests causes at most one token exchange.
    pub async fn refresh_access_token_if_needed(&self, service: &str) -> anyhow::Result<bool> {
        let _refresh_guard = self.refresh_lock.lock().await;
        let Some(connection) = self.state_store.get_oauth_connection(service).await? else {
            return Ok(false);
        };
        if !access_token_needs_refresh(&connection, chrono::Utc::now()) {
            return Ok(false);
        }

        self.refresh_token_locked(service).await?;
        Ok(true)
    }

    /// Refresh an access token using the refresh token.
    pub async fn refresh_token(&self, service: &str) -> anyhow::Result<String> {
        let _refresh_guard = self.refresh_lock.lock().await;
        self.refresh_token_locked(service).await
    }

    async fn refresh_token_locked(&self, service: &str) -> anyhow::Result<String> {
        let provider = self
            .get_provider(service)
            .await
            .ok_or_else(|| anyhow::anyhow!("Unknown OAuth provider: {}", service))?;

        if provider.auth_type == OAuthType::OAuth2ClientCredentials {
            let (access_token, refresh_token, expires_in) = self
                .exchange_client_credentials_token(service, &provider)
                .await?;
            self.store_connected_bearer_profile(
                service,
                &provider,
                &access_token,
                refresh_token.as_deref(),
                expires_in,
                true,
            )
            .await?;
            info!(service = %service, "OAuth client-credentials token refreshed");
            return Ok(format!("Token refreshed for {}", service));
        }

        let rt_key = names::oauth(service, "refresh_token");
        let refresh_token = self
            .secrets
            .get(&rt_key)
            .map_err(|_| anyhow::anyhow!("No refresh token found for '{}'", service))?
            .into_exposed();

        let (client_id, client_secret) = self.get_credentials(service)?;

        let mut params = HashMap::new();
        params.insert("grant_type", "refresh_token".to_string());
        params.insert("refresh_token", refresh_token);

        let client = reqwest::Client::new();
        let resp = client
            .post(&provider.token_url)
            .basic_auth(&client_id, Some(&client_secret))
            .form(&params)
            .timeout(Duration::from_secs(30))
            .send()
            .await
            .map_err(|e| anyhow::anyhow!("Refresh request failed: {}", e))?;

        if !resp.status().is_success() {
            let body = resp.text().await.unwrap_or_default();
            return Err(anyhow::anyhow!("Token refresh failed: {}", body));
        }

        let token_data: serde_json::Value = resp.json().await?;
        let new_access_token = token_data["access_token"]
            .as_str()
            .ok_or_else(|| anyhow::anyhow!("No access_token in refresh response"))?;

        // Store new access token
        let at_key = names::oauth(service, "access_token");
        self.secrets.set(&at_key, new_access_token)?;

        // Update refresh token if a new one was issued
        if let Some(new_rt) = token_data["refresh_token"].as_str() {
            let rt_key = names::oauth(service, "refresh_token");
            self.secrets.set(&rt_key, new_rt)?;
        }

        // Update expiry
        let expires_in = token_data["expires_in"].as_u64();
        let expires_at = expires_in
            .map(|secs| (chrono::Utc::now() + chrono::Duration::seconds(secs as i64)).to_rfc3339());
        self.state_store
            .update_oauth_token_expiry(service, expires_at.as_deref())
            .await?;

        let account_id = self
            .state_store
            .get_oauth_connection(service)
            .await?
            .and_then(|connection| connection.account_id);

        // Update in-memory profile while preserving the independently verified
        // remote identity. Token refresh must never discard mandate binding.
        {
            let mut profiles = self.http_profiles.write().await;
            let had_profile = profiles.contains_key(service);
            profiles.insert(
                service.to_string(),
                HttpAuthProfile {
                    auth_type: HttpAuthType::Bearer,
                    allowed_domains: provider.allowed_domains.clone(),
                    api_key: None,
                    api_secret: None,
                    access_token: None,
                    access_token_secret: None,
                    user_id: account_id,
                    token: Some(new_access_token.to_string()),
                    header_name: None,
                    header_value: None,
                    username: None,
                    password: None,
                },
            );
            if !had_profile {
                info!(
                    service = %service,
                    "Rebuilt missing OAuth auth profile during token refresh"
                );
            }
        }

        info!(service = %service, "OAuth token refreshed");
        Ok(format!("Token refreshed for {}", service))
    }

    /// Persist a verified remote identity and apply it to the live HTTP auth
    /// profile. Callers must prove the identity through the provider before
    /// invoking this commit point.
    pub async fn bind_account_id(&self, service: &str, account_id: &str) -> anyhow::Result<()> {
        anyhow::ensure!(
            self.state_store
                .get_oauth_connection(service)
                .await?
                .is_some(),
            "No OAuth connection found for '{}'",
            service
        );
        {
            let profiles = self.http_profiles.read().await;
            anyhow::ensure!(
                profiles.contains_key(service),
                "OAuth profile '{}' is not loaded; reconnect or refresh it before binding identity",
                service
            );
        }
        anyhow::ensure!(
            self.state_store
                .update_oauth_account_id(service, Some(account_id))
                .await?,
            "OAuth connection '{}' disappeared before identity binding",
            service
        );
        let mut profiles = self.http_profiles.write().await;
        let profile = profiles
            .get_mut(service)
            .ok_or_else(|| anyhow::anyhow!("OAuth profile '{}' disappeared", service))?;
        profile.user_id = Some(account_id.to_string());
        info!(service = %service, account_id = %account_id, "Bound verified OAuth account identity");
        Ok(())
    }

    /// Remove an OAuth connection: delete from DB, keychain, and profiles.
    pub async fn remove_connection(&self, service: &str) -> anyhow::Result<String> {
        // Remove from DB
        self.state_store.delete_oauth_connection(service).await?;

        // Remove tokens from keychain (best effort)
        for suffix in &["access_token", "refresh_token"] {
            let key = names::oauth(service, suffix);
            let _ = self.secrets.delete(&key);
        }

        // Remove from in-memory profiles
        {
            let mut profiles = self.http_profiles.write().await;
            profiles.remove(service);
        }

        info!(service = %service, "OAuth connection removed");
        Ok(format!("Disconnected from {}", service))
    }

    /// Get the flow timeout in seconds (for tool to know how long to wait).
    pub fn flow_timeout() -> Duration {
        Duration::from_secs(FLOW_TIMEOUT_SECS)
    }
}

/// Simple URL-encoding for query parameter values.
fn urlencoded(s: &str) -> String {
    let mut result = String::with_capacity(s.len() * 2);
    for byte in s.bytes() {
        match byte {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
                result.push(byte as char);
            }
            _ => {
                result.push_str(&format!("%{:02X}", byte));
            }
        }
    }
    result
}

#[async_trait::async_trait]
impl crate::http_request::OAuthTokens for OAuthGateway {
    async fn managed_scopes(&self, profile: &str) -> Option<Vec<String>> {
        self.get_provider(profile)
            .await
            .map(|provider| provider.scopes)
    }

    async fn refresh_token(&self, profile: &str) -> anyhow::Result<String> {
        OAuthGateway::refresh_token(self, profile).await
    }

    async fn refresh_access_token_if_needed(&self, profile: &str) -> anyhow::Result<bool> {
        OAuthGateway::refresh_access_token_if_needed(self, profile).await
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashMap;
    use std::net::SocketAddr;
    use std::sync::Arc;

    use axum::{Json, Router, extract::Form, routing::post};
    use tempfile::NamedTempFile;
    use tokio::net::TcpListener;

    use aidaemon_secrets::EnvSecretStore;

    use crate::services::InMemoryOAuthStore;

    /// Secrets in a fresh env file, so a test can write the file directly.
    struct TestSecrets {
        env_file: NamedTempFile,
        store: Arc<dyn SecretStore>,
    }

    impl TestSecrets {
        fn new() -> Self {
            let env_file = NamedTempFile::new().expect("create env file");
            let store = Arc::new(EnvSecretStore::at(env_file.path()));
            Self { env_file, store }
        }

        fn env_file_path(&self) -> &std::path::Path {
            self.env_file.path()
        }
    }

    fn state_from_authorize_url(authorize_url: &str) -> String {
        reqwest::Url::parse(authorize_url)
            .unwrap()
            .query_pairs()
            .find_map(|(key, value)| (key == "state").then(|| value.into_owned()))
            .unwrap()
    }

    async fn test_gateway(secrets: &TestSecrets) -> anyhow::Result<OAuthGateway> {
        let state = Arc::new(InMemoryOAuthStore::new());
        let profiles: SharedHttpProfiles = Arc::new(RwLock::new(HashMap::new()));
        Ok(OAuthGateway::new(
            state as Arc<dyn OAuthGatewayStore>,
            secrets.store.clone(),
            profiles,
            "http://localhost:8080".to_string(),
        ))
    }

    #[test]
    fn startup_refreshes_expired_or_invalid_expiry_but_preserves_nonexpiring_tokens() {
        let now = chrono::Utc::now();
        let mut connection = OAuthConnection {
            id: 0,
            service: "twitter".to_string(),
            auth_type: "oauth2_pkce".to_string(),
            username: None,
            account_id: Some("synthetic-account".to_string()),
            scopes: r#"["tweet.read"]"#.to_string(),
            token_expires_at: Some((now - chrono::Duration::minutes(1)).to_rfc3339()),
            created_at: now.to_rfc3339(),
            updated_at: now.to_rfc3339(),
        };
        assert!(access_token_needs_refresh(&connection, now));
        connection.token_expires_at = Some("not-a-timestamp".to_string());
        assert!(access_token_needs_refresh(&connection, now));
        connection.token_expires_at = Some((now + chrono::Duration::minutes(5)).to_rfc3339());
        assert!(!access_token_needs_refresh(&connection, now));
        connection.token_expires_at = None;
        assert!(!access_token_needs_refresh(&connection, now));
    }

    #[test]
    fn test_pkce_code_verifier_length() {
        let verifier = OAuthGateway::generate_code_verifier();
        assert!(verifier.len() >= 43);
        assert!(verifier.len() <= 128);
    }

    #[test]
    fn test_pkce_code_challenge_is_deterministic() {
        let verifier = "test_verifier_string";
        let c1 = OAuthGateway::generate_code_challenge(verifier);
        let c2 = OAuthGateway::generate_code_challenge(verifier);
        assert_eq!(c1, c2);
    }

    #[test]
    fn test_pkce_code_challenge_uses_sha256() {
        // Known test vector: SHA256("test") = base64url encoded
        let challenge = OAuthGateway::generate_code_challenge("test");
        // SHA256("test") = 9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08
        // base64url: n4bQgYhMfWWaL-qgxVrQFaO_TxsrC4Is0V1sFbDwCgg
        assert_eq!(challenge, "n4bQgYhMfWWaL-qgxVrQFaO_TxsrC4Is0V1sFbDwCgg");
    }

    #[test]
    fn test_state_parameter_uniqueness() {
        let s1 = OAuthGateway::generate_state();
        let s2 = OAuthGateway::generate_state();
        assert_ne!(s1, s2);
        // Should be a valid UUID
        assert!(uuid::Uuid::parse_str(&s1).is_ok());
    }

    #[tokio::test]
    async fn bind_account_id_updates_persistence_and_live_profile() {
        let gateway = test_gateway(&TestSecrets::new()).await.unwrap();
        gateway
            .state_store
            .save_oauth_connection(&OAuthConnection {
                id: 0,
                service: "synthetic".to_string(),
                auth_type: "oauth2_pkce".to_string(),
                username: None,
                account_id: None,
                scopes: "[]".to_string(),
                token_expires_at: None,
                created_at: chrono::Utc::now().to_rfc3339(),
                updated_at: chrono::Utc::now().to_rfc3339(),
            })
            .await
            .unwrap();
        gateway.http_profiles.write().await.insert(
            "synthetic".to_string(),
            HttpAuthProfile {
                auth_type: HttpAuthType::Bearer,
                allowed_domains: vec!["api.example.test".to_string()],
                api_key: None,
                api_secret: None,
                access_token: None,
                access_token_secret: None,
                user_id: None,
                token: Some("synthetic-token".to_string()),
                header_name: None,
                header_value: None,
                username: None,
                password: None,
            },
        );

        gateway
            .bind_account_id("synthetic", "stable-remote-account")
            .await
            .unwrap();

        let stored = gateway
            .state_store
            .get_oauth_connection("synthetic")
            .await
            .unwrap()
            .unwrap();
        assert_eq!(stored.account_id.as_deref(), Some("stable-remote-account"));
        let profiles = gateway.http_profiles.read().await;
        assert_eq!(
            profiles
                .get("synthetic")
                .and_then(|profile| profile.user_id.as_deref()),
            Some("stable-remote-account")
        );
    }

    #[test]
    fn test_urlencoded() {
        assert_eq!(urlencoded("hello"), "hello");
        assert_eq!(urlencoded("hello world"), "hello%20world");
        assert_eq!(urlencoded("a=b&c=d"), "a%3Db%26c%3Dd");
        assert_eq!(
            urlencoded("https://example.com"),
            "https%3A%2F%2Fexample.com"
        );
    }

    #[test]
    fn test_callback_url_accepts_base_url() {
        assert_eq!(
            OAuthGateway::normalize_callback_url("http://localhost:8080"),
            "http://localhost:8080/oauth/callback"
        );
    }

    #[test]
    fn test_callback_url_accepts_full_callback_url() {
        assert_eq!(
            OAuthGateway::normalize_callback_url("http://localhost:8080/oauth/callback"),
            "http://localhost:8080/oauth/callback"
        );
    }

    #[tokio::test]
    async fn authorization_code_flow_omits_pkce_challenge() {
        let isolation = TestSecrets::new();
        let gateway = test_gateway(&isolation).await.unwrap();
        gateway
            .register_provider(OAuthProvider {
                name: "linear".to_string(),
                display_name: "Linear".to_string(),
                auth_type: OAuthType::OAuth2AuthorizationCode,
                authorize_url: "https://linear.app/oauth/authorize".to_string(),
                token_url: "https://api.linear.app/oauth/token".to_string(),
                scopes: vec!["read".to_string()],
                allowed_domains: vec!["api.linear.app".to_string()],
            })
            .await;

        std::fs::write(
            isolation.env_file_path(),
            "OAUTH_LINEAR_CLIENT_ID=abc\nOAUTH_LINEAR_CLIENT_SECRET=def\n",
        )
        .unwrap();
        let (authorize_url, _) = gateway.start_oauth2_flow("linear", "test").await.unwrap();

        assert!(authorize_url.contains("response_type=code"));
        assert!(!authorize_url.contains("code_challenge="));
    }

    #[tokio::test]
    async fn client_credentials_flow_stores_connection_and_profile() {
        let isolation = TestSecrets::new();

        async fn token_handler(
            Form(form): Form<HashMap<String, String>>,
        ) -> Json<serde_json::Value> {
            assert_eq!(
                form.get("grant_type").map(String::as_str),
                Some("client_credentials")
            );
            Json(serde_json::json!({
                "access_token": "test-access",
                "expires_in": 3600
            }))
        }

        let app = Router::new().route("/oauth/token", post(token_handler));
        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr: SocketAddr = listener.local_addr().unwrap();
        tokio::spawn(async move {
            let _ = axum::serve(listener, app).await;
        });

        let gateway = test_gateway(&isolation).await.unwrap();
        gateway
            .register_provider(OAuthProvider {
                name: "service".to_string(),
                display_name: "Service".to_string(),
                auth_type: OAuthType::OAuth2ClientCredentials,
                authorize_url: String::new(),
                token_url: format!("http://{}/oauth/token", addr),
                scopes: vec!["read".to_string()],
                allowed_domains: vec!["api.example.com".to_string()],
            })
            .await;

        std::fs::write(
            isolation.env_file_path(),
            "OAUTH_SERVICE_CLIENT_ID=abc\nOAUTH_SERVICE_CLIENT_SECRET=def\n",
        )
        .unwrap();
        let result = gateway.connect_client_credentials("service").await.unwrap();

        assert!(result.contains("Connected to Service"));
        let conn = gateway
            .state_store
            .get_oauth_connection("service")
            .await
            .unwrap()
            .unwrap();
        assert_eq!(conn.auth_type, "oauth2_client_credentials");
        let profiles = gateway.http_profiles.read().await;
        let profile = profiles.get("service").unwrap();
        assert_eq!(profile.token.as_deref(), Some("test-access"));
    }

    #[tokio::test]
    async fn callback_survives_restart_using_persisted_pending_flow() {
        let isolation = TestSecrets::new();

        async fn token_handler(
            Form(form): Form<HashMap<String, String>>,
        ) -> Json<serde_json::Value> {
            assert_eq!(
                form.get("grant_type").map(String::as_str),
                Some("authorization_code")
            );
            assert_eq!(form.get("code").map(String::as_str), Some("auth-code"));
            assert!(form.contains_key("code_verifier"));
            Json(serde_json::json!({
                "access_token": "restart-safe-token",
                "refresh_token": "refresh-123",
                "expires_in": 3600
            }))
        }

        let app = Router::new().route("/oauth/token", post(token_handler));
        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr: SocketAddr = listener.local_addr().unwrap();
        tokio::spawn(async move {
            let _ = axum::serve(listener, app).await;
        });

        let gateway = test_gateway(&isolation).await.unwrap();
        gateway
            .register_provider(OAuthProvider {
                name: "linear".to_string(),
                display_name: "Linear".to_string(),
                auth_type: OAuthType::OAuth2Pkce,
                authorize_url: "https://linear.app/oauth/authorize".to_string(),
                token_url: format!("http://{addr}/oauth/token"),
                scopes: vec!["read".to_string()],
                allowed_domains: vec!["api.linear.app".to_string()],
            })
            .await;

        std::fs::write(
            isolation.env_file_path(),
            "OAUTH_LINEAR_CLIENT_ID=abc\nOAUTH_LINEAR_CLIENT_SECRET=def\n",
        )
        .unwrap();
        let (authorize_url, _result_rx) =
            gateway.start_oauth2_flow("linear", "test").await.unwrap();
        let state = state_from_authorize_url(&authorize_url);
        {
            let mut flows = gateway.pending_flows.write().await;
            flows.clear();
        }

        let result = gateway
            .handle_callback(&state, Some("auth-code"), None)
            .await
            .unwrap();

        assert!(result.is_connected());
        assert!(result.message().contains("Connected to Linear"));
        assert!(
            gateway
                .state_store
                .get_pending_oauth_flow(&state)
                .await
                .unwrap()
                .is_none()
        );
        assert!(
            gateway
                .state_store
                .get_oauth_connection("linear")
                .await
                .unwrap()
                .is_some()
        );
    }

    #[tokio::test]
    async fn callback_refresh_reuses_recent_result_message() {
        let isolation = TestSecrets::new();

        let gateway = test_gateway(&isolation).await.unwrap();
        gateway
            .register_provider(OAuthProvider {
                name: "linear".to_string(),
                display_name: "Linear".to_string(),
                auth_type: OAuthType::OAuth2AuthorizationCode,
                authorize_url: "https://linear.app/oauth/authorize".to_string(),
                token_url: "https://api.linear.app/oauth/token".to_string(),
                scopes: vec!["read".to_string()],
                allowed_domains: vec!["api.linear.app".to_string()],
            })
            .await;

        std::fs::write(
            isolation.env_file_path(),
            "OAUTH_LINEAR_CLIENT_ID=abc\nOAUTH_LINEAR_CLIENT_SECRET=def\n",
        )
        .unwrap();
        let (authorize_url, _result_rx) =
            gateway.start_oauth2_flow("linear", "test").await.unwrap();
        let state = state_from_authorize_url(&authorize_url);
        let first = gateway
            .handle_callback(&state, None, Some("access_denied"))
            .await
            .unwrap();
        let second = gateway.handle_callback(&state, None, None).await.unwrap();

        assert_eq!(
            first,
            OAuthCallbackOutcome::Failed {
                message: "OAuth authorization denied: access_denied".to_string()
            }
        );
        assert_eq!(second, first);
    }

    #[tokio::test]
    async fn callback_without_code_is_a_failed_outcome() {
        let isolation = TestSecrets::new();

        let gateway = test_gateway(&isolation).await.unwrap();
        gateway
            .register_provider(OAuthProvider {
                name: "linear".to_string(),
                display_name: "Linear".to_string(),
                auth_type: OAuthType::OAuth2AuthorizationCode,
                authorize_url: "https://linear.app/oauth/authorize".to_string(),
                token_url: "https://api.linear.app/oauth/token".to_string(),
                scopes: vec!["read".to_string()],
                allowed_domains: vec!["api.linear.app".to_string()],
            })
            .await;

        std::fs::write(
            isolation.env_file_path(),
            "OAUTH_LINEAR_CLIENT_ID=abc\nOAUTH_LINEAR_CLIENT_SECRET=def\n",
        )
        .unwrap();
        let (authorize_url, _result_rx) =
            gateway.start_oauth2_flow("linear", "test").await.unwrap();
        let state = state_from_authorize_url(&authorize_url);

        // The error text says nothing like "failed" or "denied"; the outcome
        // is still a failure because the variant says so.
        let outcome = gateway.handle_callback(&state, None, None).await.unwrap();
        assert_eq!(
            outcome,
            OAuthCallbackOutcome::Failed {
                message: "No authorization code in callback".to_string()
            }
        );
        let unknown = gateway
            .handle_callback("never-issued", Some("code"), None)
            .await
            .unwrap();
        assert!(!unknown.is_connected());
    }

    #[tokio::test]
    async fn cleanup_expires_persisted_flows_and_keeps_callback_message() {
        let gateway = test_gateway(&TestSecrets::new()).await.unwrap();
        gateway
            .state_store
            .save_pending_oauth_flow(&PendingOAuthFlow {
                state: "expired-state".to_string(),
                service: "linear".to_string(),
                code_verifier: Some("verifier".to_string()),
                session_id: "session-1".to_string(),
                created_at: (chrono::Utc::now()
                    - chrono::Duration::seconds((FLOW_TIMEOUT_SECS as i64) + 30))
                .to_rfc3339(),
            })
            .await
            .unwrap();

        gateway.cleanup_expired_flows().await;

        assert!(
            gateway
                .state_store
                .get_pending_oauth_flow("expired-state")
                .await
                .unwrap()
                .is_none()
        );
        let outcome = gateway
            .handle_callback("expired-state", Some("unused"), None)
            .await
            .unwrap();
        assert!(!outcome.is_connected());
        assert_eq!(outcome.message(), OAuthGateway::expired_flow_message());
    }

    #[tokio::test]
    async fn refresh_token_rebuilds_missing_http_profile() {
        let isolation = TestSecrets::new();

        async fn token_handler(
            Form(form): Form<HashMap<String, String>>,
        ) -> Json<serde_json::Value> {
            assert_eq!(
                form.get("grant_type").map(String::as_str),
                Some("refresh_token")
            );
            assert_eq!(
                form.get("refresh_token").map(String::as_str),
                Some("refresh-123")
            );
            Json(serde_json::json!({
                "access_token": "refreshed-access",
                "expires_in": 3600
            }))
        }

        let app = Router::new().route("/oauth/token", post(token_handler));
        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr: SocketAddr = listener.local_addr().unwrap();
        tokio::spawn(async move {
            let _ = axum::serve(listener, app).await;
        });

        let gateway = test_gateway(&isolation).await.unwrap();
        gateway
            .register_provider(OAuthProvider {
                name: "twitter".to_string(),
                display_name: "Twitter/X".to_string(),
                auth_type: OAuthType::OAuth2Pkce,
                authorize_url: "https://twitter.com/i/oauth2/authorize".to_string(),
                token_url: format!("http://{addr}/oauth/token"),
                scopes: vec!["tweet.read".to_string()],
                allowed_domains: vec!["api.twitter.com".to_string(), "api.x.com".to_string()],
            })
            .await;

        std::fs::write(
            isolation.env_file_path(),
            "OAUTH_TWITTER_CLIENT_ID=abc\nOAUTH_TWITTER_CLIENT_SECRET=def\nOAUTH_TWITTER_REFRESH_TOKEN=refresh-123\n",
        )
        .unwrap();
        gateway
            .state_store
            .save_oauth_connection(&OAuthConnection {
                id: 0,
                service: "twitter".to_string(),
                auth_type: "oauth2_pkce".to_string(),
                username: None,
                account_id: Some("stable-account-123".to_string()),
                scopes: r#"["tweet.read"]"#.to_string(),
                token_expires_at: None,
                created_at: chrono::Utc::now().to_rfc3339(),
                updated_at: chrono::Utc::now().to_rfc3339(),
            })
            .await
            .unwrap();

        let result = gateway.refresh_token("twitter").await.unwrap();

        assert_eq!(result, "Token refreshed for twitter");
        let profiles = gateway.http_profiles.read().await;
        let profile = profiles.get("twitter").expect("twitter profile rebuilt");
        assert_eq!(profile.token.as_deref(), Some("refreshed-access"));
        assert_eq!(profile.user_id.as_deref(), Some("stable-account-123"));
        assert!(
            profile
                .allowed_domains
                .iter()
                .any(|domain| domain == "api.x.com")
        );
    }

    #[tokio::test]
    async fn expired_token_preflight_is_serialized_and_preserves_account_binding() {
        let isolation = TestSecrets::new();

        async fn token_handler(
            Form(form): Form<HashMap<String, String>>,
        ) -> Json<serde_json::Value> {
            assert_eq!(
                form.get("grant_type").map(String::as_str),
                Some("refresh_token")
            );
            Json(serde_json::json!({
                "access_token": "preflight-access",
                "expires_in": 3600
            }))
        }

        let app = Router::new().route("/oauth/token", post(token_handler));
        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr: SocketAddr = listener.local_addr().unwrap();
        tokio::spawn(async move {
            let _ = axum::serve(listener, app).await;
        });

        let gateway = test_gateway(&isolation).await.unwrap();
        gateway
            .register_provider(OAuthProvider {
                name: "twitter".to_string(),
                display_name: "Twitter/X".to_string(),
                auth_type: OAuthType::OAuth2Pkce,
                authorize_url: "https://twitter.com/i/oauth2/authorize".to_string(),
                token_url: format!("http://{addr}/oauth/token"),
                scopes: vec!["tweet.read".to_string()],
                allowed_domains: vec!["api.twitter.com".to_string(), "api.x.com".to_string()],
            })
            .await;

        std::fs::write(
            isolation.env_file_path(),
            "OAUTH_TWITTER_CLIENT_ID=abc\nOAUTH_TWITTER_CLIENT_SECRET=def\nOAUTH_TWITTER_REFRESH_TOKEN=refresh-123\n",
        )
        .unwrap();
        gateway
            .state_store
            .save_oauth_connection(&OAuthConnection {
                id: 0,
                service: "twitter".to_string(),
                auth_type: "oauth2_pkce".to_string(),
                username: None,
                account_id: Some("stable-account-789".to_string()),
                scopes: r#"["tweet.read"]"#.to_string(),
                token_expires_at: Some(
                    (chrono::Utc::now() - chrono::Duration::minutes(1)).to_rfc3339(),
                ),
                created_at: chrono::Utc::now().to_rfc3339(),
                updated_at: chrono::Utc::now().to_rfc3339(),
            })
            .await
            .unwrap();

        let (first, second) = tokio::join!(
            gateway.refresh_access_token_if_needed("twitter"),
            gateway.refresh_access_token_if_needed("twitter")
        );

        let refresh_results = [first.unwrap(), second.unwrap()];
        assert_eq!(
            refresh_results
                .into_iter()
                .filter(|refreshed| *refreshed)
                .count(),
            1,
            "concurrent expiry checks must perform exactly one token exchange"
        );
        let profiles = gateway.http_profiles.read().await;
        let profile = profiles.get("twitter").expect("refreshed HTTP profile");
        assert_eq!(profile.token.as_deref(), Some("preflight-access"));
        assert_eq!(profile.user_id.as_deref(), Some("stable-account-789"));
    }

    #[tokio::test]
    async fn restore_connections_refreshes_when_access_token_missing() {
        let isolation = TestSecrets::new();

        async fn token_handler(
            Form(form): Form<HashMap<String, String>>,
        ) -> Json<serde_json::Value> {
            assert_eq!(
                form.get("grant_type").map(String::as_str),
                Some("refresh_token")
            );
            Json(serde_json::json!({
                "access_token": "restored-via-refresh",
                "expires_in": 3600
            }))
        }

        let app = Router::new().route("/oauth/token", post(token_handler));
        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr: SocketAddr = listener.local_addr().unwrap();
        tokio::spawn(async move {
            let _ = axum::serve(listener, app).await;
        });

        let gateway = test_gateway(&isolation).await.unwrap();
        gateway
            .register_provider(OAuthProvider {
                name: "twitter".to_string(),
                display_name: "Twitter/X".to_string(),
                auth_type: OAuthType::OAuth2Pkce,
                authorize_url: "https://twitter.com/i/oauth2/authorize".to_string(),
                token_url: format!("http://{addr}/oauth/token"),
                scopes: vec!["tweet.read".to_string()],
                allowed_domains: vec!["api.twitter.com".to_string(), "api.x.com".to_string()],
            })
            .await;

        // Reproduce the real failure: NO_KEYCHAIN mode reading a .env that has
        // the refresh token + client creds but NOT the access token.
        std::fs::write(
            isolation.env_file_path(),
            "OAUTH_TWITTER_CLIENT_ID=abc\nOAUTH_TWITTER_CLIENT_SECRET=def\nOAUTH_TWITTER_REFRESH_TOKEN=refresh-123\n",
        )
        .unwrap();
        gateway
            .state_store
            .save_oauth_connection(&OAuthConnection {
                id: 0,
                service: "twitter".to_string(),
                auth_type: "oauth2_pkce".to_string(),
                username: None,
                account_id: Some("stable-account-456".to_string()),
                scopes: r#"["tweet.read"]"#.to_string(),
                token_expires_at: None,
                created_at: chrono::Utc::now().to_rfc3339(),
                updated_at: chrono::Utc::now().to_rfc3339(),
            })
            .await
            .unwrap();

        // Startup restore must mint a bearer via refresh when the access token
        // is absent, instead of leaving the profile unloaded.
        gateway.restore_connections().await;

        let profiles = gateway.http_profiles.read().await;
        let profile = profiles
            .get("twitter")
            .expect("twitter profile should be restored via refresh");
        assert_eq!(profile.token.as_deref(), Some("restored-via-refresh"));
        assert_eq!(profile.user_id.as_deref(), Some("stable-account-456"));
    }

    fn synthetic_connection(auth_type: &str, expires_at: Option<&str>) -> OAuthConnection {
        OAuthConnection {
            id: 0,
            service: "twitter".to_string(),
            auth_type: auth_type.to_string(),
            username: None,
            account_id: Some("1000000000000000001".to_string()),
            scopes: r#"["tweet.read"]"#.to_string(),
            token_expires_at: expires_at.map(str::to_string),
            created_at: chrono::Utc::now().to_rfc3339(),
            updated_at: chrono::Utc::now().to_rfc3339(),
        }
    }

    #[test]
    fn credential_readiness_treats_an_expired_bearer_with_a_refresh_path_as_ready() {
        // Residual from R50–R53: the X bearer lives two hours, so by audit
        // time it has usually lapsed. The projection must say the next call
        // refreshes it, not that the credential is missing.
        let isolation = TestSecrets::new();
        std::fs::write(
            isolation.env_file_path(),
            "OAUTH_TWITTER_ACCESS_TOKEN=stale\nOAUTH_TWITTER_REFRESH_TOKEN=rt\nOAUTH_TWITTER_CLIENT_ID=id\nOAUTH_TWITTER_CLIENT_SECRET=secret\n",
        )
        .unwrap();
        let now = chrono::Utc::now();
        let expired = (now - chrono::Duration::hours(3)).to_rfc3339();
        let connection = synthetic_connection("oauth2_pkce", Some(&expired));

        let readiness =
            CredentialReadiness::for_connection(&connection, now, isolation.store.as_ref());
        assert_eq!(
            readiness,
            CredentialReadiness::Refreshable {
                expired_at: Some(expired.clone()),
                path: CredentialRefreshPath::RefreshToken,
            }
        );
        assert_eq!(readiness.state(), "ready-via-refresh");
        let text = readiness.describe();
        assert!(text.starts_with("ready-via-refresh ("), "{text}");
        assert!(text.contains(&expired), "{text}");
        assert!(text.contains("refresh token stored"), "{text}");
    }

    #[test]
    fn credential_readiness_reports_a_live_bearer_as_ready() {
        let isolation = TestSecrets::new();
        std::fs::write(
            isolation.env_file_path(),
            "OAUTH_TWITTER_ACCESS_TOKEN=live\n",
        )
        .unwrap();
        let now = chrono::Utc::now();
        let valid_until = (now + chrono::Duration::hours(1)).to_rfc3339();
        let connection = synthetic_connection("oauth2_pkce", Some(&valid_until));

        let readiness =
            CredentialReadiness::for_connection(&connection, now, isolation.store.as_ref());
        assert_eq!(
            readiness,
            CredentialReadiness::Ready {
                valid_until: Some(valid_until.clone()),
            }
        );
        assert_eq!(readiness.state(), "ready");
        assert!(readiness.describe().contains(&valid_until));
    }

    #[test]
    fn credential_readiness_inside_the_refresh_skew_is_not_ready_without_a_refresh_path() {
        let isolation = TestSecrets::new();
        std::fs::write(
            isolation.env_file_path(),
            "OAUTH_TWITTER_ACCESS_TOKEN=nearly-stale\nOAUTH_TWITTER_CLIENT_ID=id\nOAUTH_TWITTER_CLIENT_SECRET=secret\n",
        )
        .unwrap();
        let now = chrono::Utc::now();
        let almost =
            (now + chrono::Duration::seconds(ACCESS_TOKEN_REFRESH_SKEW_SECS / 2)).to_rfc3339();
        let connection = synthetic_connection("oauth2_pkce", Some(&almost));

        let readiness =
            CredentialReadiness::for_connection(&connection, now, isolation.store.as_ref());
        assert_eq!(
            readiness,
            CredentialReadiness::ReauthRequired {
                missing: vec!["refresh token"],
            }
        );
        assert_eq!(readiness.state(), "reauth-required");
        assert!(
            readiness
                .describe()
                .contains("reauth-required (missing: refresh token)")
        );
    }

    #[test]
    fn credential_readiness_uses_the_client_credentials_grant_when_no_bearer_is_stored() {
        let isolation = TestSecrets::new();
        std::fs::write(
            isolation.env_file_path(),
            "OAUTH_TWITTER_CLIENT_ID=id\nOAUTH_TWITTER_CLIENT_SECRET=secret\n",
        )
        .unwrap();
        let connection = synthetic_connection("oauth2_client_credentials", None);

        let readiness = CredentialReadiness::for_connection(
            &connection,
            chrono::Utc::now(),
            isolation.store.as_ref(),
        );
        assert_eq!(
            readiness,
            CredentialReadiness::Refreshable {
                expired_at: None,
                path: CredentialRefreshPath::ClientCredentials,
            }
        );
        let text = readiness.describe();
        assert!(text.contains("no bearer stored"), "{text}");
        assert!(text.contains("client-credentials grant"), "{text}");
    }

    #[test]
    fn credential_readiness_lists_every_missing_secret_when_nothing_is_stored() {
        let isolation = TestSecrets::new();
        std::fs::write(isolation.env_file_path(), "").unwrap();
        let connection = synthetic_connection("oauth2_pkce", None);

        let readiness = CredentialReadiness::for_connection(
            &connection,
            chrono::Utc::now(),
            isolation.store.as_ref(),
        );
        assert_eq!(
            readiness,
            CredentialReadiness::ReauthRequired {
                missing: vec![
                    "access token",
                    "refresh token",
                    "client id",
                    "client secret"
                ],
            }
        );
    }
}