cpa-server 0.4.4

Part of cliproxy: HTTP routes, client auth, credential selection and the management API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
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
//! Management-started logins (Go auth_files_provider_oauth.go, oauth_sessions.go,
//! oauth_callback.go, auth_files_oauth_callback.go, auth_files_v8.go):
//! `GET /oauth/auth-url`, `GET /oauth/status`, `DELETE /oauth/session`,
//! `GET|POST /oauth/callback` and `POST /oauth/import` (vertex_import.go).
//!
//! Go hands callbacks to the waiting login through `.oauth-<provider>-<state>.oauth`
//! files in auth-dir; cliproxy-rs keeps the callback with the pending session in
//! memory, so nothing extra appears in the watched directory.

use cpa_core::gostr::GoStr;
use std::collections::HashMap;
use std::panic::AssertUnwindSafe;
use std::path::PathBuf;
use std::sync::{Arc, Mutex, PoisonError};
use std::time::{Duration, Instant, SystemTime};

use axum::extract::{RawQuery, State};
use axum::http::{HeaderMap, StatusCode};
use axum::response::{IntoResponse, Response};
use cpa_core::exec::ExecError;
use cpa_exec::proxy::Proxy;
use futures_util::FutureExt;
use serde_json::{Value, json};

use super::auth_files::{Query, fail, reply};
use super::{Management, json as respond};
use crate::runtime::OAuthDelivery as Delivery;

const SESSION_TTL: Duration = Duration::from_secs(30 * 60);
/// Go `oauthCompletedSessionTTL`, for a binding failed by a file change. A completed
/// sign-in keeps [`SESSION_TTL`] instead (DIFFERENCES-FROM-GO.md).
const COMPLETED_TTL: Duration = Duration::from_secs(60);
const CALLBACK_WAIT: Duration = Duration::from_secs(5 * 60);
const ANTHROPIC_CALLBACK_PORT: u16 = 54545;
const CODEX_CALLBACK_PORT: u16 = 1455;

#[derive(Clone)]
struct Session {
    provider: String,
    status: String,
    completed: bool,
    expires: Instant,
    callback: Option<Callback>,
    /// Go `oauthSessionSourcePlugin`: a plugin auth provider's login.
    plugin: bool,
    /// The plugin's polling context (Go `Session.Metadata`).
    metadata: cpa_plugin::gojson::Metadata,
    /// A v8 Sign in with ChatGPT binding (Go `oauthSession.SIWC`).
    siwc: Option<Arc<super::siwc::Flow>>,
    /// The binding's callback was accepted and its exchange started.
    siwc_exchanging: bool,
    /// Go `SIWCCommitting`: a started disk commit keeps the session past its expiry.
    siwc_committing: bool,
}

#[derive(Clone)]
struct Callback {
    code: String,
    state: String,
    error: String,
}

/// Go `oauthSessionStore`.
#[derive(Default)]
pub(crate) struct Sessions(Mutex<HashMap<String, Session>>);

impl Sessions {
    fn lock(&self) -> std::sync::MutexGuard<'_, HashMap<String, Session>> {
        let mut map = self.0.lock().unwrap_or_else(PoisonError::into_inner);
        let now = Instant::now();
        map.retain(|_, s| {
            let keep = s.expires > now || s.siwc_committing;
            if let Some(flow) = s.siwc.as_ref().filter(|_| !keep) {
                flow.cancel();
            }
            keep
        });
        map
    }

    fn register(&self, state: &str, provider: &str) {
        let (state, provider) = (state.trim(), provider.trim().go_lower());
        if state.is_empty() || provider.is_empty() {
            return;
        }
        self.lock().insert(
            state.to_owned(),
            Session {
                provider,
                status: String::new(),
                completed: false,
                expires: Instant::now() + SESSION_TTL,
                callback: None,
                plugin: false,
                metadata: Default::default(),
                siwc: None,
                siwc_exchanging: false,
                siwc_committing: false,
            },
        );
    }

    /// Go `RegisterPlugin`: `false` when the state is unusable or already registered.
    pub(super) fn register_plugin(&self, state: &str, provider: &str, metadata: cpa_plugin::gojson::Metadata) -> bool {
        let (state, provider) = (state.trim(), provider.trim().go_lower());
        if state.is_empty() || provider.is_empty() || !valid_state(state) {
            return false;
        }
        let mut map = self.lock();
        if map.contains_key(state) {
            return false;
        }
        map.insert(
            state.to_owned(),
            Session {
                provider,
                status: String::new(),
                completed: false,
                expires: Instant::now() + SESSION_TTL,
                callback: None,
                plugin: true,
                metadata,
                siwc: None,
                siwc_exchanging: false,
                siwc_committing: false,
            },
        );
        true
    }

    /// Go `GetOAuthSessionDetails`: `(provider, status, plugin, metadata, completed)`.
    pub(super) fn details(&self, state: &str) -> Option<(String, String, bool, cpa_plugin::gojson::Metadata, bool)> {
        self.lock().get(state.trim()).map(|s| {
            (
                s.provider.clone(),
                s.status.clone(),
                s.plugin,
                s.metadata.clone(),
                s.completed,
            )
        })
    }

    pub(super) fn set_error(&self, state: &str, message: &str) {
        let message = match message.trim() {
            "" => "Authentication failed",
            m => m,
        };
        if let Some(s) = self.lock().get_mut(state.trim()).filter(|s| !s.completed) {
            s.status = message.to_owned();
            s.siwc_committing = false;
            s.expires = Instant::now() + SESSION_TTL;
        }
    }

    pub(super) fn complete(&self, state: &str) {
        if let Some(s) = self.lock().get_mut(state.trim()).filter(|s| !s.completed) {
            s.status.clear();
            s.callback = None;
            s.metadata.clear();
            s.siwc_committing = false;
            s.completed = true;
            // Go keeps it a minute; a user who approves on the provider's tab and comes
            // back later should still read the success.
            s.expires = Instant::now() + SESSION_TTL;
        }
    }

    /// `(provider, status, completed)`.
    fn get(&self, state: &str) -> Option<(String, String, bool)> {
        self.lock()
            .get(state.trim())
            .map(|s| (s.provider.clone(), s.status.clone(), s.completed))
    }

    fn is_pending(&self, state: &str, provider: &str) -> bool {
        let provider = provider.trim().go_lower();
        self.lock().get(state.trim()).is_some_and(|s| {
            !s.completed && s.status.is_empty() && (provider.is_empty() || s.provider.go_eq_fold(&provider))
        })
    }

    /// Go `Cancel`. A binding whose disk commit has started is past cancelling: Go
    /// waits on the session gate for that commit, which then leaves the session
    /// completed or failed, so the answer is `false` either way.
    fn cancel(&self, state: &str) -> bool {
        let mut map = self.lock();
        let state = state.trim();
        if map
            .get(state)
            .is_some_and(|s| !s.completed && s.status.is_empty() && !s.siwc_committing)
        {
            if let Some(flow) = map.remove(state).and_then(|s| s.siwc) {
                flow.cancel();
            }
            return true;
        }
        false
    }

    /// Go `WriteOAuthCallbackFileForPendingSession`: keeps the callback for the waiter.
    /// A binding's state is refused: its code may only reach the v8 callback.
    fn deliver(&self, provider: &str, state: &str, code: &str, error: &str) -> Delivery {
        let Some(provider) = normalize_callback_provider(provider) else {
            return Delivery::NotPending;
        };
        if !valid_state(state) {
            return Delivery::NotPending;
        }
        let mut map = self.lock();
        let Some(s) = map.get_mut(state.trim()) else {
            return Delivery::NotPending;
        };
        if s.siwc.is_some() {
            return Delivery::RequiresV8;
        }
        if s.completed || !s.status.is_empty() || !s.provider.go_eq_fold(&provider) {
            return Delivery::NotPending;
        }
        s.callback = Some(Callback {
            code: code.trim().to_owned(),
            state: state.trim().to_owned(),
            error: error.trim().to_owned(),
        });
        Delivery::Delivered
    }

    /// Go `registerSIWC`: `false` when the state exists or the credential already has
    /// a pending binding.
    pub(super) fn register_siwc(&self, state: &str, flow: Arc<super::siwc::Flow>, ttl: Duration) -> bool {
        let mut map = self.lock();
        let busy = map.values().any(|s| {
            !s.completed && s.status.is_empty() && s.siwc.as_ref().is_some_and(|f| f.target_id == flow.target_id)
        });
        if busy || map.contains_key(state) {
            return false;
        }
        map.insert(
            state.to_owned(),
            Session {
                provider: "codex".into(),
                status: String::new(),
                completed: false,
                expires: Instant::now() + ttl,
                callback: None,
                plugin: false,
                metadata: Default::default(),
                siwc: Some(flow),
                siwc_exchanging: false,
                siwc_committing: false,
            },
        );
        true
    }

    /// The binding a state belongs to, whatever its status.
    pub(super) fn siwc(&self, state: &str) -> Option<Arc<super::siwc::Flow>> {
        self.lock().get(state.trim()).and_then(|s| s.siwc.clone())
    }

    /// Accepts the binding's one callback while it is pending.
    pub(super) fn begin_siwc(&self, state: &str, flow: &Arc<super::siwc::Flow>) -> bool {
        let mut map = self.lock();
        match map.get_mut(state) {
            Some(s) if Self::siwc_pending(s, flow) && !s.siwc_exchanging => {
                s.siwc_exchanging = true;
                true
            }
            _ => false,
        }
    }

    /// The binding is still pending (not cancelled, expired, failed or completed).
    pub(super) fn siwc_is_pending(&self, state: &str, flow: &Arc<super::siwc::Flow>) -> bool {
        self.lock().get(state).is_some_and(|s| Self::siwc_pending(s, flow))
    }

    /// Go `claimSIWCCommit`; callers hold `disk`, so file mutations are fenced.
    pub(super) fn claim_siwc_commit(&self, state: &str, flow: &Arc<super::siwc::Flow>) -> bool {
        let mut map = self.lock();
        match map.get_mut(state) {
            Some(s) if Self::siwc_pending(s, flow) && !s.siwc_committing => {
                s.siwc_committing = true;
                true
            }
            _ => false,
        }
    }

    fn siwc_pending(s: &Session, flow: &Arc<super::siwc::Flow>) -> bool {
        !s.completed && s.status.is_empty() && s.siwc.as_ref().is_some_and(|f| Arc::ptr_eq(f, flow))
    }

    /// Go `beginSIWCFileMutation` (callers hold `disk`): a v8 upload or delete of a
    /// binding's file, even an identical one, fails that binding.
    pub(super) fn invalidate_siwc(&self, path: &std::path::Path) {
        let mut map = self.lock();
        for s in map.values_mut() {
            if let Some(flow) = s.siwc.as_ref()
                && !s.completed
                && s.status.is_empty()
                && super::siwc::same_path(path, &flow.path)
            {
                flow.cancel();
                s.status = "SIWC binding target changed; start a new binding".into();
                s.expires = Instant::now() + COMPLETED_TTL;
            }
        }
    }

    fn take_callback(&self, state: &str) -> Option<Callback> {
        self.lock().get_mut(state).and_then(|s| s.callback.take())
    }
}

/// Go `ValidateOAuthState`.
pub(super) fn valid_state(state: &str) -> bool {
    let s = state.trim();
    !s.is_empty()
        && s.len() <= 128
        && !s.contains("..")
        && s.bytes()
            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.'))
}

/// Go `NormalizeOAuthCallbackProvider`: the built-in aliases, else a plugin-style name.
pub(super) fn normalize_callback_provider(provider: &str) -> Option<String> {
    let p = provider.trim().go_lower();
    let builtin = match p.as_str() {
        "anthropic" | "claude" => Some("anthropic"),
        "codex" | "openai" => Some("codex"),
        "antigravity" | "anti-gravity" => Some("antigravity"),
        "xai" | "x-ai" | "x.ai" | "grok" => Some("xai"),
        "devin" | "cognition" => Some("devin"),
        "meta" | "muse" => Some("meta"),
        _ => None,
    };
    if let Some(b) = builtin {
        return Some(b.to_owned());
    }
    (!p.is_empty()
        && p.bytes()
            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-'))
    .then_some(p)
}

/// Go `oauthSessionErrorWithCause`.
fn with_cause(message: &str, cause: &str) -> String {
    match redact_upstream(cause).trim() {
        "" => message.to_owned(),
        detail => format!("{message}: {detail}"),
    }
}

/// Cuts upstream-supplied text from a login failure cause: a response body after its
/// status, an OAuth error description after its error code, and a decoder diagnostic
/// (which quotes response values) after its `parse ...` context. Go keeps them, but
/// they can carry tokens and session errors are readable by anyone holding the state
/// (the key-less callback). The earliest boundary wins: upstream text follows it.
fn redact_upstream(cause: &str) -> String {
    let mut cut: Option<(usize, String)> = None;
    let mut consider = |at: usize, kept: String| {
        if cut.as_ref().is_none_or(|(i, _)| at < *i) {
            cut = Some((at, kept));
        }
    };
    for marker in ["with status ", "(HTTP "] {
        if let Some(i) = cause.find(marker) {
            let start = i + marker.len();
            let mut end = start + cause[start..].bytes().take_while(u8::is_ascii_digit).count();
            if marker == "(HTTP " && cause[end..].starts_with(')') {
                end += 1;
            }
            consider(i, cause[..end].to_owned());
        }
    }
    for marker in [
        "error from authorization server: ",
        "device token error: ",
        "OAuth error: ",
    ] {
        if let Some(i) = cause.find(marker) {
            let start = i + marker.len();
            let code: String = cause[start..]
                .chars()
                .take_while(|c| c.is_ascii_alphanumeric() || *c == '_')
                .take(64)
                .collect();
            consider(i, format!("{}{code}", &cause[..start]));
        }
    }
    if let Some(i) = cause.find("parse ")
        && let Some(j) = cause[i..].find(": ")
    {
        consider(i, cause[..i + j].to_owned());
    }
    cut.map_or_else(|| cause.to_owned(), |(_, kept)| kept)
}

fn exec_text(e: &ExecError) -> String {
    String::from_utf8_lossy(&e.body).into_owned()
}

/// Installs the main listener's provider-callback hook (Go's `/anthropic/callback`
/// etc. call `WriteOAuthCallbackFileForPendingSession`).
pub(super) fn install_callback_sink(state: &Arc<Management>) {
    let weak = Arc::downgrade(state);
    state
        .rt
        .set_oauth_callback_sink(Some(Arc::new(move |cb: &crate::runtime::OAuthCallback| {
            weak.upgrade().map_or(Delivery::NotPending, |m| {
                m.oauth.deliver(cb.provider, &cb.state, &cb.code, &cb.error)
            })
        })));
}

fn status_error(status: StatusCode, message: &str) -> Response {
    respond(status, &json!({"status": "error", "error": message}))
}

fn unix_nanos() -> u128 {
    SystemTime::now()
        .duration_since(SystemTime::UNIX_EPOCH)
        .map_or(0, |d| d.as_nanos())
}

/// Go `misc.GenerateRandomState`: 16 random bytes, hex.
fn random_state() -> Option<String> {
    let mut bytes = [0u8; 16];
    getrandom::fill(&mut bytes).ok()?;
    Some(bytes.iter().map(|b| format!("{b:02x}")).collect())
}

/// `requests.proxy-url`, which Go's auth services use.
fn global_proxy(state: &Management) -> Proxy {
    let cfg = state.rt.config();
    let global = cfg
        .document
        .get("requests")
        .and_then(|r| r.get("proxy-url"))
        .and_then(serde_yaml_ng::Value::as_str)
        .unwrap_or_default();
    Proxy::parse(global)
}

/// The client for login traffic: the global proxy (else the environment's proxies);
/// local endpoints in tests.
pub(super) fn login_client(state: &Management) -> wreq::Client {
    if state.login_base.is_some() {
        return state.clients.get(&Proxy::Direct);
    }
    state.clients.get(&global_proxy(state))
}

/// Go `StartOAuthV8`.
pub(crate) async fn auth_url(State(state): State<Arc<Management>>, RawQuery(raw): RawQuery) -> Response {
    let raw_query = raw.clone();
    let q = Query::parse(raw);
    let webui = matches!(
        q.first("is_webui").trim().go_lower().as_str(),
        "1" | "true" | "yes" | "on"
    );
    match q.first("provider").trim().go_lower().as_str() {
        "" => fail(StatusCode::BAD_REQUEST, "provider is required"),
        "claude" => start_claude(state, webui).await,
        "codex" => start_codex(state, webui).await,
        "antigravity" => start_antigravity(state, webui).await,
        "kimi" => {
            // Go `RequestKimiToken`: `domain`, else `channel`, else kimi.com.
            let domain = [q.first("domain"), q.first("channel")]
                .into_iter()
                .map(str::trim)
                .find(|v| !v.is_empty())
                .unwrap_or(cpa_exec::kimi_auth::DOMAIN_COM)
                .to_owned();
            start_kimi(state, domain).await
        }
        "kimi-ai" => start_kimi(state, cpa_exec::kimi_auth::DOMAIN_AI.to_owned()).await,
        "meta" => start_meta(state).await,
        "xai" => start_xai(state).await,
        "devin" => start_devin(state).await,
        // Go `ServePluginAuthURL`: a plugin auth provider's login, else not found.
        _ => {
            let raw = raw_query.as_deref().unwrap_or_default();
            match super::plugin_oauth::serve_auth_url(&state, "/v8/management/oauth/auth-url", raw).await {
                Some(response) => response,
                None => fail(StatusCode::NOT_FOUND, "provider_not_found"),
            }
        }
    }
}

/// Go `ImportOAuthV8`.
pub(crate) async fn import(
    State(state): State<Arc<Management>>,
    RawQuery(raw): RawQuery,
    headers: HeaderMap,
    read: crate::body_limit::Read,
) -> Response {
    let query = Query::parse(raw);
    match query.first("provider").trim().go_lower().as_str() {
        "" => fail(StatusCode::BAD_REQUEST, "provider is required"),
        "vertex" => import_vertex(state, &query, &headers, read).await,
        _ => fail(StatusCode::NOT_FOUND, "provider_not_found"),
    }
}

/// Go `ImportVertexCredential`: a service-account key uploaded as the `file` form field;
/// `location` from the form, else the query.
async fn import_vertex(
    state: Arc<Management>,
    query: &Query,
    headers: &HeaderMap,
    read: crate::body_limit::Read,
) -> Response {
    use super::multipart::Failed;
    use cpa_exec::vertex_auth::{UploadError, import_upload};
    let content_type = headers
        .get(axum::http::header::CONTENT_TYPE)
        .and_then(|v| v.to_str().ok())
        .unwrap_or_default();
    // Go `FormFile("file")`: any form error reads as a missing file, with the limit's
    // status for the limit error.
    let body = match super::multipart::body(read, content_type) {
        Ok(body) => body,
        Err(Failed::Read(rejection)) => return rejection.into_response(),
        Err(Failed::Form(status, _)) => {
            return fail(
                StatusCode::from_u16(status).unwrap_or(StatusCode::BAD_REQUEST),
                "file required",
            );
        }
    };
    let Ok((mut files, values)) = super::multipart::form(content_type, &body) else {
        return fail(StatusCode::BAD_REQUEST, "file required");
    };
    let Some(file) = files.remove("file").and_then(|parts| parts.into_iter().next()) else {
        return fail(StatusCode::BAD_REQUEST, "file required");
    };
    let mut location = values
        .get("location")
        .and_then(|v| v.first())
        .map(|v| v.trim().to_owned())
        .unwrap_or_default();
    if location.is_empty() {
        location = query.first("location").trim().to_owned();
    }
    let auth_dir = state.rt.config().auth_dir.clone();
    let saved = tokio::task::spawn_blocking(move || {
        // Under `disk` from the read of an existing file to the write, so a concurrent
        // management edit (for example `disabled`) is neither lost nor overwritten.
        let _guard = state.disk.lock().unwrap_or_else(PoisonError::into_inner);
        let upload = import_upload(&auth_dir, &file.data, &location)?;
        // Go `saveTokenRecord`: success only once the token store has the file.
        let mut written = Ok(());
        let stored = state.store_write(Box::new(|| {
            written = upload.write();
            written.as_ref().map_err(|_| anyhow::anyhow!("write failed"))?;
            Ok(Some(upload.path.clone()))
        }));
        written?;
        stored.map_err(UploadError::Save)?;
        state.publish((*state.rt.config()).clone(), None);
        Ok(upload)
    })
    .await;
    let message = |error: &str, message: String| {
        reply(
            StatusCode::BAD_REQUEST,
            [("error", Value::from(error)), ("message", Value::from(message))],
        )
    };
    match saved {
        Ok(Ok(upload)) => reply(
            StatusCode::OK,
            [
                ("status", "ok".into()),
                ("auth-file", upload.path.to_string_lossy().into_owned().into()),
                ("project_id", upload.project.into()),
                ("email", upload.email.into()),
                ("location", upload.location.into()),
            ],
        ),
        Ok(Err(UploadError::InvalidJson(e))) => message("invalid json", e),
        Ok(Err(UploadError::InvalidServiceAccount(e))) => message("invalid service account", e),
        Ok(Err(UploadError::ProjectMissing)) => fail(StatusCode::BAD_REQUEST, "project_id missing"),
        Ok(Err(UploadError::Save(e))) => reply(
            StatusCode::INTERNAL_SERVER_ERROR,
            [("error", Value::from("save_failed")), ("message", Value::from(e))],
        ),
        Err(_) => fail(StatusCode::INTERNAL_SERVER_ERROR, "save_failed"),
    }
}

/// How a login ended, for the session (Go's `SetOAuthSessionError` texts).
enum Outcome {
    Saved,
    /// The session stopped being pending: nothing is saved or reported.
    Cancelled,
    Failed(String),
}

/// Saves through `write` only while the session is still pending (Go
/// `guardOAuthSessionPendingForSave`), then resyncs credentials.
async fn save_if_pending<T: Send + 'static>(
    state: &Arc<Management>,
    sid: &str,
    provider: &str,
    value: T,
    write: impl FnOnce(PathBuf, T) -> Result<PathBuf, String> + Send + 'static,
    save_error: &str,
) -> Outcome {
    let auth_dir = state.rt.config().auth_dir.clone();
    let (worker, sid, owner) = (state.clone(), sid.to_owned(), provider.to_owned());
    let saved = tokio::task::spawn_blocking(move || {
        let _guard = worker.disk.lock().unwrap_or_else(PoisonError::into_inner);
        // Go `saveTokenRecord`: saved only once the token store has the file. The
        // session is checked right before the write, after any store sync.
        worker.store_write(Box::new(|| {
            if !worker.oauth.is_pending(&sid, &owner) {
                return Ok(None);
            }
            assert!(!worker.login_panic, "injected login panic");
            write(auth_dir, value).map(Some).map_err(anyhow::Error::msg)
        }))
    })
    .await;
    match saved {
        Ok(Ok(Some(_))) => Outcome::Saved,
        Ok(Ok(None)) => Outcome::Cancelled,
        Ok(Err(e)) => {
            tracing::error!("failed to save {provider} token: {e}");
            Outcome::Failed(save_error.to_owned())
        }
        Err(e) => {
            resume_panic(e);
            Outcome::Failed(save_error.to_owned())
        }
    }
}

/// A blocking save task that did not finish: its panic goes on to the worker's panic
/// catch ([`panicked`]); a cancelled task returns, for the caller's save failure.
fn resume_panic(e: tokio::task::JoinError) {
    if let Ok(panic) = e.try_into_panic() {
        std::panic::resume_unwind(panic);
    }
}

async fn settle(state: &Arc<Management>, sid: &str, outcome: Outcome) {
    match outcome {
        Outcome::Saved => {
            // `disk` can be held by a save that waits on the store's async I/O, so it is
            // never taken on a runtime worker.
            let worker = state.clone();
            let published = tokio::task::spawn_blocking(move || {
                let _guard = worker.disk.lock().unwrap_or_else(PoisonError::into_inner);
                worker.publish((*worker.rt.config()).clone(), None);
            })
            .await;
            if let Err(e) = published {
                resume_panic(e);
                return fail_session(state, sid, "Failed to save authentication tokens");
            }
            state.oauth.complete(sid);
        }
        Outcome::Cancelled => {}
        Outcome::Failed(message) => return fail_session(state, sid, &message),
    }
    if let Some(settled) = &state.login_settled {
        let _ = settled.send(sid.to_owned());
    }
}

/// [`settle`] for a failed login, which publishes nothing.
fn fail_session(state: &Management, sid: &str, message: &str) {
    state.oauth.set_error(sid, message);
    if let Some(settled) = &state.login_settled {
        let _ = settled.send(sid.to_owned());
    }
}

/// The session error after a login worker panicked.
pub(super) const PANIC_MESSAGE: &str = "Sign-in failed because of an internal error. Start the sign-in again.";

/// Awaits a login worker, catching a panic in it, including one a blocking save task
/// passed on ([`resume_panic`]). Its error line names only the provider and the state (a
/// panic payload can quote tokens). Returns whether it panicked. Go recovers nothing in
/// these goroutines, so there a panic ends the process.
pub(super) async fn panicked(sid: &str, provider: &str, work: impl Future<Output = ()>) -> bool {
    let caught = AssertUnwindSafe(work).catch_unwind().await.is_err();
    if caught {
        tracing::error!("{provider} sign-in worker panicked; sign-in {sid} failed");
    }
    caught
}

/// Spawns a login's worker: a panic fails the session ([`PANIC_MESSAGE`]) instead of
/// leaving it waiting until [`SESSION_TTL`], and the login's callback forwarder
/// (`(port, id)`) stops however the worker ends.
fn spawn_login(
    state: &Arc<Management>,
    sid: &str,
    provider: &'static str,
    forwarder: Option<(u16, u64)>,
    work: impl Future<Output = ()> + Send + 'static,
) {
    let (worker, sid) = (state.clone(), sid.to_owned());
    tokio::spawn(async move {
        if panicked(&sid, provider, work).await {
            fail_session(&worker, &sid, PANIC_MESSAGE);
        }
        if let Some((port, id)) = forwarder {
            stop_forwarder(&worker, port, id);
        }
    });
}

fn started(url: String, sid: String) -> Response {
    reply(
        StatusCode::OK,
        [("status", "ok".into()), ("url", url.into()), ("state", sid.into())],
    )
}

/// Go `RequestAnthropicToken`.
async fn start_claude(state: Arc<Management>, webui: bool) -> Response {
    use cpa_exec::claude_login::ManagedLogin;
    let login = match ManagedLogin::start() {
        Ok(l) => l,
        Err(_) => return fail(StatusCode::INTERNAL_SERVER_ERROR, "failed to generate PKCE codes"),
    };
    state.oauth.register(&login.state, "anthropic");
    let forwarder = if webui {
        match start_forwarder(&state, ANTHROPIC_CALLBACK_PORT, "/anthropic/callback").await {
            Ok(id) => Some(id),
            Err(message) => return fail(StatusCode::INTERNAL_SERVER_ERROR, message),
        }
    } else {
        None
    };
    let (url, sid) = (login.url.clone(), login.state.clone());
    let worker = state.clone();
    let forwarder = forwarder.map(|id| (ANTHROPIC_CALLBACK_PORT, id));
    spawn_login(&state, &sid, "anthropic", forwarder, async move {
        if let Some(code) = wait_for_callback(&worker, &login.state, "anthropic", "Bad request").await {
            let exchanged = match &worker.login_base {
                Some(base) => {
                    let oauth = cpa_exec::oauth::OAuth::with_endpoints(
                        login_client(&worker),
                        &format!("{base}/v1/oauth/token"),
                        &format!("{base}/api/oauth/profile"),
                        &format!("{base}/api/oauth/claude_cli/roles"),
                    );
                    login.exchange_with(&oauth, &code).await
                }
                None => login.exchange(&code, &global_proxy(&worker)).await,
            };
            let outcome = match exchanged {
                Ok(patch) => {
                    let legacy = Arc::new(Mutex::new(None));
                    let slot = legacy.clone();
                    let write = move |dir: PathBuf, patch| {
                        let (path, old) = ManagedLogin::save(&dir, patch).map_err(|e| exec_text(&e))?;
                        // The bytes the save checked, so the cleanup deletes only that file.
                        let old = old.map(|p| {
                            let bytes = std::fs::read(&p).unwrap_or_default();
                            (p, bytes)
                        });
                        *slot.lock().unwrap_or_else(PoisonError::into_inner) = old;
                        Ok(path)
                    };
                    let saved = save_if_pending(
                        &worker,
                        &login.state,
                        "anthropic",
                        patch,
                        write,
                        "Failed to save authentication tokens",
                    )
                    .await;
                    let old = legacy.lock().unwrap_or_else(PoisonError::into_inner).take();
                    match (saved, old) {
                        (Outcome::Saved, Some(old)) => remove_legacy_claude(&worker, old).await,
                        (saved, _) => saved,
                    }
                }
                Err(_) => Outcome::Failed("Failed to exchange authorization code for tokens".into()),
            };
            settle(&worker, &login.state, outcome).await;
        }
    });
    started(url, sid)
}

/// Go `saveTokenRecord` after the canonical Claude credential is stored: the matching
/// legacy file is deleted through the token store (`store.Delete`), so a git store
/// commits the removal its watcher guard would refuse. Deliberate difference: Go
/// deletes the file it matched without reading it again. The disk lock is released
/// between the save and the cleanup, so a file written under that name in between (an
/// upload, or with a git store another instance's push) is kept.
async fn remove_legacy_claude(state: &Arc<Management>, (legacy, checked): (PathBuf, Vec<u8>)) -> Outcome {
    let worker = state.clone();
    let removed = tokio::task::spawn_blocking(move || {
        let _guard = worker.disk.lock().unwrap_or_else(PoisonError::into_inner);
        let deleted = if worker.store.is_some() {
            worker.store_delete_unchanged(&legacy, &checked)?
        } else if crate::persist::file_unchanged(&legacy, &checked) {
            match std::fs::remove_file(&legacy) {
                Err(e) if e.kind() != std::io::ErrorKind::NotFound => return Err(e.to_string()),
                _ => true,
            }
        } else {
            false
        };
        if !deleted && legacy.exists() {
            tracing::warn!("legacy Claude credential changed after the login checked it; kept");
        }
        Ok(())
    })
    .await;
    match removed {
        Ok(Ok(())) => Outcome::Saved,
        Ok(Err(e)) => {
            tracing::error!("canonical Claude credential saved but legacy credential cleanup failed: {e}");
            Outcome::Failed("Failed to save authentication tokens".into())
        }
        Err(e) => {
            resume_panic(e);
            Outcome::Failed("Failed to save authentication tokens".into())
        }
    }
}

/// Go `RequestCodexToken`.
async fn start_codex(state: Arc<Management>, webui: bool) -> Response {
    use cpa_exec::codex_oauth::{CodexOAuth, authorize_url, redirect_uri, write_login};
    let Ok((verifier, challenge)) = cpa_exec::oauth::pkce() else {
        return fail(StatusCode::INTERNAL_SERVER_ERROR, "failed to generate PKCE codes");
    };
    let Some(sid) = random_state() else {
        return fail(StatusCode::INTERNAL_SERVER_ERROR, "failed to generate state parameter");
    };
    let url = authorize_url(&sid, &challenge, CODEX_CALLBACK_PORT);
    state.oauth.register(&sid, "codex");
    let forwarder = if webui {
        match start_forwarder(&state, CODEX_CALLBACK_PORT, "/codex/callback").await {
            Ok(id) => Some(id),
            Err(message) => return fail(StatusCode::INTERNAL_SERVER_ERROR, message),
        }
    } else {
        None
    };
    let worker = state.clone();
    let flow = sid.clone();
    let forwarder = forwarder.map(|id| (CODEX_CALLBACK_PORT, id));
    spawn_login(&state, &sid, "codex", forwarder, async move {
        if let Some(code) = wait_for_callback(&worker, &flow, "codex", "Bad Request").await {
            let client = login_client(&worker);
            let oauth = match &worker.login_base {
                Some(base) => CodexOAuth::with_endpoints(
                    client,
                    &format!("{base}/oauth/token"),
                    &format!("{base}/api/accounts/deviceauth/usercode"),
                    &format!("{base}/api/accounts/deviceauth/token"),
                ),
                None => CodexOAuth::new(client),
            };
            let outcome = match oauth
                .exchange(&code, &redirect_uri(CODEX_CALLBACK_PORT), &verifier)
                .await
            {
                Ok(tokens) => {
                    let write = |dir: PathBuf, tokens| write_login(&dir, &tokens).map_err(|e| exec_text(&e));
                    save_if_pending(
                        &worker,
                        &flow,
                        "codex",
                        tokens,
                        write,
                        "Failed to save authentication tokens",
                    )
                    .await
                }
                Err(e) => Outcome::Failed(with_cause(
                    "Failed to exchange authorization code for tokens",
                    &exec_text(&e),
                )),
            };
            settle(&worker, &flow, outcome).await;
        }
    });
    started(url, sid)
}

/// Go `RequestAntigravityToken`: reuse the CLI exchange and storage, but unlike
/// `CompleteAntigravityOAuth`, a project discovery failure does not fail the login.
async fn start_antigravity(state: Arc<Management>, webui: bool) -> Response {
    use cpa_exec::antigravity_auth::{DEFAULT_CALLBACK_PORT, OAuth, auth_url, build_auth, redirect_uri, write_login};
    let Some(sid) = random_state() else {
        return fail(StatusCode::INTERNAL_SERVER_ERROR, "failed to generate state parameter");
    };
    let redirect = redirect_uri(DEFAULT_CALLBACK_PORT);
    let url = auth_url(&sid, &redirect);
    state.oauth.register(&sid, "antigravity");
    let forwarder = if webui {
        match start_forwarder(&state, DEFAULT_CALLBACK_PORT, "/antigravity/callback").await {
            Ok(id) => Some(id),
            Err(message) => return fail(StatusCode::INTERNAL_SERVER_ERROR, message),
        }
    } else {
        None
    };
    let worker = state.clone();
    let flow = sid.clone();
    let forwarder = forwarder.map(|id| (DEFAULT_CALLBACK_PORT, id));
    spawn_login(&state, &sid, "antigravity", forwarder, async move {
        if let Some(cb) = next_callback(&worker, &flow, "antigravity").await {
            let outcome = async {
                if !cb.error.is_empty() {
                    return Outcome::Failed("Authentication failed".into());
                }
                if !cb.state.is_empty() && cb.state != flow {
                    return Outcome::Failed("Authentication failed: state mismatch".into());
                }
                if cb.code.is_empty() {
                    return Outcome::Failed("Authentication failed: code not found".into());
                }
                let client = login_client(&worker);
                let oauth = match &worker.login_base {
                    Some(base) => OAuth::with_endpoints(
                        client,
                        &format!("{base}/token"),
                        &format!("{base}/oauth2/v2/userinfo?alt=json"),
                        base,
                        base,
                    ),
                    None => OAuth::new(client),
                };
                let tokens = match oauth.exchange_code(&cb.code, &redirect).await {
                    Ok(tokens) if !tokens.access_token.trim().is_empty() => tokens,
                    _ => return Outcome::Failed("Failed to exchange token".into()),
                };
                let access = tokens.access_token.trim();
                let email = match oauth.user_info(access).await {
                    Ok(email) if !email.trim().is_empty() => email,
                    _ => return Outcome::Failed("Failed to fetch user info".into()),
                };
                let project = oauth.project_id(access).await.unwrap_or_else(|_| {
                    // Upstream bodies can contain credentials; do not log the cause.
                    tracing::warn!("antigravity: failed to fetch project ID during management login");
                    String::new()
                });
                let record = build_auth(&tokens, &email, &project, chrono::Utc::now());
                let write = |dir: PathBuf, (name, metadata): (String, serde_json::Map<String, Value>)| {
                    write_login(&dir, &name, &metadata)
                };
                save_if_pending(
                    &worker,
                    &flow,
                    "antigravity",
                    record,
                    write,
                    "Failed to save token to file",
                )
                .await
            }
            .await;
            settle(&worker, &flow, outcome).await;
        }
    });
    started(url, sid)
}

/// Go's callback wait: every 500 ms for up to five minutes, until the callback
/// arrives, the session stops being pending, or the deadline passes (recorded as the
/// session's error).
async fn next_callback(state: &Management, sid: &str, provider: &str) -> Option<Callback> {
    let deadline = Instant::now() + CALLBACK_WAIT;
    loop {
        if !state.oauth.is_pending(sid, provider) {
            return None;
        }
        if Instant::now() > deadline {
            let message = if provider == "antigravity" {
                "OAuth flow timed out"
            } else {
                "Timeout waiting for OAuth callback"
            };
            state.oauth.set_error(sid, message);
            return None;
        }
        if let Some(cb) = state.oauth.take_callback(sid) {
            return Some(cb);
        }
        tokio::time::sleep(Duration::from_millis(500)).await;
    }
}

/// [`next_callback`] with the Claude and Codex checks: an error first, then the state.
/// Returns the code.
async fn wait_for_callback(state: &Management, sid: &str, provider: &str, bad_request: &str) -> Option<String> {
    let cb = next_callback(state, sid, provider).await?;
    if !cb.error.is_empty() {
        state.oauth.set_error(sid, bad_request);
        return None;
    }
    if cb.state != sid {
        state.oauth.set_error(sid, "State code error");
        return None;
    }
    Some(cb.code)
}

/// Go `RequestDevinToken`: PKCE login whose callback reaches the main listener's
/// `/callback` (Devin only accepts `http://127.0.0.1:<port>/callback`).
async fn start_devin(state: Arc<Management>) -> Response {
    use cpa_exec::devin_auth::{DevinAuth, generate_pkce, save_record};
    let port = state.rt.config().port;
    if port == 0 {
        return fail(StatusCode::INTERNAL_SERVER_ERROR, "callback server unavailable");
    }
    let redirect = format!("http://127.0.0.1:{port}/callback");
    let Ok(pkce) = generate_pkce() else {
        return fail(StatusCode::INTERNAL_SERVER_ERROR, "failed to generate PKCE codes");
    };
    let Some(sid) = random_state() else {
        return fail(StatusCode::INTERNAL_SERVER_ERROR, "failed to generate state parameter");
    };
    let mut auth = DevinAuth::new(login_client(&state));
    if let Some(base) = &state.login_base {
        auth = auth.with_app_base(base).with_api_base(base).with_server_base(base);
    }
    let url = auth.build_authorization_url(&redirect, &pkce.challenge, &sid);
    state.oauth.register(&sid, "devin");
    let worker = state.clone();
    let flow = sid.clone();
    spawn_login(&state, &sid, "devin", None, async move {
        // Go runs the whole flow under one five-minute context.
        let deadline = tokio::time::Instant::now() + CALLBACK_WAIT;
        let Some(cb) = next_callback(&worker, &flow, "devin").await else {
            return;
        };
        let fail = |message: &str| {
            if worker.oauth.is_pending(&flow, "devin") {
                fail_session(&worker, &flow, message);
            }
        };
        if cb.state != flow {
            return fail("State code error");
        }
        if !cb.error.is_empty() {
            return fail("Devin authorization denied");
        }
        if cb.code.trim().is_empty() {
            return fail("Missing authorization code");
        }
        // Upstream errors can carry tokens or codes: only Go's fixed messages surface.
        let exchanged = tokio::select! {
            r = auth.exchange_code(&cb.code, &pkce.verifier) => r.ok(),
            () = tokio::time::sleep_until(deadline) => None,
            () = cancelled(&worker, &flow, "devin") => return,
        };
        let token = match exchanged {
            Some(token) if !token.trim().is_empty() => token,
            _ => return fail("Failed to exchange authorization code for tokens"),
        };
        if !worker.oauth.is_pending(&flow, "devin") {
            return;
        }
        let created = tokio::select! {
            r = auth.create_auth_record(&token) => r.ok(),
            () = tokio::time::sleep_until(deadline) => None,
            () = cancelled(&worker, &flow, "devin") => return,
        };
        let Some(record) = created else {
            return fail("Failed to create Devin authentication record");
        };
        let write = |dir: PathBuf, record| save_record(&dir, &record);
        let outcome = save_if_pending(
            &worker,
            &flow,
            "devin",
            record,
            write,
            "Failed to save authentication tokens",
        )
        .await;
        settle(&worker, &flow, outcome).await;
    });
    started(url, sid)
}

/// Go `watchOAuthSessionCancel`: resolves once the session stops being pending.
async fn cancelled(state: &Management, sid: &str, provider: &str) {
    loop {
        tokio::time::sleep(Duration::from_secs(2)).await;
        if !state.oauth.is_pending(sid, provider) {
            return;
        }
    }
}

/// The JSON answer for a started device login.
fn device_started(url: String, sid: String, user_code: &str, expires_in: Option<i64>) -> Response {
    let mut out = vec![
        ("status", Value::from("ok")),
        ("url", url.into()),
        ("state", sid.into()),
        ("flow", "device".into()),
    ];
    if !user_code.trim().is_empty() {
        out.push(("user_code", user_code.trim().into()));
    }
    if let Some(e) = expires_in {
        out.push(("expires_in", e.into()));
    }
    reply(StatusCode::OK, out)
}

/// Go `requestKimiTokenWithDomain`.
async fn start_kimi(state: Arc<Management>, domain: String) -> Response {
    use cpa_exec::kimi_auth::{DeviceFlow, is_ai_domain, login_record, write_login};
    let (provider, prefix) = if is_ai_domain(&domain) {
        ("kimi-ai", "kmi-ai")
    } else {
        ("kimi", "kmi")
    };
    let sid = format!("{prefix}-{}", unix_nanos());
    let mut flow = DeviceFlow::new(login_client(&state), &domain, "");
    if let Some(base) = &state.login_base {
        flow = flow.with_oauth_host(base);
    }
    let Ok(code) = flow.request_device_code().await else {
        return fail(
            StatusCode::INTERNAL_SERVER_ERROR,
            "failed to generate authorization url",
        );
    };
    let url = if code.verification_uri_complete.is_empty() {
        code.verification_uri.clone()
    } else {
        code.verification_uri_complete.clone()
    };
    state.oauth.register(&sid, provider);
    let response = device_started(
        url,
        sid.clone(),
        &code.user_code,
        (code.expires_in > 0).then_some(code.expires_in),
    );
    let worker = state.clone();
    let flow_sid = sid.clone();
    spawn_login(&state, &flow_sid, provider, None, async move {
        let polled = tokio::select! {
            t = flow.poll(&code) => t,
            () = cancelled(&worker, &sid, provider) => return,
        };
        let outcome = match polled {
            Ok(tokens) => {
                let mut record = login_record(
                    provider,
                    &tokens,
                    flow.device_id(),
                    chrono::Utc::now().timestamp_millis(),
                );
                // Go records the requested domain as given.
                record.metadata.insert("domain".into(), domain.clone().into());
                let write = |dir: PathBuf, record| write_login(&dir, &record).map_err(|e| exec_text(&e));
                save_if_pending(
                    &worker,
                    &sid,
                    provider,
                    record,
                    write,
                    "Failed to save authentication tokens",
                )
                .await
            }
            Err(_) if !worker.oauth.is_pending(&sid, provider) => Outcome::Cancelled,
            Err(e) => Outcome::Failed(with_cause("Authentication failed", &exec_text(&e))),
        };
        settle(&worker, &sid, outcome).await;
    });
    response
}

/// Go `RequestMetaToken`.
async fn start_meta(state: Arc<Management>) -> Response {
    use cpa_exec::meta_auth::{MetaAuth, create_token_storage, save_login};
    const MAX_POLL_SECONDS: i64 = 15 * 60;
    let sid = format!("meta-{}", unix_nanos());
    let mut auth = MetaAuth::new(login_client(&state));
    if let Some(base) = &state.login_base {
        auth = auth
            .with_auth_host(base)
            .with_mint_url(&format!("{base}/muse-code/key"));
    }
    let Ok(code) = auth.start_device_flow().await else {
        return fail(
            StatusCode::INTERNAL_SERVER_ERROR,
            "failed to start device authorization flow",
        );
    };
    let url = match code.verification_uri_complete.trim() {
        "" => code.verification_uri.trim().to_owned(),
        u => u.to_owned(),
    };
    state.oauth.register(&sid, "meta");
    let expires = if code.expires_in > 0 {
        code.expires_in
    } else {
        MAX_POLL_SECONDS
    };
    let response = device_started(url, sid.clone(), &code.user_code, Some(expires));
    let worker = state.clone();
    let flow_sid = sid.clone();
    spawn_login(&state, &flow_sid, "meta", None, async move {
        let waited = tokio::select! {
            b = auth.wait_for_authorization(&code) => b,
            () = cancelled(&worker, &sid, "meta") => return,
        };
        let now = chrono::Utc::now();
        let outcome = match waited {
            Err(_) if !worker.oauth.is_pending(&sid, "meta") => Outcome::Cancelled,
            Err(e) => Outcome::Failed(with_cause("Authentication failed", &e)),
            Ok(_) if !worker.oauth.is_pending(&sid, "meta") => Outcome::Cancelled,
            Ok(bundle) if create_token_storage(&bundle, now).access_token.trim().is_empty() => {
                Outcome::Failed("Failed to exchange token".into())
            }
            Ok(bundle) => {
                let write = move |dir: PathBuf, bundle| save_login(&dir, &bundle, now).map(|o| o.path);
                save_if_pending(&worker, &sid, "meta", bundle, write, "Failed to save token to file").await
            }
        };
        settle(&worker, &sid, outcome).await;
    });
    response
}

/// Go `RequestXAIToken`: device flow; the poller saves the credential file.
async fn start_xai(state: Arc<Management>) -> Response {
    use cpa_exec::xai_auth::{LoginRecord, MAX_POLL_DURATION, XaiAuth, login_record, saved_document};
    let sid = format!("xai-{}", unix_nanos());
    let mut auth = XaiAuth::new(login_client(&state));
    if let Some(base) = &state.login_base {
        auth = auth
            .with_issuer_origin(base)
            .with_min_poll_interval(std::time::Duration::from_millis(10));
    }
    let Ok(code) = auth.start_device_flow().await else {
        return fail(
            StatusCode::INTERNAL_SERVER_ERROR,
            "failed to start device authorization flow",
        );
    };
    let url = match code.verification_uri_complete.trim() {
        "" => code.verification_uri.trim().to_owned(),
        u => u.to_owned(),
    };
    state.oauth.register(&sid, "xai");
    let expires = if code.expires_in > 0 {
        code.expires_in
    } else {
        MAX_POLL_DURATION.as_secs() as i64
    };
    let response = device_started(url, sid.clone(), &code.user_code, Some(expires));
    // Go `saveTokenRecord` through the file token store: merged with an existing file.
    fn save_login(dir: &std::path::Path, record: LoginRecord) -> Result<PathBuf, String> {
        let path = dir.join(&record.file_name);
        let existing = std::fs::read(&path).ok().filter(|raw| !raw.is_empty());
        let document = saved_document(record.metadata, existing.as_deref())?;
        let text = cpa_common::json::GoValue::Object(document).encode_indented();
        std::fs::create_dir_all(dir)
            .and_then(|()| super::auth_files::write_file(&path, &text))
            .map_err(|e| e.to_string())?;
        Ok(path)
    }
    let worker = state.clone();
    let flow_sid = sid.clone();
    spawn_login(&state, &flow_sid, "xai", None, async move {
        let waited = tokio::select! {
            t = auth.poll(&code) => t,
            () = cancelled(&worker, &sid, "xai") => return,
        };
        let now = chrono::Utc::now();
        let outcome = match waited {
            _ if !worker.oauth.is_pending(&sid, "xai") => Outcome::Cancelled,
            Err(e) => Outcome::Failed(with_cause("Authentication failed", &exec_text(&e))),
            Ok(tokens) if tokens.access_token.trim().is_empty() => Outcome::Failed("Failed to exchange token".into()),
            Ok(tokens) => {
                // Go `WaitForAuthorization`: RFC 3339 seconds in UTC.
                let last_refresh = now.format("%Y-%m-%dT%H:%M:%SZ").to_string();
                let record = login_record(&tokens, &last_refresh, &code.token_endpoint, now.timestamp_millis());
                let write = |dir: PathBuf, record| save_login(&dir, record);
                save_if_pending(&worker, &sid, "xai", record, write, "Failed to save token to file").await
            }
        };
        settle(&worker, &sid, outcome).await;
    });
    response
}

/// A running callback forwarder (Go `callbackForwarder`).
pub(crate) struct Forwarder {
    id: u64,
    task: tokio::task::JoinHandle<()>,
}

/// Go `startCallbackForwarder`: `0.0.0.0:<port>` redirects every request to the
/// main listener's provider callback. A forwarder already on that port is stopped
/// (and its listener released) first. Errors carry Go's message for the 500 answer.
async fn start_forwarder(state: &Management, port: u16, path: &str) -> Result<u64, &'static str> {
    let cfg = state.rt.config();
    if cfg.port == 0 {
        return Err("callback server unavailable");
    }
    let tls = cfg
        .document
        .get("server")
        .and_then(|s| s.get("tls"))
        .and_then(|t| t.get("enable"))
        .and_then(serde_yaml_ng::Value::as_bool)
        .unwrap_or(false);
    let target = format!("{}://127.0.0.1:{}{path}", if tls { "https" } else { "http" }, cfg.port);
    let previous = state
        .forwarders
        .lock()
        .unwrap_or_else(PoisonError::into_inner)
        .remove(&port);
    if let Some(previous) = previous {
        previous.task.abort();
        let _ = previous.task.await;
    }
    let listener = tokio::net::TcpListener::bind(("0.0.0.0", port))
        .await
        .map_err(|_| "failed to start callback server")?;
    let task = tokio::spawn(async move {
        while let Ok((stream, _)) = listener.accept().await {
            tokio::spawn(forward(stream, target.clone()));
        }
    });
    static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
    let id = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    state
        .forwarders
        .lock()
        .unwrap_or_else(PoisonError::into_inner)
        .insert(port, Forwarder { id, task });
    Ok(id)
}

const FORWARD_TIMEOUT: Duration = Duration::from_secs(5);
const MAX_REQUEST_HEAD: usize = 16 << 10;

/// One forwarder connection with Go's server deadlines (`ReadHeaderTimeout` and
/// `WriteTimeout`, 5 s each): read the request head, answer with the redirect, close.
async fn forward(mut stream: tokio::net::TcpStream, target: String) {
    use tokio::io::{AsyncReadExt, AsyncWriteExt};
    let mut head = Vec::new();
    let read = tokio::time::timeout(FORWARD_TIMEOUT, async {
        let mut buf = [0u8; 2048];
        while !head.windows(4).any(|w| w == b"\r\n\r\n") && head.len() < MAX_REQUEST_HEAD {
            let n = stream.read(&mut buf).await?;
            if n == 0 {
                break;
            }
            head.extend_from_slice(&buf[..n]);
        }
        Ok::<_, std::io::Error>(())
    })
    .await;
    if !matches!(read, Ok(Ok(()))) || !head.windows(4).any(|w| w == b"\r\n\r\n") {
        return;
    }
    let line = head.split(|b| *b == b'\n').next().unwrap_or_default();
    let line = String::from_utf8_lossy(line);
    let mut parts = line.trim_end_matches('\r').split(' ');
    let response = match (parts.next(), parts.next(), parts.next()) {
        (Some(method), Some(uri), Some(version)) if version.starts_with("HTTP/") => {
            redirect_bytes(method, &target, uri.split_once('?').map(|(_, q)| q))
        }
        _ => b"HTTP/1.1 400 Bad Request\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".to_vec(),
    };
    let _ = tokio::time::timeout(FORWARD_TIMEOUT, async {
        stream.write_all(&response).await?;
        stream.shutdown().await
    })
    .await;
}

/// The forwarder's answer: Go `http.Redirect` (302; an HTML link body for GET and
/// HEAD) plus `Cache-Control: no-store`.
fn redirect_bytes(method: &str, target: &str, query: Option<&str>) -> Vec<u8> {
    let location = match query.filter(|q| !q.is_empty()) {
        Some(q) if target.contains('?') => format!("{target}&{q}"),
        Some(q) => format!("{target}?{q}"),
        None => target.to_owned(),
    };
    let mut out = format!("HTTP/1.1 302 Found\r\nCache-Control: no-store\r\nLocation: {location}\r\n");
    let body = if matches!(method, "GET" | "HEAD") {
        let escaped = location
            .replace('&', "&amp;")
            .replace('<', "&lt;")
            .replace('>', "&gt;")
            .replace('"', "&#34;")
            .replace('\'', "&#39;");
        format!("<a href=\"{escaped}\">Found</a>.\n\n")
    } else {
        String::new()
    };
    if !body.is_empty() {
        out.push_str("Content-Type: text/html; charset=utf-8\r\n");
    }
    out.push_str(&format!("Content-Length: {}\r\nConnection: close\r\n\r\n", body.len()));
    if method != "HEAD" {
        out.push_str(&body);
    }
    out.into_bytes()
}

/// Go `stopCallbackForwarderInstance`: only the forwarder this login started.
fn stop_forwarder(state: &Management, port: u16, id: u64) {
    let mut forwarders = state.forwarders.lock().unwrap_or_else(PoisonError::into_inner);
    if forwarders.get(&port).is_some_and(|f| f.id == id)
        && let Some(f) = forwarders.remove(&port)
    {
        f.task.abort();
    }
}

/// Go `GetAuthStatus`; a pending plugin login is polled through its plugin.
pub(crate) async fn status(State(state): State<Arc<Management>>, RawQuery(raw): RawQuery) -> Response {
    let q = Query::parse(raw);
    let sid = q.first("state").trim().to_owned();
    if sid.is_empty() {
        return reply(StatusCode::OK, [("status", "ok".into())]);
    }
    if !valid_state(&sid) {
        return status_error(StatusCode::BAD_REQUEST, "invalid state");
    }
    match state.oauth.details(&sid) {
        None => status_error(StatusCode::OK, "unknown or expired state"),
        Some((_, _, _, _, true)) => reply(StatusCode::OK, [("status", "ok".into())]),
        Some((_, status, _, _, _)) if !status.is_empty() => status_error(StatusCode::OK, &status),
        Some((provider, _, true, metadata, _)) if state.rt.plugins().has_auth_provider(&provider) => {
            match super::plugin_oauth::poll(&state, &sid, &provider, metadata).await {
                Some(response) => response,
                None => reply(StatusCode::OK, [("status", "wait".into())]),
            }
        }
        Some(_) => reply(StatusCode::OK, [("status", "wait".into())]),
    }
}

/// Go `CancelAuthSession`.
pub(crate) async fn cancel(State(state): State<Arc<Management>>, RawQuery(raw): RawQuery) -> Response {
    let q = Query::parse(raw);
    let sid = q.first("state").trim().to_owned();
    if sid.is_empty() {
        return status_error(StatusCode::BAD_REQUEST, "missing state");
    }
    if !valid_state(&sid) {
        return status_error(StatusCode::BAD_REQUEST, "invalid state");
    }
    let cancelled = state.oauth.cancel(&sid);
    reply(
        StatusCode::OK,
        [("status", "ok".into()), ("cancelled", cancelled.into())],
    )
}

#[derive(Default)]
pub(super) struct CallbackRequest {
    pub(super) provider: String,
    pub(super) redirect_url: String,
    pub(super) code: String,
    pub(super) state: String,
    pub(super) error: String,
    /// v8 only: the client ID a Sign in with ChatGPT authorization issued.
    pub(super) client_id: String,
}

/// Go `GetOAuthCallback`, and under v8 `GetOAuthCallbackV8`.
pub(crate) async fn callback_get(
    State(state): State<Arc<Management>>,
    uri: axum::http::Uri,
    RawQuery(raw): RawQuery,
) -> Response {
    let q = Query::parse(raw);
    let error = [q.first("error"), q.first("error_description")]
        .into_iter()
        .map(str::trim)
        .find(|v| !v.is_empty())
        .unwrap_or_default()
        .to_owned();
    let req = CallbackRequest {
        provider: q.first("provider").trim().to_owned(),
        code: q.first("code").trim().to_owned(),
        state: q.first("state").trim().to_owned(),
        error,
        client_id: q.first("client_id").trim().to_owned(),
        ..CallbackRequest::default()
    };
    if uri.path().starts_with("/v8/")
        && let Some(response) = super::siwc::callback(&state, &req, Some(&q))
    {
        return response;
    }
    handle_callback(&state, req)
}

/// Go `PostOAuthCallback`: gin's `ShouldBindJSON` into `oauthCallbackRequest`
/// (first JSON value, exact-then-folded names, type mismatches rejected).
/// Under v8, `PostOAuthCallbackV8`, whose request also has `client_id`.
pub(crate) async fn callback_post(
    State(state): State<Arc<Management>>,
    uri: axum::http::Uri,
    body: Result<crate::body_limit::FirstJson, axum::extract::rejection::BytesRejection>,
) -> Response {
    let body = match body {
        Ok(crate::body_limit::FirstJson(body)) => body,
        Err(rejection) => return status_error(super::read_status(&rejection), "invalid body"),
    };
    let v8 = uri.path().starts_with("/v8/");
    const FIELDS: [&str; 6] = ["provider", "redirect_url", "code", "state", "error", "client_id"];
    let fields = if v8 { &FIELDS[..] } else { &FIELDS[..5] };
    let invalid = || status_error(StatusCode::BAD_REQUEST, "invalid body");
    let Some(members) = super::api_call::bind_struct(&body, fields) else {
        return invalid();
    };
    let mut req = CallbackRequest::default();
    for (i, v) in members {
        let slot = match i {
            0 => &mut req.provider,
            1 => &mut req.redirect_url,
            2 => &mut req.code,
            3 => &mut req.state,
            4 => &mut req.error,
            _ => &mut req.client_id,
        };
        match v {
            Value::String(s) => *slot = s,
            Value::Null => {}
            _ => return invalid(),
        }
    }
    if v8 && let Some(response) = super::siwc::callback(&state, &req, None) {
        return response;
    }
    handle_callback(&state, req)
}

/// Go `handleOAuthCallback`.
fn handle_callback(state: &Management, req: CallbackRequest) -> Response {
    let (mut sid, mut code, mut error) = (
        req.state.trim().to_owned(),
        req.code.trim().to_owned(),
        req.error.trim().to_owned(),
    );
    let redirect = req.redirect_url.trim();
    if !redirect.is_empty() {
        let Some(query) = redirect_query(redirect) else {
            return status_error(StatusCode::BAD_REQUEST, "invalid redirect_url");
        };
        let q = Query::parse(Some(query));
        let get = |k: &str| q.first(k).trim().to_owned();
        if sid.is_empty() {
            sid = get("state");
        }
        if code.is_empty() {
            code = get("code");
        }
        if error.is_empty() {
            error = Some(get("error"))
                .filter(|e| !e.is_empty())
                .unwrap_or_else(|| get("error_description"));
        }
    }
    if sid.is_empty() {
        return status_error(StatusCode::BAD_REQUEST, "state is required");
    }
    if !valid_state(&sid) {
        return status_error(StatusCode::BAD_REQUEST, "invalid state");
    }
    if code.is_empty() && error.is_empty() {
        return status_error(StatusCode::BAD_REQUEST, "code or error is required");
    }
    let Some((session_provider, status, plugin, _, completed)) = state.oauth.details(&sid) else {
        return status_error(StatusCode::NOT_FOUND, "unknown or expired state");
    };
    if completed {
        return status_error(StatusCode::CONFLICT, "oauth flow is already completed");
    }
    let provider = match req.provider.trim() {
        "" => session_provider.clone(),
        p => p.to_owned(),
    };
    let canonical = if plugin {
        super::plugin_oauth::normalize_provider(&provider)
    } else {
        normalize_callback_provider(&provider)
    };
    let Some(canonical) = canonical else {
        return status_error(StatusCode::BAD_REQUEST, "unsupported provider");
    };
    if !status.is_empty() {
        return status_error(StatusCode::CONFLICT, &status);
    }
    if !session_provider.go_eq_fold(&canonical) {
        return status_error(StatusCode::BAD_REQUEST, "provider does not match state");
    }
    // A plugin reads its callback from the auth directory, where Go writes every one.
    if plugin && state.oauth.is_pending(&sid, &canonical) {
        let auth_dir = state.rt.config().auth_dir.clone();
        return match super::plugin_oauth::write_callback_file(&auth_dir, &canonical, &sid, &code, &error) {
            Ok(()) => reply(StatusCode::OK, [("status", "ok".into())]),
            Err(e) => {
                tracing::error!(error = %e, "failed to persist oauth callback");
                status_error(StatusCode::INTERNAL_SERVER_ERROR, "failed to persist oauth callback")
            }
        };
    }
    if !plugin
        && matches!(
            state.oauth.deliver(&canonical, &sid, &code, &error),
            Delivery::Delivered
        )
    {
        return reply(StatusCode::OK, [("status", "ok".into())]);
    }
    match state.oauth.get(&sid) {
        Some((_, status, false)) if !status.is_empty() => status_error(StatusCode::CONFLICT, &status),
        _ => status_error(StatusCode::CONFLICT, "oauth flow is not pending"),
    }
}

/// `url.Parse(raw).RawQuery`, or `None` where Go's parser fails.
fn redirect_query(raw: &str) -> Option<String> {
    cpa_core::config::go_url::parse(raw)?;
    let without_fragment = raw.split('#').next().unwrap_or_default();
    Some(
        without_fragment
            .split_once('?')
            .map(|(_, q)| q.to_owned())
            .unwrap_or_default(),
    )
}

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

    #[test]
    fn session_causes_drop_upstream_bodies_and_descriptions() {
        for (cause, want) in [
            (
                r#"xai device token request failed with status 500: {"access_token":"sentinel"}"#,
                "xai device token request failed with status 500",
            ),
            (
                "xai device token error: invalid_grant: sentinel-description",
                "xai device token error: invalid_grant",
            ),
            ("xai device token error: weird", "xai device token error: weird"),
            (
                "meta device flow failed (HTTP 401): sentinel-body",
                "meta device flow failed (HTTP 401)",
            ),
            (
                "meta auth: error from authorization server: server_error: sentinel",
                "meta auth: error from authorization server: server_error",
            ),
            ("kimi: OAuth error: bad_code - sentinel", "kimi: OAuth error: bad_code"),
            ("kimi: OAuth error: sentinel$token!", "kimi: OAuth error: sentinel"),
            ("xai device code expired", "xai device code expired"),
            // A later marker inside the description must not decide the cut.
            (
                "kimi: OAuth error: invalid_grant - SENTINEL with status 500",
                "kimi: OAuth error: invalid_grant",
            ),
            (
                "xai device token error: x: SENTINEL (HTTP 500)",
                "xai device token error: x",
            ),
            // Decoder diagnostics quote response values.
            (
                r#"failed to parse token response: invalid type: string "SENTINEL", expected i64"#,
                "failed to parse token response",
            ),
            (
                "xai device token: parse response: json: cannot unmarshal number 123456789012345678901234567890",
                "xai device token: parse response",
            ),
            (
                "meta auth: parse mint response: number 99999999999999999999",
                "meta auth: parse mint response",
            ),
        ] {
            assert_eq!(redact_upstream(cause), want);
        }
        assert_eq!(
            with_cause(
                "Authentication failed",
                "kimi: device code request failed with status 400: body"
            ),
            "Authentication failed: kimi: device code request failed with status 400"
        );
    }

    #[test]
    fn states_and_providers_follow_go() {
        assert!(valid_state("kmi-ai-1759.x_y"));
        for bad in ["", "a/b", "a\\b", "a..b", "sp ace", &"x".repeat(129)] {
            assert!(!valid_state(bad), "{bad}");
        }
        assert_eq!(normalize_callback_provider(" Claude ").as_deref(), Some("anthropic"));
        assert_eq!(normalize_callback_provider("grok").as_deref(), Some("xai"));
        assert_eq!(normalize_callback_provider("kimi").as_deref(), Some("kimi"));
        assert_eq!(normalize_callback_provider("kimi_ai"), None);
    }

    #[test]
    fn sessions_follow_go_lifecycle() {
        let s = Sessions::default();
        s.register("st", "codex");
        assert!(s.is_pending("st", "CODEX"));
        assert_eq!(s.deliver("openai", "st", "c", ""), Delivery::Delivered);
        assert_eq!(s.take_callback("st").map(|c| c.code).as_deref(), Some("c"));
        s.set_error("st", " ");
        assert_eq!(
            s.get("st"),
            Some(("codex".into(), "Authentication failed".into(), false))
        );
        assert!(!s.cancel("st"), "an errored session is not cancellable");
        assert_eq!(s.deliver("codex", "st", "c", ""), Delivery::NotPending);
        s.register("done", "meta");
        s.complete("done");
        assert_eq!(s.get("done"), Some(("meta".into(), String::new(), true)));
        assert!(!s.cancel("done"));
        // 61 s later the success still reads, and a second callback is still refused.
        s.lock().get_mut("done").unwrap().expires -= Duration::from_secs(61);
        assert_eq!(s.get("done"), Some(("meta".into(), String::new(), true)));
        assert_eq!(s.deliver("meta", "done", "c", ""), Delivery::NotPending);
        s.register("live", "kimi");
        assert!(s.cancel("live"));
        assert!(s.get("live").is_none());
    }

    /// Go `TestSIWCBindCommitSurvivesSessionExpiry`: a binding whose disk commit has
    /// started outlives its session expiry so it can report the outcome, and completing
    /// it releases that hold.
    #[test]
    fn a_claimed_siwc_commit_outlives_the_session_expiry() {
        let s = Sessions::default();
        let flow = super::super::siwc::Flow::idle("codex.json");
        assert!(s.register_siwc("st", flow.clone(), Duration::from_secs(300)));
        assert!(s.claim_siwc_commit("st", &flow));
        let expire = || s.lock().get_mut("st").unwrap().expires = Instant::now();
        expire();
        assert_eq!(s.get("st"), Some(("codex".into(), String::new(), false)));
        assert!(!s.cancel("st"), "a started commit is past cancelling");
        s.complete("st");
        assert_eq!(s.get("st"), Some(("codex".into(), String::new(), true)));
        expire();
        assert!(s.get("st").is_none(), "the completed session no longer holds on");
    }

    #[test]
    fn forwarder_redirect_keeps_the_query() {
        let r = String::from_utf8(redirect_bytes(
            "GET",
            "http://127.0.0.1:8317/codex/callback",
            Some("code=a&state=b"),
        ))
        .unwrap();
        assert!(r.starts_with("HTTP/1.1 302 Found\r\n"), "{r}");
        assert!(
            r.contains("\r\nLocation: http://127.0.0.1:8317/codex/callback?code=a&state=b\r\n"),
            "{r}"
        );
        assert!(r.contains("\r\nCache-Control: no-store\r\n"), "{r}");
        assert!(r.ends_with("\">Found</a>.\n\n"), "{r}");
        let post = String::from_utf8(redirect_bytes("POST", "http://h/cb", None)).unwrap();
        assert!(
            post.ends_with("Content-Length: 0\r\nConnection: close\r\n\r\n"),
            "{post}"
        );
    }

    /// A client that never finishes its request head is dropped after Go's 5 s
    /// header deadline; a complete one gets the redirect.
    #[tokio::test]
    async fn forwarder_connections_have_go_deadlines() {
        use tokio::io::{AsyncReadExt, AsyncWriteExt};
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        tokio::spawn(async move {
            while let Ok((s, _)) = listener.accept().await {
                tokio::spawn(forward(s, "http://127.0.0.1:1/x".into()));
            }
        });
        let mut slow = tokio::net::TcpStream::connect(addr).await.unwrap();
        slow.write_all(b"GET /?a=1 HTTP/1.1\r\nHost: x\r\n").await.unwrap();
        let mut buf = Vec::new();
        let closed = tokio::time::timeout(Duration::from_secs(8), slow.read_to_end(&mut buf)).await;
        assert!(matches!(closed, Ok(Ok(0))), "dropped without an answer");
        let mut ok = tokio::net::TcpStream::connect(addr).await.unwrap();
        ok.write_all(b"GET /cb?code=c HTTP/1.1\r\nHost: x\r\n\r\n")
            .await
            .unwrap();
        let mut out = String::new();
        ok.read_to_string(&mut out).await.unwrap();
        assert!(out.contains("Location: http://127.0.0.1:1/x?code=c\r\n"), "{out}");
    }
}