ikigai-embedded 0.1.43

In-process transport: composes a kernel directly in the host process.
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
//! The passkey second factor on the edge, as ikigai endpoints — the server side of the
//! WebAuthn ceremony that [`ikigai_passkey`] verifies.
//!
//! The emailed decision links ([`crate::contactblock`], [`crate::decide`]) are gated today by a
//! signed token in the URL. A passkey adds "…and the person at the registered device approved it,
//! now." This module holds the three moving parts, all on the edge, all reusing one verifier:
//!
//! | endpoint / helper | verb | does |
//! |---|---|---|
//! | `urn:passkey:challenge` | Source | issues a fresh single-use challenge + the registered ids |
//! | [`require_passkey`] | — | the gate a decision POST calls before it acts |
//! | `urn:passkey:enroll-open` | Sink | opens a short enrollment window (run from the box) |
//! | `urn:passkey:register` | Source/Sink | GET shows the enrol page, POST stores the credential |
//!
//! ## Per-action, not a session — and inert until enrolled
//!
//! There is no cookie and no session store: the browser runs the ceremony on the button tap and
//! the assertion rides in the decision POST body, so a Touch-ID tap is *per decision* (the right
//! feel for a block or a decline) and nothing here touches the HTTP transport layer. And the gate
//! is **inert until a credential is registered** — [`require_passkey`] returns `Ok` when the
//! credential file is ABSENT, so deploying this cannot brick the working links; enrolling a
//! passkey is what switches it on.
//!
//! Once armed it **fails closed**: a credential file that is present but unreadable, or enrolled
//! credentials on an edge with no [`RelyingParty`] configured, refuse every gated decision and
//! say why on stderr — they never read as "not enrolled". The relying party comes from
//! `ikigai serve --passkey-rp-id <domain> [--passkey-origin <url>]` and has no default.
//!
//! ## Replay defense lives here
//!
//! [`ikigai_passkey::verify`] is stateless, so the freshness of a challenge is this module's job:
//! `urn:passkey:challenge` mints a random challenge and remembers it briefly; the gate consumes it
//! on use, so an assertion can be presented exactly once and only within the window.
//!
//! ## Enrollment trust (v1)
//!
//! Registering a passkey grants the authority to approve everything the links can, so it must be
//! bootstrapped from a trusted context. v1 uses a **local enrollment window**: `urn:passkey:enroll-open`
//! is cap-gated (`urn:cap:passkey:enroll`) and run from the box, opening a few minutes during which
//! one credential may register; the first registration closes it. Anchoring the enrol link in the
//! Mac-held decide key instead is the natural hardening, left as a follow-on.

use crate::decide::{page, param};
use crate::file_root;
use base64::Engine;
use ikigai_core::{
    ActionSpec, Description, Endpoint, Error, Invocation, ReprType, Representation, Result, Verb,
};
use serde_json::json;
use std::collections::HashMap;
use std::sync::{Mutex, MutexGuard, OnceLock};
use std::time::{Duration, Instant};

/// Cap to open an enrollment window — held only where a human at the box runs it.
pub const CAP_PASSKEY_ENROLL: &str = "urn:cap:passkey:enroll";

/// How long a challenge stays good — long enough for a biometric prompt, short enough that a
/// leaked one is stale almost at once. Measured on the MONOTONIC clock, so a backward jump of
/// the wall clock cannot extend one.
const CHALLENGE_TTL: Duration = Duration::from_secs(120);
/// How long an enrollment window stays open once a human opens it.
const ENROLL_WINDOW_SECONDS: i64 = 300;

/// Wall-clock seconds, for the enrollment window ONLY. That window is opened by one process
/// (`ikigai -c 'sink urn:passkey:enroll-open'` at the box) and read by another (the edge), so
/// its deadline has to be a number both can read from the file; an `Instant` means nothing
/// outside the process that took it. Challenges never leave this process, so they use one.
fn now_secs() -> i64 {
    chrono::Utc::now().timestamp()
}

fn b64() -> base64::engine::general_purpose::GeneralPurpose {
    base64::engine::general_purpose::URL_SAFE_NO_PAD
}

// =====================================================================================
// The relying party — configured by the host, never defaulted.
// =====================================================================================

/// The WebAuthn relying party this edge asserts under: the RP id (a registrable domain such as
/// `ikigai-rs.dev`) and the origin the browser reports (`https://ikigai-rs.dev`).
///
/// **There is no default.** A forgotten setting used to register passkeys silently under the
/// production hostname; now an edge that has not been told its relying party cannot enroll a
/// passkey, and an edge that HAS enrolled ones refuses every gated decision until it is told
/// (fail closed). `ikigai serve --passkey-rp-id <domain> [--passkey-origin <url>]` sets it.
///
/// ```
/// use ikigai_embedded::passkey::RelyingParty;
/// let rp = RelyingParty::new("ikigai-rs.dev", None).unwrap();
/// assert_eq!(rp.origin(), "https://ikigai-rs.dev");
/// let rp = RelyingParty::new("example.org", Some("https://login.example.org")).unwrap();
/// assert_eq!((rp.rp_id(), rp.origin()), ("example.org", "https://login.example.org"));
/// assert!(RelyingParty::new("https://example.org", None).is_err()); // an id, not a URL
/// assert!(RelyingParty::new("example.org", Some("https://example.org/path")).is_err());
/// ```
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RelyingParty {
    rp_id: String,
    origin: String,
}

impl RelyingParty {
    /// A relying party for `rp_id`, with `origin` defaulting to `https://<rp_id>`. Refuses an
    /// id that is not a bare host name and an origin that is not `scheme://host[:port]`.
    pub fn new(rp_id: &str, origin: Option<&str>) -> std::result::Result<Self, String> {
        let rp_id = rp_id.trim();
        if rp_id.is_empty()
            || rp_id
                .chars()
                .any(|c| matches!(c, '/' | ':' | '?' | '#' | '@') || c.is_whitespace())
        {
            return Err(format!(
                "a passkey RP id is a bare domain such as `ikigai-rs.dev`, not `{rp_id}`"
            ));
        }
        let origin = match origin {
            Some(o) => o.trim().trim_end_matches('/').to_string(),
            None => format!("https://{rp_id}"),
        };
        let host = origin
            .strip_prefix("https://")
            .or_else(|| origin.strip_prefix("http://"))
            .ok_or_else(|| format!("a passkey origin is `https://host[:port]`, not `{origin}`"))?;
        if host.is_empty() || host.contains(['/', '?', '#', '@']) {
            return Err(format!(
                "a passkey origin is `https://host[:port]` with no path, not `{origin}`"
            ));
        }
        Ok(Self {
            rp_id: rp_id.to_string(),
            origin,
        })
    }
    /// The RP id the authenticator scopes its credential to.
    pub fn rp_id(&self) -> &str {
        &self.rp_id
    }
    /// The origin `clientDataJSON` must carry.
    pub fn origin(&self) -> &str {
        &self.origin
    }
}

static RELYING_PARTY: Mutex<Option<RelyingParty>> = Mutex::new(None);

/// Tell this process's passkey endpoints which relying party they serve. Process-global like
/// the instance name, and set once at startup from `serve`'s flags.
pub fn set_relying_party(rp: RelyingParty) {
    *RELYING_PARTY.lock().unwrap_or_else(|e| e.into_inner()) = Some(rp);
}

/// The configured relying party, if any.
#[cfg(not(test))]
fn relying_party() -> Option<RelyingParty> {
    RELYING_PARTY
        .lock()
        .unwrap_or_else(|e| e.into_inner())
        .clone()
}

/// The tests override the relying party per thread (as they do `store_root`), so a test that
/// wants the unconfigured case cannot race one that configures it.
#[cfg(test)]
fn relying_party() -> Option<RelyingParty> {
    tests::test_rp()
}

/// The workspace root the passkey files live under. In production this is [`file_root`]; the
/// tests override it per-thread (each test runs on its own thread) so parallel tests never share
/// a credential file — a global env-var override would race across them.
fn store_root() -> std::path::PathBuf {
    #[cfg(test)]
    if let Some(p) = tests::test_root() {
        return p;
    }
    file_root()
}

fn credentials_path() -> std::path::PathBuf {
    store_root().join("passkey-credentials.json")
}
fn enroll_window_path() -> std::path::PathBuf {
    store_root().join("passkey-enroll.open")
}

// =====================================================================================
// The challenge store — process-global, in-memory. A restart just invalidates outstanding
// challenges (the user taps again); nothing here is worth persisting.
// =====================================================================================

fn challenges() -> &'static Mutex<HashMap<String, Instant>> {
    static STORE: OnceLock<Mutex<HashMap<String, Instant>>> = OnceLock::new();
    STORE.get_or_init(|| Mutex::new(HashMap::new()))
}

/// The monotonic clock challenges expire on. Native-only: the embedded host is a threaded,
/// filesystem-backed process that a wasm build replaces rather than compiles, and the injected
/// `Clock` offers wall time, which is exactly what a challenge's expiry must not follow. The
/// attribute is on the fn because the call is a trailing expression (an attribute on an
/// expression is not stable).
#[allow(clippy::disallowed_methods)]
fn monotonic_now() -> Instant {
    Instant::now()
}

/// Mint a fresh challenge, remember it with an expiry, and return its base64url text.
fn issue_challenge() -> Result<String> {
    issue_challenge_at(monotonic_now())
}

/// [`issue_challenge`] at a given monotonic instant — the seam the expiry tests drive.
fn issue_challenge_at(now: Instant) -> Result<String> {
    let mut raw = [0u8; 32];
    getrandom::getrandom(&mut raw)
        .map_err(|e| Error::Endpoint(format!("no OS randomness for a challenge: {e}")))?;
    let challenge = b64().encode(raw);
    // Held across no await: every critical section on this lock is a few map operations.
    let mut store = challenges().lock().expect("challenge store poisoned");
    store.retain(|_, exp| *exp > now); // opportunistic sweep so the map cannot grow without bound
    store.insert(challenge.clone(), now + CHALLENGE_TTL);
    Ok(challenge)
}

/// Consume a challenge: it must be one we issued and still in date, and it is removed so it
/// cannot be presented twice.
fn consume_challenge(challenge: &str) -> bool {
    consume_challenge_at(challenge, monotonic_now())
}

/// [`consume_challenge`] at a given monotonic instant.
fn consume_challenge_at(challenge: &str, now: Instant) -> bool {
    let mut store = challenges().lock().expect("challenge store poisoned");
    match store.remove(challenge) {
        Some(exp) => exp > now,
        None => false,
    }
}

// =====================================================================================
// The credential store — a small JSON file, the registered public key(s) for the one user.
//
// Three rules, each one a way the gate used to fail OPEN:
//
// - ABSENT means "not enrolled" (the gate is inert); PRESENT but unreadable or unparsable is an
//   error, and the gate refuses every decision until someone repairs it at the box. It used to
//   read as "not enrolled", so a truncated file silently downgraded every decision to token-only.
// - Writes are ATOMIC (temp file in the same directory, fsync, rename), so a crash leaves the old
//   file or the new one, never half of one.
// - load → verify → save runs under ONE process-wide lock, so two concurrent assertions cannot
//   each write back the copy they loaded and lower the stored signature counter.
// - The file is trusted only if nobody else could have WRITTEN it (ledger #828): write access is
//   the power to enroll a credential. Group/world-writable, or owned by another user, refuses
//   like an unparsable file; only group/world-READABLE is tightened to 0600 and logged. Checked
//   on the open handle, under the lock, before a byte is parsed. Saves were already 0600, but a
//   file enrolled before 0.1.39 is rewritten only when a counter advances, and a platform
//   passkey's counter stays 0, so without this check a loose file stayed loose for good.
// =====================================================================================

#[derive(serde::Serialize, serde::Deserialize, Clone)]
struct StoredCredential {
    /// base64url of the credentialId.
    id: String,
    /// base64url of the SubjectPublicKeyInfo DER public key.
    spki: String,
    /// The last signature counter seen, advanced on each successful assertion.
    #[serde(default)]
    sign_count: u32,
}

/// Serializes every read-modify-write of the credential file in this process. It guards no
/// data of its own (the file is the data), so a poisoned lock is safe to take over. Held across
/// no await: the gate and the register endpoint hold it only in synchronous code.
fn credential_lock() -> MutexGuard<'static, ()> {
    static LOCK: Mutex<()> = Mutex::new(());
    LOCK.lock().unwrap_or_else(|e| e.into_inner())
}

/// The registered credentials. `Ok(empty)` only when the file is ABSENT; a file that is present
/// but cannot be read or parsed, or that someone other than this process's user could have
/// written, is an `Err` naming it, which every caller treats as "refuse".
///
/// Takes the [`credential_lock`] guard so that every load provably runs under the lock: the
/// permission check (which may tighten the file) and the parse see one state of the file.
fn load_credentials(
    _held: &MutexGuard<'static, ()>,
) -> std::result::Result<Vec<StoredCredential>, String> {
    use std::io::Read;
    // The directory first, and whether or not the file is there: in a directory others can
    // write, ABSENT is not evidence of "not enrolled" (deleting the file is how they would
    // disarm the gate), and a present file may be one they put there.
    guard_directory(&store_root())?;
    let path = credentials_path();
    let unreadable =
        |e: std::io::Error| format!("{} is present but unreadable: {e}", path.display());
    let mut file = match std::fs::File::open(&path) {
        Ok(file) => file,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
        Err(e) => return Err(unreadable(e)),
    };
    // On the handle, not the path: what is judged is exactly what is then read.
    guard_permissions(&path, &file, Remedy::CheckThenChmod)?;
    let mut bytes = Vec::new();
    file.read_to_end(&mut bytes).map_err(unreadable)?;
    serde_json::from_slice(&bytes).map_err(|e| {
        format!(
            "{} is present but not a credential list: {e}",
            path.display()
        )
    })
}

/// What the credential file's permission bits and owner allow.
#[derive(Debug, PartialEq, Eq)]
enum Permission {
    /// Owner-only, owned by this process's user.
    Private,
    /// Others can read it but not write it: nothing is at stake but disclosure of public keys,
    /// so it is tightened to 0600 rather than taking the gate down for a cosmetic reason.
    Tighten,
    /// Someone else could have written it, so its contents (which credentials are enrolled) are
    /// not trusted. Tightening it now would trust whatever they wrote; a person checks it.
    Refuse(String),
}

/// Judge a file `mode` owned by uid `owner`, read by a process running as uid `me`. Pure, so
/// every branch is testable, including the foreign-owner one a test cannot stage without root.
fn judge_permissions(mode: u32, owner: u32, me: u32) -> Permission {
    if owner != me {
        return Permission::Refuse(format!(
            "is owned by uid {owner}, not by this process's uid {me}, so its owner could have \
             enrolled a credential"
        ));
    }
    if mode & 0o022 != 0 {
        return Permission::Refuse(format!(
            "is writable by its group or by everyone (mode {:04o}), so anyone who can write it \
             could have enrolled a credential",
            mode & 0o7777
        ));
    }
    if mode & 0o044 != 0 {
        return Permission::Tighten;
    }
    Permission::Private
}

/// What a person at the box does about a passkey file someone else could have written.
#[derive(Clone, Copy)]
enum Remedy {
    /// The credential store: check every entry is theirs, then take the file back.
    CheckThenChmod,
    /// The enrollment window (ledger #850): remove it. Its timestamp is not theirs to vouch
    /// for, and a new window is one command away.
    Remove,
}

/// Refuse a passkey file someone else could have written; tighten one others can only read.
/// The command in the refusal is the exact fix: for the credential store, the `chmod` after the
/// person at the box has checked that every entry in the file is theirs; for the enrollment
/// window, removing it.
#[cfg(unix)]
fn guard_permissions(
    path: &std::path::Path,
    file: &std::fs::File,
    remedy: Remedy,
) -> std::result::Result<(), String> {
    use std::os::unix::fs::{MetadataExt, PermissionsExt};
    let meta = file
        .metadata()
        .map_err(|e| format!("{} is present but cannot be inspected: {e}", path.display()))?;
    // SAFETY: `geteuid` takes no arguments, has no preconditions, and cannot fail.
    let me = unsafe { libc::geteuid() };
    match judge_permissions(meta.mode(), meta.uid(), me) {
        Permission::Private => Ok(()),
        Permission::Tighten => {
            // fchmod on the open handle; owning the file is all it needs.
            file.set_permissions(std::fs::Permissions::from_mode(0o600))
                .map_err(|e| {
                    format!(
                        "{} is readable by others (mode {:04o}) and could not be tightened: {e}; \
                         fix it at the box with `chmod 600 {}`",
                        path.display(),
                        meta.mode() & 0o7777,
                        path.display()
                    )
                })?;
            // Logged once: the file is 0600 from here on, so the next load is silent.
            eprintln!(
                "ikigai passkey: {} was readable by others (mode {:04o}); tightened it to 0600.",
                path.display(),
                meta.mode() & 0o7777
            );
            Ok(())
        }
        Permission::Refuse(why) => {
            let p = path.display();
            if let Remedy::Remove = remedy {
                let who = if meta.uid() == me { "" } else { " (as root)" };
                return Err(format!(
                    "{p} {why}, so the window it describes is not trusted; remove it at the box \
                     with `rm {p}`{who} and open a new one with `sink urn:passkey:enroll-open`"
                ));
            }
            let fix = if meta.uid() == me {
                format!("`chmod 600 {p}`")
            } else {
                format!("`chown {me} {p}` (as root), then `chmod 600 {p}`")
            };
            Err(format!(
                "{p} {why}; check that every entry in it is yours, then fix it at the box with \
                 {fix}"
            ))
        }
    }
}

/// No Unix permission bits to judge: a non-Unix host (none is deployed; the edge is Linux and the
/// desk macOS) trusts the platform's ACLs, as it did before this check existed.
#[cfg(not(unix))]
fn guard_permissions(
    _path: &std::path::Path,
    _file: &std::fs::File,
    _remedy: Remedy,
) -> std::result::Result<(), String> {
    Ok(())
}

/// Judge the DIRECTORY the passkey files live in (ledger #850): `Some(why)` when someone other
/// than this process's user could create, delete, rename or replace entries in it. Then nothing
/// in it is trusted, whatever its own mode says: they could plant an enrollment window, swap in
/// a symlink or hard link to a file of ours that happens to parse, or delete the credential file
/// and so disarm the gate. Readable by others is fine for a directory (0755 is ordinary); the
/// files in it are judged on their own. Pure, so the foreign-owner branch is testable.
fn judge_directory(mode: u32, owner: u32, me: u32) -> Option<String> {
    if owner != me {
        return Some(format!(
            "is owned by uid {owner}, not by this process's uid {me}"
        ));
    }
    if mode & 0o022 != 0 {
        return Some(format!(
            "is writable by its group or by everyone (mode {:04o})",
            mode & 0o7777
        ));
    }
    None
}

/// Refuse to trust anything in a passkey directory others could write. The fix in the refusal
/// is the exact command, after the person at the box has checked the files in it are theirs.
#[cfg(unix)]
fn guard_directory(dir: &std::path::Path) -> std::result::Result<(), String> {
    use std::os::unix::fs::MetadataExt;
    let d = dir.display();
    let meta = std::fs::metadata(dir)
        .map_err(|e| format!("the passkey workspace {d} cannot be inspected: {e}"))?;
    // SAFETY: `geteuid` takes no arguments, has no preconditions, and cannot fail.
    let me = unsafe { libc::geteuid() };
    let Some(why) = judge_directory(meta.mode(), meta.uid(), me) else {
        return Ok(());
    };
    let fix = if meta.uid() == me {
        format!("`chmod go-w {d}`")
    } else {
        format!("`chown {me} {d}` (as root), then `chmod go-w {d}`")
    };
    Err(format!(
        "the passkey workspace {d} {why}, so anyone who can write it could have enrolled a \
         credential, opened enrollment or removed the credential store, and nothing in it is \
         trusted; check that the passkey files in it are yours, then fix it at the box with {fix}"
    ))
}

/// No Unix permission bits to judge (see the non-Unix [`guard_permissions`]).
#[cfg(not(unix))]
fn guard_directory(_dir: &std::path::Path) -> std::result::Result<(), String> {
    Ok(())
}

/// Check the credential store the way the gate will, at startup, so a store the gate would
/// refuse stops a serving door from coming up rather than surfacing at the first decision
/// someone taps. Absent is fine (not enrolled); a group/world-readable file is tightened here.
/// The workspace DIRECTORY is judged first (ledger #850): one others could write refuses,
/// naming it, whether or not a credential file is in it.
pub fn preflight() -> std::result::Result<(), String> {
    let held = credential_lock();
    load_credentials(&held).map(|_| ())
}

/// The loud half of failing closed: one line on stderr per refused request, naming the file.
fn store_unreadable(detail: &str) {
    eprintln!(
        "ikigai passkey: REFUSING every passkey-gated decision: {detail}. Repair or remove the \
         file at the box (removing it un-enrolls; enroll again with `sink urn:passkey:enroll-open`)."
    );
}

fn save_credentials(creds: &[StoredCredential]) -> Result<()> {
    let json = serde_json::to_vec_pretty(creds)
        .map_err(|e| Error::Endpoint(format!("cannot serialize credentials: {e}")))?;
    write_atomic(&credentials_path(), &json)
        .map_err(|e| Error::Endpoint(format!("cannot write credentials: {e}")))
}

/// Replace `path` with `bytes` whole: write a sibling temp file (owner-only), fsync it, rename it
/// over the target, then fsync the directory so the rename itself survives a crash. A reader —
/// or a crash at any point — sees the old file or the new one, never a truncated one.
fn write_atomic(path: &std::path::Path, bytes: &[u8]) -> std::io::Result<()> {
    use std::io::Write;
    let dir = path.parent().ok_or_else(|| {
        std::io::Error::new(std::io::ErrorKind::InvalidInput, "path has no parent")
    })?;
    let name = path
        .file_name()
        .map(|n| n.to_string_lossy().into_owned())
        .unwrap_or_default();
    // Unique per process; within one, the credential lock serializes writers.
    let tmp = dir.join(format!(".{name}.tmp-{}", std::process::id()));
    let _ = std::fs::remove_file(&tmp); // a leftover from a crash would refuse `create_new`
    let mut opts = std::fs::OpenOptions::new();
    opts.write(true).create_new(true);
    #[cfg(unix)]
    std::os::unix::fs::OpenOptionsExt::mode(&mut opts, 0o600);
    let write_then_rename = |opts: &std::fs::OpenOptions| -> std::io::Result<()> {
        let mut f = opts.open(&tmp)?;
        f.write_all(bytes)?;
        f.sync_all()?;
        std::fs::rename(&tmp, path)
    };
    let written = write_then_rename(&opts);
    if written.is_err() {
        let _ = std::fs::remove_file(&tmp);
        return written;
    }
    // Durability of the rename, best-effort: not every platform can open a directory to sync it.
    if let Ok(d) = std::fs::File::open(dir) {
        let _ = d.sync_all();
    }
    Ok(())
}

/// Whether the gate is armed. True when a credential is registered — and ALSO when the store is
/// present but unreadable, because then the gate refuses everything (it fails closed).
pub fn is_enrolled() -> bool {
    let held = credential_lock();
    load_credentials(&held).map_or(true, |c| !c.is_empty())
}

// =====================================================================================
// Browser glue. The one piece that runs on the device, not the edge.
//
// Served as a SAME-ORIGIN FILE, not inline: the edge's strict CSP is `default-src 'self'`,
// which forbids inline `<script>` but allows a script fetched from the same origin. So the
// pages carry only a `<script src="/passkey/app.js">` tag and the ceremony lives in
// `PASSKEY_APP_JS`, served by `urn:passkey:js` with a JavaScript content type (X-Content-Type-
// Options: nosniff is set, so the MIME must be right). No CSP loosening anywhere.
// =====================================================================================

/// What a decision page carries: a status line and the shared ceremony script. The page's form
/// must have `id="act"`; `PASSKEY_APP_JS` wires it — on submit, fetch a challenge, run
/// `navigator.credentials.get` if enrolled, attach the assertion as `pk_*` fields, submit.
pub(crate) const DECISION_PASSKEY_JS: &str =
    "<p id=pkstatus style=\"color:#666\"></p><script src=\"/passkey/app.js\"></script>";

/// The registration page body: a button (wired by `PASSKEY_APP_JS` via `id="reg"`) that runs
/// `navigator.credentials.create`, then POSTs the new credential id + its SPKI public key.
const REGISTER_PAGE_BODY: &str = r#"<p>Create a passkey for this site — your device will ask you to confirm with Face/Touch ID.</p>
<button id=reg style="font:inherit;padding:.6rem 1.2rem">Create passkey</button>
<p id=status style="color:#666"></p>
<script src="/passkey/app.js"></script>"#;

/// What `/passkey/register` shows on an edge started without `--passkey-rp-id`.
const NOT_CONFIGURED_BODY: &str = "<p>This edge has no passkey relying party configured, so a \
     passkey registered here would be bound to nothing. Restart it with <code>--passkey-rp-id \
     &lt;domain&gt;</code> (and <code>--passkey-origin</code> if the origin is not \
     <code>https://&lt;domain&gt;</code>), then open an enrollment window.</p>";

/// The one ceremony script, served same-origin (see the section note on CSP). It wires whichever
/// page it lands on: a decision form (`#act` → `navigator.credentials.get`) or the register
/// button (`#reg` → `navigator.credentials.create`). `form.submit()` does not re-fire the submit
/// handler, so the decision path has no re-entrancy.
const PASSKEY_APP_JS: &str = r#"(function(){
  var form=document.getElementById('act');
  var reg=document.getElementById('reg');
  if(form) decision(form);
  if(reg) register(reg);

  function decision(form){
    var status=document.getElementById('pkstatus');
    form.addEventListener('submit', function(ev){ ev.preventDefault();
      status.textContent='';
      fetch('/passkey/challenge',{headers:{accept:'application/json'}})
        .then(function(r){return r.json();})
        .then(function(opt){
          if(!opt.enrolled){ form.submit(); return; }
          status.textContent='Confirm with your passkey…';
          return navigator.credentials.get({publicKey:{
            challenge:u(opt.challenge), rpId:opt.rpId,
            allowCredentials:(opt.allowCredentials||[]).map(function(c){return {type:'public-key',id:u(c.id)};}),
            userVerification:opt.userVerification||'preferred', timeout:60000
          }}).then(function(a){
            add(form,'pk_id',b(a.rawId)); add(form,'pk_auth',b(a.response.authenticatorData));
            add(form,'pk_client',b(a.response.clientDataJSON)); add(form,'pk_sig',b(a.response.signature));
            form.submit();
          });
        })
        .catch(function(e){ status.textContent='Passkey step failed ('+((e&&e.message)||e)+'). Reopen the link to retry.'; });
    });
  }

  function register(btn){
    var status=document.getElementById('status');
    btn.addEventListener('click', function(){
      status.textContent='Creating…';
      fetch('/passkey/challenge').then(function(r){return r.json();}).then(function(opt){
        return navigator.credentials.create({publicKey:{
          rp:{id:opt.rpId, name:'ikigai'},
          user:{id:new TextEncoder().encode('ikigai-owner'), name:'owner', displayName:'ikigai owner'},
          challenge:u(opt.challenge),
          pubKeyCredParams:[{type:'public-key',alg:-7}],
          authenticatorSelection:{userVerification:'preferred',residentKey:'preferred'},
          timeout:60000, attestation:'none'
        }});
      }).then(function(cred){
        var spki=cred.response.getPublicKey && cred.response.getPublicKey();
        if(!spki){ throw new Error('this browser did not expose the public key (needs WebAuthn L2)'); }
        var body='id='+encodeURIComponent(b(cred.rawId))+'&spki='+encodeURIComponent(b(spki));
        return fetch('/passkey/register',{method:'POST',headers:{'content-type':'application/x-www-form-urlencoded'},body:body});
      }).then(function(res){ return res.text(); }).then(function(html){ document.open(); document.write(html); document.close(); })
        .catch(function(e){ status.textContent='Registration failed: '+((e&&e.message)||e); });
    });
  }

  function add(f,n,v){ var i=document.createElement('input'); i.type='hidden'; i.name=n; i.value=v; f.appendChild(i); }
  function u(s){ s=s.replace(/-/g,'+').replace(/_/g,'/'); while(s.length%4)s+='='; var x=atob(s),y=new Uint8Array(x.length); for(var i=0;i<x.length;i++)y[i]=x.charCodeAt(i); return y.buffer; }
  function b(buf){ var y=new Uint8Array(buf),s=''; for(var i=0;i<y.length;i++)s+=String.fromCharCode(y[i]); return btoa(s).replace(/\+/g,'-').replace(/\//g,'_').replace(/=+$/,''); }
})();
"#;

/// Serves `PASSKEY_APP_JS` as a same-origin JavaScript file so the strict edge CSP admits it.
pub struct PasskeyJs;

#[async_trait::async_trait]
impl Endpoint for PasskeyJs {
    async fn invoke(&self, _inv: &Invocation<'_>) -> Result<Representation> {
        Ok(Representation::new(
            ReprType::new("application/javascript").with_param("charset", "utf-8"),
            PASSKEY_APP_JS.as_bytes().to_vec(),
        ))
    }
    fn name(&self) -> &str {
        "passkey-js"
    }
    fn describe(&self) -> Description {
        Description::new("passkey-js")
            .title("The passkey ceremony script")
            .summary("The same-origin script the decision and register pages load to run the WebAuthn ceremony.")
            // ★ ON THE ACTION, not beside it. `Description::action` takes an explicit
            // `ActionSpec` WHOLE — `action_specs()` never merges the flat `.output()` into
            // one — so the flat declaration below is invisible to every consumer that reads
            // the manifold's actions. Kept as well because `Description::outputs` is its own
            // public field; the action is the one that is read. (Conformance 0.2.0's OUTPUTS
            // check found all four passkey faces undeclared this way.)
            .action(
                ActionSpec::new(Verb::Source)
                    .summary("the script")
                    .output("application/javascript; charset=utf-8"),
            )
            .output("application/javascript; charset=utf-8")
    }
}

// =====================================================================================
// The gate — what a decision POST calls before it acts.
// =====================================================================================

/// Require a valid passkey assertion for this action, UNLESS no credential is enrolled (in which
/// case the action proceeds token-only, exactly as before passkeys). The assertion rides in the
/// POST body as base64url fields the glue-JS adds: `pk_id`, `pk_auth`, `pk_client`, `pk_sig`.
///
/// "Not enrolled" means the credential file is ABSENT. A file that is present but unreadable, or
/// credentials with no [`RelyingParty`] configured to check them against, refuse every decision
/// and say why on stderr: the gate fails closed, never open.
///
/// On success the challenge is consumed (single-use) and any advanced signature counter persisted.
/// Every failure is one `Denied` — a prober learns nothing from which check tripped.
pub fn require_passkey(inv: &Invocation<'_>) -> Result<()> {
    let denied = || Error::Denied("this action needs your passkey".to_string());

    // One lock from load to save, so a concurrent assertion cannot write back a stale copy.
    let held = credential_lock();
    let creds = match load_credentials(&held) {
        Ok(creds) => creds,
        Err(detail) => {
            store_unreadable(&detail);
            return Err(denied());
        }
    };
    if creds.is_empty() {
        return Ok(()); // inert until enrolled
    }
    let Some(rp) = relying_party() else {
        eprintln!(
            "ikigai passkey: REFUSING every passkey-gated decision: a credential is enrolled but \
             this edge has no relying party configured (start it with `--passkey-rp-id <domain>`)."
        );
        return Err(denied());
    };

    // Pull the four assertion fields the glue-JS attaches, all base64url.
    let (id_b64, auth_b64, client_b64, sig_b64) = (
        param(inv, "pk_id"),
        param(inv, "pk_auth"),
        param(inv, "pk_client"),
        param(inv, "pk_sig"),
    );
    if id_b64.is_empty() || auth_b64.is_empty() || client_b64.is_empty() || sig_b64.is_empty() {
        return Err(denied());
    }
    let decode = |s: &str| b64().decode(s).map_err(|_| denied());
    let (cred_id, auth_data, client_data, signature) = (
        decode(&id_b64)?,
        decode(&auth_b64)?,
        decode(&client_b64)?,
        decode(&sig_b64)?,
    );

    // The challenge inside clientDataJSON must be one we issued and have not yet spent.
    let client_json: serde_json::Value =
        serde_json::from_slice(&client_data).map_err(|_| denied())?;
    let challenge = client_json
        .get("challenge")
        .and_then(|v| v.as_str())
        .ok_or_else(denied)?
        .to_string();
    if !consume_challenge(&challenge) {
        return Err(denied()); // stale, replayed, or never issued here
    }

    // The assertion must name a credential we registered; rebuild it for the verifier.
    let stored = creds
        .iter()
        .find(|c| c.id == id_b64)
        .ok_or_else(denied)?
        .clone();
    let spki = b64().decode(&stored.spki).map_err(|_| denied())?;
    let registered =
        ikigai_passkey::RegisteredCredential::from_spki_der(cred_id, &spki, stored.sign_count)
            .map_err(|_| denied())?;

    let policy = ikigai_passkey::Policy {
        rp_id: rp.rp_id(),
        origin: rp.origin(),
        challenge_b64url: &challenge,
        require_user_verified: true,
    };
    let assertion = ikigai_passkey::Assertion {
        credential_id: &registered.id,
        authenticator_data: &auth_data,
        client_data_json: &client_data,
        signature: &signature,
    };
    let new_count =
        ikigai_passkey::verify(&registered, &assertion, &policy).map_err(|_| denied())?;
    #[cfg(test)]
    tests::after_verify();

    // Persist an advanced counter so a cloned authenticator's replay is caught next time. The
    // copy written back is the one loaded under the lock still held, so nothing newer can be
    // overwritten, and the guard below means the stored counter only ever rises.
    if new_count > stored.sign_count {
        let mut all = creds;
        if let Some(c) = all.iter_mut().find(|c| c.id == id_b64) {
            c.sign_count = new_count;
        }
        // Best-effort: a failed write must not undo a real decision — but it is said out loud.
        if let Err(e) = save_credentials(&all) {
            eprintln!("ikigai passkey: could not persist the advanced signature counter: {e}");
        }
    }
    Ok(())
}

// =====================================================================================
// urn:passkey:challenge — hand the browser a fresh challenge + the registered ids.
// =====================================================================================

/// Issues the JSON a `navigator.credentials.get()` needs: a fresh challenge, the RP id, and the
/// credential ids to allow. Empty `allowCredentials` (nothing enrolled) tells the page to submit
/// without a ceremony — the gate is inert then anyway.
pub struct PasskeyChallenge;

#[async_trait::async_trait]
impl Endpoint for PasskeyChallenge {
    async fn invoke(&self, _inv: &Invocation<'_>) -> Result<Representation> {
        // The same fail-closed reading as the gate: a broken store or a missing relying party
        // with credentials enrolled is an error the page shows, not "nothing enrolled" (which
        // would tell the page to submit token-only into a gate that will refuse it anyway).
        let unavailable = || Error::Endpoint("passkey sign-in is unavailable on this edge".into());
        // Under the lock like every load, so the permission check sees one state of the file. A
        // block, so the (non-`Send`) guard is gone before anything else in this future runs.
        let loaded = {
            let held = credential_lock();
            load_credentials(&held)
        };
        let creds = loaded.map_err(|detail| {
            store_unreadable(&detail);
            unavailable()
        })?;
        let rp = relying_party();
        if rp.is_none() && !creds.is_empty() {
            eprintln!(
                "ikigai passkey: a credential is enrolled but this edge has no relying party \
                 configured (start it with `--passkey-rp-id <domain>`)."
            );
            return Err(unavailable());
        }
        let challenge = issue_challenge()?;
        let allow: Vec<_> = creds
            .into_iter()
            .map(|c| json!({ "type": "public-key", "id": c.id }))
            .collect();
        let body = json!({
            "challenge": challenge,
            "rpId": rp.as_ref().map(RelyingParty::rp_id),
            "allowCredentials": allow,
            "userVerification": "preferred",
            "enrolled": !allow.is_empty(),
        });
        Ok(Representation::new(
            ReprType::new("application/json").with_param("charset", "utf-8"),
            serde_json::to_vec(&body).expect("serializable").to_vec(),
        ))
    }
    fn name(&self) -> &str {
        "passkey-challenge"
    }
    fn describe(&self) -> Description {
        Description::new("passkey-challenge")
            .title("Issue a WebAuthn challenge")
            .summary("A fresh single-use challenge plus the registered credential ids, for a login ceremony.")
            .action(
                ActionSpec::new(Verb::Source)
                    .summary("mint a challenge")
                    .output("application/json; charset=utf-8"),
            )
            .output("application/json; charset=utf-8")
    }
}

// =====================================================================================
// urn:passkey:enroll-open — open a short enrollment window (run from the box).
// =====================================================================================

/// Opens a brief window during which one credential may register. Cap-gated so only a human at
/// the box can open it. The first registration closes it.
pub struct PasskeyEnrollOpen;

#[async_trait::async_trait]
impl Endpoint for PasskeyEnrollOpen {
    async fn invoke(&self, inv: &Invocation<'_>) -> Result<Representation> {
        if !inv.capability.allows(CAP_PASSKEY_ENROLL) {
            return Err(Error::Denied(format!(
                "opening enrollment requires `{CAP_PASSKEY_ENROLL}`"
            )));
        }
        let until = now_secs() + ENROLL_WINDOW_SECONDS;
        // Owner-only and whole (ledger #850): `fs::write` left it 0664 under umask 002, and a
        // window that expires unused stays on disk, where anyone who can write it reopens it.
        write_atomic(&enroll_window_path(), until.to_string().as_bytes())
            .map_err(|e| Error::Endpoint(format!("cannot open the enrollment window: {e}")))?;
        Ok(Representation::new(
            ReprType::new("text/plain").with_param("charset", "utf-8"),
            format!("enrollment open for {ENROLL_WINDOW_SECONDS}s — register your passkey now\n")
                .into_bytes(),
        ))
    }
    fn name(&self) -> &str {
        "passkey-enroll-open"
    }
    fn describe(&self) -> Description {
        Description::new("passkey-enroll-open")
            .title("Open a passkey enrollment window")
            .summary("Opens a short window during which one passkey may be registered. Run from the box.")
            .action(
                ActionSpec::new(Verb::Sink)
                    .summary("open the window")
                    .output("text/plain; charset=utf-8")
                    .requires(CAP_PASSKEY_ENROLL),
            )
            .output("text/plain; charset=utf-8")
    }
}

/// Whether an enrollment window opened at the box is live. Fails CLOSED (ledger #850): the
/// window file is judged with the credential store's rule, and its directory with
/// [`guard_directory`], so a file someone else could have written or a workspace others can
/// write keeps enrollment closed (said once per check on stderr), never open.
fn enrollment_open() -> bool {
    match enroll_window() {
        Ok(until) => until.is_some_and(|u| u > now_secs()),
        Err(detail) => {
            eprintln!("ikigai passkey: enrollment stays CLOSED: {detail}");
            false
        }
    }
}

/// The window's closing time, `Ok(None)` when no window file exists (or it does not parse, which
/// is a closed window, as before), and `Err` naming the file or directory when it is not trusted.
fn enroll_window() -> std::result::Result<Option<i64>, String> {
    use std::io::Read;
    let path = enroll_window_path();
    let p = path.display();
    let mut file = match std::fs::File::open(&path) {
        Ok(file) => file,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
        Err(e) => return Err(format!("{p} is present but unreadable: {e}")),
    };
    guard_directory(&store_root())?;
    // On the handle: what is judged is what is read. Readable-only is tightened; a file someone
    // else could have written is refused and left as it is, because its timestamp is theirs.
    guard_permissions(&path, &file, Remedy::Remove)?;
    let mut text = String::new();
    file.read_to_string(&mut text)
        .map_err(|e| format!("{p} is present but unreadable: {e}"))?;
    Ok(text.trim().parse::<i64>().ok())
}

fn close_enrollment() {
    let _ = std::fs::remove_file(enroll_window_path());
}

// =====================================================================================
// urn:passkey:register — GET shows the enrol page, POST stores the credential.
// =====================================================================================

/// The enrollment endpoint. GET renders the registration page (the glue-JS runs the WebAuthn
/// create ceremony); POST accepts `{id, spki}` — base64url of the credentialId and the SPKI public
/// key — and stores it, but only while a window opened at the box is live. The first registration
/// closes the window.
pub struct PasskeyRegister;

#[async_trait::async_trait]
impl Endpoint for PasskeyRegister {
    async fn invoke(&self, inv: &Invocation<'_>) -> Result<Representation> {
        match inv.request.verb {
            Verb::Source => {
                if relying_party().is_none() {
                    return Ok(page("Passkeys are not configured", NOT_CONFIGURED_BODY));
                }
                if !enrollment_open() {
                    return Ok(page(
                        "Enrollment closed",
                        "<p>Open a window at the box first: <code>ikigai -c 'sink \
                         urn:passkey:enroll-open'</code>, then reload.</p>",
                    ));
                }
                Ok(page("Register a passkey", REGISTER_PAGE_BODY))
            }
            Verb::Sink => {
                // Registering binds a credential to a relying party; with none configured there
                // is nothing correct to bind it to (the old default silently chose production).
                if relying_party().is_none() {
                    return Err(Error::Denied(
                        "this edge has no passkey relying party configured".to_string(),
                    ));
                }
                if !enrollment_open() {
                    return Err(Error::Denied(
                        "no enrollment window is open — open one at the box first".to_string(),
                    ));
                }
                let (id_b64, spki_b64) = (param(inv, "id"), param(inv, "spki"));
                if id_b64.is_empty() || spki_b64.is_empty() {
                    return Err(Error::InvalidArgument {
                        name: "id/spki".to_string(),
                        detail: "both the credential id and the SPKI public key are required"
                            .to_string(),
                    });
                }
                // Validate the key parses as an ES256 SPKI before we trust it.
                let spki = b64()
                    .decode(&spki_b64)
                    .map_err(|_| Error::InvalidArgument {
                        name: "spki".to_string(),
                        detail: "not base64url".to_string(),
                    })?;
                ikigai_passkey::RegisteredCredential::from_spki_der(b"probe".to_vec(), &spki, 0)
                    .map_err(|e| Error::InvalidArgument {
                        name: "spki".to_string(),
                        detail: format!("not a usable public key: {e}"),
                    })?;

                let held = credential_lock();
                // A store that is present but unreadable (or that someone else could have
                // written) is not overwritten from the public face: the person at the box
                // repairs or removes it, then enrolls again.
                let mut creds = load_credentials(&held).map_err(|detail| {
                    store_unreadable(&detail);
                    Error::Endpoint(
                        "the passkey store on this edge is unreadable; repair or remove it at \
                         the box, then enroll again"
                            .to_string(),
                    )
                })?;
                // Replace any existing entry with this id rather than duplicate it.
                creds.retain(|c| c.id != id_b64);
                creds.push(StoredCredential {
                    id: id_b64,
                    spki: spki_b64,
                    sign_count: 0,
                });
                save_credentials(&creds)?;
                close_enrollment();
                Ok(page(
                    "Passkey registered",
                    "<p>Done. Decision links now ask for your passkey before they act.</p>",
                ))
            }
            other => Err(Error::Endpoint(format!(
                "register is GET to show or POST to store, not {other:?}"
            ))),
        }
    }
    fn name(&self) -> &str {
        "passkey-register"
    }
    fn describe(&self) -> Description {
        Description::new("passkey-register")
            .title("Register a passkey")
            .summary("GET shows the enrolment page; POST stores a credential while an enrollment window is open.")
            .action(
                ActionSpec::new(Verb::Source)
                    .summary("show the enrolment page")
                    .output("text/html; charset=utf-8"),
            )
            .action(
                ActionSpec::new(Verb::Sink)
                    .summary("store a credential (window must be open)")
                    .output("text/html; charset=utf-8"),
            )
            .output("text/html; charset=utf-8")
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use ikigai_core::{ArgRef, Capability, Iri, Kernel, Request};
    use p256::ecdsa::{signature::Signer, Signature, SigningKey, VerifyingKey};
    use p256::pkcs8::EncodePublicKey;
    use sha2::{Digest, Sha256};

    thread_local! {
        static TEST_ROOT: std::cell::RefCell<Option<std::path::PathBuf>> =
            const { std::cell::RefCell::new(None) };
        static TEST_RP: std::cell::RefCell<Option<RelyingParty>> =
            const { std::cell::RefCell::new(None) };
    }

    /// The current thread's override root, if a test set one. `store_root()` consults this.
    pub(super) fn test_root() -> Option<std::path::PathBuf> {
        TEST_ROOT.with(|r| r.borrow().clone())
    }

    /// The current thread's relying party. `relying_party()` reads ONLY this under test, so the
    /// unconfigured case is reachable without racing the configured tests.
    pub(super) fn test_rp() -> Option<RelyingParty> {
        TEST_RP.with(|r| r.borrow().clone())
    }

    const RP_ID: &str = "edge.test";
    const ORIGIN: &str = "https://edge.test";

    fn test_relying_party() -> RelyingParty {
        RelyingParty::new(RP_ID, None).unwrap()
    }

    fn unconfigure() {
        TEST_RP.with(|r| *r.borrow_mut() = None);
    }

    // Give this test its own workspace root — set on THIS thread only, so parallel tests never
    // collide on the credential/window files (a global env var would race across them) — and a
    // configured relying party, which a test that wants none removes with `unconfigure`.
    fn isolate(name: &str) {
        let dir = std::env::temp_dir().join(format!("ikigai-passkey-ep-{name}"));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        // Private whatever the umask: a workspace others can write is refused (ledger #850).
        #[cfg(unix)]
        std::fs::set_permissions(&dir, std::os::unix::fs::PermissionsExt::from_mode(0o700))
            .unwrap();
        TEST_ROOT.with(|r| *r.borrow_mut() = Some(dir));
        TEST_RP.with(|r| *r.borrow_mut() = Some(test_relying_party()));
    }

    /// A stand-in authenticator: a fixed P-256 key that signs assertions as a device would.
    struct Device {
        key: SigningKey,
    }
    impl Device {
        fn new() -> Self {
            Self {
                key: SigningKey::from_slice(&[0x33u8; 32]).unwrap(),
            }
        }
        fn spki_b64(&self) -> String {
            let der = VerifyingKey::from(&self.key).to_public_key_der().unwrap();
            b64().encode(der.as_bytes())
        }
        fn register(&self) {
            let creds = vec![StoredCredential {
                id: b64().encode(b"cred-1"),
                spki: self.spki_b64(),
                sign_count: 0,
            }];
            save_credentials(&creds).unwrap();
        }
        /// Build the four base64url fields for a POST body, over the given challenge. `count` is
        /// the signature counter — a real authenticator advances it every assertion.
        fn assert_fields(&self, challenge: &str, flags: u8, count: u32) -> String {
            let client = format!(
                r#"{{"type":"webauthn.get","challenge":"{challenge}","origin":"{ORIGIN}"}}"#
            )
            .into_bytes();
            let mut auth = Sha256::digest(RP_ID.as_bytes()).to_vec();
            auth.push(flags);
            auth.extend_from_slice(&count.to_be_bytes());
            let mut msg = auth.clone();
            msg.extend_from_slice(&Sha256::digest(&client));
            let sig: Signature = self.key.sign(&msg);
            format!(
                "pk_id={}&pk_auth={}&pk_client={}&pk_sig={}",
                b64().encode(b"cred-1"),
                b64().encode(&auth),
                b64().encode(&client),
                b64().encode(sig.to_der().as_bytes()),
            )
        }
    }

    /// A minimal invocation carrying a urlencoded body as `content` (how a POST arrives).
    fn post_inv(body: &str) -> (Kernel, Request) {
        let kernel = Kernel::new(std::sync::Arc::new(ikigai_core::EndpointSpace::new()));
        let req = Request::new(Verb::Sink, Iri::parse("urn:x").unwrap())
            .with_arg("content", ArgRef::Inline(body.as_bytes().to_vec()));
        (kernel, req)
    }

    fn run_gate(body: &str) -> Result<()> {
        // require_passkey only reads params off the invocation; drive it through a tiny endpoint.
        struct Gate;
        #[async_trait::async_trait]
        impl Endpoint for Gate {
            async fn invoke(&self, inv: &Invocation<'_>) -> Result<Representation> {
                require_passkey(inv)?;
                Ok(Representation::new(
                    ReprType::new("text/plain"),
                    b"ok".to_vec(),
                ))
            }
            fn name(&self) -> &str {
                "gate"
            }
            fn describe(&self) -> Description {
                Description::new("gate").verb(Verb::Sink)
            }
        }
        let kernel = Kernel::new(std::sync::Arc::new(
            ikigai_core::EndpointSpace::new().bind(ikigai_core::Exact::new("urn:x"), Gate),
        ));
        let (_k, req) = post_inv(body);
        futures::executor::block_on(kernel.issue(req, &Capability::root())).map(|_| ())
    }

    #[test]
    fn the_gate_is_inert_until_a_credential_is_enrolled() {
        isolate("inert");
        // No credential file: any POST — even one with no passkey fields — passes.
        assert!(run_gate("id=abc&exp=1").is_ok());
    }

    #[test]
    fn a_valid_assertion_passes_the_gate_and_a_forged_one_does_not() {
        isolate("valid");
        let d = Device::new();
        d.register();
        let challenge = issue_challenge().unwrap();
        let body = d.assert_fields(&challenge, 0x05, 1); // UP | UV, counter 1
        assert!(run_gate(&body).is_ok(), "a valid assertion should pass");

        // A second ceremony (fresh challenge, advanced counter) also passes...
        let challenge2 = issue_challenge().unwrap();
        let good = d.assert_fields(&challenge2, 0x05, 2);
        assert!(run_gate(&good).is_ok());
        // ...but replaying that exact assertion is refused — the challenge was consumed.
        assert!(run_gate(&good).is_err(), "the challenge is single-use");
    }

    #[test]
    fn an_enrolled_gate_refuses_a_post_with_no_assertion() {
        isolate("missing");
        Device::new().register();
        assert!(
            run_gate("id=abc&exp=1").is_err(),
            "enrolled + no passkey = refused"
        );
    }

    #[test]
    fn a_forged_signature_is_refused() {
        isolate("forged");
        let real = Device::new();
        real.register();
        // A different key signs, but the assertion claims the registered credential id.
        let imposter = Device {
            key: SigningKey::from_slice(&[0x44u8; 32]).unwrap(),
        };
        let challenge = issue_challenge().unwrap();
        let body = imposter.assert_fields(&challenge, 0x05, 1);
        assert!(
            run_gate(&body).is_err(),
            "a foreign signature must be refused"
        );
    }

    #[test]
    fn a_never_issued_challenge_is_refused() {
        isolate("nochallenge");
        let d = Device::new();
        d.register();
        // Craft an assertion over a challenge that was never issued here.
        let body = d.assert_fields("bmV2ZXItaXNzdWVk", 0x05, 1);
        assert!(
            run_gate(&body).is_err(),
            "an unissued challenge must be refused"
        );
    }

    #[test]
    fn challenges_are_single_use_and_expire() {
        isolate("challenge");
        let c = issue_challenge().unwrap();
        assert!(consume_challenge(&c), "a fresh challenge consumes once");
        assert!(!consume_challenge(&c), "and not twice");
        assert!(
            !consume_challenge("never-issued"),
            "unknown challenge is refused"
        );
    }

    thread_local! {
        static AFTER_VERIFY: std::cell::RefCell<Option<Box<dyn FnOnce()>>> =
            const { std::cell::RefCell::new(None) };
    }

    /// The seam between a successful verification and the counter write-back: a test parks a
    /// closure here to interleave a second request at exactly the point the race lives.
    pub(super) fn after_verify() {
        if let Some(hook) = AFTER_VERIFY.with(|h| h.borrow_mut().take()) {
            hook();
        }
    }

    fn stored_count() -> u32 {
        let bytes = std::fs::read(credentials_path()).unwrap();
        let creds: Vec<StoredCredential> = serde_json::from_slice(&bytes).unwrap();
        creds[0].sign_count
    }

    #[test]
    fn a_corrupt_credential_file_fails_closed() {
        isolate("corrupt");
        Device::new().register();
        // Truncate the store mid-document, as a crash during a non-atomic write would.
        let full = std::fs::read(credentials_path()).unwrap();
        std::fs::write(credentials_path(), &full[..full.len() / 2]).unwrap();
        assert!(
            run_gate("id=abc&exp=1").is_err(),
            "a present but unparsable credential store must refuse, not read as `not enrolled`"
        );
        // An empty (zero-byte) file is present too: still refused.
        std::fs::write(credentials_path(), b"").unwrap();
        assert!(
            run_gate("id=abc&exp=1").is_err(),
            "a zero-byte store refuses"
        );
    }

    #[cfg(unix)]
    #[test]
    fn the_credential_write_replaces_the_file_rather_than_rewriting_it_in_place() {
        use std::os::unix::fs::{MetadataExt, PermissionsExt};
        isolate("atomic");
        let d = Device::new();
        d.register();
        let before = std::fs::metadata(credentials_path()).unwrap().ino();
        d.register();
        let meta = std::fs::metadata(credentials_path()).unwrap();
        // An in-place write (truncate, then write) keeps the inode, so a reader or a crash
        // between the two sees a truncated file. Temp + rename swaps in a new inode whole.
        assert_ne!(
            before,
            meta.ino(),
            "the store must be replaced by rename, not truncated and rewritten in place"
        );
        assert_eq!(meta.permissions().mode() & 0o777, 0o600, "owner-only");
        // And no temp file is left behind beside it.
        let leftovers: Vec<_> = std::fs::read_dir(store_root())
            .unwrap()
            .filter_map(|e| e.ok())
            .map(|e| e.file_name().to_string_lossy().into_owned())
            .filter(|n| n != "passkey-credentials.json")
            .collect();
        assert!(leftovers.is_empty(), "stray files: {leftovers:?}");
    }

    #[cfg(unix)]
    fn set_mode(mode: u32) {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(credentials_path(), std::fs::Permissions::from_mode(mode))
            .unwrap();
    }

    #[cfg(unix)]
    fn mode() -> u32 {
        use std::os::unix::fs::PermissionsExt;
        std::fs::metadata(credentials_path())
            .unwrap()
            .permissions()
            .mode()
            & 0o777
    }

    /// Ledger #828, the reproduction: a file enrolled under 0.1.38 (`fs::write`, umask 002) is
    /// 0664, and a platform passkey keeps its counter at 0, so the 0600 atomic save never runs.
    /// Before the fix the gate trusted that file and left it 0664 for good; this test asserted
    /// exactly that against 0.1.39 and passed, then failed once the check landed.
    #[cfg(unix)]
    #[test]
    fn a_group_writable_store_refuses_every_face_and_is_left_for_a_person_to_check() {
        isolate("loose-writable");
        let d = Device::new();
        d.register();
        set_mode(0o664);
        let challenge = issue_challenge().unwrap();
        let body = d.assert_fields(&challenge, 0x05, 0); // a platform passkey: counter stays 0
        assert!(
            run_gate(&body).is_err(),
            "a store others could have written is not trusted, even with a valid assertion"
        );
        assert!(
            call(
                "urn:passkey:challenge",
                PasskeyChallenge,
                Verb::Source,
                None
            )
            .is_err(),
            "the challenge refuses too"
        );
        open_window();
        let reg = format!(
            "id={}&spki={}",
            b64().encode(b"cred-2"),
            Device::new().spki_b64()
        );
        assert!(
            call(
                "urn:passkey:register",
                PasskeyRegister,
                Verb::Sink,
                Some(&reg)
            )
            .is_err(),
            "registration does not launder a store someone else could have written"
        );
        assert!(is_enrolled(), "an untrusted store counts as armed");
        assert!(preflight().is_err(), "and a serving door refuses to start");
        // Not silently fixed: tightening would trust whatever someone else wrote.
        assert_eq!(mode(), 0o664);
        let detail = {
            let held = credential_lock();
            load_credentials(&held).err().unwrap()
        };
        let path = credentials_path();
        assert!(
            detail.contains(&format!("`chmod 600 {}`", path.display())),
            "the refusal names the exact fix: {detail}"
        );
        assert!(detail.contains("0664"), "and the mode it found: {detail}");

        // World-writable alone is refused the same way.
        set_mode(0o602);
        assert!(preflight().is_err());

        // Once the person at the box has fixed it, the very same assertion's successor passes.
        set_mode(0o600);
        let challenge = issue_challenge().unwrap();
        assert!(run_gate(&d.assert_fields(&challenge, 0x05, 0)).is_ok());
        assert!(preflight().is_ok());
    }

    #[cfg(unix)]
    #[test]
    fn a_store_others_can_only_read_is_tightened_on_load() {
        isolate("loose-readable");
        let d = Device::new();
        d.register();
        set_mode(0o644);
        let challenge = issue_challenge().unwrap();
        assert!(
            run_gate(&d.assert_fields(&challenge, 0x05, 0)).is_ok(),
            "readable-only discloses public keys and nothing else: the gate keeps working"
        );
        assert_eq!(mode(), 0o600, "a counter-0 sign-in tightened it");

        // Every other load path tightens as well.
        set_mode(0o640);
        assert!(call(
            "urn:passkey:challenge",
            PasskeyChallenge,
            Verb::Source,
            None
        )
        .is_ok());
        assert_eq!(mode(), 0o600, "the challenge tightened it");
        set_mode(0o604);
        assert!(preflight().is_ok());
        assert_eq!(mode(), 0o600, "startup tightened it");
        set_mode(0o644);
        assert!(is_enrolled());
        assert_eq!(mode(), 0o600, "is_enrolled tightened it");
    }

    #[test]
    fn permissions_are_judged_on_writers_first_then_readers() {
        let me = 501;
        assert_eq!(judge_permissions(0o100600, me, me), Permission::Private);
        assert_eq!(judge_permissions(0o100400, me, me), Permission::Private);
        // Owner execute or setuid-style bits are not about who else can write.
        assert_eq!(judge_permissions(0o100700, me, me), Permission::Private);
        for readable in [0o100640, 0o100604, 0o100644, 0o100440] {
            assert_eq!(
                judge_permissions(readable, me, me),
                Permission::Tighten,
                "{readable:o}"
            );
        }
        for writable in [0o100620, 0o100602, 0o100664, 0o100666, 0o100622] {
            assert!(
                matches!(judge_permissions(writable, me, me), Permission::Refuse(_)),
                "{writable:o}"
            );
        }
        // Another user's file is refused even at 0600: its owner can write it, and only a
        // swap through a writable directory (or a hand edit) puts one there.
        match judge_permissions(0o100600, 0, me) {
            Permission::Refuse(why) => assert!(why.contains("uid 0"), "{why}"),
            other => panic!("a foreign owner must refuse, got {other:?}"),
        }
    }

    #[test]
    fn an_absent_store_passes_preflight() {
        isolate("preflight-absent");
        assert!(
            preflight().is_ok(),
            "not enrolled is not a reason to refuse to start"
        );
        assert!(
            !credentials_path().exists(),
            "and preflight creates nothing"
        );
    }

    #[test]
    fn interleaved_assertions_never_lower_the_stored_counter() {
        isolate("race");
        let root = test_root().unwrap();
        let d = Device::new();
        d.register();
        let c_low = issue_challenge().unwrap();
        let c_high = issue_challenge().unwrap();
        let low = d.assert_fields(&c_low, 0x05, 2);
        let high = d.assert_fields(&c_high, 0x05, 3);

        // Request A (counter 2) has verified and is about to write back; request B (counter 3)
        // runs now on another thread. Without a lock B completes inside A's window and A then
        // writes its stale copy over B's; with one, B waits for A and loads A's result.
        let (done_tx, done_rx) = std::sync::mpsc::channel();
        let b = std::sync::Arc::new(std::sync::Mutex::new(None));
        let b_slot = b.clone();
        AFTER_VERIFY.with(|h| {
            *h.borrow_mut() = Some(Box::new(move || {
                let handle = std::thread::spawn(move || {
                    TEST_ROOT.with(|r| *r.borrow_mut() = Some(root));
                    TEST_RP.with(|r| *r.borrow_mut() = Some(test_relying_party()));
                    let r = run_gate(&high);
                    let _ = done_tx.send(());
                    r
                });
                // Give B the chance to finish inside A's window (it cannot, under a lock).
                let _ = done_rx.recv_timeout(std::time::Duration::from_millis(300));
                *b_slot.lock().unwrap() = Some(handle);
            }))
        });
        assert!(run_gate(&low).is_ok(), "A's assertion is valid");
        let handle = b.lock().unwrap().take().expect("the hook ran");
        assert!(handle.join().unwrap().is_ok(), "B's assertion is valid");
        assert_eq!(
            stored_count(),
            3,
            "the stored counter must be the highest seen, never a stale write-back"
        );
    }

    /// Issue `verb` at `iri` against a kernel that binds only `endpoint` there.
    fn call(
        iri: &str,
        endpoint: impl Endpoint + 'static,
        verb: Verb,
        body: Option<&str>,
    ) -> Result<Representation> {
        let kernel = Kernel::new(std::sync::Arc::new(
            ikigai_core::EndpointSpace::new().bind(ikigai_core::Exact::new(iri), endpoint),
        ));
        let mut req = Request::new(verb, Iri::parse(iri).unwrap());
        if let Some(body) = body {
            req = req.with_arg("content", ArgRef::Inline(body.as_bytes().to_vec()));
        }
        futures::executor::block_on(kernel.issue(req, &Capability::root()))
    }

    fn open_window() {
        write_atomic(
            &enroll_window_path(),
            (now_secs() + 60).to_string().as_bytes(),
        )
        .unwrap();
    }

    #[test]
    fn a_corrupt_store_errors_the_challenge_and_is_not_overwritten_by_registration() {
        isolate("corrupt-faces");
        std::fs::write(credentials_path(), b"[{\"id\":").unwrap();
        assert!(
            call(
                "urn:passkey:challenge",
                PasskeyChallenge,
                Verb::Source,
                None
            )
            .is_err(),
            "the page must not be told `not enrolled` and submit token-only"
        );
        open_window();
        let body = format!(
            "id={}&spki={}",
            b64().encode(b"cred-2"),
            Device::new().spki_b64()
        );
        assert!(
            call(
                "urn:passkey:register",
                PasskeyRegister,
                Verb::Sink,
                Some(&body)
            )
            .is_err(),
            "registration does not paper over a broken store from the public face"
        );
        assert_eq!(std::fs::read(credentials_path()).unwrap(), b"[{\"id\":");
        assert!(is_enrolled(), "a broken store counts as armed");
    }

    #[test]
    fn an_enrolled_gate_with_no_relying_party_refuses_everything() {
        isolate("no-rp-enrolled");
        let d = Device::new();
        d.register();
        let challenge = issue_challenge().unwrap();
        let body = d.assert_fields(&challenge, 0x05, 1);
        unconfigure();
        assert!(run_gate(&body).is_err(), "no RP to check against = refuse");
        assert!(
            call(
                "urn:passkey:challenge",
                PasskeyChallenge,
                Verb::Source,
                None
            )
            .is_err(),
            "and the challenge says so rather than naming no RP"
        );
    }

    #[test]
    fn an_unconfigured_edge_with_nothing_enrolled_stays_inert() {
        isolate("no-rp-inert");
        unconfigure();
        assert!(
            run_gate("id=abc&exp=1").is_ok(),
            "deploying cannot brick the links"
        );
        let rep = call(
            "urn:passkey:challenge",
            PasskeyChallenge,
            Verb::Source,
            None,
        )
        .unwrap();
        let v: serde_json::Value = serde_json::from_slice(&rep.bytes).unwrap();
        assert_eq!(v["enrolled"], false);
        assert!(
            v["rpId"].is_null(),
            "no RP is reported as none, never a default"
        );
    }

    #[test]
    fn registration_needs_a_relying_party() {
        isolate("no-rp-register");
        open_window();
        let body = format!(
            "id={}&spki={}",
            b64().encode(b"cred-1"),
            Device::new().spki_b64()
        );
        unconfigure();
        assert!(
            call(
                "urn:passkey:register",
                PasskeyRegister,
                Verb::Sink,
                Some(&body)
            )
            .is_err(),
            "nothing to bind a credential to"
        );
        assert!(!credentials_path().exists());
        let page = call("urn:passkey:register", PasskeyRegister, Verb::Source, None).unwrap();
        assert!(String::from_utf8_lossy(&page.bytes).contains("--passkey-rp-id"));

        TEST_RP.with(|r| *r.borrow_mut() = Some(test_relying_party()));
        assert!(call(
            "urn:passkey:register",
            PasskeyRegister,
            Verb::Sink,
            Some(&body)
        )
        .is_ok());
        assert!(is_enrolled());
    }

    #[test]
    fn a_challenge_expires_on_the_monotonic_clock() {
        isolate("ttl");
        let t0 = monotonic_now();
        let fresh = issue_challenge_at(t0).unwrap();
        assert!(consume_challenge_at(
            &fresh,
            t0 + CHALLENGE_TTL - Duration::from_secs(1)
        ));
        let stale = issue_challenge_at(t0).unwrap();
        assert!(
            !consume_challenge_at(&stale, t0 + CHALLENGE_TTL),
            "a challenge is dead at its TTL"
        );
    }

    #[test]
    fn enrollment_window_gates_registration() {
        isolate("enroll");
        assert!(!enrollment_open(), "closed by default");
        // Opening requires the cap.
        let kernel = Kernel::new(std::sync::Arc::new(ikigai_core::EndpointSpace::new().bind(
            ikigai_core::Exact::new("urn:passkey:enroll-open"),
            PasskeyEnrollOpen,
        )));
        let open = |cap: &Capability| {
            futures::executor::block_on(kernel.issue(
                Request::new(Verb::Sink, Iri::parse("urn:passkey:enroll-open").unwrap()),
                cap,
            ))
        };
        assert!(
            open(&Capability::scoped(Vec::<String>::new())).is_err(),
            "no cap, no open"
        );
        assert!(open(&Capability::root()).is_ok(), "root opens it");
        assert!(enrollment_open(), "now open");
    }

    #[cfg(unix)]
    fn chmod(path: &std::path::Path, mode: u32) {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode)).unwrap();
    }

    #[cfg(unix)]
    fn mode_of(path: &std::path::Path) -> u32 {
        use std::os::unix::fs::PermissionsExt;
        std::fs::metadata(path).unwrap().permissions().mode() & 0o777
    }

    /// Whether a registration through the PUBLIC face (no enroll capability) stored anything.
    fn public_registration_succeeds() -> bool {
        let reg = format!(
            "id={}&spki={}",
            b64().encode(b"intruder"),
            Device::new().spki_b64()
        );
        call(
            "urn:passkey:register",
            PasskeyRegister,
            Verb::Sink,
            Some(&reg),
        )
        .is_ok()
    }

    /// ★ Ledger #850, the reproduction. `urn:passkey:enroll-open` wrote the window file with
    /// `fs::write`, so under umask 002 it is 0664, and a window that expires unused leaves it
    /// behind. Anyone in the group can then write a future timestamp into it and register a
    /// credential through the public face, without `urn:cap:passkey:enroll`. On main this test
    /// failed at its first assertion: `enrollment_open()` read the file with no mode check.
    #[cfg(unix)]
    #[test]
    fn an_enroll_file_others_could_have_written_keeps_enrollment_closed() {
        isolate("enroll-writable");
        for loose in [0o664, 0o602, 0o620] {
            open_window();
            chmod(&enroll_window_path(), loose);
            assert!(
                !enrollment_open(),
                "a window file others could have written is not a window ({loose:o})"
            );
            assert!(
                !public_registration_succeeds(),
                "nothing registers through it ({loose:o})"
            );
            assert!(!is_enrolled(), "and nothing was stored ({loose:o})");
            // Not silently fixed: tightening it would trust a timestamp someone else wrote.
            assert_eq!(mode_of(&enroll_window_path()), loose);
        }
        let refusal = enroll_window().expect_err("an untrusted window is an error, not absence");
        assert!(
            refusal.contains(&format!("`rm {}`", enroll_window_path().display())),
            "the refusal says to remove it, never to chmod a planted timestamp: {refusal}"
        );
        // Once fixed at the box, the same file is a window again.
        chmod(&enroll_window_path(), 0o600);
        assert!(enrollment_open());
    }

    #[test]
    fn the_workspace_directory_is_judged_on_writers_and_its_owner() {
        let me = 501;
        for private in [0o40700, 0o40755, 0o40750, 0o40711] {
            assert_eq!(judge_directory(private, me, me), None, "{private:o}");
        }
        for writable in [0o40775, 0o40770, 0o40757, 0o41777, 0o40730] {
            assert!(judge_directory(writable, me, me).is_some(), "{writable:o}");
        }
        let why = judge_directory(0o40700, 0, me).expect("a foreign owner refuses");
        assert!(why.contains("uid 0"), "{why}");
    }

    /// The other half of #850: a workspace DIRECTORY others can write lets them create or swap
    /// any file in it, so nothing in it is trusted: not the window, not the credential store.
    #[cfg(unix)]
    #[test]
    fn a_workspace_others_can_write_trusts_nothing_in_it() {
        isolate("workspace-writable");
        let root = test_root().unwrap();
        let d = Device::new();
        d.register();
        open_window();
        chmod(&root, 0o775);
        assert!(!enrollment_open(), "the window is not trusted");
        assert!(!public_registration_succeeds(), "so nothing registers");
        let challenge = issue_challenge().unwrap();
        assert!(
            run_gate(&d.assert_fields(&challenge, 0x05, 0)).is_err(),
            "the store in it is not trusted either, even with a valid assertion"
        );
        assert!(is_enrolled(), "an untrusted store counts as armed");
        let refusal = preflight().expect_err("a serving door refuses to start");
        assert!(
            refusal.contains(&root.display().to_string()) && refusal.contains("0775"),
            "the refusal names the directory and its mode: {refusal}"
        );
        assert!(
            refusal.contains(&format!("`chmod go-w {}`", root.display())),
            "and the exact fix: {refusal}"
        );
        // World-writable, sticky or not, is refused the same way.
        chmod(&root, 0o1777);
        assert!(preflight().is_err());
        assert!(!enrollment_open());

        // Once a person at the box has fixed the directory, everything in it is trusted again.
        chmod(&root, 0o755);
        assert!(preflight().is_ok());
        assert!(enrollment_open());
        let challenge = issue_challenge().unwrap();
        assert!(run_gate(&d.assert_fields(&challenge, 0x05, 0)).is_ok());
    }

    /// A window file others can only read discloses a timestamp: it is tightened, not refused.
    #[cfg(unix)]
    #[test]
    fn an_enroll_file_others_can_only_read_is_tightened() {
        isolate("enroll-readable");
        open_window();
        chmod(&enroll_window_path(), 0o644);
        assert!(enrollment_open());
        assert_eq!(mode_of(&enroll_window_path()), 0o600);
    }

    /// Opening a window writes it owner-only, whatever the umask, so a window that expires
    /// unused never leaves behind a file others could reopen.
    #[cfg(unix)]
    #[test]
    fn opening_a_window_writes_it_owner_only() {
        isolate("enroll-mode");
        let kernel = Kernel::new(std::sync::Arc::new(ikigai_core::EndpointSpace::new().bind(
            ikigai_core::Exact::new("urn:passkey:enroll-open"),
            PasskeyEnrollOpen,
        )));
        futures::executor::block_on(kernel.issue(
            Request::new(Verb::Sink, Iri::parse("urn:passkey:enroll-open").unwrap()),
            &Capability::root(),
        ))
        .unwrap();
        assert_eq!(mode_of(&enroll_window_path()), 0o600);
        assert!(enrollment_open());
    }
}