dave

    Safe native MoonBit bindings for Discord's official libdave C API

    dave
    libdave
    discord
    e2ee
    mls
    native
    ffi
    Download zip
    Author
    Version
    0.3.1
    License
    Apache-2.0
    Last updated
    14 days ago
    Downloads
    632

    No dependencies

    #gaato/dave

    Native MoonBit bindings for Discord's official libdave, the library behind Discord's DAVE end-to-end encryption for voice and video. Use it to establish the MLS group and encrypt or decrypt media frames in your own voice implementation.

    Most bots do not need this module directly. Bots built with gaato/discord get DAVE, together with the voice gateway and RTP transport, from gaato/discord_voice.

    gaato/dave owns the unsafe FFI boundary and exposes opaque types for MLS sessions, key ratchets and media encryptors and decryptors. It is a protocol and media-crypto library, not a Discord client. Gateway and voice WebSocket opcodes, participant bookkeeping, transition timing, RTP/UDP transport and recovery policy stay in your application.

    #Install

    moon add gaato/dave

    Import gaato/dave in your package's moon.pkg. Then download the native library once, from a native build:

    env MBT_DAVE_REQUIRE_NATIVE=1 moon build --target native --release

    The build hook fetches Discord's official prebuilt libdave for the host, checks its size and SHA-256 digest, and caches it for loading at run time. Nothing is installed system-wide. The hook runs with node, so Node.js must be on PATH for native builds. Linux and macOS also need unzip. Builds without MBT_DAVE_REQUIRE_NATIVE=1 download nothing.

    HostArchitectureSupport
    Linuxx86-64, ARM64Supported
    macOSARM64Supported
    Windowsx86-64Supported
    macOSx86-64Upstream asset only. MoonBit has no Darwin x86-64 toolchain.

    Other hosts have no upstream asset. Upstream's Linux binaries need a recent glibc. On older distributions, point MBT_DAVE_NATIVE_LIB at a compatible self-built library.

    On JavaScript and linear-memory Wasm the package still type-checks, so it can stay in a multi-target dependency graph. There, available() is false and native-handle constructors raise DaveError::LibraryUnavailable.

    #Start a session

    Create an MLS session and obtain the key package that your DAVE orchestration sends to the voice server:

    ///|
    test "create a session and its key package" {
    guard @dave.available() else { return }
    let session = @dave.Session::new(
    protocol_version=1,
    group_id=42UL,
    self_user_id=100UL,
    )
    let key_package = session.key_package()
    assert_true(key_package.length() > 0)
    }

    Then:

    1. Set the external sender before processing proposals.
    2. Feed proposal, commit and Welcome messages into the session.
    3. Once an epoch is established, get each participant's KeyRatchet and install it into an Encryptor or Decryptor.
    4. Assign a supported codec to each outbound SSRC before encrypting its frames.

    The external sender cannot be replaced while pending or established group state exists. Call reset, replace it, then reinitialize. reset keeps the configured external sender, as libdave does.

    Check available() before starting an optional DAVE path, or let constructors raise DaveError::LibraryUnavailable when DAVE is required.

    #Ownership and errors

    • Session, KeyRatchet, Encryptor and Decryptor own native handles. Copying one of these values aliases the same mutable native state, so serialize access to each one.
    • Bytes returned from native code are copied into MoonBit memory. Installing a KeyRatchet copies its key state into the media object.
    • Invalid use, unavailable native support and native failures raise DaveError. A rejected commit or Welcome is a protocol outcome, returned as CommitResult::Failed or WelcomeResult::Failed, for your state machine to handle. An applied commit or Welcome carries the changes to the roster of signature keys: Upsert with a user's key, or Remove for a user whose key libdave returned empty.
    • Session::new always uses transient signing keys. Persisted keys are not exposed.

    #Verification codes

    current_group_pairwise_fingerprint_blocking returns the pairwise fingerprint for a peer in the current group, and pairwise_verification_code formats it as the code users compare:

    ///|
    fn current_group_verification_code(
    session : @dave.Session,
    peer_user_id : UInt64,
    ) -> String raise @dave.DaveError {
    let fingerprint = session.current_group_pairwise_fingerprint_blocking(
    user_id=peer_user_id,
    )
    @dave.pairwise_verification_code(fingerprint)
    }

    ///|
    test "the verification example compiles" {
    ignore(current_group_verification_code)
    }

    A code is valid for the current group only. Because signing identities are transient, discard any stored fingerprint, code or trust decision after a reconnect, a reinitialize or a new Session. The call blocks until libdave's worker answers, so do not make it on an event-loop thread.

    #Upstream and licensing

    This is an independent binding, not affiliated with or endorsed by Discord. libdave and its bundled dependencies keep their upstream licenses. The downloaded release and its digests are recorded in THIRD_PARTY.md.

    #License

    Apache-2.0

    DaveError

    pub(all) suberror DaveError {
    LibraryUnavailable(reason~ : String)
    InvalidArgument(operation~ : String, reason~ : String)
    InvalidState(operation~ : String, reason~ : String)
    MlsOperationFailed(operation~ : String, failure~ : MlsFailure)
    FingerprintFailed(user_id~ : UInt64, reason~ : String)
    EncryptFailed(reason~ : EncryptFailure)
    DecryptFailed(reason~ : DecryptFailure)
    NativeFailure(operation~ : String, reason~ : String)
    } derive(Eq,
    Debug
    )

    Errors reported by the safe DAVE wrapper.

    Protocol-level commit and Welcome rejection is returned as CommitResult::Failed or WelcomeResult::Failed, rather than raised as an error. Raised errors represent invalid wrapper use, unavailable native support, or an operation that could not produce a protocol result.

    Codec

    pub(all) enum Codec {
    Opus
    Vp8
    Vp9
    H264
    H265
    Av1
    } derive(Eq,
    Debug
    )

    A codec supported by libdave's frame processors.

    libdave's Unknown codec is deliberately omitted because it cannot safely be used for encryption.

    CommitResult

    pub(all) enum CommitResult {
    Applied(changes~ : Array[RosterChange])
    Ignored
    Failed(failure~ : MlsFailure)
    } derive(Eq,
    Debug
    )

    The protocol outcome of processing an MLS commit.

    DecryptFailure

    pub(all) enum DecryptFailure {
    DecryptionFailure
    MissingKeyRatchet
    InvalidNonce
    MissingCryptor
    Unknown(code~ : Int)
    } derive(Eq,
    Debug
    )

    Why media-frame decryption failed.

    Decryptor

    pub struct Decryptor {
    // private fields
    }

    A stateful media-frame decryptor.

    Applications normally keep one decryptor per remote participant. The native handle is released by a finalizer; copied Decryptor values alias the same mutable state and must not be used concurrently.

    Decryptor::decrypt

    fn Decryptor::decrypt(self : Decryptor, media_type~ : MediaType, encrypted_frame : Bytes) -> Bytes raise DaveError

    Decrypt one media frame and return a new MoonBit-owned byte string.

    Decryptor::new

    fn Decryptor::new() -> Decryptor raise DaveError

    Create a media-frame decryptor.

    Decryptor::transition_to_key_ratchet

    fn Decryptor::transition_to_key_ratchet(self : Decryptor, key_ratchet : KeyRatchet) -> Unit raise DaveError

    Begin libdave's transition to a copy of key_ratchet.

    libdave retains old decryption keys for its built-in transition window.

    Decryptor::transition_to_passthrough_mode

    fn Decryptor::transition_to_passthrough_mode(self : Decryptor, enabled~ : Bool) -> Unit raise DaveError

    Transition to or from unencrypted passthrough.

    EncryptFailure

    pub(all) enum EncryptFailure {
    EncryptionFailure
    MissingKeyRatchet
    MissingCryptor
    TooManyAttempts
    Unknown(code~ : Int)
    } derive(Eq,
    Debug
    )

    Why media-frame encryption failed.

    Encryptor

    pub struct Encryptor {
    // private fields
    }

    A stateful media-frame encryptor.

    Assign each SSRC to its codec before encrypting frames for that SSRC. The native handle is released by a finalizer; copied Encryptor values alias the same mutable state and must not be used concurrently.

    Encryptor::assign_ssrc_to_codec

    fn Encryptor::assign_ssrc_to_codec(self : Encryptor, ssrc~ : UInt, codec~ : Codec) -> Unit raise DaveError

    Associate an RTP SSRC with its media codec.

    Encryptor::encrypt

    fn Encryptor::encrypt(self : Encryptor, media_type~ : MediaType, ssrc~ : UInt, frame : Bytes) -> Bytes raise DaveError

    Encrypt one media frame and return a new MoonBit-owned byte string.

    SSRC/codec assignment is required while encryption is active. Native passthrough mode accepts frames without an assignment, matching libdave.

    Encryptor::has_key_ratchet

    fn Encryptor::has_key_ratchet(self : Encryptor) -> Bool

    Whether an outbound key ratchet has been installed.

    Encryptor::is_passthrough_mode

    fn Encryptor::is_passthrough_mode(self : Encryptor) -> Bool

    Whether outbound media is currently passed through unencrypted.

    Encryptor::new

    fn Encryptor::new() -> Encryptor raise DaveError

    Create a media-frame encryptor.

    Encryptor::protocol_version

    fn Encryptor::protocol_version(self : Encryptor) -> UInt16

    Return the protocol version selected by the active outbound ratchet.

    Encryptor::set_key_ratchet

    fn Encryptor::set_key_ratchet(self : Encryptor, key_ratchet : KeyRatchet) -> Unit raise DaveError

    Install a copy of key_ratchet for outbound media.

    Encryptor::set_passthrough_mode

    fn Encryptor::set_passthrough_mode(self : Encryptor, enabled~ : Bool) -> Unit raise DaveError

    Enable or disable unencrypted passthrough.

    KeyRatchet

    pub struct KeyRatchet {
    // private fields
    }

    A key ratchet derived from an established MLS session.

    Installing a ratchet into an encryptor or decryptor copies its native key state. The KeyRatchet therefore remains independently owned and may be collected after installation.

    MediaType

    pub(all) enum MediaType {
    Audio
    Video
    } derive(Eq,
    Debug
    )

    The kind of media carried by a DAVE frame.

    MlsFailure

    pub(all) struct MlsFailure {
    source : String
    reason : String
    } derive(Eq,
    Debug
    )

    Details captured from libdave's MLS failure callback.

    RosterChange

    pub(all) enum RosterChange {
    Upsert(user_id~ : UInt64, signature_key~ : Bytes)
    Remove(user_id~ : UInt64)
    } derive(Eq,
    Debug
    )

    A change to the P-256 signature-public-key roster returned by an applied MLS commit or Welcome.

    Session

    pub struct Session {
    // private fields
    }

    A stateful MLS session.

    The native handle is owned by this value and released by a finalizer. A copied Session aliases the same mutable native session, so calls on the same session must be serialized by the application.

    Session::add_recognized_user

    fn Session::add_recognized_user(self : Session, user_id~ : UInt64) -> Unit raise DaveError

    Recognize user_id as a member of the call, allowing it in the MLS group.

    libdave accepts an add proposal, a commit that applies one, or a Welcome only for recognized users. In Discord voice, recognize each user that clients_connect (op 11) announces and stop recognizing one on client_disconnect (op 13). This session's own user is always recognized. Recognized users persist across reinitialize and reset. Recognizing a user twice has no further effect.

    Session::current_group_pairwise_fingerprint_blocking

    fn Session::current_group_pairwise_fingerprint_blocking(self : Session, user_id~ : UInt64) -> Bytes raise DaveError

    Compute a pairwise fingerprint for the currently established MLS group.

    This proves only that the two signing keys in the current group produce the same comparison value. With the official prebuilt C ABI, signing identities differ between concurrent Session values and rotate on every reinitialize, so this is not persistent identity verification or DAVE identity continuity. Discard the result when the session is reinitialized or replaced. The DAVE fingerprint-format version is fixed to zero by this API, as required by the canonical protocol.

    The operation is deliberately synchronous and may block for an expensive scrypt computation. Do not call it on a latency-sensitive cooperative event loop.

    Session::key_package

    fn Session::key_package(self : Session) -> Bytes raise DaveError

    Create a fresh, single-use marshalled MLS key package.

    Session::key_ratchet

    fn Session::key_ratchet(self : Session, user_id~ : UInt64) -> KeyRatchet? raise DaveError

    Derive a media key ratchet for user_id from the established MLS epoch.

    Session::last_epoch_authenticator

    fn Session::last_epoch_authenticator(self : Session) -> Bytes? raise DaveError

    Return the authenticator of the established MLS epoch, if one exists.

    Session::new

    fn Session::new(protocol_version~ : UInt16, group_id~ : UInt64, self_user_id~ : UInt64) -> Session raise DaveError

    Create and initialize an MLS session.

    The official libdave prebuilt C ABI has persistent keys disabled, so each Session receives a new transient signing identity. Persisted native authentication-session IDs are intentionally not exposed by this v0.1 API.

    Session::process_commit

    fn Session::process_commit(self : Session, commit : Bytes) -> CommitResult raise DaveError

    Process an incoming MLS commit without collapsing its protocol outcome into an exception. An empty serialized commit is rejected before FFI.

    Session::process_proposals

    fn Session::process_proposals(self : Session, proposals : Bytes, recognized_user_ids? : ArrayView[UInt64]) -> Bytes? raise DaveError

    Process a complete libdave proposals payload.

    The nonempty payload includes its leading revoke/append byte. Processing requires pending or established MLS group state, normally created by set_external_sender after initialization. libdave validates the whole batch before queueing any of it, and refuses it when an add proposal names a user that is not recognized (see add_recognized_user).

    On success this returns one serialized commit followed by an optional serialized Welcome, or None when no proposal is left queued, as after a revoke that withdraws every queued proposal: there is nothing to commit and nothing to send.

    recognized_user_ids is deprecated and will be removed in the next minor release: each listed user is recognized with add_recognized_user before the proposals are processed, and none is removed.

    Session::process_welcome

    fn Session::process_welcome(self : Session, welcome : Bytes, recognized_user_ids? : ArrayView[UInt64]) -> WelcomeResult raise DaveError

    Process an incoming MLS Welcome without collapsing protocol rejection into an exception. An applied result carries a roster delta: an Upsert has a signature key and a Remove represents an empty native signature. libdave fails a Welcome whose group lists a user that is not recognized (see add_recognized_user). An empty serialized Welcome is rejected before FFI.

    recognized_user_ids is deprecated and will be removed in the next minor release: each listed user is recognized with add_recognized_user before the Welcome is processed, and none is removed.

    Session::protocol_version

    fn Session::protocol_version(self : Session) -> UInt16

    Return the session's current protocol version.

    Session::reinitialize

    fn Session::reinitialize(self : Session, protocol_version~ : UInt16, group_id~ : UInt64, self_user_id~ : UInt64) -> Unit raise DaveError

    Reset and initialize this session for a new group context.

    This invokes libdave's session initialization again on the same native handle. libdave retains a configured external sender and uses it to create the new pending group state, and the recognized users. The official prebuilt C ABI also generates a new transient signing identity on every reinitialization, so verification state from the previous group must not be carried forward.

    Session::remove_recognized_user

    fn Session::remove_recognized_user(self : Session, user_id~ : UInt64) -> Unit raise DaveError

    Stop recognizing user_id, so later proposals, commits, and Welcomes that add it are rejected. Removing a user that is not recognized has no effect.

    Session::reset

    fn Session::reset(self : Session) -> Unit raise DaveError

    Clear this session's MLS group state and group context.

    libdave retains a configured external sender and the recognized users, so a later reinitialize can create pending group state without setting them again.

    Session::set_external_sender

    fn Session::set_external_sender(self : Session, external_sender : Bytes) -> Unit raise DaveError

    Configure the serialized MLS external sender package.

    The sender may only be changed while there is no pending or established MLS group state. Call reset first when replacing a sender, then reinitialize to create the new pending group state.

    Session::set_protocol_version

    fn Session::set_protocol_version(self : Session, protocol_version~ : UInt16) -> Unit raise DaveError

    Set the protocol version recorded by this session. Zero selects the unencrypted protocol state; higher values must not exceed the loaded library's supported maximum.

    WelcomeResult

    pub(all) enum WelcomeResult {
    Applied(changes~ : Array[RosterChange])
    Failed(failure~ : MlsFailure)
    } derive(Eq,
    Debug
    )

    The protocol outcome of processing an MLS Welcome.

    available

    fn available() -> Bool

    Whether the bundled native libdave runtime is available to this process.

    max_supported_protocol_version

    fn max_supported_protocol_version() -> UInt16

    Return the maximum DAVE protocol version supported by the loaded libdave.

    This returns zero when the native library is unavailable. It does not identify the libdave ABI or release version.

    pairwise_verification_code

    fn pairwise_verification_code(fingerprint : Bytes) -> String raise DaveError

    Convert a pairwise fingerprint into DAVE's standard 45-digit verification code.

    The input must contain at least 45 bytes. Additional fingerprint bytes are intentionally ignored by the standard display-code algorithm. This function only formats bytes; it does not establish their session provenance or make a current-group fingerprint persistent across a session replacement or reinitialization.

    unavailable_reason

    fn unavailable_reason() -> String?

    Explain why native libdave support is unavailable, if it is unavailable.