derec-library 0.0.1-alpha.8

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
// 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",
//! );
//!
//! // 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;
// `pending_action_wire` lives in `crate::protocol` so both WASM and
// FFI bridges can share the same on-the-wire encoding for the opaque
// PendingAction blob.
pub(crate) use crate::protocol::pending_action_wire;
mod stores;

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

use crate::{
    protocol::{
        DeRecFlow, DeRecProtocol, DeRecProtocolBuilder, UnpairAck,
        types::{Target, UserSecret},
    },
    types::ChannelId,
    wasm::ts_bindings_utils::{js_error, js_error_from_lib},
};
use crate::wasm::primitives::pairing::ContactMessage as PairingContactMessage;
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 [`DeRecProtocol`](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, owner_replica_id }` (same nested shape as `ReplicaSecretReceived.secret`) |
/// | `NoOp`             | _(none)_                                               |
///
/// `SecretVersionEntry = { secret_id: bigint, versions: { version: number, description: string }[] }`
#[wasm_bindgen]
pub struct DeRecProtocolWasm {
    inner: WasmProtocol,
}

/// 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`, `withOwnTransport`. 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>,
    threshold: u32,
    keep_versions_count: u32,
    communication_info: HashMap<String, String>,
    timeout_in_secs: u32,
    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,
            threshold: 3,
            keep_versions_count: 3,
            communication_info: HashMap::new(),
            timeout_in_secs: 300,
            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` must be `"https"` (the only protocol supported today).
    #[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 = match parsed.protocol.to_lowercase().as_str() {
            "https" => 0i32,
            other => {
                return Err(js_error(
                    "INVALID_PROTOCOL",
                    format!("unknown protocol: {other}"),
                ));
            }
        };
        self.own_transport_uri = Some(parsed.uri);
        self.own_transport_protocol_num = Some(protocol_num);
        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
    }

    /// Protocol-wide staleness boundary (seconds). Clamped to at least
    /// 1. Default: 300.
    #[wasm_bindgen(js_name = withTimeout)]
    pub fn with_timeout(mut self, timeout_in_secs: u32) -> DeRecProtocolBuilderWasm {
        self.timeout_in_secs = timeout_in_secs.max(1);
        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 mirror the
    /// `ParameterRange` proto (`minShareSize`, `maxShareSize`,
    /// `minTimeBetweenVerifications`, ...). Each field is `i64` —
    /// accept either a number or a `BigInt` on the JS side. 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)]
        #[serde(rename_all = "camelCase")]
        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"))?;
        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.
        let own_transport = crate::transport::TransportProtocol::try_from(&proto_tp)
            .map_err(|e| js_error("INVALID_OWN_TRANSPORT", e.to_string()))?;

        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_transport(own_transport)
            .with_threshold(self.threshold as usize)
            .with_keep_versions_count(self.keep_versions_count as usize)
            .with_communication_info(self.communication_info)
            .with_timeout(Duration::from_secs(u64::from(self.timeout_in_secs)))
            .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);
        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 this node's local transport endpoint. See
    /// `setCommunicationInfo` for the matching update-propagation flow.
    /// 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 = match protocol.to_lowercase().as_str() {
            "https" => 0i32,
            other => {
                return Err(js_error(
                    "INVALID_PROTOCOL",
                    format!("unknown protocol: {other}"),
                ));
            }
        };
        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_transport(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()))
    }

    /// 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()))
    }

    /// Feed any incoming wire bytes to the protocol.
    ///
    /// Returns an `Array` of plain JS event objects (see struct-level docs for shapes).
    /// All five flows (pairing, sharing, verification, discovery, recovery) are
    /// 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> {
    #[derive(serde::Deserialize)]
    struct HelperIn {
        channel_id: String,
        transport_uri: String,
        shared_key: Vec<u8>,
        #[serde(default)]
        communication_info: HashMap<String, String>,
    }
    #[derive(serde::Deserialize)]
    struct ReplicaIn {
        channel_id: String,
        transport_uri: String,
        #[serde(default)]
        communication_info: HashMap<String, String>,
        replica_id: String,
        sender_kind: i32,
    }
    #[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>,
        #[serde(default)]
        owner_replica_id: String,
    }
    #[derive(serde::Deserialize)]
    struct ReplicasIn {
        #[serde(default)]
        replicas: 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")?,
                transport_uri: h.transport_uri,
                shared_key: h.shared_key,
                communication_info: h.communication_info,
            })
        })
        .collect::<Result<Vec<_>, _>>()?;

    let replicas = input
        .replicas
        .map(|g| -> Result<_, JsValue> {
            let replicas = g
                .replicas
                .into_iter()
                .map(|r| -> Result<_, JsValue> {
                    Ok(crate::protocol::types::ReplicaInfo {
                        channel_id: parse_u64(&r.channel_id, "replica.channel_id")?,
                        transport_uri: r.transport_uri,
                        communication_info: r.communication_info,
                        replica_id: parse_u64(&r.replica_id, "replica.replica_id")?,
                        sender_kind: r.sender_kind,
                    })
                })
                .collect::<Result<Vec<_>, _>>()?;
            Ok(crate::protocol::types::Replicas {
                replicas,
                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();

    let owner_replica_id = parse_u64(&input.owner_replica_id, "owner_replica_id")?;

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

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())
                        })?,
                    )
                };
            let transport_protocol_val =
                js_sys::Reflect::get(&params, &JsValue::from_str("transport_protocol"))
                    .unwrap_or(JsValue::UNDEFINED);
            let transport_protocol = if transport_protocol_val.is_null()
                || transport_protocol_val.is_undefined()
            {
                None
            } else {
                #[derive(serde::Deserialize)]
                struct TransportShape {
                    uri: String,
                    protocol: i32,
                }
                let parsed: TransportShape = serde_wasm_bindgen::from_value(transport_protocol_val)
                    .map_err(|e| js_error("INVALID_TRANSPORT_PROTOCOL", e.to_string()))?;
                Some(TransportProtocol {
                    uri: parsed.uri,
                    protocol: parsed.protocol,
                })
            };
            Ok(DeRecFlow::UpdateChannelInfo {
                target,
                communication_info,
                transport_protocol,
            })
        }
        _ => Err(js_error(
            "INVALID_FLOW_KIND",
            format!("invalid flow kind: {flow_kind}, must be 0..6"),
        )),
    }
}