openrtc 2.9.8

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
//! Generation-fenced control frames for packet-carrier preparation.
//!
//! These frames travel only over an already-admitted OpenRTC control stream.
//! They negotiate route-local carrier objects; they do not admit peers,
//! authorize product traffic, or install a physical replacement.

use crate::{
    iroh_carrier::CarrierFrameExpectation,
    iroh_carrier_kind::{EXPERIMENTAL_MOQ_TRANSPORT_ID, EXPERIMENTAL_WEBRTC_TRANSPORT_ID},
};

/// One recovery budget shared by native and browser carrier owners. Only
/// transient mechanism/base failures qualify; authorization denial and policy failures
/// remain terminal. Attempt numbers travel on the peer control transcript.
#[cfg(feature = "transport-webrtc")]
pub(crate) fn webrtc_retry_attempt(failure_code: &str, attempt: u8) -> Option<u8> {
    (attempt == 1
        && matches!(
            failure_code,
            "carrier-base-generation-stale"
                | "carrier-base-not-ready"
                | "carrier-start-failed"
                | "carrier-timeout"
                | "carrier-proof-failed"
                | "data-channel-failed"
                | "ice-failed"
                | "signaling-failed"
                | "carrier-authorization-stale"
        ))
    .then_some(2)
}

/// Preserve recoverable peer facts without treating arbitrary diagnostic text
/// as retry policy. A denied capability must never become a transient failure.
#[cfg(feature = "transport-webrtc")]
pub(crate) fn webrtc_peer_failure_code(code: Option<&str>) -> &'static str {
    match code {
        Some("carrier-base-not-ready") => "carrier-base-not-ready",
        Some("carrier-base-generation-stale") => "carrier-base-generation-stale",
        Some("carrier-start-failed") => "carrier-start-failed",
        Some("carrier-timeout") => "carrier-timeout",
        Some("carrier-proof-failed") => "carrier-proof-failed",
        Some("data-channel-failed") => "data-channel-failed",
        Some("ice-failed") => "ice-failed",
        Some("signaling-failed") => "signaling-failed",
        Some("carrier-authorization-stale") => "carrier-authorization-stale",
        Some("carrier-authorization-rejected") => "carrier-authorization-rejected",
        _ => "peer-rejected-carrier",
    }
}

/// Random upgrade IDs spread simultaneous recovery without another RNG or
/// coordination request. This is one delayed retry, never a polling loop.
#[cfg(feature = "transport-webrtc")]
pub(crate) fn webrtc_retry_delay(upgrade_id: &str) -> std::time::Duration {
    let seed = upgrade_id.bytes().fold(0u64, |seed, byte| {
        seed.wrapping_mul(31).wrapping_add(u64::from(byte))
    });
    std::time::Duration::from_millis(400 + seed % 401)
}

/// One event-driven ICE refresh per committed mechanism per quiet interval.
/// This is subordinate policy state, not a timer or another peer registry.
#[cfg(feature = "transport-webrtc")]
#[derive(Debug, Clone, Default)]
pub(crate) struct WebRtcIceRefreshGate {
    last_refresh: Option<web_time::Instant>,
}

#[cfg(feature = "transport-webrtc")]
pub(crate) const WEBRTC_ICE_REFRESH_INTERVAL_MS: u64 = 30_000;

#[cfg(feature = "transport-webrtc")]
impl WebRtcIceRefreshGate {
    pub(crate) fn reserve(&mut self, now: web_time::Instant) -> bool {
        if self.last_refresh.is_some_and(|last| {
            now.duration_since(last).as_millis() < u128::from(WEBRTC_ICE_REFRESH_INTERVAL_MS)
        }) {
            return false;
        }
        self.last_refresh = Some(now);
        true
    }
}

/// Shared native/WASM interpretation of platform facts. A network change
/// while hidden is retained until foreground; brief tab changes alone do not
/// refresh ICE. There is no availability polling or lifecycle timer here.
#[cfg(feature = "transport-webrtc")]
#[derive(Debug, Default)]
pub(crate) struct WebRtcAvailability {
    backgrounded_at: Option<web_time::Instant>,
    network_changed: bool,
}

#[cfg(feature = "transport-webrtc")]
impl WebRtcAvailability {
    pub(crate) fn observe(&mut self, observation: &str) -> bool {
        match observation {
            "background" => {
                self.backgrounded_at
                    .get_or_insert_with(web_time::Instant::now);
                false
            }
            "foreground" => {
                let elapsed = self.backgrounded_at.take().map(|since| since.elapsed());
                let changed = std::mem::take(&mut self.network_changed);
                changed
                    || elapsed.is_some_and(|duration| {
                        duration.as_millis() >= u128::from(WEBRTC_ICE_REFRESH_INTERVAL_MS)
                    })
            }
            "network-change" => {
                if self.backgrounded_at.is_some() {
                    self.network_changed = true;
                    false
                } else {
                    true
                }
            }
            _ => false,
        }
    }
}

pub const CARRIER_BOOTSTRAP_PROTOCOL_VERSION: u8 = 1;
pub const CARRIER_BOOTSTRAP_FRAME_TYPE: &str = "#openrtc-iroh-carrier";

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum CarrierBootstrapKind {
    Ble,
    WebRtc,
    MoqDraft14,
}

impl CarrierBootstrapKind {
    pub fn transport_id(self) -> u64 {
        match self {
            Self::Ble => 0x42_4c_45,
            Self::WebRtc => EXPERIMENTAL_WEBRTC_TRANSPORT_ID,
            Self::MoqDraft14 => EXPERIMENTAL_MOQ_TRANSPORT_ID,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum CarrierBootstrapAction {
    Request,
    Ready,
    Failed,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
/// Process-local fence issued with a carrier request. The peer echoes every
/// field; only the issuing process compares the echo with its lifecycle state.
pub struct CarrierGenerationFence {
    pub transport_stable_id: u64,
    pub transport_generation: u64,
    pub route_generation: u64,
}

#[cfg(not(target_arch = "wasm32"))]
impl From<crate::client::NativePeerDataGeneration> for CarrierGenerationFence {
    fn from(value: crate::client::NativePeerDataGeneration) -> Self {
        Self {
            transport_stable_id: value.transport_stable_id,
            transport_generation: value.transport_generation,
            route_generation: value.route_generation,
        }
    }
}

/// One carrier bootstrap attempt.
///
/// `failure_code` is intentionally typed and bounded. Adapter errors, relay
/// tokens, SDP, candidates, and other potentially sensitive diagnostics do not
/// belong in this envelope.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CarrierBootstrapFrame {
    #[serde(rename = "type")]
    pub frame_type: String,
    pub protocol_version: u8,
    pub carrier: CarrierBootstrapKind,
    pub action: CarrierBootstrapAction,
    pub upgrade_id: String,
    pub carrier_session_id: String,
    pub attempt: u8,
    pub base: CarrierGenerationFence,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub failure_code: Option<String>,
}

impl CarrierBootstrapFrame {
    pub fn request(
        carrier: CarrierBootstrapKind,
        base: CarrierGenerationFence,
        attempt: u8,
    ) -> Result<Self, CarrierBootstrapError> {
        let mut upgrade_id = [0u8; 16];
        let mut carrier_session_id = [0u8; 16];
        getrandom::getrandom(&mut upgrade_id).map_err(|_| CarrierBootstrapError::Entropy)?;
        getrandom::getrandom(&mut carrier_session_id)
            .map_err(|_| CarrierBootstrapError::Entropy)?;
        Ok(Self::request_with_ids(
            carrier,
            base,
            attempt,
            upgrade_id,
            carrier_session_id,
        ))
    }

    pub fn request_with_ids(
        carrier: CarrierBootstrapKind,
        base: CarrierGenerationFence,
        attempt: u8,
        upgrade_id: [u8; 16],
        carrier_session_id: [u8; 16],
    ) -> Self {
        Self {
            frame_type: CARRIER_BOOTSTRAP_FRAME_TYPE.to_string(),
            protocol_version: CARRIER_BOOTSTRAP_PROTOCOL_VERSION,
            carrier,
            action: CarrierBootstrapAction::Request,
            upgrade_id: hex::encode(upgrade_id),
            carrier_session_id: hex::encode(carrier_session_id),
            attempt,
            base,
            failure_code: None,
        }
    }

    pub fn ready_from(request: &Self) -> Result<Self, CarrierBootstrapError> {
        request.validate()?;
        if request.action != CarrierBootstrapAction::Request {
            return Err(CarrierBootstrapError::InvalidTransition);
        }
        let mut ready = request.clone();
        ready.action = CarrierBootstrapAction::Ready;
        Ok(ready)
    }

    pub fn failed_from(
        request: &Self,
        failure_code: impl Into<String>,
    ) -> Result<Self, CarrierBootstrapError> {
        request.validate()?;
        let failure_code = failure_code.into();
        if request.action != CarrierBootstrapAction::Request
            || failure_code.is_empty()
            || failure_code.len() > 96
            || !failure_code
                .bytes()
                .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-')
        {
            return Err(CarrierBootstrapError::InvalidFailureCode);
        }
        let mut failed = request.clone();
        failed.action = CarrierBootstrapAction::Failed;
        failed.failure_code = Some(failure_code);
        Ok(failed)
    }

    pub fn validate(&self) -> Result<(), CarrierBootstrapError> {
        if self.frame_type != CARRIER_BOOTSTRAP_FRAME_TYPE {
            return Err(CarrierBootstrapError::WrongFrameType);
        }
        if self.protocol_version != CARRIER_BOOTSTRAP_PROTOCOL_VERSION {
            return Err(CarrierBootstrapError::UnsupportedVersion(
                self.protocol_version,
            ));
        }
        if self.attempt == 0 {
            return Err(CarrierBootstrapError::InvalidAttempt);
        }
        decode_id(&self.upgrade_id).ok_or(CarrierBootstrapError::InvalidUpgradeId)?;
        decode_id(&self.carrier_session_id)
            .ok_or(CarrierBootstrapError::InvalidCarrierSessionId)?;
        match self.action {
            CarrierBootstrapAction::Request | CarrierBootstrapAction::Ready
                if self.failure_code.is_some() =>
            {
                Err(CarrierBootstrapError::UnexpectedFailureCode)
            }
            CarrierBootstrapAction::Failed if self.failure_code.is_none() => {
                Err(CarrierBootstrapError::InvalidFailureCode)
            }
            _ => Ok(()),
        }
    }

    pub fn is_current(
        &self,
        carrier: CarrierBootstrapKind,
        base: CarrierGenerationFence,
        attempt: u8,
        upgrade_id: &str,
    ) -> bool {
        self.validate().is_ok()
            && self.carrier == carrier
            && self.base == base
            && self.attempt == attempt
            && self.upgrade_id == upgrade_id
    }

    pub fn is_response_to(&self, request: &Self) -> bool {
        self.validate().is_ok()
            && request.validate().is_ok()
            && request.action == CarrierBootstrapAction::Request
            && matches!(
                self.action,
                CarrierBootstrapAction::Ready | CarrierBootstrapAction::Failed
            )
            && self.carrier == request.carrier
            && self.upgrade_id == request.upgrade_id
            && self.carrier_session_id == request.carrier_session_id
            && self.attempt == request.attempt
            && self.base == request.base
    }

    pub fn frame_expectation(&self) -> Result<CarrierFrameExpectation, CarrierBootstrapError> {
        self.validate()?;
        let session = decode_id(&self.carrier_session_id)
            .ok_or(CarrierBootstrapError::InvalidCarrierSessionId)?;
        Ok(CarrierFrameExpectation {
            transport_id: self.carrier.transport_id(),
            carrier_session_id: session,
            transport_generation: self.base.transport_generation.saturating_add(1),
        })
    }

    pub fn from_json(value: &serde_json::Value) -> Option<Self> {
        if value.get("type").and_then(serde_json::Value::as_str)
            != Some(CARRIER_BOOTSTRAP_FRAME_TYPE)
        {
            return None;
        }
        serde_json::from_value::<Self>(value.clone())
            .ok()
            .filter(|frame| frame.validate().is_ok())
    }
}

fn decode_id(value: &str) -> Option<[u8; 16]> {
    if value.len() != 32
        || !value
            .bytes()
            .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
    {
        return None;
    }
    let decoded = hex::decode(value).ok()?;
    decoded.try_into().ok()
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CarrierBootstrapError {
    Entropy,
    WrongFrameType,
    UnsupportedVersion(u8),
    InvalidAttempt,
    InvalidUpgradeId,
    InvalidCarrierSessionId,
    InvalidTransition,
    InvalidFailureCode,
    UnexpectedFailureCode,
}

impl std::fmt::Display for CarrierBootstrapError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Entropy => formatter.write_str("carrier bootstrap entropy unavailable"),
            Self::WrongFrameType => formatter.write_str("wrong carrier bootstrap frame type"),
            Self::UnsupportedVersion(version) => {
                write!(formatter, "unsupported carrier bootstrap version {version}")
            }
            Self::InvalidAttempt => {
                formatter.write_str("carrier bootstrap attempt must be non-zero")
            }
            Self::InvalidUpgradeId => formatter.write_str("invalid carrier upgrade id"),
            Self::InvalidCarrierSessionId => formatter.write_str("invalid carrier session id"),
            Self::InvalidTransition => formatter.write_str("invalid carrier bootstrap transition"),
            Self::InvalidFailureCode => formatter.write_str("invalid carrier failure code"),
            Self::UnexpectedFailureCode => {
                formatter.write_str("failure code is not allowed for this carrier action")
            }
        }
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;

    fn generation() -> CarrierGenerationFence {
        CarrierGenerationFence {
            transport_stable_id: 41,
            transport_generation: 7,
            route_generation: 3,
        }
    }

    fn request(carrier: CarrierBootstrapKind, attempt: u8) -> CarrierBootstrapFrame {
        CarrierBootstrapFrame::request_with_ids(
            carrier,
            generation(),
            attempt,
            [attempt; 16],
            [attempt.saturating_add(1); 16],
        )
    }

    #[test]
    fn request_ready_round_trip_retains_complete_fence() {
        let request = request(CarrierBootstrapKind::WebRtc, 2);
        let ready = CarrierBootstrapFrame::ready_from(&request).unwrap();
        let value = serde_json::to_value(&ready).unwrap();
        let decoded = CarrierBootstrapFrame::from_json(&value).unwrap();

        assert!(decoded.is_current(
            CarrierBootstrapKind::WebRtc,
            generation(),
            2,
            &request.upgrade_id
        ));
        assert_eq!(
            decoded.frame_expectation().unwrap().transport_generation,
            generation().transport_generation + 1
        );
        assert!(decoded.is_response_to(&request));
    }

    #[test]
    fn response_must_match_session_and_complete_generation_fence() {
        let request = request(CarrierBootstrapKind::WebRtc, 2);
        let mut ready = CarrierBootstrapFrame::ready_from(&request).unwrap();
        ready.carrier_session_id = "00".repeat(16);
        assert!(!ready.is_response_to(&request));

        let mut ready = CarrierBootstrapFrame::ready_from(&request).unwrap();
        ready.base.route_generation += 1;
        assert!(!ready.is_response_to(&request));

        let failed = CarrierBootstrapFrame::failed_from(&request, "carrier-timeout").unwrap();
        assert!(failed.is_response_to(&request));
    }

    #[test]
    fn stale_generation_and_attempt_are_not_current() {
        let request = request(CarrierBootstrapKind::MoqDraft14, 1);
        let mut replacement = generation();
        replacement.transport_generation += 1;

        assert!(!request.is_current(
            CarrierBootstrapKind::MoqDraft14,
            replacement,
            1,
            &request.upgrade_id
        ));
        assert!(!request.is_current(
            CarrierBootstrapKind::MoqDraft14,
            generation(),
            2,
            &request.upgrade_id
        ));
    }

    #[test]
    fn failures_are_typed_and_do_not_accept_diagnostics() {
        let request = request(CarrierBootstrapKind::WebRtc, 1);
        assert!(CarrierBootstrapFrame::failed_from(&request, "relay-unavailable").is_ok());
        assert!(CarrierBootstrapFrame::failed_from(&request, "token=secret value").is_err());
    }

    #[test]
    fn malformed_bootstrap_json_is_not_claimed() {
        let request = request(CarrierBootstrapKind::WebRtc, 1);
        let mut value = serde_json::to_value(request).unwrap();
        value["carrierSessionId"] = serde_json::Value::String("not-an-id".to_string());
        assert!(CarrierBootstrapFrame::from_json(&value).is_none());
    }
}