vtcode-auth 0.142.8

Authentication and OAuth flows shared across VT Code
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
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
//! OpenAI ChatGPT subscription OAuth flow and secure session storage.
//!
//! This module implements an OAuth 2.0 PKCE authorization-code flow for ChatGPT
//! subscription auth, mirroring the flow used by [openai/codex]. By default VT
//! Code reuses the Codex CLI's **public PKCE OAuth client identity** (no client
//! secret — the ID is not a secret by OAuth 2.1 design). This is an **unofficial
//! compatibility mechanism**: OpenAI has not documented or guaranteed third-party
//! reuse of this client identity, and a public client ID is not authorization
//! to reuse another tool's OAuth registration. This allows ChatGPT subscription
//! login to work without the Codex CLI installed.
//! Organizations with their own OpenAI-issued client can override via
//! `VTCODE_OPENAI_OAUTH_CLIENT_ID` / `VTCODE_OPENAI_OAUTH_ORIGINATOR`.
//!
//! - OAuth authorization-code flow with PKCE
//! - refresh-token exchange
//! - token exchange for an OpenAI API-key-style bearer token
//! - secure storage in keyring or encrypted file storage
//!
//! Based on patterns from [openai/codex] (Apache-2.0). Copyright 2025 OpenAI.
//! See the repository `THIRD-PARTY-NOTICES` file for full attribution.
//!
//! [openai/codex]: https://github.com/openai/codex

use anyhow::{Context, Result, anyhow, bail};
use async_trait::async_trait;
use base64::{Engine, engine::general_purpose::STANDARD, engine::general_purpose::URL_SAFE_NO_PAD};
use fs2::FileExt;
use reqwest::Client;
use ring::aead::{self, Aad, LessSafeKey, NONCE_LEN, Nonce, UnboundKey};
use ring::rand::{SecureRandom, SystemRandom};
use serde::{Deserialize, Serialize};
use std::fmt;
use std::fs;
use std::fs::OpenOptions;
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use tokio::sync::Mutex as AsyncMutex;

use crate::storage_paths::{auth_storage_dir, write_private_file};
use crate::{OpenAIAuthConfig, OpenAIPreferredMethod};

pub use super::credentials::AuthCredentialsStoreMode;
use super::credentials::keyring;
use super::pkce::PkceChallenge;

const OPENAI_AUTH_URL: &str = "https://auth.openai.com/oauth/authorize";
const OPENAI_TOKEN_URL: &str = "https://auth.openai.com/oauth/token";
/// Default OAuth client identity.
///
/// This is the **Codex CLI's public PKCE OAuth client ID**. VT Code reuses
/// Codex's public client identity (a PKCE public client with no client secret
/// — the ID is not a secret by OAuth 2.1 design) as an **unofficial
/// compatibility mechanism**. OpenAI has not documented or guaranteed
/// third-party reuse of this identity, and a public client ID is not
/// authorization to reuse another tool's OAuth registration. This lets VT
/// Code perform ChatGPT subscription login without requiring the Codex CLI
/// to be installed.
///
/// Organizations with their own OpenAI-issued OAuth client can override this
/// via the `VTCODE_OPENAI_OAUTH_CLIENT_ID` environment variable.
///
/// See `docs/guides/oauth-authentication.md` for the full explanation.
const DEFAULT_OPENAI_CLIENT_ID: &str = "app_EMoamEEZ73f0CkXaXp7hrann";
/// Default originator sent to OpenAI's authorization endpoint.
///
/// This matches the Codex CLI's originator because the default client ID is
/// Codex's. Override with `VTCODE_OPENAI_OAUTH_ORIGINATOR` when using a custom
/// client ID.
const DEFAULT_OPENAI_ORIGINATOR: &str = "codex_cli_rs";
/// Maximum bytes read from a token-endpoint error response body for
/// classification. Prevents unbounded reads from a misbehaving or hostile
/// endpoint while still capturing standard OAuth 2.0 error JSON.
const MAX_ERROR_BODY_BYTES: usize = 8 * 1024;
const OPENAI_CALLBACK_PATH: &str = "/auth/callback";
const OPENAI_STORAGE_SERVICE: &str = "vtcode";
const OPENAI_STORAGE_USER: &str = "openai_chatgpt_session";
const OPENAI_SESSION_FILE: &str = "openai_chatgpt.json";
const OPENAI_REFRESH_LOCK_FILE: &str = "openai_chatgpt.refresh.lock";
const REFRESH_INTERVAL_SECS: u64 = 8 * 60;
const REFRESH_SKEW_SECS: u64 = 60;

/// Resolved OAuth client identity (client ID + originator).
///
/// Both fields must be consistent: when a custom client ID is provided via
/// `VTCODE_OPENAI_OAUTH_CLIENT_ID`, the originator must also be overridden
/// via `VTCODE_OPENAI_OAUTH_ORIGINATOR`. Sending a custom client ID with
/// Codex's `codex_cli_rs` originator (or vice versa) would be inconsistent
/// and is rejected.
///
/// `Debug` is safe to derive: the client ID is a public PKCE client
/// identifier (not a secret by OAuth 2.1 design), and the originator is
/// a public identifier string.
#[derive(Debug)]
struct OAuthClientIdentity {
    client_id: String,
    originator: String,
}

/// Resolve the OAuth client identity from environment variables.
///
/// ## Invariant
///
/// The client ID and originator form a **coherent pair**. One-sided overrides
/// are rejected to prevent mixed identities (e.g. a custom client ID paired
/// with Codex's `codex_cli_rs` originator).
///
/// - Both `VTCODE_OPENAI_OAUTH_CLIENT_ID` and `VTCODE_OPENAI_OAUTH_ORIGINATOR`
///   set and non-blank → use the custom pair.
/// - Neither set → use the complete Codex default pair.
/// - Only one set → return a configuration error with an actionable message.
///   The caller must surface this so the user can fix the environment before
///   any OAuth request is sent.
///
/// All four flow stages (authorization URL, code exchange, refresh, token
/// exchange) call this resolver, so the same coherent pair is used throughout.
fn resolve_oauth_client_identity() -> Result<OAuthClientIdentity> {
    let custom_client_id = std::env::var("VTCODE_OPENAI_OAUTH_CLIENT_ID")
        .ok()
        .filter(|v| !v.trim().is_empty());
    let custom_originator = std::env::var("VTCODE_OPENAI_OAUTH_ORIGINATOR")
        .ok()
        .filter(|v| !v.trim().is_empty());

    match (custom_client_id, custom_originator) {
        (Some(id), Some(originator)) => Ok(OAuthClientIdentity { client_id: id, originator }),
        (Some(_), None) => bail!(
            "VTCODE_OPENAI_OAUTH_CLIENT_ID is set but VTCODE_OPENAI_OAUTH_ORIGINATOR is not. \
             The client ID and originator must be overridden together to form a coherent OAuth \
             identity. Set VTCODE_OPENAI_OAUTH_ORIGINATOR to match your custom client ID, \
             or unset VTCODE_OPENAI_OAUTH_CLIENT_ID to use the default Codex identity."
        ),
        (None, Some(_)) => bail!(
            "VTCODE_OPENAI_OAUTH_ORIGINATOR is set but VTCODE_OPENAI_OAUTH_CLIENT_ID is not. \
             The client ID and originator must be overridden together to form a coherent OAuth \
             identity. Set VTCODE_OPENAI_OAUTH_CLIENT_ID to match your custom originator, \
             or unset VTCODE_OPENAI_OAUTH_ORIGINATOR to use the default Codex identity."
        ),
        (None, None) => Ok(OAuthClientIdentity {
            client_id: DEFAULT_OPENAI_CLIENT_ID.to_string(),
            originator: DEFAULT_OPENAI_ORIGINATOR.to_string(),
        }),
    }
}

/// Stored OpenAI ChatGPT subscription session.
///
/// Custom `Debug` redacts all token fields to prevent credential leakage
/// through `tracing::debug!(?session)` or error wrappers.
#[derive(Clone, Serialize, Deserialize)]
pub struct OpenAIChatGptSession {
    /// Exchanged OpenAI bearer token used for normal API calls when available.
    /// If unavailable, VT Code falls back to the OAuth access token.
    pub openai_api_key: String,
    /// OAuth ID token from the sign-in flow.
    pub id_token: String,
    /// OAuth access token from the sign-in flow.
    pub access_token: String,
    /// Refresh token used to renew the session.
    pub refresh_token: String,
    /// ChatGPT workspace/account identifier, if present.
    pub account_id: Option<String>,
    /// Account email, if present.
    pub email: Option<String>,
    /// ChatGPT plan type, if present.
    pub plan: Option<String>,
    /// When the session was originally created.
    pub obtained_at: u64,
    /// When the OAuth/API-key exchange was last refreshed.
    pub refreshed_at: u64,
    /// Access-token expiry, if supplied by the authority.
    pub expires_at: Option<u64>,
}

impl fmt::Debug for OpenAIChatGptSession {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("OpenAIChatGptSession")
            .field("openai_api_key", &"<redacted>")
            .field("id_token", &"<redacted>")
            .field("access_token", &"<redacted>")
            .field("refresh_token", &"<redacted>")
            .field("account_id", &self.account_id)
            .field("email", &self.email)
            .field("plan", &self.plan)
            .field("obtained_at", &self.obtained_at)
            .field("refreshed_at", &self.refreshed_at)
            .field("expires_at", &self.expires_at)
            .finish()
    }
}

impl OpenAIChatGptSession {
    fn is_refresh_due(&self) -> bool {
        let now = now_secs();
        if let Some(expires_at) = self.expires_at
            && now.saturating_add(REFRESH_SKEW_SECS) >= expires_at
        {
            return true;
        }
        now.saturating_sub(self.refreshed_at) >= REFRESH_INTERVAL_SECS
    }
}

/// Host-provided refresher for externally managed ChatGPT auth tokens.
#[async_trait]
pub trait OpenAIChatGptSessionRefresher: Send + Sync {
    async fn refresh_session(&self, current: &OpenAIChatGptSession) -> Result<OpenAIChatGptSession>;
}

#[derive(Clone)]
enum OpenAIChatGptAuthRefreshStrategy {
    Stored {
        storage_mode: AuthCredentialsStoreMode,
    },
    External {
        refresher: Arc<dyn OpenAIChatGptSessionRefresher>,
    },
}

impl fmt::Debug for OpenAIChatGptAuthRefreshStrategy {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Stored { storage_mode } => f.debug_struct("Stored").field("storage_mode", storage_mode).finish(),
            Self::External { .. } => f.debug_struct("External").finish_non_exhaustive(),
        }
    }
}

/// Runtime auth state shared by OpenAI provider instances.
#[derive(Clone)]
pub struct OpenAIChatGptAuthHandle {
    session: Arc<Mutex<OpenAIChatGptSession>>,
    refresh_gate: Arc<AsyncMutex<()>>,
    auto_refresh: bool,
    refresh_strategy: OpenAIChatGptAuthRefreshStrategy,
}

impl fmt::Debug for OpenAIChatGptAuthHandle {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("OpenAIChatGptAuthHandle")
            .field("auto_refresh", &self.auto_refresh)
            .field("refresh_strategy", &self.refresh_strategy)
            .finish()
    }
}

impl OpenAIChatGptAuthHandle {
    pub fn new(
        session: OpenAIChatGptSession,
        auth_config: OpenAIAuthConfig,
        storage_mode: AuthCredentialsStoreMode,
    ) -> Self {
        Self {
            session: Arc::new(Mutex::new(session)),
            refresh_gate: Arc::new(AsyncMutex::new(())),
            auto_refresh: auth_config.auto_refresh,
            refresh_strategy: OpenAIChatGptAuthRefreshStrategy::Stored { storage_mode },
        }
    }

    pub fn new_external(
        session: OpenAIChatGptSession,
        auto_refresh: bool,
        refresher: Arc<dyn OpenAIChatGptSessionRefresher>,
    ) -> Self {
        Self {
            session: Arc::new(Mutex::new(session)),
            refresh_gate: Arc::new(AsyncMutex::new(())),
            auto_refresh,
            refresh_strategy: OpenAIChatGptAuthRefreshStrategy::External { refresher },
        }
    }

    pub fn snapshot(&self) -> Result<OpenAIChatGptSession> {
        self.session
            .lock()
            .map(|guard| guard.clone())
            .map_err(|_| anyhow!("openai chatgpt auth mutex poisoned"))
    }

    pub fn current_api_key(&self) -> Result<String> {
        self.snapshot().map(|session| active_api_bearer_token(&session).to_string())
    }

    pub fn provider_label(&self) -> &'static str {
        "OpenAI (ChatGPT)"
    }

    pub async fn refresh_if_needed(&self) -> Result<()> {
        if !self.auto_refresh {
            return Ok(());
        }

        self.refresh_when(|session| session.is_refresh_due()).await
    }

    pub async fn force_refresh(&self) -> Result<()> {
        self.refresh_when(|_| true).await
    }

    async fn refresh_when<P>(&self, should_refresh: P) -> Result<()>
    where
        P: FnOnce(&OpenAIChatGptSession) -> bool,
    {
        let _refresh_guard = self.refresh_gate.lock().await;
        let session = self.snapshot()?;
        if !should_refresh(&session) {
            return Ok(());
        }

        let refreshed = match &self.refresh_strategy {
            OpenAIChatGptAuthRefreshStrategy::Stored { storage_mode } => {
                refresh_openai_chatgpt_session_from_snapshot(&session, *storage_mode).await?
            }
            OpenAIChatGptAuthRefreshStrategy::External { refresher } => refresher.refresh_session(&session).await?,
        };
        self.replace_session(refreshed)
    }

    #[must_use]
    fn using_external_tokens(&self) -> bool {
        matches!(self.refresh_strategy, OpenAIChatGptAuthRefreshStrategy::External { .. })
    }

    fn replace_session(&self, session: OpenAIChatGptSession) -> Result<()> {
        let mut guard = self.session.lock().map_err(|_| anyhow!("openai chatgpt auth mutex poisoned"))?;
        *guard = session;
        Ok(())
    }
}

/// OpenAI auth resolution chosen for the current runtime.
///
/// Custom `Debug` redacts the bearer `api_key` to prevent credential leakage.
#[derive(Clone)]
pub enum OpenAIResolvedAuth {
    ApiKey {
        api_key: String,
    },
    ChatGpt {
        api_key: String,
        handle: OpenAIChatGptAuthHandle,
    },
}

impl fmt::Debug for OpenAIResolvedAuth {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::ApiKey { .. } => f.debug_struct("OpenAIResolvedAuth::ApiKey").finish(),
            Self::ChatGpt { .. } => f.debug_struct("OpenAIResolvedAuth::ChatGpt").finish(),
        }
    }
}

impl OpenAIResolvedAuth {
    pub fn api_key(&self) -> &str {
        match self {
            Self::ApiKey { api_key } => api_key,
            Self::ChatGpt { api_key, .. } => api_key,
        }
    }

    pub fn handle(&self) -> Option<OpenAIChatGptAuthHandle> {
        match self {
            Self::ApiKey { .. } => None,
            Self::ChatGpt { handle, .. } => Some(handle.clone()),
        }
    }

    fn using_chatgpt(&self) -> bool {
        matches!(self, Self::ChatGpt { .. })
    }
}

fn active_api_bearer_token(session: &OpenAIChatGptSession) -> &str {
    if session.openai_api_key.trim().is_empty() {
        session.access_token.as_str()
    } else {
        session.openai_api_key.as_str()
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OpenAIResolvedAuthSource {
    ApiKey,
    ChatGpt,
}

/// Where the ChatGPT session originated — used by CLI/TUI to render accurate
/// status without directly inspecting the filesystem.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OpenAIChatGptSessionProvenance {
    /// Session stored in VT Code's own credential storage (full auto-refresh).
    Native,
    /// Session loaded from Codex CLI's `~/.codex/auth.json` (managed by Codex).
    CodexFallback,
}

/// Redacted summary of available OpenAI credentials for CLI/TUI display.
///
/// Does NOT carry token data — only metadata (email, plan, provenance, expiry)
/// so credential values can never leak through `Debug` or logging.
#[derive(Debug, Clone)]
pub struct OpenAICredentialOverview {
    pub api_key_available: bool,
    /// Email from the ChatGPT session's ID token, if available.
    pub chatgpt_email: Option<String>,
    /// Plan type from the ChatGPT session's ID token, if available.
    pub chatgpt_plan: Option<String>,
    /// `true` when a ChatGPT session (native or Codex fallback) is available.
    pub chatgpt_session_present: bool,
    /// Provenance of the ChatGPT session — `None` when no session is available.
    pub chatgpt_session_provenance: Option<OpenAIChatGptSessionProvenance>,
    /// `true` only when Codex's auth.json was **successfully parsed** into a
    /// usable session (not merely that the file exists on disk).
    pub codex_fallback_available: bool,
    pub active_source: Option<OpenAIResolvedAuthSource>,
    pub preferred_method: OpenAIPreferredMethod,
    pub notice: Option<String>,
    pub recommendation: Option<String>,
}

/// Generic auth status reused by slash auth/status output.
#[derive(Debug, Clone)]
pub enum OpenAIChatGptAuthStatus {
    Authenticated {
        label: Option<String>,
        age_seconds: u64,
        expires_in: Option<u64>,
    },
    NotAuthenticated,
}

/// Build the OpenAI ChatGPT OAuth authorization URL.
pub fn get_openai_chatgpt_auth_url(challenge: &PkceChallenge, callback_port: u16, state: &str) -> Result<String> {
    let redirect_uri = format!("http://localhost:{callback_port}{OPENAI_CALLBACK_PATH}");
    let identity = resolve_oauth_client_identity()?;
    let query = [
        ("response_type", "code".to_string()),
        ("client_id", identity.client_id.clone()),
        ("redirect_uri", redirect_uri),
        ("scope", "openid profile email offline_access api.connectors.read api.connectors.invoke".to_string()),
        ("code_challenge", challenge.code_challenge.clone()),
        ("code_challenge_method", challenge.code_challenge_method.clone()),
        ("id_token_add_organizations", "true".to_string()),
        ("codex_cli_simplified_flow", "true".to_string()),
        ("state", state.to_string()),
        ("originator", identity.originator),
    ];

    let encoded = query
        .iter()
        .map(|(key, value)| format!("{key}={}", urlencoding::encode(value)))
        .collect::<Vec<_>>()
        .join("&");
    Ok(format!("{OPENAI_AUTH_URL}?{encoded}"))
}

pub fn generate_openai_oauth_state() -> Result<String> {
    let mut state_bytes = [0_u8; 32];
    SystemRandom::new()
        .fill(&mut state_bytes)
        .map_err(|_| anyhow!("failed to generate openai oauth state"))?;
    Ok(URL_SAFE_NO_PAD.encode(state_bytes))
}

pub fn parse_openai_chatgpt_manual_callback_input(input: &str, expected_state: &str) -> Result<String> {
    let trimmed = input.trim();
    if trimmed.is_empty() {
        bail!("missing authorization callback input");
    }

    let query = if trimmed.contains("://") {
        let url = reqwest::Url::parse(trimmed).context("invalid callback url")?;
        url.query()
            .ok_or_else(|| anyhow!("callback url did not include a query string"))?
            .to_string()
    } else if trimmed.contains('=') {
        trimmed.trim_start_matches('?').to_string()
    } else {
        bail!("paste the full redirect url or query string containing code and state");
    };

    let code = extract_query_value(&query, "code")
        .ok_or_else(|| anyhow!("callback input did not include an authorization code"))?;
    let state = extract_query_value(&query, "state").ok_or_else(|| anyhow!("callback input did not include state"))?;
    if state != expected_state {
        bail!("OAuth error: state mismatch");
    }
    Ok(code)
}

/// Exchange an authorization code for OAuth tokens.
pub async fn exchange_openai_chatgpt_code_for_tokens(
    code: &str,
    challenge: &PkceChallenge,
    callback_port: u16,
) -> Result<OpenAIChatGptSession> {
    let redirect_uri = format!("http://localhost:{callback_port}{OPENAI_CALLBACK_PATH}");
    let identity = resolve_oauth_client_identity()?;
    let body = format!(
        "grant_type=authorization_code&code={}&redirect_uri={}&client_id={}&code_verifier={}",
        urlencoding::encode(code),
        urlencoding::encode(&redirect_uri),
        urlencoding::encode(&identity.client_id),
        urlencoding::encode(&challenge.code_verifier),
    );

    let token_response: OpenAITokenResponse = Client::new()
        .post(OPENAI_TOKEN_URL)
        .header("Content-Type", "application/x-www-form-urlencoded")
        .body(body)
        .send()
        .await
        .context("failed to exchange openai authorization code")?
        .error_for_status()
        .context("openai authorization-code exchange failed")?
        .json()
        .await
        .context("failed to parse openai authorization-code response")?;

    build_session_from_token_response(token_response).await
}

/// Resolve the active OpenAI auth source for the current configuration.
pub fn resolve_openai_auth(
    auth_config: &OpenAIAuthConfig,
    storage_mode: AuthCredentialsStoreMode,
    api_key: Option<String>,
) -> Result<OpenAIResolvedAuth> {
    crate::auth_service::OpenAIAccountAuthService::new(auth_config.clone(), storage_mode).resolve_runtime_auth(api_key)
}

pub fn summarize_openai_credentials(
    auth_config: &OpenAIAuthConfig,
    storage_mode: AuthCredentialsStoreMode,
    api_key: Option<String>,
) -> Result<OpenAICredentialOverview> {
    crate::auth_service::OpenAIAccountAuthService::new(auth_config.clone(), storage_mode).summarize_credentials(api_key)
}

pub fn save_openai_chatgpt_session(session: &OpenAIChatGptSession) -> Result<()> {
    save_openai_chatgpt_session_with_mode(session, AuthCredentialsStoreMode::default())
}

pub fn save_openai_chatgpt_session_with_mode(
    session: &OpenAIChatGptSession,
    mode: AuthCredentialsStoreMode,
) -> Result<()> {
    let serialized = serde_json::to_string(session).context("failed to serialize openai session")?;
    match mode.effective_mode() {
        AuthCredentialsStoreMode::Keyring => persist_session_to_keyring_or_file(session, &serialized)?,
        AuthCredentialsStoreMode::File => save_session_to_file(session)?,
        AuthCredentialsStoreMode::Auto => unreachable!(),
    }
    Ok(())
}

pub fn load_openai_chatgpt_session() -> Result<Option<OpenAIChatGptSession>> {
    load_preferred_openai_chatgpt_session(AuthCredentialsStoreMode::Keyring)
}

pub fn load_openai_chatgpt_session_with_mode(mode: AuthCredentialsStoreMode) -> Result<Option<OpenAIChatGptSession>> {
    load_preferred_openai_chatgpt_session(mode.effective_mode())
}

pub fn clear_openai_chatgpt_session() -> Result<()> {
    clear_session_from_all_stores()
}

pub fn clear_openai_chatgpt_session_with_mode(mode: AuthCredentialsStoreMode) -> Result<()> {
    match mode.effective_mode() {
        AuthCredentialsStoreMode::Keyring => clear_session_from_keyring(),
        AuthCredentialsStoreMode::File => clear_session_from_file(),
        AuthCredentialsStoreMode::Auto => unreachable!(),
    }
}

pub fn get_openai_chatgpt_auth_status() -> Result<OpenAIChatGptAuthStatus> {
    get_openai_chatgpt_auth_status_with_mode(AuthCredentialsStoreMode::default())
}

pub fn get_openai_chatgpt_auth_status_with_mode(mode: AuthCredentialsStoreMode) -> Result<OpenAIChatGptAuthStatus> {
    let Some(session) = load_openai_chatgpt_session_with_mode(mode)? else {
        return Ok(OpenAIChatGptAuthStatus::NotAuthenticated);
    };
    let now = now_secs();
    Ok(OpenAIChatGptAuthStatus::Authenticated {
        label: session
            .email
            .clone()
            .or_else(|| session.plan.clone())
            .or_else(|| session.account_id.clone()),
        age_seconds: now.saturating_sub(session.obtained_at),
        expires_in: session.expires_at.map(|expires_at| expires_at.saturating_sub(now)),
    })
}

/// Refresh a ChatGPT session using only a refresh token.
///
/// **Deprecated/unused:** This helper constructs a minimal session with blank
/// token fields and relies on the refresh endpoint returning a complete
/// response. It has no internal callers and is kept private to prevent
/// external code from persisting sessions with blank sentinel values.
/// Use `refresh_openai_chatgpt_session_with_mode` instead, which loads the
/// full stored session first.
async fn refresh_openai_chatgpt_session_from_refresh_token(
    refresh_token: &str,
    storage_mode: AuthCredentialsStoreMode,
) -> Result<OpenAIChatGptSession> {
    let _lock = acquire_refresh_lock().await?;
    // Construct a minimal session from just the refresh token — used when
    // the caller only has the refresh token (e.g. external integrations).
    let minimal = OpenAIChatGptSession {
        openai_api_key: String::new(),
        id_token: String::new(),
        access_token: String::new(),
        refresh_token: refresh_token.to_string(),
        account_id: None,
        email: None,
        plan: None,
        obtained_at: 0,
        refreshed_at: 0,
        expires_at: None,
    };
    refresh_openai_chatgpt_session_without_lock(&minimal, storage_mode).await
}

pub async fn refresh_openai_chatgpt_session_with_mode(mode: AuthCredentialsStoreMode) -> Result<OpenAIChatGptSession> {
    let session = load_openai_chatgpt_session_with_mode(mode)?.ok_or_else(|| anyhow!("Run vtcode login openai"))?;
    refresh_openai_chatgpt_session_from_snapshot(&session, mode).await
}

async fn refresh_openai_chatgpt_session_from_snapshot(
    session: &OpenAIChatGptSession,
    storage_mode: AuthCredentialsStoreMode,
) -> Result<OpenAIChatGptSession> {
    let _lock = acquire_refresh_lock().await?;
    if let Some(current) = load_openai_chatgpt_session_with_mode(storage_mode)?
        && session_has_newer_refresh_state(&current, session)
    {
        return Ok(current);
    }
    refresh_openai_chatgpt_session_without_lock(session, storage_mode).await
}

/// Refresh the ChatGPT session using the stored refresh token.
///
/// The response is parsed as [`OpenAIRefreshResponse`] with independently
/// optional fields — OpenAI's token endpoint may omit unchanged fields.
/// Omitted fields preserve the current session's values. This matches the
/// behavior of `openai/codex`'s `RefreshResponse` + `persist_tokens`.
async fn refresh_openai_chatgpt_session_without_lock(
    current: &OpenAIChatGptSession,
    storage_mode: AuthCredentialsStoreMode,
) -> Result<OpenAIChatGptSession> {
    let identity = resolve_oauth_client_identity()?;
    let response = Client::new()
        .post(OPENAI_TOKEN_URL)
        .header("Content-Type", "application/x-www-form-urlencoded")
        .body(format!(
            "grant_type=refresh_token&client_id={}&refresh_token={}",
            urlencoding::encode(&identity.client_id),
            urlencoding::encode(&current.refresh_token),
        ))
        .send()
        .await
        .context("failed to refresh openai chatgpt token")?;

    // Check for HTTP errors. Unlike error_for_status_ref(), we capture the
    // response body to classify token-endpoint errors (e.g. invalid_grant,
    // refresh_token_expired) that reqwest's status-only error would miss.
    if !response.status().is_success() {
        let status = response.status();
        // Read a bounded body for error classification — never log it raw.
        let body_text = read_bounded_text(response, MAX_ERROR_BODY_BYTES).await;
        return Err(classify_refresh_status_error(status, &body_text));
    }

    let refresh_response: OpenAIRefreshResponse =
        response.json().await.context("failed to parse openai refresh response")?;

    let session = merge_refresh_response(current, refresh_response).await?;
    // Guard against a blank access_token — the primary bearer credential.
    // This protects the minimal-session refresh helper (which starts with
    // blank token fields) from persisting a session with blank tokens when
    // the token endpoint returns a partial response that omits access_token.
    if session.access_token.trim().is_empty() {
        bail!("openai token refresh returned no access token — the session cannot be used");
    }
    save_openai_chatgpt_session_with_mode(&session, storage_mode)?;
    Ok(session)
}

/// Merge a partial refresh response into the current session, preserving
/// omitted fields. Only re-exchanges the API key when a new `id_token` is
/// present; otherwise keeps the previous exchanged key.
async fn merge_refresh_response(
    current: &OpenAIChatGptSession,
    resp: OpenAIRefreshResponse,
) -> Result<OpenAIChatGptSession> {
    let now = now_secs();
    // Track which fields were present before moving them out of resp.
    // Treat blank-string values as absent — some token endpoints return
    // empty strings for omitted fields rather than leaving them out.
    let has_new_id_token = resp.id_token.as_deref().is_some_and(|v| !v.trim().is_empty());
    let has_new_access_token = resp.access_token.as_deref().is_some_and(|v| !v.trim().is_empty());
    let new_id_token = resp
        .id_token
        .filter(|v| !v.trim().is_empty())
        .unwrap_or_else(|| current.id_token.clone());
    let new_access_token = resp
        .access_token
        .filter(|v| !v.trim().is_empty())
        .unwrap_or_else(|| current.access_token.clone());
    let new_refresh_token = resp
        .refresh_token
        .filter(|v| !v.trim().is_empty())
        .unwrap_or_else(|| current.refresh_token.clone());

    // Re-exchange the API key only when a new id_token was provided.
    let openai_api_key = if has_new_id_token {
        match exchange_openai_chatgpt_api_key(&new_id_token).await {
            Ok(api_key) => api_key,
            Err(err) => {
                tracing::warn!("openai api-key exchange unavailable, falling back to previous key: {err}");
                current.openai_api_key.clone()
            }
        }
    } else {
        current.openai_api_key.clone()
    };

    // Recompute expiry: prefer expires_in from the response, then try to parse
    // exp from the new access_token JWT. For a **changed** access token without
    // expires_in or a parseable exp, set None — do NOT inherit the previous
    // token's expiry, which belongs to a different token.
    //
    // Key distinction: `has_new_access_token` means the field was present and
    // non-blank, NOT that the token value changed. If the endpoint repeats the
    // same opaque access token without expires_in, the old expiry is still
    // valid and must be preserved.
    let access_token_changed = has_new_access_token && new_access_token != current.access_token;
    let expires_at = if let Some(secs) = resp.expires_in {
        Some(now.saturating_add(secs))
    } else if access_token_changed {
        parse_jwt_exp(&new_access_token)
    } else {
        current.expires_at
    };

    // Update email/plan/account_id only when a new id_token was provided.
    let (email, plan, account_id) = if has_new_id_token {
        let id_claims = parse_jwt_claims(&new_id_token)?;
        let access_claims = parse_jwt_claims(&new_access_token).ok();
        let email = id_claims.email.clone();
        let plan = access_claims.as_ref().and_then(|c| c.plan.clone()).or(id_claims.plan);
        let account_id = access_claims
            .as_ref()
            .and_then(|c| c.account_id.clone())
            .or(id_claims.account_id);
        (email, plan, account_id)
    } else {
        (current.email.clone(), current.plan.clone(), current.account_id.clone())
    };

    Ok(OpenAIChatGptSession {
        openai_api_key,
        id_token: new_id_token,
        access_token: new_access_token,
        refresh_token: new_refresh_token,
        account_id,
        email,
        plan,
        // Preserve the original obtained_at — only refreshed_at advances.
        obtained_at: current.obtained_at,
        refreshed_at: now,
        expires_at,
    })
}

async fn build_session_from_token_response(token_response: OpenAITokenResponse) -> Result<OpenAIChatGptSession> {
    // Validate that the token response contains usable credentials.
    if token_response.access_token.trim().is_empty() {
        bail!("openai authorization-code response did not include a usable access token");
    }
    if token_response.refresh_token.trim().is_empty() {
        bail!("openai authorization-code response did not include a usable refresh token");
    }
    let id_claims = parse_jwt_claims(&token_response.id_token)?;
    let access_claims = parse_jwt_claims(&token_response.access_token).ok();
    let api_key = match exchange_openai_chatgpt_api_key(&token_response.id_token).await {
        Ok(api_key) => api_key,
        Err(err) => {
            tracing::warn!("openai api-key exchange unavailable, falling back to oauth access token: {err}");
            String::new()
        }
    };
    let now = now_secs();
    Ok(OpenAIChatGptSession {
        openai_api_key: api_key,
        id_token: token_response.id_token,
        access_token: token_response.access_token,
        refresh_token: token_response.refresh_token,
        account_id: access_claims
            .as_ref()
            .and_then(|claims| claims.account_id.clone())
            .or(id_claims.account_id),
        email: id_claims
            .email
            .or_else(|| access_claims.as_ref().and_then(|claims| claims.email.clone())),
        plan: access_claims.as_ref().and_then(|claims| claims.plan.clone()).or(id_claims.plan),
        obtained_at: now,
        refreshed_at: now,
        expires_at: token_response.expires_in.map(|secs| now.saturating_add(secs)),
    })
}

async fn exchange_openai_chatgpt_api_key(id_token: &str) -> Result<String> {
    #[derive(Deserialize)]
    struct ExchangeResponse {
        access_token: String,
    }

    let identity = resolve_oauth_client_identity()?;
    let exchange: ExchangeResponse = Client::new()
        .post(OPENAI_TOKEN_URL)
        .header("Content-Type", "application/x-www-form-urlencoded")
        .body(format!(
            "grant_type={}&client_id={}&requested_token={}&subject_token={}&subject_token_type={}",
            urlencoding::encode("urn:ietf:params:oauth:grant-type:token-exchange"),
            urlencoding::encode(&identity.client_id),
            urlencoding::encode("openai-api-key"),
            urlencoding::encode(id_token),
            urlencoding::encode("urn:ietf:params:oauth:token-type:id_token"),
        ))
        .send()
        .await
        .context("failed to exchange openai id token for api key")?
        .error_for_status()
        .context("openai api-key exchange failed")?
        .json()
        .await
        .context("failed to parse openai api-key exchange response")?;

    Ok(exchange.access_token)
}

#[derive(Deserialize)]
struct OpenAITokenResponse {
    id_token: String,
    access_token: String,
    refresh_token: String,
    #[serde(default)]
    expires_in: Option<u64>,
}

/// Refresh-token grant response — all token fields are independently optional
/// because OpenAI's token endpoint may omit unchanged fields (matching the
/// behavior observed in `openai/codex`'s `RefreshResponse`). Omitted fields
/// preserve the previous session's values during merge.
#[derive(Deserialize)]
struct OpenAIRefreshResponse {
    #[serde(default)]
    id_token: Option<String>,
    #[serde(default)]
    access_token: Option<String>,
    #[serde(default)]
    refresh_token: Option<String>,
    #[serde(default)]
    expires_in: Option<u64>,
}

#[derive(Debug, Deserialize)]
struct IdTokenClaims {
    #[serde(default)]
    email: Option<String>,
    #[serde(rename = "https://api.openai.com/profile", default)]
    profile: Option<ProfileClaims>,
    #[serde(rename = "https://api.openai.com/auth", default)]
    auth: Option<AuthClaims>,
}

#[derive(Debug, Deserialize)]
struct ProfileClaims {
    #[serde(default)]
    email: Option<String>,
}

#[derive(Debug, Deserialize)]
struct AuthClaims {
    #[serde(default)]
    chatgpt_plan_type: Option<String>,
    #[serde(default)]
    chatgpt_account_id: Option<String>,
}

#[derive(Debug)]
pub(crate) struct ParsedIdTokenClaims {
    pub(crate) email: Option<String>,
    pub(crate) account_id: Option<String>,
    pub(crate) plan: Option<String>,
}

pub(crate) fn parse_jwt_claims(jwt: &str) -> Result<ParsedIdTokenClaims> {
    let mut parts = jwt.split('.');
    let (_, payload_b64, _) = match (parts.next(), parts.next(), parts.next()) {
        (Some(header), Some(payload), Some(signature))
            if !header.is_empty() && !payload.is_empty() && !signature.is_empty() =>
        {
            (header, payload, signature)
        }
        _ => bail!("invalid openai id token"),
    };

    let payload = URL_SAFE_NO_PAD
        .decode(payload_b64)
        .context("failed to decode openai id token payload")?;
    let claims: IdTokenClaims = serde_json::from_slice(&payload).context("failed to parse openai id token payload")?;

    Ok(ParsedIdTokenClaims {
        email: claims.email.or_else(|| claims.profile.and_then(|profile| profile.email)),
        account_id: claims.auth.as_ref().and_then(|auth| auth.chatgpt_account_id.clone()),
        plan: claims.auth.and_then(|auth| auth.chatgpt_plan_type),
    })
}

/// Extract the standard `exp` (expiry) claim from a JWT, if present.
///
/// Returns `None` when the token is not a JWT or has no `exp` claim.
/// This is used to populate `expires_at` for Codex-imported sessions,
/// since Codex's `auth.json` does not store expiry separately.
pub(crate) fn parse_jwt_exp(jwt: &str) -> Option<u64> {
    let mut parts = jwt.split('.');
    let _ = parts.next()?;
    let payload_b64 = parts.next()?;
    if payload_b64.is_empty() {
        return None;
    }
    let payload = URL_SAFE_NO_PAD.decode(payload_b64).ok()?;
    #[derive(Deserialize)]
    struct ExpClaim {
        #[serde(default)]
        exp: Option<u64>,
    }
    let claims: ExpClaim = serde_json::from_slice(&payload).ok()?;
    claims.exp
}

fn extract_query_value(query: &str, key: &str) -> Option<String> {
    query
        .trim_start_matches('?')
        .split('&')
        .filter_map(|pair| {
            let (pair_key, pair_value) = pair.split_once('=')?;
            (pair_key == key)
                .then(|| urlencoding::decode(pair_value).ok().map(|value| value.into_owned()))
                .flatten()
        })
        .find(|value| !value.is_empty())
}

fn session_has_newer_refresh_state(current: &OpenAIChatGptSession, previous: &OpenAIChatGptSession) -> bool {
    current.refresh_token != previous.refresh_token
        || current.refreshed_at > previous.refreshed_at
        || current.obtained_at > previous.obtained_at
}

struct RefreshLockGuard {
    file: fs::File,
}

impl Drop for RefreshLockGuard {
    fn drop(&mut self) {
        drop(FileExt::unlock(&self.file));
    }
}

async fn acquire_refresh_lock() -> Result<RefreshLockGuard> {
    let path = auth_storage_dir()?.join(OPENAI_REFRESH_LOCK_FILE);
    let file = OpenOptions::new()
        .create(true)
        .read(true)
        .write(true)
        .truncate(false)
        .open(&path)
        .context("failed to open openai refresh lock")?;
    let file = tokio::task::spawn_blocking(move || {
        file.lock_exclusive().context("failed to acquire openai refresh lock")?;
        Ok::<_, anyhow::Error>(file)
    })
    .await
    .context("openai refresh lock task failed")??;
    Ok(RefreshLockGuard { file })
}

/// Read at most `max_bytes` from an HTTP response body as a string.
///
/// Reads the response in chunks and stops once `max_bytes` have been
/// accumulated, preventing unbounded memory allocation from a misbehaving or
/// hostile endpoint. Invalid UTF-8 sequences are replaced (lossy) since we
/// only use the text for best-effort error classification, never for display
/// or logging.
async fn read_bounded_text(mut response: reqwest::Response, max_bytes: usize) -> String {
    let mut buf = Vec::with_capacity(max_bytes.min(8 * 1024));
    while buf.len() < max_bytes {
        match response.chunk().await {
            Ok(Some(chunk)) => {
                let remaining = max_bytes - buf.len();
                if chunk.len() <= remaining {
                    buf.extend_from_slice(&chunk);
                } else {
                    buf.extend_from_slice(chunk.get(..remaining).unwrap_or_default());
                    break;
                }
            }
            Ok(None) => break,
            Err(_) => break,
        }
    }
    String::from_utf8_lossy(&buf).into_owned()
}

/// Extract the OAuth 2.0 error code from a token-endpoint error body.
///
/// Handles multiple JSON shapes that authorization servers use:
///
/// 1. **Flat form** (RFC 6749 §5.2): `{"error": "invalid_grant"}`
/// 2. **Nested object form**: `{"error": {"code": "invalid_grant", "message": "..."}}`
/// 3. **Nested with `type`** (some providers): `{"error": {"type": "invalid_grant", "message": "..."}}`
/// 4. **Top-level `code`** (some providers): `{"code": "invalid_grant", "message": "..."}`
///
/// Returns the matched error code (lowercased for case-insensitive matching)
/// or an empty string when the body cannot be parsed. Matching is exact
/// (normalized to lowercase) — never a substring match on free-text messages.
fn extract_error_code(body: &str) -> String {
    // Flat form: { "error": "invalid_grant" }
    #[derive(Deserialize)]
    struct FlatErrorResponse {
        #[serde(default)]
        error: Option<serde_json::Value>,
        // Some providers put the code at the top level instead of under "error".
        #[serde(default)]
        code: Option<String>,
    }

    if let Ok(parsed) = serde_json::from_str::<FlatErrorResponse>(body) {
        // If "error" is a string, use it directly.
        if let Some(serde_json::Value::String(s)) = &parsed.error
            && !s.trim().is_empty()
        {
            return s.to_lowercase();
        }

        // If "error" is an object, extract the code from the structured
        // "code" or "type" field only. We deliberately do NOT fall back to
        // the free-text "message" field — a descriptive message that happens
        // to contain a terminal code string (e.g. "invalid_grant") must not
        // be treated as a structured terminal code, per the exact-match
        // contract.
        if let Some(serde_json::Value::Object(obj)) = &parsed.error {
            let code = obj
                .get("code")
                .or_else(|| obj.get("type"))
                .and_then(|v| v.as_str())
                .filter(|s| !s.trim().is_empty());
            if let Some(c) = code {
                return c.to_lowercase();
            }
        }

        // Top-level "code" field (not under "error").
        if let Some(code) = &parsed.code
            && !code.trim().is_empty()
        {
            return code.to_lowercase();
        }
    }

    String::new()
}

/// Classify a non-success response from the OpenAI token endpoint during a
/// refresh-token grant.
///
/// ## Terminal vs. transient classification
///
/// **Terminal** — the refresh token itself is no longer usable. Stored
/// credentials are cleared so the user sees a clear "re-login" message rather
/// than repeated silent failures.
///
/// Confirmed terminal grant error codes (matched exactly, across both 400 and
/// 401 token-endpoint responses):
///
/// | Code                        | Meaning                                         |
/// |-----------------------------|-------------------------------------------------|
/// | `invalid_grant`             | Refresh token expired, revoked, or invalid      |
/// | `invalid_token`             | Token is malformed or no longer valid           |
/// | `refresh_token_expired`     | Explicit refresh-token expiry (OpenAI variant)   |
/// | `refresh_token_revoked`     | Explicit refresh-token revocation                |
/// | `refresh_token_reused`      | Refresh token was used concurrently (single-use) |
/// | `refresh_token_invalidated` | Refresh token was explicitly invalidated         |
///
/// **Transient / configuration** — the session is preserved so the user can
/// retry or fix configuration without re-authenticating:
///
/// - `invalid_client` — bad custom client ID; the refresh token may still be
///   valid once the client ID is corrected.
/// - HTTP 5xx — server-side error, likely temporary.
/// - HTTP 429 — throttling; retry with backoff.
/// - Ambiguous 401 without a confirmed terminal code — could be a transient
///   auth issue or client-configuration problem.
///
/// The raw response body is never included in the returned error to avoid
/// leaking sensitive endpoint diagnostics.
#[cold]
fn classify_refresh_status_error(status: reqwest::StatusCode, body: &str) -> anyhow::Error {
    let error_code = extract_error_code(body);

    // Only these exact codes indicate the refresh token itself is no longer
    // usable. We match exactly (not substring) to avoid false positives from
    // descriptive messages that happen to contain these words.
    const TERMINAL_GRANT_CODES: &[&str] = &[
        "invalid_grant",
        "invalid_token",
        "refresh_token_expired",
        "refresh_token_revoked",
        "refresh_token_reused",
        "refresh_token_invalidated",
    ];

    // Terminal grant errors can appear on both 400 and 401 token-endpoint
    // responses. We do NOT clear for `invalid_client` (client config issue),
    // server errors, throttling, or ambiguous 401s without a confirmed code.
    let is_client_error = status == reqwest::StatusCode::BAD_REQUEST || status == reqwest::StatusCode::UNAUTHORIZED;
    let is_terminal_grant =
        is_client_error && error_code != String::new() && TERMINAL_GRANT_CODES.iter().any(|code| error_code == *code);

    if is_terminal_grant {
        if let Err(clear_err) = clear_session_from_all_stores() {
            tracing::warn!("failed to clear expired openai chatgpt session across all stores: {clear_err}");
        }
        anyhow!("Your ChatGPT session expired. Run `vtcode login openai` again.")
    } else if error_code == "invalid_client" {
        // Client configuration error — the refresh token may still be valid
        // once the OAuth client ID/originator is corrected. Preserve the session.
        anyhow!(
            "openai token refresh failed (HTTP {status}, invalid_client) — \
             check your VTCODE_OPENAI_OAUTH_CLIENT_ID / VTCODE_OPENAI_OAUTH_ORIGINATOR configuration"
        )
    } else if status == reqwest::StatusCode::UNAUTHORIZED {
        // 401 without a confirmed terminal code is ambiguous — it could be
        // a transient auth issue or a client-configuration problem. Preserve
        // the session so the user can retry or fix config without losing auth.
        anyhow!("openai token refresh failed (HTTP {status}) — check your OAuth client configuration and retry")
    } else if status == reqwest::StatusCode::TOO_MANY_REQUESTS {
        // Throttling — transient, preserve session for retry with backoff.
        anyhow!("openai token refresh was rate-limited (HTTP {status}) — retry later")
    } else {
        // Server errors (5xx) and other non-terminal 4xx — transient.
        anyhow!("openai token refresh failed (HTTP {status})")
    }
}

fn clear_session_from_all_stores() -> Result<()> {
    let mut errors = Vec::new();

    if let Err(err) = clear_session_from_keyring() {
        errors.push(err.to_string());
    }
    if let Err(err) = clear_session_from_file() {
        errors.push(err.to_string());
    }

    if errors.is_empty() {
        Ok(())
    } else {
        Err(anyhow!("failed to clear openai session from all stores: {}", errors.join("; ")))
    }
}

fn save_session_to_keyring(serialized: &str) -> Result<()> {
    let entry = keyring::entry(OPENAI_STORAGE_SERVICE, OPENAI_STORAGE_USER)
        .context("failed to access keyring for openai session")?;
    entry
        .set_password(serialized)
        .context("failed to store openai session in keyring")?;
    Ok(())
}

fn persist_session_to_keyring_or_file(session: &OpenAIChatGptSession, serialized: &str) -> Result<()> {
    match save_session_to_keyring(serialized) {
        Ok(()) => match load_session_from_keyring_decoded() {
            Ok(Some(_)) => Ok(()),
            Ok(None) => {
                tracing::warn!(
                    "openai session keyring write did not round-trip; falling back to encrypted file storage"
                );
                save_session_to_file(session)
            }
            Err(err) => {
                tracing::warn!(
                    "openai session keyring verification failed, falling back to encrypted file storage: {err}"
                );
                save_session_to_file(session)
            }
        },
        Err(err) => {
            tracing::warn!(
                "failed to persist openai session in keyring, falling back to encrypted file storage: {err}"
            );
            save_session_to_file(session).context("failed to persist openai session after keyring fallback")
        }
    }
}

fn decode_session_from_keyring(serialized: String) -> Result<OpenAIChatGptSession> {
    serde_json::from_str(&serialized).context("failed to decode openai session")
}

fn load_session_from_keyring_decoded() -> Result<Option<OpenAIChatGptSession>> {
    load_session_from_keyring()?.map(decode_session_from_keyring).transpose()
}

fn load_preferred_openai_chatgpt_session(mode: AuthCredentialsStoreMode) -> Result<Option<OpenAIChatGptSession>> {
    match mode {
        AuthCredentialsStoreMode::Keyring => match load_session_from_keyring_decoded() {
            Ok(Some(session)) => Ok(Some(session)),
            Ok(None) => load_session_from_file(),
            Err(err) => {
                tracing::warn!("failed to load openai session from keyring, falling back to encrypted file: {err}");
                load_session_from_file()
            }
        },
        AuthCredentialsStoreMode::File => {
            if let Some(session) = load_session_from_file()? {
                return Ok(Some(session));
            }
            load_session_from_keyring_decoded()
        }
        AuthCredentialsStoreMode::Auto => unreachable!(),
    }
}

fn load_session_from_keyring() -> Result<Option<String>> {
    let entry = match keyring::entry(OPENAI_STORAGE_SERVICE, OPENAI_STORAGE_USER) {
        Ok(entry) => entry,
        Err(_) => return Ok(None),
    };

    match entry.get_password() {
        Ok(value) => Ok(Some(value)),
        Err(keyring_core::Error::NoEntry) => Ok(None),
        Err(err) => Err(anyhow!("failed to read openai session from keyring: {err}")),
    }
}

fn clear_session_from_keyring() -> Result<()> {
    let entry = match keyring::entry(OPENAI_STORAGE_SERVICE, OPENAI_STORAGE_USER) {
        Ok(entry) => entry,
        Err(_) => return Ok(()),
    };

    match entry.delete_credential() {
        Ok(()) | Err(keyring_core::Error::NoEntry) => Ok(()),
        Err(err) => Err(anyhow!("failed to clear openai session keyring entry: {err}")),
    }
}

fn save_session_to_file(session: &OpenAIChatGptSession) -> Result<()> {
    let encrypted = encrypt_session(session)?;
    let path = get_session_path()?;
    let payload = serde_json::to_vec_pretty(&encrypted)?;
    write_private_file(&path, &payload).context("failed to persist openai session file")?;
    Ok(())
}

fn load_session_from_file() -> Result<Option<OpenAIChatGptSession>> {
    let path = get_session_path()?;
    let data = match fs::read(path) {
        Ok(data) => data,
        Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(None),
        Err(err) => return Err(anyhow!("failed to read openai session file: {err}")),
    };

    let encrypted: EncryptedSession = serde_json::from_slice(&data).context("failed to decode openai session file")?;
    Ok(Some(decrypt_session(&encrypted)?))
}

fn clear_session_from_file() -> Result<()> {
    let path = get_session_path()?;
    match fs::remove_file(path) {
        Ok(()) => Ok(()),
        Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(()),
        Err(err) => Err(anyhow!("failed to delete openai session file: {err}")),
    }
}

fn get_session_path() -> Result<PathBuf> {
    Ok(auth_storage_dir()?.join(OPENAI_SESSION_FILE))
}

#[derive(Debug, Serialize, Deserialize)]
struct EncryptedSession {
    nonce: String,
    ciphertext: String,
    version: u8,
}

fn encrypt_session(session: &OpenAIChatGptSession) -> Result<EncryptedSession> {
    let key = derive_encryption_key()?;
    let rng = SystemRandom::new();
    let mut nonce_bytes = [0u8; NONCE_LEN];
    rng.fill(&mut nonce_bytes).map_err(|_| anyhow!("failed to generate nonce"))?;

    let mut ciphertext = serde_json::to_vec(session).context("failed to serialize openai session for encryption")?;
    let nonce = Nonce::assume_unique_for_key(nonce_bytes);
    key.seal_in_place_append_tag(nonce, Aad::empty(), &mut ciphertext)
        .map_err(|_| anyhow!("failed to encrypt openai session"))?;

    Ok(EncryptedSession {
        nonce: STANDARD.encode(nonce_bytes),
        ciphertext: STANDARD.encode(ciphertext),
        version: 1,
    })
}

fn decrypt_session(encrypted: &EncryptedSession) -> Result<OpenAIChatGptSession> {
    if encrypted.version != 1 {
        bail!("unsupported openai session encryption format");
    }

    let nonce_bytes = STANDARD
        .decode(&encrypted.nonce)
        .context("failed to decode openai session nonce")?;
    let nonce_array: [u8; NONCE_LEN] = nonce_bytes
        .try_into()
        .map_err(|_| anyhow!("invalid openai session nonce length"))?;
    let mut ciphertext = STANDARD
        .decode(&encrypted.ciphertext)
        .context("failed to decode openai session ciphertext")?;

    let key = derive_encryption_key()?;
    let plaintext = key
        .open_in_place(Nonce::assume_unique_for_key(nonce_array), Aad::empty(), &mut ciphertext)
        .map_err(|_| anyhow!("failed to decrypt openai session"))?;
    serde_json::from_slice(plaintext).context("failed to parse decrypted openai session")
}

fn derive_encryption_key() -> Result<LessSafeKey> {
    use ring::digest::{SHA256, digest};

    let mut key_material = Vec::new();
    if let Ok(hostname) = hostname::get() {
        key_material.extend_from_slice(hostname.as_encoded_bytes());
    }

    #[cfg(unix)]
    {
        key_material.extend_from_slice(&nix::unistd::getuid().as_raw().to_le_bytes());
    }
    #[cfg(not(unix))]
    {
        if let Ok(user) = std::env::var("USER").or_else(|_| std::env::var("USERNAME")) {
            key_material.extend_from_slice(user.as_bytes());
        }
    }

    key_material.extend_from_slice(b"vtcode-openai-chatgpt-oauth-v1");
    let hash = digest(&SHA256, &key_material);
    let key_bytes: &[u8; 32] = hash
        .as_ref()
        .get(..32)
        .context("openai session encryption key was too short")?
        .try_into()
        .context("openai session encryption key had an invalid length")?;
    let unbound =
        UnboundKey::new(&aead::AES_256_GCM, key_bytes).map_err(|_| anyhow!("invalid openai session encryption key"))?;
    Ok(LessSafeKey::new(unbound))
}

fn now_secs() -> u64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|duration| duration.as_secs())
        .unwrap_or(0)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::AuthCallbackOutcome;
    use crate::generate_pkce_challenge;
    use assert_fs::TempDir;
    use serial_test::serial;
    use std::sync::Arc;

    struct ExternalRefresher;

    #[async_trait]
    impl OpenAIChatGptSessionRefresher for ExternalRefresher {
        async fn refresh_session(&self, current: &OpenAIChatGptSession) -> Result<OpenAIChatGptSession> {
            let mut refreshed = current.clone();
            refreshed.access_token = "oauth-access-refreshed".to_string();
            refreshed.refreshed_at = current.refreshed_at.saturating_add(1);
            refreshed.expires_at = Some(now_secs() + 3600);
            Ok(refreshed)
        }
    }

    struct TestAuthDirGuard {
        temp_dir: Option<TempDir>,
        codex_temp_dir: Option<TempDir>,
        previous: Option<PathBuf>,
        previous_codex_home: Option<String>,
    }

    impl TestAuthDirGuard {
        fn new() -> Self {
            let temp_dir = TempDir::new().expect("create temp auth dir");
            let previous = crate::storage_paths::auth_storage_dir_override_for_tests().expect("read auth dir override");
            crate::storage_paths::set_auth_storage_dir_override_for_tests(Some(temp_dir.path().to_path_buf()))
                .expect("set temp auth dir override");

            // Isolate CODEX_HOME so the Codex auth.json fallback doesn't pick
            // up a real Codex session from the user's machine during tests.
            let codex_temp_dir = TempDir::new().expect("create temp codex home");
            let previous_codex_home = std::env::var("CODEX_HOME").ok();
            vtcode_commons::env_lock::set_var("CODEX_HOME", codex_temp_dir.path());

            Self {
                temp_dir: Some(temp_dir),
                codex_temp_dir: Some(codex_temp_dir),
                previous,
                previous_codex_home,
            }
        }
    }

    impl Drop for TestAuthDirGuard {
        fn drop(&mut self) {
            crate::storage_paths::set_auth_storage_dir_override_for_tests(self.previous.clone())
                .expect("restore auth dir override");
            if let Some(temp_dir) = self.temp_dir.take() {
                temp_dir.close().expect("remove temp auth dir");
            }
            vtcode_commons::env_lock::lock().restore_var("CODEX_HOME", self.previous_codex_home.as_deref());
            if let Some(codex_temp_dir) = self.codex_temp_dir.take() {
                codex_temp_dir.close().expect("remove temp codex home");
            }
        }
    }

    fn sample_session() -> OpenAIChatGptSession {
        OpenAIChatGptSession {
            openai_api_key: "api-key".to_string(),
            id_token: "aGVhZGVy.eyJlbWFpbCI6InRlc3RAZXhhbXBsZS5jb20iLCJodHRwczovL2FwaS5vcGVuYWkuY29tL2F1dGgiOnsiY2hhdGdwdF9hY2NvdW50X2lkIjoiYWNjXzEyMyIsImNoYXRncHRfcGxhbl90eXBlIjoicGx1cyJ9fQ.sig".to_string(),
            access_token: "oauth-access".to_string(),
            refresh_token: "refresh-token".to_string(),
            account_id: Some("acc_123".to_string()),
            email: Some("test@example.com".to_string()),
            plan: Some("plus".to_string()),
            obtained_at: 10,
            refreshed_at: 10,
            expires_at: Some(now_secs() + 3600),
        }
    }

    #[test]
    fn auth_url_contains_expected_openai_parameters() {
        // RAII guard locks env and restores both vars on drop (panic-safe).
        let env = OauthEnvGuard::new();
        env.remove_client_id();
        env.remove_originator();

        let challenge = PkceChallenge {
            code_verifier: "verifier".to_string(),
            code_challenge: "challenge".to_string(),
            code_challenge_method: "S256".to_string(),
        };

        let url = get_openai_chatgpt_auth_url(&challenge, 1455, "test-state").expect("auth url");
        assert!(url.starts_with(OPENAI_AUTH_URL));
        assert!(url.contains("client_id=app_EMoamEEZ73f0CkXaXp7hrann"));
        assert!(url.contains("code_challenge=challenge"));
        assert!(url.contains("codex_cli_simplified_flow=true"));
        assert!(url.contains("redirect_uri=http%3A%2F%2Flocalhost%3A1455%2Fauth%2Fcallback"));
        assert!(url.contains("state=test-state"));
    }

    #[test]
    fn auth_url_honors_custom_client_id_env_override() {
        // RAII guard locks env and restores both vars on drop (panic-safe).
        let env = OauthEnvGuard::new();
        env.set_client_id("app_custom_override");
        env.set_originator("vtcode_custom");

        let challenge = PkceChallenge {
            code_verifier: "verifier".to_string(),
            code_challenge: "challenge".to_string(),
            code_challenge_method: "S256".to_string(),
        };
        let url = get_openai_chatgpt_auth_url(&challenge, 1455, "test-state").expect("auth url");
        assert!(url.contains("client_id=app_custom_override"), "custom client_id not used: {url}");
        assert!(url.contains("originator=vtcode_custom"), "custom originator not used: {url}");
        assert!(!url.contains("app_EMoamEEZ73f0CkXaXp7hrann"), "default client_id leaked through override: {url}");
    }

    /// RAII guard that locks the environment and restores both OAuth identity
    /// env vars on drop — even if the test panics. This ensures parallel
    /// tests don't leak env mutations to each other.
    struct OauthEnvGuard {
        env: vtcode_commons::env_lock::EnvGuard,
        prev_client_id: Option<std::ffi::OsString>,
        prev_originator: Option<std::ffi::OsString>,
    }

    impl OauthEnvGuard {
        fn new() -> Self {
            let env = vtcode_commons::env_lock::lock();
            let prev_client_id = std::env::var_os("VTCODE_OPENAI_OAUTH_CLIENT_ID");
            let prev_originator = std::env::var_os("VTCODE_OPENAI_OAUTH_ORIGINATOR");
            Self { env, prev_client_id, prev_originator }
        }

        fn set_client_id(&self, value: &str) {
            self.env.set_var("VTCODE_OPENAI_OAUTH_CLIENT_ID", value);
        }

        fn set_originator(&self, value: &str) {
            self.env.set_var("VTCODE_OPENAI_OAUTH_ORIGINATOR", value);
        }

        fn remove_client_id(&self) {
            self.env.remove_var("VTCODE_OPENAI_OAUTH_CLIENT_ID");
        }

        fn remove_originator(&self) {
            self.env.remove_var("VTCODE_OPENAI_OAUTH_ORIGINATOR");
        }
    }

    impl Drop for OauthEnvGuard {
        fn drop(&mut self) {
            self.env
                .restore_var("VTCODE_OPENAI_OAUTH_CLIENT_ID", self.prev_client_id.take());
            self.env
                .restore_var("VTCODE_OPENAI_OAUTH_ORIGINATOR", self.prev_originator.take());
        }
    }

    #[test]
    fn resolve_oauth_client_identity_both_defaults() {
        let env = OauthEnvGuard::new();
        env.remove_client_id();
        env.remove_originator();

        let identity = resolve_oauth_client_identity().expect("defaults");
        assert_eq!(identity.client_id, DEFAULT_OPENAI_CLIENT_ID);
        assert_eq!(identity.originator, DEFAULT_OPENAI_ORIGINATOR);
    }

    #[test]
    fn resolve_oauth_client_identity_both_custom() {
        let env = OauthEnvGuard::new();
        env.set_client_id("app_custom");
        env.set_originator("my_originator");

        let identity = resolve_oauth_client_identity().expect("custom pair");
        assert_eq!(identity.client_id, "app_custom");
        assert_eq!(identity.originator, "my_originator");
    }

    #[test]
    fn resolve_oauth_client_identity_only_client_id_is_error() {
        let env = OauthEnvGuard::new();
        env.set_client_id("app_custom");
        env.remove_originator();

        let err = resolve_oauth_client_identity().unwrap_err();
        let msg = err.to_string();
        assert!(msg.contains("VTCODE_OPENAI_OAUTH_CLIENT_ID"), "error should name the set var: {msg}");
        assert!(msg.contains("VTCODE_OPENAI_OAUTH_ORIGINATOR"), "error should name the missing var: {msg}");
    }

    #[test]
    fn resolve_oauth_client_identity_only_originator_is_error() {
        let env = OauthEnvGuard::new();
        env.remove_client_id();
        env.set_originator("my_originator");

        let err = resolve_oauth_client_identity().unwrap_err();
        let msg = err.to_string();
        assert!(msg.contains("VTCODE_OPENAI_OAUTH_ORIGINATOR"), "error should name the set var: {msg}");
        assert!(msg.contains("VTCODE_OPENAI_OAUTH_CLIENT_ID"), "error should name the missing var: {msg}");
    }

    #[test]
    fn resolve_oauth_client_identity_blank_values_treated_as_unset() {
        let env = OauthEnvGuard::new();
        env.set_client_id("   ");
        env.set_originator("  ");

        // Blank values are treated as unset → defaults used.
        let identity = resolve_oauth_client_identity().expect("defaults from blank");
        assert_eq!(identity.client_id, DEFAULT_OPENAI_CLIENT_ID);
        assert_eq!(identity.originator, DEFAULT_OPENAI_ORIGINATOR);
    }

    #[test]
    fn parse_jwt_claims_extracts_openai_claims() {
        let claims = parse_jwt_claims(
            "aGVhZGVy.eyJlbWFpbCI6InRlc3RAZXhhbXBsZS5jb20iLCJodHRwczovL2FwaS5vcGVuYWkuY29tL2F1dGgiOnsiY2hhdGdwdF9hY2NvdW50X2lkIjoiYWNjXzEyMyIsImNoYXRncHRfcGxhbl90eXBlIjoicGx1cyJ9fQ.sig",
        )
        .expect("claims");
        assert_eq!(claims.email.as_deref(), Some("test@example.com"));
        assert_eq!(claims.account_id.as_deref(), Some("acc_123"));
        assert_eq!(claims.plan.as_deref(), Some("plus"));
    }

    #[test]
    fn session_refresh_due_uses_expiry_and_age() {
        let mut session = sample_session();
        let now = now_secs();
        session.obtained_at = now;
        session.refreshed_at = now;
        session.expires_at = Some(now + 3600);
        assert!(!session.is_refresh_due());
        session.expires_at = Some(now);
        assert!(session.is_refresh_due());
    }

    #[tokio::test]
    #[serial]
    async fn external_auth_handle_refreshes_without_persisting_session() {
        let _guard = TestAuthDirGuard::new();
        let mut session = sample_session();
        session.openai_api_key.clear();
        session.expires_at = Some(now_secs().saturating_sub(1));
        let handle = OpenAIChatGptAuthHandle::new_external(session, true, Arc::new(ExternalRefresher));

        assert!(handle.using_external_tokens());
        assert!(
            load_openai_chatgpt_session_with_mode(AuthCredentialsStoreMode::File)
                .expect("load session")
                .is_none()
        );

        handle.force_refresh().await.expect("force refresh");

        assert_eq!(handle.current_api_key().expect("current api key"), "oauth-access-refreshed");
        assert!(
            load_openai_chatgpt_session_with_mode(AuthCredentialsStoreMode::File)
                .expect("load session")
                .is_none()
        );
    }

    struct CountingExternalRefresher {
        calls: Arc<Mutex<usize>>,
    }

    #[async_trait]
    impl OpenAIChatGptSessionRefresher for CountingExternalRefresher {
        async fn refresh_session(&self, current: &OpenAIChatGptSession) -> Result<OpenAIChatGptSession> {
            let mut calls = self.calls.lock().expect("refresh calls mutex should lock");
            *calls += 1;
            drop(calls);

            let mut refreshed = current.clone();
            refreshed.access_token = "oauth-access-refreshed".to_string();
            refreshed.refreshed_at = now_secs();
            refreshed.expires_at = Some(now_secs() + 3600);
            Ok(refreshed)
        }
    }

    #[tokio::test]
    async fn refresh_if_needed_serializes_external_refreshes() {
        let mut session = sample_session();
        session.openai_api_key.clear();
        session.expires_at = Some(now_secs().saturating_sub(1));
        let calls = Arc::new(Mutex::new(0usize));
        let handle = OpenAIChatGptAuthHandle::new_external(
            session,
            true,
            Arc::new(CountingExternalRefresher { calls: Arc::clone(&calls) }),
        );

        let first = handle.clone();
        let second = handle.clone();
        let (first_result, second_result) = tokio::join!(first.refresh_if_needed(), second.refresh_if_needed());

        first_result.expect("first refresh should succeed");
        second_result.expect("second refresh should succeed");
        assert_eq!(
            *calls.lock().expect("refresh calls mutex should lock"),
            1,
            "concurrent refresh_if_needed calls should share one refresh"
        );
        assert_eq!(handle.current_api_key().expect("current api key"), "oauth-access-refreshed");
    }

    #[test]
    #[serial]
    fn resolve_openai_auth_prefers_chatgpt_in_auto_permission() {
        let _guard = TestAuthDirGuard::new();
        let session = sample_session();
        save_openai_chatgpt_session_with_mode(&session, AuthCredentialsStoreMode::File).expect("save session");
        let resolved = resolve_openai_auth(
            &OpenAIAuthConfig::default(),
            AuthCredentialsStoreMode::File,
            Some("api-key".to_string()),
        )
        .expect("resolved auth");
        assert!(resolved.using_chatgpt());
        clear_openai_chatgpt_session_with_mode(AuthCredentialsStoreMode::File).expect("clear session");
    }

    #[test]
    #[serial]
    #[cfg(unix)]
    fn file_storage_uses_private_permissions() {
        use std::fs;
        use std::os::unix::fs::PermissionsExt;

        let _guard = TestAuthDirGuard::new();
        let session = sample_session();

        save_openai_chatgpt_session_with_mode(&session, AuthCredentialsStoreMode::File).expect("save session");

        let metadata = fs::metadata(get_session_path().expect("session path")).expect("read session metadata");
        assert_eq!(metadata.permissions().mode() & 0o777, 0o600);
    }

    #[test]
    #[serial]
    fn resolve_openai_auth_auto_falls_back_to_api_key_without_session() {
        let _guard = TestAuthDirGuard::new();
        clear_openai_chatgpt_session_with_mode(AuthCredentialsStoreMode::File).expect("clear session");
        let resolved = resolve_openai_auth(
            &OpenAIAuthConfig::default(),
            AuthCredentialsStoreMode::File,
            Some("api-key".to_string()),
        )
        .expect("resolved auth");
        assert!(matches!(resolved, OpenAIResolvedAuth::ApiKey { .. }));
    }

    #[test]
    #[serial]
    fn resolve_openai_auth_auto_rejects_blank_api_key_without_session() {
        let _guard = TestAuthDirGuard::new();
        clear_openai_chatgpt_session_with_mode(AuthCredentialsStoreMode::File).expect("clear session");
        let error =
            resolve_openai_auth(&OpenAIAuthConfig::default(), AuthCredentialsStoreMode::File, Some("   ".to_string()))
                .expect_err("blank api key should fail");
        assert!(error.to_string().contains("OpenAI API key not found"));
    }

    #[test]
    #[serial]
    fn resolve_openai_auth_api_key_mode_ignores_stored_chatgpt_session() {
        let _guard = TestAuthDirGuard::new();
        let session = sample_session();
        save_openai_chatgpt_session_with_mode(&session, AuthCredentialsStoreMode::File).expect("save session");
        let resolved = resolve_openai_auth(
            &OpenAIAuthConfig {
                preferred_method: OpenAIPreferredMethod::ApiKey,
                ..OpenAIAuthConfig::default()
            },
            AuthCredentialsStoreMode::File,
            Some("api-key".to_string()),
        )
        .expect("resolved auth");
        assert!(matches!(resolved, OpenAIResolvedAuth::ApiKey { .. }));
        clear_openai_chatgpt_session_with_mode(AuthCredentialsStoreMode::File).expect("clear session");
    }

    #[test]
    #[serial]
    fn resolve_openai_auth_chatgpt_mode_requires_stored_session() {
        let _guard = TestAuthDirGuard::new();
        clear_openai_chatgpt_session_with_mode(AuthCredentialsStoreMode::File).expect("clear session");
        let error = resolve_openai_auth(
            &OpenAIAuthConfig {
                preferred_method: OpenAIPreferredMethod::Chatgpt,
                ..OpenAIAuthConfig::default()
            },
            AuthCredentialsStoreMode::File,
            Some("api-key".to_string()),
        )
        .expect_err("chatgpt mode should require a stored session");
        assert!(error.to_string().contains("vtcode login openai"));
    }

    #[test]
    #[serial]
    fn summarize_openai_credentials_reports_dual_source_notice() {
        let _guard = TestAuthDirGuard::new();
        let session = sample_session();
        save_openai_chatgpt_session_with_mode(&session, AuthCredentialsStoreMode::File).expect("save session");
        let overview = summarize_openai_credentials(
            &OpenAIAuthConfig::default(),
            AuthCredentialsStoreMode::File,
            Some("api-key".to_string()),
        )
        .expect("overview");
        assert_eq!(overview.active_source, Some(OpenAIResolvedAuthSource::ChatGpt));
        assert!(overview.notice.is_some());
        assert!(overview.recommendation.is_some());
        clear_openai_chatgpt_session_with_mode(AuthCredentialsStoreMode::File).expect("clear session");
    }

    #[test]
    #[serial]
    fn summarize_openai_credentials_respects_api_key_preference() {
        let _guard = TestAuthDirGuard::new();
        let session = sample_session();
        save_openai_chatgpt_session_with_mode(&session, AuthCredentialsStoreMode::File).expect("save session");
        let overview = summarize_openai_credentials(
            &OpenAIAuthConfig {
                preferred_method: OpenAIPreferredMethod::ApiKey,
                ..OpenAIAuthConfig::default()
            },
            AuthCredentialsStoreMode::File,
            Some("api-key".to_string()),
        )
        .expect("overview");
        assert_eq!(overview.active_source, Some(OpenAIResolvedAuthSource::ApiKey));
        clear_openai_chatgpt_session_with_mode(AuthCredentialsStoreMode::File).expect("clear session");
    }

    #[test]
    fn encrypted_file_round_trip_restores_session() {
        let session = sample_session();
        let encrypted = encrypt_session(&session).expect("encrypt");
        let decrypted = decrypt_session(&encrypted).expect("decrypt");
        assert_eq!(decrypted.account_id, session.account_id);
        assert_eq!(decrypted.email, session.email);
        assert_eq!(decrypted.plan, session.plan);
    }

    #[test]
    #[serial]
    fn default_loader_falls_back_to_file_session() {
        let _guard = TestAuthDirGuard::new();
        let session = sample_session();
        save_openai_chatgpt_session_with_mode(&session, AuthCredentialsStoreMode::File).expect("save session");

        let loaded = load_openai_chatgpt_session()
            .expect("load session")
            .expect("stored session should be found");

        assert_eq!(loaded.account_id, session.account_id);
        clear_openai_chatgpt_session_with_mode(AuthCredentialsStoreMode::File).expect("clear session");
    }

    #[test]
    #[serial]
    fn keyring_mode_loader_falls_back_to_file_session() {
        let _guard = TestAuthDirGuard::new();
        let session = sample_session();
        save_openai_chatgpt_session_with_mode(&session, AuthCredentialsStoreMode::File).expect("save session");

        let loaded = load_openai_chatgpt_session_with_mode(AuthCredentialsStoreMode::Keyring)
            .expect("load session")
            .expect("stored session should be found");

        assert_eq!(loaded.email, session.email);
        clear_openai_chatgpt_session_with_mode(AuthCredentialsStoreMode::File).expect("clear session");
    }

    #[test]
    #[serial]
    fn clear_openai_chatgpt_session_removes_file_and_keyring_sessions() {
        let _guard = TestAuthDirGuard::new();
        let session = sample_session();
        save_openai_chatgpt_session_with_mode(&session, AuthCredentialsStoreMode::File).expect("save file session");

        if save_openai_chatgpt_session_with_mode(&session, AuthCredentialsStoreMode::Keyring).is_err() {
            clear_openai_chatgpt_session().expect("clear session");
            assert!(
                load_openai_chatgpt_session_with_mode(AuthCredentialsStoreMode::File)
                    .expect("load file session")
                    .is_none()
            );
            return;
        }

        clear_openai_chatgpt_session().expect("clear session");
        assert!(
            load_openai_chatgpt_session_with_mode(AuthCredentialsStoreMode::File)
                .expect("load file session")
                .is_none()
        );
        assert!(
            load_openai_chatgpt_session_with_mode(AuthCredentialsStoreMode::Keyring)
                .expect("load keyring session")
                .is_none()
        );
    }

    #[test]
    fn active_api_bearer_token_falls_back_to_access_token() {
        let mut session = sample_session();
        session.openai_api_key.clear();

        assert_eq!(active_api_bearer_token(&session), "oauth-access");
    }

    #[test]
    fn parse_manual_callback_input_accepts_full_redirect_url() {
        let code = parse_openai_chatgpt_manual_callback_input(
            "http://localhost:1455/auth/callback?code=auth-code&state=test-state",
            "test-state",
        )
        .expect("manual input should parse");
        assert_eq!(code, "auth-code");
    }

    #[test]
    fn parse_manual_callback_input_accepts_query_string() {
        let code = parse_openai_chatgpt_manual_callback_input("code=auth-code&state=test-state", "test-state")
            .expect("manual input should parse");
        assert_eq!(code, "auth-code");
    }

    #[test]
    fn parse_manual_callback_input_rejects_bare_code() {
        let error = parse_openai_chatgpt_manual_callback_input("auth-code", "test-state")
            .expect_err("bare code should be rejected");
        assert!(error.to_string().contains("full redirect url or query string"));
    }

    #[test]
    fn parse_manual_callback_input_rejects_state_mismatch() {
        let error = parse_openai_chatgpt_manual_callback_input("code=auth-code&state=wrong-state", "test-state")
            .expect_err("state mismatch should fail");
        assert!(error.to_string().contains("state mismatch"));
    }

    #[tokio::test]
    #[serial]
    async fn refresh_lock_serializes_parallel_acquisition() {
        let _guard = TestAuthDirGuard::new();
        let first = tokio::spawn(async {
            let _lock = acquire_refresh_lock().await.expect("first lock");
            tokio::time::sleep(std::time::Duration::from_millis(150)).await;
        });
        tokio::time::sleep(std::time::Duration::from_millis(20)).await;

        let start = std::time::Instant::now();
        let second = tokio::spawn(async {
            let _lock = acquire_refresh_lock().await.expect("second lock");
        });

        first.await.expect("first task");
        second.await.expect("second task");
        assert!(start.elapsed() >= std::time::Duration::from_millis(100));
    }

    // ── Debug redaction tests ──

    #[test]
    fn debug_impl_redacts_all_token_fields() {
        let session = sample_session();
        let debug_str = format!("{session:?}");
        // None of the secret values may appear in the Debug output.
        assert!(!debug_str.contains("api-key"), "openai_api_key leaked: {debug_str}");
        assert!(!debug_str.contains("oauth-access"), "access_token leaked: {debug_str}");
        assert!(!debug_str.contains("refresh-token"), "refresh_token leaked: {debug_str}");
        // The id_token JWT body is long; check a distinctive substring.
        assert!(!debug_str.contains("eyJlbWFpbCI6InRlc3RAZXhhbXBsZS5jb20i"), "id_token leaked: {debug_str}");
        // Non-secret metadata should still be present.
        assert!(debug_str.contains("test@example.com"), "email should be visible: {debug_str}");
        assert!(debug_str.contains("plus"), "plan should be visible: {debug_str}");
    }

    #[test]
    fn debug_impl_redacts_resolved_auth_api_key() {
        let resolved = OpenAIResolvedAuth::ApiKey { api_key: "sk-secret-key".to_string() };
        let debug_str = format!("{resolved:?}");
        assert!(!debug_str.contains("sk-secret-key"), "api_key leaked: {debug_str}");
    }

    #[test]
    fn debug_impl_redacts_resolved_auth_chatgpt_handle() {
        let _guard = TestAuthDirGuard::new();
        let session = sample_session();
        let handle = OpenAIChatGptAuthHandle::new(session, OpenAIAuthConfig::default(), AuthCredentialsStoreMode::File);
        let resolved = OpenAIResolvedAuth::ChatGpt { api_key: "sk-secret-bearer".to_string(), handle };
        let debug_str = format!("{resolved:?}");
        assert!(!debug_str.contains("sk-secret-bearer"), "bearer leaked: {debug_str}");
    }

    #[test]
    fn credential_overview_carries_no_token_fields() {
        let _guard = TestAuthDirGuard::new();
        let session = sample_session();
        save_openai_chatgpt_session_with_mode(&session, AuthCredentialsStoreMode::File).expect("save");
        let overview = summarize_openai_credentials(
            &OpenAIAuthConfig::default(),
            AuthCredentialsStoreMode::File,
            Some("sk-overview-key".to_string()),
        )
        .expect("overview");
        // The overview is a display struct — verify it only carries metadata,
        // not the raw session or token strings.
        let debug_str = format!("{overview:?}");
        assert!(!debug_str.contains("oauth-access"), "access_token leaked: {debug_str}");
        assert!(!debug_str.contains("refresh-token"), "refresh_token leaked: {debug_str}");
        assert!(!debug_str.contains("api-key"), "openai_api_key leaked: {debug_str}");
        // The overview should not contain the raw API key value either.
        assert!(!debug_str.contains("sk-overview-key"), "api key value leaked: {debug_str}");
        clear_openai_chatgpt_session_with_mode(AuthCredentialsStoreMode::File).expect("clear");
    }

    // ── Partial refresh response merge tests ──
    //
    // These test merge_refresh_response directly with resp.id_token = None,
    // which skips the HTTP API-key exchange (has_new_id_token = false).
    // This lets us verify field-preservation behavior without network access.

    #[tokio::test]
    async fn merge_preserves_omitted_access_token() {
        let current = sample_session();
        let resp = OpenAIRefreshResponse {
            id_token: None,
            access_token: None,
            refresh_token: Some("new-refresh".to_string()),
            expires_in: Some(3600),
        };
        let merged = merge_refresh_response(&current, resp).await.expect("merge");
        assert_eq!(merged.access_token, current.access_token, "omitted access_token should be preserved");
        assert_eq!(merged.refresh_token, "new-refresh");
    }

    #[tokio::test]
    async fn merge_preserves_omitted_refresh_token() {
        let current = sample_session();
        let resp = OpenAIRefreshResponse {
            id_token: None,
            access_token: Some("new-access".to_string()),
            refresh_token: None,
            expires_in: None,
        };
        let merged = merge_refresh_response(&current, resp).await.expect("merge");
        assert_eq!(merged.refresh_token, current.refresh_token, "omitted refresh_token should be preserved");
        assert_eq!(merged.access_token, "new-access");
    }

    #[tokio::test]
    async fn merge_preserves_omitted_id_token_and_api_key() {
        let current = sample_session();
        let resp = OpenAIRefreshResponse {
            id_token: None,
            access_token: Some("new-access".to_string()),
            refresh_token: None,
            expires_in: Some(1800),
        };
        let merged = merge_refresh_response(&current, resp).await.expect("merge");
        // No new id_token → old id_token and api_key preserved, no HTTP exchange.
        assert_eq!(merged.id_token, current.id_token, "omitted id_token should be preserved");
        assert_eq!(merged.openai_api_key, current.openai_api_key, "api_key should be preserved without new id_token");
        // Email/plan/account_id also preserved without a new id_token.
        assert_eq!(merged.email, current.email);
        assert_eq!(merged.plan, current.plan);
    }

    #[tokio::test]
    async fn merge_all_omitted_preserves_everything() {
        let current = sample_session();
        let resp = OpenAIRefreshResponse {
            id_token: None,
            access_token: None,
            refresh_token: None,
            expires_in: None,
        };
        let merged = merge_refresh_response(&current, resp).await.expect("merge");
        assert_eq!(merged.id_token, current.id_token);
        assert_eq!(merged.access_token, current.access_token);
        assert_eq!(merged.refresh_token, current.refresh_token);
        assert_eq!(merged.openai_api_key, current.openai_api_key);
        assert_eq!(merged.email, current.email);
        // expires_in is None and no new access_token → old expiry preserved.
        assert_eq!(merged.expires_at, current.expires_at);
    }

    #[tokio::test]
    async fn merge_new_access_token_updates_bearer_without_id_token() {
        let current = sample_session();
        let resp = OpenAIRefreshResponse {
            id_token: None,
            access_token: Some("replaced-access".to_string()),
            refresh_token: None,
            expires_in: Some(7200),
        };
        let merged = merge_refresh_response(&current, resp).await.expect("merge");
        assert_eq!(merged.access_token, "replaced-access");
        // active_api_bearer_token should use the exchanged api_key (unchanged)
        // because no new id_token was provided.
        assert_eq!(active_api_bearer_token(&merged), current.openai_api_key);
    }

    // ── Blank-string refresh field tests ──
    //
    // Some token endpoints return empty strings for omitted fields rather than
    // leaving them out. These verify that blank strings are treated as omitted.

    #[tokio::test]
    async fn merge_treats_blank_access_token_as_omitted() {
        let current = sample_session();
        let resp = OpenAIRefreshResponse {
            id_token: None,
            access_token: Some("   ".to_string()),
            refresh_token: Some("new-refresh".to_string()),
            expires_in: Some(3600),
        };
        let merged = merge_refresh_response(&current, resp).await.expect("merge");
        assert_eq!(merged.access_token, current.access_token, "blank access_token should be treated as omitted");
        assert_eq!(merged.refresh_token, "new-refresh");
    }

    #[tokio::test]
    async fn merge_treats_blank_refresh_token_as_omitted() {
        let current = sample_session();
        let resp = OpenAIRefreshResponse {
            id_token: None,
            access_token: Some("new-access".to_string()),
            refresh_token: Some(String::new()),
            expires_in: None,
        };
        let merged = merge_refresh_response(&current, resp).await.expect("merge");
        assert_eq!(merged.refresh_token, current.refresh_token, "blank refresh_token should be treated as omitted");
        assert_eq!(merged.access_token, "new-access");
    }

    #[tokio::test]
    async fn merge_treats_blank_id_token_as_omitted() {
        let current = sample_session();
        let resp = OpenAIRefreshResponse {
            id_token: Some("  ".to_string()),
            access_token: Some("new-access".to_string()),
            refresh_token: None,
            expires_in: None,
        };
        let merged = merge_refresh_response(&current, resp).await.expect("merge");
        // Blank id_token → treated as omitted → no HTTP exchange, old preserved.
        assert_eq!(merged.id_token, current.id_token, "blank id_token should be treated as omitted");
        assert_eq!(merged.openai_api_key, current.openai_api_key, "api_key preserved when id_token is blank");
    }

    // ── Opaque access token expiry tests ──

    #[tokio::test]
    async fn merge_changed_opaque_access_token_clears_stale_expiry() {
        let mut current = sample_session();
        current.expires_at = Some(now_secs() + 3600); // old expiry for old token

        // New access token without expires_in and without a parseable JWT exp.
        // "opaque-new-token" is not a JWT, so parse_jwt_exp returns None.
        let resp = OpenAIRefreshResponse {
            id_token: None,
            access_token: Some("opaque-new-token".to_string()),
            refresh_token: None,
            expires_in: None,
        };
        let merged = merge_refresh_response(&current, resp).await.expect("merge");
        assert_eq!(merged.access_token, "opaque-new-token");
        // Changed token without expires_in or JWT exp → expiry must be None,
        // NOT the old token's expiry.
        assert_eq!(merged.expires_at, None, "changed opaque access token must not inherit old token's expiry");
    }

    #[tokio::test]
    async fn merge_repeated_opaque_access_token_preserves_expiry() {
        let old_expiry = now_secs() + 3600;
        let mut current = sample_session();
        current.access_token = "opaque-same-token".to_string();
        current.expires_at = Some(old_expiry);

        // The endpoint repeats the SAME opaque access token without expires_in.
        // Since the token didn't change, the old expiry is still valid.
        let resp = OpenAIRefreshResponse {
            id_token: None,
            access_token: Some("opaque-same-token".to_string()),
            refresh_token: Some("new-refresh".to_string()),
            expires_in: None,
        };
        let merged = merge_refresh_response(&current, resp).await.expect("merge");
        assert_eq!(merged.access_token, "opaque-same-token");
        assert_eq!(merged.expires_at, Some(old_expiry), "repeated same opaque access token must preserve old expiry");
    }

    #[tokio::test]
    async fn merge_omitted_access_token_preserves_old_expiry() {
        let old_expiry = now_secs() + 3600;
        let mut current = sample_session();
        current.expires_at = Some(old_expiry);

        let resp = OpenAIRefreshResponse {
            id_token: None,
            access_token: None,
            refresh_token: Some("new-refresh".to_string()),
            expires_in: None,
        };
        let merged = merge_refresh_response(&current, resp).await.expect("merge");
        // No new access_token and no expires_in → old expiry preserved.
        assert_eq!(merged.expires_at, Some(old_expiry), "omitted access_token should preserve old expiry");
    }

    #[tokio::test]
    async fn merge_expires_in_overrides_for_omitted_access_token() {
        let old_expiry = now_secs() + 3600;
        let mut current = sample_session();
        current.expires_at = Some(old_expiry);

        let resp = OpenAIRefreshResponse {
            id_token: None,
            access_token: None,
            refresh_token: None,
            expires_in: Some(1800),
        };
        let merged = merge_refresh_response(&current, resp).await.expect("merge");
        // expires_in takes priority over old expiry even without a new access_token.
        assert_ne!(merged.expires_at, Some(old_expiry));
        assert!(merged.expires_at.is_some());
    }

    // ── Error classification tests (pure, no network) ──

    #[test]
    fn extract_error_code_flat_form() {
        assert_eq!(extract_error_code(r#"{"error": "invalid_grant"}"#), "invalid_grant");
    }

    #[test]
    fn extract_error_code_nested_form() {
        let body = r#"{"error": {"code": "refresh_token_expired", "message": "token expired"}}"#;
        assert_eq!(extract_error_code(body), "refresh_token_expired");
    }

    #[test]
    fn extract_error_code_nested_form_does_not_fall_back_to_message() {
        // A descriptive message that happens to contain a terminal code string
        // must NOT be treated as a structured error code. Only `code` and
        // `type` fields are recognized — `message` is free-text.
        let body = r#"{"error": {"message": "invalid_grant"}}"#;
        assert_eq!(extract_error_code(body), "", "message field should not be used as error code: {body}");
    }

    #[test]
    fn extract_error_code_empty_body() {
        assert_eq!(extract_error_code(""), "");
    }

    #[test]
    fn extract_error_code_non_json_body() {
        assert_eq!(extract_error_code("Internal Server Error"), "");
    }

    #[test]
    fn extract_error_code_blank_error_field() {
        assert_eq!(extract_error_code(r#"{"error": "  "}"#), "");
    }

    #[test]
    fn classify_refresh_status_error_invalid_grant_clears_session() {
        let _guard = TestAuthDirGuard::new();
        // Store a session so we can verify it gets cleared.
        let session = sample_session();
        save_openai_chatgpt_session_with_mode(&session, AuthCredentialsStoreMode::File).expect("save");
        assert!(
            load_openai_chatgpt_session_with_mode(AuthCredentialsStoreMode::File)
                .expect("load")
                .is_some()
        );

        let err = classify_refresh_status_error(reqwest::StatusCode::BAD_REQUEST, r#"{"error": "invalid_grant"}"#);
        assert!(err.to_string().contains("session expired"));

        // Session should have been cleared.
        assert!(
            load_openai_chatgpt_session_with_mode(AuthCredentialsStoreMode::File)
                .expect("load")
                .is_none()
        );
    }

    #[test]
    fn classify_refresh_status_error_nested_refresh_token_expired_clears_session() {
        let _guard = TestAuthDirGuard::new();
        let session = sample_session();
        save_openai_chatgpt_session_with_mode(&session, AuthCredentialsStoreMode::File).expect("save");

        let err = classify_refresh_status_error(
            reqwest::StatusCode::BAD_REQUEST,
            r#"{"error": {"code": "refresh_token_expired", "message": "The refresh token has expired"}}"#,
        );
        assert!(err.to_string().contains("session expired"));

        assert!(
            load_openai_chatgpt_session_with_mode(AuthCredentialsStoreMode::File)
                .expect("load")
                .is_none()
        );
    }

    #[test]
    fn classify_refresh_status_error_unauthorized_preserves_session() {
        let _guard = TestAuthDirGuard::new();
        let session = sample_session();
        save_openai_chatgpt_session_with_mode(&session, AuthCredentialsStoreMode::File).expect("save");

        let err = classify_refresh_status_error(reqwest::StatusCode::UNAUTHORIZED, "");
        assert!(err.to_string().contains("HTTP 401"), "should report HTTP 401: {err}");
        // 401 without a confirmed terminal code preserves the session.
        assert!(
            load_openai_chatgpt_session_with_mode(AuthCredentialsStoreMode::File)
                .expect("load")
                .is_some(),
            "session should be preserved on ambiguous 401"
        );
    }

    #[test]
    fn classify_refresh_status_error_server_error_does_not_clear_session() {
        let _guard = TestAuthDirGuard::new();
        let session = sample_session();
        save_openai_chatgpt_session_with_mode(&session, AuthCredentialsStoreMode::File).expect("save");

        let err =
            classify_refresh_status_error(reqwest::StatusCode::INTERNAL_SERVER_ERROR, r#"{"error": "internal_error"}"#);
        assert!(err.to_string().contains("HTTP 500"));
        // Transient error → session preserved for retry.
        assert!(
            load_openai_chatgpt_session_with_mode(AuthCredentialsStoreMode::File)
                .expect("load")
                .is_some()
        );
    }

    #[test]
    fn classify_refresh_status_error_never_includes_raw_body() {
        let _guard = TestAuthDirGuard::new();
        let err = classify_refresh_status_error(
            reqwest::StatusCode::BAD_REQUEST,
            r#"{"error": "invalid_grant", "sensitive_data": "secret-leak-attempt"}"#,
        );
        assert!(!err.to_string().contains("secret-leak-attempt"), "raw body leaked into error: {err}");
    }

    // ── Table-driven classification matrix (status × body shape × expected) ──

    /// Expected outcome of `classify_refresh_status_error`.
    #[derive(Debug, PartialEq)]
    enum ClassifyOutcome {
        /// Session was cleared (terminal grant error).
        Terminal,
        /// Session was preserved; error message contains this fragment.
        Preserved(&'static str),
    }

    fn run_classify_matrix(status: reqwest::StatusCode, body: &str, expected: ClassifyOutcome) {
        let _guard = TestAuthDirGuard::new();
        let session = sample_session();
        save_openai_chatgpt_session_with_mode(&session, AuthCredentialsStoreMode::File).expect("save");

        let err = classify_refresh_status_error(status, body);
        let msg = err.to_string();
        let loaded = load_openai_chatgpt_session_with_mode(AuthCredentialsStoreMode::File).expect("load");

        match expected {
            ClassifyOutcome::Terminal => {
                assert!(msg.contains("session expired"), "terminal error should say 'session expired': {msg}");
                assert!(loaded.is_none(), "session should be cleared for terminal: {status} {body}");
            }
            ClassifyOutcome::Preserved(frag) => {
                assert!(!msg.contains("session expired"), "non-terminal should not say 'session expired': {msg}");
                assert!(loaded.is_some(), "session should be preserved for: {status} {body}");
                if !frag.is_empty() {
                    assert!(msg.contains(frag), "error should contain '{frag}': {msg}");
                }
            }
        }
    }

    #[test]
    fn classify_matrix_terminal_400_flat() {
        run_classify_matrix(
            reqwest::StatusCode::BAD_REQUEST,
            r#"{"error": "invalid_grant"}"#,
            ClassifyOutcome::Terminal,
        );
    }

    #[test]
    fn classify_matrix_terminal_400_nested_code() {
        run_classify_matrix(
            reqwest::StatusCode::BAD_REQUEST,
            r#"{"error": {"code": "invalid_grant", "message": "..."}}"#,
            ClassifyOutcome::Terminal,
        );
    }

    #[test]
    fn classify_matrix_terminal_400_nested_type() {
        run_classify_matrix(
            reqwest::StatusCode::BAD_REQUEST,
            r#"{"error": {"type": "invalid_grant", "message": "..."}}"#,
            ClassifyOutcome::Terminal,
        );
    }

    #[test]
    fn classify_matrix_terminal_400_toplevel_code() {
        run_classify_matrix(
            reqwest::StatusCode::BAD_REQUEST,
            r#"{"code": "refresh_token_revoked", "message": "..."}"#,
            ClassifyOutcome::Terminal,
        );
    }

    #[test]
    fn classify_matrix_terminal_401_flat() {
        // Terminal codes on 401 should also clear the session.
        run_classify_matrix(
            reqwest::StatusCode::UNAUTHORIZED,
            r#"{"error": "invalid_token"}"#,
            ClassifyOutcome::Terminal,
        );
    }

    #[test]
    fn classify_matrix_terminal_401_nested() {
        run_classify_matrix(
            reqwest::StatusCode::UNAUTHORIZED,
            r#"{"error": {"code": "refresh_token_expired"}}"#,
            ClassifyOutcome::Terminal,
        );
    }

    #[test]
    fn classify_matrix_terminal_401_refresh_token_invalidated() {
        run_classify_matrix(
            reqwest::StatusCode::UNAUTHORIZED,
            r#"{"error": "refresh_token_invalidated"}"#,
            ClassifyOutcome::Terminal,
        );
    }

    #[test]
    fn classify_matrix_terminal_400_toplevel_refresh_token_reused() {
        run_classify_matrix(
            reqwest::StatusCode::BAD_REQUEST,
            r#"{"code": "refresh_token_reused", "message": "..."}"#,
            ClassifyOutcome::Terminal,
        );
    }

    #[test]
    fn classify_matrix_message_only_does_not_clear_session() {
        // A body with only a free-text "message" field (no structured code/type)
        // must NOT be treated as terminal, even if the message text happens to
        // contain a terminal code string. This prevents false-positive session
        // clearing from descriptive error messages.
        run_classify_matrix(
            reqwest::StatusCode::BAD_REQUEST,
            r#"{"error": {"message": "invalid_grant"}}"#,
            ClassifyOutcome::Preserved("HTTP 400"),
        );
    }

    #[test]
    fn classify_matrix_invalid_client_preserves() {
        run_classify_matrix(
            reqwest::StatusCode::BAD_REQUEST,
            r#"{"error": "invalid_client"}"#,
            ClassifyOutcome::Preserved("invalid_client"),
        );
    }

    #[test]
    fn classify_matrix_invalid_client_401_preserves() {
        run_classify_matrix(
            reqwest::StatusCode::UNAUTHORIZED,
            r#"{"error": "invalid_client"}"#,
            ClassifyOutcome::Preserved("invalid_client"),
        );
    }

    #[test]
    fn classify_matrix_429_throttling_preserves() {
        run_classify_matrix(
            reqwest::StatusCode::TOO_MANY_REQUESTS,
            r#"{"error": "rate_limited"}"#,
            ClassifyOutcome::Preserved("rate-limited"),
        );
    }

    #[test]
    fn classify_matrix_500_server_error_preserves() {
        run_classify_matrix(
            reqwest::StatusCode::INTERNAL_SERVER_ERROR,
            r#"{"error": "internal_error"}"#,
            ClassifyOutcome::Preserved("HTTP 500"),
        );
    }

    #[test]
    fn classify_matrix_502_bad_gateway_preserves() {
        run_classify_matrix(reqwest::StatusCode::BAD_GATEWAY, "", ClassifyOutcome::Preserved("HTTP 502"));
    }

    #[test]
    fn classify_matrix_503_service_unavailable_preserves() {
        run_classify_matrix(reqwest::StatusCode::SERVICE_UNAVAILABLE, "", ClassifyOutcome::Preserved("HTTP 503"));
    }

    #[test]
    fn classify_matrix_ambiguous_401_empty_body_preserves() {
        run_classify_matrix(reqwest::StatusCode::UNAUTHORIZED, "", ClassifyOutcome::Preserved("HTTP 401"));
    }

    #[test]
    fn classify_matrix_400_nonterminal_code_preserves() {
        // A 400 with a code that is NOT in the terminal list should preserve.
        run_classify_matrix(
            reqwest::StatusCode::BAD_REQUEST,
            r#"{"error": "some_unknown_error"}"#,
            ClassifyOutcome::Preserved("HTTP 400"),
        );
    }

    #[test]
    fn classify_matrix_never_leaks_body_in_any_branch() {
        // Terminal branch
        let _guard = TestAuthDirGuard::new();
        let err = classify_refresh_status_error(
            reqwest::StatusCode::BAD_REQUEST,
            r#"{"error": "invalid_grant", "leak": "TERMINAL_LEAK"}"#,
        );
        assert!(!err.to_string().contains("TERMINAL_LEAK"));

        // Preserved branch (invalid_client)
        let err = classify_refresh_status_error(
            reqwest::StatusCode::BAD_REQUEST,
            r#"{"error": "invalid_client", "leak": "CLIENT_LEAK"}"#,
        );
        assert!(!err.to_string().contains("CLIENT_LEAK"));

        // Preserved branch (429)
        let err = classify_refresh_status_error(
            reqwest::StatusCode::TOO_MANY_REQUESTS,
            r#"{"error": "rate_limited", "leak": "THROTTLE_LEAK"}"#,
        );
        assert!(!err.to_string().contains("THROTTLE_LEAK"));
    }

    // ── Error code extraction shape tests ──

    #[test]
    fn extract_error_code_nested_with_type_field() {
        let body = r#"{"error": {"type": "invalid_grant", "message": "..."}}"#;
        assert_eq!(extract_error_code(body), "invalid_grant");
    }

    #[test]
    fn extract_error_code_toplevel_code_field() {
        let body = r#"{"code": "refresh_token_expired", "message": "..."}"#;
        assert_eq!(extract_error_code(body), "refresh_token_expired");
    }

    #[test]
    fn extract_error_code_case_insensitive_normalization() {
        assert_eq!(extract_error_code(r#"{"error": "INVALID_GRANT"}"#), "invalid_grant");
    }

    #[test]
    fn extract_error_code_no_substring_matching() {
        // "invalid_grant_really" is not a terminal code — extract_error_code
        // returns it verbatim, but classify won't match it as terminal.
        let code = extract_error_code(r#"{"error": "invalid_grant_really_not_a_real_code"}"#);
        assert_eq!(code, "invalid_grant_really_not_a_real_code");
        // Verify classify does NOT treat this as terminal.
        let _guard = TestAuthDirGuard::new();
        let session = sample_session();
        save_openai_chatgpt_session_with_mode(&session, AuthCredentialsStoreMode::File).expect("save");
        let err = classify_refresh_status_error(
            reqwest::StatusCode::BAD_REQUEST,
            r#"{"error": "invalid_grant_really_not_a_real_code"}"#,
        );
        assert!(!err.to_string().contains("session expired"));
        assert!(
            load_openai_chatgpt_session_with_mode(AuthCredentialsStoreMode::File)
                .expect("load")
                .is_some()
        );
    }

    // ── PKCE and callback Debug redaction tests ──

    #[test]
    fn pkce_challenge_debug_redacts_verifier() {
        let challenge = generate_pkce_challenge().expect("generate pkce");
        let debug_str = format!("{challenge:?}");
        assert!(!debug_str.contains(&challenge.code_verifier), "code_verifier leaked: {debug_str}");
        assert!(debug_str.contains("<redacted>"), "verifier should be redacted: {debug_str}");
        // Challenge and method are safe to display.
        assert!(debug_str.contains(&challenge.code_challenge), "code_challenge should be visible: {debug_str}");
    }

    #[test]
    fn auth_callback_outcome_debug_redacts_code() {
        let outcome = AuthCallbackOutcome::Code("super-secret-auth-code".to_string());
        let debug_str = format!("{outcome:?}");
        assert!(!debug_str.contains("super-secret-auth-code"), "authorization code leaked: {debug_str}");
        assert!(debug_str.contains("<redacted>"), "code should be redacted: {debug_str}");
    }

    #[test]
    fn auth_callback_outcome_debug_shows_cancelled_and_redacts_error() {
        let cancelled = format!("{:?}", AuthCallbackOutcome::Cancelled);
        assert!(cancelled.contains("Cancelled"));

        // Error messages from OAuth callbacks are untrusted query parameters
        // that may contain sensitive values — Debug must redact them.
        let error = format!("{:?}", AuthCallbackOutcome::Error("access_denied".to_string()));
        assert!(!error.contains("access_denied"), "error message leaked through Debug: {error}");
        assert!(error.contains("<redacted>"), "error should be redacted: {error}");
    }
}