Skip to main content

node_device_session/
serve.rs

1//! [`serve`]: the C-5 device-session accept loop.
2
3use crate::messages::{
4    endpoint_hex, scope_allows, service, stamp, OpenMode, OpenOk, OpenRequest, PairOk, PairRequest,
5    RenewOk, RenewRequest, ServiceCall, StampIdentity,
6};
7use crate::registry::{SessionClose, SessionRegistry};
8use crate::traits::{BoxRecv, BoxSend, HostBus, SessionStreams, WebRtcSignaling};
9use crate::tunnel::{self, Gate};
10use crate::types::{IngressSocket, Refusal, Session, SessionEnd, SessionPath, WireSocket};
11use crate::wire::{
12    decode_request, encode_response, peek_method, DEVICE_CALL_METHOD, HTTP_REQUEST_METHOD,
13    MAX_FRAME_BYTES, RESPONSE_STATUS_ERR, RESPONSE_STATUS_OK, SESSION_OPEN_METHOD,
14    SESSION_PAIR_METHOD, SESSION_RENEW_METHOD, WEBRTC_SIGNAL_METHOD, WIRE_METHOD, WS_STREAM_METHOD,
15};
16use crate::wire_stream;
17use std::sync::Arc;
18use std::time::Duration;
19use tokio::io::{AsyncReadExt, AsyncWriteExt};
20use tokio::task::JoinSet;
21
22const OPEN_DEADLINE: Duration = Duration::from_secs(10);
23const CALL_DEADLINE: Duration = Duration::from_secs(30);
24const CALL_READ_DEADLINE: Duration = Duration::from_secs(30);
25const CLOSE_GRACE: Duration = Duration::from_secs(2);
26const MAX_SESSION_STREAMS: usize = 16;
27const RENEWAL_LIFETIME: Duration = Duration::from_secs(120);
28const PAIRING_LIFETIME: Duration = Duration::from_secs(120);
29const PROTOCOL_CLOSE_CODE: u32 = 1;
30
31fn err_frame(code: &str, message: &str) -> Vec<u8> {
32    encode_response(RESPONSE_STATUS_ERR, format!("{code}: {message}").as_bytes())
33}
34
35fn session_from_verify(session: Session) -> OpenOk {
36    OpenOk {
37        mode: OpenMode::Full,
38        device_id: session.device_id,
39        device_did: session.device_did,
40        scopes: session.scopes,
41        expires_at: session.expires_at,
42    }
43}
44
45fn session_from_admit(session: Session) -> OpenOk {
46    OpenOk {
47        mode: OpenMode::Renewal,
48        device_id: session.device_id,
49        device_did: session.device_did,
50        scopes: vec![],
51        expires_at: if session.expires_at.is_empty() {
52            renewal_expires_at()
53        } else {
54            session.expires_at
55        },
56    }
57}
58
59fn map_verify_refusal(refusal: Refusal) -> Vec<u8> {
60    match refusal.code.as_str() {
61        "invalid_request"
62        | "endpoint_mismatch"
63        | "invalid_credential"
64        | "device_revoked"
65        | "expired"
66        | "verifier_unavailable" => err_frame(&refusal.code, &refusal.message),
67        _ => err_frame(
68            "verifier_unavailable",
69            "verification is temporarily unavailable",
70        ),
71    }
72}
73
74fn map_renew_refusal(refusal: Refusal) -> (&'static str, &'static str) {
75    match refusal.code.as_str() {
76        "device_revoked" => ("device_revoked", "the device is revoked"),
77        "device_not_registered" => ("device_not_registered", "the device is not registered"),
78        "pending_approval" => ("pending_approval", "the device awaits approval"),
79        "rejected" => ("rejected", "the device was rejected"),
80        "rate_limited" => ("rate_limited", "try renewal later"),
81        "invalid_request" => ("invalid_request", "invalid renewal request"),
82        "internal_error" => ("internal_error", "renewal failed"),
83        _ => ("renew_unavailable", "renewal is temporarily unavailable"),
84    }
85}
86
87fn map_admit_refusal(refusal: Refusal) -> Vec<u8> {
88    match refusal.code.as_str() {
89        "rate_limited" => err_frame("rate_limited", "renewal admission rate limited"),
90        "device_revoked" => err_frame("device_revoked", "the device is revoked"),
91        "unknown_endpoint" => err_frame("unknown_endpoint", "the endpoint is not registered"),
92        _ => err_frame(
93            "verifier_unavailable",
94            "verification is temporarily unavailable",
95        ),
96    }
97}
98
99/// A pairing-only session, admitted by a door token (C-7) or opened without
100/// one (ADR-399 Amendment 2).
101struct Pairing {
102    /// The door member stamped in `x-node-pairing-door`; `None` for an open
103    /// session, which stamps only the endpoint.
104    member: Option<String>,
105    /// The proven endpoint, stamped in `x-node-pairing-endpoint`.
106    endpoint: String,
107    /// How long this session lives: [`PAIRING_LIFETIME`], or less when the
108    /// token expires first.
109    lifetime: Duration,
110}
111
112fn map_pairing_refusal(refusal: Refusal) -> Vec<u8> {
113    match refusal.code.as_str() {
114        "pairing_token_invalid" => {
115            err_frame("pairing_token_invalid", "the door token is not valid")
116        }
117        "pairing_token_expired" => err_frame("pairing_token_expired", "the door token has expired"),
118        "pairing_token_bound" => err_frame(
119            "pairing_token_bound",
120            "the door token belongs to another device",
121        ),
122        "pairing_rate_limited" => err_frame("pairing_rate_limited", "try pairing later"),
123        "not_open" => err_frame("not_open", "this node does not open pairing sessions"),
124        "invalid_request" => err_frame("invalid_request", "invalid pairing request"),
125        _ => err_frame(
126            "verifier_unavailable",
127            "verification is temporarily unavailable",
128        ),
129    }
130}
131
132/// A member id goes into an HTTP header: only ASCII alphanumerics (node ids are hex).
133fn member_node_id_ok(member: &str) -> bool {
134    !member.is_empty() && member.len() <= 256 && member.bytes().all(|b| b.is_ascii_alphanumeric())
135}
136
137async fn respond(send: &mut (impl AsyncWriteExt + Unpin), frame: Vec<u8>) {
138    let _ = send.write_all(&frame).await;
139    let _ = send.shutdown().await;
140}
141
142async fn respond_before_close(send: &mut (impl AsyncWriteExt + Unpin), frame: Vec<u8>) {
143    respond(send, frame).await;
144    tokio::time::sleep(CLOSE_GRACE).await;
145}
146
147/// Optional knobs for [`serve_with_options`].
148///
149/// Additive: existing [`serve`] / [`serve_with_registry`] keep their signatures
150/// and behave as today (no wire socket → `wire/1` refused).
151#[non_exhaustive]
152#[derive(Clone, Default)]
153pub struct ServeOptions {
154    /// Live-session registry for periodic revalidation; `None` skips registration.
155    pub registry: Option<SessionRegistry>,
156    /// Node wire socket `wire/1` splices onto; default (no path) refuses.
157    pub wire: WireSocket,
158}
159
160/// Serve one authenticated peer connection until it ends.
161///
162/// `webrtc` is the carrier hook for `webrtc.signal/1`. Pass [`Some`] when the
163/// carrier can answer WebRTC on this connection (iroh); pass [`None`] to refuse
164/// with `unsupported_transport`.
165///
166/// Does not touch a [`SessionRegistry`]. Carriers that need live-session
167/// revalidation should call [`serve_with_registry`] instead. Carriers that
168/// need `wire/1` should call [`serve_with_options`].
169pub async fn serve<C, B>(
170    conn: C,
171    bus: B,
172    ingress: IngressSocket,
173    path: SessionPath,
174    webrtc: Option<Arc<dyn WebRtcSignaling>>,
175) -> Result<(), SessionEnd>
176where
177    C: SessionStreams + 'static,
178    B: HostBus + 'static,
179{
180    serve_with_options(conn, bus, ingress, path, webrtc, ServeOptions::default()).await
181}
182
183/// Like [`serve`], but registers a successful full-mode open in `registry`
184/// (for once-a-minute revalidation) and removes it when this call returns.
185///
186/// The close callback stored in the registry closes the [`SessionStreams`]
187/// connection. Bind a [`crate::WebRtcHandle`] with
188/// [`SessionRegistry::bind_webrtc`] so revocation also tears down WebRTC.
189///
190/// For `wire/1`, use [`serve_with_options`] with both `registry` and `wire`.
191pub async fn serve_with_registry<C, B>(
192    conn: C,
193    bus: B,
194    ingress: IngressSocket,
195    path: SessionPath,
196    webrtc: Option<Arc<dyn WebRtcSignaling>>,
197    registry: SessionRegistry,
198) -> Result<(), SessionEnd>
199where
200    C: SessionStreams + 'static,
201    B: HostBus + 'static,
202{
203    serve_with_options(
204        conn,
205        bus,
206        ingress,
207        path,
208        webrtc,
209        ServeOptions {
210            registry: Some(registry),
211            ..ServeOptions::default()
212        },
213    )
214    .await
215}
216
217/// Like [`serve`], with optional registry and wire socket via [`ServeOptions`].
218pub async fn serve_with_options<C, B>(
219    conn: C,
220    bus: B,
221    ingress: IngressSocket,
222    path: SessionPath,
223    webrtc: Option<Arc<dyn WebRtcSignaling>>,
224    options: ServeOptions,
225) -> Result<(), SessionEnd>
226where
227    C: SessionStreams + 'static,
228    B: HostBus + 'static,
229{
230    serve_inner(
231        conn,
232        bus,
233        ingress,
234        options.wire,
235        path,
236        webrtc,
237        options.registry,
238    )
239    .await
240}
241
242async fn serve_inner<C, B>(
243    conn: C,
244    bus: B,
245    ingress: IngressSocket,
246    wire: WireSocket,
247    path: SessionPath,
248    webrtc: Option<Arc<dyn WebRtcSignaling>>,
249    registry: Option<SessionRegistry>,
250) -> Result<(), SessionEnd>
251where
252    C: SessionStreams + 'static,
253    B: HostBus + 'static,
254{
255    let conn = Arc::new(conn);
256    let bus = Arc::new(bus);
257    let ingress = Arc::new(ingress);
258    let wire = Arc::new(wire);
259
260    let attempt = tokio::time::timeout(OPEN_DEADLINE, async {
261        let (mut send, mut recv) = conn.accept_bi().await?;
262        let mut bytes = Vec::new();
263        (&mut recv)
264            .take(MAX_FRAME_BYTES as u64 + 1)
265            .read_to_end(&mut bytes)
266            .await?;
267        if bytes.len() > MAX_FRAME_BYTES {
268            conn.close(PROTOCOL_CLOSE_CODE, b"frame too large or unreadable");
269            return Err(SessionEnd::NotOpened("frame too large".into()));
270        }
271        match decode_request(&bytes) {
272            Ok((method, payload)) if method == SESSION_OPEN_METHOD => {
273                open_first(conn.as_ref(), bus.as_ref(), send, payload)
274                    .await
275                    .map(|(send, ok, credential)| (send, ok, credential, None))
276            }
277            Ok((method, payload)) if method == SESSION_RENEW_METHOD => {
278                // Renew is one-shot and never registers a live session.
279                renew_first(conn.as_ref(), bus.as_ref(), send, payload)
280                    .await
281                    .map(|(send, ok)| (send, ok, None, None))
282            }
283            Ok((method, payload)) if method == SESSION_PAIR_METHOD => {
284                // No credential: a pairing-only session never registers.
285                pair_first(conn.as_ref(), bus.as_ref(), send, payload)
286                    .await
287                    .map(|(send, ok, pairing)| (send, ok, None, Some(pairing)))
288            }
289            _ => {
290                respond_before_close(
291                    &mut send,
292                    err_frame("not_open", "the first stream must be session.open/1"),
293                )
294                .await;
295                conn.close(PROTOCOL_CLOSE_CODE, b"session not opened");
296                Err(SessionEnd::NotOpened("not_open".into()))
297            }
298        }
299    })
300    .await;
301
302    let (send, identity, credential, pairing) = match attempt {
303        Ok(Ok(v)) => v,
304        Ok(Err(e)) => return Err(e),
305        Err(_) => {
306            conn.close(PROTOCOL_CLOSE_CODE, b"session not opened in time");
307            return Err(SessionEnd::OpenTimeout);
308        }
309    };
310
311    let registered = match (registry.as_ref(), credential) {
312        (Some(registry), Some(credential)) => {
313            let conn_close = conn.clone();
314            let close: SessionClose = Arc::new(move |code, reason| {
315                conn_close.close(code, reason);
316            });
317            let device_id = identity.device_id.clone();
318            let endpoint = endpoint_hex(&conn.peer_key());
319            let session_id = registry.insert(device_id.clone(), credential, endpoint, close);
320            Some((device_id, session_id))
321        }
322        _ => None,
323    };
324
325    let result = serve_opened(
326        conn, bus, ingress, wire, path, webrtc, send, identity, pairing,
327    )
328    .await;
329
330    if let (Some(registry), Some((device_id, session_id))) = (registry, registered) {
331        registry.remove_if(&device_id, session_id);
332    }
333    result
334}
335
336async fn open_first(
337    conn: &impl SessionStreams,
338    bus: &impl HostBus,
339    mut send: BoxSend,
340    payload: &[u8],
341) -> Result<(BoxSend, OpenOk, Option<String>), SessionEnd> {
342    let request: OpenRequest = match serde_json::from_slice(payload) {
343        Ok(r) => r,
344        Err(_) => {
345            respond_before_close(
346                &mut send,
347                err_frame(
348                    "invalid_request",
349                    "session.open/1 needs {credential} or {mode: renewal}",
350                ),
351            )
352            .await;
353            conn.close(PROTOCOL_CLOSE_CODE, b"session not opened");
354            return Err(SessionEnd::NotOpened("invalid_request".into()));
355        }
356    };
357
358    let endpoint = endpoint_hex(&conn.peer_key());
359    let (ok, credential) = if request.mode == Some(OpenMode::Renewal) {
360        if request.credential.is_some() {
361            respond_before_close(
362                &mut send,
363                err_frame("invalid_request", "renewal mode takes no credential"),
364            )
365            .await;
366            conn.close(PROTOCOL_CLOSE_CODE, b"session not opened");
367            return Err(SessionEnd::NotOpened("invalid_request".into()));
368        }
369        let ok = match bus.admit_renewal(&endpoint).await {
370            Ok(session) => session_from_admit(session),
371            Err(refusal) => {
372                respond_before_close(&mut send, map_admit_refusal(refusal)).await;
373                conn.close(PROTOCOL_CLOSE_CODE, b"session not opened");
374                return Err(SessionEnd::NotOpened("admit refused".into()));
375            }
376        };
377        (ok, None)
378    } else {
379        let credential = match request.credential.filter(|c| !c.is_empty()) {
380            Some(c) => c,
381            None => {
382                respond_before_close(
383                    &mut send,
384                    err_frame("invalid_request", "full mode needs a credential"),
385                )
386                .await;
387                conn.close(PROTOCOL_CLOSE_CODE, b"session not opened");
388                return Err(SessionEnd::NotOpened("invalid_request".into()));
389            }
390        };
391        let ok = match bus.verify(&credential, &endpoint).await {
392            Ok(session) => session_from_verify(session),
393            Err(refusal) => {
394                respond_before_close(&mut send, map_verify_refusal(refusal)).await;
395                conn.close(PROTOCOL_CLOSE_CODE, b"session not opened");
396                return Err(SessionEnd::NotOpened("verify refused".into()));
397            }
398        };
399        (ok, Some(credential))
400    };
401
402    let body = serde_json::to_vec(&ok).map_err(|_| SessionEnd::NotOpened("encode".into()))?;
403    respond(&mut send, encode_response(RESPONSE_STATUS_OK, &body)).await;
404    Ok((send, ok, credential))
405}
406
407async fn renew_first(
408    conn: &impl SessionStreams,
409    bus: &impl HostBus,
410    mut send: BoxSend,
411    payload: &[u8],
412) -> Result<(BoxSend, OpenOk), SessionEnd> {
413    let endpoint = endpoint_hex(&conn.peer_key());
414    let value: serde_json::Value = match serde_json::from_slice::<serde_json::Value>(payload) {
415        Ok(v) if v.is_object() => v,
416        _ => {
417            respond_before_close(
418                &mut send,
419                err_frame("invalid_request", "session.renew/1 needs {}"),
420            )
421            .await;
422            conn.close(PROTOCOL_CLOSE_CODE, b"renewal complete");
423            return Err(SessionEnd::NotOpened("invalid_request".into()));
424        }
425    };
426    if serde_json::from_value::<RenewRequest>(value).is_err() {
427        respond_before_close(
428            &mut send,
429            err_frame("invalid_request", "session.renew/1 needs {}"),
430        )
431        .await;
432        conn.close(PROTOCOL_CLOSE_CODE, b"renewal complete");
433        return Err(SessionEnd::NotOpened("invalid_request".into()));
434    }
435
436    match bus.renew(&endpoint).await {
437        Ok(session) => {
438            let ok = RenewOk {
439                credential: session.credential.unwrap_or_default(),
440                expires_at: session.expires_at,
441                scopes: session.scopes,
442                device_id: session.device_id,
443                device_did: session.device_did,
444                revocation_id: None,
445            };
446            let body = serde_json::to_vec(&ok).unwrap_or_default();
447            respond_before_close(&mut send, encode_response(RESPONSE_STATUS_OK, &body)).await;
448            conn.close(0, b"renewal complete");
449            Err(SessionEnd::Closed)
450        }
451        Err(refusal) => {
452            let (code, detail) = map_renew_refusal(refusal);
453            respond_before_close(&mut send, err_frame(code, detail)).await;
454            conn.close(PROTOCOL_CLOSE_CODE, b"renewal complete");
455            Err(SessionEnd::NotOpened(code.into()))
456        }
457    }
458}
459
460async fn pair_first(
461    conn: &impl SessionStreams,
462    bus: &impl HostBus,
463    mut send: BoxSend,
464    payload: &[u8],
465) -> Result<(BoxSend, OpenOk, Pairing), SessionEnd> {
466    let endpoint = endpoint_hex(&conn.peer_key());
467    // An empty token is a malformed request, never an open session: only a
468    // request without the field asks for one.
469    let request = serde_json::from_slice::<serde_json::Value>(payload)
470        .ok()
471        .filter(serde_json::Value::is_object)
472        .and_then(|v| serde_json::from_value::<PairRequest>(v).ok())
473        .filter(|r| r.token.as_deref() != Some(""));
474    let Some(request) = request else {
475        respond_before_close(
476            &mut send,
477            err_frame(
478                "invalid_request",
479                "session.pair/1 needs {endpoint_id} and, with a door link, its token",
480            ),
481        )
482        .await;
483        conn.close(PROTOCOL_CLOSE_CODE, b"session not opened");
484        return Err(SessionEnd::NotOpened("invalid_request".into()));
485    };
486    if !request.endpoint_id.eq_ignore_ascii_case(&endpoint) {
487        respond_before_close(
488            &mut send,
489            err_frame(
490                "endpoint_mismatch",
491                "endpoint_id is not the key this connection proved",
492            ),
493        )
494        .await;
495        conn.close(PROTOCOL_CLOSE_CODE, b"session not opened");
496        return Err(SessionEnd::NotOpened("endpoint_mismatch".into()));
497    }
498
499    let admitted = match request.token.as_deref() {
500        Some(token) => match bus.admit_pairing(token, &endpoint).await {
501            Ok(admission) if member_node_id_ok(&admission.member_node_id) => {
502                pairing_from_admission(
503                    Some(admission.member_node_id),
504                    admission.expires_at_ms,
505                    &endpoint,
506                )
507            }
508            // A member id that cannot be a header is a host fault, not the device's.
509            Ok(_) => Err(Refusal::new("internal_error", "unusable member id")),
510            Err(refusal) => Err(refusal),
511        },
512        None => bus
513            .admit_open_pairing(&endpoint)
514            .await
515            .and_then(|admission| pairing_from_admission(None, admission.expires_at_ms, &endpoint)),
516    };
517    let pairing = match admitted {
518        Ok(pairing) => pairing,
519        Err(refusal) => {
520            respond_before_close(&mut send, map_pairing_refusal(refusal)).await;
521            conn.close(PROTOCOL_CLOSE_CODE, b"session not opened");
522            return Err(SessionEnd::NotOpened("pairing refused".into()));
523        }
524    };
525    let ok = OpenOk {
526        mode: OpenMode::Renewal,
527        device_id: String::new(),
528        device_did: String::new(),
529        scopes: vec![],
530        expires_at: String::new(),
531    };
532    let body = serde_json::to_vec(&PairOk {
533        mode: "pairing",
534        expires_at_ms: now_ms().saturating_add(pairing.lifetime.as_millis() as i64),
535    })
536    .map_err(|_| SessionEnd::NotOpened("encode".into()))?;
537    respond(&mut send, encode_response(RESPONSE_STATUS_OK, &body)).await;
538    Ok((send, ok, pairing))
539}
540
541fn now_ms() -> i64 {
542    use std::time::{SystemTime, UNIX_EPOCH};
543    SystemTime::now()
544        .duration_since(UNIX_EPOCH)
545        .unwrap_or_default()
546        .as_millis() as i64
547}
548
549/// Shortest session worth opening; a token closer to expiry is refused.
550const MIN_PAIRING_LIFETIME: Duration = Duration::from_secs(1);
551
552/// [`PAIRING_LIFETIME`], cut short when the admission expires sooner.
553///
554/// A non-positive expiry is a host fault (`verifier_unavailable`); an
555/// admission that expires within [`MIN_PAIRING_LIFETIME`] is
556/// `pairing_token_expired`.
557fn pairing_from_admission(
558    member: Option<String>,
559    expires_at_ms: i64,
560    endpoint: &str,
561) -> Result<Pairing, Refusal> {
562    if expires_at_ms <= 0 {
563        return Err(Refusal::new(
564            "internal_error",
565            "admission without an expiry",
566        ));
567    }
568    let until_expiry = expires_at_ms.saturating_sub(now_ms());
569    if until_expiry < MIN_PAIRING_LIFETIME.as_millis() as i64 {
570        return Err(Refusal::new(
571            "pairing_token_expired",
572            "the door token has expired",
573        ));
574    }
575    Ok(Pairing {
576        member,
577        endpoint: endpoint.to_string(),
578        lifetime: PAIRING_LIFETIME.min(Duration::from_millis(until_expiry as u64)),
579    })
580}
581
582fn renewal_expires_at() -> String {
583    use std::time::{SystemTime, UNIX_EPOCH};
584    let secs = SystemTime::now()
585        .duration_since(UNIX_EPOCH)
586        .unwrap_or_default()
587        .as_secs()
588        + RENEWAL_LIFETIME.as_secs();
589    format!("{secs}")
590}
591
592#[allow(clippy::too_many_arguments)]
593async fn serve_opened<C, B>(
594    conn: Arc<C>,
595    bus: Arc<B>,
596    ingress: Arc<IngressSocket>,
597    wire: Arc<WireSocket>,
598    path: SessionPath,
599    webrtc: Option<Arc<dyn WebRtcSignaling>>,
600    _open_send: BoxSend,
601    identity: OpenOk,
602    pairing: Option<Pairing>,
603) -> Result<(), SessionEnd>
604where
605    C: SessionStreams + 'static,
606    B: HostBus + 'static,
607{
608    let identity = Arc::new(identity);
609    let pairing = pairing.map(Arc::new);
610    let peer = conn.peer_key();
611    let mut streams = JoinSet::new();
612    let lifetime = async {
613        if let Some(pairing) = pairing.as_ref() {
614            tokio::time::sleep(pairing.lifetime).await;
615        } else if identity.mode == OpenMode::Renewal {
616            tokio::time::sleep(RENEWAL_LIFETIME).await;
617        } else {
618            std::future::pending::<()>().await;
619        }
620    };
621    tokio::pin!(lifetime);
622
623    let serve = async {
624        loop {
625            while streams.try_join_next().is_some() {}
626            let (send, recv) = match conn.accept_bi().await {
627                Ok(s) => s,
628                Err(_) => break,
629            };
630            if streams.len() >= MAX_SESSION_STREAMS {
631                let mut send = send;
632                let mut recv = recv;
633                let _ = tokio::time::timeout(CALL_READ_DEADLINE, async {
634                    if let Ok(method) = peek_method(&mut recv).await {
635                        let _ = tunnel::refuse(&mut send, &method, "too_many_streams").await;
636                    }
637                })
638                .await;
639                let _ = send.shutdown().await;
640                continue;
641            }
642            let bus = bus.clone();
643            let ingress = ingress.clone();
644            let wire = wire.clone();
645            let identity = identity.clone();
646            let pairing = pairing.clone();
647            let webrtc = webrtc.clone();
648            streams.spawn(async move {
649                serve_stream(
650                    bus,
651                    ingress,
652                    wire,
653                    path,
654                    peer,
655                    &identity,
656                    pairing.as_deref(),
657                    webrtc,
658                    send,
659                    recv,
660                )
661                .await;
662            });
663        }
664    };
665
666    tokio::select! {
667        biased;
668        _ = &mut lifetime => {
669            let reason: &[u8] = if pairing.is_some() {
670                b"pairing session expired"
671            } else {
672                b"renewal session expired"
673            };
674            conn.close(PROTOCOL_CLOSE_CODE, reason);
675        }
676        _ = serve => {}
677    }
678    streams.abort_all();
679    while streams.join_next().await.is_some() {}
680    Ok(())
681}
682
683#[allow(clippy::too_many_arguments)]
684async fn serve_stream<B: HostBus>(
685    bus: Arc<B>,
686    ingress: Arc<IngressSocket>,
687    wire: Arc<WireSocket>,
688    path: SessionPath,
689    peer: [u8; 32],
690    identity: &OpenOk,
691    pairing: Option<&Pairing>,
692    webrtc: Option<Arc<dyn WebRtcSignaling>>,
693    mut send: BoxSend,
694    mut recv: BoxRecv,
695) {
696    let deadline = tokio::time::Instant::now() + CALL_READ_DEADLINE;
697    let method = match tokio::time::timeout_at(deadline, peek_method(&mut recv)).await {
698        Err(_) | Ok(Err(_)) => {
699            let _ = tunnel::refuse(&mut send, "unknown/1", "invalid_request").await;
700            let _ = send.shutdown().await;
701            return;
702        }
703        Ok(Ok(method)) => method,
704    };
705
706    // Checked first: a pairing session also carries a renewal-mode identity,
707    // so even without this gate it could do no more than renewal.
708    if pairing.is_some() && method != HTTP_REQUEST_METHOD {
709        let _ = tunnel::refuse(&mut send, &method, "pairing_only").await;
710        let _ = send.shutdown().await;
711        return;
712    }
713
714    if identity.mode == OpenMode::Renewal && method != HTTP_REQUEST_METHOD {
715        let _ = tunnel::refuse(&mut send, &method, "renewal_only").await;
716        let _ = send.shutdown().await;
717        return;
718    }
719
720    if method == WEBRTC_SIGNAL_METHOD {
721        match webrtc {
722            Some(hook) => {
723                hook.handle(identity, peer, send, recv).await;
724            }
725            None => {
726                let _ = tunnel::refuse(&mut send, &method, "unsupported_transport").await;
727                let _ = send.shutdown().await;
728            }
729        }
730        return;
731    }
732
733    // Post-open wire/1 for a FULL session only (renewal already refused above).
734    if method == WIRE_METHOD {
735        match wire.path.as_ref() {
736            Some(socket) => {
737                // Device-session carriers omit peer (no browser TCP IP).
738                let _ =
739                    wire_stream::splice_to_wire_socket(socket, path.as_str(), None, "", send, recv)
740                        .await;
741            }
742            None => {
743                let _ = tunnel::refuse(&mut send, WIRE_METHOD, "wire_unavailable").await;
744                let _ = send.shutdown().await;
745            }
746        }
747        return;
748    }
749
750    if method == HTTP_REQUEST_METHOD {
751        let gate = match (pairing, identity.mode) {
752            (Some(pairing), _) => Gate::Pairing {
753                member: pairing.member.as_deref(),
754                endpoint: &pairing.endpoint,
755            },
756            (None, OpenMode::Renewal) => Gate::Renewal,
757            (None, OpenMode::Full) => Gate::Full,
758        };
759        let _ = tunnel::serve_http(&ingress, path, &mut recv, &mut send, gate).await;
760        let _ = send.shutdown().await;
761        return;
762    }
763
764    if method == WS_STREAM_METHOD {
765        let _ = tunnel::serve_ws(&ingress, path, recv, send).await;
766        return;
767    }
768
769    let mut payload = Vec::new();
770    let read = tokio::time::timeout_at(
771        deadline,
772        recv.take((MAX_FRAME_BYTES - 2 - method.len()) as u64)
773            .read_to_end(&mut payload),
774    )
775    .await;
776    if read.is_err() || matches!(read, Ok(Err(_))) {
777        respond(
778            &mut send,
779            err_frame("invalid_request", "frame too large or unreadable"),
780        )
781        .await;
782        return;
783    }
784
785    let response = if method == SESSION_OPEN_METHOD || method == SESSION_PAIR_METHOD {
786        err_frame("already_open", "this connection already has a session")
787    } else if method == DEVICE_CALL_METHOD {
788        match device_call(bus.as_ref(), identity, &peer, &payload).await {
789            Ok(body) => encode_response(RESPONSE_STATUS_OK, body.to_string().as_bytes()),
790            Err(frame) => frame,
791        }
792    } else {
793        err_frame("unknown_method", &method)
794    };
795    respond(&mut send, response).await;
796}
797
798async fn device_call(
799    bus: &impl HostBus,
800    identity: &OpenOk,
801    peer: &[u8; 32],
802    payload: &[u8],
803) -> Result<serde_json::Value, Vec<u8>> {
804    let call: ServiceCall = serde_json::from_slice(payload)
805        .map_err(|_| err_frame("invalid_request", "device.call/1 needs {service, payload}"))?;
806    let svc = service(&call.service).ok_or_else(|| err_frame("unknown_service", &call.service))?;
807    if !scope_allows(&identity.scopes, svc.scope) {
808        return Err(err_frame("scope_denied", svc.scope));
809    }
810    let endpoint = endpoint_hex(peer);
811    let stamped = stamp(
812        call.payload,
813        &StampIdentity {
814            device_id: &identity.device_id,
815            device_did: &identity.device_did,
816            scopes: &identity.scopes,
817            endpoint_hex: &endpoint,
818        },
819    );
820    match tokio::time::timeout(CALL_DEADLINE, bus.invoke(svc.capability, stamped)).await {
821        Err(_) => Err(err_frame(
822            "timeout",
823            "the node service did not answer in time",
824        )),
825        Ok(Ok(value)) => Ok(value),
826        Ok(Err(refusal)) => Err(err_frame("service_error", &refusal.message)),
827    }
828}