rtci-host 0.2.0

The host I/O around the sans-I/O rtci WebRTC engine: sockets, timers, STUN/TURN clients, ICE-TCP, mDNS and media, behind a permission gate and a socket factory
Documentation
// Copyright 2026 Brainwires. MIT OR Apache-2.0.

//! `RTCCertificate`: DTLS key generation, fingerprints, PEM export and
//! import, and a per-realm store of certificates by id.

use std::collections::HashMap;
use std::time::Duration;
use std::time::SystemTime;
use std::time::UNIX_EPOCH;

use rtci::peer_connection::certificate::CertificateParams;
use rtci::peer_connection::certificate::RTCCertificate;

use crate::args::CertificateInfo;
use crate::args::FingerprintInfo;
use crate::args::KeygenArg;
use crate::error::Error;
use crate::error::ErrorKind;

fn op_err(e: impl std::fmt::Display) -> Error {
  Error::new(ErrorKind::Operation, e.to_string())
}

/// The `RTCCertificate`s of a realm, by id: each holds a key and an X.509
/// certificate for the DTLS handshakes of the connections given it. The
/// front end removes an entry when its `RTCCertificate` is garbage
/// collected; a connection keeps its own copy.
#[derive(Default)]
pub struct CertificateStore {
  next: u32,
  certs: HashMap<u32, RTCCertificate>,
}

impl CertificateStore {
  /// A copy of certificate `id`; an unknown id is an `InvalidAccessError`.
  pub fn get(&self, id: u32) -> Result<RTCCertificate, Error> {
    self.certs.get(&id).cloned().ok_or_else(|| {
      Error::new(ErrorKind::InvalidAccess, "Unknown RTCCertificate")
    })
  }

  pub fn remove(&mut self, id: u32) {
    self.certs.remove(&id);
  }

  /// Keeps `cert` under a new id and describes it for JavaScript.
  pub fn insert(
    &mut self,
    cert: RTCCertificate,
  ) -> Result<CertificateInfo, Error> {
    let fingerprints = certificate_fingerprints(&cert)?;
    let expires = expires_ms(&cert);
    self.next += 1;
    let id = self.next;
    self.certs.insert(id, cert);
    Ok(CertificateInfo {
      id,
      expires,
      fingerprints,
    })
  }
}

/// The certificate's fingerprints, in each algorithm the engine computes.
pub fn certificate_fingerprints(
  cert: &RTCCertificate,
) -> Result<Vec<FingerprintInfo>, Error> {
  let provider = rtci::crypto::default_provider().map_err(op_err)?;
  Ok(
    cert
      .get_fingerprints(provider.crypto())
      .map_err(op_err)?
      .into_iter()
      .map(|f| FingerprintInfo {
        algorithm: f.algorithm,
        value: f.value,
      })
      .collect(),
  )
}

/// The W3C `expires`, a DOMTimeStamp: whole milliseconds since the epoch.
pub fn expires_ms(cert: &RTCCertificate) -> f64 {
  cert
    .expires
    .duration_since(UNIX_EPOCH)
    .map(|d| d.as_millis() as f64)
    .unwrap_or(0.0)
}

/// The DTLS key: ECDSA P-256 (what browsers default to), or RSASSA-PKCS1-v1_5
/// with SHA-256 and the public exponent 65537 (WebCrypto's algorithm
/// dictionaries, as `generateCertificate` takes them). CPU-heavy for RSA:
/// call it off the engine's thread.
pub fn generate_certificate(
  alg: &KeygenArg,
  expires_at_ms: f64,
) -> Result<RTCCertificate, Error> {
  use rtci::crypto::SignatureScheme;
  let provider = rtci::crypto::default_provider().map_err(op_err)?;
  let not_supported = |m: String| Error::new(ErrorKind::NotSupported, m);
  let name = alg.name.to_ascii_uppercase();
  let (scheme, signing_key) = match name.as_str() {
    "ECDSA" => {
      if alg.named_curve.as_deref() != Some("P-256") {
        return Err(not_supported(format!(
          "ECDSA curve {:?} is not supported (P-256 is)",
          alg.named_curve.as_deref().unwrap_or("")
        )));
      }
      let key = provider
        .crypto()
        .generate_signing_key(SignatureScheme::EcdsaP256Sha256)
        .map_err(op_err)?;
      (SignatureScheme::EcdsaP256Sha256, key)
    }
    "RSASSA-PKCS1-V1_5" => {
      let hash = alg
        .hash
        .as_deref()
        .unwrap_or("SHA-256")
        .to_ascii_uppercase();
      if hash != "SHA-256" {
        return Err(not_supported(format!(
          "RSASSA-PKCS1-v1_5 with {hash} is not supported (SHA-256 is)"
        )));
      }
      let exponent = alg.public_exponent.as_deref().unwrap_or(&[1, 0, 1]);
      let trimmed: Vec<u8> =
        exponent.iter().copied().skip_while(|b| *b == 0).collect();
      if trimmed != [1, 0, 1] {
        return Err(not_supported(
          "Only the RSA public exponent 65537 is supported".to_string(),
        ));
      }
      let size = match alg.modulus_length.unwrap_or(2048) {
        2048 => aws_lc_rs::rsa::KeySize::Rsa2048,
        3072 => aws_lc_rs::rsa::KeySize::Rsa3072,
        4096 => aws_lc_rs::rsa::KeySize::Rsa4096,
        other => {
          return Err(not_supported(format!(
            "An RSA modulus of {other} bits is not supported (2048, 3072 or 4096 are)"
          )));
        }
      };
      let pair = aws_lc_rs::rsa::KeyPair::generate(size).map_err(op_err)?;
      let der = aws_lc_rs::encoding::AsDer::<
        aws_lc_rs::encoding::Pkcs8V1Der<'static>,
      >::as_der(&pair)
      .map_err(op_err)?;
      let key = provider
        .crypto()
        .import_signing_key(SignatureScheme::RsaPkcs1Sha256, der.as_ref())
        .map_err(op_err)?;
      (SignatureScheme::RsaPkcs1Sha256, key)
    }
    _ => {
      return Err(not_supported(format!(
        "'{}' is not a supported certificate algorithm",
        alg.name
      )));
    }
  };
  let params =
    CertificateParams::new(vec!["WebRTC".to_owned()]).map_err(op_err)?;
  let mut cert =
    RTCCertificate::generate_from_signing_key(params, scheme, signing_key)
      .map_err(op_err)?;
  // W3C `expires`: the certificate stops being usable for new connections
  // then (the X.509 validity is the engine's; DTLS peers check fingerprints,
  // not validity). `expires_at_ms` is a time on the JS clock (`Date.now()`
  // plus the `expires` the page asked for): the attribute, the constructor's
  // expiry check and the page all read that clock, which on Windows can lag
  // the system clock by a few milliseconds, so the instant is kept as given
  // (at most a year ahead) instead of being re-based on `SystemTime::now()`.
  let max_ms = SystemTime::now()
    .duration_since(UNIX_EPOCH)
    .map(|d| d.as_millis() as f64)
    .unwrap_or(0.0)
    + 365.0 * 24.0 * 3600.0 * 1000.0;
  let expires_at_ms = expires_at_ms.clamp(0.0, max_ms);
  cert.expires = UNIX_EPOCH + Duration::from_millis(expires_at_ms as u64);
  Ok(cert)
}

/// `Deno.webrtc.exportCertificate`: the key and certificate as PEM, with
/// the `expires` time, to keep a server's DTLS fingerprint across restarts.
pub fn certificate_to_pem(cert: &RTCCertificate) -> Result<String, Error> {
  cert.serialize_pem().map_err(op_err)
}

/// The inverse of [`certificate_to_pem`]; anything else is a `SyntaxError`.
pub fn certificate_from_pem(pem: &str) -> Result<RTCCertificate, Error> {
  let provider = rtci::crypto::default_provider().map_err(op_err)?;
  RTCCertificate::from_pem(pem, provider.crypto()).map_err(|e| {
    Error::new(
      ErrorKind::Syntax,
      format!("Not an exported RTCCertificate: {e}"),
    )
  })
}