openrtc 1.0.4

OpenRTC: a Rust-first P2P runtime for device discovery, signaling, and iroh/QUIC networking.
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
pub mod application_crypto;
pub mod application_crypto_streams;
pub mod client;
pub mod connection;
pub mod explicit_transfer_crypto;
pub mod firebase;
pub(crate) mod generated;
pub mod heartbeat;
pub(crate) mod iroh_connection_policy;
pub mod key_agreement;
pub mod lifecycle_reason;
pub(crate) mod native_moq_policy;
pub mod native_protocol;
#[cfg(not(target_arch = "wasm32"))]
pub(crate) mod native_send_policy;
pub(crate) mod native_webrtc_policy;
pub mod presence;
pub mod route_policy;
pub mod runtime_policy;
pub mod session_token;
pub mod signaling;
pub mod stream_metadata;
pub(crate) mod transport_label;

#[cfg(all(not(target_arch = "wasm32"), feature = "transport-lan"))]
pub mod local_discovery;

#[cfg(all(target_arch = "wasm32", feature = "transport-webrtc"))]
compile_error!(
    "feature `transport-webrtc` is native-only and must not be enabled for wasm32 targets"
);

#[cfg(all(target_arch = "wasm32", feature = "transport-moq"))]
compile_error!("feature `transport-moq` is native-only and must not be enabled for wasm32 targets");

/// Test constants — use these instead of hardcoding project IDs in tests.
/// Unit tests that don't hit real Firestore should use TEST_PROJECT_ID.
/// Live/integration tests must use LIVE_PROJECT_ID ("pluto-rtc-prod").
#[cfg(test)]
pub mod test_constants {
    pub const TEST_PROJECT_ID: &str = "test-project";
    pub const TEST_API_KEY: &str = "pk_test_0000000000000000000000000000000000000000";
}

/// Re-export for downstream crates' tests.
pub const LIVE_PROJECT_ID: &str = "pluto-rtc-prod";

pub fn app_tag_from_api_key(api_key: &str) -> String {
    let trimmed = api_key.trim();
    if trimmed.is_empty() {
        return "app_anonymous".to_string();
    }

    let suffix_len = trimmed.len().min(16);
    format!("app_{}", &trimmed[trimmed.len() - suffix_len..])
}

pub fn space_app_tag_from_keys(api_key: &str, space_key: &str) -> String {
    let input = format!("{}:{}", api_key.trim(), space_key.trim());
    let digest = <sha2::Sha256 as sha2::Digest>::digest(input.as_bytes());
    format!("space::{}", hex::encode(digest))
}

#[cfg(not(target_arch = "wasm32"))]
pub fn ensure_default_rustls_provider() {
    if rustls::crypto::CryptoProvider::get_default().is_none() {
        let _ = rustls::crypto::ring::default_provider().install_default();
    }
}

#[cfg(not(target_arch = "wasm32"))]
pub mod adapters;

pub mod connection_manager;
pub mod logging;

#[cfg(not(target_arch = "wasm32"))]
pub mod protocol_registry;

#[cfg(not(target_arch = "wasm32"))]
pub mod runtime_manager;

#[cfg(not(target_arch = "wasm32"))]
pub mod transport;

#[cfg(not(target_arch = "wasm32"))]
pub use client::EndpointHandle;

#[cfg(all(
    not(target_arch = "wasm32"),
    not(any(target_os = "ios", target_os = "android"))
))]
pub mod sso;

#[cfg(not(target_arch = "wasm32"))]
pub mod native_node;

#[cfg(not(target_arch = "wasm32"))]
pub mod native_device;

#[cfg(not(target_arch = "wasm32"))]
pub mod native_auth;

#[cfg(target_arch = "wasm32")]
pub mod wasm_node;

#[cfg(target_arch = "wasm32")]
#[macro_export]
macro_rules! console_log {
    ($($t:tt)*) => (web_sys::console::log_1(&wasm_bindgen::JsValue::from_str(&format_args!($($t)*).to_string())))
}

// WASM entry point bindings
#[cfg(target_arch = "wasm32")]
pub mod wasm_api {
    use crate::client::Client;
    use crate::session_token::split_compound_ticket;
    use crate::wasm_node::{
        into_js_readable_stream, peer_uni_stream_from_send, BiStream, PeerUniStream,
    };
    use iroh_tickets::endpoint::EndpointTicket;
    use std::str::FromStr;
    use std::sync::{Arc, Mutex};
    use wasm_bindgen::prelude::*;
    use wasm_streams::readable::sys::ReadableStream as JsReadableStream;

    #[wasm_bindgen]
    pub struct WasmClient {
        inner: Arc<Client>,
        auth_token: Arc<Mutex<Option<String>>>,
        last_auth_log: Arc<Mutex<Option<(bool, usize)>>>,
    }

    #[wasm_bindgen]
    impl WasmClient {
        #[wasm_bindgen(constructor)]
        pub fn new(project_id: String, tag: String) -> Result<WasmClient, JsValue> {
            Self::new_with_app_tag(project_id, tag)
        }

        #[wasm_bindgen(js_name = newWithAppTag)]
        pub fn new_with_app_tag(
            project_id: String,
            app_tag: String,
        ) -> Result<WasmClient, JsValue> {
            let auth_token: Arc<Mutex<Option<String>>> = Arc::new(Mutex::new(None));
            let token_state = auth_token.clone();
            let token_provider = Box::new(move || -> Option<String> {
                token_state.lock().ok().and_then(|guard| guard.clone())
            });

            Ok(Self {
                inner: Arc::new(Client::new_with_app_tag(
                    project_id,
                    app_tag,
                    token_provider,
                )),
                auth_token,
                last_auth_log: Arc::new(Mutex::new(None)),
            })
        }

        pub fn set_auth_token(&self, token: Option<String>) {
            let has_token = token.as_ref().map(|t| !t.is_empty()).unwrap_or(false);
            let token_len = token.as_ref().map(|t| t.len()).unwrap_or(0);

            if let Ok(mut guard) = self.auth_token.lock() {
                *guard = token.filter(|t| !t.is_empty());
            }

            let should_log = if let Ok(mut guard) = self.last_auth_log.lock() {
                let next = (has_token, token_len);
                if guard.as_ref() == Some(&next) {
                    false
                } else {
                    *guard = Some(next);
                    true
                }
            } else {
                true
            };

            if should_log {
                web_sys::console::log_1(&JsValue::from_str(&format!(
                    "[OPENRTC][WASM-AUTH] set_auth_token called has_token={} token_len={}",
                    has_token, token_len
                )));
            }
        }

        /// Normalize and rank eligible route labels using the Rust-owned pure
        /// policy. This does not dial, retry, promote, demote, or mutate state.
        #[wasm_bindgen(js_name = rankRoutes)]
        pub fn rank_routes(
            &self,
            configured_priority: Vec<String>,
            candidates: Vec<String>,
        ) -> Vec<String> {
            crate::route_policy::rank_routes(&configured_priority, &candidates)
        }

        pub async fn init_iroh(&self, secret_key: Option<Vec<u8>>) -> Result<String, JsValue> {
            let started_at = js_sys::Date::now();
            web_sys::console::log_1(&JsValue::from_str(&format!(
                "[OPENRTC][WASM-API] init_iroh called has_secret_key={} secret_key_len={}",
                secret_key.as_ref().is_some(),
                secret_key.as_ref().map(|k| k.len()).unwrap_or(0)
            )));
            match self.inner.init_iroh(secret_key, vec![]).await {
                Ok(node_id) => {
                    self.inner.clone().start_wasm_accept_bridge();
                    let elapsed = js_sys::Date::now() - started_at;
                    web_sys::console::log_1(&JsValue::from_str(&format!(
                        "[OPENRTC][WASM-API] init_iroh success elapsed_ms={:.0} node_id={}",
                        elapsed, node_id
                    )));
                    Ok(node_id)
                }
                Err(err) => {
                    let elapsed = js_sys::Date::now() - started_at;
                    web_sys::console::error_1(&JsValue::from_str(&format!(
                        "[OPENRTC][WASM-API] init_iroh failed elapsed_ms={:.0} error={}",
                        elapsed, err
                    )));
                    Err(JsValue::from_str(&err.to_string()))
                }
            }
        }

        pub async fn iroh_secret_key(&self) -> Result<Vec<u8>, JsValue> {
            let node_guard = self.inner.iroh_node.read().await;
            if let Some(node) = node_guard.as_ref() {
                Ok(node.secret_key())
            } else {
                Err(JsValue::from_str("Iroh node not initialized"))
            }
        }

        pub async fn node_addr(&self) -> Result<String, JsValue> {
            let node_guard = self.inner.iroh_node.read().await;
            if let Some(node) = node_guard.as_ref() {
                let addr = node
                    .node_addr()
                    .await
                    .map_err(|e| JsValue::from_str(&e.to_string()))?;
                serde_json::to_string(&addr).map_err(|e| JsValue::from_str(&e.to_string()))
            } else {
                Err(JsValue::from_str("Iroh node not initialized"))
            }
        }

        pub async fn endpoint_ticket(&self) -> Result<String, JsValue> {
            self.inner
                .endpoint_ticket()
                .await
                .map_err(|e| JsValue::from_str(&e.to_string()))
        }

        /// Build a compound ticket with an embedded session token.
        /// Registers the token on the canonical Rust client and returns the compound ticket string.
        /// `scope`: logical label (e.g. "share"). `max_connections`: 0 = unlimited.
        pub async fn endpoint_ticket_with_token(
            &self,
            grant_scope: String,
            max_connections: u32,
        ) -> Result<String, JsValue> {
            self.inner
                .endpoint_ticket_with_token(&grant_scope, max_connections)
                .await
                .map_err(|e| JsValue::from_str(&e.to_string()))
        }

        /// Register a session token on the canonical Rust client.
        pub fn register_session_token(
            &self,
            token: String,
            grant_scope: String,
            max_connections: u32,
        ) {
            self.inner
                .register_session_token(token, grant_scope, max_connections);
        }

        /// Register a session token with an absolute Unix-millisecond expiry.
        pub fn register_session_token_with_expiry_ms(
            &self,
            token: String,
            grant_scope: String,
            max_connections: u32,
            expires_at_ms: u64,
        ) {
            self.inner.register_session_token_with_expiry_ms(
                token,
                grant_scope,
                max_connections,
                expires_at_ms,
            );
        }

        /// Mark a connection as requiring application crypto on native outbound paths.
        #[wasm_bindgen(js_name = setConnectionApplicationCryptoRequired)]
        pub fn set_connection_application_crypto_required(
            &self,
            connection_id: String,
        ) -> Result<(), JsValue> {
            self.inner
                .set_connection_application_crypto_required(&connection_id);
            Ok(())
        }

        /// Install a negotiated per-connection application crypto key for native send paths.
        #[wasm_bindgen(js_name = setConnectionApplicationCryptoKey)]
        pub async fn set_connection_application_crypto_key(
            &self,
            connection_id: String,
            key: Vec<u8>,
        ) -> Result<(), JsValue> {
            if key.len() != crate::application_crypto::APPLICATION_KEY_BYTES {
                return Err(JsValue::from_str("application crypto key must be 32 bytes"));
            }
            let mut key_bytes = [0u8; crate::application_crypto::APPLICATION_KEY_BYTES];
            key_bytes.copy_from_slice(&key);
            self.inner
                .set_connection_application_crypto_key(&connection_id, key_bytes);
            self.inner
                .emit_current_wasm_connection_state(&connection_id)
                .await;
            Ok(())
        }

        /// Retire the negotiated application key and ephemeral agreement for a
        /// logical connection. Connection ids may be reused after an ACL revoke
        /// and regrant, so lifecycle cleanup must clear the WASM runtime together
        /// with the TypeScript crypto indexes before a fresh handshake begins.
        #[wasm_bindgen(js_name = clearConnectionApplicationCryptoKey)]
        pub fn clear_connection_application_crypto_key(&self, connection_id: String) {
            self.inner
                .clear_connection_application_crypto_key(&connection_id);
        }

        /// Validate (and consume one use of) a session token.
        /// Returns the scope string on success, throws on failure.
        /// If the registry is empty, always succeeds (backward-compat gate).
        pub fn validate_session_token(&self, token: String) -> Result<String, JsValue> {
            self.inner
                .validate_session_token(&token)
                .map_err(|e| JsValue::from_str(&e))
        }

        /// Validate and record token admission for a specific connection.
        pub async fn validate_session_token_for_connection(
            &self,
            token: String,
            connection_id: String,
        ) -> Result<String, JsValue> {
            self.inner
                .validate_session_token_for_connection(&token, &connection_id)
                .await
                .map_err(|e| JsValue::from_str(&e))
        }

        pub async fn validate_session_token_for_connection_with_payload(
            &self,
            token: String,
            connection_id: String,
            token_payload: Option<String>,
        ) -> Result<String, JsValue> {
            self.inner
                .validate_session_token_for_connection_with_payload(
                    &token,
                    &connection_id,
                    token_payload.as_deref(),
                )
                .await
                .map_err(|e| JsValue::from_str(&e))
        }

        /// Present a session token to the remote host over the SDK-owned
        /// native main stream before application traffic starts.
        /// Returns the approved scope string once the host acknowledges admission.
        ///
        /// Requires a managed transport record: call [`Self::connect_device`]
        /// (or another dial that runs `ensure_connected_addr`) before presenting.
        pub async fn present_session_token_to_host(
            &self,
            endpoint_id: String,
            token: String,
        ) -> Result<String, JsValue> {
            self.present_session_token_to_host_with_payload(endpoint_id, token, None)
                .await
        }

        pub async fn present_session_token_to_host_with_payload(
            &self,
            endpoint_id: String,
            token: String,
            token_payload: Option<String>,
        ) -> Result<String, JsValue> {
            self.present_session_token_to_host_with_payload_and_device_id(
                endpoint_id,
                token,
                token_payload,
                None,
            )
            .await
        }

        pub async fn present_session_token_to_host_with_payload_and_device_id(
            &self,
            endpoint_id: String,
            token: String,
            token_payload: Option<String>,
            device_id: Option<String>,
        ) -> Result<String, JsValue> {
            crate::console_log!(
                "[OpenRTC][session-admission][wasm-present] endpoint_id={} claimed_local_device_id={}",
                endpoint_id,
                device_id.as_deref().unwrap_or("<none>")
            );
            let endpoint_id_parsed: iroh::EndpointId = endpoint_id
                .parse()
                .map_err(|e| JsValue::from_str(&format!("{}", e)))?;
            let local_node_id = self.inner.current_node_id().await.ok_or_else(|| {
                JsValue::from_str("missing local node id for session-token presentation")
            })?;
            let connection_id =
                crate::client::Client::deterministic_connection_id(&local_node_id, &endpoint_id);
            let approval_scope = self
                .inner
                .present_and_accept_session_token_with_local_claim(
                    endpoint_id_parsed,
                    &connection_id,
                    &token,
                    token_payload.as_deref(),
                    None,
                    device_id,
                )
                .await
                .map_err(|e| JsValue::from_str(&e))?;
            self.inner
                .emit_current_wasm_connection_state(&connection_id)
                .await;

            Ok(approval_scope)
        }

        /// Report whether this runtime has the current transport-generation
        /// outbound admission proof required by an endpoint ticket.
        pub async fn remote_session_admission_ready_for_ticket(
            &self,
            endpoint_ticket: String,
        ) -> Result<bool, JsValue> {
            self.inner
                .remote_session_admission_ready_for_ticket(&endpoint_ticket)
                .await
                .map_err(|error| JsValue::from_str(&error.to_string()))
        }

        /// Fence one browser-relayed reciprocal presentation in the Rust
        /// admission owner before the adapter writes it to the stream.
        #[allow(clippy::too_many_arguments)]
        pub async fn prepare_inline_reciprocal_session_admission(
            &self,
            endpoint_id: String,
            expected_transport_stable_id: u64,
            stream_instance_id: String,
            presentation_id: String,
            token: String,
            token_payload: String,
            device_id: String,
            stream_contract: String,
        ) -> Result<bool, JsValue> {
            let endpoint_id: iroh::EndpointId = endpoint_id
                .parse()
                .map_err(|error| JsValue::from_str(&format!("{error}")))?;
            let stream_contract = match stream_contract.trim() {
                "one-shot-admission" => {
                    crate::native_protocol::SessionTokenStreamContract::OneShotAdmission
                }
                "persistent-control" => {
                    crate::native_protocol::SessionTokenStreamContract::PersistentControl
                }
                other => {
                    return Err(JsValue::from_str(&format!(
                        "unsupported reciprocal stream contract: {other}"
                    )))
                }
            };
            self.inner
                .prepare_inline_reciprocal_session_admission(
                    endpoint_id,
                    expected_transport_stable_id,
                    stream_instance_id.as_str(),
                    presentation_id.as_str(),
                    token.as_str(),
                    token_payload.as_str(),
                    device_id.as_str(),
                    stream_contract,
                )
                .await
                .map_err(|error| JsValue::from_str(&error))?;
            Ok(true)
        }

        /// Commit an inline reciprocal session admission only when the ACK
        /// belongs to the exact Rust-owned transcript and physical generation.
        pub async fn confirm_inline_reciprocal_session_admission(
            &self,
            endpoint_id: String,
            expected_transport_stable_id: u64,
            stream_instance_id: String,
            presentation_id: String,
            accepted: bool,
            approval_scope: Option<String>,
        ) -> Result<bool, JsValue> {
            let endpoint_id: iroh::EndpointId = endpoint_id
                .parse()
                .map_err(|error| JsValue::from_str(&format!("{error}")))?;
            self.inner
                .confirm_inline_reciprocal_session_admission(
                    endpoint_id,
                    expected_transport_stable_id,
                    stream_instance_id.as_str(),
                    presentation_id.as_str(),
                    accepted,
                    approval_scope.as_deref(),
                )
                .await
                .map_err(|error| JsValue::from_str(&error))?;
            self.inner
                .emit_current_wasm_connection_state(
                    &crate::client::Client::deterministic_connection_id(
                        &self.inner.current_node_id().await.ok_or_else(|| {
                            JsValue::from_str(
                                "missing local node id after reciprocal admission ACK",
                            )
                        })?,
                        &endpoint_id.to_string(),
                    ),
                )
                .await;
            Ok(true)
        }

        /// Revoke a single token by value.
        pub fn revoke_session_token(&self, token: String) -> Result<JsValue, JsValue> {
            serde_wasm_bindgen::to_value(&self.inner.revoke_session_token(&token))
                .map_err(|error| JsValue::from_str(&error.to_string()))
        }

        /// Revoke all tokens that match the given scope and disconnect affected peers.
        pub async fn revoke_tokens_by_scope(
            &self,
            grant_scope: String,
        ) -> Result<JsValue, JsValue> {
            let affected = self.inner.revoke_tokens_by_scope(&grant_scope).await;
            serde_wasm_bindgen::to_value(&affected).map_err(|e| JsValue::from_str(&e.to_string()))
        }

        /// Clear all short-lived session tokens and admission state.
        pub fn clear_session_tokens(&self) {
            self.inner.clear_session_tokens();
        }

        pub fn endpoint_id_from_ticket(&self, ticket: String) -> Result<String, JsValue> {
            let (iroh_ticket, _token_suffix) = split_compound_ticket(ticket.trim());
            let parsed = EndpointTicket::from_str(iroh_ticket)
                .map_err(|e| JsValue::from_str(&format!("Invalid endpoint ticket: {}", e)))?;
            Ok(parsed.endpoint_addr().id.to_string())
        }

        /// Deprecated: product code must dial through [`Self::connect_device`], which
        /// registers the connection and starts the wasm connect-event bridge.
        /// This raw stream export remains for legacy harness callers only.
        pub async fn connect(&self, ticket: String) -> Result<JsReadableStream, JsValue> {
            web_sys::console::warn_1(&wasm_bindgen::JsValue::from_str(
                "[OPENRTC][WASM-API] WasmClient.connect() is deprecated; use connect_device() for managed product dials.",
            ));
            let (iroh_ticket, _token_suffix) = split_compound_ticket(ticket.trim());
            let parsed = EndpointTicket::from_str(iroh_ticket)
                .map_err(|e| JsValue::from_str(&format!("Invalid endpoint ticket: {}", e)))?;
            let endpoint_addr = parsed.endpoint_addr().clone();
            let endpoint_id = endpoint_addr.id;
            let stream = {
                let node_guard = self.inner.iroh_node.read().await;
                if let Some(node) = node_guard.as_ref() {
                    node.connect_addr(endpoint_id, endpoint_addr)
                } else {
                    return Err(JsValue::from_str("Iroh node not initialized"));
                }
            };
            Ok(into_js_readable_stream(stream))
        }

        pub async fn disconnect(&self, endpoint_id: String) -> Result<(), JsValue> {
            let endpoint_id: iroh::EndpointId = endpoint_id
                .parse()
                .map_err(|e| JsValue::from_str(&format!("{}", e)))?;
            let node_guard = self.inner.iroh_node.read().await;
            if let Some(node) = node_guard.as_ref() {
                node.disconnect(endpoint_id)
                    .await
                    .map_err(|e| JsValue::from_str(&e.to_string()))
            } else {
                Err(JsValue::from_str("Iroh node not initialized"))
            }
        }

        /// Drop the iroh transport to a peer with a **transient** reason — a
        /// simulated network flap, as opposed to [`disconnect`] which signals a
        /// user/manual disconnect.
        ///
        /// `disconnect()` (and the generic close) reports `disconnected by user`,
        /// which `lifecycle_reason` classifies as `ManualDisconnect` — terminal and
        /// sticky: the remote will NOT auto-reconnect and WebRTC is retired
        /// immediately. That is correct for a real user action, but wrong for a
        /// transient transport drop. This variant uses a transient reason code
        /// (`network-change-forced-reconnect`, `is_transient_reconnect()`), so both
        /// peers treat the drop as a recoverable transition and auto-reconnect —
        /// the browser equivalent of the native test harness's `irohDisconnect`.
        pub async fn disconnect_transient(&self, endpoint_id: String) -> Result<(), JsValue> {
            let endpoint_id: iroh::EndpointId = endpoint_id
                .parse()
                .map_err(|e| JsValue::from_str(&format!("{}", e)))?;
            self.inner
                .disconnect_with_reason(
                    endpoint_id,
                    crate::lifecycle_reason::REASON_NETWORK_CHANGE_RECONNECT,
                )
                .await
                .map_err(|e| JsValue::from_str(&e.to_string()))
        }

        pub async fn is_connected(&self, endpoint_id: String) -> Result<bool, JsValue> {
            let endpoint_id: iroh::EndpointId = endpoint_id
                .parse()
                .map_err(|e| JsValue::from_str(&format!("{}", e)))?;
            Ok(self.inner.is_connected(endpoint_id).await)
        }

        pub fn runtime_policy(&self) -> Result<JsValue, JsValue> {
            serde_wasm_bindgen::to_value(&self.inner.runtime_policy_snapshot())
                .map_err(|e| JsValue::from_str(&e.to_string()))
        }

        pub async fn add_peer_scope(&self, id: String, scope: String) -> Result<JsValue, JsValue> {
            let scopes = self.inner.add_peer_scope(&id, &scope).await;
            serde_wasm_bindgen::to_value(&scopes).map_err(|e| JsValue::from_str(&e.to_string()))
        }

        pub async fn release_peer_scope(
            &self,
            id: String,
            scope: Option<String>,
        ) -> Result<JsValue, JsValue> {
            let scopes = self.inner.release_peer_scope(&id, scope.as_deref()).await;
            serde_wasm_bindgen::to_value(&scopes).map_err(|e| JsValue::from_str(&e.to_string()))
        }

        pub async fn peer_scopes(&self, id: String) -> Result<JsValue, JsValue> {
            let scopes = self.inner.peer_scopes(&id).await;
            serde_wasm_bindgen::to_value(&scopes).map_err(|e| JsValue::from_str(&e.to_string()))
        }

        pub async fn same_peer(&self, left: String, right: String) -> Result<bool, JsValue> {
            Ok(self.inner.same_peer(&left, &right).await)
        }

        pub async fn peer_snapshot(&self, id: String) -> Result<JsValue, JsValue> {
            let snapshot = self.inner.peer_snapshot(&id).await;
            serde_wasm_bindgen::to_value(&snapshot).map_err(|e| JsValue::from_str(&e.to_string()))
        }

        // U9: the `peer_snapshots()` wasm binding was retired; `peer_sessions()`
        // (below) is the single settled Rust projection exposed to TS.

        pub async fn peer_session(&self, id: String) -> Result<JsValue, JsValue> {
            let snapshot = self.inner.peer_session(&id).await;
            serde_wasm_bindgen::to_value(&snapshot).map_err(|e| JsValue::from_str(&e.to_string()))
        }

        pub async fn peer_sessions(&self) -> Result<JsValue, JsValue> {
            let snapshots = self.inner.peer_sessions().await;
            serde_wasm_bindgen::to_value(&snapshots).map_err(|e| JsValue::from_str(&e.to_string()))
        }

        pub async fn connection_state(&self, connection_id: String) -> Result<JsValue, JsValue> {
            let snapshot = self.inner.connection_state(&connection_id).await;
            serde_wasm_bindgen::to_value(&snapshot).map_err(|e| JsValue::from_str(&e.to_string()))
        }

        pub async fn connection_states(&self) -> Result<JsValue, JsValue> {
            let snapshots = self.inner.connection_states().await;
            serde_wasm_bindgen::to_value(&snapshots).map_err(|e| JsValue::from_str(&e.to_string()))
        }

        pub async fn wait_for_settled_peer(
            &self,
            id: String,
            timeout_ms: Option<u32>,
        ) -> Result<JsValue, JsValue> {
            let snapshot = self
                .inner
                .wait_for_settled_peer(&id, timeout_ms.map(|value| value as u64))
                .await;
            serde_wasm_bindgen::to_value(&snapshot).map_err(|e| JsValue::from_str(&e.to_string()))
        }

        pub async fn resolve_peer_connection_records(
            &self,
            id: String,
        ) -> Result<JsValue, JsValue> {
            let records = self.inner.resolve_peer_connection_records(&id).await;
            serde_wasm_bindgen::to_value(&records).map_err(|e| JsValue::from_str(&e.to_string()))
        }

        pub async fn list_managed_connections(&self) -> Result<JsValue, JsValue> {
            let records = self.inner.list_managed_connections().await;
            serde_wasm_bindgen::to_value(&records).map_err(|e| JsValue::from_str(&e.to_string()))
        }

        pub async fn bind_connection_device_id(
            &self,
            connection_id: String,
            device_id: String,
        ) -> Result<JsValue, JsValue> {
            let snapshot = self
                .inner
                .bind_connection_device_id(&connection_id, &device_id)
                .await;
            serde_wasm_bindgen::to_value(&snapshot).map_err(|e| JsValue::from_str(&e.to_string()))
        }

        pub async fn bind_node_device_id(
            &self,
            node_id: String,
            device_id: String,
        ) -> Result<(), JsValue> {
            self.inner.bind_node_device_id(&node_id, &device_id).await;
            Ok(())
        }

        pub async fn reject_connection_admission(
            &self,
            connection_id: String,
            reason: String,
        ) -> Result<JsValue, JsValue> {
            self.inner
                .reject_session_connection(&connection_id, &reason);
            self.inner
                .emit_current_wasm_connection_state(&connection_id)
                .await;
            let snapshot = self.inner.connection_state(&connection_id).await;
            serde_wasm_bindgen::to_value(&snapshot).map_err(|e| JsValue::from_str(&e.to_string()))
        }

        pub async fn report_managed_connection_settled(
            &self,
            connection_id: String,
            settled: bool,
            device_id: Option<String>,
            transport_stable_id: Option<u64>,
            transport_generation: Option<u64>,
            route_generation: Option<u64>,
        ) -> Result<JsValue, JsValue> {
            let snapshot = match (transport_stable_id, transport_generation, route_generation) {
                (Some(transport_stable_id), Some(transport_generation), Some(route_generation)) => {
                    self.inner
                        .report_managed_connection_settled_for_transport(
                            &connection_id,
                            settled,
                            transport_stable_id,
                            transport_generation,
                            route_generation,
                        )
                        .await
                }
                _ => None,
            };
            let _ = device_id;
            serde_wasm_bindgen::to_value(&snapshot).map_err(|e| JsValue::from_str(&e.to_string()))
        }

        pub async fn report_transport_status(
            &self,
            connection_id: String,
            active_transport: String,
            parallel_transport: Option<String>,
            transport_stable_id: Option<u64>,
            transport_generation: Option<u64>,
            route_generation: Option<u64>,
        ) -> Result<JsValue, JsValue> {
            let snapshot = match (transport_stable_id, transport_generation, route_generation) {
                (Some(transport_stable_id), Some(transport_generation), Some(route_generation)) => {
                    self.inner
                        .report_transport_status_for_generation(
                            &connection_id,
                            &active_transport,
                            parallel_transport.as_deref(),
                            transport_stable_id,
                            transport_generation,
                            route_generation,
                        )
                        .await
                }
                _ => None,
            };
            serde_wasm_bindgen::to_value(&snapshot).map_err(|e| JsValue::from_str(&e.to_string()))
        }

        pub async fn is_current_transport_stable_id(
            &self,
            endpoint_id: String,
            transport_stable_id: u64,
        ) -> Result<bool, JsValue> {
            let endpoint_id = endpoint_id
                .parse::<iroh::EndpointId>()
                .map_err(|error| JsValue::from_str(&error.to_string()))?;
            Ok(self
                .inner
                .is_current_transport_stable_id(endpoint_id, transport_stable_id)
                .await)
        }

        pub async fn open_bi(&self, endpoint_id: String) -> Result<BiStream, JsValue> {
            let endpoint_id: iroh::EndpointId = endpoint_id
                .parse()
                .map_err(|e| JsValue::from_str(&format!("{}", e)))?;
            self.inner
                .assert_raw_peer_stream_allowed(&endpoint_id)
                .await
                .map_err(|e| JsValue::from_str(&e.to_string()))?;
            // Parity with the native `Client::open_bi`: register/finalize the
            // connection_manager record for the (already-alive) transport before
            // handing out a raw peer stream, so browser raw-stream opens
            // (explicit transfer, native-main signaling) participate in
            // connection lifecycle / close tracking. Idempotent, and a no-op when
            // the transport is not alive. `Client::open_bi` itself is native-only
            // (it returns native iroh stream types), so the wasm binding cannot
            // delegate to it and must mirror its guard + record + open sequence.
            self.inner
                .ensure_connection_manager_record_before_peer_stream(&endpoint_id)
                .await
                .map_err(|e| JsValue::from_str(&e.to_string()))?;
            let (send, recv) = self
                .inner
                .open_bi_internal(endpoint_id)
                .await
                .map_err(|e| JsValue::from_str(&e.to_string()))?;
            Ok(BiStream::from_parts(send, recv, endpoint_id.to_string()))
        }

        /// Open a raw bi-stream for the SDK-owned native-main **control plane**
        /// (WebRTC signaling: SDP / ICE candidates / renegotiate, and the
        /// bootstrap application-route handshake).
        ///
        /// Unlike [`open_bi`], this is deliberately **exempt** from the
        /// application-crypto raw-open guard (`assert_raw_peer_stream_allowed`).
        /// That guard protects application *data* — but the control plane is not
        /// application data:
        ///   1. Signaling bootstraps the very application route (and key
        ///      agreement) it would otherwise depend on, so it cannot require app
        ///      crypto that has not been negotiated yet.
        ///   2. It is already authenticated by the iroh QUIC TLS that binds the
        ///      sender's node id.
        ///   3. The receiver classifies the stream by its `[0x00][len]["main"]`
        ///      native-main label and routes it to the signal handler; bytes sent
        ///      here can never be delivered as application data, so this cannot be
        ///      abused to smuggle unencrypted app payloads past the guard.
        ///
        /// This binding is intentionally named for native-main. It is not a
        /// general-purpose raw-stream escape hatch: JS callers must immediately
        /// write the `[0x00][len]["main"]` native-main label and then framed
        /// control payloads. Application data must continue to use `open_peer_bi`
        /// / `open_peer_uni` so the application-crypto guard stays fail-closed.
        ///
        /// Without this, a peer whose inbound native-main control writer was lost
        /// (e.g. after a rapid disconnect/reconnect flap) and that requires app
        /// crypto could not (re)open a signaling stream at all, stranding the
        /// edge on base Iroh because SDP offers/answers can never be exchanged.
        pub async fn open_native_main_control_bi(
            &self,
            endpoint_id: String,
        ) -> Result<BiStream, JsValue> {
            let endpoint_id: iroh::EndpointId = endpoint_id
                .parse()
                .map_err(|e| JsValue::from_str(&format!("{}", e)))?;
            self.inner
                .ensure_connection_manager_record_before_peer_stream(&endpoint_id)
                .await
                .map_err(|e| JsValue::from_str(&e.to_string()))?;
            let (send, recv) = self
                .inner
                .open_bi_internal(endpoint_id)
                .await
                .map_err(|e| JsValue::from_str(&e.to_string()))?;
            Ok(BiStream::from_parts(send, recv, endpoint_id.to_string()))
        }

        pub async fn open_peer_bi(
            &self,
            id: String,
            timeout_ms: Option<u32>,
        ) -> Result<BiStream, JsValue> {
            let (_connection_id, remote_node_id, send, recv) = self
                .inner
                .open_peer_bi(&id, timeout_ms.map(|value| value as u64))
                .await
                .map_err(|e| JsValue::from_str(&e.to_string()))?;
            Ok(BiStream::from_peer_parts(send, recv, remote_node_id))
        }

        /// Send a complete protected application frame on a fresh peer stream.
        /// Rust owns the QUIC FIN so JS readable cancellation cannot reset the
        /// one-shot stream before the remote runtime admits it.
        pub async fn send_peer_application_frame(
            &self,
            id: String,
            frame: Vec<u8>,
            timeout_ms: Option<u32>,
        ) -> Result<(), JsValue> {
            self.inner
                .send_peer_application_frame(&id, &frame, timeout_ms.map(|value| value as u64))
                .await
                .map_err(|error| JsValue::from_str(&error.to_string()))
        }

        /// Open a settled peer stream for explicit file transfer.
        ///
        /// The runtime writes the plaintext explicit-file protocol byte (`0x02`)
        /// before returning the send stream, then wraps only the transfer body
        /// with application crypto when a key is active for the peer.
        pub async fn open_peer_bi_explicit_file_sender(
            &self,
            id: String,
            timeout_ms: Option<u32>,
        ) -> Result<PeerUniStream, JsValue> {
            let (_connection_id, _remote_node_id, send) = self
                .inner
                .open_peer_bi_explicit_file_sender(&id, timeout_ms.map(|value| value as u64))
                .await
                .map_err(|e| JsValue::from_str(&e.to_string()))?;
            Ok(peer_uni_stream_from_send(send))
        }

        /// Open a bi-stream to a peer that is transport-connected but may not yet
        /// be settled (auth-ready). Use for latency probes and other transport-level
        /// diagnostics where `settled_ready` is not required.
        pub async fn open_peer_bi_transport_only(
            &self,
            id: String,
            timeout_ms: Option<u32>,
        ) -> Result<BiStream, JsValue> {
            let (_connection_id, remote_node_id, send, recv) = self
                .inner
                .open_peer_bi_transport_only(&id, timeout_ms.map(|value| value as u64))
                .await
                .map_err(|e| JsValue::from_str(&e.to_string()))?;
            Ok(BiStream::from_parts(send, recv, remote_node_id))
        }

        /// Open a settled peer bi-stream for a native host protocol and write
        /// the standard OpenRTC channel envelope before returning it to JS.
        ///
        /// This is intentionally narrower than `open_peer_bi_transport_only`:
        /// native Plutonium drive-view hosts authorize with OpenRTC session
        /// admission + drive scopes. The channel envelope is written through the
        /// protected peer stream, so keyed and unkeyed sessions use the same wire
        /// contract and never expose a plaintext product label beside encrypted
        /// payloads.
        pub async fn open_peer_native_bi(
            &self,
            id: String,
            label: String,
            timeout_ms: Option<u32>,
        ) -> Result<BiStream, JsValue> {
            if label != "drive-view" {
                return Err(JsValue::from_str(
                    "unsupported native peer stream label; only drive-view is allowed",
                ));
            }

            let (_connection_id, remote_node_id, mut send, recv) = self
                .inner
                .open_peer_bi(&id, timeout_ms.map(|value| value as u64))
                .await
                .map_err(|e| JsValue::from_str(&e.to_string()))?;
            let envelope = crate::stream_metadata::encode_channel_envelope(&label, None)
                .map_err(|e| JsValue::from_str(&e.to_string()))?;
            send.write_all(&envelope)
                .await
                .map_err(|e| JsValue::from_str(&e.to_string()))?;

            Ok(BiStream::from_peer_parts(send, recv, remote_node_id))
        }

        pub async fn open_uni(&self, endpoint_id: String) -> Result<PeerUniStream, JsValue> {
            let endpoint_id: iroh::EndpointId = endpoint_id
                .parse()
                .map_err(|e| JsValue::from_str(&format!("{}", e)))?;
            self.inner
                .assert_raw_peer_stream_allowed(&endpoint_id)
                .await
                .map_err(|e| JsValue::from_str(&e.to_string()))?;
            // Parity with the native `Client::open_uni`, which also finalizes the
            // connection_manager record before opening a raw uni peer stream.
            self.inner
                .ensure_connection_manager_record_before_peer_stream(&endpoint_id)
                .await
                .map_err(|e| JsValue::from_str(&e.to_string()))?;
            let node_guard = self.inner.iroh_node.read().await;
            if let Some(node) = node_guard.as_ref() {
                let send = node
                    .open_uni(endpoint_id.clone())
                    .await
                    .map_err(|e| JsValue::from_str(&e.to_string()))?;
                Ok(peer_uni_stream_from_send(
                    crate::application_crypto_streams::PeerSendStream::plain(send),
                ))
            } else {
                Err(JsValue::from_str("Iroh node not initialized"))
            }
        }

        pub async fn open_peer_uni(
            &self,
            id: String,
            timeout_ms: Option<u32>,
        ) -> Result<PeerUniStream, JsValue> {
            let (_connection_id, _remote_node_id, send) = self
                .inner
                .open_peer_uni(&id, timeout_ms.map(|value| value as u64))
                .await
                .map_err(|e| JsValue::from_str(&e.to_string()))?;
            Ok(peer_uni_stream_from_send(send))
        }

        /// Send `data` to `peer_id` using the best available transport.
        ///
        /// Native route order is edge-aware: proven upgraded routes stay first,
        /// relay/unknown iroh can probe upgraded transports first, and direct
        /// iroh/LAN/BLE paths stay primary with upgraded transports as fallback.
        ///
        /// On WASM this always routes through iroh (relay or QUIC as iroh determines).
        /// Use the TypeScript `Connection.sendTyped()` for full transport priority on the
        /// browser side — this binding is primarily for symmetry and native callers.
        pub async fn send_peer(&self, id: String, data: Vec<u8>) -> Result<(), JsValue> {
            self.inner
                .send_peer(&id, &data)
                .await
                .map_err(|e| JsValue::from_str(&e.to_string()))
        }

        /// Returns the current iroh path kind for a connected peer.
        ///
        /// Returns one of `"direct-quic"`, `"relay"`, or `"unknown"`.
        pub async fn iroh_path_kind(&self, peer_id: String) -> String {
            match self.inner.iroh_path_kind(&peer_id).await {
                crate::client::IrohPathKind::DirectQuic => "direct-quic".to_string(),
                crate::client::IrohPathKind::DirectLan => "direct-lan".to_string(),
                crate::client::IrohPathKind::Relay => "relay".to_string(),
                crate::client::IrohPathKind::Ble => "ble".to_string(),
                crate::client::IrohPathKind::Unknown => "unknown".to_string(),
            }
        }

        /// Returns the current iroh transport RTT in milliseconds, when iroh has
        /// selected a live path and published path stats.
        pub async fn iroh_transport_rtt_ms(&self, peer_id: String) -> Option<u32> {
            self.inner
                .iroh_transport_rtt_ms(&peer_id)
                .await
                .map(|value| value.min(u32::MAX as u64) as u32)
        }

        pub async fn incoming_streams(&self) -> Result<JsReadableStream, JsValue> {
            let (node, stream) = {
                let node_guard = self.inner.iroh_node.read().await;
                if let Some(node) = node_guard.as_ref() {
                    (node.clone(), node.incoming_streams_stream())
                } else {
                    return Err(JsValue::from_str("Iroh node not initialized"));
                }
            };

            use futures::StreamExt;
            let mapped_stream = stream.filter_map(move |incoming| {
                let node = node.clone();
                async move {
                    node.incoming_stream_is_current(&incoming)
                        .await
                        .then(|| crate::wasm_node::BiStream::incoming_to_js_value(incoming))
                }
            });

            Ok(wasm_streams::ReadableStream::from_stream(mapped_stream).into_raw())
        }

        pub async fn update_presence(
            &self,
            user_id: String,
            device_name: String,
            ticket: String,
            metadata: Option<String>,
            ttl_ms: Option<u64>,
        ) -> Result<(), JsValue> {
            self.inner
                .update_presence_with_ttl(
                    &user_id,
                    &device_name,
                    &ticket,
                    ttl_ms.unwrap_or(300_000),
                    metadata.as_deref(),
                )
                .await
                .map_err(|e| JsValue::from_str(&e.to_string()))
        }

        pub async fn send_message(
            &self,
            target_id: String,
            payload: String,
            state: Option<String>,
            reply_payload: Option<String>,
        ) -> Result<String, JsValue> {
            self.inner
                .send_message(
                    &target_id,
                    &payload,
                    state.as_deref(),
                    reply_payload.as_deref(),
                )
                .await
                .map_err(|e| JsValue::from_str(&e.to_string()))
        }

        pub async fn set_offline(&self, user_id: String) -> Result<(), JsValue> {
            self.inner
                .set_offline(&user_id)
                .await
                .map_err(|e| JsValue::from_str(&e.to_string()))
        }

        pub async fn update_device(
            &self,
            user_id: String,
            device_id: String,
            device_name: Option<String>,
            capabilities: Option<JsValue>,
            metadata: Option<String>,
        ) -> Result<(), JsValue> {
            let parsed_capabilities = match capabilities {
                Some(value) if !value.is_null() && !value.is_undefined() => Some(
                    serde_wasm_bindgen::from_value::<crate::signaling::DeviceCapabilities>(value)
                        .map_err(|e| JsValue::from_str(&e.to_string()))?,
                ),
                _ => None,
            };

            self.inner
                .update_device(
                    &user_id,
                    &device_id,
                    device_name.as_deref(),
                    parsed_capabilities,
                    metadata.as_deref(),
                )
                .await
                .map_err(|e| JsValue::from_str(&e.to_string()))
        }

        pub async fn delete_device(
            &self,
            user_id: String,
            device_id: String,
        ) -> Result<(), JsValue> {
            self.inner
                .delete_device(&user_id, &device_id)
                .await
                .map_err(|e| JsValue::from_str(&e.to_string()))
        }

        pub fn force_reconnect_snapshot(&self) {
            self.inner.clone().force_reconnect_snapshot();
        }

        pub fn stop_presence_loop(&self) {
            self.inner.stop_presence_loop();
        }

        pub fn stop_auto_connect(&self) {
            self.inner.stop_auto_connect();
            self.inner.stop_browser_auto_connect();
        }

        pub fn start_auto_connect(
            &self,
            user_id: String,
            local_device_id: String,
        ) -> Result<(), JsValue> {
            self.inner
                .start_browser_auto_connect(user_id, local_device_id)
                .map_err(|error| JsValue::from_str(&error.to_string()))
        }

        pub fn submit_browser_desired_peers(
            &self,
            revision: u32,
            peers_json: String,
        ) -> Result<bool, JsValue> {
            self.inner
                .submit_browser_desired_peers(u64::from(revision), &peers_json)
                .map_err(|error| JsValue::from_str(&error.to_string()))
        }

        pub fn wake_browser_auto_connect(&self) -> bool {
            self.inner.wake_browser_auto_connect()
        }

        pub async fn set_auto_connect_excluded(&self, device_id: String, excluded: bool) {
            if excluded {
                self.inner.exclude_peer_and_publish(&device_id).await;
            } else {
                self.inner.unexclude_peer_and_publish(&device_id).await;
            }
            self.inner.wake_browser_auto_connect();
        }

        pub fn is_auto_connect_excluded(&self, device_id: String) -> bool {
            self.inner.is_auto_connect_excluded(&device_id)
        }

        pub async fn disconnect_device(
            &self,
            device_id: String,
            node_id_hint: Option<String>,
        ) -> Result<JsValue, JsValue> {
            let retired = self
                .inner
                .disconnect_device(&device_id, node_id_hint.as_deref())
                .await;
            serde_wasm_bindgen::to_value(&retired).map_err(|e| JsValue::from_str(&e.to_string()))
        }

        pub fn stop_auth_scoped_activity(&self) {
            self.inner.stop_auth_scoped_activity();
            self.inner.stop_browser_auto_connect();
        }

        pub fn start_presence_loop(
            &self,
            user_id: String,
            device_name: String,
            ticket: String,
            metadata: Option<String>,
        ) {
            self.inner
                .clone()
                .start_signaling_loop(user_id, device_name, ticket, metadata);
        }

        pub async fn search_devices(&self, user_id: String) -> Result<JsValue, JsValue> {
            let devices = self
                .inner
                .search_devices(&user_id)
                .await
                .map_err(|e| JsValue::from_str(&e.to_string()))?;
            serde_wasm_bindgen::to_value(&devices).map_err(|e| JsValue::from_str(&e.to_string()))
        }

        pub async fn devices_with_status(&self, user_id: String) -> Result<JsValue, JsValue> {
            let devices = self
                .inner
                .devices_with_status(&user_id)
                .await
                .map_err(|e| JsValue::from_str(&e.to_string()))?;
            serde_wasm_bindgen::to_value(&devices).map_err(|e| JsValue::from_str(&e.to_string()))
        }

        pub async fn connect_device(
            &self,
            device_id: Option<String>,
            endpoint_ticket: String,
        ) -> Result<JsValue, JsValue> {
            let result = self
                .inner
                .connect_device(device_id.as_deref(), &endpoint_ticket)
                .await
                .map_err(|e| JsValue::from_str(&e.to_string()))?;
            serde_wasm_bindgen::to_value(&result).map_err(|e| JsValue::from_str(&e.to_string()))
        }

        pub async fn create_session(&self, session_json: String) -> Result<(), JsValue> {
            let session: crate::signaling::SignalingSession =
                serde_json::from_str(&session_json)
                    .map_err(|e| JsValue::from_str(&e.to_string()))?;
            self.inner
                .create_session(session)
                .await
                .map_err(|e| JsValue::from_str(&e.to_string()))
        }

        pub async fn update_session(
            &self,
            session_id: String,
            update_json: String,
        ) -> Result<(), JsValue> {
            let update_data: serde_json::Value = serde_json::from_str(&update_json)
                .map_err(|e| JsValue::from_str(&e.to_string()))?;
            self.inner
                .update_session(&session_id, update_data)
                .await
                .map_err(|e| JsValue::from_str(&e.to_string()))
        }

        // --- Room Management API ---

        pub async fn create_room(
            &self,
            room_id: String,
            user_id: String,
            ticket_str: String,
            my_node_id: String,
            tag: String,
            max_members: Option<u32>,
        ) -> Result<bool, JsValue> {
            self.inner
                .room
                .create_room(
                    &room_id,
                    &user_id,
                    &ticket_str,
                    &my_node_id,
                    &tag,
                    max_members,
                )
                .await
                .map_err(|e| JsValue::from_str(&e.to_string()))
        }

        pub async fn join_room(
            &self,
            room_id: String,
            user_id: String,
            ticket_str: String,
            my_node_id: String,
            tag: String,
        ) -> Result<(), JsValue> {
            self.inner
                .room
                .join_room(&room_id, &user_id, &ticket_str, &my_node_id, &tag)
                .await
                .map_err(|e| JsValue::from_str(&e.to_string()))
        }

        pub async fn get_members(
            &self,
            room_id: String,
            my_node_id: String,
            tag: String,
        ) -> Result<String, JsValue> {
            let members = self
                .inner
                .room
                .get_members(&room_id, &my_node_id, &tag)
                .await
                .map_err(|e| JsValue::from_str(&e.to_string()))?;
            serde_json::to_string(&members).map_err(|e| JsValue::from_str(&e.to_string()))
        }

        pub async fn leave_room(
            &self,
            room_id: String,
            my_node_id: String,
            tag: String,
        ) -> Result<(), JsValue> {
            self.inner
                .room
                .leave_room(&room_id, &my_node_id, &tag)
                .await
                .map_err(|e| JsValue::from_str(&e.to_string()))
        }

        pub async fn heartbeat_tick(
            &self,
            room_id: String,
            member_id: String,
            tag: String,
        ) -> Result<(), JsValue> {
            self.inner
                .room
                .heartbeat_tick(&room_id, &member_id, &tag)
                .await
                .map_err(|e| JsValue::from_str(&e.to_string()))
        }
    }

    #[wasm_bindgen(start)]
    pub fn start() {
        console_error_panic_hook::set_once();
    }
}