derec-library 0.0.4

Rust SDK for the DeRec protocol, including native and WebAssembly bindings.
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
// SPDX-License-Identifier: Apache-2.0
// Copyright (c) 2026 DeRec Alliance. All rights reserved.

//! Higher-level WASM binding: [`DeRecProtocolWasm`].
//!
//! This module exposes the same high-level orchestrator as the native
//! [`crate::protocol::DeRecProtocol`] but wired to JS-side store and transport
//! objects so that TypeScript applications can use it without managing raw
//! message routing.
//!
//! # Usage (TypeScript)
//!
//! ```ts
//! import init, { DeRecProtocol } from "@derec-alliance/web";
//!
//! await init();
//!
//! const protocol = new DeRecProtocol(
//!   contactStore,   // implements { load, save }
//!   shareStore,     // implements { load, save, loadChannelsForSecret, loadSecretsForChannel }
//!   secretStore,    // implements { load, save, remove }
//!   transport,      // implements { send }
//!   "https://my-node.example.com/derec",
//!   "https",         // or "grpc" for a grpc://... / grpcs://... endpoint
//! );
//!
//! // Owner: generate a contact message, read channel_id, serialize for QR.
//! const contact = await protocol.createContact();
//! const channelId = BigInt(contact.channel_id);
//!
//! // Owner: receive peer's ContactMessage object and begin pairing.
//! const channelId = await protocol.startPairing(0, peerContact); // 0 = Owner
//!
//! // Feed incoming wire bytes; react to returned events.
//! const events = await protocol.process(rawBytes);
//! for (const ev of events) {
//!   if (ev.type === "PairingCompleted") { ... }
//! }
//! ```
//!
//! See each method's documentation for full details on event shapes and JS
//! interface contracts.

mod events;

/// Maps a transport protocol *name* to its wire discriminant.
///
/// Case-insensitive; accepts exactly `"https"` and `"grpc"` — the two
/// protocol-family names, not the four URI schemes each admits. `https://`
/// and `http://` both name `Protocol::Https`; `grpcs://` and `grpc://` both
/// name `Protocol::Grpc`.
///
/// Lives here rather than beside
/// [`crate::transport::protocol_for_scheme`](crate::transport) because names
/// only cross this seam: every other layer derives the protocol from a URI
/// instead of taking a bare string. Both directions go through this single
/// pair so the name/discriminant pairing cannot drift between call sites.
pub(super) fn protocol_name_to_discriminant(name: &str) -> Option<i32> {
    match name.to_lowercase().as_str() {
        "https" => Some(derec_proto::Protocol::Https.into()),
        "grpc" => Some(derec_proto::Protocol::Grpc.into()),
        _ => None,
    }
}

/// Inverse of [`protocol_name_to_discriminant`]: maps a wire discriminant
/// back to its lowercase protocol name. `None` for any discriminant outside
/// the defined `Protocol` variants.
pub(super) fn protocol_discriminant_to_name(discriminant: i32) -> Option<&'static str> {
    match derec_proto::Protocol::try_from(discriminant).ok()? {
        derec_proto::Protocol::Https => Some("https"),
        derec_proto::Protocol::Grpc => Some("grpc"),
    }
}
// `pending_action_wire` lives in `crate::protocol::utils` so both WASM
// and FFI bridges can share the same on-the-wire encoding for the opaque
// PendingAction blob.
pub(crate) use crate::protocol::utils::pending_action_wire;
mod stores;

use std::collections::HashMap;
use std::time::Duration;

use crate::interop::wasm::primitives::pairing::ContactMessage as PairingContactMessage;
use crate::{
    interop::wasm::ts_bindings_utils::{js_error, js_error_from_lib},
    protocol::{
        DeRecFlow, DeRecProtocol, DeRecProtocolBuilder, UnpairAck,
        types::{Target, UserSecret},
    },
    types::ChannelId,
};
use derec_proto::{SenderKind, TransportProtocol};
use js_sys::{Array, Uint8Array};
use stores::{
    JsChannelStore, JsSecretStore, JsShareStore, JsStateStore, JsTransport, JsUserSecretStore,
};
use wasm_bindgen::prelude::*;

type WasmProtocol = DeRecProtocol<
    JsChannelStore,
    JsShareStore,
    JsSecretStore,
    JsUserSecretStore,
    JsStateStore,
    JsTransport,
>;

/// Higher-level DeRec protocol orchestrator for TypeScript/JavaScript consumers.
///
/// Wraps [`crate::protocol::DeRecProtocol`] with JS-side store
/// and transport adapters so that a TypeScript application can drive all five
/// protocol flows without routing raw bytes manually.
///
/// # Stores
///
/// Pass four JS objects that implement the interfaces documented on each
/// parameter.  All store methods must return `Promise`s — synchronous
/// implementations can wrap their result with `Promise.resolve(...)`.
///
/// # Events
///
/// [`process`](DeRecProtocolWasm::process) returns an `Array` of plain JS
/// objects, each with a `type` discriminant field:
///
/// | `type`             | Additional fields                                      |
/// |--------------------|--------------------------------------------------------|
/// | `PairingCompleted`  | `channel_id: string`, `pairing_channel_id: string`, `kind: number` |
/// | `ShareStored`      | `channel_id: string`, `version: number`                |
/// | `ShareConfirmed`   | `channel_id: string`, `version: number`                |
/// | `ShareVerified`    | `channel_id: string`, `version: number`                |
/// | `SecretsDiscovered`| `channel_id: string`, `secrets: SecretVersionEntry[]`  |
/// | `SecretRecovered`  | `secret: { helpers, secrets, replicas }` (same nested shape as `ReplicaSecretReceived.secret`) |
/// | `NoOp`             | _(none)_                                               |
///
/// `SecretVersionEntry = { secret_id: bigint, versions: { version: number, description: string }[] }`
#[wasm_bindgen]
pub struct DeRecProtocolWasm {
    inner: WasmProtocol,
}

/// JS-side shape of [`crate::protocol::types::Timeouts`]. Every field is
/// optional; absent means the library's default stands. Mirrors the FFI
/// `"timeouts"` config object so the two bindings cannot drift.
#[derive(serde::Deserialize)]
struct TimeoutsJs {
    #[serde(default)]
    inbound_message_secs: Option<u64>,
    #[serde(default)]
    sharing_round_secs: Option<u64>,
    #[serde(default)]
    unpair_ack_secs: Option<u64>,
    #[serde(default)]
    expired_channels: Option<ExpiredChannelsJs>,
}

#[derive(serde::Deserialize)]
struct ExpiredChannelsJs {
    enabled: bool,
    timeout_in_secs: u64,
}

impl TimeoutsJs {
    fn to_timeouts(&self) -> crate::protocol::types::Timeouts {
        let d = crate::protocol::types::Timeouts::default();
        crate::protocol::types::Timeouts {
            inbound_message: self
                .inbound_message_secs
                .map_or(d.inbound_message, Duration::from_secs),
            sharing_round: self
                .sharing_round_secs
                .map_or(d.sharing_round, Duration::from_secs),
            unpair_ack: self
                .unpair_ack_secs
                .map_or(d.unpair_ack, Duration::from_secs),
            expired_channels: self
                .expired_channels
                .as_ref()
                .map_or(d.expired_channels, |e| {
                    crate::protocol::ExpiredChannelCleanup::new(e.enabled, e.timeout_in_secs)
                }),
        }
    }
}

/// Fluent builder for [`DeRecProtocolWasm`]. Mirrors the Rust
/// [`crate::protocol::DeRecProtocolBuilder`] and the dotnet
/// `DeRecProtocolBuilder` method-for-method so a developer who already
/// knows one SDK can move between them without reaching for reference
/// docs.
///
/// Required setters: `withChannelStore`, `withShareStore`,
/// `withSecretStore`, `withTransport`, and either `withOwnTransport` or
/// `withOwnTransports`. Calling `build()` without all five throws.
///
/// All optional setters carry the defaults documented on the Rust
/// builder.
#[wasm_bindgen(js_name = DeRecProtocolBuilder)]
pub struct DeRecProtocolBuilderWasm {
    secret_id: u64,
    channel_store: Option<JsValue>,
    share_store: Option<JsValue>,
    secret_store: Option<JsValue>,
    user_secret_store: Option<JsValue>,
    state_store: Option<JsValue>,
    transport: Option<JsValue>,
    own_transport_uri: Option<String>,
    own_transport_protocol_num: Option<i32>,
    /// Set by `withOwnTransports`, in preference order. Takes precedence
    /// over `own_transport_uri` / `own_transport_protocol_num` in `build()`
    /// when non-empty.
    own_transports: Vec<crate::transport::TransportProtocol>,
    threshold: u32,
    keep_versions_count: u32,
    communication_info: HashMap<String, String>,
    /// `None` until `withTimeouts` is called, so an unconfigured builder
    /// leaves the library's own defaults in force rather than restating them
    /// here.
    timeouts: Option<TimeoutsJs>,
    unsafe_http: Option<bool>,
    unsafe_connection: Option<bool>,
    auto_respond_on_failure: bool,
    unpair_ack: UnpairAck,
    auto_reply_to: bool,
    auto_accept: crate::protocol::AutoAcceptPolicy,
    replica_id: Option<u64>,
    parameter_range: Option<derec_proto::ParameterRange>,
}

#[wasm_bindgen(js_class = DeRecProtocolBuilder)]
impl DeRecProtocolBuilderWasm {
    /// `secretId` is a JS `bigint` or `number`. Identifies the single
    /// secret this protocol instance manages; apps that juggle multiple
    /// secrets instantiate one protocol per id.
    #[wasm_bindgen(constructor)]
    pub fn new(secret_id: JsValue) -> Result<DeRecProtocolBuilderWasm, JsValue> {
        let secret_id = js_value_to_u64(secret_id)
            .map_err(|e| js_error("INVALID_SECRET_ID", format!("{e:?}")))?;
        Ok(DeRecProtocolBuilderWasm {
            secret_id,
            channel_store: None,
            share_store: None,
            secret_store: None,
            user_secret_store: None,
            state_store: None,
            transport: None,
            own_transport_uri: None,
            own_transport_protocol_num: None,
            own_transports: Vec::new(),
            threshold: 3,
            keep_versions_count: 3,
            communication_info: HashMap::new(),
            timeouts: None,
            unsafe_http: None,
            unsafe_connection: None,
            auto_respond_on_failure: false,
            unpair_ack: UnpairAck::Required,
            auto_reply_to: false,
            auto_accept: crate::protocol::AutoAcceptPolicy::default(),
            replica_id: None,
            parameter_range: None,
        })
    }

    #[wasm_bindgen(js_name = withChannelStore)]
    pub fn with_channel_store(mut self, store: JsValue) -> DeRecProtocolBuilderWasm {
        self.channel_store = Some(store);
        self
    }

    #[wasm_bindgen(js_name = withShareStore)]
    pub fn with_share_store(mut self, store: JsValue) -> DeRecProtocolBuilderWasm {
        self.share_store = Some(store);
        self
    }

    #[wasm_bindgen(js_name = withSecretStore)]
    pub fn with_secret_store(mut self, store: JsValue) -> DeRecProtocolBuilderWasm {
        self.secret_store = Some(store);
        self
    }

    #[wasm_bindgen(js_name = withUserSecretStore)]
    pub fn with_user_secret_store(mut self, store: JsValue) -> DeRecProtocolBuilderWasm {
        self.user_secret_store = Some(store);
        self
    }

    #[wasm_bindgen(js_name = withStateStore)]
    pub fn with_state_store(mut self, store: JsValue) -> DeRecProtocolBuilderWasm {
        self.state_store = Some(store);
        self
    }

    #[wasm_bindgen(js_name = withTransport)]
    pub fn with_transport(mut self, transport: JsValue) -> DeRecProtocolBuilderWasm {
        self.transport = Some(transport);
        self
    }

    /// `endpoint` shape: `{ uri: string, protocol: string }`.
    /// `protocol` is `"https"` or `"grpc"` (case-insensitive).
    ///
    /// @deprecated Use `withOwnTransports`, which takes the whole preference
    /// list — `withOwnTransports([endpoint])` is the direct replacement.
    /// Removed at 0.0.5.
    #[wasm_bindgen(js_name = withOwnTransport)]
    pub fn with_own_transport(
        mut self,
        endpoint: JsValue,
    ) -> Result<DeRecProtocolBuilderWasm, JsValue> {
        #[derive(serde::Deserialize)]
        struct EndpointShape {
            uri: String,
            protocol: String,
        }
        let parsed: EndpointShape = serde_wasm_bindgen::from_value(endpoint)
            .map_err(|e| js_error("INVALID_OWN_TRANSPORT", e.to_string()))?;
        let protocol_num = protocol_name_to_discriminant(&parsed.protocol).ok_or_else(|| {
            js_error(
                "INVALID_PROTOCOL",
                format!("unknown protocol: {}", parsed.protocol.to_lowercase()),
            )
        })?;
        self.own_transport_uri = Some(parsed.uri);
        self.own_transport_protocol_num = Some(protocol_num);
        Ok(self)
    }

    /// Every transport endpoint this application serves, in preference
    /// order. `transports` is an array of `{ uri: string, protocol: string
    /// }` objects, `protocol` being `"https"` or `"grpc"`
    /// (case-insensitive), same shape as [`Self::with_own_transport`].
    ///
    /// The order is the application's own preference and decides which of
    /// a peer's offered endpoints is used. Every listed transport must
    /// actually be served, because delivery is push-only — listing an
    /// endpoint this application does not serve makes pairing succeed and
    /// replies vanish.
    ///
    /// Supersedes [`Self::with_own_transport`] for applications serving
    /// more than one transport; the single-endpoint setter remains fully
    /// supported.
    #[wasm_bindgen(js_name = withOwnTransports)]
    pub fn with_own_transports(
        mut self,
        transports: Vec<JsValue>,
    ) -> Result<DeRecProtocolBuilderWasm, JsValue> {
        #[derive(serde::Deserialize)]
        struct EndpointShape {
            uri: String,
            protocol: String,
        }
        let mut parsed_transports = Vec::with_capacity(transports.len());
        for endpoint in transports {
            let parsed: EndpointShape = serde_wasm_bindgen::from_value(endpoint)
                .map_err(|e| js_error("INVALID_OWN_TRANSPORT", e.to_string()))?;
            let protocol_num =
                protocol_name_to_discriminant(&parsed.protocol).ok_or_else(|| {
                    js_error(
                        "INVALID_PROTOCOL",
                        format!("unknown protocol: {}", parsed.protocol.to_lowercase()),
                    )
                })?;
            let proto_tp = TransportProtocol {
                uri: parsed.uri,
                protocol: protocol_num,
            };
            // Same structural + scheme/protocol validation as
            // `withOwnTransport`, run per entry, order preserved verbatim
            // — it is the application's preference.
            let tp = crate::transport::TransportProtocol::try_from(&proto_tp)
                .map_err(|e| js_error("INVALID_OWN_TRANSPORT", e.to_string()))?;
            parsed_transports.push(tp);
        }
        self.own_transports = parsed_transports;
        Ok(self)
    }

    /// Minimum number of shares required to reconstruct the secret.
    /// Default: 3.
    #[wasm_bindgen(js_name = withThreshold)]
    pub fn with_threshold(mut self, threshold: u32) -> DeRecProtocolBuilderWasm {
        self.threshold = threshold;
        self
    }

    /// Number of recent versions each helper must retain. Default: 3.
    #[wasm_bindgen(js_name = withKeepVersionsCount)]
    pub fn with_keep_versions_count(mut self, count: u32) -> DeRecProtocolBuilderWasm {
        self.keep_versions_count = count;
        self
    }

    /// Accept plaintext `http://` transport endpoints. **Development only.**
    /// Default `false`.
    ///
    /// With it `false`, plaintext is accepted only for an endpoint this
    /// device configured for *itself* that names loopback (`localhost`,
    /// `127.0.0.1`, `::1`) — so a local dev server needs no configuration.
    /// With it `true`, plaintext is accepted for any host on any path,
    /// including endpoints a peer supplies. That is what makes the LAN case
    /// work (a phone against a laptop), and why the name is blunt.
    ///
    /// Superseded by `withUnsafeConnection`; still honored, and wins on
    /// conflict. Removed at 0.0.5.
    #[wasm_bindgen(js_name = withUnsafeHttp)]
    pub fn with_unsafe_http(mut self, allow: bool) -> DeRecProtocolBuilderWasm {
        self.unsafe_http = Some(allow);
        self
    }

    /// Accept plaintext transport endpoints — `http://` and `grpc://`.
    /// **Development only.** Default `false`. See `withUnsafeHttp` for the
    /// conflict rule when both are set.
    #[wasm_bindgen(js_name = withUnsafeConnection)]
    pub fn with_unsafe_connection(mut self, allow: bool) -> DeRecProtocolBuilderWasm {
        self.unsafe_connection = Some(allow);
        self
    }

    /// Configure the four waiting periods in one call.
    ///
    /// Object shape — every field optional, and **absent means "keep the
    /// library default"**:
    ///
    /// ```text
    /// {
    ///   inbound_message_secs?: number,   // staleness / replay window
    ///   sharing_round_secs?:   number,
    ///   unpair_ack_secs?:      number,
    ///   expired_channels?:     { enabled: boolean, timeout_in_secs: number },
    /// }
    /// ```
    ///
    /// Values are forwarded verbatim; clamping and the meaning of a disabled
    /// `expired_channels` are library decisions, not this shim's. Not calling
    /// this leaves every default in force.
    #[wasm_bindgen(js_name = withTimeouts)]
    pub fn with_timeouts(mut self, timeouts: JsValue) -> Result<DeRecProtocolBuilderWasm, JsValue> {
        let parsed: TimeoutsJs = serde_wasm_bindgen::from_value(timeouts)
            .map_err(|e| js_error("INVALID_TIMEOUTS", e.to_string()))?;
        self.timeouts = Some(parsed);
        Ok(self)
    }

    /// `info` shape: `Record<string, string>`. Default: empty.
    #[wasm_bindgen(js_name = withCommunicationInfo)]
    pub fn with_communication_info(
        mut self,
        info: JsValue,
    ) -> Result<DeRecProtocolBuilderWasm, JsValue> {
        let parsed: HashMap<String, String> = serde_wasm_bindgen::from_value(info)
            .map_err(|e| js_error("INVALID_COMMUNICATION_INFO", e.to_string()))?;
        self.communication_info = parsed;
        Ok(self)
    }

    /// Whether the protocol auto-replies on failed inbound processing.
    /// Default: false.
    #[wasm_bindgen(js_name = withAutoRespondOnFailure)]
    pub fn with_auto_respond_on_failure(mut self, enabled: bool) -> DeRecProtocolBuilderWasm {
        self.auto_respond_on_failure = enabled;
        self
    }

    /// `ack` is `"required"` (default) or `"not_required"`.
    #[wasm_bindgen(js_name = withUnpairAck)]
    pub fn with_unpair_ack(mut self, ack: String) -> Result<DeRecProtocolBuilderWasm, JsValue> {
        self.unpair_ack = match ack.to_ascii_lowercase().as_str() {
            "required" => UnpairAck::Required,
            "not_required" | "notrequired" | "fire_and_forget" => UnpairAck::NotRequired,
            other => {
                return Err(js_error(
                    "INVALID_UNPAIR_ACK",
                    format!(
                        "unknown unpair_ack value: {other:?}; expected \"required\" or \"not_required\""
                    ),
                ));
            }
        };
        Ok(self)
    }

    /// Whether outbound requests stamp `replyTo = ownTransport`.
    /// Default: false.
    #[wasm_bindgen(js_name = withAutoReplyTo)]
    pub fn with_auto_reply_to(mut self, enabled: bool) -> DeRecProtocolBuilderWasm {
        self.auto_reply_to = enabled;
        self
    }

    /// Per-flow auto-accept policy.
    ///
    /// `policy` shape (all fields optional, default `false`):
    /// `{ pairing, prePair, storeShare, verifyShare, discovery, getShare, unpair, updateChannelInfo }`.
    ///
    /// When a field is `true`, `process()` internally accepts the
    /// matching incoming request and emits an `AutoAccepted` event in
    /// place of `ActionRequired`. See the Rust-side
    /// `AutoAcceptPolicy` rustdoc for the per-flow trade-offs.
    /// Default: every field `false`.
    #[wasm_bindgen(js_name = withAutoAccept)]
    pub fn with_auto_accept(
        mut self,
        policy: JsValue,
    ) -> Result<DeRecProtocolBuilderWasm, JsValue> {
        #[derive(serde::Deserialize, Default)]
        #[serde(rename_all = "camelCase", default)]
        struct AutoAcceptPolicyShape {
            pairing: bool,
            pre_pair: bool,
            store_share: bool,
            verify_share: bool,
            discovery: bool,
            get_share: bool,
            unpair: bool,
            update_channel_info: bool,
        }
        let parsed: AutoAcceptPolicyShape = serde_wasm_bindgen::from_value(policy)
            .map_err(|e| js_error("INVALID_AUTO_ACCEPT_POLICY", e.to_string()))?;
        self.auto_accept = crate::protocol::AutoAcceptPolicy {
            pairing: parsed.pairing,
            pre_pair: parsed.pre_pair,
            store_share: parsed.store_share,
            verify_share: parsed.verify_share,
            discovery: parsed.discovery,
            get_share: parsed.get_share,
            unpair: parsed.unpair,
            update_channel_info: parsed.update_channel_info,
        };
        Ok(self)
    }

    /// `id` is a JS `bigint` or `number`. Default: unset.
    #[wasm_bindgen(js_name = withReplicaId)]
    pub fn with_replica_id(mut self, id: JsValue) -> Result<DeRecProtocolBuilderWasm, JsValue> {
        let v =
            js_value_to_u64(id).map_err(|e| js_error("INVALID_REPLICA_ID", format!("{e:?}")))?;
        self.replica_id = Some(v);
        Ok(self)
    }

    /// Declare the local node's acceptable parameter range for pair
    /// negotiation. `range` is a JS object whose keys match the
    /// `ParameterRange` interface every binding already declares —
    /// `min_share_size`, `max_share_size`, `min_time_between_verifications`,
    /// … — so one shape serves the wasm and FFI paths alike. Each field is
    /// `i64`: accept either a number or a `BigInt` on the JS side. Every
    /// field is optional and defaults to `0`, which the proto reads as no
    /// constraint on that dimension. Default: unset (no constraints
    /// advertised, every peer range accepted).
    #[wasm_bindgen(js_name = withParameterRange)]
    pub fn with_parameter_range(
        mut self,
        range: JsValue,
    ) -> Result<DeRecProtocolBuilderWasm, JsValue> {
        #[derive(serde::Deserialize)]
        struct In {
            #[serde(default)]
            min_share_size: i64,
            #[serde(default)]
            max_share_size: i64,
            #[serde(default)]
            min_time_between_verifications: i64,
            #[serde(default)]
            max_time_between_verifications: i64,
            #[serde(default)]
            min_time_between_share_updates: i64,
            #[serde(default)]
            max_time_between_share_updates: i64,
            #[serde(default)]
            min_unresponsive_deletion_timeout: i64,
            #[serde(default)]
            max_unresponsive_deletion_timeout: i64,
            #[serde(default)]
            min_unresponsive_deactivation_timeout: i64,
            #[serde(default)]
            max_unresponsive_deactivation_timeout: i64,
        }
        let parsed: In = serde_wasm_bindgen::from_value(range)
            .map_err(|e| js_error("INVALID_PARAMETER_RANGE", e.to_string()))?;
        self.parameter_range = Some(derec_proto::ParameterRange {
            min_share_size: parsed.min_share_size,
            max_share_size: parsed.max_share_size,
            min_time_between_verifications: parsed.min_time_between_verifications,
            max_time_between_verifications: parsed.max_time_between_verifications,
            min_time_between_share_updates: parsed.min_time_between_share_updates,
            max_time_between_share_updates: parsed.max_time_between_share_updates,
            min_unresponsive_deletion_timeout: parsed.min_unresponsive_deletion_timeout,
            max_unresponsive_deletion_timeout: parsed.max_unresponsive_deletion_timeout,
            min_unresponsive_deactivation_timeout: parsed.min_unresponsive_deactivation_timeout,
            max_unresponsive_deactivation_timeout: parsed.max_unresponsive_deactivation_timeout,
        });
        Ok(self)
    }

    /// Finalize the configuration. Throws if any of the required
    /// setters was not called.
    pub fn build(self) -> Result<DeRecProtocolWasm, JsValue> {
        let channel_store = self
            .channel_store
            .ok_or_else(|| js_error("BUILDER_MISSING", "withChannelStore is required"))?;
        let share_store = self
            .share_store
            .ok_or_else(|| js_error("BUILDER_MISSING", "withShareStore is required"))?;
        let secret_store = self
            .secret_store
            .ok_or_else(|| js_error("BUILDER_MISSING", "withSecretStore is required"))?;
        let user_secret_store = self
            .user_secret_store
            .ok_or_else(|| js_error("BUILDER_MISSING", "withUserSecretStore is required"))?;
        let state_store = self
            .state_store
            .ok_or_else(|| js_error("BUILDER_MISSING", "withStateStore is required"))?;
        let transport = self
            .transport
            .ok_or_else(|| js_error("BUILDER_MISSING", "withTransport is required"))?;
        // `withOwnTransports` takes precedence over `withOwnTransport`
        // when non-empty; both remain fully supported.
        let own_transports: Vec<crate::transport::TransportProtocol> =
            if !self.own_transports.is_empty() {
                self.own_transports
            } else {
                let own_transport_uri = self
                    .own_transport_uri
                    .ok_or_else(|| js_error("BUILDER_MISSING", "withOwnTransport is required"))?;
                let own_transport_protocol = self
                    .own_transport_protocol_num
                    .ok_or_else(|| js_error("BUILDER_MISSING", "withOwnTransport is required"))?;

                let proto_tp = TransportProtocol {
                    uri: own_transport_uri,
                    protocol: own_transport_protocol,
                };
                // Library-level structural + scheme/protocol validation —
                // `TryFrom` runs both the enum-discriminant check and the
                // URI rules in a single step. Catches plaintext downgrades
                // and unknown enums before the value can be propagated to
                // peers via pairing or UpdateChannelInfo.
                vec![
                    crate::transport::TransportProtocol::try_from(&proto_tp)
                        .map_err(|e| js_error("INVALID_OWN_TRANSPORT", e.to_string()))?,
                ]
            };

        let unsafe_connection = crate::protocol::builder::resolve_plaintext_opt_in(
            self.unsafe_http,
            self.unsafe_connection,
        )
        .map_err(js_error_from_lib)?;

        let mut builder = DeRecProtocolBuilder::new(self.secret_id)
            .with_channel_store(JsChannelStore(channel_store))
            .with_share_store(JsShareStore(share_store))
            .with_secret_store(JsSecretStore(secret_store))
            .with_user_secret_store(JsUserSecretStore(user_secret_store))
            .with_state_store(JsStateStore(state_store))
            .with_transport(JsTransport(transport))
            .with_own_transports(own_transports)
            .with_threshold(self.threshold as usize)
            .with_keep_versions_count(self.keep_versions_count as usize)
            .with_communication_info(self.communication_info)
            .with_auto_respond_on_failure(self.auto_respond_on_failure)
            .with_unpair_ack(self.unpair_ack)
            .with_auto_reply_to(self.auto_reply_to)
            .with_auto_accept(self.auto_accept)
            .with_unsafe_connection(unsafe_connection);
        if let Some(t) = self.timeouts {
            builder = builder.with_timeouts(t.to_timeouts());
        }
        if let Some(id) = self.replica_id {
            builder = builder.with_replica_id(id);
        }
        if let Some(range) = self.parameter_range {
            builder = builder.with_parameter_range(range);
        }
        let inner = builder.build().map_err(js_error_from_lib)?;
        Ok(DeRecProtocolWasm { inner })
    }
}

#[wasm_bindgen]
impl DeRecProtocolWasm {
    /// Generate an out-of-band contact message (QR code payload, deep link, …).
    ///
    /// Returns a plain JS `ContactMessage` object. The `channel_id` field identifies
    /// the pairing session and will match the `channel_id` in the eventual
    /// `PairingCompleted` event — read it directly from the returned object.
    ///
    /// The caller is responsible for serializing the contact for out-of-band
    /// delivery (QR code, deep link, etc.). The peer passes the deserialized object
    /// to [`start`](Self::start) with `FlowKind::Pairing`.
    ///
    /// # Arguments
    ///
    /// * `channel_id` — Optional `BigInt` channel identifier. Pass `null` or
    ///   `undefined` to have the library generate a random one.
    /// * `contact_mode` — `0` for `InlineKeys` (keys embedded directly), `1`
    ///   for `HashedKeys` (contact carries only a SHA-384 binding hash; the
    ///   scanner fetches keys via a `PrePair` round-trip). `HashedKeys`
    ///   requires the protocol's `own_transport` to be ephemeral.
    /// The secret identifier this protocol instance is bound to.
    #[wasm_bindgen(js_name = "secretId")]
    pub fn secret_id(&self) -> u64 {
        self.inner.secret_id()
    }

    /// Single entry point for all three contact modes (`InlineKeys`,
    /// `HashedKeys`, `NoKeys`).
    ///
    /// * `channel_id` — `null`/`undefined` lets the library mint a
    ///   random id; otherwise `bigint` / `number` is used verbatim.
    /// * `contact_mode` — `0` (InlineKeys), `1` (HashedKeys), `2` (NoKeys).
    /// * `nonce` — `null`/`undefined` lets the library generate a fresh
    ///   random `u64`; otherwise the supplied `bigint`/`number` is used.
    ///   Required for `NoKeys` where callers typically pick a small
    ///   human-typable value.
    #[wasm_bindgen(js_name = "createContact")]
    pub async fn create_contact(
        &mut self,
        channel_id: JsValue,
        contact_mode: u32,
        nonce: JsValue,
    ) -> Result<JsValue, JsValue> {
        let id = parse_optional_channel_id(channel_id)?;
        let mode = match contact_mode {
            0 => derec_proto::ContactMode::InlineKeys,
            1 => derec_proto::ContactMode::HashedKeys,
            2 => derec_proto::ContactMode::NoKeys,
            other => {
                return Err(js_error(
                    "INVALID_CONTACT_MODE",
                    format!(
                        "unknown contact_mode: {other}; expected 0 (InlineKeys), 1 (HashedKeys), or 2 (NoKeys)"
                    ),
                ));
            }
        };
        let nonce = if nonce.is_null() || nonce.is_undefined() {
            None
        } else {
            Some(js_value_to_u64(nonce)?)
        };
        let contact = self
            .inner
            .create_contact(id, mode, nonce)
            .await
            .map_err(|e| js_error("DEREC_ERROR", e.to_string()))?;
        let contact: PairingContactMessage = contact.into();
        let serializer =
            serde_wasm_bindgen::Serializer::new().serialize_large_number_types_as_bigints(true);
        use serde::Serialize as _;
        contact
            .serialize(&serializer)
            .map_err(|e| js_error("WASM_SERIALIZE_ERROR", e.to_string()))
    }

    /// Replace this node's local communication info. Does not contact peers —
    /// follow up with a `start(UpdateChannelInfo, ...)` to propagate.
    #[wasm_bindgen(js_name = "setCommunicationInfo")]
    pub fn set_communication_info(&mut self, info: JsValue) -> Result<(), JsValue> {
        let map: HashMap<String, String> = if info.is_null() || info.is_undefined() {
            HashMap::new()
        } else {
            serde_wasm_bindgen::from_value(info)
                .map_err(|e| js_error("INVALID_COMMUNICATION_INFO", e.to_string()))?
        };
        self.inner.set_communication_info(map);
        Ok(())
    }

    /// Replace every endpoint this node advertises, in preference order.
    ///
    /// `transports` is an array of `{ uri: string, protocol: string }`
    /// objects, same shape as `withOwnTransports`. The runtime counterpart
    /// to that builder setter, and the way to change the whole set:
    /// `setOwnTransport` replaces only the entry for the protocol its URI
    /// names. A node serves at most one endpoint per protocol, so this list
    /// is a preference order over distinct protocols and two entries of the
    /// same protocol are rejected.
    ///
    /// Every entry is validated before any is stored, so a malformed URI
    /// leaves the previous set intact. IMPORTANT: keep the old endpoints
    /// operational during the changeover — see the Rust docs on
    /// `set_own_transports` for the discipline.
    #[wasm_bindgen(js_name = "setOwnTransports")]
    pub fn set_own_transports(&mut self, transports: Vec<JsValue>) -> Result<(), JsValue> {
        #[derive(serde::Deserialize)]
        struct EndpointShape {
            uri: String,
            protocol: String,
        }
        let mut validated = Vec::with_capacity(transports.len());
        for endpoint in transports {
            let parsed: EndpointShape = serde_wasm_bindgen::from_value(endpoint)
                .map_err(|e| js_error("INVALID_OWN_TRANSPORT", e.to_string()))?;
            let protocol_num =
                protocol_name_to_discriminant(&parsed.protocol).ok_or_else(|| {
                    js_error(
                        "INVALID_PROTOCOL",
                        format!("unknown protocol: {}", parsed.protocol.to_lowercase()),
                    )
                })?;
            let proto_tp = TransportProtocol {
                uri: parsed.uri,
                protocol: protocol_num,
            };
            validated.push(
                crate::transport::TransportProtocol::try_from(&proto_tp)
                    .map_err(|e| js_error("INVALID_OWN_TRANSPORT", e.to_string()))?,
            );
        }
        self.inner
            .set_own_transports(validated)
            .map_err(|e| js_error("INVALID_OWN_TRANSPORT", e.to_string()))?;
        Ok(())
    }

    /// Replace this node's endpoint for one protocol, leaving the others
    /// alone. A node serves at most one endpoint per protocol, so the
    /// `(uri, protocol)` pair identifies the entry it replaces; an entry for
    /// a protocol not yet served is appended, and a replaced one keeps its
    /// position in the preference order.
    ///
    /// @deprecated Use `setOwnTransports`, which takes the whole preference
    /// list and is the only way to change which protocols this node serves,
    /// or their order. Removed at 0.0.5.
    ///
    /// See `setCommunicationInfo` for the matching update-propagation
    /// flow, and `setOwnTransports` to keep more than one endpoint.
    /// IMPORTANT: keep the old endpoint operational during the changeover —
    /// see the Rust docs on `set_own_transport` for the discipline.
    #[wasm_bindgen(js_name = "setOwnTransport")]
    pub fn set_own_transport(&mut self, uri: String, protocol: String) -> Result<(), JsValue> {
        let protocol_num = protocol_name_to_discriminant(&protocol).ok_or_else(|| {
            js_error(
                "INVALID_PROTOCOL",
                format!("unknown protocol: {}", protocol.to_lowercase()),
            )
        })?;
        let proto_tp = TransportProtocol {
            uri,
            protocol: protocol_num,
        };
        // Validation runs through the typed `TryFrom` so scheme +
        // enum mismatches are rejected before the URI is stored.
        let lib_tp = crate::transport::TransportProtocol::try_from(&proto_tp)
            .map_err(|e| js_error("INVALID_OWN_TRANSPORT", e.to_string()))?;
        self.inner
            .set_own_transports([lib_tp])
            .map_err(|e| js_error("INVALID_OWN_TRANSPORT", e.to_string()))?;
        Ok(())
    }

    /// Unified entry point for initiating any protocol flow.
    ///
    /// # Arguments
    ///
    /// * `flow_kind` — Flow discriminant:
    ///   - `0` = Pairing (params: `{ kind: number, contact: ContactMessage, name?: string }`)
    ///   - `1` = Discovery (params: `{ target: BigInt | BigInt[] | null }`)
    ///   - `2` = ProtectSecret (params: `{ secrets: UserSecret[], description?: string }`)
    ///   - `3` = VerifyShares (params: `{ version: number, target: BigInt | BigInt[] | null }`)
    ///   - `4` = RecoverSecret (params: `{ secretId: Uint8Array, version: number }`)
    ///
    /// # Returns
    ///
    /// An `Array` of `*Started` / `*Failed` events describing the
    /// dispatched requests. Same shape as `process()`.
    #[wasm_bindgen(js_name = "start")]
    pub async fn start(&mut self, flow_kind: u32, params: JsValue) -> Result<JsValue, JsValue> {
        let flow = parse_flow(flow_kind, params)?;
        let rust_events = self
            .inner
            .start(flow)
            .await
            .map_err(|e| js_error("DEREC_ERROR", e.to_string()))?;
        let js_events = Array::new();
        for event in rust_events {
            js_events.push(&events::event_to_js(event)?);
        }
        Ok(js_events.into())
    }

    /// Derive the human-readable fingerprint for a paired channel. Both
    /// sides of a replica pair derive the same fingerprint from the
    /// shared key, enabling out-of-band confirmation before the channel
    /// transitions from `Pending` to `Paired`.
    #[wasm_bindgen(js_name = "getFingerprint")]
    pub async fn get_fingerprint(&mut self, channel_id: JsValue) -> Result<String, JsValue> {
        let id = js_value_to_u64(channel_id)?;
        self.inner
            .get_fingerprint(ChannelId(id))
            .await
            .map_err(|e| js_error("DEREC_ERROR", e.to_string()))
    }

    /// Verify a fingerprint against the channel's locally-derived one. On
    /// match, the channel transitions from `Pending` to `Paired`. Returns
    /// `true` when the fingerprint matches and the channel is confirmed,
    /// `false` otherwise.
    #[wasm_bindgen(js_name = "verifyFingerprint")]
    pub async fn verify_fingerprint(
        &mut self,
        channel_id: JsValue,
        fingerprint: String,
    ) -> Result<bool, JsValue> {
        let id = js_value_to_u64(channel_id)?;
        self.inner
            .verify_fingerprint(ChannelId(id), &fingerprint)
            .await
            .map_err(|e| js_error("DEREC_ERROR", e.to_string()))
    }

    /// Remove `Pending` channels older than `older_than_secs`, along with
    /// their pairing keys.
    ///
    /// Independent of the configured cleanup policy — it sweeps at the
    /// threshold given, even when the policy is disabled. The age
    /// comparison is strict, so a channel created within the current
    /// second survives even `0`.
    ///
    /// # Returns
    ///
    /// An `Array` of removed channel ids as decimal strings.
    #[wasm_bindgen(js_name = removeExpiredChannels)]
    pub async fn remove_expired_channels(
        &mut self,
        older_than_secs: u32,
    ) -> Result<JsValue, JsValue> {
        let ids = self
            .inner
            .remove_expired_channels(u64::from(older_than_secs))
            .await
            .map_err(|e| js_error("DEREC_ERROR", e.to_string()))?;
        let decimal: Vec<String> = ids.iter().map(|c| c.0.to_string()).collect();
        serde_wasm_bindgen::to_value(&decimal)
            .map_err(|e| js_error("WASM_SERIALIZE_ERROR", e.to_string()))
    }

    /// Accept a pending action from an `ActionRequired` event.
    ///
    /// # Arguments
    ///
    /// * `action_bytes` — Opaque `Uint8Array` from the `action` field of an `ActionRequired` event.
    ///
    /// # Returns
    ///
    /// An `Array` of event objects (same format as `process()`).
    pub async fn accept(&mut self, action_bytes: &[u8]) -> Result<JsValue, JsValue> {
        let action = pending_action_wire::deserialize(action_bytes)
            .map_err(|e| js_error("DECODE_ERROR", e))?;
        let rust_events = self
            .inner
            .accept(action)
            .await
            .map_err(|e| js_error("DEREC_ERROR", e.to_string()))?;
        let js_events = Array::new();
        for event in rust_events {
            js_events.push(&events::event_to_js(event)?);
        }
        Ok(js_events.into())
    }

    /// Reject a pending action from an `ActionRequired` event.
    ///
    /// # Arguments
    ///
    /// * `action_bytes` — Opaque `Uint8Array` from the `action` field of an `ActionRequired` event.
    /// * `status` — Numeric status code from `StatusEnum` (e.g. 2 for FAIL, 10 for REJECTED).
    /// * `memo` — Human-readable rejection reason.
    pub async fn reject(
        &mut self,
        action_bytes: &[u8],
        status: i32,
        memo: &str,
    ) -> Result<(), JsValue> {
        let action = pending_action_wire::deserialize(action_bytes)
            .map_err(|e| js_error("DECODE_ERROR", e))?;
        let status_enum = derec_proto::StatusEnum::try_from(status).map_err(|_| {
            js_error(
                "INVALID_STATUS",
                format!("invalid StatusEnum value: {status}"),
            )
        })?;
        self.inner
            .reject(action, status_enum, memo)
            .await
            .map_err(|e| js_error("DEREC_ERROR", e.to_string()))
    }

    /// Advance time-driven state without an inbound message.
    ///
    /// Timeouts are otherwise only evaluated by `process`, so a publish whose
    /// helpers all go quiet has nothing left to close it. Call this from a
    /// timer — `setInterval`, a service-worker alarm, a job runner — at an
    /// interval shorter than the configured timeout.
    ///
    /// Returns an `Array` of plain JS event objects, empty when nothing was
    /// in flight. Safe to call at any time.
    pub async fn tick(&mut self) -> Result<JsValue, JsValue> {
        let rust_events = self.inner.tick().await;
        let js_events = Array::new();
        for event in rust_events {
            js_events.push(&events::event_to_js(event)?);
        }
        Ok(js_events.into())
    }

    /// Feed any incoming wire bytes to the protocol.
    ///
    /// Returns an `Array` of plain JS event objects (see struct-level docs for shapes).
    /// Every inbound flow — pairing, sharing, verification, discovery,
    /// recovery, unpairing, channel-info updates and the replica flows — is
    /// handled through this single entry point.
    ///
    /// # Arguments
    ///
    /// * `message` — Raw wire bytes of an incoming `DeRecMessage`.
    pub async fn process(&mut self, message: &[u8]) -> Result<JsValue, JsValue> {
        let rust_events = self.inner.process(message).await.map_err(|e| {
            web_sys::console::error_1(&format!("[wasm-process] error: {e}").into());
            let channel_id_str = e.channel_id.map(|c| c.0.to_string());
            if let Some((status, memo)) = e.as_non_ok_status() {
                non_ok_status_error(status, memo, channel_id_str.as_deref())
            } else {
                process_error(e.to_string(), channel_id_str.as_deref())
            }
        })?;
        let js_events = Array::new();
        for event in rust_events {
            js_events.push(&events::event_to_js(event)?);
        }
        Ok(js_events.into())
    }

    /// Rebuild this protocol's `secret_id` namespace from a recovered
    /// `Secret`. Mirrors [`crate::protocol::DeRecProtocol::restore`] —
    /// see that method for the full contract.
    ///
    /// `recoveredSecret` is the typed `Secret` object carried by the
    /// `SecretRecovered` event; pass it verbatim.
    ///
    /// Errors surface as structured JS errors with a `code` field:
    ///
    /// | code               | meaning                                                          |
    /// |--------------------|------------------------------------------------------------------|
    /// | `ALREADY_RESTORED` | A user-secret snapshot already exists for this `secret_id`.      |
    /// | `CONFLICT`         | Channels live at canonical helper / replica ids. The error       |
    /// |                    | carries `channel_ids: string[]` listing the collisions.          |
    /// | `INVARIANT`        | The recovered `Secret` is internally inconsistent.               |
    /// | `STORAGE`          | A store I/O call failed mid-restore.                             |
    #[wasm_bindgen(js_name = "restore")]
    pub async fn restore(
        &mut self,
        recovered_secret: JsValue,
        version: u32,
    ) -> Result<JsValue, JsValue> {
        let secret = parse_recovered_secret(recovered_secret)?;
        let rust_events = self
            .inner
            .restore(&secret, version)
            .await
            .map_err(|e| match e {
                crate::Error::Restore(inner) => restore_error_to_js(inner),
                other => js_error_from_lib(other),
            })?;
        let js_events = Array::new();
        for event in rust_events {
            js_events.push(&events::event_to_js(event)?);
        }
        Ok(js_events.into())
    }
}

fn parse_recovered_secret(value: JsValue) -> Result<crate::protocol::types::Secret, JsValue> {
    /// One advertised endpoint: URI plus the `Protocol` discriminant, so
    /// no protocol is inferred from a scheme.
    #[derive(serde::Deserialize)]
    struct EndpointIn {
        uri: String,
        protocol: i32,
    }

    impl From<EndpointIn> for derec_proto::TransportProtocol {
        fn from(j: EndpointIn) -> Self {
            derec_proto::TransportProtocol {
                uri: j.uri,
                protocol: j.protocol,
            }
        }
    }

    #[derive(serde::Deserialize)]
    struct HelperIn {
        channel_id: String,
        transports: Vec<EndpointIn>,
        shared_key: Vec<u8>,
        #[serde(default)]
        communication_info: HashMap<String, String>,
    }
    #[derive(serde::Deserialize)]
    struct ReplicaIn {
        replica_id: String,
        transports: Vec<EndpointIn>,
        /// `"Source"` or `"Destination"`.
        role: String,
        #[serde(default)]
        communication_info: HashMap<String, String>,
    }
    #[derive(serde::Deserialize)]
    struct UserSecretIn {
        id: Vec<u8>,
        name: String,
        data: Vec<u8>,
    }
    #[derive(serde::Deserialize)]
    struct SecretIn {
        #[serde(default)]
        helpers: Vec<HelperIn>,
        #[serde(default)]
        secrets: Vec<UserSecretIn>,
        #[serde(default)]
        replicas: Option<ReplicasIn>,
    }
    #[derive(serde::Deserialize)]
    struct ReplicasIn {
        #[serde(default)]
        channel_id: String,
        #[serde(default)]
        members: Vec<ReplicaIn>,
        #[serde(default)]
        shared_key: Vec<u8>,
    }

    let input: SecretIn = serde_wasm_bindgen::from_value(value)
        .map_err(|e| js_error("INVALID_RECOVERED_SECRET", e.to_string()))?;

    let parse_u64 = |s: &str, ctx: &str| -> Result<u64, JsValue> {
        if s.is_empty() {
            return Ok(0);
        }
        s.parse::<u64>().map_err(|e| {
            js_error(
                "INVALID_RECOVERED_SECRET",
                format!("{ctx} must be a u64 decimal string: {e}"),
            )
        })
    };

    let helpers = input
        .helpers
        .into_iter()
        .map(|h| -> Result<_, JsValue> {
            Ok(crate::protocol::types::HelperInfo {
                channel_id: parse_u64(&h.channel_id, "helper.channel_id")?,
                transports: h.transports.into_iter().map(Into::into).collect(),
                shared_key: h.shared_key,
                communication_info: h.communication_info,
            })
        })
        .collect::<Result<Vec<_>, _>>()?;

    let replicas = input
        .replicas
        .map(|g| -> Result<_, JsValue> {
            let members = g
                .members
                .into_iter()
                .map(|r| -> Result<_, JsValue> {
                    let role = match r.role.as_str() {
                        "Source" => crate::protocol::types::ReplicaRole::Source,
                        "Destination" => crate::protocol::types::ReplicaRole::Destination,
                        other => {
                            return Err(js_error(
                                "INVALID_RECOVERED_SECRET",
                                format!(
                                    "replica.role must be \"Source\" or \"Destination\", got {other:?}"
                                ),
                            ));
                        }
                    };
                    Ok(crate::protocol::types::ReplicaInfo {
                        replica_id: parse_u64(&r.replica_id, "replica.replica_id")?,
                        transports: r.transports.into_iter().map(Into::into).collect(),
                        role: role as i32,
                        communication_info: r.communication_info,
                    })
                })
                .collect::<Result<Vec<_>, _>>()?;
            Ok(crate::protocol::types::Replicas {
                channel_id: parse_u64(&g.channel_id, "replicas.channel_id")?,
                members,
                shared_key: g.shared_key,
            })
        })
        .transpose()?;

    let secrets = input
        .secrets
        .into_iter()
        .map(|s| crate::protocol::types::UserSecret {
            id: s.id,
            name: s.name,
            data: s.data,
        })
        .collect();

    Ok(crate::protocol::types::Secret {
        helpers,
        secrets,
        replicas,
    })
}

fn restore_error_to_js(e: crate::protocol::RestoreError) -> JsValue {
    use crate::protocol::RestoreError;
    match e {
        RestoreError::AlreadyRestored => js_error("ALREADY_RESTORED", e.to_string()),
        RestoreError::Conflict(ids) => {
            #[derive(serde::Serialize)]
            struct ConflictError {
                code: &'static str,
                message: String,
                channel_ids: Vec<String>,
            }
            serde_wasm_bindgen::to_value(&ConflictError {
                code: "CONFLICT",
                message: "restore blocked by pre-existing channels at canonical ids".to_owned(),
                channel_ids: ids.iter().map(|c| c.0.to_string()).collect(),
            })
            .unwrap_or_else(|_| js_error("CONFLICT", "restore conflict"))
        }
        RestoreError::Invariant(msg) => js_error("INVARIANT", msg.to_string()),
    }
}

/// Produce a structured JS error for `NonOkStatus` responses.
///
/// Returns `{ code: "NON_OK_STATUS", message, status, memo, channel_id? }`.
fn non_ok_status_error(status: i32, memo: &str, channel_id: Option<&str>) -> JsValue {
    #[derive(serde::Serialize)]
    struct NonOkStatusError<'a> {
        code: &'static str,
        message: String,
        status: i32,
        memo: &'a str,
        #[serde(skip_serializing_if = "Option::is_none")]
        channel_id: Option<&'a str>,
    }

    serde_wasm_bindgen::to_value(&NonOkStatusError {
        code: "NON_OK_STATUS",
        message: format!("non-ok status (status={status}): {memo}"),
        status,
        memo,
        channel_id,
    })
    .unwrap_or_else(|_| JsValue::from_str("failed to serialize non-ok status error"))
}

/// Produce a structured JS error for general `process()` failures.
///
/// Returns `{ code: "DEREC_ERROR", message, channel_id? }`.
fn process_error(message: String, channel_id: Option<&str>) -> JsValue {
    #[derive(serde::Serialize)]
    struct ProcessErrorJs<'a> {
        code: &'static str,
        message: String,
        #[serde(skip_serializing_if = "Option::is_none")]
        channel_id: Option<&'a str>,
    }

    serde_wasm_bindgen::to_value(&ProcessErrorJs {
        code: "DEREC_ERROR",
        message,
        channel_id,
    })
    .unwrap_or_else(|_| JsValue::from_str("failed to serialize process error"))
}

fn parse_optional_channel_id(val: JsValue) -> Result<Option<ChannelId>, JsValue> {
    if val.is_null() || val.is_undefined() {
        return Ok(None);
    }
    Ok(Some(ChannelId(js_value_to_u64(val)?)))
}

/// Convert a JS value to a Rust `u64`.
///
/// Accepts BigInt, Number, or decimal-string encodings. Strings are
/// the documented wire convention for u64 identifiers on the JS/TS
/// surface (see `packages/{nodejs,web}/index.d.ts`) — they dodge
/// `Number.MAX_SAFE_INTEGER` without forcing every caller to reach for
/// BigInt.
fn js_value_to_u64(val: JsValue) -> Result<u64, JsValue> {
    if val.is_bigint() {
        let s = js_sys::BigInt::from(val)
            .to_string(10)
            .map_err(|e| js_error("DECODE_ERROR", format!("{e:?}")))?
            .as_string()
            .ok_or_else(|| js_error("DECODE_ERROR", "BigInt.toString returned non-string"))?;
        s.parse::<u64>()
            .map_err(|e| js_error("DECODE_ERROR", e.to_string()))
    } else if let Some(s) = val.as_string() {
        s.parse::<u64>()
            .map_err(|e| js_error("DECODE_ERROR", format!("string is not a decimal u64: {e}")))
    } else {
        val.as_f64()
            .ok_or_else(|| {
                js_error(
                    "DECODE_ERROR",
                    "value must be BigInt, number, or decimal string",
                )
            })
            .map(|f| f as u64)
    }
}

fn parse_sender_kind(kind: u32) -> Result<SenderKind, JsValue> {
    match kind {
        0 => Ok(SenderKind::Owner),
        1 => Ok(SenderKind::Helper),
        3 => Ok(SenderKind::ReplicaSource),
        4 => Ok(SenderKind::ReplicaDestination),
        _ => Err(js_error(
            "INVALID_SENDER_KIND",
            format!(
                "invalid sender kind: {kind}, valid values are 0 (Owner), 1 (Helper), 3 (ReplicaSource), 4 (ReplicaDestination)"
            ),
        )),
    }
}

/// Parse a JS discovery target into [`Target`].
///
/// - `null` / `undefined` → `All`
/// - `BigInt` or `number` → `Single`
/// - `Array<BigInt | number>` → `Many`
fn parse_target(val: JsValue) -> Result<Target, JsValue> {
    if val.is_null() || val.is_undefined() {
        return Ok(Target::All);
    }
    if val.is_bigint() || val.as_f64().is_some() {
        let id = js_value_to_u64(val)?;
        return Ok(Target::Single(ChannelId(id)));
    }
    if Array::is_array(&val) {
        let arr = Array::from(&val);
        let mut ids = Vec::with_capacity(arr.length() as usize);
        for i in 0..arr.length() {
            ids.push(ChannelId(js_value_to_u64(arr.get(i))?));
        }
        return Ok(Target::Many(ids));
    }
    Err(js_error(
        "INVALID_DISCOVERY_TARGET",
        "target must be null (all), a BigInt (single), or an array of BigInts (many)",
    ))
}

/// Parse a JS `Array<{ id: Uint8Array, name: string, data: Uint8Array }>` into
/// a `Vec<UserSecret>`.
fn parse_user_secrets(val: JsValue) -> Result<Vec<UserSecret>, JsValue> {
    let arr = Array::from(&val);
    let mut result = Vec::with_capacity(arr.length() as usize);
    for i in 0..arr.length() {
        let entry = arr.get(i);
        let id = js_sys::Reflect::get(&entry, &JsValue::from_str("id"))
            .map_err(|e| js_error("DECODE_ERROR", format!("missing id: {e:?}")))?;
        let name = js_sys::Reflect::get(&entry, &JsValue::from_str("name"))
            .map_err(|e| js_error("DECODE_ERROR", format!("missing name: {e:?}")))?
            .as_string()
            .ok_or_else(|| js_error("DECODE_ERROR", "name must be a string"))?;
        let data = js_sys::Reflect::get(&entry, &JsValue::from_str("data"))
            .map_err(|e| js_error("DECODE_ERROR", format!("missing data: {e:?}")))?;
        result.push(UserSecret {
            id: Uint8Array::new(&id).to_vec(),
            name,
            data: Uint8Array::new(&data).to_vec(),
        });
    }
    Ok(result)
}

/// Parse a JS flow kind + params into a [`DeRecFlow`].
///
/// Flow kinds:
/// - `0` = Pairing: `{ kind: number, contact: ContactMessage, peerCommunicationInfo?: Record<string, string> }`
/// - `1` = Discovery: `{ target: BigInt | BigInt[] | null }`
/// - `2` = ProtectSecret: `{ secrets: UserSecret[], description?: string }`
/// - `3` = VerifyShares: `{ version: number, target: BigInt | BigInt[] | null }`
/// - `4` = RecoverSecret: `{ secretId: Uint8Array, version: number }`
/// - `5` = Unpair: `{ target: BigInt | BigInt[] | null, memo?: string }`
fn parse_flow(flow_kind: u32, params: JsValue) -> Result<DeRecFlow, JsValue> {
    match flow_kind {
        0 => {
            // Pairing
            let kind_val = js_sys::Reflect::get(&params, &JsValue::from_str("kind"))
                .map_err(|e| js_error("DECODE_ERROR", format!("missing kind: {e:?}")))?;
            let kind = kind_val
                .as_f64()
                .ok_or_else(|| js_error("DECODE_ERROR", "kind must be a number"))?
                as u32;
            let sender_kind = parse_sender_kind(kind)?;
            let contact_val = js_sys::Reflect::get(&params, &JsValue::from_str("contact"))
                .map_err(|e| js_error("DECODE_ERROR", format!("missing contact: {e:?}")))?;
            let contact: PairingContactMessage = serde_wasm_bindgen::from_value(contact_val)
                .map_err(|e| js_error("DECODE_ERROR", e.to_string()))?;
            let contact: derec_proto::ContactMessage = contact.into();
            let raw = js_sys::Reflect::get(&params, &JsValue::from_str("peerCommunicationInfo"))
                .unwrap_or(JsValue::UNDEFINED);
            let peer_communication_info: HashMap<String, String> =
                if raw.is_null() || raw.is_undefined() {
                    HashMap::new()
                } else {
                    serde_wasm_bindgen::from_value(raw)
                        .map_err(|e| js_error("INVALID_PEER_COMMUNICATION_INFO", e.to_string()))?
                };
            Ok(DeRecFlow::Pairing {
                kind: sender_kind,
                contact,
                peer_communication_info,
            })
        }
        1 => {
            // Discovery
            let target_val = js_sys::Reflect::get(&params, &JsValue::from_str("target"))
                .unwrap_or(JsValue::UNDEFINED);
            let target = parse_target(target_val)?;
            Ok(DeRecFlow::Discovery { target })
        }
        2 => {
            // ProtectSecret
            let secrets_val = js_sys::Reflect::get(&params, &JsValue::from_str("secrets"))
                .map_err(|e| js_error("DECODE_ERROR", format!("missing secrets: {e:?}")))?;
            let secrets = parse_user_secrets(secrets_val)?;
            let description = js_sys::Reflect::get(&params, &JsValue::from_str("description"))
                .unwrap_or(JsValue::UNDEFINED)
                .as_string();
            Ok(DeRecFlow::ProtectSecret {
                secrets,
                description,
            })
        }
        3 => {
            // VerifyShares
            let secret_id_val = js_sys::Reflect::get(&params, &JsValue::from_str("secretId"))
                .map_err(|e| js_error("DECODE_ERROR", format!("missing secretId: {e:?}")))?;
            let secret_id = js_value_to_u64(secret_id_val)?;
            let version = js_sys::Reflect::get(&params, &JsValue::from_str("version"))
                .map_err(|e| js_error("DECODE_ERROR", format!("missing version: {e:?}")))?
                .as_f64()
                .ok_or_else(|| js_error("DECODE_ERROR", "version must be a number"))?
                as u32;
            let target_val = js_sys::Reflect::get(&params, &JsValue::from_str("target"))
                .unwrap_or(JsValue::UNDEFINED);
            let target = parse_target(target_val)?;
            Ok(DeRecFlow::VerifyShares {
                secret_id,
                version,
                target,
            })
        }
        4 => {
            // RecoverSecret
            let secret_id_val = js_sys::Reflect::get(&params, &JsValue::from_str("secretId"))
                .map_err(|e| js_error("DECODE_ERROR", format!("missing secretId: {e:?}")))?;
            let secret_id = js_value_to_u64(secret_id_val)?;
            let version = js_sys::Reflect::get(&params, &JsValue::from_str("version"))
                .map_err(|e| js_error("DECODE_ERROR", format!("missing version: {e:?}")))?
                .as_f64()
                .ok_or_else(|| js_error("DECODE_ERROR", "version must be a number"))?
                as u32;
            Ok(DeRecFlow::RecoverSecret { secret_id, version })
        }
        5 => {
            // Unpair
            let channel_id_val = js_sys::Reflect::get(&params, &JsValue::from_str("channel_id"))
                .map_err(|e| js_error("DECODE_ERROR", format!("missing channel_id: {e:?}")))?;
            let channel_id = ChannelId(js_value_to_u64(channel_id_val)?);
            let memo = js_sys::Reflect::get(&params, &JsValue::from_str("memo"))
                .unwrap_or(JsValue::UNDEFINED)
                .as_string();
            Ok(DeRecFlow::Unpair { channel_id, memo })
        }
        6 => {
            // UpdateChannelInfo
            //
            // Wire-shape mirrors the dotnet `UpdateChannelInfoParams`:
            // `{ target, communication_info?, transport_protocol?: { uri, protocol: number } }`.
            // Field names are snake_case for SDK parity.
            let target_val = js_sys::Reflect::get(&params, &JsValue::from_str("target"))
                .unwrap_or(JsValue::UNDEFINED);
            let target = parse_target(target_val)?;
            let communication_info_val =
                js_sys::Reflect::get(&params, &JsValue::from_str("communication_info"))
                    .unwrap_or(JsValue::UNDEFINED);
            let communication_info: Option<HashMap<String, String>> =
                if communication_info_val.is_null() || communication_info_val.is_undefined() {
                    None
                } else {
                    Some(
                        serde_wasm_bindgen::from_value(communication_info_val)
                            .map_err(|e| js_error("INVALID_COMMUNICATION_INFO", e.to_string()))?,
                    )
                };
            #[derive(serde::Deserialize)]
            struct TransportShape {
                uri: String,
                protocol: i32,
            }
            let read_one = |v: JsValue| -> Result<TransportProtocol, JsValue> {
                let parsed: TransportShape = serde_wasm_bindgen::from_value(v)
                    .map_err(|e| js_error("INVALID_TRANSPORT_PROTOCOL", e.to_string()))?;
                Ok(TransportProtocol {
                    uri: parsed.uri,
                    protocol: parsed.protocol,
                })
            };

            // The list wins when present; the singular field is the
            // deprecated spelling a host predating it still sends.
            let own_transports_val =
                js_sys::Reflect::get(&params, &JsValue::from_str("own_transports"))
                    .unwrap_or(JsValue::UNDEFINED);
            let own_transports =
                if own_transports_val.is_null() || own_transports_val.is_undefined() {
                    let singular =
                        js_sys::Reflect::get(&params, &JsValue::from_str("transport_protocol"))
                            .unwrap_or(JsValue::UNDEFINED);
                    if singular.is_null() || singular.is_undefined() {
                        Vec::new()
                    } else {
                        vec![read_one(singular)?]
                    }
                } else {
                    let array = js_sys::Array::from(&own_transports_val);
                    let mut out = Vec::with_capacity(array.length() as usize);
                    for entry in array.iter() {
                        out.push(read_one(entry)?);
                    }
                    out
                };
            Ok(DeRecFlow::UpdateChannelInfo {
                target,
                communication_info,
                own_transports,
            })
        }
        8 => {
            // UnpairReplica: `{ replica_id, memo? }`. `replica_id` is a
            // decimal string so large values survive JS number handling.
            let replica_id_val = js_sys::Reflect::get(&params, &JsValue::from_str("replica_id"))
                .unwrap_or(JsValue::UNDEFINED);
            // A decimal string, so ids above 2^53 survive JS number handling.
            let replica_id: u64 = replica_id_val
                .as_string()
                .ok_or_else(|| {
                    js_error(
                        "INVALID_FLOW_PARAMS",
                        "replica_id must be a decimal string".to_owned(),
                    )
                })?
                .parse::<u64>()
                .map_err(|e| {
                    js_error(
                        "INVALID_FLOW_PARAMS",
                        format!("replica_id must be a decimal u64: {e}"),
                    )
                })?;
            let memo_val = js_sys::Reflect::get(&params, &JsValue::from_str("memo"))
                .unwrap_or(JsValue::UNDEFINED);
            let memo = if memo_val.is_null() || memo_val.is_undefined() {
                None
            } else {
                memo_val.as_string()
            };
            Ok(DeRecFlow::UnpairReplica { replica_id, memo })
        }
        7 => {
            // ReplicaDiscovery takes no parameters: the group and this device's own
            // version are both read from the stores.
            Ok(DeRecFlow::ReplicaDiscovery)
        }
        _ => Err(js_error(
            "INVALID_FLOW_KIND",
            format!("invalid flow kind: {flow_kind}, must be 0..8"),
        )),
    }
}