Skip to main content

universal_exports/
browser_link.rs

1//! A browser's Noise link. The authenticated HTTP request records the peer ID on the sign-in;
2//! the encrypted link then names that sign-in and proves possession of the paired key.
3
4use std::collections::HashMap;
5use std::io;
6use std::net::{IpAddr, SocketAddr};
7use std::path::Path;
8use std::pin::Pin;
9use std::sync::atomic::{AtomicBool, Ordering};
10use std::sync::{Mutex, MutexGuard, PoisonError};
11use std::time::Duration;
12
13use axum::extract::State;
14use axum::extract::ws::{Message, WebSocket, WebSocketUpgrade};
15use cabuya::auth::{self, Identity, Method, Proof, Sealed, Trust};
16use cabuya::link::{self, Host, Options, Services};
17use cabuya::mux::{CloseReason, LinkStream, Side};
18use cabuya::peers::{NoEvents, PeerRecord, PeerStore};
19use coqui_transport_web::{Channel, Failure, Limits};
20use futures_util::{Sink, Stream, sink, stream};
21use tokio::runtime::Handle;
22
23use super::*;
24use crate::moneypenny::links::socket::SocketChannel;
25
26#[cfg(test)]
27#[path = "browser_link_tests.rs"]
28mod tests;
29
30const DIPTEL: &str = "diptel/1";
31const MONEYPENNY: &str = "moneypenny/1";
32const SIGN_IN_BYTES: usize = 36; // Canonical UUID, sent as the first sealed message.
33
34pub(crate) struct BrowserLinks {
35    proof: Proof,
36    admission: Arc<Mutex<Admission>>,
37    webtransport: bool,
38}
39
40impl Gateway {
41    /// Enables the browser link routes with a persistent Noise identity.
42    ///
43    /// # Errors
44    ///
45    /// The key cannot be read or created, or it is of another method.
46    pub fn with_browser_links(
47        mut self,
48        path: &Path,
49        webtransport: bool,
50    ) -> Result<Self, cabuya::Error> {
51        let identity = Identity::open_or_create(path, Method::Noise)?;
52        let proof = Proof::builder(identity)
53            .initiators(Trust::asked(|_, _, _| true))
54            .build()?;
55        self.browser_links = Some(Arc::new(BrowserLinks {
56            proof,
57            admission: Arc::default(),
58            webtransport,
59        }));
60        Ok(self)
61    }
62
63    /// Starts the opt-in UDP listener. Drop the returned guard to stop accepting links.
64    ///
65    /// # Errors
66    ///
67    /// WebTransport is off, TLS or the UDP listener could not start, or no Tokio runtime is active.
68    pub fn start_browser_webtransport(
69        &self,
70        address: SocketAddr,
71        tls: Arc<rustls::ServerConfig>,
72    ) -> io::Result<BrowserWebTransport> {
73        let links = self
74            .browser_links
75            .as_ref()
76            .filter(|links| links.webtransport)
77            .ok_or_else(|| io::Error::other("browser WebTransport is off"))?;
78        let runtime = Handle::try_current().map_err(io::Error::other)?;
79        let gateway = self.clone();
80        let links = Arc::clone(links);
81        let stop = Arc::new(AtomicBool::new(false));
82        let stopping = Arc::clone(&stop);
83        let (ready, waiting) = std::sync::mpsc::sync_channel(1);
84        let thread = std::thread::Builder::new()
85            .name("browser-webtransport".into())
86            .spawn(move || {
87                let mut limits = Limits::default();
88                limits.max_message = record_bytes();
89                limits.handshake = gateway.config.unex().gateway.browser_proof_wait.0;
90                let listener = coqui_transport_web::webtransport::Listener::builder(address, tls)
91                    .origins(vec![gateway.public_origin().to_owned()])
92                    .limits(limits)
93                    .build();
94                let listener = match listener {
95                    Ok(listener) => listener,
96                    Err(error) => {
97                        let _ = ready.send(Err(io::Error::other(error)));
98                        return;
99                    }
100                };
101                let _ = ready.send(Ok(listener.local_addr()));
102                while !stopping.load(Ordering::Relaxed) {
103                    let pending = match listener.next(Some(Duration::from_millis(250))) {
104                        Ok(pending) => pending,
105                        Err(Failure::Timeout) => continue,
106                        Err(_) => break,
107                    };
108                    let Some(place) = links.admit(&gateway, pending.peer_addr().ip()) else {
109                        continue;
110                    };
111                    let (gateway, links, runtime, stopping) = (
112                        gateway.clone(),
113                        Arc::clone(&links),
114                        runtime.clone(),
115                        Arc::clone(&stopping),
116                    );
117                    spawn_link(move || {
118                        if let Ok(channel) = pending.handshake() {
119                            run(&channel, gateway, &links, &runtime, &stopping, place);
120                            channel.close();
121                        }
122                    });
123                }
124            })?;
125        let address = waiting.recv().map_err(io::Error::other)??;
126        Ok(BrowserWebTransport {
127            address,
128            stop,
129            thread: Some(thread),
130        })
131    }
132}
133
134/// The browser WebTransport listener, while its gateway serves.
135#[derive(Debug)]
136pub struct BrowserWebTransport {
137    address: SocketAddr,
138    stop: Arc<AtomicBool>,
139    thread: Option<std::thread::JoinHandle<()>>,
140}
141
142impl BrowserWebTransport {
143    /// The UDP address the listener bound.
144    pub fn local_addr(&self) -> SocketAddr {
145        self.address
146    }
147}
148
149impl Drop for BrowserWebTransport {
150    fn drop(&mut self) {
151        self.stop.store(true, Ordering::Relaxed);
152        if let Some(thread) = self.thread.take() {
153            let _ = thread.join();
154        }
155    }
156}
157
158impl BrowserLinks {
159    /// A place among the links that have proved nothing yet, or `None` when the gateway holds
160    /// as many as `browser_unproven_links` allows, or `address` holds as many as
161    /// `browser_unproven_per_address` does. The link has `browser_proof_wait` from now to
162    /// prove itself.
163    fn admit(&self, gateway: &Gateway, address: IpAddr) -> Option<Unproven> {
164        let limits = &gateway.config.unex().gateway;
165        let address = crate::login_limit::network(address);
166        let mut held = held(&self.admission);
167        let at_address = held.addresses.get(&address).copied().unwrap_or(0);
168        if !limits.browser_unproven_links.allows(held.unproven + 1)
169            || !limits.browser_unproven_per_address.allows(at_address + 1)
170        {
171            return None;
172        }
173        held.unproven += 1;
174        *held.addresses.entry(address).or_default() += 1;
175        Some(Unproven {
176            admission: Arc::clone(&self.admission),
177            address,
178            deadline: Instant::now() + limits.browser_proof_wait.0,
179        })
180    }
181
182    /// The place of a link that has proved a paired key and named its sign-in, or `None` when
183    /// `browser_links` or `browser_links_per_sign_in` is used up. Proven links never share a
184    /// budget with unproven ones.
185    fn prove(&self, gateway: &Gateway, sign_in: &str) -> Option<Proven> {
186        let limits = &gateway.config.unex().gateway;
187        let mut held = held(&self.admission);
188        let of_sign_in = held.sign_ins.get(sign_in).copied().unwrap_or(0);
189        if !limits.browser_links.allows(held.proven + 1)
190            || !limits.browser_links_per_sign_in.allows(of_sign_in + 1)
191        {
192            return None;
193        }
194        held.proven += 1;
195        *held.sign_ins.entry(sign_in.to_owned()).or_default() += 1;
196        Some(Proven {
197            admission: Arc::clone(&self.admission),
198            sign_in: sign_in.to_owned(),
199        })
200    }
201}
202
203/// What the gateway holds open for browser links. One lock, so a check and its count agree.
204#[derive(Default)]
205struct Admission {
206    proven: usize,
207    unproven: usize,
208    addresses: HashMap<IpAddr, usize>,
209    sign_ins: HashMap<String, usize>,
210}
211
212fn held(admission: &Mutex<Admission>) -> MutexGuard<'_, Admission> {
213    admission.lock().unwrap_or_else(PoisonError::into_inner)
214}
215
216/// The place of a link that has not yet proved a paired key, with the one deadline that
217/// covers everything it must do before it does.
218struct Unproven {
219    admission: Arc<Mutex<Admission>>,
220    address: IpAddr,
221    deadline: Instant,
222}
223
224impl Unproven {
225    fn left(&self) -> Duration {
226        self.deadline.saturating_duration_since(Instant::now())
227    }
228}
229
230impl Drop for Unproven {
231    fn drop(&mut self) {
232        let mut held = held(&self.admission);
233        held.unproven = held.unproven.saturating_sub(1);
234        if let Some(count) = held.addresses.get_mut(&self.address) {
235            *count -= 1;
236            if *count == 0 {
237                held.addresses.remove(&self.address);
238            }
239        }
240    }
241}
242
243/// The place of a link that proved its key, held while it serves.
244struct Proven {
245    admission: Arc<Mutex<Admission>>,
246    sign_in: String,
247}
248
249impl Drop for Proven {
250    fn drop(&mut self) {
251        let mut held = held(&self.admission);
252        held.proven = held.proven.saturating_sub(1);
253        if let Some(count) = held.sign_ins.get_mut(&self.sign_in) {
254            *count -= 1;
255            if *count == 0 {
256                held.sign_ins.remove(&self.sign_in);
257            }
258        }
259    }
260}
261
262#[derive(Deserialize)]
263#[serde(deny_unknown_fields)]
264pub(crate) struct Pair {
265    peer: String,
266}
267
268#[derive(Serialize)]
269pub(crate) struct Paired {
270    sign_in: String,
271    peer: String,
272    webtransport: bool,
273    max_message: usize,
274}
275
276async fn token_record(gateway: &Gateway, token: &str) -> Result<ai6::AccessTokenRecord, ApiError> {
277    let registry = gateway.registry.clone().ok_or_else(ApiError::unavailable)?;
278    let digest = access_token_digest(token);
279    tokio::task::spawn_blocking(move || registry.find_access_token(&digest))
280        .await
281        .map_err(|_| ApiError::internal())?
282        .map_err(|_| ApiError::internal())?
283        .ok_or_else(ApiError::unauthorized)
284}
285
286pub(crate) async fn pair(
287    State(gateway): State<Gateway>,
288    headers: HeaderMap,
289    Json(pair): Json<Pair>,
290) -> Result<Json<Paired>, ApiError> {
291    require_origin(&gateway, &headers)?;
292    let links = gateway
293        .browser_links
294        .as_ref()
295        .ok_or_else(ApiError::unavailable)?;
296    let token = bearer(&headers)?;
297    let record = token_record(&gateway, token).await?;
298    let person = person_by_id(&gateway, record.person_id().to_owned()).await?;
299    let sign_in = root_id(&record).to_owned();
300    let registry = gateway.registry.clone().ok_or_else(ApiError::unavailable)?;
301    require_session_cookie(&registry, &headers, &sign_in).await?;
302    let limit = gateway
303        .config
304        .unex()
305        .gateway
306        .browser_keys_per_sign_in
307        .or_max();
308    let (id, peer) = (sign_in.clone(), pair.peer.clone());
309    let write = registry.clone();
310    let paired = tokio::task::spawn_blocking(move || write.pair_browser_key(&id, &peer, limit))
311        .await
312        .map_err(|_| ApiError::internal())?
313        .map_err(|error| match error.kind() {
314            io::ErrorKind::InvalidInput => ApiError::bad_request(),
315            _ => ApiError::internal(),
316        })?
317        .ok_or_else(ApiError::unauthorized)?;
318    let actor = crate::actor_of(&person);
319    let mut events = Vec::new();
320    for gone in &paired.evicted {
321        events.push(("browser_link.evict", gone.clone()));
322    }
323    if paired.added {
324        events.push(("browser_link.pair", pair.peer.clone()));
325    }
326    for (action, target) in events {
327        let audit = ai6::AuditRecord {
328            id: Uuid::new_v4().to_string(),
329            actor: actor.clone(),
330            action: action.to_owned(),
331            operation: String::new(),
332            resource: Some(format!("sign-in:{sign_in}")),
333            target,
334            at: unix_timestamp()?,
335        };
336        let registry = registry.clone();
337        tokio::task::spawn_blocking(move || registry.record_audit(&audit))
338            .await
339            .map_err(|_| ApiError::internal())?
340            .map_err(|_| ApiError::internal())?;
341    }
342    Ok(Json(Paired {
343        sign_in,
344        peer: links.proof.peer_id().to_string(),
345        webtransport: links.webtransport,
346        max_message: message_bytes(&gateway),
347    }))
348}
349
350/// A sign-in that holds a session cookie pairs a key only with that cookie in hand, so a
351/// bearer taken from the page cannot pair the thief's key. The cookie is HttpOnly and scoped
352/// to `/v1/auth`, which is why pairing lives there.
353async fn require_session_cookie(
354    registry: &Arc<dyn RegistryBackend>,
355    headers: &HeaderMap,
356    sign_in: &str,
357) -> Result<(), ApiError> {
358    let (root, id) = (registry.clone(), sign_in.to_owned());
359    let root = tokio::task::spawn_blocking(move || root.login_by_id(&id))
360        .await
361        .map_err(|_| ApiError::internal())?
362        .map_err(|_| ApiError::internal())?
363        .ok_or_else(ApiError::unauthorized)?;
364    if !root.is_session_cookie() {
365        return Ok(());
366    }
367    let value = session_cookie(headers).ok_or_else(ApiError::unauthorized)?;
368    let digest = session_cookie_digest(value);
369    let found = registry.clone();
370    let cookie = tokio::task::spawn_blocking(move || found.find_session_cookie(&digest))
371        .await
372        .map_err(|_| ApiError::internal())?
373        .map_err(|_| ApiError::internal())?;
374    match cookie {
375        Some(cookie) if cookie.token_id() == sign_in => Ok(()),
376        _ => Err(ApiError::unauthorized()),
377    }
378}
379
380fn root_id(record: &ai6::AccessTokenRecord) -> &str {
381    record.sign_in().unwrap_or_else(|| record.token_id())
382}
383
384/// A proven peer and its selected sign-in. The same key can be paired independently by
385/// different people; the sign-in selector never authenticates without that key.
386pub(crate) struct Binding {
387    registry: Arc<dyn RegistryBackend>,
388    sign_in: String,
389    peer: String,
390}
391
392impl Binding {
393    fn active(&self) -> io::Result<Option<ai6::AccessTokenRecord>> {
394        Ok(self
395            .registry
396            .login_by_id(&self.sign_in)?
397            .filter(|record| record.has_browser_key(&self.peer)))
398    }
399
400    async fn person(&self, gateway: &Gateway) -> Result<Person, ApiError> {
401        let (registry, id, peer) = (
402            self.registry.clone(),
403            self.sign_in.clone(),
404            self.peer.clone(),
405        );
406        let record = tokio::task::spawn_blocking(move || {
407            Binding {
408                registry,
409                sign_in: id,
410                peer,
411            }
412            .active()
413        })
414        .await
415        .map_err(|_| ApiError::internal())?
416        .map_err(|_| ApiError::internal())?
417        .ok_or_else(ApiError::unauthorized)?;
418        person_by_id(gateway, record.person_id().into()).await
419    }
420
421    pub(crate) async fn resolve(&self, gateway: &Gateway, token: &str) -> Result<Person, ApiError> {
422        let record = token_record(gateway, token).await?;
423        if root_id(&record) != self.sign_in {
424            return Err(ApiError::unauthorized());
425        }
426        self.person(gateway).await
427    }
428}
429
430impl PeerStore for Binding {
431    fn get(&self, peer: &str) -> Result<Option<PeerRecord>, cabuya::Error> {
432        let record = self
433            .active()
434            .map_err(|error| cabuya::Error::Identity(error.to_string()))?;
435        Ok((self.peer == peer && record.is_some())
436            .then(|| PeerRecord::new(peer).granting(DIPTEL).granting(MONEYPENNY)))
437    }
438
439    fn put(&self, _: &PeerRecord) -> Result<(), cabuya::Error> {
440        Err(cabuya::Error::Identity(
441            "pair browser keys through HTTP".into(),
442        ))
443    }
444
445    fn remove(&self, _: &str) -> Result<(), cabuya::Error> {
446        Err(cabuya::Error::Identity(
447            "revoke the browser's sign-in".into(),
448        ))
449    }
450}
451
452fn record_bytes() -> usize {
453    Method::Noise
454        .record_length(mux_record_bytes())
455        .max(auth::MAX_PROOF_MESSAGE)
456}
457
458/// The most one Attach message may carry on a link.
459fn attach_bytes(gateway: &Gateway) -> usize {
460    gateway.config.unex().attach.socket_bytes.or_max()
461}
462
463/// The most one Run message may carry on a link.
464fn run_bytes(gateway: &Gateway) -> usize {
465    gateway.config.limits.max_frame_bytes
466}
467
468/// The link's message size: the largest any protocol on it needs, which the mux holds for
469/// every stream. Each protocol's own, smaller, limit is enforced when its stream opens.
470fn message_bytes(gateway: &Gateway) -> usize {
471    // Credit in the shared stream protocol is expressed in u32 bytes.
472    [
473        attach_bytes(gateway),
474        run_bytes(gateway),
475        moneypenny::socket_limit(gateway),
476    ]
477    .into_iter()
478    .max()
479    .unwrap_or_default()
480    .min(u32::MAX as usize)
481}
482
483fn mux_record_bytes() -> usize {
484    let limits = cabuya::mux::Limits::default();
485    // One encoded mux record (including Open metadata), or one proof record.
486    limits.max_frame + limits.max_metadata
487}
488
489pub(crate) async fn socket(
490    State(gateway): State<Gateway>,
491    connection: Option<Extension<ConnectInfo<SocketAddr>>>,
492    headers: HeaderMap,
493    upgrade: WebSocketUpgrade,
494) -> Result<Response, ApiError> {
495    require_origin(&gateway, &headers)?;
496    let links = gateway
497        .browser_links
498        .clone()
499        .ok_or_else(ApiError::unavailable)?;
500    let address = connection.map(|Extension(ConnectInfo(address))| address);
501    let source = gateway.resume_guard().source(&headers, address);
502    let place = links
503        .admit(&gateway, source)
504        .ok_or_else(ApiError::unavailable)?;
505    let bound = record_bytes();
506    let buffer = gateway.config.unex().gateway.socket_buffer_bytes.or_max();
507    Ok(upgrade
508        .max_message_size(bound)
509        .max_frame_size(bound)
510        .max_write_buffer_size(bound.saturating_mul(2).max(buffer))
511        .on_upgrade(move |socket| async move {
512            let limits = gateway.config.unex();
513            let channel = SocketChannel::new(
514                socket,
515                bound.max(limits.gateway.socket_buffer_bytes.or_max()),
516            );
517            if !channel.first_message(place.left()).await {
518                channel.close();
519                return;
520            }
521            let runtime = Handle::current();
522            spawn_link(move || {
523                run(
524                    &channel,
525                    gateway,
526                    &links,
527                    &runtime,
528                    &AtomicBool::new(false),
529                    place,
530                );
531                channel.close();
532            });
533        }))
534}
535
536fn spawn_link(body: impl FnOnce() + Send + 'static) {
537    if std::thread::Builder::new()
538        .name("browser-link".into())
539        .spawn(body)
540        .is_err()
541    {
542        eprintln!("universal-exports: a browser link could not start its thread");
543    }
544}
545
546fn run<C: Channel>(
547    channel: &C,
548    gateway: Gateway,
549    links: &BrowserLinks,
550    runtime: &Handle,
551    stop: &AtomicBool,
552    unproven: Unproven,
553) {
554    let Some(registry) = gateway.registry.clone() else {
555        return;
556    };
557    let limits = gateway.config.unex();
558    // One deadline covers the proof, the sign-in selector and the check of the paired key.
559    let Ok(proven) = auth::prove(&links.proof, channel, unproven.left(), mux_record_bytes()) else {
560        return;
561    };
562    let peer = proven.peer.to_string();
563    let sealed = Sealed::new(channel, proven.session);
564    let Ok(Some(sign_in)) = sealed.receive(Some(unproven.left())) else {
565        return;
566    };
567    if sign_in.len() != SIGN_IN_BYTES {
568        return;
569    }
570    let Ok(sign_in) = String::from_utf8(sign_in) else {
571        return;
572    };
573    let binding = Arc::new(Binding {
574        registry,
575        sign_in,
576        peer,
577    });
578    let paired = runtime
579        .block_on(async { tokio::time::timeout(unproven.left(), binding.person(&gateway)).await });
580    if !matches!(paired, Ok(Ok(_))) {
581        return;
582    }
583    let Some(_place) = links.prove(&gateway, &binding.sign_in) else {
584        return;
585    };
586    drop(unproven);
587    let recheck = limits.attach.recheck_every.0;
588    let sealed = sealed
589        .with_check(|| {
590            !stop.load(Ordering::Relaxed) && binding.active().is_ok_and(|record| record.is_some())
591        })
592        .with_check_every(recheck);
593    if sealed.send(b"ok").is_err() {
594        return;
595    }
596    let mut options = Options::default();
597    let streams = limits.gateway.browser_streams.or_max();
598    options.limits.max_streams = streams;
599    options.limits.max_per_protocol = streams;
600    options.limits.max_message = message_bytes(&gateway);
601    options.recheck = recheck;
602    let (terminal_gateway, terminal_binding, terminal_runtime) =
603        (gateway.clone(), Arc::clone(&binding), runtime.clone());
604    let (chat_binding, chat_runtime) = (Arc::clone(&binding), runtime.clone());
605    let services = Services::default()
606        .with(
607            DIPTEL,
608            Box::new(move |stream, open| {
609                if open.metadata == b"attach" {
610                    let max = attach_bytes(&terminal_gateway);
611                    with_stream(stream, max, true, |socket| {
612                        terminal_runtime.block_on(crate::run_attach::attached(
613                            socket,
614                            terminal_gateway.clone(),
615                            Some(&terminal_binding),
616                        ))
617                    });
618                    return;
619                }
620                let Ok(request) = serde_json::from_slice(&open.metadata) else {
621                    stream.close_with(CloseReason::Refused, "invalid Run attachment");
622                    return;
623                };
624                let result = terminal_runtime.block_on(open_run(
625                    &terminal_gateway,
626                    &terminal_binding,
627                    request,
628                ));
629                let Ok(attachment) = result else {
630                    stream.close_with(CloseReason::Refused, "Run attachment refused");
631                    return;
632                };
633                let run = attachment.run_id.clone();
634                with_stream(stream, run_bytes(&terminal_gateway), false, |socket| {
635                    terminal_runtime.block_on(serve_socket(
636                        socket,
637                        terminal_gateway.clone(),
638                        attachment,
639                        run,
640                    ))
641                });
642            }),
643        )
644        .with(
645            MONEYPENNY,
646            Box::new(move |stream, _| {
647                if gateway.assistant().is_none() {
648                    stream.close_with(CloseReason::Refused, "Moneypenny is unavailable");
649                    return;
650                }
651                with_stream(stream, moneypenny::socket_limit(&gateway), true, |socket| {
652                    chat_runtime.block_on(moneypenny::converse(
653                        socket,
654                        gateway.clone(),
655                        Some(&chat_binding),
656                    ))
657                });
658            }),
659        );
660    let host = Host {
661        store: binding.as_ref(),
662        services: &services,
663        events: &NoEvents,
664    };
665    link::serve(&sealed, Side::Answered, options, None, &binding.peer, &host);
666    sealed.close();
667}
668
669#[derive(Deserialize)]
670#[serde(deny_unknown_fields)]
671struct RunRequest {
672    run_id: String,
673    after: u64,
674    write: bool,
675}
676
677async fn open_run(
678    gateway: &Gateway,
679    binding: &Binding,
680    request: RunRequest,
681) -> Result<Attachment, ApiError> {
682    let person = binding.person(gateway).await?;
683    let run_id = RunId::new(request.run_id).map_err(|_| ApiError::bad_request())?;
684    let (operation_id, mission_id) = gateway
685        .inner
686        .lock()
687        .await
688        .runs
689        .get(&run_id)
690        .map(|run| (run.operation_id.clone(), run.mission_id.clone()))
691        .ok_or_else(ApiError::not_found)?;
692    let grant = AttachGrant {
693        operation_id,
694        mission_id,
695        run_id,
696        mode: if request.write {
697            AttachMode::Write
698        } else {
699            AttachMode::Read
700        },
701    };
702    if request.write {
703        let read = AttachGrant {
704            mode: AttachMode::Read,
705            ..grant.clone()
706        };
707        authorize_attachment(gateway, person.clone(), &read).await?;
708    }
709    authorize_attachment(gateway, person, &grant).await?;
710    let timed = TimedGrant {
711        grant,
712        expires: Instant::now() + gateway.config.attach_token_ttl(),
713    };
714    let mut inner = gateway.inner.lock().await;
715    prune_expired(&mut inner);
716    Ok(gateway.activate_attachment(&mut inner, timed, request.after)?)
717}
718
719pub(crate) type AppSender = Pin<Box<dyn Sink<Message, Error = ()> + Send>>;
720
721/// The existing application protocols share their handler between both carriers.
722pub(crate) struct AppSocket {
723    pub(crate) sender: AppSender,
724    pub(crate) receiver: Pin<Box<dyn Stream<Item = Result<Message, ()>> + Send>>,
725}
726
727impl AppSocket {
728    pub(crate) fn websocket(socket: WebSocket) -> Self {
729        let (sender, receiver) = socket.split();
730        Self {
731            sender: Box::pin(sender.sink_map_err(|_| ())),
732            receiver: Box::pin(receiver.map(|message| message.map_err(|_| ()))),
733        }
734    }
735}
736
737fn with_stream(stream: &dyn LinkStream, max: usize, text: bool, body: impl FnOnce(AppSocket)) {
738    std::thread::scope(|scope| {
739        // One message prefetched. A slow application leaves the rest in the mux's credit window.
740        let (tx, rx) = tokio::sync::mpsc::channel(1);
741        scope.spawn(move || {
742            while let Ok(Some(bytes)) = stream.receive(None) {
743                let message = if bytes.len() > max {
744                    // The link carries the largest message any protocol needs; this one's own
745                    // limit is what its stream may send.
746                    stream.close_with(CloseReason::Broken, "message exceeds the protocol's limit");
747                    Err(())
748                } else if text {
749                    String::from_utf8(bytes)
750                        .map(|value| Message::Text(value.into()))
751                        .map_err(|_| ())
752                } else {
753                    Ok(Message::Binary(bytes.into()))
754                };
755                let invalid = message.is_err();
756                if tx.blocking_send(message).is_err() || invalid {
757                    break;
758                }
759            }
760        });
761        // Cabuya and the transport may block, including on WebTransport's private runtime.
762        // Wait for each write on the application side without entering the transport there.
763        type Write = (Message, tokio::sync::oneshot::Sender<Result<(), ()>>);
764        let (writes, mut writer) = tokio::sync::mpsc::channel::<Write>(1);
765        scope.spawn(move || {
766            while let Some((message, done)) = writer.blocking_recv() {
767                let result = match message {
768                    Message::Binary(bytes) => stream.send(&bytes).map_err(|_| ()),
769                    Message::Text(text) => stream.send(text.as_bytes()).map_err(|_| ()),
770                    Message::Close(_) => {
771                        stream.close();
772                        Ok(())
773                    }
774                    Message::Ping(_) | Message::Pong(_) => Err(()),
775                };
776                let _ = done.send(result);
777                if result.is_err() {
778                    break;
779                }
780            }
781        });
782        let sender = sink::unfold(writes, |writes, message| async move {
783            let (done, wrote) = tokio::sync::oneshot::channel();
784            writes.send((message, done)).await.map_err(|_| ())?;
785            wrote.await.map_err(|_| ())??;
786            Ok(writes)
787        });
788        let receiver = stream::unfold(rx, |mut rx| async {
789            rx.recv().await.map(|message| (message, rx))
790        });
791        body(AppSocket {
792            sender: Box::pin(sender),
793            receiver: Box::pin(receiver),
794        });
795        stream.close();
796    });
797}