openlatch-client 0.3.3

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
//! `openlatch auth` command handlers — login, logout, and status.
//!
//! ## Flow overview
//!
//! **login**: Binds a callback server on 127.0.0.1:0, opens the browser to
//! `app.openlatch.ai/cli-auth?callback=<url>`, waits up to 5 minutes with a
//! live countdown spinner, receives the API key via the callback GET request,
//! stores it in the OS keychain (via KeyringCredentialStore), and prints the
//! masked key prefix + org info.
//!
//! **logout**: Attempts server-side revocation (fail-open), clears local
//! credentials from keychain + config.
//!
//! **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 crate::cli::output::{OutputConfig, OutputFormat};
use crate::error::{OlError, ERR_AUTH_FLOW_FAILED, ERR_AUTH_TIMEOUT};

// 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`).
///
/// - Unix: `libc::gethostname` syscall, NUL-terminated into a 256-byte buffer
/// - Windows: `COMPUTERNAME` env var (set by the OS for interactive sessions,
///   which is the only context `openlatch auth login` runs in)
pub fn system_hostname() -> Option<String> {
    #[cfg(unix)]
    {
        use std::ffi::CStr;
        // HOST_NAME_MAX is 64 on Linux and 255 on macOS; 256 bytes covers both
        // plus the NUL terminator.
        let mut buf = [0u8; 256];
        // SAFETY: buf is 256 writable bytes; libc::gethostname writes a
        // NUL-terminated C string on success (ret == 0).
        let ret = unsafe { libc::gethostname(buf.as_mut_ptr() as *mut libc::c_char, buf.len()) };
        if ret != 0 {
            return None;
        }
        let cstr = unsafe { CStr::from_ptr(buf.as_ptr() as *const libc::c_char) };
        let s = cstr.to_str().ok()?.trim();
        if s.is_empty() {
            None
        } else {
            Some(s.to_string())
        }
    }
    #[cfg(windows)]
    {
        let s = std::env::var("COMPUTERNAME").ok()?;
        let trimmed = s.trim();
        if trimmed.is_empty() {
            None
        } else {
            Some(trimmed.to_string())
        }
    }
    #[cfg(not(any(unix, windows)))]
    {
        None
    }
}

/// Parse `api_key`, `org_name`, and `org_id` from a URL query string.
///
/// Expects a raw query string (the part after `?`). Returns `(api_key, org_name, org_id)`.
/// `org_name` and `org_id` default to empty strings if absent.
/// Values are percent-decoded (WR-04: org names with spaces are stored correctly).
///
/// # Errors
///
/// Returns `OL-1606` if `api_key` is missing or empty.
pub fn parse_callback_params(query: &str) -> Result<(String, String, String), OlError> {
    let mut api_key = String::new();
    let mut org_name = String::new();
    let mut org_id = String::new();

    for pair in query.split('&') {
        let mut parts = pair.splitn(2, '=');
        let k = parts.next().unwrap_or("").trim();
        let v = parts.next().unwrap_or("").trim();
        match k {
            "key" => api_key = url_decode(v),
            "org_name" => org_name = url_decode(v),
            "org_id" => org_id = url_decode(v),
            _ => {}
        }
    }

    if api_key.is_empty() {
        return Err(OlError::new(
            ERR_AUTH_FLOW_FAILED,
            "Callback is missing required 'key' parameter",
        )
        .with_suggestion("The authentication server may be misconfigured. Try again."));
    }

    Ok((api_key, org_name, org_id))
}

// ---------------------------------------------------------------------------
// 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 accepts exactly one connection**, so no favicon request is
//   ever served and the page must not reference one.

/// Which page the loopback listener is rendering.
#[derive(Debug, Clone, Copy)]
pub enum Outcome {
    /// The callback arrived carrying a usable key.
    Connected,
    /// The login window closed before the browser came back.
    Expired,
    /// Something reached the port without a well-formed callback — a non-GET
    /// request, no query string, or no `key` parameter. Most often a human
    /// opening the URL by hand.
    Malformed,
}

/// 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 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 auth login</code> in your terminal.",
                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)]
enum Reply {
    Connected,
    BadRequest,
    MethodNotAllowed,
    RequestTimeout,
    Expired,
}

impl Reply {
    fn status(self) -> &'static str {
        match self {
            Reply::Connected => "200 OK",
            Reply::BadRequest => "400 Bad Request",
            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::Expired => Outcome::Expired,
            Reply::BadRequest | 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 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)
}

/// Parse a raw HTTP request into callback params.
///
/// Pure, and deliberately holds no stream — see [`Rejection`]. Being a plain
/// `&[u8] -> Result` also makes the 405 and 400 branches unit-testable without
/// a live socket, which is what they lacked when they were inline.
fn parse_callback_request(raw: &[u8]) -> Result<(String, String, String), Rejection> {
    let request_str = String::from_utf8_lossy(raw);
    let first_line = request_str.lines().next().unwrap_or("");

    // Must be a GET request
    if !first_line.starts_with("GET ") {
        return Err(Rejection::answered(
            Reply::MethodNotAllowed,
            OlError::new(
                ERR_AUTH_FLOW_FAILED,
                format!("Callback received unexpected request: {first_line}"),
            ),
        ));
    }

    // Extract path from "GET /path?query HTTP/1.1"
    let path_part = first_line
        .trim_start_matches("GET ")
        .split_whitespace()
        .next()
        .unwrap_or("");

    let Some(pos) = path_part.find('?') else {
        return Err(Rejection::answered(
            Reply::BadRequest,
            OlError::new(
                ERR_AUTH_FLOW_FAILED,
                "Callback URL missing query parameters (api_key not provided)",
            )
            .with_suggestion("The authentication server may be misconfigured. Try again."),
        ));
    };

    parse_callback_params(&path_part[pos + 1..])
        .map_err(|e| Rejection::answered(Reply::BadRequest, e))
}

/// Read one request off an accepted `stream`, answer it, and parse auth params.
///
/// A browser reaching this port must never see `ERR_EMPTY_RESPONSE`. That is
/// upheld here by shape, not by discipline: the fallible work happens in
/// [`read_request`] and [`parse_callback_request`], neither of which can touch
/// the socket, and this function has exactly one write site per branch.
async fn handle_callback(
    stream: &mut tokio::net::TcpStream,
    read_timeout: Duration,
) -> Result<(String, String, String), OlError> {
    let parsed = match read_request(stream, read_timeout).await {
        Ok(raw) => parse_callback_request(&raw),
        Err(rejection) => Err(rejection),
    };

    match parsed {
        Ok(params) => {
            write_page(stream, Reply::Connected).await;
            Ok(params)
        }
        Err(Rejection { reply, error }) => {
            if let Some(reply) = reply {
                write_page(stream, reply).await;
            }
            Err(error)
        }
    }
}

/// 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
// ---------------------------------------------------------------------------

/// Run `openlatch auth login`.
///
/// Creates a local tokio runtime and calls the async login flow (per init.rs pattern).
pub fn run_login(args: &AuthLoginArgs, 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}"),
        )
    })?;
    let started = std::time::Instant::now();
    let result = rt.block_on(run_login_async(args, output));
    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) => {
            // `stage` is best-effort: derive from error code so we can chart
            // where the login flow tends to break without leaking error text.
            let stage = match e.code {
                "OL-1605" => "timeout",
                "OL-1606" => "callback",
                _ => "other",
            };
            crate::telemetry::capture_global(crate::telemetry::Event::auth_failed(e.code, stage));
        }
    }
    result
}

async fn run_login_async(args: &AuthLoginArgs, output: &OutputConfig) -> Result<(), OlError> {
    use tokio::sync::oneshot;

    // Step 1: Bind callback server on 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();

    let callback_url = format!("http://127.0.0.1:{port}/callback");
    // Web-app URL for the browser step. Precedence:
    //   1. `OPENLATCH_APP_URL` — explicit override when the web app and API
    //      are hosted on different origins (production default).
    //   2. `cloud.api_url` from config with a trailing `/api` stripped —
    //      lets dev setups (Vite at `http://localhost:5173`) point both at
    //      one origin via `OPENLATCH_API_URL` alone.
    //   3. `https://app.openlatch.ai` default.
    let app_url = resolve_app_url();
    let mut auth_url = format!(
        "{}/cli-auth?callback={callback_url}",
        app_url.trim_end_matches('/')
    );
    // Platform labels the generated key with this hostname (e.g.
    // `cli-devbox-2026-04-22`). Best-effort: if the OS syscall fails,
    // omit the param and let the platform pick a generic label.
    if let Some(h) = system_hostname() {
        auth_url.push_str("&hostname=");
        auth_url.push_str(&url_encode(&h));
    }

    // Step 2: Attempt to open browser (D-08, D-09, AUTH-07)
    let browser_opened = if args.no_browser {
        false
    } else {
        try_open_browser(&auth_url)
    };

    // Step 3: Print URL for manual copy-paste (always shown per D-08)
    if browser_opened {
        output.print_info("Opening browser for authentication...");
    } else {
        output.print_info("Open the following URL in your browser to authenticate:");
    }
    output.print_info(&format!("\n  {auth_url}\n"));

    // Step 4: Spinner with countdown (D-08, CLI-11: spinner to stderr, not stdout)
    let (cancel_tx, cancel_rx) = oneshot::channel::<()>();
    let spinner_handle = if output.format != OutputFormat::Json && !output.quiet {
        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
    };

    // Step 5: Wait for the callback (AUTH-06, T-04-02-04).
    //
    // The budget covers waiting for a CONNECTION, not handling one. Wrapping
    // the whole handler meant a callback accepted at 4:59 had its socket
    // dropped mid-read when the timer fired at 5:00, and the browser rendered
    // `ERR_EMPTY_RESPONSE` on an authentication that had in fact succeeded.
    // Once a connection is accepted it is always answered.
    let accepted = tokio::time::timeout(CALLBACK_TIMEOUT, listener.accept()).await;

    // Cancel spinner (T-04-02-04: no orphaned tasks)
    let _ = cancel_tx.send(());
    if let Some(handle) = spinner_handle {
        let _ = handle.await;
    }

    let (api_key, org_name, org_id) = match accepted {
        Err(_timeout) => {
            serve_expired_page(&listener).await;
            return Err(
                OlError::new(ERR_AUTH_TIMEOUT, "Authentication timed out after 5 minutes")
                    .with_suggestion("Run 'openlatch auth login' to try again."),
            );
        }
        Ok(Err(e)) => {
            return Err(OlError::new(
                ERR_AUTH_FLOW_FAILED,
                format!("Failed to accept callback connection: {e}"),
            ));
        }
        Ok(Ok((mut stream, _))) => handle_callback(&mut stream, REQUEST_READ_TIMEOUT).await?,
    };

    // Step 6: Store credential (CRED-01, T-04-02-03 — never log api_key value)
    let store = crate::core::auth::KeyringCredentialStore::new();
    let secret_key = secrecy::SecretString::from(api_key.clone());
    store.store_async(secret_key).await.map_err(|e| {
        OlError::new(
            ERR_AUTH_FLOW_FAILED,
            format!("Failed to store API key in keychain: {}", e.message),
        )
        .with_suggestion("Try running 'openlatch auth login' again.")
    })?;

    // Step 6.5: Telemetry identity stitching (Phase C).
    // Fetch user_db_id from /api/v1/users/me, persist it, and emit $create_alias
    // BEFORE the auth_completed event so PostHog merges the prior agent_id
    // events into the user's persistent person. Best-effort — older platforms
    // omit the field, in which case we skip the alias and continue.
    {
        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 validation = validate_online_full(&api_key, &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 = crate::core::config::Config::load(None, None, false)
                    .ok()
                    .and_then(|c| c.agent_id)
                    .unwrap_or_else(|| "agt_unknown".into());
                let org_id_opt = if validation.org_id.is_empty() {
                    None
                } else {
                    Some(validation.org_id.as_str())
                };
                crate::telemetry::identity::record_auth_success(
                    handle, &dir, &agent_id, user_db_id, org_id_opt,
                );
            }
        }
    }

    // Step 6.75: Tell a running daemon to clear its cloud-worker auth_error
    // latch. Best-effort — if no daemon is running, or the token is wrong,
    // we just skip. The worker also picks up a real credential rotation on
    // its next 60s poll, but this nudge means a same-key re-login (WR-01)
    // resumes POSTs immediately instead of waiting up to a minute.
    notify_daemon_auth_refresh().await;

    // Step 7: Print success output (D-10, T-04-02-03 — masked key only, never raw)
    let masked = mask_api_key(&api_key);
    let backend = keychain_backend_name();

    if output.format == OutputFormat::Json {
        let json = serde_json::json!({
            "authenticated": true,
            "org_name": org_name,
            "org_id": org_id,
            "key_prefix": masked,
            "keychain_backend": backend,
        });
        output.print_json(&json);
    } else {
        output.print_step("Authenticated successfully");
        if !org_name.is_empty() {
            output.print_substep(&format!("Org: {org_name} ({org_id})"));
        }
        output.print_substep(&format!("API key: {masked}"));
        output.print_substep(&format!("Stored in: {backend}"));
    }

    Ok(())
}

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

/// Run `openlatch auth logout`.
pub fn run_logout(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_logout_async(output))
}

async fn run_logout_async(output: &OutputConfig) -> Result<(), OlError> {
    let store = crate::core::auth::KeyringCredentialStore::new();

    // Load api_url from config for server-side revocation (WR-03: respect staging env)
    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);

    // Step 1: Attempt server-side revocation (D-16, fail-open, T-04-02-07)
    let server_revoked = match store.retrieve_async().await {
        Ok(key) => {
            use secrecy::ExposeSecret;
            let key_str = key.expose_secret().to_string();
            attempt_server_revocation(&key_str, &api_url, &egress).await
        }
        Err(_) => false,
    };

    // Step 2: Clear local credential (always runs regardless of revocation result, T-04-02-07)
    if let Err(e) = store.delete_async().await {
        tracing::warn!(error = %e.message, "Failed to delete credential from keychain");
    }

    // Step 3: Output (D-11)
    let backend = keychain_backend_name();

    if output.format == OutputFormat::Json {
        let json = serde_json::json!({
            "logged_out": true,
            "server_revoked": server_revoked,
            "backend": backend,
        });
        output.print_json(&json);
    } else {
        if server_revoked {
            output.print_step("API key revoked on server");
        } else {
            output.print_step("Server revocation failed — continuing with local cleanup");
        }
        output.print_substep(&format!("Credentials cleared from {backend}"));
        output.print_substep("Cloud forwarding is now disabled");
        output.print_info("\nRun 'openlatch auth login' to re-authenticate.");
    }

    Ok(())
}

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

/// Run `openlatch 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 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).
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.
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)
}

/// 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,
    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 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,
        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"
            );
        }
    }

    // --- parse_callback_params ---

    #[test]
    fn test_parse_callback_params_extracts_all_fields() {
        let query = "key=ol_org_abc123&org_name=Acme&org_id=org_456";
        let result = parse_callback_params(query).expect("Should parse successfully");
        assert_eq!(result.0, "ol_org_abc123");
        assert_eq!(result.1, "Acme");
        assert_eq!(result.2, "org_456");
    }

    #[test]
    fn test_parse_callback_params_decodes_percent_encoded_org_name() {
        let query = "key=ol_org_abc123&org_name=Acme%20Corp&org_id=org_456";
        let result = parse_callback_params(query).expect("Should parse successfully");
        assert_eq!(result.1, "Acme Corp");
    }

    #[test]
    fn test_parse_callback_params_decodes_plus_encoded_org_name() {
        let query = "key=ol_org_abc123&org_name=Acme+Corp&org_id=org_456";
        let result = parse_callback_params(query).expect("Should parse successfully");
        assert_eq!(result.1, "Acme Corp");
    }

    #[test]
    fn test_parse_callback_params_returns_error_on_missing_key() {
        let query = "org_name=Acme&org_id=org_456";
        let result = parse_callback_params(query);
        assert!(result.is_err(), "Should fail when key is absent");
        let err = result.unwrap_err();
        assert_eq!(err.code, ERR_AUTH_FLOW_FAILED);
    }

    #[test]
    fn test_parse_callback_params_returns_error_on_empty_key() {
        let query = "key=&org_name=Acme&org_id=org_456";
        let result = parse_callback_params(query);
        assert!(result.is_err(), "Should fail when key is empty");
        let err = result.unwrap_err();
        assert_eq!(err.code, ERR_AUTH_FLOW_FAILED);
    }

    #[test]
    fn test_parse_callback_params_returns_error_on_empty_query() {
        // Simulates a truncated request where no query params are present
        let result = parse_callback_params("");
        assert!(result.is_err(), "Should fail on empty query string");
        let err = result.unwrap_err();
        assert_eq!(err.code, ERR_AUTH_FLOW_FAILED);
    }

    // --- 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."),
        ] {
            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] {
            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] {
            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:"));
    }

    // --- parse_callback_request ---
    //
    // These three branches had no test while they were inline in
    // `handle_callback`: exercising them needed a live socket. Pulling the
    // parse out as a pure `&[u8] -> Result` is what makes them assertable.

    #[test]
    fn test_parse_callback_request_answers_every_rejection() {
        // A rejection that carries no reply would leave the browser on
        // ERR_EMPTY_RESPONSE — the bug this whole page exists to fix.
        for (label, raw, want) in [
            (
                "non-GET",
                &b"POST /callback?key=k HTTP/1.1\r\n\r\n"[..],
                "405 Method Not Allowed",
            ),
            (
                "no query string",
                &b"GET /callback HTTP/1.1\r\n\r\n"[..],
                "400 Bad Request",
            ),
            (
                "query without key",
                &b"GET /callback?state=xyz HTTP/1.1\r\n\r\n"[..],
                "400 Bad Request",
            ),
        ] {
            let rejection = parse_callback_request(raw)
                .expect_err(&format!("{label} must be rejected"))
                .reply
                .unwrap_or_else(|| panic!("{label} must still answer the browser"));
            assert_eq!(rejection.status(), want, "{label}");
            // Whatever the status, the browser gets a rendered page.
            assert!(render_page(rejection.outcome()).contains("<h1"), "{label}");
        }
    }

    #[test]
    fn test_parse_callback_request_accepts_a_well_formed_callback() {
        let raw = b"GET /callback?key=ol_org_abc&org_name=Meridian&org_id=o1 HTTP/1.1\r\n\r\n";
        let (key, org_name, org_id) = parse_callback_request(raw).unwrap_or_else(|e| {
            panic!("well-formed callback must parse: {}", e.error.message);
        });
        assert_eq!(key, "ol_org_abc");
        assert_eq!(org_name, "Meridian");
        assert_eq!(org_id, "o1");
    }

    // --- read_request / handle_callback (T-04-02-08) ---

    #[tokio::test]
    async fn test_handle_callback_returns_error_on_truncated_request() {
        // Connect and immediately drop: 0 bytes = empty/truncated request.
        // The peer is already gone, so this is one of the two paths that
        // deliberately writes nothing back.
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();

        tokio::spawn(async move {
            let _stream = tokio::net::TcpStream::connect(addr).await.unwrap();
        });

        let (mut stream, _) = listener.accept().await.unwrap();
        let result = handle_callback(&mut stream, REQUEST_READ_TIMEOUT).await;

        let err = result.expect_err("Empty/truncated request should return error");
        assert_eq!(
            err.code, ERR_AUTH_FLOW_FAILED,
            "Expected OL-1606 for truncated request, got: {}",
            err.code
        );
    }

    #[tokio::test]
    async fn test_handle_callback_does_not_hang_on_a_peer_that_never_speaks() {
        // A browser preconnect, a port scan or an idle `nc` consumes the one
        // connection this listener accepts. Before the read was bounded, that
        // hung `openlatch auth login` forever with the spinner already gone.
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();

        let peer = tokio::spawn(async move {
            let stream = tokio::net::TcpStream::connect(addr).await.unwrap();
            // Hold the socket open, saying nothing, past the read timeout.
            tokio::time::sleep(Duration::from_millis(400)).await;
            drop(stream);
        });

        let (mut stream, _) = listener.accept().await.unwrap();
        let result = handle_callback(&mut stream, Duration::from_millis(50)).await;

        let err = result.expect_err("a silent peer must not hang the login");
        assert_eq!(err.code, ERR_AUTH_FLOW_FAILED);
        let _ = peer.await;
    }

    // --- 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_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.user_db_id.as_deref(), Some("usr_abc"));
    }

    #[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"));
    }

    // --- run_logout (fail-open behavior) ---

    #[test]
    fn test_run_logout_succeeds_even_when_no_credentials_stored() {
        // run_logout must succeed (fail-open) even when no credentials exist locally
        // and server revocation fails (network unavailable in tests).
        let output = OutputConfig {
            format: OutputFormat::Json,
            verbose: false,
            debug: false,
            quiet: true,
            color: false,
        };
        let result = run_logout(&output);
        assert!(
            result.is_ok(),
            "run_logout must succeed (fail-open) even with no stored credentials: {result:?}"
        );
    }
}