openlatch-client 0.6.19

OpenLatch runtime enforcement node — the capture-and-enforce adapter that evaluates every covered action against a coding agent's Autonomy Zone before it runs
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
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
//! `openlatch system auth` command handlers — login, logout, and status.
//!
//! ## Flow overview
//!
//! **login**: Binds a callback server on 127.0.0.1:0 and opens the browser to
//! `app.openlatch.ai/cli-auth?flow=code&…` with a PKCE challenge and `state`
//! (PLT-7 C-2). The page hands back a single-use code, never a key. The CLI
//! lists the user's organizations with it, the user chooses one (or names it
//! with `--org` / `OPENLATCH_ORG`), and only then is a key minted, in that
//! organization, and stored in the OS keychain (or the encrypted file).
//!
//! **logout**: Revokes the stored key (fail-open) and deletes it from both the
//! keychain and the encrypted file (C-9).
//!
//! **status**: Retrieves stored credential, optionally validates online via
//! `GET /api/v1/users/me`, and prints human or JSON output.

use std::time::Duration;

use tokio::io::AsyncReadExt;

use secrecy::{ExposeSecret, SecretString};

use crate::cli::output::{OutputConfig, OutputFormat};
use crate::core::auth::org_choice;
pub use crate::core::auth::org_choice::Org;
use crate::core::auth::pkce::{Pkce, CHALLENGE_METHOD};
use crate::error::{
    OlError, ERR_AUTH_FLOW_FAILED, ERR_AUTH_TIMEOUT, ERR_CLOUD_UNREACHABLE, ERR_NO_ORGANIZATION,
    ERR_ORG_UNAVAILABLE, ERR_SIGN_IN_EXPIRED, ERR_SIGN_IN_THROTTLED,
};
use crate::generated::types::{CliAuthExchangeResponse, CliAuthOrganizationsResponse};

// AuthLoginArgs is defined in crate::cli::AuthLoginArgs (src/cli/mod.rs) for
// clap derive integration. Re-export here for internal test convenience.
pub use crate::cli::AuthLoginArgs;

const DEFAULT_CLOUD_URL: &str = "https://app.openlatch.ai";

/// How long `auth login` waits for the browser to come back (AUTH-06).
///
/// The spinner's countdown reads from this, so the number the user watches and
/// the number the timer honours cannot drift apart.
const CALLBACK_TIMEOUT: Duration = Duration::from_secs(300);

/// How long the callback port stays open after [`CALLBACK_TIMEOUT`] elapses,
/// purely so one late browser is told the link expired instead of meeting a
/// closed socket.
///
/// Deliberately short. The common timeout is nobody arriving at all, and this
/// window is awaited *after* the spinner is cleared, so every second of it is
/// a terminal that looks wedged — the cost lands on the case the feature was
/// not built for. It also sits inside `auth_failed`'s `duration_ms`, so a long
/// grace would smear the timeout histogram's spike across a 30-second band.
/// A browser redirecting more than a moment after the deadline has been
/// abandoned anyway.
const EXPIRED_GRACE: Duration = Duration::from_secs(3);

/// How long an accepted connection has to send its request.
///
/// [`CALLBACK_TIMEOUT`] bounds waiting for a *connection*; this bounds the
/// request that follows. Without it a peer that connects and says nothing
/// consumes the single accept and hangs the login forever.
const REQUEST_READ_TIMEOUT: Duration = Duration::from_secs(10);

// ---------------------------------------------------------------------------
// Helper functions (shared by login, logout, status)
// ---------------------------------------------------------------------------

/// Attempt to open `url` in the system browser.
///
/// On Linux, skips the open attempt if neither `DISPLAY` nor `WAYLAND_DISPLAY`
/// is set (headless environment). On all platforms, returns `false` if the
/// open attempt fails.
///
/// Returns `true` if the browser was successfully launched.
pub fn try_open_browser(url: &str) -> bool {
    #[cfg(target_os = "linux")]
    {
        let has_display = std::env::var("DISPLAY").is_ok();
        let has_wayland = std::env::var("WAYLAND_DISPLAY").is_ok();
        if !has_display && !has_wayland {
            return false;
        }
    }

    open::that(url).is_ok()
}

/// Mask an API key for display, showing only the prefix and last 4 characters.
///
/// Returns `"{first_7}...{last_4}"`. For keys shorter than 11 characters, the
/// full key is returned to avoid displaying nothing meaningful.
///
/// # Examples
/// `mask_api_key("ol_org_abcdef1234567890")` → `"ol_org_...7890"`
pub fn mask_api_key(key: &str) -> String {
    if key.len() <= 11 {
        return key.to_string();
    }
    let prefix = &key[..7];
    let suffix = &key[key.len() - 4..];
    format!("{prefix}...{suffix}")
}

/// Percent-decode a URL query string value (WR-04).
///
/// Converts `%XX` hex sequences to the corresponding byte and replaces `+` with space.
/// Invalid `%XX` sequences (non-hex or truncated) are passed through verbatim.
fn url_decode(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    let bytes = s.as_bytes();
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i] == b'+' {
            out.push(' ');
            i += 1;
        } else if bytes[i] == b'%' && i + 2 < bytes.len() {
            let hi = (bytes[i + 1] as char).to_digit(16);
            let lo = (bytes[i + 2] as char).to_digit(16);
            if let (Some(h), Some(l)) = (hi, lo) {
                out.push(char::from((h * 16 + l) as u8));
                i += 3;
            } else {
                out.push(bytes[i] as char);
                i += 1;
            }
        } else {
            out.push(bytes[i] as char);
            i += 1;
        }
    }
    out
}

/// Percent-encode a string as a URL query-value component.
///
/// Matches the complement of `url_decode`: only RFC 3986 unreserved characters
/// (`ALPHA / DIGIT / "-" / "." / "_" / "~"`) pass through; every other byte
/// is encoded as `%XX`. Used to build the `/cli-auth` URL so hostnames with
/// spaces, apostrophes, or non-ASCII characters (common on macOS) survive
/// the browser round-trip.
fn url_encode(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for &b in s.as_bytes() {
        match b {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => {
                out.push(b as char);
            }
            _ => {
                out.push('%');
                out.push_str(&format!("{b:02X}"));
            }
        }
    }
    out
}

/// Best-effort system hostname for naming the generated API key.
///
/// The platform uses this to label the key (e.g. `cli-devbox-2026-04-22`).
/// Returns `None` on any failure — the platform falls back to a generic label.
/// Does not leak to telemetry (see `core/telemetry/super_props.rs`).
///
/// Re-exported rather than defined here: the resolver moved to
/// `daemon::identity::hostname` when `hostname` became a wire attribute (I-4),
/// and one host has one hostname however many callers ask for it.
pub use crate::daemon::identity::hostname::system_hostname;

/// The three parameters a `/callback` query can carry (PLT-7 C-2), each
/// percent-decoded. Anything else in the query is ignored.
#[derive(Default, PartialEq, Eq)]
pub(crate) struct CallbackQuery {
    /// The single-use sign-in code (`olc_…`). Secret until exchanged.
    pub code: Option<String>,
    /// Must equal the sign-in's own `state`.
    pub state: Option<String>,
    /// A refusal the page sends instead of a code (`no_organization`,
    /// `too_many_codes`, …).
    pub error: Option<String>,
}

/// Parse a raw query string (the part after `?`). Empty values count as absent.
pub(crate) fn parse_callback_query(query: &str) -> CallbackQuery {
    let mut q = CallbackQuery::default();
    for pair in query.split('&') {
        let mut parts = pair.splitn(2, '=');
        let k = parts.next().unwrap_or("").trim();
        let v = url_decode(parts.next().unwrap_or("").trim());
        if v.is_empty() {
            continue;
        }
        match k {
            "code" => q.code = Some(v),
            "state" => q.state = Some(v),
            "error" => q.error = Some(v),
            _ => {}
        }
    }
    q
}

// ---------------------------------------------------------------------------
// Callback landing page
// ---------------------------------------------------------------------------
//
// This is the only moment in enrolment where the product speaks for itself
// rather than through the terminal, so it is built to the console's design
// system — and it renders on EVERY path that reaches the port, including the
// failures, which previously dropped the socket and showed the browser
// `ERR_EMPTY_RESPONSE`.
//
// Hard constraints, none of them enforced by a test that can see the browser:
//
// * **Zero external requests.** No webfont, no CDN, no remote logo. The client
//   targets air-gapped and proxied enterprise hosts; a page that hangs on
//   `fonts.googleapis.com` is broken exactly where it must not be. The mark is
//   inlined SVG path data lifted verbatim from the console's `BrandLogo.tsx`,
//   and every font is a system stack.
// * **Tokens are hand-ported, not imported** — the accepted cost of answering
//   from the loopback listener instead of redirecting to the console. Values
//   mirror `ui/styles/theme.css`; keep them in sync by hand.
// * **The listener keeps serving until a callback carries this sign-in's own
//   `state`** (PLT-7 D-4), so a favicon request or a stray hit is answered and
//   ignored. The page still references no favicon: nothing should ask for one.

/// Which page the loopback listener is rendering.
#[derive(Debug, Clone, Copy)]
pub enum Outcome {
    /// The callback arrived carrying a sign-in code.
    Connected,
    /// The login window closed before the browser came back.
    Expired,
    /// Something reached the port without a well-formed callback — a non-GET
    /// request, another path, or a missing or foreign `state`. Most often a
    /// human opening the URL by hand.
    Malformed,
    /// The sign-in page sent a refusal (`error=…`) instead of a code; the
    /// terminal says why.
    Refused,
}

/// Everything that varies between the three pages.
///
/// One table rather than copy here and a body class decided elsewhere: the
/// arrival choreography is the success signal, and a new variant that picked
/// it up by defaulting would animate as though something had arrived.
struct Page {
    title: &'static str,
    heading: &'static str,
    /// May carry inline markup. Every value is a literal — see `render_page`.
    body: &'static str,
    class: &'static str,
}

impl Outcome {
    fn page(self) -> Page {
        match self {
            Outcome::Connected => Page {
                title: "Connected",
                heading: "Connected.",
                body: "You can close this tab — the terminal has what it needs.",
                class: "connected",
            },
            Outcome::Expired => Page {
                title: "Link expired",
                heading: "This link expired.",
                body: "Run <code>openlatch system auth login</code> again to start over.",
                class: "settled",
            },
            Outcome::Malformed => Page {
                title: "Open from the CLI",
                heading: "This page opens from the CLI.",
                body: "Run <code>openlatch system auth login</code> in your terminal.",
                class: "settled",
            },
            Outcome::Refused => Page {
                title: "Sign-in stopped",
                heading: "Sign-in stopped.",
                body: "Your terminal says why, and what to do next.",
                class: "settled",
            },
        }
    }
}

/// What the listener answers with: a status line welded to its page.
///
/// The two travel together so a call site cannot pair a `200 OK` with the
/// expired page, and so `Allow: GET` cannot be lost by writing a status
/// without its reason phrase.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Reply {
    Connected,
    Refused,
    BadRequest,
    NotFound,
    MethodNotAllowed,
    RequestTimeout,
    Expired,
}

impl Reply {
    fn status(self) -> &'static str {
        match self {
            Reply::Connected | Reply::Refused => "200 OK",
            Reply::BadRequest => "400 Bad Request",
            Reply::NotFound => "404 Not Found",
            Reply::MethodNotAllowed => "405 Method Not Allowed",
            Reply::RequestTimeout => "408 Request Timeout",
            Reply::Expired => "410 Gone",
        }
    }

    fn outcome(self) -> Outcome {
        match self {
            Reply::Connected => Outcome::Connected,
            Reply::Refused => Outcome::Refused,
            Reply::Expired => Outcome::Expired,
            Reply::BadRequest
            | Reply::NotFound
            | Reply::MethodNotAllowed
            | Reply::RequestTimeout => Outcome::Malformed,
        }
    }

    /// RFC 9110 requires `Allow` on a 405.
    fn extra_headers(self) -> &'static str {
        match self {
            Reply::MethodNotAllowed => "Allow: GET\r\n",
            _ => "",
        }
    }
}

/// The OpenLatch icon mark, lifted verbatim from the console's `BrandLogo.tsx`
/// (`icon` variant, viewBox `0 0 218.89 225.39`).
///
/// The two paths are interlocking half-brackets, and they are also the page's
/// only motion: on load they arrive from opposite corners and close once. The
/// fills are driven by `--signal` so the same markup serves every outcome.
const MARK_SVG: &str = r#"<svg class="mark" viewBox="0 0 218.89 225.39" fill="none" xmlns="http://www.w3.org/2000/svg" role="img" aria-label="OpenLatch">
<g transform="translate(-503.156 -640.3556)">
<path class="mk-a" data-anim fill="var(--signal)" d="M706.5,698.5v112.9h-55.7v-92.7c0-25.6-20.8-46.3-46.3-46.3h-85.7v-16.5h145.1 C687.4,655.8,706.5,674.9,706.5,698.5z"/>
<path class="mk-b" data-anim fill="var(--signal-2)" d="M518.7,807.5V694.7h55.7v92.7c0,25.6,20.8,46.3,46.3,46.3h85.7v16.5H561.4 C537.8,850.2,518.7,831.1,518.7,807.5z"/>
</g>
</svg>"#;

/// The page's whole stylesheet. Carries no interpolation on purpose: the
/// outcome is expressed by a single class on `<body>`, so this stays a plain
/// constant instead of a `format!` template full of escaped braces.
const PAGE_CSS: &str = r#":root{
  --background:#FFFFFF;
  --foreground:#0F172A;
  --muted-foreground:#64748B;
  --border:#E2E8F0;
  --primary:#0D9488;
  --primary-deep:#0F766E;
  --ease-kinetic:cubic-bezier(.34,1.56,.64,1);
  --ease-micro:cubic-bezier(.2,0,0,1);
  --serif:Georgia,"Times New Roman",serif;
  --sans:system-ui,-apple-system,"Segoe UI",sans-serif;
  --mono:ui-monospace,"JetBrains Mono",Consolas,monospace;
}
@media (prefers-color-scheme:dark){
  :root{
    --background:#0F172A;
    --foreground:#F8FAFC;
    --muted-foreground:#94A3B8;
    --border:#334155;
    --primary:#14B8A6;
    --primary-deep:#0D9488;
  }
}
/* The mark carries the outcome: teal when the handshake landed, muted when
   it did not. Set on body so it cascades into the inlined SVG. */
body{--signal:var(--muted-foreground);--signal-2:var(--muted-foreground)}
body.connected{--signal:var(--primary);--signal-2:var(--primary-deep)}

*{box-sizing:border-box}
html,body{height:100%}
body{margin:0;display:flex;background:var(--background);color:var(--foreground);
     font-family:var(--sans);-webkit-font-smoothing:antialiased;
     text-rendering:optimizeLegibility}
.wrap{margin:auto;padding:40px 28px;text-align:center;max-width:600px}
.mark{display:block;width:86px;height:auto;margin:0 auto 42px}
h1{font-family:var(--serif);font-weight:600;font-size:clamp(30px,5.4vw,42px);
   line-height:1.1;letter-spacing:-.021em;margin:0 0 16px;text-wrap:balance}
p{margin:0 auto;max-width:48ch;color:var(--muted-foreground);font-size:15px;
  line-height:1.62;text-wrap:balance}
code{font-family:var(--mono);font-size:.92em;color:var(--foreground);
     border:1px solid var(--border);padding:1px 5px;white-space:nowrap}

/* One page-load beat, and only one. The implicit `to` keyframe resolves to
   each element's own resting style, so nothing has to restate it. */
@keyframes latch-a{from{transform:translate(40px,-32px);opacity:0}}
@keyframes latch-b{from{transform:translate(-40px,32px);opacity:0}}
@keyframes rise{from{transform:translateY(10px);opacity:0}}
@keyframes fade{from{opacity:0}}
.mk-a{animation:latch-a 640ms var(--ease-kinetic) both}
.mk-b{animation:latch-b 640ms var(--ease-kinetic) 90ms both}
h1{animation:rise 480ms var(--ease-micro) 430ms both}
p{animation:rise 480ms var(--ease-micro) 530ms both}

/* Nothing arrived, so nothing animates as if it did. */
.settled [data-anim]{animation-name:fade!important;animation-duration:340ms!important;
                     animation-timing-function:ease!important}
@media (prefers-reduced-motion:reduce){
  [data-anim]{animation-name:fade!important;animation-duration:300ms!important;
              animation-timing-function:ease!important}
}"#;

/// Render the landing page for `outcome`.
///
/// Every string interpolated here is a compile-time constant — nothing from
/// the callback query reaches the DOM, so there is no escaping to get wrong.
pub fn render_page(outcome: Outcome) -> String {
    let Page {
        title,
        heading,
        body,
        class,
    } = outcome.page();

    // Raw string: `format!` still interpolates `{}` inside `r#"…"#`, and the
    // markup reads as markup instead of through an escape on every attribute.
    format!(
        r#"<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>OpenLatch — {title}</title>
<style>
{PAGE_CSS}
</style>
</head>
<body class="{class}">
<div class="wrap">
{MARK_SVG}
<h1 data-anim>{heading}</h1>
<p data-anim>{body}</p>
</div>
</body>
</html>"#
    )
}

/// Build the full HTTP response carrying `html`.
///
/// `Content-Length` is `html.len()` — the BYTE length, which is what
/// `str::len` gives. The copy contains an em dash, so a char count would
/// under-report by two and truncate the page in the browser.
fn build_response(reply: Reply, html: &str) -> String {
    format!(
        "HTTP/1.1 {status}\r\n\
         Content-Type: text/html; charset=utf-8\r\n\
         Content-Length: {len}\r\n\
         Cache-Control: no-store\r\n\
         {extra}\
         Connection: close\r\n\
         \r\n\
         {html}",
        status = reply.status(),
        extra = reply.extra_headers(),
        len = html.len(),
    )
}

/// Write `outcome`'s page to `stream`, then let the caller drop it.
///
/// Best-effort by design: a browser that has already navigated away leaves a
/// half-closed socket, and failing to write to it must never fail a login that
/// otherwise succeeded.
async fn write_page(stream: &mut tokio::net::TcpStream, reply: Reply) {
    use tokio::io::AsyncWriteExt;
    let response = build_response(reply, &render_page(reply.outcome()));
    let _ = stream.write_all(response.as_bytes()).await;
    let _ = stream.flush().await;
}

/// Return the platform-appropriate credential store backend name.
pub fn keychain_backend_name() -> &'static str {
    #[cfg(target_os = "macos")]
    return "macOS Keychain";
    #[cfg(target_os = "windows")]
    return "Windows Credential Manager";
    #[cfg(target_os = "linux")]
    return "Linux Secret Service";
    #[cfg(not(any(target_os = "macos", target_os = "windows", target_os = "linux")))]
    return "OS Keychain";
}

// ---------------------------------------------------------------------------
// Callback server
// ---------------------------------------------------------------------------

/// A callback this listener refuses, and the page the browser gets for it.
///
/// Carrying the reply as **data** is what makes "every rejection is answered"
/// structural rather than remembered: the code that decides a request is bad
/// holds no socket, so a new early return cannot forget to write a page. It
/// can only choose which page.
///
/// `reply` is `None` for exactly the two cases with nobody left to render
/// onto — a socket read error and a zero-byte read, both meaning the peer is
/// already gone.
struct Rejection {
    reply: Option<Reply>,
    error: OlError,
}

impl Rejection {
    fn silent(error: OlError) -> Self {
        Rejection { reply: None, error }
    }

    fn answered(reply: Reply, error: OlError) -> Self {
        Rejection {
            reply: Some(reply),
            error,
        }
    }
}

/// Read one HTTP request off an accepted `stream`, bounded in both size and time.
///
/// `timeout` bounds a peer that connects and then says nothing. The login
/// budget covers waiting for a *connection*; once one is accepted this is the
/// only thing standing between a browser preconnect, a port scan or an idle
/// `nc` and an `openlatch system auth login` that hangs forever — the listener
/// accepts exactly one connection, so a silent peer consumes it.
///
/// (T-04-02-08: capped read, no infinite loops)
async fn read_request(
    stream: &mut tokio::net::TcpStream,
    timeout: Duration,
) -> Result<Vec<u8>, Rejection> {
    // Read up to 4096 bytes (T-04-02-08: capped read, no infinite loops)
    let mut buf = vec![0u8; 4096];

    let read = tokio::time::timeout(timeout, stream.read(&mut buf)).await;

    let n = match read {
        Ok(Ok(n)) => n,
        Ok(Err(e)) => {
            return Err(Rejection::silent(OlError::new(
                ERR_AUTH_FLOW_FAILED,
                format!("Failed to read callback request: {e}"),
            )))
        }
        Err(_elapsed) => {
            return Err(Rejection::answered(
                Reply::RequestTimeout,
                OlError::new(
                    ERR_AUTH_FLOW_FAILED,
                    "Callback connection sent no request in time",
                )
                .with_suggestion("Something else may have claimed the port. Try again."),
            ))
        }
    };

    // Empty read = connection closed prematurely (T-04-02-08)
    if n == 0 {
        return Err(Rejection::silent(
            OlError::new(
                ERR_AUTH_FLOW_FAILED,
                "Callback received empty (truncated) HTTP request",
            )
            .with_suggestion("The browser may have closed the connection. Try again."),
        ));
    }

    buf.truncate(n);
    Ok(buf)
}

/// What one request to the loopback port amounts to (PLT-7 D-4).
#[derive(Debug, PartialEq, Eq)]
enum CallbackDecision {
    /// `GET /callback` with this sign-in's `state` and a code: done.
    Code(String),
    /// `GET /callback` with this sign-in's `state` and `error=<code>`: the
    /// sign-in ends with that refusal.
    Refused(String),
    /// Anything else — another method, another path, a missing or foreign
    /// `state`. Answered with this reply, and the listener keeps waiting.
    Ignored(Reply),
}

/// Decide what a raw HTTP request is.
///
/// Pure, and deliberately holds no stream — see [`Rejection`]. Only a request
/// carrying this sign-in's own `state` can end the wait, so a favicon fetch, a
/// port scan or a stray redirect never aborts a sign-in, and a callback forged
/// by a page that does not know `state` is refused (RFC 8252 §8.3).
fn classify_callback(raw: &[u8], pkce: &Pkce) -> CallbackDecision {
    let request_str = String::from_utf8_lossy(raw);
    let first_line = request_str.lines().next().unwrap_or("");

    let Some(target) = first_line.strip_prefix("GET ") else {
        return CallbackDecision::Ignored(Reply::MethodNotAllowed);
    };
    // "GET /path?query HTTP/1.1"
    let target = target.split_whitespace().next().unwrap_or("");
    let (path, query) = target.split_once('?').unwrap_or((target, ""));
    if path != "/callback" {
        return CallbackDecision::Ignored(Reply::NotFound);
    }

    let q = parse_callback_query(query);
    match q.state.as_deref() {
        Some(state) if pkce.state_matches(state) => {}
        _ => return CallbackDecision::Ignored(Reply::BadRequest),
    }
    match (q.code, q.error) {
        (_, Some(error)) => CallbackDecision::Refused(error),
        (Some(code), None) => CallbackDecision::Code(code),
        (None, None) => CallbackDecision::Ignored(Reply::BadRequest),
    }
}

/// The error a refusal from the sign-in page ends the sign-in with (C-2, C-10).
fn callback_refusal(code: &str) -> OlError {
    match code {
        "no_organization" => no_organization(),
        "too_many_codes" => OlError::new(
            ERR_SIGN_IN_THROTTLED,
            "Too many sign-ins are in progress for your account",
        )
        .with_suggestion("Wait five minutes, then run the command again."),
        // An unknown refusal is shown by its code: it is the platform's word,
        // never a secret.
        other => OlError::new(
            ERR_AUTH_FLOW_FAILED,
            format!("The sign-in page refused the sign-in ({other})"),
        )
        .with_suggestion("Run the command again. If it keeps failing, update the client."),
    }
}

fn no_organization() -> OlError {
    OlError::new(
        ERR_NO_ORGANIZATION,
        "Your account belongs to no available organization",
    )
    .with_suggestion("Ask an admin of your organization to invite you.")
}

/// Serve the loopback port until a callback carries this sign-in's `state`, or
/// `deadline` passes.
///
/// Every connection is answered — a browser reaching this port must never see
/// `ERR_EMPTY_RESPONSE` — and only [`CallbackDecision::Code`] or
/// [`CallbackDecision::Refused`] end the wait. The platform is never called
/// from here: nothing reaches it until a code with the right `state` arrived.
async fn wait_for_code(
    listener: &tokio::net::TcpListener,
    pkce: &Pkce,
    deadline: tokio::time::Instant,
    read_timeout: Duration,
) -> Result<String, OlError> {
    loop {
        let accepted = match tokio::time::timeout_at(deadline, listener.accept()).await {
            Err(_elapsed) => {
                serve_expired_page(listener).await;
                return Err(OlError::new(
                    ERR_AUTH_TIMEOUT,
                    "Authentication timed out after 5 minutes",
                )
                .with_suggestion("Run the command again to sign in."));
            }
            Ok(accepted) => accepted,
        };
        let Ok((mut stream, _)) = accepted else {
            // A failed accept is one connection, not the sign-in.
            continue;
        };
        let raw = match read_request(&mut stream, read_timeout).await {
            Ok(raw) => raw,
            Err(Rejection { reply, error }) => {
                tracing::debug!(code = error.code, reason = %error.message, "loopback connection ignored");
                if let Some(reply) = reply {
                    write_page(&mut stream, reply).await;
                }
                continue;
            }
        };
        match classify_callback(&raw, pkce) {
            CallbackDecision::Code(code) => {
                write_page(&mut stream, Reply::Connected).await;
                return Ok(code);
            }
            CallbackDecision::Refused(error) => {
                write_page(&mut stream, Reply::Refused).await;
                return Err(callback_refusal(&error));
            }
            CallbackDecision::Ignored(reply) => write_page(&mut stream, reply).await,
        }
    }
}

/// Hold the callback port open briefly after the login window closes, purely
/// to tell one late browser that the link expired.
///
/// Without this the listener is dropped the moment the timer fires and a
/// browser finishing the handshake a second later meets a closed socket —
/// `ERR_CONNECTION_REFUSED`, which says nothing about what happened. The wait
/// is bounded by [`EXPIRED_GRACE`], runs after the spinner has already been
/// cleared, and never delays the CLI's own timeout error by more than that.
async fn serve_expired_page(listener: &tokio::net::TcpListener) {
    let Ok(Ok((mut stream, _))) = tokio::time::timeout(EXPIRED_GRACE, listener.accept()).await
    else {
        return;
    };

    // Same bounded reader as the live path — the window is closed, so the
    // request is drained and discarded rather than parsed.
    let _ = read_request(&mut stream, REQUEST_READ_TIMEOUT).await;

    write_page(&mut stream, Reply::Expired).await;
}

// ---------------------------------------------------------------------------
// Login: the single-use code flow (PLT-7 C-2, C-3, C-6)
// ---------------------------------------------------------------------------
//
// The browser no longer hands back a key. It hands back a single-use code
// bound to this process by PKCE and `state`; the CLI lists the user's
// organizations with it, the user (or `--org`) chooses one, and only then is a
// key minted, in that organization. `init`, `auth login` and `auth switch`
// share the one sequence, [`sign_in_with_code`].

/// How long the organization picker waits for a typed line: the consent
/// prompt's budget, so the two questions of one `init` behave alike.
const PICKER_BUDGET: Duration = Duration::from_secs(120);

/// What a sign-in is for: the exchange's `intent` and the audit action the
/// platform writes (`host.enrolled` / `host.switched`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Intent {
    Enroll,
    Switch,
}

impl Intent {
    /// The wire value.
    pub fn as_str(self) -> &'static str {
        match self {
            Intent::Enroll => "enroll",
            Intent::Switch => "switch",
        }
    }
}

/// What [`sign_in_with_code`] produced.
pub enum Exchanged {
    /// A key minted in `organization`. The key is secret: store it, never print it.
    New {
        key: SecretString,
        organization: Org,
    },
    /// A switch named the organization this machine already reports to. No key
    /// was minted (C-8 step 2).
    AlreadyIn(Org),
}

/// Where a sign-in runs.
pub struct SignInCtx<'a> {
    pub output: &'a OutputConfig,
    /// The platform API origin (`cloud.api_url`).
    pub api_url: String,
    /// The web-app origin the browser opens.
    pub app_url: String,
    pub egress: crate::egress::EgressConfig,
    /// Someone is at a terminal to answer the picker.
    pub interactive: bool,
    /// `--no-browser`: print the link only.
    pub no_browser: bool,
}

impl<'a> SignInCtx<'a> {
    /// From config, the way every other auth call reads it (WR-03).
    pub fn from_config(output: &'a OutputConfig, interactive: bool, no_browser: bool) -> Self {
        let loaded = crate::core::config::Config::load(None, None, false).ok();
        Self {
            output,
            api_url: loaded
                .as_ref()
                .map(|c| c.cloud.api_url.clone())
                .unwrap_or_else(|| DEFAULT_CLOUD_URL.to_string()),
            app_url: resolve_app_url(),
            egress: loaded
                .map(|c| c.egress)
                .unwrap_or_else(crate::egress::EgressConfig::direct),
            interactive,
            no_browser,
        }
    }

    fn api(&self, path: &str) -> String {
        format!("{}{path}", self.api_url.trim_end_matches('/'))
    }
}

/// The organization this machine is enrolled in: the trust-on-first-use pin
/// in `policy/bundle.meta.json` (C-6 "An enrolled machine"). It survives a
/// logout and a revoked key, and only `uninstall --purge` clears it, so the
/// pin, not the stored credential, decides whether a sign-in may change the
/// organization.
///
/// # Errors
///
/// `ERR_INVALID_CONFIG` when the metadata exists but cannot be read or parsed.
/// Only a missing file means "not enrolled": a pin that is merely unreadable
/// for a moment must never let a sign-in move the machine.
pub fn pinned_organization() -> Result<Option<String>, OlError> {
    pinned_organization_in(&crate::config::openlatch_dir())
}

/// [`pinned_organization`] under `base`, for tests.
pub(crate) fn pinned_organization_in(base: &std::path::Path) -> Result<Option<String>, OlError> {
    match crate::core::policy::store::read_meta(base) {
        Ok(Some(meta)) if !meta.organization_id.is_empty() => Ok(Some(meta.organization_id)),
        Ok(_) => Ok(None),
        Err(e) => Err(OlError::new(
            crate::error::ERR_INVALID_CONFIG,
            format!("Cannot read the organization this machine is enrolled in: {e}"),
        )
        .with_suggestion("Check the permissions of the policy directory, then re-run.")),
    }
}

/// The URL the browser opens (C-2). Every value is percent-encoded; the
/// verifier never appears here, only its challenge.
fn cli_auth_url(app_url: &str, port: u16, hostname: &str, pkce: &Pkce) -> String {
    format!(
        "{}/cli-auth?flow=code&callback=http://127.0.0.1:{port}/callback&hostname={}&state={}\
         &code_challenge={}&code_challenge_method={CHALLENGE_METHOD}",
        app_url.trim_end_matches('/'),
        url_encode(hostname),
        url_encode(&pkce.state),
        url_encode(&pkce.challenge),
    )
}

/// The one sign-in sequence `init`, `auth login` and `auth switch` share (D-7).
///
/// PKCE and `state`, the browser, the organization list, the choice, then:
/// - `Enroll` on a machine pinned to another organization refuses with
///   `ERR_ALREADY_ENROLLED` before any key is minted (C-6);
/// - `Switch` that names the pinned organization returns
///   [`Exchanged::AlreadyIn`] without an exchange (C-8 step 2);
/// - otherwise one exchange, never retried: a retry is a replay, and the
///   platform revokes the key the first attempt minted (C-3).
pub async fn sign_in_with_code(
    ctx: &SignInCtx<'_>,
    intent: Intent,
    org_value: Option<&str>,
    pinned: Option<&str>,
) -> Result<Exchanged, OlError> {
    let pkce = Pkce::new()?;
    let code = browser_code(ctx, &pkce).await?;
    let orgs = list_organizations(ctx, &code, &pkce.verifier).await?;
    let chosen = choose(ctx, org_value, &orgs)?;
    match (intent, pinned) {
        (Intent::Enroll, Some(p)) if chosen.id != p => {
            return Err(org_choice::already_enrolled(
                &org_choice::display_name(p, &orgs),
                &chosen.slug,
            ));
        }
        (Intent::Switch, Some(p)) if chosen.id == p => return Ok(Exchanged::AlreadyIn(chosen)),
        _ => {}
    }
    let previous = match intent {
        Intent::Switch => pinned,
        Intent::Enroll => None,
    };
    exchange(
        ctx,
        &code,
        &pkce.verifier,
        &chosen,
        intent,
        previous,
        org_value,
    )
    .await
}

/// Open the browser on `/cli-auth` and wait for the code on the loopback port.
async fn browser_code(ctx: &SignInCtx<'_>, pkce: &Pkce) -> Result<String, OlError> {
    use tokio::sync::oneshot;
    let output = ctx.output;

    // Bind the callback server on an OS-assigned port (AUTH-05, T-04-02-01).
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
        .await
        .map_err(|e| {
            OlError::new(
                ERR_AUTH_FLOW_FAILED,
                format!("Failed to bind callback server: {e}"),
            )
            .with_suggestion("Check that no firewall rules block localhost connections.")
        })?;
    let port = listener
        .local_addr()
        .map_err(|e| {
            OlError::new(
                ERR_AUTH_FLOW_FAILED,
                format!("Failed to get callback port: {e}"),
            )
        })?
        .port();

    // `hostname` is always sent (C-2): the platform names the key and the
    // audit entry after it, and falls back to the same `unknown-host`.
    let hostname = system_hostname().unwrap_or_else(|| "unknown-host".to_string());
    let auth_url = cli_auth_url(&ctx.app_url, port, &hostname, pkce);

    let browser_opened = !ctx.no_browser && try_open_browser(&auth_url);

    // The link is always shown (D-08). On a rail (`openlatch init`) the
    // instructions belong to the running sign-in stage: shown under its
    // spinner, never wrapped, gone once it closes.
    let rail = crate::cli::ui::is_active();
    if rail {
        crate::cli::ui::progress("Waiting for you to sign in");
        if browser_opened {
            crate::cli::ui::hint("A browser window opened. Sign in there to continue.");
            crate::cli::ui::link("Didn't open? ", &auth_url);
        } else {
            crate::cli::ui::hint("Open this link in your browser to sign in.");
            crate::cli::ui::link("", &auth_url);
        }
    } else {
        if browser_opened {
            output.print_info("Opening browser for authentication...");
        } else {
            output.print_info("Open the following URL in your browser to authenticate:");
        }
        // The link itself is a line the operator must see whatever the flags say:
        // under `--json` or `--quiet` it is the only way to finish the sign-in on
        // a machine where no browser opened. stderr, so stdout stays the document.
        output.print_note(&format!("\n  {auth_url}\n"));
    }

    // Spinner with countdown (D-08, CLI-11: stderr, not stdout). A rail
    // already shows its own spinner for the stage.
    let (cancel_tx, cancel_rx) = oneshot::channel::<()>();
    let spinner_handle = if output.format != OutputFormat::Json && !output.quiet && !rail {
        let total_secs = CALLBACK_TIMEOUT.as_secs();
        Some(tokio::spawn(async move {
            let pb = indicatif::ProgressBar::new_spinner();
            pb.set_draw_target(indicatif::ProgressDrawTarget::stderr());
            pb.enable_steady_tick(Duration::from_millis(100));

            let mut remaining = total_secs;
            let mut cancel_rx = cancel_rx;
            loop {
                let minutes = remaining / 60;
                let seconds = remaining % 60;
                pb.set_message(format!(
                    "Waiting for authentication... ({minutes}:{seconds:02} remaining)"
                ));

                tokio::select! {
                    _ = tokio::time::sleep(Duration::from_secs(1)) => {
                        remaining = remaining.saturating_sub(1);
                    }
                    _ = &mut cancel_rx => {
                        pb.finish_and_clear();
                        break;
                    }
                }
            }
        }))
    } else {
        drop(cancel_rx);
        None
    };

    // The budget covers waiting for a CONNECTION that carries this sign-in's
    // `state`, not handling one: once accepted, a connection is always
    // answered (AUTH-06, T-04-02-04).
    let deadline = tokio::time::Instant::now() + CALLBACK_TIMEOUT;
    let result = wait_for_code(&listener, pkce, deadline, REQUEST_READ_TIMEOUT).await;

    // Cancel the spinner (T-04-02-04: no orphaned tasks) before the late-page
    // grace, so the terminal never shows a countdown at zero.
    let _ = cancel_tx.send(());
    if let Some(handle) = spinner_handle {
        let _ = handle.await;
    }
    if matches!(&result, Err(e) if e.code == ERR_AUTH_TIMEOUT) {
        serve_expired_page(&listener).await;
    }
    result
}

/// `error.code` of the console's error envelope `{"error":{"code",…}}`.
async fn error_code_of(resp: reqwest::Response) -> Option<String> {
    let body: serde_json::Value = resp.json().await.ok()?;
    body.get("error")?.get("code")?.as_str().map(str::to_string)
}

fn cloud_unreachable(e: &reqwest::Error) -> OlError {
    OlError::new(
        ERR_CLOUD_UNREACHABLE,
        format!("Could not reach the OpenLatch platform: {e}"),
    )
    .with_suggestion("Check your network or proxy, then run the command again.")
}

fn sign_in_expired() -> OlError {
    OlError::new(
        ERR_SIGN_IN_EXPIRED,
        "The sign-in expired or was already used",
    )
    .with_suggestion("Run the command again to sign in.")
}

/// A refusal shared by the listing and the exchange (C-3 errors → C-10).
fn api_refusal(status: reqwest::StatusCode, code: Option<&str>, org: Option<&Org>) -> OlError {
    match (status.as_u16(), code) {
        (401, _) => sign_in_expired(),
        (403, Some("no_organization")) => no_organization(),
        (403, Some("FORBIDDEN" | "license_expired")) => {
            let name = org.map_or("The organization", |o| o.name.as_str());
            OlError::new(
                ERR_ORG_UNAVAILABLE,
                format!("{name} is suspended, deleted, or its licence has ended"),
            )
            .with_suggestion("Pick another organization, or ask its admin.")
        }
        (s, code) => OlError::new(
            ERR_AUTH_FLOW_FAILED,
            format!(
                "The platform refused the sign-in (HTTP {s}{})",
                code.map(|c| format!(", {c}")).unwrap_or_default()
            ),
        )
        .with_suggestion("Run the command again. If it keeps failing, update the client."),
    }
}

/// `GET /api/v1/cli-auth/organizations` (C-3). Does not consume the code.
async fn list_organizations(
    ctx: &SignInCtx<'_>,
    code: &str,
    verifier: &str,
) -> Result<Vec<Org>, OlError> {
    let client = crate::egress::build_client(crate::egress::Consumer::Auth, &ctx.egress)?;
    let resp = client
        .get(ctx.api("/api/v1/cli-auth/organizations"))
        .bearer_auth(code)
        .header(VERIFIER_HEADER, verifier)
        .send()
        .await
        .map_err(|e| cloud_unreachable(&e))?;
    let status = resp.status();
    if !status.is_success() {
        let code = error_code_of(resp).await;
        return Err(api_refusal(status, code.as_deref(), None));
    }
    let body: CliAuthOrganizationsResponse = resp.json().await.map_err(|e| {
        OlError::new(
            ERR_AUTH_FLOW_FAILED,
            format!("The platform's organization list could not be read: {e}"),
        )
    })?;
    let orgs: Vec<Org> = body.data.into_iter().map(Org::from).collect();
    if orgs.is_empty() {
        return Err(no_organization());
    }
    Ok(orgs)
}

/// The header carrying the PKCE verifier on the listing (C-3).
const VERIFIER_HEADER: &str = "X-OpenLatch-Code-Verifier";

/// Choose the organization (C-6 "Interactive sign-in"): the named one, the
/// only one, or the picker. Never a default.
fn choose(ctx: &SignInCtx<'_>, org_value: Option<&str>, orgs: &[Org]) -> Result<Org, OlError> {
    if let Some(value) = org_value {
        return org_choice::resolve(value, orgs)
            .cloned()
            .map_err(|e| org_choice::match_error(value, orgs, &e));
    }
    match orgs {
        [] => Err(no_organization()),
        [only] => {
            let line = format!("Organization  {}", only.name);
            if crate::cli::ui::is_active() {
                crate::cli::ui::note(&line);
            } else {
                ctx.output.print_substep(&line);
            }
            Ok(only.clone())
        }
        _ if !ctx.interactive => Err(org_choice::choice_required(orgs)),
        _ => pick(orgs),
    }
}

/// The picker (C-7). Unanswered in any way → `ERR_ORG_NOT_CHOSEN`.
fn pick(orgs: &[Org]) -> Result<Org, OlError> {
    let host = system_hostname().unwrap_or_else(|| "This machine".to_string());
    let line = format!("{host} will report to it and follow its policies.");
    let lines = [line.as_str()];
    let question = crate::cli::ui::SelectList {
        title: "Organization",
        question: "Which organization should this machine join?",
        lines: &lines,
        items: orgs
            .iter()
            .map(|o| (o.name.clone(), o.slug.clone()))
            .collect(),
        timeout: Some(PICKER_BUDGET),
    };
    let outcome =
        crate::cli::ui::select_list(&question).unwrap_or_else(|| ask_list_without_rail(&question));
    match outcome {
        crate::cli::ui::ListOutcome::Answered(i) if i < orgs.len() => Ok(orgs[i].clone()),
        _ => Err(org_choice::not_chosen(orgs)),
    }
}

/// With no rail installed (`auth login`), ask on a plain line prompt on stderr.
fn ask_list_without_rail(question: &crate::cli::ui::SelectList<'_>) -> crate::cli::ui::ListOutcome {
    use crate::cli::ui;
    let caps = ui::Caps::new(ui::Mode::Plain, false, false, 80);
    ui::Rail::new(caps, ui::Out::Term(console::Term::stderr()), None, 0).select_list(question)
}

/// `POST /api/v1/cli-auth/exchange` (C-3). Never retried.
async fn exchange(
    ctx: &SignInCtx<'_>,
    code: &str,
    verifier: &str,
    chosen: &Org,
    intent: Intent,
    previous: Option<&str>,
    org_value: Option<&str>,
) -> Result<Exchanged, OlError> {
    let client = crate::egress::build_client(crate::egress::Consumer::Auth, &ctx.egress)?;
    let body = serde_json::json!({
        "code_verifier": verifier,
        "organization_id": chosen.id,
        // The 32-hex host key, or null on a host with no machine identifier;
        // never the `agent:` fallback, which is not the shape the audit takes.
        "machine_id": crate::daemon::identity::host_id::host_id(),
        "intent": intent.as_str(),
        "previous_organization_id": previous,
    });
    let resp = client
        .post(ctx.api("/api/v1/cli-auth/exchange"))
        .bearer_auth(code)
        .json(&body)
        .send()
        .await
        .map_err(|e| cloud_unreachable(&e))?;
    let status = resp.status();
    if !status.is_success() {
        let error = error_code_of(resp).await;
        if status.as_u16() == 403 && error.as_deref() == Some("not_a_member") {
            // The membership went away between the listing and the exchange.
            // The code is still unconsumed, so the fresh list can be fetched.
            let fresh = list_organizations(ctx, code, verifier)
                .await
                .unwrap_or_default();
            let value = org_value.unwrap_or(&chosen.slug);
            return Err(org_choice::not_found(value, &fresh));
        }
        return Err(api_refusal(status, error.as_deref(), Some(chosen)));
    }
    let minted: CliAuthExchangeResponse = resp.json().await.map_err(|e| {
        OlError::new(
            ERR_AUTH_FLOW_FAILED,
            format!("The platform's answer to the sign-in could not be read: {e}"),
        )
    })?;
    let organization = Org {
        id: minted.organization.id,
        slug: minted
            .organization
            .slug
            .unwrap_or_else(|| chosen.slug.clone()),
        name: minted.organization.name,
    };
    Ok(Exchanged::New {
        key: SecretString::from(minted.key),
        organization,
    })
}

/// What `/users/me` says about the stored credential, against a named
/// organization (C-6 "An enrolled machine").
pub(crate) enum StoredCheck {
    /// The stored key belongs to the named organization.
    Matches(AuthValidation),
    /// The stored key belongs to another organization.
    Differs(AuthValidation),
    /// No stored key, or the platform rejected it: a sign-in decides.
    NoUsableCredential,
}

/// Compare `value` with the STORED credential's organization, with no
/// sign-in. `OPENLATCH_API_KEY` is not consulted: it has its own check.
///
/// # Errors
///
/// `ERR_ORG_UNVERIFIED` when a stored key exists and the platform cannot be
/// reached to read its organization.
pub(crate) async fn check_stored_credential(
    ctx: &SignInCtx<'_>,
    value: &str,
) -> Result<StoredCheck, OlError> {
    let keychain = crate::core::auth::KeyringCredentialStore::new();
    let file_store = make_file_store();
    let Some((key, _)) = crate::core::auth::retrieve_stored(&keychain, &file_store) else {
        return Ok(StoredCheck::NoUsableCredential);
    };
    let v = validate_online_full(key.expose_secret(), &ctx.api_url, &ctx.egress).await;
    if v.rejected {
        return Ok(StoredCheck::NoUsableCredential);
    }
    if !v.online {
        return Err(org_choice::unverified());
    }
    if org_choice::names(value, &v.org_id, v.org_slug.as_deref(), &v.org_name) {
        Ok(StoredCheck::Matches(v))
    } else {
        Ok(StoredCheck::Differs(v))
    }
}

/// Store a freshly minted key and run the post-login nudges.
async fn store_new_key(
    key: &SecretString,
    api_url: &str,
    egress: &crate::egress::EgressConfig,
) -> Result<(), OlError> {
    // Store (CRED-01, T-04-02-03: never log the key). The encrypted file is not
    // a lesser store: it is the one `retrieve_credential` already falls back
    // to, so a credential written there is found again.
    let store = crate::core::auth::KeyringCredentialStore::new();
    let file_store = make_file_store();
    crate::core::auth::store_credential(&store, &file_store, key.clone()).map_err(|e| {
        OlError::new(
            ERR_AUTH_FLOW_FAILED,
            format!("Failed to store API key: {}", e.message),
        )
        .with_suggestion("Try running 'openlatch system auth login' again.")
    })?;

    // Telemetry identity stitching (Phase C): user_db_id from /users/me,
    // persisted, then `$create_alias` before `auth_completed`. Best-effort.
    let validation = validate_online_full(key.expose_secret(), api_url, egress).await;
    if let Some(user_db_id) = validation.user_db_id.as_deref() {
        if let Some(handle) = crate::telemetry::global() {
            let dir = crate::config::openlatch_dir();
            let agent_id = load_agent_id().unwrap_or_else(|| "agt_unknown".into());
            let org_id_opt = (!validation.org_id.is_empty()).then_some(validation.org_id.as_str());
            crate::telemetry::identity::record_auth_success(
                handle, &dir, &agent_id, user_db_id, org_id_opt,
            );
        }
    }

    // Tell a running daemon to clear its cloud-worker auth latch, so a
    // same-key re-login (WR-01) resumes at once. Best-effort.
    notify_daemon_auth_refresh().await;
    Ok(())
}

/// Sign in with the code flow as an enrollment and store the key: the browser
/// path of `init` and of `auth login`.
async fn enroll_and_store(
    ctx: &SignInCtx<'_>,
    org_value: Option<&str>,
    pinned: Option<&str>,
) -> Result<(Org, String), OlError> {
    match sign_in_with_code(ctx, Intent::Enroll, org_value, pinned).await? {
        Exchanged::New { key, organization } => {
            store_new_key(&key, &ctx.api_url, &ctx.egress).await?;
            Ok((organization, mask_api_key(key.expose_secret())))
        }
        // An enrollment never answers AlreadyIn; treat it as "already here".
        Exchanged::AlreadyIn(organization) => Ok((organization, String::new())),
    }
}

/// The telemetry stage a failed sign-in is charted under (no error text).
fn auth_failure_stage(code: &str) -> &'static str {
    match code {
        "OL-1605" => "timeout",
        "OL-1606" => "callback",
        crate::error::ERR_ORG_CHOICE_REQUIRED
        | crate::error::ERR_ORG_NOT_CHOSEN
        | crate::error::ERR_ORG_NOT_FOUND
        | crate::error::ERR_ORG_AMBIGUOUS
        | crate::error::ERR_ORG_KEY_MISMATCH
        | crate::error::ERR_ORG_UNVERIFIED
        | crate::error::ERR_ALREADY_ENROLLED
        | crate::error::ERR_NO_ORGANIZATION
        | crate::error::ERR_ORG_UNAVAILABLE => "org",
        _ => "other",
    }
}

/// Run `f` and chart its outcome as `auth_completed` / `auth_failed`.
fn with_auth_telemetry<T>(f: impl FnOnce() -> Result<T, OlError>) -> Result<T, OlError> {
    let started = std::time::Instant::now();
    let result = f();
    let duration_ms = started.elapsed().as_millis().min(u128::from(u64::MAX)) as u64;
    match &result {
        Ok(_) => crate::telemetry::capture_global(crate::telemetry::Event::auth_completed(
            "browser",
            duration_ms,
        )),
        Err(e) => crate::telemetry::capture_global(crate::telemetry::Event::auth_failed(
            e.code,
            auth_failure_stage(e.code),
        )),
    }
    result
}

fn runtime() -> Result<tokio::runtime::Runtime, OlError> {
    tokio::runtime::Runtime::new().map_err(|e| {
        OlError::new(
            ERR_AUTH_FLOW_FAILED,
            format!("Failed to create async runtime: {e}"),
        )
    })
}

/// The browser path of `openlatch init`: sign in with the code flow, choose
/// the organization, store the key. Returns the organization.
///
/// Runs its own runtime, like [`run_login`]: `init` calls it from sync code.
/// `ctx` carries the platform this run talks to, which on a re-init with
/// `--api-url` is not yet the one in config.
pub(crate) fn enroll_for_init(
    ctx: &SignInCtx<'_>,
    org_value: Option<&str>,
    pinned: Option<&str>,
) -> Result<Org, OlError> {
    let rt = runtime()?;
    let org = with_auth_telemetry(|| rt.block_on(enroll_and_store(ctx, org_value, pinned)))
        .map(|(org, _)| org)?;
    ctx.output
        .print_step(&format!("Authenticated (org: {})", org.name));
    Ok(org)
}

/// Run `openlatch system auth login`.
pub fn run_login(args: &AuthLoginArgs, output: &OutputConfig) -> Result<(), OlError> {
    let rt = runtime()?;
    with_auth_telemetry(|| rt.block_on(run_login_async(args, output)))
}

async fn run_login_async(args: &AuthLoginArgs, output: &OutputConfig) -> Result<(), OlError> {
    let org_value = org_choice::requested(args.org.as_deref());
    let pinned = pinned_organization()?;
    let ctx = SignInCtx::from_config(
        output,
        crate::cli::prompt::interactive(output, false),
        args.no_browser,
    );

    // An enrolled machine never changes organization here (C-6, R-7). With a
    // name given and a valid stored key, the comparison needs no sign-in: the
    // same organization keeps the stored key, another one is refused.
    let mut reused = None;
    if let (Some(value), Some(pinned_id)) = (org_value.as_deref(), pinned.as_deref()) {
        match check_stored_credential(&ctx, value).await? {
            StoredCheck::Differs(v) => {
                let current = if v.org_name.is_empty() {
                    pinned_id.to_string()
                } else {
                    v.org_name
                };
                return Err(org_choice::already_enrolled(&current, value));
            }
            StoredCheck::Matches(v) => reused = Some(v),
            StoredCheck::NoUsableCredential => {}
        }
    }

    let (organization, masked) = match reused {
        Some(v) => {
            let keychain = crate::core::auth::KeyringCredentialStore::new();
            let file_store = make_file_store();
            let masked = crate::core::auth::retrieve_stored(&keychain, &file_store)
                .map(|(key, _)| mask_api_key(key.expose_secret()))
                .unwrap_or_default();
            let slug = v.org_slug.clone().unwrap_or_default();
            (
                Org {
                    id: v.org_id,
                    slug,
                    name: v.org_name,
                },
                masked,
            )
        }
        None => enroll_and_store(&ctx, org_value.as_deref(), pinned.as_deref()).await?,
    };

    // Success output (D-10, T-04-02-03: the masked key only, never the raw one).
    let backend = keychain_backend_name();
    if output.format == OutputFormat::Json {
        let json = serde_json::json!({
            "authenticated": true,
            "org_name": organization.name,
            "org_id": organization.id,
            "key_prefix": masked,
            "keychain_backend": backend,
        });
        output.print_json(&json);
    } else {
        output.print_step("Authenticated successfully");
        output.print_substep(&format!("Org: {} ({})", organization.name, organization.id));
        output.print_substep(&format!("API key: {masked}"));
        output.print_substep(&format!("Stored in: {backend}"));
    }

    Ok(())
}

// ---------------------------------------------------------------------------
// Logout
// ---------------------------------------------------------------------------

/// Run `openlatch system auth logout`.
pub fn run_logout(output: &OutputConfig) -> Result<(), OlError> {
    runtime()?.block_on(run_logout_async(output))
}

/// What a logout did.
pub(crate) struct LogoutReport {
    pub server_revoked: bool,
    pub cleared: Vec<crate::core::auth::Tier>,
    /// A tier whose delete failed and that still holds a credential.
    pub remaining: Option<crate::core::auth::Tier>,
}

/// Revoke the STORED key and delete it from both tiers (C-9, D-14).
///
/// The key revoked is read from the keychain, then the file, directly; never
/// through [`crate::core::auth::retrieve_credential`], which returns
/// `OPENLATCH_API_KEY` first. A key from the environment is the operator's.
pub(crate) async fn logout_stores(
    primary: &dyn crate::core::auth::CredentialStore,
    fallback: &dyn crate::core::auth::CredentialStore,
    api_url: &str,
    egress: &crate::egress::EgressConfig,
) -> LogoutReport {
    // Server-side revocation first, fail-open (D-16, T-04-02-07).
    let server_revoked = match crate::core::auth::retrieve_stored(primary, fallback) {
        Some((key, _)) => attempt_server_revocation(key.expose_secret(), api_url, egress).await,
        None => false,
    };
    // Local cleanup always runs, whatever the revocation did.
    let cleared = crate::core::auth::delete_all_credentials(primary, fallback);
    primary.invalidate();
    let remaining = crate::core::auth::retrieve_stored(primary, fallback).map(|(_, tier)| tier);
    LogoutReport {
        server_revoked,
        cleared,
        remaining,
    }
}

async fn run_logout_async(output: &OutputConfig) -> Result<(), OlError> {
    // api_url from config for server-side revocation (WR-03: respect staging).
    let loaded = crate::core::config::Config::load(None, None, false).ok();
    let api_url = loaded
        .as_ref()
        .map(|c| c.cloud.api_url.clone())
        .unwrap_or_else(|| DEFAULT_CLOUD_URL.to_string());
    let egress = loaded
        .as_ref()
        .map(|c| c.egress.clone())
        .unwrap_or_else(crate::egress::EgressConfig::direct);

    let keychain = crate::core::auth::KeyringCredentialStore::new();
    let file_store = make_file_store();
    let report = logout_stores(&keychain, &file_store, &api_url, &egress).await;
    if let Some(tier) = report.remaining {
        // A credential is still there: this is not a logout, whatever else ran.
        let (code, place) = match tier {
            crate::core::auth::Tier::Keychain => {
                (crate::error::ERR_KEYCHAIN_PERMISSION, "the OS keychain")
            }
            crate::core::auth::Tier::File => (
                crate::error::ERR_FILE_FALLBACK_ERROR,
                "the encrypted credentials file",
            ),
        };
        return Err(OlError::new(
            code,
            format!("Could not delete the stored credential from {place}; it is still there"),
        )
        .with_suggestion(
            "Check the permissions of the credential store, then run the command again.",
        ));
    }

    crate::telemetry::identity::record_logout(
        crate::telemetry::global(),
        &crate::config::openlatch_dir(),
    );
    notify_daemon_auth_refresh().await;

    let backend = keychain_backend_name();
    let cleared: Vec<&str> = report.cleared.iter().map(|t| t.as_str()).collect();
    if output.format == OutputFormat::Json {
        let json = serde_json::json!({
            "logged_out": true,
            "server_revoked": report.server_revoked,
            "backend": backend,
            "credentials_cleared": cleared,
        });
        output.print_json(&json);
    } else {
        if report.server_revoked {
            output.print_step("API key revoked on server");
        } else {
            output.print_step("Server revocation failed — continuing with local cleanup");
        }
        let place = |t: &crate::core::auth::Tier| match t {
            crate::core::auth::Tier::Keychain => backend.to_string(),
            crate::core::auth::Tier::File => "the encrypted credentials file".to_string(),
        };
        if report.cleared.is_empty() {
            output.print_substep("No stored credentials to clear");
        } else {
            let places: Vec<String> = report.cleared.iter().map(place).collect();
            output.print_substep(&format!(
                "Credentials cleared from {}",
                places.join(" and ")
            ));
        }
        output.print_substep("Cloud forwarding is now disabled");
        output.print_info("\nRun 'openlatch system auth login' to re-authenticate.");
    }

    Ok(())
}

// ---------------------------------------------------------------------------
// Status
// ---------------------------------------------------------------------------

/// Run `openlatch system auth status`.
pub fn run_status(output: &OutputConfig) -> Result<(), OlError> {
    let rt = tokio::runtime::Runtime::new().map_err(|e| {
        OlError::new(
            ERR_AUTH_FLOW_FAILED,
            format!("Failed to create async runtime: {e}"),
        )
    })?;
    rt.block_on(run_status_async(output))
}

/// `, N event(s) waiting in the outbox` when anything is spooled, else empty.
///
/// Read from the file rather than the daemon: this runs on the "no credential"
/// path, where the daemon may not be up and the number is the whole point.
fn pending_outbox_summary() -> String {
    let path = crate::config::openlatch_dir().join("outbox.jsonl");
    let Ok(content) = std::fs::read_to_string(&path) else {
        return String::new();
    };
    let pending = content.lines().filter(|l| !l.trim().is_empty()).count();
    if pending == 0 {
        String::new()
    } else {
        format!(", {pending} event(s) waiting in the outbox")
    }
}

async fn run_status_async(output: &OutputConfig) -> Result<(), OlError> {
    use secrecy::ExposeSecret;

    let store = crate::core::auth::KeyringCredentialStore::new();
    let file_store = make_file_store();

    // Load api_url from config (WR-03: respect staging/custom environments)
    let loaded = crate::core::config::Config::load(None, None, false).ok();
    let api_url = loaded
        .as_ref()
        .map(|c| c.cloud.api_url.clone())
        .unwrap_or_else(|| DEFAULT_CLOUD_URL.to_string());
    let egress = loaded
        .as_ref()
        .map(|c| c.egress.clone())
        .unwrap_or_else(crate::egress::EgressConfig::direct);

    let key_result = crate::core::auth::retrieve_credential(
        &store as &dyn crate::core::auth::CredentialStore,
        &file_store as &dyn crate::core::auth::CredentialStore,
    );

    match key_result {
        Err(_) => {
            // No credential found in any store
            if output.format == OutputFormat::Json {
                output.print_json(&build_auth_status_json(false, "", "", "", "", false));
            } else {
                output.print_info("Not authenticated");
                // What is actually lost, not just what is missing. Without a
                // credential the daemon keeps capturing and the events pile up
                // in the outbox reaching nobody — a state that looks fine from
                // every other angle.
                output.print_info(&format!(
                    "  Cloud forwarding is paused{}. Run `openlatch system auth login` to resume it.",
                    pending_outbox_summary()
                ));
            }
            // No credential is a capability the host is missing, not a
            // successful report about it.
            crate::cli::report::record_exit_code(1);
        }
        Ok(key) => {
            let key_str = key.expose_secret().to_string();
            let masked = mask_api_key(&key_str);
            let backend = keychain_backend_name();

            // Attempt online validation (D-17 from Phase 3, AUTH-03)
            let (online, org_name, org_id) = validate_online(&key_str, &api_url, &egress).await;

            if output.format == OutputFormat::Json {
                output.print_json(&build_auth_status_json(
                    true, &org_name, &org_id, &masked, backend, online,
                ));
            } else {
                output.print_step(if online {
                    "Authenticated (online)"
                } else {
                    "Authenticated (offline — could not reach cloud)"
                });
                if !online {
                    // Offline is not failure — the credential is stored and the
                    // outbox holds — but it is not the working state either.
                    crate::cli::report::record_exit_code(crate::cli::report::EXIT_DEGRADED);
                }
                output.print_substep(&format!("API key: {masked}"));
                output.print_substep(&format!("Keychain: {backend}"));
                if !org_name.is_empty() {
                    output.print_substep(&format!("Org: {org_name} ({org_id})"));
                }
            }
        }
    }

    Ok(())
}

// ---------------------------------------------------------------------------
// JSON builders (tested directly)
// ---------------------------------------------------------------------------

/// Build the JSON object for `auth status` output.
pub fn build_auth_status_json(
    authenticated: bool,
    org_name: &str,
    org_id: &str,
    key_prefix: &str,
    keychain_backend: &str,
    online: bool,
) -> serde_json::Value {
    if !authenticated {
        return serde_json::json!({ "authenticated": false });
    }
    serde_json::json!({
        "authenticated": true,
        "org_name": org_name,
        "org_id": org_id,
        "key_prefix": key_prefix,
        "keychain_backend": keychain_backend,
        "online": online,
    })
}

// ---------------------------------------------------------------------------
// Internal helpers
// ---------------------------------------------------------------------------

/// Create a FileCredentialStore for the fallback chain.
pub(crate) fn make_file_store() -> crate::core::auth::FileCredentialStore {
    let path = crate::core::config::openlatch_dir().join("credentials.enc");
    // Load agent_id from config for key derivation; fall back to empty string
    // (store.retrieve() will error on mismatched key, which is handled gracefully)
    let agent_id = load_agent_id().unwrap_or_default();
    crate::core::auth::FileCredentialStore::new(path, agent_id)
}

fn load_agent_id() -> Option<String> {
    // Config::load requires cli args — use None/false for all (config-file only load)
    let config = crate::core::config::Config::load(None, None, false).ok()?;
    config.agent_id
}

/// Best-effort POST to the local daemon's `/admin/auth/refresh` endpoint.
/// Tells a running daemon to clear its cloud-worker `auth_error` latch
/// after a successful login, so a same-key re-login (WR-01) resumes POSTs
/// without waiting for the 60s credential-poll cycle.
///
/// Silent on every failure mode (no daemon, no token, network error, non-2xx
/// response) — this is purely a latency optimisation, not a correctness
/// requirement. The worker will pick up the new key on its own anyway.
async fn notify_daemon_auth_refresh() {
    let cfg = match crate::core::config::Config::load(None, None, false) {
        Ok(c) => c,
        Err(_) => return,
    };
    let port = cfg.port;
    let token_path = crate::core::config::openlatch_dir().join("daemon.token");
    let Ok(token) = std::fs::read_to_string(&token_path) else {
        return;
    };
    let token = token.trim().to_string();
    if token.is_empty() {
        return;
    }
    let client = match crate::egress::client_builder()
        .timeout(Duration::from_secs(2))
        .use_rustls_tls()
        .build()
    {
        Ok(c) => c,
        Err(_) => return,
    };
    let url = format!("http://127.0.0.1:{port}/admin/auth/refresh");
    let _ = client.post(&url).bearer_auth(&token).send().await;
}

/// Attempt to revoke the API key server-side.
///
/// Sends `DELETE api/v1/api-keys/self` with Bearer auth. Returns `true` on 2xx,
/// `false` on any error (network or HTTP). Fail-open per D-16.
///
/// `api_url` is read from config so staging/custom environments are respected (WR-03).
pub(crate) async fn attempt_server_revocation(
    api_key: &str,
    api_url: &str,
    egress: &crate::egress::EgressConfig,
) -> bool {
    let client = match crate::egress::build_client(crate::egress::Consumer::Auth, egress) {
        Ok(c) => c,
        Err(_) => return false,
    };

    let base = api_url.trim_end_matches('/');
    let result = client
        .delete(format!("{base}/api/v1/api-keys/self"))
        .bearer_auth(api_key)
        .send()
        .await;

    match result {
        Ok(resp) => resp.status().is_success(),
        Err(_) => false,
    }
}

/// Derive the web-app origin from an API URL by stripping a trailing `/api`.
///
/// Pure function so it can be unit-tested without touching config/env.
fn derive_app_url_from_api(api_url: &str) -> String {
    let trimmed = api_url.trim_end_matches('/');
    trimmed.strip_suffix("/api").unwrap_or(trimmed).to_string()
}

/// Resolve the web-app origin used for the browser auth step.
///
/// Precedence:
///   1. `OPENLATCH_APP_URL` — explicit override (production uses this when
///      the web app and the API live on different hosts).
///   2. `cloud.api_url` from config with a trailing `/api` stripped —
///      `OPENLATCH_API_URL=http://localhost:5173` becomes
///      `http://localhost:5173` so dev setups only need one env var.
///   3. `https://app.openlatch.ai` default.
///
/// Never fails: any config-load error collapses to the default.
pub(crate) fn resolve_app_url() -> String {
    if let Ok(val) = std::env::var("OPENLATCH_APP_URL") {
        if !val.is_empty() {
            return val;
        }
    }
    let api_url = crate::core::config::Config::load(None, None, false)
        .ok()
        .map(|c| c.cloud.api_url)
        .unwrap_or_else(|| DEFAULT_CLOUD_URL.to_string());
    derive_app_url_from_api(&api_url)
}

/// [`resolve_app_url`] for a run that talks to `api_url`, which may not be
/// the one in config yet (`init --api-url`). `OPENLATCH_APP_URL` still wins.
pub(crate) fn resolve_app_url_for(api_url: &str) -> String {
    match std::env::var("OPENLATCH_APP_URL") {
        Ok(val) if !val.is_empty() => val,
        _ => derive_app_url_from_api(api_url),
    }
}

/// Validate credential online via `GET /api/v1/users/me`.
///
/// Returns `(online, org_name, org_id)`. On any failure, returns `(false, "", "")`.
/// The caller falls back to cached config values when offline.
/// (D-21: parse as serde_json::Value — placeholder schema for M2)
///
/// `api_url` is read from config so staging/custom environments are respected (WR-03).
pub async fn validate_online(
    api_key: &str,
    api_url: &str,
    egress: &crate::egress::EgressConfig,
) -> (bool, String, String) {
    let v = validate_online_full(api_key, api_url, egress).await;
    (v.online, v.org_name, v.org_id)
}

/// Extended return shape for `validate_online` — adds `user_db_id` for
/// PostHog identity stitching (telemetry Phase C). Callers that don't need
/// the alias path can keep using `validate_online`.
#[derive(Debug, Default, Clone)]
pub struct AuthValidation {
    pub online: bool,
    /// Server explicitly rejected the credential (401/403). Distinct from
    /// `online=false` caused by network/transient errors, which should
    /// fail-open rather than trigger re-authentication.
    pub rejected: bool,
    pub org_name: String,
    pub org_id: String,
    /// The organization's slug, from platforms that send it (PLT-7 C-3).
    pub org_slug: Option<String>,
    pub user_db_id: Option<String>,
}

pub async fn validate_online_full(
    api_key: &str,
    api_url: &str,
    egress: &crate::egress::EgressConfig,
) -> AuthValidation {
    let client = match crate::egress::build_client(crate::egress::Consumer::Auth, egress) {
        Ok(c) => c,
        Err(_) => return AuthValidation::default(),
    };

    let base = api_url.trim_end_matches('/');
    let result = client
        .get(format!("{base}/api/v1/users/me"))
        .bearer_auth(api_key)
        .send()
        .await;

    match result {
        Ok(resp) if resp.status().is_success() => {
            // TODO: Switch to generated AuthMeResponse type when schema stabilizes (D-21)
            match resp.json::<serde_json::Value>().await {
                Ok(body) => parse_me_response_body(&body),
                Err(_) => AuthValidation {
                    online: true,
                    ..Default::default()
                },
            }
        }
        Ok(resp)
            if resp.status() == reqwest::StatusCode::UNAUTHORIZED
                || resp.status() == reqwest::StatusCode::FORBIDDEN =>
        {
            // Valid credential exists locally but server rejects it
            AuthValidation {
                rejected: true,
                ..Default::default()
            }
        }
        _ => {
            // Network error or unexpected status — offline mode
            AuthValidation::default()
        }
    }
}

/// Extract org/user identity fields from a successful `/api/v1/users/me` body.
///
/// Reads the canonical platform shape: `organization_id`,
/// `organization_name`, `user_db_id` (with `id` as its schema-documented
/// mirror). Pure function — unit-testable without HTTP.
fn parse_me_response_body(body: &serde_json::Value) -> AuthValidation {
    let org_name = body
        .get("organization_name")
        .and_then(|v| v.as_str())
        .unwrap_or("")
        .to_string();
    let org_id = body
        .get("organization_id")
        .and_then(|v| v.as_str())
        .unwrap_or("")
        .to_string();
    let org_slug = body
        .get("organization_slug")
        .and_then(|v| v.as_str())
        .filter(|s| !s.is_empty())
        .map(|s| s.to_string());
    let user_db_id = body
        .get("user_db_id")
        .or_else(|| body.get("id"))
        .and_then(|v| v.as_str())
        .filter(|s| !s.is_empty())
        .map(|s| s.to_string());
    AuthValidation {
        online: true,
        rejected: false,
        org_name,
        org_id,
        org_slug,
        user_db_id,
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    // --- try_open_browser ---

    #[cfg(target_os = "linux")]
    #[test]
    fn test_try_open_browser_headless_linux_returns_false() {
        // NOTE: This test sets/removes env vars. Run isolated (cargo test -- --test-threads=1)
        // to avoid races with other tests that may read DISPLAY/WAYLAND_DISPLAY.
        let display_orig = std::env::var("DISPLAY").ok();
        let wayland_orig = std::env::var("WAYLAND_DISPLAY").ok();
        unsafe {
            std::env::remove_var("DISPLAY");
            std::env::remove_var("WAYLAND_DISPLAY");
        }

        let result = try_open_browser("https://example.com");

        // Restore original values
        unsafe {
            match display_orig {
                Some(v) => std::env::set_var("DISPLAY", v),
                None => std::env::remove_var("DISPLAY"),
            }
            match wayland_orig {
                Some(v) => std::env::set_var("WAYLAND_DISPLAY", v),
                None => std::env::remove_var("WAYLAND_DISPLAY"),
            }
        }

        assert!(
            !result,
            "Expected false on headless Linux (no DISPLAY/WAYLAND_DISPLAY)"
        );
    }

    // --- derive_app_url_from_api ---

    #[test]
    fn test_derive_app_url_strips_trailing_api_suffix() {
        assert_eq!(
            derive_app_url_from_api("https://app.openlatch.ai/api"),
            "https://app.openlatch.ai"
        );
    }

    #[test]
    fn test_derive_app_url_strips_trailing_slash_before_api() {
        assert_eq!(
            derive_app_url_from_api("https://app.openlatch.ai/api/"),
            "https://app.openlatch.ai"
        );
    }

    #[test]
    fn test_derive_app_url_passes_through_bare_origin() {
        // Dev setup: Vite serves both app and API under the same origin with no /api path
        assert_eq!(
            derive_app_url_from_api("http://localhost:5173"),
            "http://localhost:5173"
        );
    }

    #[test]
    fn test_derive_app_url_passes_through_bare_origin_with_trailing_slash() {
        assert_eq!(
            derive_app_url_from_api("http://localhost:5173/"),
            "http://localhost:5173"
        );
    }

    #[test]
    fn test_derive_app_url_does_not_strip_mid_path_api_segment() {
        // Only trailing `/api` is stripped — arbitrary paths are preserved
        assert_eq!(
            derive_app_url_from_api("https://example.com/api/v2"),
            "https://example.com/api/v2"
        );
    }

    // --- url_decode ---

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

    #[test]
    fn test_url_decode_plus_becomes_space() {
        assert_eq!(url_decode("Acme+Corp"), "Acme Corp");
    }

    #[test]
    fn test_url_decode_percent_encoded_space() {
        assert_eq!(url_decode("Acme%20Corp"), "Acme Corp");
    }

    #[test]
    fn test_url_decode_mixed_encoding() {
        assert_eq!(url_decode("Acme%20Corp+Ltd"), "Acme Corp Ltd");
    }

    #[test]
    fn test_url_decode_invalid_percent_sequence_passes_through() {
        // %ZZ is not valid hex — should pass through verbatim
        assert_eq!(url_decode("%ZZ"), "%ZZ");
    }

    // --- url_encode ---

    #[test]
    fn test_url_encode_alphanumeric_unchanged() {
        assert_eq!(url_encode("devbox-01"), "devbox-01");
    }

    #[test]
    fn test_url_encode_space_becomes_percent_20() {
        assert_eq!(url_encode("Acme Corp"), "Acme%20Corp");
    }

    #[test]
    fn test_url_encode_apostrophe_encoded() {
        // macOS default hostname style: "Alice's MacBook"
        assert_eq!(url_encode("Alice's Mac"), "Alice%27s%20Mac");
    }

    #[test]
    fn test_url_encode_unreserved_chars_passthrough() {
        // RFC 3986 unreserved: ALPHA / DIGIT / "-" / "." / "_" / "~"
        assert_eq!(url_encode("a-b.c_d~e"), "a-b.c_d~e");
    }

    #[test]
    fn test_url_encode_non_ascii_utf8() {
        // UTF-8 multibyte must be encoded byte-by-byte (valid for URL query values)
        assert_eq!(url_encode("café"), "caf%C3%A9");
    }

    #[test]
    fn test_url_encode_roundtrips_with_url_decode() {
        let input = "Alice's MacBook Pro";
        assert_eq!(url_decode(&url_encode(input)), input);
    }

    // --- system_hostname ---

    #[test]
    fn test_system_hostname_is_non_empty_when_available() {
        // On any real CI or dev machine the OS call succeeds. We don't assert a
        // specific value (it differs per host) — only that the helper never
        // returns `Some("")` (empty-string guard in the implementation).
        if let Some(h) = system_hostname() {
            assert!(!h.is_empty(), "system_hostname must not return Some(\"\")");
            assert_eq!(
                h.trim(),
                h,
                "system_hostname must not return padded whitespace"
            );
        }
    }

    // --- loopback callback (PLT-7 C-2, D-4) ---

    fn pkce() -> Pkce {
        Pkce::new().expect("CSPRNG available")
    }

    fn get(target: &str) -> Vec<u8> {
        format!("GET {target} HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n").into_bytes()
    }

    #[test]
    fn callback_query_reads_code_state_and_error() {
        let q = parse_callback_query("code=olc_eu-west-1_abc&state=s%2Dx&error=&other=1");
        assert_eq!(q.code.as_deref(), Some("olc_eu-west-1_abc"));
        assert_eq!(q.state.as_deref(), Some("s-x"));
        assert_eq!(q.error, None, "an empty value is absent");
        assert!(parse_callback_query("") == CallbackQuery::default());
    }

    #[test]
    fn callback_with_this_state_and_a_code_ends_the_wait() {
        let p = pkce();
        let raw = get(&format!("/callback?code=olc_c1&state={}", p.state));
        assert_eq!(
            classify_callback(&raw, &p),
            CallbackDecision::Code("olc_c1".into())
        );
    }

    #[test]
    fn callback_with_this_state_and_an_error_ends_the_sign_in() {
        let p = pkce();
        let raw = get(&format!(
            "/callback?error=no_organization&state={}",
            p.state
        ));
        assert_eq!(
            classify_callback(&raw, &p),
            CallbackDecision::Refused("no_organization".into())
        );
        assert_eq!(
            callback_refusal("no_organization").code,
            ERR_NO_ORGANIZATION
        );
        assert_eq!(
            callback_refusal("too_many_codes").code,
            ERR_SIGN_IN_THROTTLED
        );
        assert_eq!(callback_refusal("something_new").code, ERR_AUTH_FLOW_FAILED);
    }

    #[test]
    fn callback_rejections_are_answered_and_ignored() {
        let p = pkce();
        let wrong = format!("/callback?code=olc_c1&state={}x", p.state);
        let cases: Vec<(&str, Vec<u8>, Reply)> = vec![
            (
                "non-GET",
                format!("POST /callback?state={} HTTP/1.1\r\n\r\n", p.state).into_bytes(),
                Reply::MethodNotAllowed,
            ),
            ("favicon", get("/favicon.ico"), Reply::NotFound),
            (
                "another path with the right state",
                get(&format!("/other?code=olc_c1&state={}", p.state)),
                Reply::NotFound,
            ),
            ("no query", get("/callback"), Reply::BadRequest),
            (
                "missing state",
                get("/callback?code=olc_c1"),
                Reply::BadRequest,
            ),
            ("foreign state", get(&wrong), Reply::BadRequest),
            (
                "an old client's key callback",
                get("/callback?key=openlatch_k&org_id=o1"),
                Reply::BadRequest,
            ),
            (
                "the right state and nothing else",
                get(&format!("/callback?state={}", p.state)),
                Reply::BadRequest,
            ),
        ];
        for (label, raw, want) in cases {
            assert_eq!(
                classify_callback(&raw, &p),
                CallbackDecision::Ignored(want),
                "{label}"
            );
            // Whatever the status, the browser gets a rendered page.
            assert!(render_page(want.outcome()).contains("<h1"), "{label}");
        }
        assert_eq!(Reply::NotFound.status(), "404 Not Found");
        assert_eq!(Reply::BadRequest.status(), "400 Bad Request");
    }

    /// Send `raw` to `addr` and return the status line of the answer.
    async fn send(addr: std::net::SocketAddr, raw: Vec<u8>) -> String {
        use tokio::io::AsyncWriteExt;
        let mut s = tokio::net::TcpStream::connect(addr).await.unwrap();
        s.write_all(&raw).await.unwrap();
        let mut buf = Vec::new();
        let _ = s.read_to_end(&mut buf).await;
        String::from_utf8_lossy(&buf)
            .lines()
            .next()
            .unwrap_or("")
            .to_string()
    }

    #[tokio::test]
    async fn callback_listener_keeps_waiting_past_strays_and_foreign_state() {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        let p = pkce();
        let state = p.state.clone();

        let client = tokio::spawn(async move {
            let favicon = send(addr, get("/favicon.ico")).await;
            let foreign = send(addr, get("/callback?code=olc_bad&state=nope")).await;
            let missing = send(addr, get("/callback?code=olc_bad")).await;
            let good = send(addr, get(&format!("/callback?code=olc_good&state={state}"))).await;
            (favicon, foreign, missing, good)
        });

        let deadline = tokio::time::Instant::now() + Duration::from_secs(10);
        let code = wait_for_code(&listener, &p, deadline, Duration::from_secs(2))
            .await
            .expect("the callback with this sign-in's state is accepted");
        assert_eq!(code, "olc_good");
        let (favicon, foreign, missing, good) = client.await.unwrap();
        assert_eq!(favicon, "HTTP/1.1 404 Not Found");
        assert_eq!(foreign, "HTTP/1.1 400 Bad Request");
        assert_eq!(missing, "HTTP/1.1 400 Bad Request");
        assert_eq!(good, "HTTP/1.1 200 OK");
    }

    #[tokio::test]
    async fn callback_listener_ends_on_a_refusal_with_its_error() {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        let p = pkce();
        let state = p.state.clone();
        let client = tokio::spawn(async move {
            send(
                addr,
                get(&format!("/callback?error=too_many_codes&state={state}")),
            )
            .await
        });
        let deadline = tokio::time::Instant::now() + Duration::from_secs(10);
        let err = wait_for_code(&listener, &p, deadline, Duration::from_secs(2))
            .await
            .expect_err("a refusal ends the sign-in");
        assert_eq!(err.code, ERR_SIGN_IN_THROTTLED);
        assert_eq!(client.await.unwrap(), "HTTP/1.1 200 OK");
    }

    #[tokio::test]
    async fn callback_listener_survives_a_peer_that_never_speaks() {
        // A preconnect or an idle `nc` used to consume the one connection the
        // listener accepted. Now it is answered and the wait goes on.
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        let p = pkce();
        let state = p.state.clone();
        let client = tokio::spawn(async move {
            let silent = tokio::net::TcpStream::connect(addr).await.unwrap();
            tokio::time::sleep(Duration::from_millis(300)).await;
            drop(silent);
            send(addr, get(&format!("/callback?code=olc_ok&state={state}"))).await
        });
        let deadline = tokio::time::Instant::now() + Duration::from_secs(10);
        let code = wait_for_code(&listener, &p, deadline, Duration::from_millis(100))
            .await
            .expect("a silent peer does not abort the sign-in");
        assert_eq!(code, "olc_ok");
        let _ = client.await;
    }

    #[tokio::test]
    async fn callback_listener_times_out_at_the_deadline() {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let deadline = tokio::time::Instant::now() + Duration::from_millis(50);
        let err = wait_for_code(&listener, &pkce(), deadline, Duration::from_millis(50))
            .await
            .expect_err("nobody came");
        assert_eq!(err.code, ERR_AUTH_TIMEOUT);
    }

    #[test]
    fn callback_url_carries_the_challenge_never_the_verifier() {
        let p = pkce();
        let url = cli_auth_url("https://app.example.test/", 4321, "Alice's Mac", &p);
        assert!(url.starts_with("https://app.example.test/cli-auth?flow=code&"));
        assert!(url.contains("&callback=http://127.0.0.1:4321/callback&"));
        assert!(url.contains("&hostname=Alice%27s%20Mac&"));
        assert!(url.contains(&format!("&state={}&", p.state)));
        assert!(url.contains(&format!("&code_challenge={}&", p.challenge)));
        assert!(url.ends_with("&code_challenge_method=S256"));
        assert!(!url.contains(&p.verifier));
    }

    // --- mask_api_key ---

    #[test]
    fn test_mask_api_key_shows_prefix_and_suffix() {
        let masked = mask_api_key("ol_org_abcdef1234567890");
        assert_eq!(masked, "ol_org_...7890");
    }

    #[test]
    fn test_mask_api_key_short_key_returned_as_is() {
        // Keys 11 chars or shorter are returned whole
        let masked = mask_api_key("short");
        assert_eq!(masked, "short");
    }

    // --- render_page ---

    #[test]
    fn test_render_page_connected_tells_the_user_to_close_the_tab() {
        let html = render_page(Outcome::Connected);
        assert!(
            html.contains("You can close this tab"),
            "Connected page must tell the user to close the tab; got: {html}"
        );
    }

    #[test]
    fn test_render_page_every_outcome_has_its_own_copy() {
        for (outcome, heading) in [
            (Outcome::Connected, "Connected."),
            (Outcome::Expired, "This link expired."),
            (Outcome::Malformed, "This page opens from the CLI."),
            (Outcome::Refused, "Sign-in stopped."),
        ] {
            let html = render_page(outcome);
            assert!(
                html.contains(heading),
                "{outcome:?} must render its own heading {heading:?}; got: {html}"
            );
        }
    }

    #[test]
    fn test_render_page_marks_failures_as_settled() {
        // The arrival choreography is the success signal. A page for something
        // that did not arrive must not animate as though it did.
        assert!(render_page(Outcome::Connected).contains(r#"<body class="connected">"#));
        for outcome in [Outcome::Expired, Outcome::Malformed, Outcome::Refused] {
            assert!(
                render_page(outcome).contains(r#"<body class="settled">"#),
                "{outcome:?} must render settled"
            );
        }
    }

    #[test]
    fn test_render_page_makes_no_external_requests() {
        // The client targets air-gapped and proxied hosts. A webfont, a CDN
        // script or a remote logo would leave this page visibly broken there,
        // and nothing else in the build enforces it.
        for outcome in [
            Outcome::Connected,
            Outcome::Expired,
            Outcome::Malformed,
            Outcome::Refused,
        ] {
            let html = render_page(outcome);
            for probe in ["<link", "<script", "@import", "src=", "url("] {
                assert!(
                    !html.contains(probe),
                    "{outcome:?} page must not contain {probe:?} — it would fetch; got: {html}"
                );
            }
            // The one URL that may appear is the SVG namespace, which is an
            // identifier and is never dereferenced.
            assert_eq!(
                html.matches("http").count(),
                1,
                "{outcome:?} page may reference exactly one http string, the SVG xmlns"
            );
            assert!(html.contains(r#"xmlns="http://www.w3.org/2000/svg""#));
        }
    }

    #[test]
    fn test_render_page_is_responsive_and_theme_aware() {
        let html = render_page(Outcome::Connected);
        assert!(
            html.contains(r#"<meta name="viewport""#),
            "page must scale on a phone; got: {html}"
        );
        assert!(
            html.contains("prefers-color-scheme:dark"),
            "page must follow the browser theme; got: {html}"
        );
        assert!(
            html.contains("prefers-reduced-motion:reduce"),
            "every animation must carry a reduced-motion guard; got: {html}"
        );
    }

    // --- build_response ---

    #[test]
    fn test_build_response_declares_utf8_and_a_byte_accurate_length() {
        let html = render_page(Outcome::Connected);
        // The copy carries an em dash — three bytes, one char. A char count
        // under-reports and truncates the page in the browser.
        assert!(html.contains('—'), "fixture must exercise multi-byte copy");

        let response = build_response(Reply::Connected, &html);
        assert!(response.starts_with("HTTP/1.1 200 OK\r\n"));
        assert!(response.contains("Content-Type: text/html; charset=utf-8\r\n"));
        assert!(response.contains(&format!("Content-Length: {}\r\n", html.len())));

        // Headers and body are separated by exactly one blank line, and the
        // body that follows is the whole page.
        let body = response
            .split("\r\n\r\n")
            .nth(1)
            .expect("response has a body");
        assert_eq!(body.len(), html.len());
    }

    #[test]
    fn test_build_response_405_advertises_the_allowed_method() {
        let response = build_response(Reply::MethodNotAllowed, &render_page(Outcome::Malformed));
        assert!(response.contains("Allow: GET\r\n"), "got: {response}");
        // Only the 405 carries it (RFC 9110).
        assert!(!build_response(Reply::Connected, "x").contains("Allow:"));
    }

    // --- build_auth_status_json ---

    #[test]
    fn test_build_auth_status_json_authenticated() {
        let json = build_auth_status_json(
            true,
            "Acme Corp",
            "org_123",
            "ol_org_...7890",
            "macOS Keychain",
            true,
        );
        assert_eq!(json["authenticated"], true);
        assert_eq!(json["org_name"], "Acme Corp");
        assert_eq!(json["org_id"], "org_123");
        assert_eq!(json["key_prefix"], "ol_org_...7890");
        assert_eq!(json["keychain_backend"], "macOS Keychain");
        assert_eq!(json["online"], true);
    }

    #[test]
    fn test_build_auth_status_json_not_authenticated() {
        let json = build_auth_status_json(false, "", "", "", "", false);
        assert_eq!(json["authenticated"], false);
        // When not authenticated, the JSON only has "authenticated"
        assert!(
            json.as_object().map(|o| o.len() == 1).unwrap_or(false),
            "Unauthenticated JSON should have exactly one field"
        );
    }

    // --- parse_me_response_body ---

    #[test]
    fn test_parse_me_response_body_canonical_platform_shape() {
        let body = serde_json::json!({
            "id": "usr_abc",
            "user_db_id": "usr_abc",
            "email": "alice@example.com",
            "organization_id": "org_123",
            "organization_slug": "acme",
            "organization_name": "Acme Corp",
        });
        let v = parse_me_response_body(&body);
        assert!(v.online);
        assert!(!v.rejected);
        assert_eq!(v.org_name, "Acme Corp");
        assert_eq!(v.org_id, "org_123");
        assert_eq!(v.org_slug.as_deref(), Some("acme"));
        assert_eq!(v.user_db_id.as_deref(), Some("usr_abc"));
    }

    /// C-3: `organization_slug` is `str | null`; null means "no slug".
    #[test]
    fn test_parse_me_response_body_null_slug_is_no_slug() {
        let body = serde_json::json!({
            "organization_id": "org_123",
            "organization_slug": null,
            "organization_name": "Acme Corp",
        });
        let v = parse_me_response_body(&body);
        assert_eq!(v.org_id, "org_123");
        assert_eq!(v.org_slug, None);
        let typed: crate::generated::types::AuthMeResponse =
            serde_json::from_value(body).expect("the schema type accepts a null slug");
        assert_eq!(typed.organization_slug, None);
    }

    #[test]
    fn test_parse_me_response_body_user_db_id_falls_back_to_id() {
        // Schema documents `id` as a mirror of `user_db_id`; older platforms
        // may ship only `id`. Both are canonical, not legacy.
        let body = serde_json::json!({
            "id": "usr_xyz",
            "organization_id": "org_123",
            "organization_name": "Acme Corp",
        });
        let v = parse_me_response_body(&body);
        assert_eq!(v.user_db_id.as_deref(), Some("usr_xyz"));
    }

    #[test]
    fn test_parse_me_response_body_missing_org_fields_yield_empty_strings() {
        // Safety net: a response lacking organization_name/organization_id
        // must yield empty strings, not null or panic. Init suppresses the
        // "(org: )" line when org_name is empty.
        let body = serde_json::json!({
            "id": "usr_no_org",
        });
        let v = parse_me_response_body(&body);
        assert_eq!(v.org_name, "");
        assert_eq!(v.org_id, "");
        assert_eq!(v.user_db_id.as_deref(), Some("usr_no_org"));
    }

    // --- sign-in against the frozen contract (PLT-7 C-3, C-6) ---

    fn quiet() -> OutputConfig {
        OutputConfig {
            format: OutputFormat::Json,
            verbose: false,
            debug: false,
            quiet: true,
            color: false,
        }
    }

    fn ctx<'a>(output: &'a OutputConfig, api_url: &str, interactive: bool) -> SignInCtx<'a> {
        SignInCtx {
            output,
            api_url: api_url.to_string(),
            app_url: "http://127.0.0.1:9".into(),
            egress: crate::egress::EgressConfig::direct(),
            interactive,
            no_browser: true,
        }
    }

    const TWO_ORGS: &str = r#"{"data":[
        {"organization_id":"11111111-0000-4000-a000-000000000001","slug":"openlatch","name":"OpenLatch","role":"admin"},
        {"organization_id":"11111111-0000-4000-a000-000000000002","slug":"superadmin","name":"SuperAdmin","role":"owner"}
    ],"user":{"email":"alice@example.com"}}"#;

    fn two_orgs() -> Vec<Org> {
        serde_json::from_str::<CliAuthOrganizationsResponse>(TWO_ORGS)
            .unwrap()
            .data
            .into_iter()
            .map(Org::from)
            .collect()
    }

    #[test]
    fn org_choice_schema_examples_parse_into_the_generated_types() {
        for (name, raw) in [
            (
                "organizations",
                include_str!("../../../schemas/cli-auth-organizations-response.schema.json"),
            ),
            (
                "exchange",
                include_str!("../../../schemas/cli-auth-exchange-response.schema.json"),
            ),
        ] {
            let schema: serde_json::Value = serde_json::from_str(raw).unwrap();
            for example in schema["examples"].as_array().expect(name) {
                let ok = match name {
                    "organizations" => {
                        serde_json::from_value::<CliAuthOrganizationsResponse>(example.clone())
                            .is_ok()
                    }
                    _ => serde_json::from_value::<CliAuthExchangeResponse>(example.clone()).is_ok(),
                };
                assert!(ok, "{name} example must parse: {example}");
            }
        }
    }

    #[tokio::test]
    async fn org_choice_listing_sends_the_code_and_verifier() {
        let mut server = mockito::Server::new_async().await;
        let m = server
            .mock("GET", "/api/v1/cli-auth/organizations")
            .match_header("authorization", "Bearer olc_code")
            .match_header("x-openlatch-code-verifier", "the-verifier")
            .with_status(200)
            .with_body(TWO_ORGS)
            .create_async()
            .await;
        let out = quiet();
        let orgs = list_organizations(&ctx(&out, &server.url(), false), "olc_code", "the-verifier")
            .await
            .expect("listing");
        m.assert_async().await;
        assert_eq!(orgs, two_orgs());
    }

    #[tokio::test]
    async fn org_choice_listing_maps_the_platform_refusals() {
        let mut server = mockito::Server::new_async().await;
        let out = quiet();
        for (status, body, want) in [
            (
                401,
                r#"{"error":{"code":"code_invalid"}}"#,
                ERR_SIGN_IN_EXPIRED,
            ),
            (
                403,
                r#"{"error":{"code":"no_organization"}}"#,
                ERR_NO_ORGANIZATION,
            ),
            (200, r#"{"data":[]}"#, ERR_NO_ORGANIZATION),
            (500, "oops", ERR_AUTH_FLOW_FAILED),
        ] {
            let m = server
                .mock("GET", "/api/v1/cli-auth/organizations")
                .with_status(status)
                .with_body(body)
                .create_async()
                .await;
            let err = list_organizations(&ctx(&out, &server.url(), false), "olc_c", "v")
                .await
                .expect_err("refused");
            assert_eq!(err.code, want, "{status} {body}");
            m.remove_async().await;
        }
    }

    #[tokio::test]
    async fn org_choice_exchange_names_the_chosen_organization() {
        let mut server = mockito::Server::new_async().await;
        let m = server
            .mock("POST", "/api/v1/cli-auth/exchange")
            .match_header("authorization", "Bearer olc_code")
            .match_body(mockito::Matcher::PartialJson(serde_json::json!({
                "code_verifier": "v",
                "organization_id": "11111111-0000-4000-a000-000000000002",
                "intent": "switch",
                "previous_organization_id": "11111111-0000-4000-a000-000000000001",
            })))
            .with_status(201)
            .with_body(
                r#"{"key":"openlatch_secret","key_prefix":"openlatch_s",
                    "organization":{"id":"11111111-0000-4000-a000-000000000002","slug":"superadmin","name":"SuperAdmin"}}"#,
            )
            .expect(1)
            .create_async()
            .await;
        let out = quiet();
        let orgs = two_orgs();
        let got = exchange(
            &ctx(&out, &server.url(), false),
            "olc_code",
            "v",
            &orgs[1],
            Intent::Switch,
            Some(&orgs[0].id),
            None,
        )
        .await
        .expect("exchange");
        m.assert_async().await;
        match got {
            Exchanged::New { key, organization } => {
                assert_eq!(key.expose_secret(), "openlatch_secret");
                assert_eq!(organization, orgs[1]);
            }
            Exchanged::AlreadyIn(_) => panic!("a key was minted"),
        }
    }

    #[tokio::test]
    async fn org_choice_exchange_maps_refusals_and_is_never_retried() {
        let mut server = mockito::Server::new_async().await;
        let out = quiet();
        let orgs = two_orgs();
        for (status, code, want) in [
            (401, "code_invalid", ERR_SIGN_IN_EXPIRED),
            (403, "FORBIDDEN", ERR_ORG_UNAVAILABLE),
            (403, "license_expired", ERR_ORG_UNAVAILABLE),
            (403, "no_organization", ERR_NO_ORGANIZATION),
        ] {
            let m = server
                .mock("POST", "/api/v1/cli-auth/exchange")
                .with_status(status)
                .with_body(format!(r#"{{"error":{{"code":"{code}","message":"m"}}}}"#))
                .expect(1)
                .create_async()
                .await;
            let err = exchange(
                &ctx(&out, &server.url(), false),
                "olc_c",
                "v",
                &orgs[0],
                Intent::Enroll,
                None,
                None,
            )
            .await
            .err()
            .expect("refused");
            assert_eq!(err.code, want, "{status} {code}");
            m.assert_async().await;
            m.remove_async().await;
        }
    }

    #[tokio::test]
    async fn org_choice_exchange_not_a_member_lists_the_fresh_organizations() {
        let mut server = mockito::Server::new_async().await;
        let _x = server
            .mock("POST", "/api/v1/cli-auth/exchange")
            .with_status(403)
            .with_body(r#"{"error":{"code":"not_a_member"}}"#)
            .create_async()
            .await;
        let _l = server
            .mock("GET", "/api/v1/cli-auth/organizations")
            .with_status(200)
            .with_body(
                r#"{"data":[{"organization_id":"i9","slug":"left-over","name":"Left Over"}]}"#,
            )
            .create_async()
            .await;
        let out = quiet();
        let orgs = two_orgs();
        let err = exchange(
            &ctx(&out, &server.url(), false),
            "olc_c",
            "v",
            &orgs[1],
            Intent::Enroll,
            None,
            Some("SuperAdmin"),
        )
        .await
        .err()
        .expect("not a member");
        assert_eq!(err.code, crate::error::ERR_ORG_NOT_FOUND);
        assert_eq!(err.exit_code(), 3);
        assert!(err.message.contains("\"SuperAdmin\""), "{}", err.message);
        assert!(err.message.contains("left-over"), "{}", err.message);
    }

    #[test]
    fn org_choice_choose_follows_the_c6_table() {
        let out = quiet();
        let orgs = two_orgs();
        let headless = ctx(&out, "http://127.0.0.1:9", false);
        // A value: matched, with no prompt.
        assert_eq!(
            choose(&headless, Some("SUPERADMIN"), &orgs).unwrap(),
            orgs[1]
        );
        assert_eq!(
            choose(&headless, Some(&orgs[0].id), &orgs).unwrap(),
            orgs[0]
        );
        assert_eq!(
            choose(&headless, Some("nope"), &orgs).unwrap_err().code,
            crate::error::ERR_ORG_NOT_FOUND
        );
        // One organization: chosen, never asked.
        assert_eq!(choose(&headless, None, &orgs[..1]).unwrap(), orgs[0]);
        // Two, nobody to ask: refused, listing both.
        let e = choose(&headless, None, &orgs).unwrap_err();
        assert_eq!(e.code, crate::error::ERR_ORG_CHOICE_REQUIRED);
        assert!(e.message.contains("openlatch") && e.message.contains("superadmin"));
    }

    #[test]
    fn org_choice_pin_is_read_from_the_bundle_meta() {
        let dir = tempfile::tempdir().unwrap();
        assert_eq!(pinned_organization_in(dir.path()).unwrap(), None);
        let policy = dir.path().join("policy");
        std::fs::create_dir_all(&policy).unwrap();
        std::fs::write(policy.join("bundle.meta.json"), "{not json").unwrap();
        // Unreadable is not "not enrolled".
        assert_eq!(
            pinned_organization_in(dir.path()).unwrap_err().code,
            crate::error::ERR_INVALID_CONFIG
        );
        std::fs::write(
            policy.join("bundle.meta.json"),
            r#"{"digest":"sha256:00","revision":1,"organization_id":"org-a","built_at":"2026-10-12T00:00:00Z"}"#,
        )
        .unwrap();
        assert_eq!(
            pinned_organization_in(dir.path()).unwrap().as_deref(),
            Some("org-a")
        );
    }

    // --- logout (PLT-7 C-9, D-14) ---

    #[tokio::test]
    async fn logout_revokes_the_stored_key_and_clears_both_tiers() {
        use crate::core::auth::{CredentialStore, InMemoryCredentialStore, Tier};
        let mut server = mockito::Server::new_async().await;
        let m = server
            .mock("DELETE", "/api/v1/api-keys/self")
            .match_header("authorization", "Bearer stored-key")
            .with_status(204)
            .expect(1)
            .create_async()
            .await;
        let keychain = InMemoryCredentialStore::new();
        let file = InMemoryCredentialStore::new();
        file.store(SecretString::from("stored-key".to_string()))
            .unwrap();

        let report = logout_stores(
            &keychain,
            &file,
            &server.url(),
            &crate::egress::EgressConfig::direct(),
        )
        .await;
        m.assert_async().await;
        assert!(report.server_revoked);
        assert_eq!(report.cleared, vec![Tier::File]);
        assert!(crate::core::auth::retrieve_stored(&keychain, &file).is_none());
    }

    #[tokio::test]
    async fn logout_with_nothing_stored_revokes_nothing_and_succeeds() {
        use crate::core::auth::InMemoryCredentialStore;
        let mut server = mockito::Server::new_async().await;
        let m = server
            .mock("DELETE", "/api/v1/api-keys/self")
            .expect(0)
            .create_async()
            .await;
        let report = logout_stores(
            &InMemoryCredentialStore::new(),
            &InMemoryCredentialStore::new(),
            &server.url(),
            &crate::egress::EgressConfig::direct(),
        )
        .await;
        m.assert_async().await;
        assert!(!report.server_revoked);
        assert!(report.cleared.is_empty());
    }
}