car-sync 0.50.0

Multi-device sync core for Common Agent Runtime — replica-tagged append-only oplog + deterministic CRDT fold
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
//! End-to-end payload encryption boundary (slice B6 of
//! `docs/proposals/multi-device-sync.md`, §"Transport: Parslee-hosted relay,
//! E2E for personal scope").
//!
//! The proposal's trust posture: **the relay is a dumb, untrusted ordered-log
//! store.** Personal-scope payloads are encrypted end-to-end, always; the
//! relay stores only ciphertext and "can route and dedup on `op_id` and `hlc`
//! (which stay cleartext) but **cannot read conversations, memory, or
//! secrets**." This module is the encrypt/decrypt boundary that realizes it.
//!
//! ## The design that keeps the shipped oplog intact
//!
//! An op's `op_id` is the SHA-256 content address over `device_id ‖ seq ‖ prev
//! ‖ hlc ‖ scope ‖ surface ‖ canonical(payload)` (see [`crate::oplog`]). To
//! keep `op_id`/`seq`/`prev`/`hlc`/`scope`/`surface` **cleartext metadata** —
//! exactly what B3's relay chain-verification and dedup rely on — the
//! encryption is applied to the **payload only, at authoring time**: a device
//! that wants E2E authors its op with `cipher.encrypt(plaintext)` as the
//! payload, so the canonical op the whole system carries is ciphertext-native.
//! The chain hashes over ciphertext, [`crate::oplog::verify_log`] verifies it,
//! and the relay sees only the [`Envelope`]. A peer holding the same key
//! recovers the plaintext with [`PayloadCipher::decrypt`]. No change to the
//! `OpRecord` shape, the journal, the relay, or the fold — the ciphertext is
//! just a `serde_json::Value` like any other payload.
//!
//! ## Real crypto, not a placeholder
//!
//! [`LocalKeyCipher`] is a genuine AEAD: **ChaCha20-Poly1305** with a random
//! 96-bit nonce per op (RustCrypto `chacha20poly1305`). Confidentiality AND
//! integrity — a tampered ciphertext fails the Poly1305 tag and
//! [`PayloadCipher::decrypt`] returns [`CryptoError::Decrypt`], never silently
//! wrong plaintext. The key is a user-held 256-bit secret
//! ([`LocalKeyCipher::load_or_generate`] persists it `0600` under
//! `~/.car/sync/`), never transmitted — the proposal's "the key is user-held,
//! derived at Parslee login, never transmitted."
//!
//! ## What's wired, what remains
//!
//! Shipped + tested here and in the session:
//!
//! - **Decrypt-before-fold** — [`crate::session::SyncSession::with_key_provider`]
//!   encrypts each payload at `append` (ciphertext-native, `op_id` over
//!   ciphertext) and decrypts at `state()` *after* the chain verifies and
//!   *before* the fold groups on `payload["id"]`/`fold_key`. Op identity stays
//!   the cleartext-metadata `op_id`.
//! - **Login-derived key distribution** — [`DerivedKeyProvider`] HKDF-derives
//!   per-audience keys from one master; [`DerivedKeyProvider::from_passphrase`]
//!   is the zero-knowledge cross-device source (same passphrase → same keys on
//!   every device, never transmitted). [`LocalKeyCipher`] remains the raw
//!   single-key reference. Per-audience isolation via [`encryption_audience`].
//! - **Checkpoints under E2E** — [`crate::session::SyncSession::publish_checkpoint`]
//!   is guarded off under a key provider: a ciphertext-folded checkpoint would
//!   form an inconsistent decrypt base, and a cleartext one would leak. The
//!   encrypted op log is retained and cold bootstrap replays it.
//!
//! - **Client-side org-key agreement (authenticated)** — [`wrap_org_key`] /
//!   [`unwrap_org_key`] (ECIES over X25519, [`derive_x25519_identity`]) share ONE
//!   org master key `K_org` across all members so org-scoped ops are mutually
//!   readable, while the relay/platform never sees `K_org`. Each wrap is SIGNED by
//!   the publisher's Ed25519 identity ([`derive_ed25519_identity`]) and unwrap
//!   REFUSES any wrap not signed by a caller-trusted holder — closing the
//!   key-substitution hole. The directory ([`crate::org_key_directory`]),
//!   transport, and the consuming [`crate::org_key_provider::OrgAwareKeyProvider`]
//!   are built on top. It all stays inert; the `login_secret → identity` entropy
//!   dependency MUST be reviewed by a cryptographer before production (see the
//!   security notes above the identity functions).
//!
//! Remaining before activation: **per-scope encrypted checkpoint push** — a
//! whole-chain checkpoint mixes `Personal` + `Shared{org}` audiences, so it must
//! be split per scope key before it can be pushed to an untrusted relay to
//! restore relay-side GC; the oplog **epoch field** + fold key-selection (so old
//! epochs decrypt after **rotation**); the out-of-band `org → K_org` **resolver**
//! that wires `OrgAwareKeyProvider` into the subsystem; and the cryptographer
//! audit itself.

use crate::oplog::{canonical_json, Scope};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::path::Path;

use chacha20poly1305::aead::{Aead, AeadCore, KeyInit, OsRng, Payload};
use chacha20poly1305::{ChaCha20Poly1305, Key, Nonce};
use ed25519_dalek::{Signature, Signer, SigningKey, VerifyingKey};
use sha2::Digest;
use x25519_dalek::{PublicKey, StaticSecret};
use zeroize::{Zeroize, Zeroizing};

/// The frozen algorithm tag written into every [`Envelope`] — lets a future
/// cipher upgrade coexist (a decryptor rejects an unknown tag rather than
/// mis-decoding).
pub const ALG_CHACHA20POLY1305: &str = "chacha20poly1305";

/// The ciphertext form of a payload — what the relay stores and sees. Cleartext
/// `op_id`/`seq`/`hlc`/`scope`/`surface` metadata lives *outside* this, on the
/// [`crate::oplog::OpRecord`]; the envelope hides only the payload body.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Envelope {
    /// Algorithm tag ([`ALG_CHACHA20POLY1305`]).
    pub car_enc: String,
    /// The 96-bit AEAD nonce, hex (24 chars). Random per encryption, so the
    /// same plaintext encrypts to distinct ciphertext each time.
    pub nonce: String,
    /// The ciphertext ‖ Poly1305 tag, hex.
    pub ct: String,
    /// Org key-id (rotation EPOCH). ONLY the multi-epoch org cipher sets it, so a
    /// remaining member can select the right per-epoch key after a rotation instead
    /// of trial-decrypting. Personal / wrap envelopes omit it.
    ///
    /// `skip_serializing_if` is LOAD-BEARING: personal envelopes stay byte-identical
    /// (the field never serializes), AND `wrap_org_key` signs `canonical_json(envelope)`
    /// — so an always-omitted `kid` keeps every Ed25519 wrap signature valid. Do NOT
    /// drop `skip_serializing_if`, and do NOT add `deny_unknown_fields`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub kid: Option<u64>,
}

impl Envelope {
    /// Is this JSON value a ciphertext envelope (vs. a cleartext payload)?
    pub fn is_envelope(v: &Value) -> bool {
        v.get("car_enc").and_then(Value::as_str) == Some(ALG_CHACHA20POLY1305)
            && v.get("nonce").is_some()
            && v.get("ct").is_some()
    }
}

/// A crypto-boundary failure.
#[derive(Debug)]
pub enum CryptoError {
    /// Serializing the plaintext payload / deserializing the recovered plaintext.
    Json(serde_json::Error),
    /// The envelope is malformed, or its algorithm tag is unknown.
    BadEnvelope(String),
    /// AEAD open failed — a wrong key OR a tampered ciphertext/nonce (Poly1305
    /// tag mismatch). Indistinguishable by design; both mean "do not trust".
    Decrypt,
    /// The persisted key file is the wrong length or unreadable.
    Key(String),
    /// I/O reading/writing the key file.
    Io(std::io::Error),
}

impl std::fmt::Display for CryptoError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            CryptoError::Json(e) => write!(f, "crypto payload json error: {e}"),
            CryptoError::BadEnvelope(d) => write!(f, "crypto envelope malformed: {d}"),
            CryptoError::Decrypt => {
                write!(
                    f,
                    "crypto decrypt failed (wrong key or tampered ciphertext)"
                )
            }
            CryptoError::Key(d) => write!(f, "crypto key error: {d}"),
            CryptoError::Io(e) => write!(f, "crypto io error: {e}"),
        }
    }
}

impl std::error::Error for CryptoError {}

impl From<serde_json::Error> for CryptoError {
    fn from(e: serde_json::Error) -> Self {
        CryptoError::Json(e)
    }
}
impl From<std::io::Error> for CryptoError {
    fn from(e: std::io::Error) -> Self {
        CryptoError::Io(e)
    }
}

/// The encrypt/decrypt boundary. A device authors an E2E op with
/// `cipher.encrypt(plaintext)` as its payload; a peer holding the key recovers
/// it with `cipher.decrypt(&op.payload)`. Object-safe so a daemon can hold an
/// `Arc<dyn PayloadCipher>` (a null/local reference now, a login-derived key
/// later) without a type change.
pub trait PayloadCipher: Send + Sync {
    /// Encrypt a cleartext payload into a ciphertext [`Envelope`] (as a
    /// `Value`).
    fn encrypt(&self, plaintext: &Value) -> Result<Value, CryptoError>;
    /// Recover the cleartext payload from a ciphertext [`Envelope`]. Fails
    /// ([`CryptoError::Decrypt`]) on a wrong key or any tamper.
    fn decrypt(&self, envelope: &Value) -> Result<Value, CryptoError>;
}

/// The single-user reference cipher: a local 256-bit ChaCha20-Poly1305 key.
///
/// Genuinely linearizable-free confidentiality + integrity for the personal
/// multi-device case. NOT a login-derived or org-distributed key — see the
/// module's key-distribution follow-up.
#[derive(Clone)]
pub struct LocalKeyCipher {
    key: [u8; 32],
}

impl Drop for LocalKeyCipher {
    fn drop(&mut self) {
        // Wipe the key on drop. Load-bearing for the org-key path: an org wrap key
        // and (transitively) K_org get copied into a `LocalKeyCipher` via
        // `from_key(*wrap_key)`, so the `Zeroizing` wrapper on the source no longer
        // covers this copy — this Drop does. (Also the first org-SHARED subkey to
        // live in a cache; blast radius is every member.)
        self.key.zeroize();
    }
}

impl std::fmt::Debug for LocalKeyCipher {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        // Never print the key.
        f.debug_struct("LocalKeyCipher").finish_non_exhaustive()
    }
}

impl LocalKeyCipher {
    /// Build a cipher over an explicit 256-bit key.
    pub fn from_key(key: [u8; 32]) -> Self {
        Self { key }
    }

    /// Mint a fresh random key (OS CSPRNG). Not persisted — pair with
    /// [`Self::key_hex`] to store it, or use [`Self::load_or_generate`].
    pub fn generate() -> Self {
        let key = ChaCha20Poly1305::generate_key(&mut OsRng);
        Self { key: key.into() }
    }

    /// The key as 64 hex chars (for persistence). Handle as a secret.
    pub fn key_hex(&self) -> String {
        to_hex(&self.key)
    }

    /// Parse a 64-hex-char key.
    pub fn from_key_hex(hex: &str) -> Result<Self, CryptoError> {
        let bytes = from_hex(hex).map_err(CryptoError::Key)?;
        let key: [u8; 32] = bytes
            .try_into()
            .map_err(|_| CryptoError::Key("key must be 32 bytes (64 hex chars)".into()))?;
        Ok(Self { key })
    }

    /// Load the key from `path`, or mint + persist a new one there (`0600` on
    /// unix). The single-user "the key lives on my devices" story — a device
    /// gets the key out of band (copy the file / a recovery phrase); this is
    /// the local reference, not the login-derived distribution (the follow-up).
    pub fn load_or_generate(path: &Path) -> Result<Self, CryptoError> {
        if path.exists() {
            let hex = std::fs::read_to_string(path)?;
            return Self::from_key_hex(hex.trim());
        }
        let cipher = Self::generate();
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent)?;
        }
        // Create the key file 0600 from the FIRST byte (review): a
        // `write` + later `chmod` leaves the 256-bit AEAD key in a
        // world-readable file for the window between the two syscalls,
        // and a swallowed chmod error would leave it 0600-claimed but
        // 0644-real forever. `create_new` also refuses a symlink/TOCTOU
        // swap at the path. The chmod failure is surfaced, never
        // discarded.
        #[cfg(unix)]
        {
            use std::io::Write;
            use std::os::unix::fs::OpenOptionsExt;
            let mut f = std::fs::OpenOptions::new()
                .write(true)
                .create_new(true)
                .mode(0o600)
                .open(path)?;
            f.write_all(cipher.key_hex().as_bytes())?;
            f.sync_all()?;
        }
        #[cfg(not(unix))]
        {
            std::fs::write(path, cipher.key_hex())?;
            // Unix set the mode via create_new(...).mode(0o600); on Windows lock
            // the E2E key file owner-only via ACL. No-op off Windows.
            car_secrets::harden_owner_only(path);
        }
        Ok(cipher)
    }

    fn aead(&self) -> ChaCha20Poly1305 {
        ChaCha20Poly1305::new(Key::from_slice(&self.key))
    }
}

impl PayloadCipher for LocalKeyCipher {
    fn encrypt(&self, plaintext: &Value) -> Result<Value, CryptoError> {
        let bytes = serde_json::to_vec(plaintext)?;
        let nonce = ChaCha20Poly1305::generate_nonce(&mut OsRng);
        let ct = self
            .aead()
            .encrypt(&nonce, bytes.as_ref())
            .map_err(|_| CryptoError::Decrypt)?;
        let env = Envelope {
            car_enc: ALG_CHACHA20POLY1305.to_string(),
            nonce: to_hex(nonce.as_slice()),
            ct: to_hex(&ct),
            // Personal / single-key cipher: no epoch key-id (omitted on the wire).
            kid: None,
        };
        Ok(serde_json::to_value(env)?)
    }

    fn decrypt(&self, envelope: &Value) -> Result<Value, CryptoError> {
        let env: Envelope = serde_json::from_value(envelope.clone())
            .map_err(|e| CryptoError::BadEnvelope(e.to_string()))?;
        if env.car_enc != ALG_CHACHA20POLY1305 {
            return Err(CryptoError::BadEnvelope(format!(
                "unknown algorithm tag {:?}",
                env.car_enc
            )));
        }
        let nonce_bytes = from_hex(&env.nonce).map_err(CryptoError::BadEnvelope)?;
        if nonce_bytes.len() != 12 {
            return Err(CryptoError::BadEnvelope("nonce must be 12 bytes".into()));
        }
        let ct = from_hex(&env.ct).map_err(CryptoError::BadEnvelope)?;
        let nonce = Nonce::from_slice(&nonce_bytes);
        let pt = self
            .aead()
            .decrypt(nonce, ct.as_ref())
            .map_err(|_| CryptoError::Decrypt)?;
        Ok(serde_json::from_slice(&pt)?)
    }
}

/// The ChaCha20-Poly1305 associated data binding an org payload to its exact
/// `(algorithm, audience, epoch)`. Length-prefixed + domain-tagged so the bytes
/// are injective and can't be reinterpreted under a future mode — the same
/// discipline as [`wrap_sign_transcript`]. Authenticated by the AEAD tag: a
/// tampered `car_enc`/audience/`kid` fails the open. Org path ONLY — personal
/// envelopes carry no AAD (byte-identical).
///
/// The `v2` tag aligns with the wrap transcript version; there is no v1 payload
/// AAD (the personal path has none), so don't hunt for one. All integers are
/// little-endian to match [`wrap_sign_transcript`] — one endianness crate-wide.
fn org_payload_aad(car_enc: &str, audience: &str, kid: u64) -> Vec<u8> {
    let mut a = b"car-sync:payload:v2\0".to_vec();
    let mut lp = |field: &[u8]| {
        a.extend_from_slice(&(field.len() as u64).to_le_bytes());
        a.extend_from_slice(field);
    };
    lp(car_enc.as_bytes());
    lp(audience.as_bytes());
    a.extend_from_slice(&kid.to_le_bytes());
    a
}

/// A multi-epoch org cipher: holds the per-epoch derived audience keys and, on
/// decrypt, selects EXACTLY ONE by the envelope's `kid` — it NEVER iterates the
/// keyring (no trial-decrypt / wrong-key-acceptance). Encrypt always uses the
/// NEWEST epoch held and stamps `kid`. This is what makes rotation expressible: a
/// remaining member holding {N, N+1} decrypts old ops under N and new ops under
/// N+1, deterministically. Fail-closed: an unknown `kid`, a missing `kid`, or an
/// empty keyring all error (the op stays opaque) — never a wrong key.
pub struct MultiEpochOrgCipher {
    audience: String,
    /// epoch → derived audience key (`derive_key(K_org@epoch, audience)`). BTreeMap
    /// so `.last_key_value()` is the newest epoch.
    keys: std::collections::BTreeMap<u64, Zeroizing<[u8; 32]>>,
}

impl std::fmt::Debug for MultiEpochOrgCipher {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("MultiEpochOrgCipher")
            .field("audience", &self.audience)
            .field("epochs", &self.keys.keys().collect::<Vec<_>>())
            .finish_non_exhaustive()
    }
}

impl MultiEpochOrgCipher {
    /// Build over the per-epoch derived audience keys (see [`OrgAwareKeyProvider`]).
    pub fn new(
        audience: impl Into<String>,
        keys: std::collections::BTreeMap<u64, Zeroizing<[u8; 32]>>,
    ) -> Self {
        Self {
            audience: audience.into(),
            keys,
        }
    }

    fn aead_for(key: &[u8; 32]) -> ChaCha20Poly1305 {
        ChaCha20Poly1305::new(Key::from_slice(key))
    }
}

impl PayloadCipher for MultiEpochOrgCipher {
    fn encrypt(&self, plaintext: &Value) -> Result<Value, CryptoError> {
        // Newest epoch held. Empty keyring → fail closed (member holds no key).
        let (&kid, key) = self
            .keys
            .last_key_value()
            .ok_or_else(|| CryptoError::Key("org cipher has no epoch keys".into()))?;
        let bytes = serde_json::to_vec(plaintext)?;
        let nonce = ChaCha20Poly1305::generate_nonce(&mut OsRng);
        let aad = org_payload_aad(ALG_CHACHA20POLY1305, &self.audience, kid);
        let ct = Self::aead_for(key)
            .encrypt(
                &nonce,
                Payload {
                    msg: bytes.as_ref(),
                    aad: &aad,
                },
            )
            .map_err(|_| CryptoError::Decrypt)?;
        let env = Envelope {
            car_enc: ALG_CHACHA20POLY1305.to_string(),
            nonce: to_hex(nonce.as_slice()),
            ct: to_hex(&ct),
            kid: Some(kid),
        };
        Ok(serde_json::to_value(env)?)
    }

    fn decrypt(&self, envelope: &Value) -> Result<Value, CryptoError> {
        let env: Envelope = serde_json::from_value(envelope.clone())
            .map_err(|e| CryptoError::BadEnvelope(e.to_string()))?;
        if env.car_enc != ALG_CHACHA20POLY1305 {
            return Err(CryptoError::BadEnvelope(format!(
                "unknown algorithm tag {:?}",
                env.car_enc
            )));
        }
        // Org envelopes MUST carry a kid; select EXACTLY that epoch's key. No kid,
        // or a kid we don't hold → fail closed. Never iterate / trial-decrypt.
        let kid = env
            .kid
            .ok_or_else(|| CryptoError::BadEnvelope("org envelope missing epoch kid".into()))?;
        let key = self
            .keys
            .get(&kid)
            .ok_or_else(|| CryptoError::Key(format!("no org key held for epoch {kid}")))?;
        let nonce_bytes = from_hex(&env.nonce).map_err(CryptoError::BadEnvelope)?;
        if nonce_bytes.len() != 12 {
            return Err(CryptoError::BadEnvelope("nonce must be 12 bytes".into()));
        }
        let ct = from_hex(&env.ct).map_err(CryptoError::BadEnvelope)?;
        let nonce = Nonce::from_slice(&nonce_bytes);
        let aad = org_payload_aad(ALG_CHACHA20POLY1305, &self.audience, kid);
        let pt = Self::aead_for(key)
            .decrypt(
                nonce,
                Payload {
                    msg: ct.as_ref(),
                    aad: &aad,
                },
            )
            .map_err(|_| CryptoError::Decrypt)?;
        Ok(serde_json::from_slice(&pt)?)
    }
}

/// The encryption **audience** a scope maps to — the set of principals whose
/// key a payload under this scope is encrypted to. `Personal` → the user's own
/// key; `Shared{org}` → the org key. The B4-pinned rule ("scopes are
/// encryption audiences") uses this: a single ciphertext must have a single
/// audience, so a whole-chain checkpoint mixing scopes cannot be one ciphertext.
pub fn encryption_audience(scope: &Scope) -> String {
    match scope {
        Scope::Personal => "personal".to_string(),
        Scope::Shared { org } => format!("org:{org}"),
    }
}

// ---------------------------------------------------------------------------
// Login-derived key distribution (B6).
//
// A single-user reference key (`LocalKeyCipher::load_or_generate`) doesn't scale
// to "onboard once": a new device would have to copy a key file out of band.
// Instead every device HKDF-derives its per-audience AEAD keys from ONE master
// secret it gets from the Parslee login (per-user) / entitlements (per-org).
// Same login → same master → same derived keys on every device (so they decrypt
// each other), while "personal" and "org:<id>" audiences stay cryptographically
// independent. The master never leaves the authenticated client — the relay
// only ever holds ciphertext under a key it does not possess.
// ---------------------------------------------------------------------------

/// HKDF-SHA256 info prefix for CAR sync AEAD keys — bump `v1` on a KDF change.
const KDF_INFO_PREFIX: &[u8] = b"car-sync/v1/aead/";
/// A fixed (non-secret) HKDF salt. A constant makes derivation deterministic
/// across a user's devices from the same master — the whole point.
const KDF_SALT: &[u8] = b"car-sync/v1/salt";

/// Derive a 256-bit AEAD key for `audience` from a login/entitlement `master`
/// secret via HKDF-SHA256. Deterministic: the same `(master, audience)` yields
/// the same key on every device (a user's Mac and phone decrypt each other's
/// ops); distinct audiences ("personal" vs "org:<id>") yield independent keys.
pub fn derive_key(master: &[u8], audience: &str) -> [u8; 32] {
    let hk = hkdf::Hkdf::<sha2::Sha256>::new(Some(KDF_SALT), master);
    let mut info = KDF_INFO_PREFIX.to_vec();
    info.extend_from_slice(audience.as_bytes());
    let mut okm = [0u8; 32];
    hk.expand(&info, &mut okm)
        .expect("32 bytes is a valid HKDF-SHA256 output length");
    okm
}

/// The KDF profile a [`StretchedMaster`] was minted under. Versioned so that
/// RAISING the Argon2id params later is an explicit re-key epoch (it changes every
/// downstream key, so it folds into org-key rotation) — never a silent key fork.
/// A device records which profile minted its current keys.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum KdfProfile {
    /// Argon2id V0x13, m=64 MiB, t=3, p=1 — the launch profile for passphrases.
    Argon2idV1,
    /// HKDF-only — a Parslee-issued ≥256-bit secret (no stretch needed).
    IssuedHkdfV1,
}

// Launch Argon2id params (OWASP-defensible; won't OOM an older phone).
const ARGON2_M_COST_KIB: u32 = 65536; // 64 MiB
const ARGON2_T_COST: u32 = 3;
const ARGON2_P_COST: u32 = 1;
/// Prefix for the DETERMINISTIC per-user Argon2id salt. Deterministic (not random)
/// so a passphrase yields the same keys on every device with no server state; the
/// salt is domain separation across users, NOT secrecy (the work factor is the
/// memory-hardness). `user_id` MUST be canonical upstream (else two spellings fork
/// keys and cross-device sync silently breaks).
const KDF_ARGON2_SALT_PREFIX: &[u8] = b"car-sync/v1/argon2-salt/user:";

fn argon2_salt(user_id: &str) -> [u8; 16] {
    let mut h = sha2::Sha256::new();
    h.update(KDF_ARGON2_SALT_PREFIX);
    h.update(user_id.as_bytes());
    let digest = h.finalize();
    let mut salt = [0u8; 16];
    salt.copy_from_slice(&digest[..16]);
    salt
}

/// A high-entropy 32-byte master for ALL of a user's key derivations — the
/// per-audience AEAD keys AND the X25519/Ed25519 identities derive from THIS (via
/// HKDF), never from a raw passphrase. The type is the gate: an identity or
/// audience key cannot be derived from an unstretched password, because those
/// functions take `&StretchedMaster`, and the only ways to build one are the two
/// constructors below.
pub struct StretchedMaster {
    bytes: Zeroizing<[u8; 32]>,
    profile: KdfProfile,
}

impl std::fmt::Debug for StretchedMaster {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("StretchedMaster")
            .field("profile", &self.profile)
            .finish_non_exhaustive()
    }
}

impl StretchedMaster {
    /// Argon2id-stretch a (password-equivalent) passphrase into the master,
    /// deterministically per user (see [`argon2_salt`]).
    ///
    /// SECURITY — mitigation, NOT closure: this raises the per-guess cost of a weak
    /// passphrase but cannot mint entropy it never had. The user's identity PUBLIC
    /// key is published (the platform maps `account_id → pubkey`), which is an
    /// OFFLINE verification oracle — an attacker guesses a passphrase, stretches,
    /// derives, and compares to the published key with NO network. Argon2id's
    /// per-guess cost is then the entire wall; a short password still falls. A PAKE
    /// removes the oracle and is the strictly stronger path. Passphrase policy,
    /// param benchmarking, and the PAKE alternative still require a cryptographer
    /// before production.
    pub fn from_passphrase(passphrase: &[u8], user_id: &str) -> Self {
        let salt = argon2_salt(user_id);
        let params = argon2::Params::new(ARGON2_M_COST_KIB, ARGON2_T_COST, ARGON2_P_COST, Some(32))
            .expect("fixed Argon2idV1 params are valid");
        let argon =
            argon2::Argon2::new(argon2::Algorithm::Argon2id, argon2::Version::V0x13, params);
        let mut bytes = Zeroizing::new([0u8; 32]);
        argon
            .hash_password_into(passphrase, &salt, bytes.as_mut_slice())
            .expect("argon2 with valid params + 32-byte output does not fail");
        Self {
            bytes,
            profile: KdfProfile::Argon2idV1,
        }
    }

    /// From a Parslee-issued high-entropy secret (the caller CERTIFIES it is
    /// ≥256-bit). Skips Argon2id — stretching a strong key is pointless cost —
    /// and HKDF-binds it to `user_id` for per-user domain separation.
    pub fn from_issued_high_entropy(secret: &[u8], user_id: &str) -> Self {
        Self {
            bytes: Zeroizing::new(derive_key(secret, &format!("user/{user_id}"))),
            profile: KdfProfile::IssuedHkdfV1,
        }
    }

    /// The profile that minted this master (for the rotation/migration machinery).
    pub fn profile(&self) -> KdfProfile {
        self.profile
    }

    fn as_bytes(&self) -> &[u8; 32] {
        &self.bytes
    }
}

/// Supplies the [`PayloadCipher`] for a scope's encryption audience. The daemon
/// holds one and asks for a cipher per op-scope, so a remote relay only ever
/// sees ciphertext under the right (personal / org) key.
pub trait SyncKeyProvider: Send + Sync {
    fn cipher_for(&self, scope: &Scope) -> std::sync::Arc<dyn PayloadCipher>;
}

/// Derives per-audience [`LocalKeyCipher`]s from one login-derived master secret
/// (HKDF-SHA256), caching by audience. The master comes from the Parslee login
/// (per-user) / entitlements (per-org); it is NEVER sent to the relay.
pub struct DerivedKeyProvider {
    master: Zeroizing<Vec<u8>>,
    cache: std::sync::Mutex<std::collections::HashMap<String, std::sync::Arc<LocalKeyCipher>>>,
}

impl std::fmt::Debug for DerivedKeyProvider {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("DerivedKeyProvider").finish_non_exhaustive()
    }
}

impl DerivedKeyProvider {
    /// Build over a raw 32-byte master (already high-entropy + stable across the
    /// user's devices). Prefer [`Self::from_master`] with a [`StretchedMaster`].
    pub fn new(master: impl Into<Vec<u8>>) -> Self {
        Self {
            master: Zeroizing::new(master.into()),
            cache: std::sync::Mutex::new(std::collections::HashMap::new()),
        }
    }

    /// Build the per-audience AEAD keys from a [`StretchedMaster`] — the same
    /// master that mints the identity keys, so Argon2id runs ONCE at open and both
    /// paths share it.
    pub fn from_master(master: &StretchedMaster) -> Self {
        Self::new(master.as_bytes().to_vec())
    }

    /// Build from a Parslee-issued high-entropy secret bound to `user_id` (no
    /// Argon2id — the secret is already strong). The issued-key alternative to a
    /// passphrase; both converge on a [`StretchedMaster`].
    pub fn from_login_secret(login_secret: &[u8], user_id: &str) -> Self {
        Self::from_master(&StretchedMaster::from_issued_high_entropy(
            login_secret,
            user_id,
        ))
    }

    /// Build from a user **sync passphrase** — the zero-knowledge cross-device key
    /// source that needs NO server key distribution: every device on which the
    /// user enters the same passphrase derives the same keys, and Parslee (relay +
    /// platform) never sees it. The passphrase is Argon2id-STRETCHED (see
    /// [`StretchedMaster::from_passphrase`]) before any key derivation.
    pub fn from_passphrase(passphrase: &str, user_id: &str) -> Self {
        Self::from_master(&StretchedMaster::from_passphrase(
            passphrase.as_bytes(),
            user_id,
        ))
    }

    fn cipher_for_audience(&self, audience: &str) -> std::sync::Arc<dyn PayloadCipher> {
        let mut cache = self.cache.lock().expect("key cache poisoned");
        if let Some(c) = cache.get(audience) {
            return c.clone();
        }
        let cipher = std::sync::Arc::new(LocalKeyCipher::from_key(derive_key(
            self.master.as_slice(),
            audience,
        )));
        cache.insert(audience.to_string(), cipher.clone());
        cipher
    }
}

impl SyncKeyProvider for DerivedKeyProvider {
    fn cipher_for(&self, scope: &Scope) -> std::sync::Arc<dyn PayloadCipher> {
        self.cipher_for_audience(&encryption_audience(scope))
    }
}

pub(crate) fn to_hex(bytes: &[u8]) -> String {
    bytes.iter().map(|b| format!("{b:02x}")).collect()
}

pub(crate) fn from_hex(s: &str) -> Result<Vec<u8>, String> {
    if !s.len().is_multiple_of(2) {
        return Err("hex length must be even".into());
    }
    (0..s.len())
        .step_by(2)
        .map(|i| u8::from_str_radix(&s[i..i + 2], 16).map_err(|e| e.to_string()))
        .collect()
}

// ---------------------------------------------------------------------------
// Client-side ORG-key agreement (ECIES over X25519).
//
// The gap this closes: `DerivedKeyProvider` derives the org audience from each
// member's OWN login master, so members end up with DIFFERENT org keys and
// cannot read each other's org-scoped ops. The fix is a SHARED org master key
// `K_org` that every member obtains — but the relay/platform must NEVER see it.
//
// So `K_org` is wrapped for each member with public-key encryption (ECIES): a
// fresh ephemeral X25519 exchange to the member's identity key, HKDF over the
// shared secret WITH THE FULL TRANSCRIPT BOUND (org, epoch, recipient, both
// public keys), then the existing AEAD. The relay stores only the wrapped blob;
// only the member's identity secret unwraps it. Established primitives, standard
// construction — nothing invented.
//
// SECURITY — MUST be reviewed by a cryptographer before production:
//   * the login_secret → identity derivation (see `derive_x25519_identity`);
//   * whether org/epoch also belong in the AEAD AAD (not only the HKDF info);
//   * secret zeroization + at-rest protection of the identity secret;
//   * rotation-under-compromise and key recovery/escrow.
// This module gives the pure wrap/unwrap + identity primitive; the relay org-key
// surface, the oplog epoch field, rotation orchestration, and the
// `SyncKeyProvider` swap-in are follow-ups.
// ---------------------------------------------------------------------------

/// HKDF info prefix for the deterministic per-user X25519 identity key. Its OWN
/// namespace — an asymmetric identity key must not share the `derive_key`
/// (`.../aead/`) domain-separation namespace with the symmetric AEAD keys.
const KDF_INFO_X25519_ID: &[u8] = b"car-sync/v1/x25519-identity/v1/user:";
/// HKDF domain for the Ed25519 SIGNING identity. DISTINCT label from the X25519
/// identity domain above — HKDF-expand with different `info` yields independent
/// sibling subkeys (no key reuse between the DH key and the signing key). The two
/// labels must never collide.
const KDF_INFO_ED25519_ID: &[u8] = b"car-sync/v1/ed25519-identity/v1/user:";

/// Wire tag for a wrapped org-key blob. **v2** adds the publisher signature:
/// every wrap is signed by the publisher's Ed25519 identity, and [`unwrap_org_key`]
/// REFUSES any wrap not signed by a caller-trusted holder — closing the key
/// SUBSTITUTION hole (v1 sealed a key TO a recipient but authenticated NO ONE, so
/// any member could wrap an attacker-chosen `K_org'` to a victim). There is NO v1
/// accept path in live unwrap: a downgrade to an unsigned wrap is structurally
/// impossible, not policy-gated.
pub const ALG_ORG_KEY_WRAP: &str = "org-key-wrap/v2";

/// Derive a user's deterministic X25519 identity secret from their
/// [`StretchedMaster`], so every device reconstructs the SAME keypair (the public
/// key is published; the secret never leaves the device). 32 bytes of HKDF-SHA256
/// output are a valid X25519 scalar (dalek clamps at DH time).
///
/// Takes a `&StretchedMaster` (not raw bytes) BY DESIGN: a password-equivalent
/// passphrase must be Argon2id-stretched first (the memory-hard work factor the
/// audit required), and the type forbids feeding an unstretched password here.
/// SECURITY residual: the published public key is still an offline guessing oracle
/// — see [`StretchedMaster::from_passphrase`]. Cryptographer review still required.
pub fn derive_x25519_identity(master: &StretchedMaster, user_id: &str) -> StaticSecret {
    let hk = hkdf::Hkdf::<sha2::Sha256>::new(Some(KDF_SALT), master.as_bytes());
    let mut info = KDF_INFO_X25519_ID.to_vec();
    info.extend_from_slice(user_id.as_bytes());
    let mut sk = [0u8; 32];
    hk.expand(&info, &mut sk)
        .expect("32 is a valid HKDF-SHA256 output length");
    let secret = StaticSecret::from(sk);
    sk.zeroize();
    secret
}

/// The publishable public identity for a user (the platform maps
/// `account_id → this` so a wrapper can find each member's key).
pub fn x25519_public(secret: &StaticSecret) -> PublicKey {
    PublicKey::from(secret)
}

/// Derive a user's deterministic Ed25519 SIGNING identity from their
/// [`StretchedMaster`], under a domain distinct from the X25519 identity (see
/// [`KDF_INFO_ED25519_ID`]). The publisher signs each wrap with this key so a
/// recipient can reject wraps not authored by a trusted holder. The verifying key
/// ([`ed25519_verifying`]) is published beside the X25519 public key.
///
/// Takes a `&StretchedMaster` for the same reason as [`derive_x25519_identity`] —
/// the Argon2id stretch is enforced by the type, and the same offline-oracle
/// residual applies.
pub fn derive_ed25519_identity(master: &StretchedMaster, user_id: &str) -> SigningKey {
    let hk = hkdf::Hkdf::<sha2::Sha256>::new(Some(KDF_SALT), master.as_bytes());
    let mut info = KDF_INFO_ED25519_ID.to_vec();
    info.extend_from_slice(user_id.as_bytes());
    let mut seed = [0u8; 32];
    hk.expand(&info, &mut seed)
        .expect("32 is a valid HKDF-SHA256 output length");
    let signing = SigningKey::from_bytes(&seed);
    seed.zeroize();
    signing
}

/// The publishable Ed25519 verifying key for a signing identity.
pub fn ed25519_verifying(signing: &SigningKey) -> VerifyingKey {
    signing.verifying_key()
}

/// An org id usable in a wrap: rejected (never rewritten) unless it is a strict
/// ASCII slug `[A-Za-z0-9._-]+`. This blocks Unicode confusables and
/// delimiter-injection at the crypto boundary and pins the exact bytes bound into
/// BOTH the KDF transcript and the signature — so a caller cannot sign a different
/// transcript for "Acme" than for "acme". Case-folding is deliberately NOT done
/// here (the Turkish-İ / locale trap is itself a canonicalization bypass); the
/// platform MUST mint ONE canonical opaque org id upstream (a tenant id), and this
/// only enforces that it is well-formed and bound verbatim.
pub fn require_canonical_org(org: &str) -> Result<(), CryptoError> {
    if org.is_empty() {
        return Err(CryptoError::Key("org id is empty".into()));
    }
    if !org
        .bytes()
        .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-'))
    {
        return Err(CryptoError::Key(format!(
            "org id {org:?} is not a canonical ASCII slug [A-Za-z0-9._-]"
        )));
    }
    Ok(())
}

/// The HKDF info that binds the FULL transcript of a wrap — org, epoch,
/// recipient, the ephemeral pubkey, and the recipient pubkey. Binding all five
/// makes each wrap blob non-transplantable across members/epochs/orgs and pins
/// it to this exact exchange: a substituted `E` or `P` derives a different key,
/// so the AEAD open fails. Under-binding here passes every functional test while
/// silently breaking security — so it is bound in exactly one place, here.
///
/// The embedded `org-key-wrap/v1` label is the KDF-CONSTRUCTION version and is
/// deliberately FROZEN — decoupled from the `v2` wire tag ([`ALG_ORG_KEY_WRAP`]).
/// v1→v2 only ADDED the signature layer; the ECIES/KDF derivation is unchanged, so
/// bumping this label would gratuitously break key derivation for no benefit.
fn org_wrap_info(
    org: &str,
    epoch: u64,
    recipient_user_id: &str,
    e_pub: &PublicKey,
    p_pub: &PublicKey,
) -> String {
    // LENGTH-PREFIX the free-form fields (`org`, `recipient_user_id`) so the
    // transcript is injective: a reader consumes exactly N bytes after `=N:`, so
    // no (org, epoch, recipient) tuple can collide with another via delimiter
    // injection (e.g. an org id containing "/recipient:..."). Naive `/`+`:`
    // interpolation is NOT injective when the ids are attacker-influenced.
    // `epoch` is decimal-only and `E`/`P` are fixed-width hex, so they're safe.
    format!(
        "org-key-wrap/v1|org={}:{}|epoch={}|recipient={}:{}|E={}|P={}",
        org.len(),
        org,
        epoch,
        recipient_user_id.len(),
        recipient_user_id,
        to_hex(e_pub.as_bytes()),
        to_hex(p_pub.as_bytes()),
    )
}

/// The exact bytes the publisher SIGNS. Binds every field + the AEAD envelope +
/// the publisher id, so no field/ciphertext is substitutable under a copied
/// signature and the wrap is attributed non-repudiably to `publisher`. Each
/// variable-length field is length-prefixed (8-byte LE) so the encoding is
/// injective; `epoch` is fixed-width. The alg tag is included so a v2 signature
/// can never be replayed under another version. Signs the AEAD ENVELOPE (its
/// canonical JSON — nonce+ct+tag), NOT the plaintext. NOTE: what defends against
/// key substitution is the SIGNATURE plus the per-wrap unique key (a fresh
/// ephemeral DH → a distinct `wrap_key` per blob, and each blob is
/// single-recipient) — NOT any commitment property of the AEAD: ChaCha20-Poly1305
/// is NOT key-committing (Poly1305 is not collision-resistant on the key). Signing
/// the ciphertext is sufficient here because the signature binds it; do not
/// refactor this to lean on "the AEAD commits `k_org`" — it does not.
fn wrap_sign_transcript(
    org: &str,
    epoch: u64,
    recipient_user_id: &str,
    publisher_user_id: &str,
    e_pub: &PublicKey,
    p_pub: &PublicKey,
    envelope: &Value,
) -> Vec<u8> {
    fn lp(buf: &mut Vec<u8>, field: &[u8]) {
        buf.extend_from_slice(&(field.len() as u64).to_le_bytes());
        buf.extend_from_slice(field);
    }
    let mut t = Vec::new();
    lp(&mut t, ALG_ORG_KEY_WRAP.as_bytes());
    lp(&mut t, org.as_bytes());
    t.extend_from_slice(&epoch.to_le_bytes());
    lp(&mut t, recipient_user_id.as_bytes());
    lp(&mut t, publisher_user_id.as_bytes());
    lp(&mut t, e_pub.as_bytes());
    lp(&mut t, p_pub.as_bytes());
    lp(&mut t, canonical_json(envelope).as_bytes());
    t
}

/// A shared org master key wrapped for one member — AUTHENTICATED ECIES over
/// X25519. Sealed to the member's X25519 key (only their secret unwraps it) AND
/// signed by the publisher's Ed25519 identity (only a caller-trusted publisher is
/// accepted). Every member unwraps the SAME `k_org` and derives the org-audience
/// AEAD key from it, so org-scoped ops become mutually readable.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct WrappedOrgKey {
    /// Algorithm tag ([`ALG_ORG_KEY_WRAP`], "org-key-wrap/v2").
    pub car_wrap: String,
    pub org: String,
    /// The key-rotation epoch this `k_org` belongs to (member removal bumps it).
    pub epoch: u64,
    /// The member this blob is addressed to. ADVISORY ONLY — not
    /// integrity-protected for ROUTING: unwrap binds the CALLER's own `my_user_id`
    /// into both the KDF and the signature transcript, not this field. Do not
    /// route or authorize on it.
    pub recipient: String,
    /// The publisher (signer) user id. ADVISORY — a routing/label hint. unwrap
    /// authorizes on the injected TRUSTED verifying-key set, NEVER on this field.
    pub publisher: String,
    /// Ephemeral X25519 public key (hex) — re-fed into the KDF on unwrap.
    pub ephemeral_pub: String,
    /// Recipient's X25519 public key (hex) — bound into the KDF.
    pub recipient_pub: String,
    /// AEAD envelope over `{ "k_org": <hex> }`.
    pub envelope: Value,
    /// Ed25519 signature (hex, 64 bytes) by the publisher over
    /// [`wrap_sign_transcript`]. Verified with `verify_strict` against a trusted
    /// key on unwrap, BEFORE any decrypt.
    pub signature: String,
}

/// Mint a fresh org master key `K_org` from the OS CSPRNG. Returned in
/// [`Zeroizing`] so it wipes on drop.
///
/// CRITICAL for rotation: a NEW epoch's `K_org` MUST come from here — an
/// independent random draw — NEVER a hash/KDF chain from the previous epoch's
/// key. A removed member still holds the old `K_org`; if `K_org@(N+1)` were any
/// function of `K_org@N`, they could derive the new key and rotation would be
/// theatre. There is deliberately no `derive_next_org_key(old)` API.
pub fn generate_org_key() -> Zeroizing<[u8; 32]> {
    Zeroizing::new(ChaCha20Poly1305::generate_key(&mut OsRng).into())
}

/// Wrap the shared org master key `k_org` for `recipient_pub` in `(org, epoch)`,
/// SIGNED by `publisher_user_id`'s `signer`. A fresh ephemeral keypair per wrap;
/// the full transcript is bound into the KDF; a low-order (degenerate) recipient
/// key is rejected via the contributory check; the whole blob (incl. the AEAD
/// envelope + publisher id) is signed so a recipient can reject wraps not authored
/// by a trusted holder. `org` must be a canonical ASCII slug (see
/// [`require_canonical_org`]).
pub fn wrap_org_key(
    k_org: &[u8; 32],
    org: &str,
    epoch: u64,
    recipient_user_id: &str,
    recipient_pub: &PublicKey,
    publisher_user_id: &str,
    signer: &SigningKey,
) -> Result<WrappedOrgKey, CryptoError> {
    require_canonical_org(org)?;
    // Fresh ephemeral keypair (reuse the OS-CSPRNG path the AEAD already uses).
    let mut e_bytes: [u8; 32] = ChaCha20Poly1305::generate_key(&mut OsRng).into();
    let e_secret = StaticSecret::from(e_bytes);
    e_bytes.zeroize();
    let e_pub = PublicKey::from(&e_secret);

    let shared = e_secret.diffie_hellman(recipient_pub);
    if !shared.was_contributory() {
        // Low-order / degenerate recipient key → all-zero shared secret. Refuse
        // (dalek does NOT reject it for us).
        return Err(CryptoError::Key(
            "recipient public key is low-order (non-contributory DH)".into(),
        ));
    }
    let wrap_key = zeroize::Zeroizing::new(derive_key(
        shared.as_bytes(),
        &org_wrap_info(org, epoch, recipient_user_id, &e_pub, recipient_pub),
    ));
    let envelope = LocalKeyCipher::from_key(*wrap_key).encrypt(&serde_json::json!({
        "k_org": to_hex(k_org),
    }))?;
    // Sign the whole transcript (fields + envelope + publisher id).
    let signature = signer.sign(&wrap_sign_transcript(
        org,
        epoch,
        recipient_user_id,
        publisher_user_id,
        &e_pub,
        recipient_pub,
        &envelope,
    ));
    Ok(WrappedOrgKey {
        car_wrap: ALG_ORG_KEY_WRAP.to_string(),
        org: org.to_string(),
        epoch,
        recipient: recipient_user_id.to_string(),
        publisher: publisher_user_id.to_string(),
        ephemeral_pub: to_hex(e_pub.as_bytes()),
        recipient_pub: to_hex(recipient_pub.as_bytes()),
        envelope,
        signature: to_hex(&signature.to_bytes()),
    })
}

/// Unwrap a [`WrappedOrgKey`] addressed to this member with their identity
/// secret — ONLY if it is signed by a key in `trusted`. Order is
/// verify-BEFORE-decrypt: the signature (over the full transcript, bound to THIS
/// caller's `my_user_id`) is checked with `verify_strict` against each trusted
/// verifying key FIRST; if none accept it, the blob is refused and no decrypt
/// runs. Then the transcript-bound key is re-derived from the PUBLIC blob and
/// `my_user_id`, so a wrong recipient / tampered ephemeral or recipient pubkey /
/// altered org/epoch also yield a different key and the AEAD open fails.
///
/// `trusted` is the caller's policy — the set of holders authorized to grant this
/// org's key (admin-designated granters; NOT all current holders). The blob's
/// advisory `publisher`/`recipient` fields are NEVER authorized on. There is no
/// v1 (unsigned) accept path — a downgrade is structurally impossible.
pub fn unwrap_org_key(
    wrapped: &WrappedOrgKey,
    my_secret: &StaticSecret,
    my_user_id: &str,
    trusted: &[VerifyingKey],
) -> Result<[u8; 32], CryptoError> {
    if wrapped.car_wrap != ALG_ORG_KEY_WRAP {
        return Err(CryptoError::BadEnvelope(format!(
            "unknown wrap tag {:?} (expected {ALG_ORG_KEY_WRAP})",
            wrapped.car_wrap
        )));
    }
    require_canonical_org(&wrapped.org)?;
    let e_pub = parse_x25519_pub(&wrapped.ephemeral_pub)?;
    let recipient_pub = parse_x25519_pub(&wrapped.recipient_pub)?;

    // AUTHENTICATE FIRST — reject any wrap not signed by a trusted holder, before
    // touching the DH / AEAD. The transcript binds MY user id (not the blob's
    // advisory recipient), so a wrap the publisher signed for a DIFFERENT
    // recipient won't verify here.
    let sig_bytes: [u8; 64] = from_hex(&wrapped.signature)
        .map_err(CryptoError::Key)?
        .try_into()
        .map_err(|_| CryptoError::Key("signature must be 64 bytes".into()))?;
    let signature = Signature::from_bytes(&sig_bytes);
    let transcript = wrap_sign_transcript(
        &wrapped.org,
        wrapped.epoch,
        my_user_id,
        &wrapped.publisher,
        &e_pub,
        &recipient_pub,
        &wrapped.envelope,
    );
    let authenticated = trusted
        .iter()
        .any(|vk| vk.verify_strict(&transcript, &signature).is_ok());
    if !authenticated {
        return Err(CryptoError::Key(
            "wrap is not signed by any trusted holder — refusing (possible key substitution)"
                .into(),
        ));
    }

    let shared = my_secret.diffie_hellman(&e_pub);
    if !shared.was_contributory() {
        return Err(CryptoError::Key(
            "ephemeral public key is low-order (non-contributory DH)".into(),
        ));
    }
    // Bind OUR user id (not the blob's claimed recipient): a blob is unwrappable
    // only if its wrapper used this exact user id AND our secret matches the
    // bound recipient pubkey.
    let wrap_key = zeroize::Zeroizing::new(derive_key(
        shared.as_bytes(),
        &org_wrap_info(
            &wrapped.org,
            wrapped.epoch,
            my_user_id,
            &e_pub,
            &recipient_pub,
        ),
    ));
    let pt = LocalKeyCipher::from_key(*wrap_key).decrypt(&wrapped.envelope)?;
    let k_hex = pt
        .get("k_org")
        .and_then(Value::as_str)
        .ok_or_else(|| CryptoError::BadEnvelope("wrapped payload missing k_org".into()))?;
    let bytes = from_hex(k_hex).map_err(CryptoError::Key)?;
    bytes
        .try_into()
        .map_err(|_| CryptoError::Key("k_org must be 32 bytes".into()))
}

/// Parse a 64-hex-char X25519 public key — e.g. a member's published identity
/// pubkey ([`crate::org_key_directory::MemberPublicKey::public_hex`]) that a
/// granter wraps `K_org` against.
///
/// This validates ONLY the encoding (32 bytes of hex); it does NOT reject a
/// low-order / non-contributory point (`PublicKey::from([u8;32])` is infallible).
/// That rejection happens later, at wrap time, via `wrap_org_key`'s contributory
/// DH check — so callers must treat a successful parse as "well-encoded", not
/// "safe to wrap to".
pub fn parse_x25519_pub(hex: &str) -> Result<PublicKey, CryptoError> {
    let bytes = from_hex(hex).map_err(CryptoError::Key)?;
    let arr: [u8; 32] = bytes
        .try_into()
        .map_err(|_| CryptoError::Key("x25519 public key must be 32 bytes".into()))?;
    Ok(PublicKey::from(arr))
}

/// Parse a 64-hex-char Ed25519 verifying (public) key — e.g. a configured trusted
/// granter key for the `trusted` set of [`unwrap_org_key`]. Rejects a bad length
/// or a non-canonical / small-order point (`VerifyingKey::from_bytes` validates).
pub fn parse_ed25519_verifying(hex: &str) -> Result<VerifyingKey, CryptoError> {
    let bytes = from_hex(hex).map_err(CryptoError::Key)?;
    let arr: [u8; 32] = bytes
        .try_into()
        .map_err(|_| CryptoError::Key("ed25519 verifying key must be 32 bytes".into()))?;
    VerifyingKey::from_bytes(&arr)
        .map_err(|e| CryptoError::Key(format!("invalid ed25519 verifying key: {e}")))
}

#[cfg(test)]
mod org_key_tests {
    use super::*;
    use serde_json::json;

    // Fast identity helpers for tests: issued-high-entropy (skips Argon2id) so the
    // suite stays fast, then the real derivation. Same `(secret, user)` shape as
    // the old raw-bytes fns, so the call sites below are a pure rename.
    fn x25519_id(secret: &[u8], user: &str) -> StaticSecret {
        crate::crypto::derive_x25519_identity(
            &StretchedMaster::from_issued_high_entropy(secret, user),
            user,
        )
    }
    fn ed25519_id(secret: &[u8], user: &str) -> SigningKey {
        crate::crypto::derive_ed25519_identity(
            &StretchedMaster::from_issued_high_entropy(secret, user),
            user,
        )
    }

    // A trusted granter — the admin-designated holder authorized to grant this
    // org's key. Its verifying key is the recipient's `trusted` policy.
    fn granter() -> SigningKey {
        ed25519_id(b"granter-login-secret", "acc_granter")
    }
    fn trusted() -> Vec<VerifyingKey> {
        vec![ed25519_verifying(&granter())]
    }
    // Wrap authored by the trusted granter (the common happy-path publisher).
    fn wrap_by_granter(
        k_org: &[u8; 32],
        org: &str,
        epoch: u64,
        recipient: &str,
        recipient_pub: &PublicKey,
    ) -> WrappedOrgKey {
        wrap_org_key(
            k_org,
            org,
            epoch,
            recipient,
            recipient_pub,
            "acc_granter",
            &granter(),
        )
        .unwrap()
    }

    #[test]
    fn org_key_wrap_round_trips_for_the_recipient() {
        let alice = x25519_id(b"alice-login-secret", "acc_alice");
        let k_org = [7u8; 32];
        let wrapped = wrap_by_granter(&k_org, "acme", 1, "acc_alice", &x25519_public(&alice));
        assert_eq!(
            unwrap_org_key(&wrapped, &alice, "acc_alice", &trusted()).unwrap(),
            k_org
        );
    }

    #[test]
    fn substitution_by_untrusted_publisher_is_refused() {
        // THE FIX. Mallory is a real org member (so the backend lets her publish),
        // and she seals an attacker-chosen K_org' to Alice's REAL pubkey — the
        // AEAD would open fine. But Mallory's signing key is NOT in Alice's trusted
        // set, so unwrap refuses BEFORE decrypting. Under v1 Alice would have
        // adopted the attacker's key.
        let alice = x25519_id(b"alice", "acc_alice");
        let mallory = ed25519_id(b"mallory-login", "acc_mallory");
        let k_org_evil = [0xEEu8; 32];
        let poisoned = wrap_org_key(
            &k_org_evil,
            "acme",
            1,
            "acc_alice",
            &x25519_public(&alice),
            "acc_mallory",
            &mallory,
        )
        .unwrap();
        let err = unwrap_org_key(&poisoned, &alice, "acc_alice", &trusted()).unwrap_err();
        assert!(matches!(err, CryptoError::Key(_)));
        // ...and it WOULD have opened if Mallory were trusted (proves the AEAD
        // itself doesn't distinguish the keys — only the signature policy does).
        let mallory_trusted = vec![ed25519_verifying(&mallory)];
        assert_eq!(
            unwrap_org_key(&poisoned, &alice, "acc_alice", &mallory_trusted).unwrap(),
            k_org_evil
        );
    }

    #[test]
    fn wrap_for_a_different_recipient_cannot_be_replayed() {
        // The granter signs a wrap FOR bob; alice (trusting the granter) must not
        // be able to unwrap it as herself — the signature transcript binds the
        // recipient, and unwrap rebuilds it with the CALLER's id.
        let alice = x25519_id(b"alice", "acc_alice");
        let bob = x25519_id(b"bob", "acc_bob");
        let for_bob = wrap_by_granter(&[9u8; 32], "acme", 1, "acc_bob", &x25519_public(&bob));
        assert!(unwrap_org_key(&for_bob, &alice, "acc_alice", &trusted()).is_err());
    }

    #[test]
    fn org_key_does_not_unwrap_for_a_different_member_or_id() {
        let alice = x25519_id(b"alice-secret", "acc_alice");
        let bob = x25519_id(b"bob-secret", "acc_bob");
        let k_org = [9u8; 32];
        let wrapped = wrap_by_granter(&k_org, "acme", 1, "acc_alice", &x25519_public(&alice));
        // Bob's secret can't unwrap Alice's blob (and his id fails the sig transcript).
        assert!(unwrap_org_key(&wrapped, &bob, "acc_bob", &trusted()).is_err());
        // Nor can Alice unwrap it while claiming a different id (id binding).
        assert!(unwrap_org_key(&wrapped, &alice, "acc_bob", &trusted()).is_err());
    }

    #[test]
    fn org_key_unwrap_rejects_tampered_transcript_and_ciphertext() {
        let alice = x25519_id(b"alice-secret", "acc_alice");
        let k_org = [3u8; 32];
        let base = wrap_by_granter(&k_org, "acme", 1, "acc_alice", &x25519_public(&alice));
        let bob_pub = x25519_public(&x25519_id(b"bob", "acc_bob"));
        let unwrap = |t: &WrappedOrgKey| unwrap_org_key(t, &alice, "acc_alice", &trusted());

        // Every field is under the signature now — any tamper fails verify first.
        // Tamper the AEAD ciphertext (flip the last hex char).
        let mut t = base.clone();
        let ct = t.envelope["ct"].as_str().unwrap().to_string();
        let mut chars: Vec<char> = ct.chars().collect();
        let last = chars.len() - 1;
        chars[last] = if chars[last] == '0' { '1' } else { '0' };
        t.envelope["ct"] = json!(chars.into_iter().collect::<String>());
        assert!(unwrap(&t).is_err());

        // Tamper the ephemeral / recipient pubkey, epoch, org, publisher label —
        // every one is under the signature, so each fails verify.
        let mut t = base.clone();
        t.ephemeral_pub = to_hex(bob_pub.as_bytes());
        assert!(unwrap(&t).is_err());
        let mut t = base.clone();
        t.recipient_pub = to_hex(bob_pub.as_bytes());
        assert!(unwrap(&t).is_err());
        let mut t = base.clone();
        t.epoch = 2;
        assert!(unwrap(&t).is_err());
        let mut t = base.clone();
        t.org = "evil".into();
        assert!(unwrap(&t).is_err());
        let mut t = base.clone();
        t.publisher = "acc_mallory".into();
        assert!(unwrap(&t).is_err());

        // Tamper the signature itself.
        let mut t = base.clone();
        let mut sig: Vec<char> = t.signature.chars().collect();
        sig[0] = if sig[0] == '0' { '1' } else { '0' };
        t.signature = sig.into_iter().collect();
        assert!(unwrap(&t).is_err());
    }

    #[test]
    fn identities_are_deterministic_and_domain_separated() {
        // Same login+user → same X25519 AND same Ed25519 key; the two are derived
        // under DISTINCT HKDF domains, so neither reveals the other.
        let a = x25519_id(b"same-login", "acc_x");
        let b = x25519_id(b"same-login", "acc_x");
        assert_eq!(x25519_public(&a).as_bytes(), x25519_public(&b).as_bytes());
        let s1 = ed25519_id(b"same-login", "acc_x");
        let s2 = ed25519_id(b"same-login", "acc_x");
        assert_eq!(
            ed25519_verifying(&s1).to_bytes(),
            ed25519_verifying(&s2).to_bytes()
        );
        // Different user / different login → different keys, both curves.
        assert_ne!(
            x25519_public(&a).as_bytes(),
            x25519_public(&x25519_id(b"same-login", "acc_y")).as_bytes()
        );
        assert_ne!(
            ed25519_verifying(&s1).to_bytes(),
            ed25519_verifying(&ed25519_id(b"other-login", "acc_x")).to_bytes()
        );
        // The X25519 and Ed25519 32-byte public encodings must not coincide.
        assert_ne!(
            x25519_public(&a).as_bytes(),
            &ed25519_verifying(&s1).to_bytes()
        );
    }

    #[test]
    fn argon2id_stretch_is_deterministic_and_domain_separated() {
        // Cross-device determinism: same passphrase + user → same stretched master
        // → same published identity keys (the property the whole scheme rests on).
        let a = StretchedMaster::from_passphrase(b"correct horse battery staple", "acc_u1");
        let b = StretchedMaster::from_passphrase(b"correct horse battery staple", "acc_u1");
        assert_eq!(a.profile(), KdfProfile::Argon2idV1);
        assert_eq!(
            x25519_public(&derive_x25519_identity(&a, "acc_u1")).as_bytes(),
            x25519_public(&derive_x25519_identity(&b, "acc_u1")).as_bytes(),
            "same passphrase+user must derive the same identity on every device"
        );
        // Different passphrase OR different user → different keys (salt + info).
        let diff_pass = StretchedMaster::from_passphrase(b"hunter2", "acc_u1");
        assert_ne!(
            x25519_public(&derive_x25519_identity(&a, "acc_u1")).as_bytes(),
            x25519_public(&derive_x25519_identity(&diff_pass, "acc_u1")).as_bytes()
        );
        let diff_user = StretchedMaster::from_passphrase(b"correct horse battery staple", "acc_u2");
        assert_ne!(
            x25519_public(&derive_x25519_identity(&a, "acc_u1")).as_bytes(),
            x25519_public(&derive_x25519_identity(&diff_user, "acc_u2")).as_bytes(),
            "the per-user Argon2id salt + HKDF info domain-separate users"
        );
        // The issued-high-entropy path carries a distinct profile and (being a
        // different derivation) yields different keys than the Argon2id path.
        let issued =
            StretchedMaster::from_issued_high_entropy(b"correct horse battery staple", "acc_u1");
        assert_eq!(issued.profile(), KdfProfile::IssuedHkdfV1);
        assert_ne!(
            x25519_public(&derive_x25519_identity(&a, "acc_u1")).as_bytes(),
            x25519_public(&derive_x25519_identity(&issued, "acc_u1")).as_bytes()
        );
    }

    #[test]
    fn wrap_rejects_low_order_recipient_key() {
        // The all-zero X25519 point is low-order → non-contributory DH.
        let low_order = PublicKey::from([0u8; 32]);
        assert!(wrap_org_key(
            &[1u8; 32],
            "acme",
            1,
            "acc_x",
            &low_order,
            "acc_granter",
            &granter()
        )
        .is_err());
    }

    #[test]
    fn non_canonical_org_is_rejected_on_wrap_and_unwrap() {
        let alice = x25519_id(b"alice", "acc_alice");
        // Wrap refuses a non-slug org (Unicode / delimiter / space).
        for bad in ["Acme corp", "org/evil", "acmé", ""] {
            assert!(
                wrap_org_key(
                    &[1u8; 32],
                    bad,
                    1,
                    "acc_alice",
                    &x25519_public(&alice),
                    "acc_granter",
                    &granter()
                )
                .is_err(),
                "wrap must reject non-canonical org {bad:?}"
            );
        }
        // A blob whose org is mutated after signing is refused. ("Acme" is itself
        // a valid slug — uppercase is allowed — so this is caught by the SIGNATURE
        // layer, not require_canonical_org: the transcript diverges. Upstream the
        // platform must mint ONE canonical org id so "Acme"/"acme" never coexist.)
        let mut t = wrap_by_granter(&[1u8; 32], "acme", 1, "acc_alice", &x25519_public(&alice));
        t.org = "Acme".into();
        assert!(unwrap_org_key(&t, &alice, "acc_alice", &trusted()).is_err());
    }

    #[test]
    fn org_wrap_info_is_injective_under_delimiter_injection() {
        let e = x25519_public(&x25519_id(b"e", "e"));
        let p = x25519_public(&x25519_id(b"p", "p"));
        // These two (org, recipient) tuples collide under naive `/`+`:`
        // interpolation; length-prefixing must keep the transcript distinct.
        let a = org_wrap_info("acme/epoch:1/recipient:mallory", 1, "acc_alice", &e, &p);
        let b = org_wrap_info("acme", 1, "mallory/epoch:1/recipient:acc_alice", &e, &p);
        assert_ne!(a, b, "delimiter injection must not collide the transcript");
    }

    #[test]
    fn all_members_derive_the_same_org_audience_key() {
        // The whole point: with a SHARED k_org, every member derives the SAME
        // org-audience AEAD key — closing the gap the old per-user derivation
        // left (where each member got a different, non-interoperable org key).
        let alice = x25519_id(b"alice", "acc_alice");
        let bob = x25519_id(b"bob", "acc_bob");
        let k_org = [42u8; 32];
        let ka = unwrap_org_key(
            &wrap_by_granter(&k_org, "acme", 1, "acc_alice", &x25519_public(&alice)),
            &alice,
            "acc_alice",
            &trusted(),
        )
        .unwrap();
        let kb = unwrap_org_key(
            &wrap_by_granter(&k_org, "acme", 1, "acc_bob", &x25519_public(&bob)),
            &bob,
            "acc_bob",
            &trusted(),
        )
        .unwrap();
        assert_eq!(ka, kb);
        assert_eq!(
            derive_key(&ka, "org:acme/epoch:1"),
            derive_key(&kb, "org:acme/epoch:1")
        );
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::oplog::{logical_clock, verify_log, DeviceLog, Surface};
    use serde_json::json;

    #[test]
    fn personal_envelope_omits_kid_on_the_wire() {
        // LOAD-BEARING: personal (LocalKeyCipher) envelopes must serialize WITHOUT a
        // `kid` field, byte-identical to pre-org-scope envelopes. `wrap_org_key`
        // signs `canonical_json(envelope)`, so a stray always-null `kid` would break
        // every existing wrap signature. This pins `skip_serializing_if`.
        let cipher = LocalKeyCipher::generate();
        let env = cipher.encrypt(&json!({"x": 1})).unwrap();
        let obj = env.as_object().unwrap();
        assert!(!obj.contains_key("kid"), "personal envelope must omit kid");
        assert_eq!(
            obj.keys()
                .cloned()
                .collect::<std::collections::BTreeSet<_>>(),
            ["car_enc", "ct", "nonce"]
                .into_iter()
                .map(String::from)
                .collect::<std::collections::BTreeSet<_>>(),
            "exactly the legacy three fields"
        );
    }

    #[test]
    fn multi_epoch_org_cipher_selects_by_kid_and_fails_closed() {
        // Two epochs held. Encrypt uses the NEWEST; each envelope carries its kid;
        // decrypt selects EXACTLY that epoch's key — never trial-decrypts. An
        // envelope whose kid we don't hold fails closed.
        let mut keys = std::collections::BTreeMap::new();
        keys.insert(1u64, Zeroizing::new([1u8; 32]));
        keys.insert(2u64, Zeroizing::new([2u8; 32]));
        let cipher = MultiEpochOrgCipher::new("org:acme", keys);

        let msg = json!({"shared": "brain"});
        let env = cipher.encrypt(&msg).unwrap();
        assert_eq!(
            env.get("kid").and_then(|v| v.as_u64()),
            Some(2),
            "encrypts under the newest epoch"
        );
        assert_eq!(cipher.decrypt(&env).unwrap(), msg);

        // Only epoch 1 held → an op stamped kid=2 is opaque (fail closed).
        let mut only1 = std::collections::BTreeMap::new();
        only1.insert(1u64, Zeroizing::new([1u8; 32]));
        let e1 = MultiEpochOrgCipher::new("org:acme", only1);
        assert!(matches!(e1.decrypt(&env), Err(CryptoError::Key(_))));
    }

    #[test]
    fn org_cipher_aad_binds_epoch_and_audience() {
        // The AAD binds (algorithm, audience, kid). Tampering the kid on the wire, or
        // replaying the ciphertext under a cipher for a DIFFERENT audience, both fail
        // the AEAD open — never a silent wrong-context accept.
        let mut keys = std::collections::BTreeMap::new();
        keys.insert(5u64, Zeroizing::new([5u8; 32]));
        let acme = MultiEpochOrgCipher::new("org:acme", keys.clone());
        let env = acme.encrypt(&json!({"m": 1})).unwrap();

        // Same key bytes, different audience string → AAD differs → Decrypt error.
        let globex = MultiEpochOrgCipher::new("org:globex", keys);
        assert!(matches!(globex.decrypt(&env), Err(CryptoError::Decrypt)));

        // Flip the kid to an epoch we DO hold but that wasn't used → AAD mismatch.
        let mut two = std::collections::BTreeMap::new();
        two.insert(5u64, Zeroizing::new([5u8; 32]));
        two.insert(6u64, Zeroizing::new([5u8; 32])); // same bytes, different epoch
        let acme2 = MultiEpochOrgCipher::new("org:acme", two);
        let mut tampered = env.clone();
        tampered["kid"] = json!(6);
        assert!(matches!(
            acme2.decrypt(&tampered),
            Err(CryptoError::Decrypt)
        ));
    }

    #[test]
    fn local_key_cipher_round_trips() {
        let cipher = LocalKeyCipher::generate();
        let plaintext = json!({"id": "f1", "secret": "the launch codes", "n": 42});
        let env = cipher.encrypt(&plaintext).unwrap();
        assert!(Envelope::is_envelope(&env));
        assert_eq!(cipher.decrypt(&env).unwrap(), plaintext);

        // Randomized nonce: two encryptions of the same plaintext differ.
        let env2 = cipher.encrypt(&plaintext).unwrap();
        assert_ne!(env, env2, "each encryption uses a fresh nonce");
        assert_eq!(cipher.decrypt(&env2).unwrap(), plaintext);
    }

    #[test]
    fn encrypted_op_chain_verifies_and_relay_sees_only_ciphertext() {
        // A device authors two ops with ENCRYPTED payloads. The op_id chain is
        // ciphertext-native, so verify_log passes and the relay (which only
        // ever holds op.payload) sees no plaintext — exactly the proposal's
        // "the relay stores only ciphertext; op_id/hlc stay cleartext".
        let cipher = LocalKeyCipher::generate();
        let mut dev = DeviceLog::new("mac-a");
        dev.set_wall_clock(logical_clock());

        let secret1 = json!({"id": "f1", "body": "the sky is blue"});
        let secret2 = json!({"id": "f2", "body": "water is wet"});
        let op1 = dev.append(
            Scope::Personal,
            Surface::Knowledge,
            cipher.encrypt(&secret1).unwrap(),
        );
        let op2 = dev.append(
            Scope::Personal,
            Surface::Knowledge,
            cipher.encrypt(&secret2).unwrap(),
        );

        // The ciphertext chain verifies (op_id covers the ciphertext payload).
        verify_log(&[op1.clone(), op2.clone()]).unwrap();
        assert!(op1.id_valid());

        // The wire form leaks nothing: no "body"/"id" fields, only the envelope.
        for op in [&op1, &op2] {
            assert!(Envelope::is_envelope(&op.payload));
            assert!(op.payload.get("body").is_none());
            assert!(op.payload.get("id").is_none());
        }

        // A peer holding the key recovers the plaintext.
        assert_eq!(cipher.decrypt(&op1.payload).unwrap(), secret1);
        assert_eq!(cipher.decrypt(&op2.payload).unwrap(), secret2);
    }

    #[test]
    fn tampered_ciphertext_is_rejected() {
        let cipher = LocalKeyCipher::generate();
        let env = cipher.encrypt(&json!({"x": 1})).unwrap();

        // Flip one hex nibble of the ciphertext → AEAD tag mismatch → refusal.
        let mut tampered = env.clone();
        let ct = tampered["ct"].as_str().unwrap().to_string();
        let flipped: String = {
            let mut chars: Vec<char> = ct.chars().collect();
            chars[0] = if chars[0] == '0' { '1' } else { '0' };
            chars.into_iter().collect()
        };
        tampered["ct"] = json!(flipped);
        assert!(matches!(
            cipher.decrypt(&tampered),
            Err(CryptoError::Decrypt)
        ));
    }

    #[test]
    fn wrong_key_cannot_decrypt() {
        let cipher = LocalKeyCipher::generate();
        let other = LocalKeyCipher::generate();
        let env = cipher.encrypt(&json!({"x": 1})).unwrap();
        assert!(matches!(other.decrypt(&env), Err(CryptoError::Decrypt)));
    }

    #[test]
    fn load_or_generate_persists_and_reloads_the_same_key() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("sync").join("personal.key");
        let a = LocalKeyCipher::load_or_generate(&path).unwrap();
        assert!(path.exists());
        let b = LocalKeyCipher::load_or_generate(&path).unwrap();
        assert_eq!(
            a.key_hex(),
            b.key_hex(),
            "the persisted key reloads identically"
        );

        // And the reloaded key decrypts the first cipher's output (same key).
        let env = a.encrypt(&json!({"k": "v"})).unwrap();
        assert_eq!(b.decrypt(&env).unwrap(), json!({"k": "v"}));
    }

    #[test]
    fn scope_maps_to_a_single_encryption_audience() {
        assert_eq!(encryption_audience(&Scope::Personal), "personal");
        assert_eq!(
            encryption_audience(&Scope::Shared { org: "acme".into() }),
            "org:acme"
        );
    }

    #[test]
    fn same_login_master_derives_interoperable_keys_across_devices() {
        // Mac and phone each build a provider from the SAME login master. A
        // payload the Mac encrypts under `Personal` must decrypt on the phone —
        // the whole "my devices share config after one login" property.
        let master = b"parslee-issued-per-user-sync-secret";
        let mac = DerivedKeyProvider::new(master.to_vec());
        let phone = DerivedKeyProvider::new(master.to_vec());

        let secret = json!({"messaging_allowlist": ["+15551234567"]});
        let env = mac.cipher_for(&Scope::Personal).encrypt(&secret).unwrap();
        assert_eq!(
            phone.cipher_for(&Scope::Personal).decrypt(&env).unwrap(),
            secret
        );
    }

    #[test]
    fn personal_and_org_audiences_are_cryptographically_isolated() {
        let p = DerivedKeyProvider::new(b"master".to_vec());
        let env = p
            .cipher_for(&Scope::Personal)
            .encrypt(&json!({"x": 1}))
            .unwrap();
        // The org key cannot read a personal-audience ciphertext.
        assert!(matches!(
            p.cipher_for(&Scope::Shared { org: "acme".into() })
                .decrypt(&env),
            Err(CryptoError::Decrypt)
        ));
    }

    #[test]
    fn passphrase_derives_the_same_keys_on_every_device_zero_knowledge() {
        // The zero-knowledge path: same passphrase + user → same keys, so the
        // phone reads what the Mac wrote, with no server ever holding the key.
        let mac = DerivedKeyProvider::from_passphrase("correct horse battery staple", "user-1");
        let phone = DerivedKeyProvider::from_passphrase("correct horse battery staple", "user-1");
        let env = mac
            .cipher_for(&Scope::Personal)
            .encrypt(&json!({"s": 1}))
            .unwrap();
        assert_eq!(
            phone.cipher_for(&Scope::Personal).decrypt(&env).unwrap(),
            json!({"s": 1})
        );
        // A wrong passphrase cannot read it.
        let wrong = DerivedKeyProvider::from_passphrase("hunter2", "user-1");
        assert!(matches!(
            wrong.cipher_for(&Scope::Personal).decrypt(&env),
            Err(CryptoError::Decrypt)
        ));
    }

    #[test]
    fn a_different_login_cannot_decrypt() {
        let mine = DerivedKeyProvider::new(b"my-secret".to_vec());
        let theirs = DerivedKeyProvider::new(b"their-secret".to_vec());
        let env = mine
            .cipher_for(&Scope::Personal)
            .encrypt(&json!({"x": 1}))
            .unwrap();
        assert!(matches!(
            theirs.cipher_for(&Scope::Personal).decrypt(&env),
            Err(CryptoError::Decrypt)
        ));
    }

    #[test]
    fn from_login_secret_is_stable_per_user_and_distinct_across_users() {
        let raw = b"raw-oauth-derived-material";
        // Two sign-ins for the same user → same keys (idempotent onboarding).
        let a = DerivedKeyProvider::from_login_secret(raw, "user-1");
        let b = DerivedKeyProvider::from_login_secret(raw, "user-1");
        let env = a
            .cipher_for(&Scope::Personal)
            .encrypt(&json!({"k": "v"}))
            .unwrap();
        assert_eq!(
            b.cipher_for(&Scope::Personal).decrypt(&env).unwrap(),
            json!({"k": "v"})
        );
        // A different user derives a different master → cannot decrypt.
        let other = DerivedKeyProvider::from_login_secret(raw, "user-2");
        assert!(matches!(
            other.cipher_for(&Scope::Personal).decrypt(&env),
            Err(CryptoError::Decrypt)
        ));
    }
}