node-device-session 7.7.20

Shared server for /econ-v1/device-session/1 behind transport-neutral traits (C-5)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
use super::super::budget::SESSION_BYTES;
use super::stun_binding_request;
use super::*;
use crate::messages::{OpenMode, OpenOk};
use crate::stream_wire::{encode_request, StreamRequest};
use crate::traits::WebRtcSignaling;
use crate::tunnel::{self, encode_ws, read_ws, WsFrame};
use crate::types::{IngressSocket, WireSocket};
use crate::wire;
use serde_json::json;
use std::sync::Arc;
use std::time::{Duration, Instant};
use str0m::change::SdpAnswer;
use str0m::net::{Protocol, Receive};
use str0m::{Candidate, Event, Input, Output, Rtc};
use tokio::io::DuplexStream;
use tokio::net::{UdpSocket, UnixListener};
use tokio::sync::mpsc;
use tokio::task::JoinSet;

fn empty_ingress() -> Arc<IngressSocket> {
    Arc::new(IngressSocket::default())
}

fn empty_wire() -> Arc<WireSocket> {
    Arc::new(WireSocket::default())
}

// Model separate LANs with endpoint-independent mappings and port-restricted
// inbound filtering: a mapping alone (STUN discovery) does not open the peer
// pinhole. Both endpoints must send to the other's public address first.
#[test]
fn full_ice_answerer_punches_two_port_restricted_nats() {
    let base: [SocketAddr; 2] = [
        "10.1.0.2:4000".parse().unwrap(),
        "10.2.0.2:5000".parse().unwrap(),
    ];
    let public: [SocketAddr; 2] = [
        "203.0.113.1:14000".parse().unwrap(),
        "203.0.113.2:15000".parse().unwrap(),
    ];
    let mut peers = [rtc(), rtc()];
    for i in 0..2 {
        peers[i].add_local_candidate(Candidate::host(base[i], "udp").unwrap());
        peers[i]
            .add_local_candidate(Candidate::server_reflexive(public[i], base[i], "udp").unwrap());
    }
    let mut changes = peers[0].sdp_api();
    changes.add_channel("http.request/1".into());
    let (offer, pending) = changes.apply().unwrap();
    // Browser offers can precede all IP candidates (mDNS host + later srflx).
    let sdp = offer
        .to_sdp_string()
        .lines()
        .filter(|line| !line.starts_with("a=candidate:"))
        .collect::<Vec<_>>()
        .join("\r\n")
        + "\r\n";
    let mut binding = Binding {
        nonce: None,
        candidates: 0,
    };
    let answer = binding.signal(&mut peers[1], json!({"type":"offer", "version":1,
        "offer_nonce":"0123456789abcdef", "dtls_fingerprint":fingerprint(&sdp).unwrap(), "sdp":sdp})).unwrap().unwrap();
    let answer_sdp = answer["sdp"].as_str().unwrap();
    assert!(!answer_sdp.contains("a=ice-lite"));
    assert!(answer_sdp.contains("203.0.113.2 15000 typ srflx"));
    peers[0]
        .sdp_api()
        .accept_answer(pending, SdpAnswer::from_sdp_string(answer_sdp).unwrap())
        .unwrap();
    for candidate in [
        "candidate:1 1 udp 2113937151 test.local 4000 typ host".to_owned(),
        Candidate::host(base[0], "udp").unwrap().to_sdp_string(),
        format!("candidate:2 1 udp 1677729535 {} {} typ srflx raddr 0.0.0.0 rport 0 generation 0 network-cost 999", public[0].ip(), public[0].port()),
    ] {
        binding.signal(&mut peers[1], json!({"type":"candidate", "offer_nonce":"0123456789abcdef", "candidate":candidate})).unwrap();
    }
    let start = Instant::now();
    let mut opened = [false; 2];
    let mut connected = [false; 2];
    let mut checked = std::collections::HashSet::new();
    for tick in 0..2000 {
        let now = start + Duration::from_millis(tick * 10);
        for i in 0..2 {
            peers[i].handle_input(Input::Timeout(now)).unwrap();
            loop {
                match peers[i].poll_output().unwrap() {
                    Output::Timeout(_) => break,
                    Output::Event(Event::ChannelOpen(_, _)) => connected[i] = true,
                    Output::Transmit(t) => {
                        assert_eq!(
                            t.source, base[i],
                            "srflx traffic must use its bound base socket"
                        );
                        if i == 1 && t.contents[..2] == [0, 1] {
                            checked.insert(t.destination);
                        }
                        let other = 1 - i;
                        if t.destination != public[other] {
                            continue;
                        }
                        opened[i] = true;
                        if !opened[other] {
                            continue;
                        }
                        let contents = (&*t.contents).try_into().unwrap();
                        let input = Input::Receive(
                            now,
                            Receive {
                                proto: Protocol::Udp,
                                source: public[i],
                                destination: base[other],
                                contents,
                            },
                        );
                        assert!(peers[other].accepts(&input));
                        peers[other].handle_input(input).unwrap();
                    }
                    _ => {}
                }
            }
        }
        if connected == [true; 2] {
            break;
        }
    }
    assert!(
        checked.contains(&base[0]),
        "answerer never checked host candidate"
    );
    assert!(
        checked.contains(&public[0]),
        "answerer never checked trickled srflx candidate"
    );
    assert_eq!(opened, [true; 2]);
    assert_eq!(
        connected, [true; 2],
        "DataChannel must connect through translated addresses"
    );
}

#[tokio::test]
async fn answerer_checks_trickled_candidates_from_the_stun_gathering_socket() {
    let stun = UdpSocket::bind("127.0.0.1:0").await.unwrap();
    let stun_address = stun.local_addr().unwrap();
    let responder = tokio::spawn(async move {
        let mut request = [0; 20];
        let (_, peer) = stun.recv_from(&mut request).await.unwrap();
        let mut reply = request.to_vec();
        reply[..4].copy_from_slice(&[1, 1, 0, 12]);
        reply.extend_from_slice(&[0, 0x20, 0, 8, 0, 1]);
        reply.extend_from_slice(&(peer.port() ^ 0x2112).to_be_bytes());
        reply.extend_from_slice(&(u32::from_be_bytes([203, 0, 113, 5]) ^ 0x2112a442).to_be_bytes());
        stun.send_to(&reply, peer).await.unwrap();
        peer
    });
    let mut offerer = rtc();
    let mut changes = offerer.sdp_api();
    changes.add_media(
        str0m::media::MediaKind::Audio,
        str0m::media::Direction::SendRecv,
        None,
        None,
        None,
    );
    changes.add_channel("http.request/1".into());
    let (offer, _) = changes.apply().unwrap();
    let sdp = offer.to_sdp_string();
    let (mut signal, server) = tokio::io::duplex(65536);
    let handle = WebRtcHandle::new();
    let cancel = handle.clone();
    let task = tokio::spawn(async move {
        let (read, write) = tokio::io::split(server);
        serve(
            read,
            write,
            empty_ingress(),
            cancel,
            vec![stun_address],
            Some("127.0.0.1:0".parse().unwrap()),
        )
        .await
    });
    write_signal(&mut signal, &json!({"type":"offer", "version":1,
        "offer_nonce":"0123456789abcdef", "dtls_fingerprint":fingerprint(&sdp).unwrap(), "sdp":sdp})).await.unwrap();
    let answer = tokio::time::timeout(Duration::from_secs(3), read_signal(&mut signal))
        .await
        .unwrap()
        .unwrap();
    let bound = responder.await.unwrap();
    let answer_sdp = answer["sdp"].as_str().unwrap();
    assert!(!answer_sdp.contains("a=ice-lite"));
    assert!(answer_sdp.contains(&format!("203.0.113.5 {} typ srflx", bound.port())));
    let mut trickled = false;
    for _ in 0..answer_sdp
        .lines()
        .filter(|line| line.starts_with("a=candidate:"))
        .count()
    {
        let msg = read_signal(&mut signal).await.unwrap();
        assert_eq!(msg["offer_nonce"], "0123456789abcdef");
        assert_eq!(msg["sdp_mline_index"], 1);
        trickled |= msg["candidate"].as_str().unwrap().contains("typ srflx");
    }
    assert!(trickled);
    let host = UdpSocket::bind("127.0.0.1:0").await.unwrap();
    let reflexive = UdpSocket::bind("127.0.0.1:0").await.unwrap();
    for candidate in [
        "candidate:1 1 udp 2113937151 test.local 4000 typ host".to_owned(),
        Candidate::host(host.local_addr().unwrap(), "udp").unwrap().to_sdp_string(),
        format!("candidate:2 1 udp 1677729535 127.0.0.1 {} typ srflx raddr 0.0.0.0 rport 0 generation 0 network-cost 999", reflexive.local_addr().unwrap().port()),
    ] {
        write_signal(&mut signal, &json!({"type":"candidate", "offer_nonce":"0123456789abcdef", "candidate":candidate})).await.unwrap();
    }
    // No inbound checks or responses are sent. A controlled full-ICE answerer
    // must proactively check every remote address, from the mapping it gathered.
    for remote in [&host, &reflexive] {
        let mut packet = [0; 1500];
        let (n, source) =
            tokio::time::timeout(Duration::from_secs(2), remote.recv_from(&mut packet))
                .await
                .unwrap()
                .unwrap();
        assert!(n > 20);
        assert_eq!(&packet[..2], &[0, 1]);
        assert_eq!(source, bound);
    }
    handle.close();
    task.await.unwrap().unwrap();
}

pub(crate) struct Browser {
    rtc: Rtc,
    socket: UdpSocket,
    signal: DuplexStream,
    channel: str0m::channel::ChannelId,
    handle: WebRtcHandle,
    task: tokio::task::JoinHandle<Result<(), String>>,
    partial: Vec<u8>,
}
impl Drop for Browser {
    fn drop(&mut self) {
        self.handle.close();
        self.task.abort();
    }
}
impl Browser {
    async fn new(method: &str, ingress: Arc<IngressSocket>) -> Self {
        Self::with_stun(method, ingress, vec![]).await
    }
    async fn with_stun(method: &str, ingress: Arc<IngressSocket>, stun: Vec<SocketAddr>) -> Self {
        Self::with_connection(method, ingress, stun).await
    }
    async fn with_connection(
        method: &str,
        ingress: Arc<IngressSocket>,
        stun: Vec<SocketAddr>,
    ) -> Self {
        let gathered = !stun.is_empty();
        Self::connect(method, gathered, move |server| {
            let handle = WebRtcHandle::new();
            let server_handle = handle.clone();
            let task = tokio::spawn(async move {
                let (read, write) = tokio::io::split(server);
                serve(
                    read,
                    write,
                    ingress,
                    server_handle,
                    stun,
                    Some("127.0.0.1:0".parse().unwrap()),
                )
                .await
            });
            (handle, task)
        })
        .await
    }
    /// The public [`crate::WebRtcAnswerer`] (the `WebRtcSignaling` hook carriers install),
    /// splicing `wire/1` channels onto `wire`, behind loopback ICE.
    async fn with_answerer(method: &str, wire: Arc<WireSocket>) -> Self {
        let bound = Arc::new(parking_lot::Mutex::new(None));
        let carrier = LoopbackCarrier(bound.clone());
        let mut browser = Self::connect(method, false, move |server| {
            let task = tokio::spawn(async move {
                let (read, write) = tokio::io::split(server);
                let identity = OpenOk {
                    mode: OpenMode::Full,
                    device_id: "device".into(),
                    device_did: "did:key:device".into(),
                    scopes: vec![],
                    expires_at: "0".into(),
                };
                crate::WebRtcAnswerer::new(empty_ingress(), carrier)
                    .with_wire_socket(wire)
                    .handle(&identity, [0; 32], Box::new(write), Box::new(read))
                    .await;
                Ok(())
            });
            // Replaced by the answerer's own handle once the channel is open.
            (WebRtcHandle::new(), task)
        })
        .await;
        browser.handle = bound.lock().take().expect("the answerer bound its session");
        browser
    }
    async fn connect(
        method: &str,
        gathered: bool,
        spawn: impl FnOnce(DuplexStream) -> (WebRtcHandle, tokio::task::JoinHandle<Result<(), String>>),
    ) -> Self {
        let socket = UdpSocket::bind("127.0.0.1:0").await.unwrap();
        let mut rtc = Rtc::builder()
            .set_sctp_max_buffered_amount(FRAME)
            .build(Instant::now());
        rtc.add_local_candidate(Candidate::host(socket.local_addr().unwrap(), "udp").unwrap());
        let mut changes = rtc.sdp_api();
        let channel = changes.add_channel(method.into());
        let (offer, pending) = changes.apply().unwrap();
        let sdp = offer.to_sdp_string();
        let (mut signal, server) = tokio::io::duplex(65536);
        let (handle, task) = spawn(server);
        write_signal(&mut signal, &serde_json::json!({"type":"offer", "version":1,
            "offer_nonce":"0123456789abcdef", "dtls_fingerprint":fingerprint(&sdp).unwrap(), "sdp":sdp})).await.unwrap();
        let answer = tokio::time::timeout(Duration::from_secs(5), read_signal(&mut signal))
            .await
            .unwrap()
            .unwrap();
        if gathered {
            assert!(answer["sdp"].as_str().unwrap().contains("typ srflx"));
        }
        assert_eq!(answer["offer_nonce"], "0123456789abcdef");
        assert_eq!(
            answer["dtls_fingerprint"],
            fingerprint(answer["sdp"].as_str().unwrap()).unwrap()
        );
        let candidate = tokio::time::timeout(Duration::from_secs(2), read_signal(&mut signal))
            .await
            .unwrap()
            .unwrap();
        assert_eq!(candidate["type"], "candidate");
        assert_eq!(candidate["offer_nonce"], "0123456789abcdef");
        Candidate::from_sdp_string(candidate["candidate"].as_str().unwrap()).unwrap();
        rtc.sdp_api()
            .accept_answer(
                pending,
                SdpAnswer::from_sdp_string(answer["sdp"].as_str().unwrap()).unwrap(),
            )
            .unwrap();
        let mut browser = Self {
            rtc,
            socket,
            signal,
            channel,
            handle,
            task,
            partial: vec![],
        };
        tokio::time::timeout(Duration::from_secs(5), async {
            loop {
                if matches!(browser.step().await, Some(Event::ChannelOpen(_, _))) {
                    break;
                }
            }
        })
        .await
        .unwrap();
        browser
    }
    async fn step(&mut self) -> Option<Event> {
        let deadline = loop {
            match self.rtc.poll_output().unwrap() {
                Output::Timeout(t) => break t,
                Output::Transmit(t) => {
                    // A gathered public candidate need not be routable from
                    // this loopback-only offerer; ICE can select its host pair.
                    let _ = self.socket.send_to(&t.contents, t.destination).await;
                }
                Output::Event(e) => return Some(e),
            }
        };
        // Cap waits so a remote disconnect is noticed within expect_close's budget
        // even when str0m's next timer is far away.
        let wait = deadline
            .saturating_duration_since(Instant::now())
            .min(Duration::from_millis(100));
        let mut buf = [0; 65536];
        tokio::select! {
            _ = tokio::time::sleep(wait) => { self.rtc.handle_input(Input::Timeout(Instant::now())).unwrap(); }
            received = self.socket.recv_from(&mut buf) => {
                let (n, source) = received.unwrap();
                if let Ok(contents) = (&buf[..n]).try_into() {
                    self.rtc.handle_input(Input::Receive(Instant::now(), Receive { proto: Protocol::Udp, source,
                        destination:self.socket.local_addr().unwrap(), contents })).unwrap();
                }
            }
        }
        None
    }
    fn send(&mut self, bytes: &[u8]) {
        for chunk in segment(bytes) {
            assert!(self
                .rtc
                .channel(self.channel)
                .unwrap()
                .write(true, &chunk)
                .unwrap());
        }
    }
    async fn receive(&mut self) -> Vec<u8> {
        tokio::time::timeout(Duration::from_secs(5), async {
            loop {
                if let Some(Event::ChannelData(data)) = self.step().await {
                    assert!(data.binary);
                    assert!(data.data.len() <= 16384);
                    self.partial.extend_from_slice(&data.data[1..]);
                    if data.data[0] & 1 == 0 {
                        return std::mem::take(&mut self.partial);
                    }
                }
            }
        })
        .await
        .unwrap()
    }
    pub(crate) async fn expect_close(&mut self) {
        // Generous: a 4 MiB debug-build round trip on a loaded CI runner can take
        // seconds before the channel close is observed.
        tokio::time::timeout(Duration::from_secs(10), async {
            loop {
                match self.step().await {
                    Some(Event::ChannelClose(_)) | Some(Event::Closed) => break,
                    _ => {}
                }
            }
        })
        .await
        .unwrap();
    }
    fn method(&mut self, method: &str) {
        self.send(&wire::encode_request(method, &[]).unwrap());
    }
}

#[tokio::test]
async fn wire_channel_splices_to_wire_socket() {
    use tokio::io::{AsyncReadExt, AsyncWriteExt};
    let dir = tempfile::tempdir().unwrap();
    let sock = dir.path().join("wire.sock");
    let listener = UnixListener::bind(&sock).unwrap();
    let server = tokio::spawn(async move {
        let (mut stream, _) = listener.accept().await.unwrap();
        let mut line = Vec::new();
        loop {
            let mut byte = [0u8; 1];
            stream.read_exact(&mut byte).await.unwrap();
            line.push(byte[0]);
            if byte[0] == b'\n' {
                break;
            }
        }
        assert_eq!(
            line.as_slice(),
            br#"{"v":1,"carrier":"webrtc","origin":""}
"#
        );
        let mut buf = [0u8; 32];
        let n = stream.read(&mut buf).await.unwrap();
        assert_eq!(&buf[..n], b"ping-wire");
        stream.write_all(b"pong-wire").await.unwrap();
        let _ = stream.shutdown().await;
    });

    let mut tasks = JoinSet::new();
    let (output, mut outgoing) = mpsc::channel(16);
    let mut rtc = rtc();
    let id = rtc.sdp_api().add_channel("wire/1".into());
    let wire = Arc::new(WireSocket { path: Some(sock) });
    let channel = open_channel(
        id,
        "wire/1".into(),
        empty_ingress(),
        wire,
        &mut tasks,
        output,
        ByteBudget::default(),
    );
    assert!(channel
        .input
        .push(wire::encode_request("wire/1", &[]).unwrap()));
    assert!(channel.input.push(b"ping-wire".to_vec()));

    // node-wire frames are not B2-framed: the node's bytes reach the browser
    // as they are, each DataChannel message flagged complete (no MORE bit).
    let received = tokio::time::timeout(Duration::from_secs(5), async {
        let mut received = Vec::new();
        loop {
            match outgoing.recv().await {
                Some(Out::Bytes(from, bytes)) if from == id => {
                    assert_eq!(bytes[0], 0, "a wire chunk is a whole message");
                    received.extend_from_slice(&bytes[1..]);
                }
                Some(Out::Finished(finished)) if finished == id => break received,
                Some(_) => {}
                None => panic!("channel output closed before Finished"),
            }
        }
    })
    .await
    .expect("wire channel splice timed out");
    assert_eq!(received, b"pong-wire");
    server.await.unwrap();
    tasks.join_next().await.unwrap().unwrap();
}

#[tokio::test]
async fn offer_answer_establishes_datachannel() {
    let mut b = Browser::new("http.request/1", empty_ingress()).await;
    write_signal(
        &mut b.signal,
        &serde_json::json!({"type":"close","offer_nonce":"0123456789abcdef"}),
    )
    .await
    .unwrap();
    tokio::time::timeout(Duration::from_secs(2), &mut b.task)
        .await
        .unwrap()
        .unwrap()
        .unwrap();
    assert!(b.handle.is_closed());
}

#[tokio::test]
async fn datachannel_http_request_round_trip() {
    use tokio::io::{AsyncReadExt, AsyncWriteExt};
    let dir = tempfile::tempdir().unwrap();
    let sock = dir.path().join("http.sock");
    let listener = UnixListener::bind(&sock).unwrap();
    let server = tokio::spawn(async move {
        let (mut stream, _) = listener.accept().await.unwrap();
        let mut buf = vec![0u8; 8 * 1024 * 1024];
        let mut collected = Vec::new();
        loop {
            let n = stream.read(&mut buf).await.unwrap();
            if n == 0 {
                break;
            }
            collected.extend_from_slice(&buf[..n]);
            if let Some(split) = collected.windows(4).position(|w| w == b"\r\n\r\n") {
                let head = std::str::from_utf8(&collected[..split]).unwrap();
                let content_length = head
                    .lines()
                    .find_map(|l| {
                        l.strip_prefix("content-length: ")
                            .or_else(|| l.strip_prefix("Content-Length: "))
                    })
                    .and_then(|v| v.trim().parse::<usize>().ok())
                    .unwrap_or(0);
                if collected.len() >= split + 4 + content_length {
                    let body = collected[split + 4..split + 4 + content_length].to_vec();
                    let response = format!(
                        "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
                        body.len()
                    );
                    stream.write_all(response.as_bytes()).await.unwrap();
                    stream.write_all(&body).await.unwrap();
                    return;
                }
            }
        }
    });
    let ingress = Arc::new(IngressSocket { path: Some(sock) });
    let mut b = Browser::new("http.request/1", ingress).await;
    use base64::Engine;
    let body = vec![42; 64 * 1024];
    let request = encode_request(&StreamRequest {
        method: "PUT".into(),
        path: "/api/echo".into(),
        headers: Default::default(),
        body_b64: base64::engine::general_purpose::STANDARD.encode(&body),
    })
    .unwrap();
    let method = "http.request/1";
    let mut frame = (method.len() as u16).to_be_bytes().to_vec();
    frame.extend_from_slice(method.as_bytes());
    frame.extend(request);
    b.send(&frame);
    let mut response = vec![];
    loop {
        let frame = b.receive().await;
        let end = frame[0] == 3;
        response.extend(frame);
        if end {
            break;
        }
    }
    let mut decoder = crate::stream_wire::StreamDecoder::new(response.as_slice());
    assert!(
        matches!(decoder.next_frame().await.unwrap(), Some(crate::stream_wire::StreamFrame::Head(h)) if h.status == 200)
    );
    let mut received = vec![];
    while let Some(frame) = decoder.next_frame().await.unwrap() {
        if let crate::stream_wire::StreamFrame::Data(bytes) = frame {
            received.extend(bytes);
        }
    }
    assert_eq!(received, body);
    b.expect_close().await;
    server.abort();
}

#[tokio::test]
async fn datachannel_ws_stream_round_trip() {
    use futures_util::{SinkExt, StreamExt};
    let dir = tempfile::tempdir().unwrap();
    let sock = dir.path().join("ws.sock");
    let listener = UnixListener::bind(&sock).unwrap();
    let server = tokio::spawn(async move {
        let (stream, _) = listener.accept().await.unwrap();
        let mut ws = tokio_tungstenite::accept_async(stream).await.unwrap();
        while let Some(Ok(message)) = ws.next().await {
            ws.send(message).await.unwrap();
        }
    });
    let ingress = Arc::new(IngressSocket { path: Some(sock) });
    let mut b = Browser::new("ws.stream/1", ingress).await;
    b.method("ws.stream/1");
    b.send(
        &encode_ws(&WsFrame::Open {
            path: "/api/ws".into(),
            headers: Default::default(),
        })
        .unwrap(),
    );
    let bytes = b.receive().await;
    assert!(matches!(
        read_ws(&mut bytes.as_slice()).await.unwrap(),
        WsFrame::Open { .. }
    ));
    b.send(&encode_ws(&WsFrame::Text("hello".into())).unwrap());
    let bytes = b.receive().await;
    assert_eq!(
        read_ws(&mut bytes.as_slice()).await.unwrap(),
        WsFrame::Text("hello".into())
    );
    server.abort();
}

#[tokio::test]
async fn cancellation_closes_bound_datachannel() {
    let mut b = Browser::new("http.request/1", empty_ingress()).await;
    b.handle.close();
    tokio::time::timeout(Duration::from_secs(2), &mut b.task)
        .await
        .unwrap()
        .unwrap()
        .unwrap();
    assert!(b.handle.is_closed());
}

#[test]
fn signaling_rejects_unbound_fingerprints_and_restarts() {
    let mut rtc = rtc();
    let mut binding = Binding {
        nonce: None,
        candidates: 0,
    };
    for message in [
        json!({"type":"offer","version":1,"offer_nonce":"0123456789abcdef","sdp":"v=0\r\na=fingerprint:sha-256 AA\r\n","dtls_fingerprint":"sha-256 BB"}),
        json!({"type":"restart","version":1,"offer_nonce":"0123456789abcdef","previous_offer_nonce":"other0123456789abcdef"}),
    ] {
        assert!(binding.signal(&mut rtc, message).is_err());
    }
}

#[tokio::test]
async fn signaling_frame_bound_precedes_allocation() {
    let (mut client, mut server) = tokio::io::duplex(4);
    use tokio::io::AsyncWriteExt;
    client.write_u32((SIGNAL + 1) as u32).await.unwrap();
    assert!(read_signal(&mut server)
        .await
        .unwrap_err()
        .contains("bound"));
}

#[tokio::test]
async fn method_prefix_must_match_channel_label() {
    let mut b = Browser::new("http.request/1", empty_ingress()).await;
    b.method("ws.stream/1");
    b.expect_close().await;
    assert!(!b.handle.is_closed());
}

#[tokio::test]
async fn ice_restart_keeps_the_existing_datachannel() {
    let mut b = Browser::new("http.request/1", empty_ingress()).await;
    let mut changes = b.rtc.sdp_api();
    changes.ice_restart(true);
    let (offer, pending) = changes.apply().unwrap();
    let sdp = offer.to_sdp_string();
    write_signal(
        &mut b.signal,
        &json!({"type":"restart", "version":1,
        "offer_nonce":"fedcba9876543210", "previous_offer_nonce":"0123456789abcdef",
        "dtls_fingerprint":fingerprint(&sdp).unwrap(), "sdp":sdp}),
    )
    .await
    .unwrap();
    let answer = tokio::time::timeout(Duration::from_secs(2), async {
        loop {
            let message = read_signal(&mut b.signal).await.unwrap();
            if message["type"] == "answer" {
                break message;
            }
            assert_eq!(message["type"], "candidate");
        }
    })
    .await
    .unwrap();
    assert_eq!(answer["offer_nonce"], "fedcba9876543210");
    b.rtc
        .sdp_api()
        .accept_answer(
            pending,
            SdpAnswer::from_sdp_string(answer["sdp"].as_str().unwrap()).unwrap(),
        )
        .unwrap();
    // An ordinary B2 denial proves that the pre-existing channel still works.
    b.method("http.request/1");
    b.send(
        &encode_request(&StreamRequest {
            method: "GET".into(),
            path: "/private".into(),
            headers: Default::default(),
            body_b64: String::new(),
        })
        .unwrap(),
    );
    let bytes = b.receive().await;
    let mut decoder = crate::stream_wire::StreamDecoder::new(bytes.as_slice());
    assert!(
        matches!(decoder.next_frame().await.unwrap(), Some(crate::stream_wire::StreamFrame::Head(h)) if h.status == 403)
    );
}

#[tokio::test]
async fn advertised_stun_candidate_is_in_the_answer() {
    let stun = UdpSocket::bind("127.0.0.1:0").await.unwrap();
    let address = stun.local_addr().unwrap();
    let responder = tokio::spawn(async move {
        let mut request = [0; 20];
        let (n, peer) = stun.recv_from(&mut request).await.unwrap();
        assert_eq!(n, 20);
        assert_eq!(&request[..2], &[0, 1]);
        let mut reply = request.to_vec();
        reply[..4].copy_from_slice(&[1, 1, 0, 12]);
        reply.extend_from_slice(&[0, 0x20, 0, 8, 0, 1]);
        reply.extend_from_slice(&(45678u16 ^ 0x2112).to_be_bytes());
        reply.extend_from_slice(&(u32::from_be_bytes([203, 0, 113, 5]) ^ 0x2112a442).to_be_bytes());
        stun.send_to(&reply, peer).await.unwrap();
    });
    let _b = Browser::with_stun("http.request/1", empty_ingress(), vec![address]).await;
    responder.await.unwrap();
}

#[tokio::test]
async fn signaling_eof_closes_the_remote_datachannel() {
    let mut b = Browser::new("http.request/1", empty_ingress()).await;
    b.signal.shutdown().await.unwrap();
    let _ = tokio::time::timeout(Duration::from_secs(2), &mut b.task)
        .await
        .unwrap()
        .unwrap();
    assert!(b.handle.is_closed());
}

fn segment(bytes: &[u8]) -> Vec<Vec<u8>> {
    if bytes.is_empty() {
        return vec![vec![0]];
    }
    let count = bytes.len().div_ceil(CHUNK - 1);
    bytes
        .chunks(CHUNK - 1)
        .enumerate()
        .map(|(i, data)| {
            let mut chunk = Vec::with_capacity(data.len() + 1);
            chunk.push(u8::from(i + 1 < count));
            chunk.extend_from_slice(data);
            chunk
        })
        .collect()
}

#[tokio::test]
async fn mdns_and_stale_candidates_keep_channel_open() {
    let mut b = Browser::new("http.request/1", empty_ingress()).await;
    for offer_nonce in ["0123456789abcdef", "fedcba9876543210"] {
        write_signal(&mut b.signal, &json!({"type":"candidate", "offer_nonce":offer_nonce,
            "candidate":"candidate:1 1 udp 2113937151 0b1c1234-5678-9abc-def0-123456789abc.local 54321 typ host"})).await.unwrap();
    }
    b.method("http.request/1");
    b.send(
        &encode_request(&StreamRequest {
            method: "GET".into(),
            path: "/private".into(),
            headers: Default::default(),
            body_b64: String::new(),
        })
        .unwrap(),
    );
    let bytes = b.receive().await;
    let mut decoder = crate::stream_wire::StreamDecoder::new(bytes.as_slice());
    assert!(
        matches!(decoder.next_frame().await.unwrap(), Some(crate::stream_wire::StreamFrame::Head(h)) if h.status == 403)
    );
    assert!(!b.handle.is_closed());
}

#[test]
fn unparseable_candidates_count_toward_cap() {
    let mut rtc = rtc();
    let mut binding = Binding {
        nonce: Some("0123456789abcdef".into()),
        candidates: 0,
    };
    for _ in 0..32 {
        assert!(binding.signal(&mut rtc, json!({"type":"candidate", "offer_nonce":"0123456789abcdef", "candidate":"candidate:bad"})).is_ok());
    }
    assert_eq!(binding.candidates, 32);
    assert!(binding.signal(&mut rtc, json!({"type":"candidate", "offer_nonce":"0123456789abcdef", "candidate":"candidate:bad"})).is_err());
}

#[tokio::test(start_paused = true)]
async fn idle_method_prefix_releases_channel_slot() {
    let mut tasks = JoinSet::new();
    let (output, mut outgoing) = mpsc::channel(16);
    // ChannelId comes from the same offerer API used by the integration tests.
    let mut rtc = rtc();
    let id = rtc.sdp_api().add_channel("http.request/1".into());
    let _channel = open_channel(
        id,
        "http.request/1".into(),
        empty_ingress(),
        empty_wire(),
        &mut tasks,
        output,
        ByteBudget::default(),
    );
    tokio::task::yield_now().await;
    tokio::time::advance(DEVICE_CALL_READ_DEADLINE).await;
    assert!(matches!(outgoing.recv().await, Some(Out::Finished(finished)) if finished == id));
    tasks.join_next().await.unwrap().unwrap();
}

#[test]
fn channel_input_is_bounded_by_bytes_instead_of_message_count() {
    let input = ChannelInput::default();
    for _ in 0..FRAME / (CHUNK - 1) {
        assert!(input.push(vec![42; CHUNK - 1]));
    }
    let remaining = FRAME % (CHUNK - 1);
    assert!(input.push(vec![42; remaining]));
    assert_eq!(input.queue.lock().1, FRAME);
    assert!(!input.push(vec![42]));
}

#[tokio::test]
async fn sixteen_prepared_channels_are_admitted() {
    let mut b = Browser::new("http.request/1", empty_ingress()).await;
    assert_eq!(MAX_SESSION_STREAMS, 16);
    for _ in 1..MAX_SESSION_STREAMS {
        let id = b
            .rtc
            .direct_api()
            .create_data_channel(str0m::channel::ChannelConfig {
                label: "http.request/1".into(),
                ..Default::default()
            });
        b.channel = id;
        tokio::time::timeout(Duration::from_secs(2), async {
            loop {
                match b.step().await {
                    Some(Event::ChannelOpen(opened, _)) if opened == id => break,
                    Some(Event::ChannelClose(_)) => {
                        panic!("prepared channel closed below the limit")
                    }
                    _ => {}
                }
            }
        })
        .await
        .unwrap();
    }
    // An additional prepared channel is refused without ending the session.
    let extra = b
        .rtc
        .direct_api()
        .create_data_channel(str0m::channel::ChannelConfig {
            label: "http.request/1".into(),
            ..Default::default()
        });
    tokio::time::timeout(Duration::from_secs(2), async {
        loop {
            if matches!(b.step().await, Some(Event::ChannelClose(id)) if id == extra) {
                break;
            }
        }
    })
    .await
    .unwrap();
    // Prove that channel sixteen survived server-side admission.
    b.method("http.request/1");
    b.send(
        &encode_request(&StreamRequest {
            method: "GET".into(),
            path: "/private".into(),
            headers: Default::default(),
            body_b64: String::new(),
        })
        .unwrap(),
    );
    let bytes = b.receive().await;
    let mut decoder = crate::stream_wire::StreamDecoder::new(bytes.as_slice());
    assert!(
        matches!(decoder.next_frame().await.unwrap(), Some(crate::stream_wire::StreamFrame::Head(h)) if h.status == 403)
    );
    assert!(!b.handle.is_closed());
}

#[tokio::test]
async fn ipv6_only_stun_list_still_answers_with_ipv4_host() {
    let mut offerer = rtc();
    let mut changes = offerer.sdp_api();
    changes.add_channel("http.request/1".into());
    let (offer, _) = changes.apply().unwrap();
    let sdp = offer.to_sdp_string();
    let (mut signal, server) = tokio::io::duplex(65536);
    let handle = WebRtcHandle::new();
    let server_handle = handle.clone();
    let task = tokio::spawn(async move {
        let (read, write) = tokio::io::split(server);
        // IPv4 must use its own fallback route target, not this IPv6 server.
        serve(
            read,
            write,
            empty_ingress(),
            server_handle,
            vec!["[::1]:3478".parse().unwrap()],
            None,
        )
        .await
    });
    write_signal(&mut signal, &json!({"type":"offer", "version":1,
        "offer_nonce":"0123456789abcdef", "dtls_fingerprint":fingerprint(&sdp).unwrap(), "sdp":sdp})).await.unwrap();
    let answer = tokio::time::timeout(Duration::from_secs(2), read_signal(&mut signal))
        .await
        .unwrap()
        .unwrap();
    assert_eq!(answer["type"], "answer");
    assert!(answer["sdp"]
        .as_str()
        .unwrap()
        .lines()
        .filter_map(|line| line.strip_prefix("a="))
        .filter_map(|line| Candidate::from_sdp_string(line).ok())
        .any(|candidate| candidate.addr().is_ipv4()));
    handle.close();
    task.await.unwrap().unwrap();
}

#[tokio::test]
async fn session_budget_is_shared_by_dc_queues_and_http_bodies_and_released() {
    let budget = ByteBudget::default();
    let inputs: Vec<_> = (0..4)
        .map(|_| ChannelInput {
            budget: budget.clone(),
            ..Default::default()
        })
        .collect();
    for input in &inputs {
        assert!(input.push(vec![0; FRAME]));
    }
    assert!(budget.reserve(1).is_none());
    // Exhausted budget refuses HTTP admission the same way open_channel does.
    let mut refusal = vec![];
    tunnel::refuse(&mut refusal, "http.request/1", "too_busy")
        .await
        .unwrap();
    assert_eq!(refusal[0], 1); // Head
    drop(inputs);
    assert!(budget.reserve(SESSION_BYTES).is_some());
}

#[test]
fn logical_frame_accepts_six_mib_and_rejects_one_more_byte() {
    assert_eq!(FRAME, 6 * 1024 * 1024);
    let input = ChannelInput::default();
    assert!(input.push(vec![0; FRAME]));
    assert!(!input.push(vec![0]));
}

#[tokio::test]
async fn dc_websocket_remains_open_beyond_one_hour() {
    use futures_util::{SinkExt, StreamExt};
    let dir = tempfile::tempdir().unwrap();
    let sock = dir.path().join("ws.sock");
    let listener = UnixListener::bind(&sock).unwrap();
    let server = tokio::spawn(async move {
        let (stream, _) = listener.accept().await.unwrap();
        let mut ws = tokio_tungstenite::accept_async(stream).await.unwrap();
        while let Some(Ok(message)) = ws.next().await {
            ws.send(message).await.unwrap();
        }
    });
    let ingress = Arc::new(IngressSocket { path: Some(sock) });
    let mut rtc = rtc();
    let id = rtc.sdp_api().add_channel("ws.stream/1".into());
    let mut tasks = JoinSet::new();
    let (output, mut outgoing) = mpsc::channel(16);
    let channel = open_channel(
        id,
        "ws.stream/1".into(),
        ingress,
        empty_wire(),
        &mut tasks,
        output,
        ByteBudget::default(),
    );
    assert!(channel.input.push(
        wire::encode_request(
            "ws.stream/1",
            &encode_ws(&WsFrame::Open {
                path: "/api/ws".into(),
                headers: Default::default()
            })
            .unwrap()
        )
        .unwrap()
    ));
    assert!(matches!(outgoing.recv().await, Some(Out::Bytes(_, _))));
    tokio::time::pause();
    tokio::time::advance(Duration::from_secs(3601)).await;
    tokio::task::yield_now().await;
    assert!(channel
        .input
        .push(encode_ws(&WsFrame::Text("still live".into())).unwrap()));
    tokio::time::resume();
    let Some(Out::Bytes(_, bytes)) = tokio::time::timeout(Duration::from_secs(3), outgoing.recv())
        .await
        .unwrap()
    else {
        panic!("websocket ended at one hour");
    };
    assert_eq!(
        read_ws(&mut &bytes[1..]).await.unwrap(),
        WsFrame::Text("still live".into())
    );
    tasks.abort_all();
    server.abort();
}

#[tokio::test]
async fn late_stun_reply_is_trickled_after_answer() {
    let stun = UdpSocket::bind("127.0.0.1:0").await.unwrap();
    let address = stun.local_addr().unwrap();
    let mut offerer = rtc();
    let mut changes = offerer.sdp_api();
    changes.add_media(
        str0m::media::MediaKind::Audio,
        str0m::media::Direction::SendRecv,
        None,
        None,
        None,
    );
    changes.add_channel("http.request/1".into());
    let (offer, _) = changes.apply().unwrap();
    let sdp = offer.to_sdp_string();
    let (mut signal, server) = tokio::io::duplex(65536);
    let handle = WebRtcHandle::new();
    let cancel = handle.clone();
    let task = tokio::spawn(async move {
        let (read, write) = tokio::io::split(server);
        serve(
            read,
            write,
            empty_ingress(),
            cancel,
            vec![address],
            Some("127.0.0.1:0".parse().unwrap()),
        )
        .await
    });
    write_signal(&mut signal, &json!({"type":"offer", "version":1,
        "offer_nonce":"0123456789abcdef", "dtls_fingerprint":fingerprint(&sdp).unwrap(), "sdp":sdp})).await.unwrap();
    let mut request = [0; 20];
    let (_, peer) = stun.recv_from(&mut request).await.unwrap();
    let answer = tokio::time::timeout(Duration::from_secs(2), read_signal(&mut signal))
        .await
        .unwrap()
        .unwrap();
    assert_eq!(answer["type"], "answer");
    assert!(!answer["sdp"].as_str().unwrap().contains("typ srflx"));
    let mut reply = request.to_vec();
    reply[..4].copy_from_slice(&[1, 1, 0, 12]);
    reply.extend_from_slice(&[0, 0x20, 0, 8, 0, 1]);
    reply.extend_from_slice(&(45678u16 ^ 0x2112).to_be_bytes());
    reply.extend_from_slice(&(u32::from_be_bytes([203, 0, 113, 5]) ^ 0x2112a442).to_be_bytes());
    stun.send_to(&reply, peer).await.unwrap();
    let candidate = tokio::time::timeout(Duration::from_secs(2), async {
        loop {
            let msg = read_signal(&mut signal).await.unwrap();
            assert_eq!(msg["type"], "candidate");
            if msg["candidate"].as_str().unwrap().contains("typ srflx") {
                break msg;
            }
        }
    })
    .await
    .unwrap();
    assert_eq!(candidate["offer_nonce"], "0123456789abcdef");
    assert_eq!(candidate["sdp_mline_index"], 1);
    stun.send_to(&reply, peer).await.unwrap();
    assert!(
        tokio::time::timeout(Duration::from_millis(100), read_signal(&mut signal))
            .await
            .is_err()
    );
    handle.close();
    task.await.unwrap().unwrap();
}

fn answer_with_hosts(addresses: &[SocketAddr]) -> String {
    let mut offerer = rtc();
    let mut changes = offerer.sdp_api();
    changes.add_channel("http.request/1".into());
    let (offer, _) = changes.apply().unwrap();
    let sdp = offer.to_sdp_string();
    let mut answerer = rtc();
    LocalCandidates::hosts(&mut answerer, addresses.iter().copied()).unwrap();
    let mut binding = Binding {
        nonce: None,
        candidates: 0,
    };
    binding.signal(&mut answerer, json!({"type":"offer", "version":1,
        "offer_nonce":"0123456789abcdef", "dtls_fingerprint":fingerprint(&sdp).unwrap(), "sdp":sdp}))
        .unwrap().unwrap()["sdp"].as_str().unwrap().to_owned()
}

#[test]
fn answer_advertises_one_host_per_available_family() {
    let v4 = "192.0.2.1:12000".parse().unwrap();
    let v6 = "[fd00::1]:13000".parse().unwrap();
    let answer = answer_with_hosts(&[v4, v6]);
    assert!(answer.contains("192.0.2.1 12000 typ host"));
    assert!(answer.contains("fd00::1 13000 typ host"));
    assert_eq!(
        answer
            .lines()
            .filter(|line| line.starts_with("a=candidate:"))
            .count(),
        2
    );
}

#[tokio::test]
async fn ipv6_bind_failure_keeps_ipv4_answer() {
    let sockets = session_sockets(Some("127.0.0.1:0".parse().unwrap()), &[], |_| {
        Err(std::io::Error::new(
            std::io::ErrorKind::AddrNotAvailable,
            "injected IPv6 bind failure",
        ))
    })
    .unwrap();
    assert_eq!(sockets.len(), 1);
    let local = sockets[0].local;
    let answer = answer_with_hosts(&[local]);
    assert!(answer.contains(&format!("127.0.0.1 {} typ host", local.port())));
    let peer = UdpSocket::bind("127.0.0.1:0").await.unwrap();
    peer.send_to(b"still usable", local).await.unwrap();
    let mut buf = [0; 64];
    let (index, n, _) = recv_packet(&sockets, &mut buf).await.unwrap();
    assert_eq!(index, 0);
    assert_eq!(&buf[..n], b"still usable");
}

#[test]
fn ipv6_host_scope_policy() {
    for ip in [
        "::",
        "::1",
        "fe80::1",
        "febf::1",
        "ff02::1",
        "::ffff:192.0.2.1",
        "fec0::1",
        "::2",
    ] {
        assert!(!usable_ipv6(ip.parse().unwrap()), "{ip}");
    }
    for ip in ["2001:db8::1", "fd00::1", "fc00::1"] {
        assert!(usable_ipv6(ip.parse().unwrap()), "{ip}");
    }
}

#[test]
fn ipv6_stun_mapping_checks_transaction_and_candidate_bounds() {
    let txid = [42; 12];
    let mut reply = stun_binding_request(&txid).to_vec();
    reply[..4].copy_from_slice(&[1, 1, 0, 24]);
    reply.extend_from_slice(&[0, 0x20, 0, 20, 0, 2]);
    reply.extend_from_slice(&(45678u16 ^ 0x2112).to_be_bytes());
    let ip: Ipv6Addr = "2001:db8::1234".parse().unwrap();
    let encoded: Vec<_> = ip
        .octets()
        .iter()
        .zip(reply[4..20].iter())
        .map(|(a, b)| a ^ b)
        .collect();
    reply.extend_from_slice(&encoded);
    let mapped = SocketAddr::new(ip.into(), 45678);
    assert_eq!(stun_mapped(&reply, &txid), Some(mapped));
    assert_eq!(stun_mapped(&reply, &[0; 12]), None);
    for n in 0..reply.len() {
        assert_eq!(stun_mapped(&reply[..n], &txid), None);
    }
    let mut rtc = rtc();
    let local = "[fd00::1]:10000".parse().unwrap();
    let mut candidates = LocalCandidates::hosts(&mut rtc, [local].into_iter()).unwrap();
    assert!(candidates
        .mapped(&mut rtc, mapped, local)
        .unwrap()
        .is_some());
    assert!(candidates
        .mapped(&mut rtc, mapped, local)
        .unwrap()
        .is_none());
    for port in 1..8 {
        assert!(candidates
            .mapped(&mut rtc, SocketAddr::new(ip.into(), port), local)
            .unwrap()
            .is_some());
    }
    assert!(candidates
        .mapped(&mut rtc, SocketAddr::new(ip.into(), 8), local)
        .unwrap()
        .is_none());
    // The IPv6 cap must leave room for IPv4 candidates.
    assert!(candidates
        .mapped(
            &mut rtc,
            "203.0.113.1:45678".parse().unwrap(),
            "192.0.2.1:10000".parse().unwrap()
        )
        .unwrap()
        .is_some());
}

// The real answerer path for node-wire (PR #4917 / #4929). The splice test above drives
// `open_channel` with plain bytes. These drive the public `WebRtcAnswerer` over loopback ICE (a
// str0m offerer standing in for the browser, real DTLS/SCTP DataChannels) with the real node-wire
// node (`node_adapters_wire::serve_connection`) behind the wire socket, and record every
// DataChannel message the answerer sends. The browser's own reassembler and `WireTransport`
// replay that record in `client/adapters-web/src/network/wire/webrtc-answerer-fixture.test.js`.

/// Loopback ICE for the real answerer; keeps the session handle so the test can close it.
struct LoopbackCarrier(Arc<parking_lot::Mutex<Option<WebRtcHandle>>>);

#[async_trait::async_trait]
impl crate::WebRtcCarrier for LoopbackCarrier {
    async fn stun_servers(&self) -> Vec<SocketAddr> {
        Vec::new()
    }
    fn bind_addr(&self) -> Option<SocketAddr> {
        Some("127.0.0.1:0".parse().unwrap())
    }
    async fn bind_session(&self, _: &OpenOk, _: [u8; 32], handle: &WebRtcHandle) -> bool {
        *self.0.lock() = Some(handle.clone());
        true
    }
}

/// Shared with the JS replay through the fixture (`credential`, `op`).
const WIRE_CREDENTIAL: &str = "sample-access-token-never-print";
const WIRE_OP: &str = "GET /api/v2/system/info";
/// `FEATURE_HELLO_BROWSER` (client `wire/limits.js`): what `WireTransport` offers.
const WIRE_BROWSER_FEATURES: u64 = 0x3f;
const WIRE_FIXTURE: &str = concat!(
    env!("CARGO_MANIFEST_DIR"),
    "/../../client/adapters-web/src/network/wire/fixtures/webrtc-answerer-datachannel.json"
);

/// A 20 KiB JSON body: its REPLY frame is larger than one 16 KiB DataChannel message and below
/// the node's 64 KiB stream threshold, so it goes out as one whole REPLY frame.
fn wire_reply_body() -> Vec<u8> {
    let mut body = b"{\"pad\":\"".to_vec();
    body.extend((0..20 * 1024).map(|i| b"0123456789abcdef"[i % 16]));
    body.extend_from_slice(b"\"}");
    body
}

struct NodeAuth;
#[async_trait::async_trait]
impl node_adapters_wire::WireAuth for NodeAuth {
    async fn verify(
        &self,
        token: &str,
        _delegation: Option<&str>,
    ) -> Result<node_adapters_wire::Verified, node_adapters_wire::AuthError> {
        if token != WIRE_CREDENTIAL {
            return Err(node_adapters_wire::AuthError::Invalid);
        }
        Ok(node_adapters_wire::Verified {
            identity: node_adapters_wire::Identity::Browser {
                user_id: "u".into(),
                device_id: None,
                is_primary_owner: true,
                role: node_adapters_wire::CallerRole::Owner,
                delegation: None,
            },
            valid_for: Duration::from_secs(3600),
        })
    }
    fn is_revoked(&self, _: &node_adapters_wire::Identity) -> bool {
        false
    }
}

struct NodeDispatch;
#[async_trait::async_trait]
impl node_adapters_wire::WireDispatch for NodeDispatch {
    async fn call(
        &self,
        _who: &node_adapters_wire::Identity,
        _credential: &node_adapters_wire::Credential,
        op: &str,
        _args: Option<&[u8]>,
        _features: u64,
    ) -> node_adapters_wire::DispatchReply {
        assert_eq!(op, WIRE_OP);
        node_adapters_wire::DispatchReply {
            status: 200,
            body_kind: 1,
            body: node_adapters_wire::Body::Whole(wire_reply_body()),
        }
    }
}

/// The node's side of the wire socket: the preamble the splice writes, then the real node-wire
/// connection driver.
async fn node_behind_wire_socket(listener: UnixListener) {
    use tokio::io::AsyncReadExt;
    let (mut stream, _) = listener.accept().await.unwrap();
    let mut line = Vec::new();
    loop {
        let byte = stream.read_u8().await.unwrap();
        if byte == b'\n' {
            break;
        }
        line.push(byte);
    }
    let preamble: serde_json::Value = serde_json::from_slice(&line).unwrap();
    assert_eq!(preamble["carrier"], "webrtc");
    let meta = node_adapters_wire::ConnMeta {
        carrier: node_adapters_wire::Carrier::WebRtc,
        peer: node_adapters_wire::ConnPeer::Unknown,
        peer_node_id: None,
        local_endpoint_id: None,
        peer_hello: None,
    };
    let _ = node_adapters_wire::serve_connection(
        stream,
        meta,
        Arc::new(NodeAuth),
        Arc::new(NodeDispatch),
        Arc::new(node_adapters_wire::WireStats::new()),
        Arc::new(node_adapters_wire::WireTail::with_enabled(false)),
        None,
        None,
    )
    .await;
}

/// One browser write and the DataChannel messages the answerer sent back for it, each message
/// whole (its MORE flag byte first). `closed`: the answerer closed the channel. `timed_out`:
/// the expected frame (WELCOME, then REPLY) had not arrived within the deadline.
struct WireStep {
    uplink: Vec<u8>,
    messages: Vec<Vec<u8>>,
    closed: bool,
    timed_out: bool,
}

fn wire_client() -> (node_wire::Session, Vec<u8>) {
    let hello = node_wire::Hello {
        versions: vec![1],
        features: WIRE_BROWSER_FEATURES,
        role: 0,
        credential: Some(WIRE_CREDENTIAL.into()),
        peer_proof: None,
        resume_token: None,
        text_mode: None,
        delegation: None,
    };
    let cfg = node_wire::Config {
        versions: vec![1],
        features: WIRE_BROWSER_FEATURES,
        role: node_wire::Role::Browser,
    };
    node_wire::Session::client(cfg, hello).unwrap()
}

/// What the browser makes of the messages: `DataChannelFrameReassembler` (join payloads until a
/// message without MORE), then the node-wire decoder over the joined stream.
struct BrowserSide {
    client: node_wire::Session,
    partial: Vec<u8>,
    failed: bool,
}
impl BrowserSide {
    fn message(&mut self, message: &[u8]) -> Vec<node_wire::Event> {
        self.partial.extend_from_slice(&message[1..]);
        if message[0] & 1 != 0 || self.failed {
            return vec![];
        }
        let frame = std::mem::take(&mut self.partial);
        match self.client.on_bytes(&frame) {
            Ok(events) => events,
            Err(_) => {
                self.failed = true;
                vec![]
            }
        }
    }
}

/// HELLO, then (once WELCOME is read) one CALL, through the real answerer; returns what the
/// answerer put on the DataChannel for each. Records whatever arrives within the deadline, so it
/// also captures a broken answerer (the RED fixture).
async fn capture_wire_answerer() -> Vec<WireStep> {
    let dir = tempfile::tempdir().unwrap();
    let sock = dir.path().join("wire.sock");
    let listener = UnixListener::bind(&sock).unwrap();
    let node = tokio::spawn(node_behind_wire_socket(listener));
    let mut b = Browser::with_answerer(
        crate::wire::WIRE_METHOD,
        Arc::new(WireSocket { path: Some(sock) }),
    )
    .await;
    b.method(crate::wire::WIRE_METHOD);
    let (client, hello) = wire_client();
    let mut side = BrowserSide {
        client,
        partial: vec![],
        failed: false,
    };
    let mut steps = Vec::new();
    let mut next = Some(hello);
    while let Some(uplink) = next.take() {
        b.send(&uplink);
        let mut step = WireStep {
            uplink,
            messages: vec![],
            closed: false,
            timed_out: false,
        };
        let mut ready = false;
        step.timed_out = tokio::time::timeout(Duration::from_secs(3), async {
            loop {
                match b.step().await {
                    Some(Event::ChannelData(data)) => {
                        assert!(data.binary);
                        step.messages.push(data.data.clone());
                        for event in side.message(&data.data) {
                            match event {
                                node_wire::Event::Ready { .. } => ready = true,
                                node_wire::Event::Reply { .. } => return,
                                _ => {}
                            }
                        }
                        if ready {
                            return;
                        }
                    }
                    Some(Event::ChannelClose(_)) | Some(Event::Closed) => {
                        step.closed = true;
                        return;
                    }
                    _ => {}
                }
            }
        })
        .await
        .is_err();
        let first = steps.is_empty();
        let closed = step.closed;
        steps.push(step);
        if first && ready && !closed {
            next = Some(side.client.call(WIRE_OP, None).unwrap().1);
        }
    }
    b.handle.close();
    drop(b);
    node.abort();
    steps
}

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

#[tokio::test]
async fn wire_answerer_hands_the_browser_whole_node_wire_frames() {
    let steps = capture_wire_answerer().await;
    assert_eq!(
        steps.len(),
        2,
        "the browser read WELCOME, so its CALL went out"
    );
    // Replay the messages as the browser does and read the frames back.
    let (client, _) = wire_client();
    let mut side = BrowserSide {
        client,
        partial: vec![],
        failed: false,
    };
    let mut events = Vec::new();
    for step in &steps {
        assert!(
            !step.timed_out,
            "no WELCOME/REPLY within 3 s of the browser's write ({} messages)",
            step.messages.len()
        );
        assert!(!step.closed, "the answerer closed the wire channel");
        for message in &step.messages {
            assert!(message.len() <= CHUNK, "a DataChannel message over 16 KiB");
            assert_eq!(message[0], 0, "a wire message is whole (no MORE bit)");
            events.extend(side.message(message));
        }
    }
    assert!(!side.failed, "the browser's decoder rejected the bytes");
    assert!(
        matches!(
            events.first(),
            Some(node_wire::Event::Ready { version: 1, .. })
        ),
        "WELCOME first: {events:?}"
    );
    let body = wire_reply_body();
    match events.get(1) {
        Some(node_wire::Event::Reply {
            id: 1,
            status: 200,
            body: Some(raw),
            ..
        }) => {
            // `raw` is the body as a CBOR byte string: a 3-byte head (major type 2 with a
            // 2-byte length, 0x59 len_hi len_lo, since 20 KiB needs 16 bits) and then the bytes.
            assert_eq!(
                raw.0[..3],
                [0x59, (body.len() >> 8) as u8, body.len() as u8]
            );
            assert_eq!(raw.0[3..], body[..]);
        }
        other => panic!("REPLY to call 1 expected, got {other:?}"),
    }
    // The REPLY frame really crossed the DataChannel limit.
    let reply: usize = steps[1].messages.iter().map(|m| m.len() - 1).sum();
    assert!(reply > CHUNK && steps[1].messages.len() >= 2);
}

/// Writes the fixture the JS replay reads. Regenerate with
/// `cargo test -p node-device-session --lib write_webrtc_answerer_wire_fixture -- --ignored`.
#[tokio::test]
#[ignore = "writes client/adapters-web/src/network/wire/fixtures/webrtc-answerer-datachannel.json"]
async fn write_webrtc_answerer_wire_fixture() {
    let steps = capture_wire_answerer().await;
    let fixture = json!({
        "about": "DataChannel messages the real device-session WebRtcAnswerer sent for one node-wire \
            exchange (HELLO -> WELCOME, CALL -> a 20 KiB REPLY), the real node-wire node behind the \
            wire socket. Each message is hex with its 1-byte MORE flag first. Written by \
            sdk/device-session/src/webrtc/tests.rs; replayed by \
            client/adapters-web/src/network/wire/webrtc-answerer-fixture.test.js.",
        "regenerate": "cargo test -p node-device-session --lib write_webrtc_answerer_wire_fixture -- --ignored",
        "credential": WIRE_CREDENTIAL,
        "op": WIRE_OP,
        "reply_body_bytes": wire_reply_body().len(),
        "steps": steps.iter().map(|s| json!({
            "uplink": to_hex(&s.uplink),
            "closed": s.closed,
            "timed_out": s.timed_out,
            "messages": s.messages.iter().map(|m| json!({
                "more": m[0] & 1 == 1,
                "hex": to_hex(m),
            })).collect::<Vec<_>>(),
        })).collect::<Vec<_>>(),
    });
    let mut text = serde_json::to_string_pretty(&fixture).unwrap();
    text.push('\n');
    std::fs::write(WIRE_FIXTURE, text).unwrap();
}