moonmls

    Pure MoonBit IETF MLS (RFC 9420) end-to-end encrypted group messaging protocol engine: TreeKEM, Secret Tree, Key Schedule, framing, and stateful Group API.

    mls
    rfc9420
    e2ee
    treekem
    hpke
    crypto
    messaging
    security
    Download zip
    Author
    Version
    0.1.1
    License
    MIT
    Last updated
    10 hours ago
    Downloads
    13

    #Ridge-Lab/moonmls

    Pure MoonBit IETF MLS (RFC 9420) End-to-End Encrypted Group Messaging Protocol Engine

    moonmls is a zero-C, multi-target (wasm-gc, wasm, js, native) MoonBit implementation of the IETF Messaging Layer Security standard (RFC 9420), delivering asynchronous group key agreement with O(log N) TreeKEM, Forward Secrecy (FS), and Post-Compromise Security (PCS) across five standard cipher suites (CS1, CS2, CS3, CS4, CS6).

    • Package: Ridge-Lab/moonmls (MIT)
    • Interactive Browser Demo: TreeKEM Studio (GitHub Pages) — 100% client-side, zero uploads
    • RFC 9420 Interoperability: 16 / 16 official IETF mlswg/mls-implementations test-vector suites passing (622 vectors verified in default CI profile, 0 failures; including passive-client-random.json 200-epoch randomized multi-member trace and messages.json 5,100 canonical wire roundtrips)
    • Toolchain: MoonBit >= 1.0.0-rc1 (verified on moonc v1.0.0-rc1+3c0520448)


    #Why moonmls?

    An ecosystem audit of all 4,201 packages indexed on mooncakes.io on 2026-12-02 confirmed zero RFC 9420 MLS protocol engines existed for MoonBit (see docs/ECOSYSTEM.md). Rather than re-implementing low-level cryptographic primitives, moonmls builds cleanly on cc06b/mooncry (Apache-2.0) and implements the entire RFC 9420 protocol stack from scratch in idiomatic MoonBit:

    • LBBT Tree Math (treemath): Left-Balanced Binary Tree indexing, direct_path, copath, common_ancestor, power-of-2 normalization (RFC 9420 Appendix C)
    • Strict TLS Wire Codec (codec): Canonical TLS Presentation Language serializer/deserializer enforcing RFC 9420 §2.1.2 minimal QUIC varints (rejects non-minimal encodings and forbidden 8-byte prefixes)
    • CipherSuite Crypto (crypto): ExpandWithLabel, DeriveSecret, DeriveTreeSecret, RefHash, SignWithLabel/VerifyWithLabel (Ed25519, Ed448, strict ASN.1 DER ECDSA P-256), RFC 9180 HPKE EncryptWithLabel/DecryptWithLabel, AEAD Seal/Open
    • Secret Tree & Hash Ratchets (secret_tree): Lazy node derivation with parent secret erasure (FS), Handshake & Application ratchets with bounded out-of-order decryption cache and replay rejection (RFC 9420 §9)
    • Key Schedule & PSK Chain (key_schedule): Epoch secret advancement, External & Resumption PSKs, Confirmed & Interim Transcript Hashes, MLS-Exporter, External HPKE key pair derivation (RFC 9420 §8)
    • Message Framing (framing): PublicMessage (with membership_tag, forbidding Application payloads) and PrivateMessage (with reuse_guard XOR, zero-padding enforcement, SenderData AEAD) (RFC 9420 §6)
    • Ratchet Tree & TreeKEM (tree): Tree hash, parent-hash validation (§7.9.2), leaf signature verification, Add/Update/Remove with right-half blank truncation, filtered_direct_path, UpdatePath creation & processing (RFC 9420 §7)
    • Stateful Group Engine (root Ridge-Lab/moonmls): Group::create, generate_key_package / verify_key_package, Group::join_from_welcome, Group::join_external (§12.4.3.2 External Commit), propose / propose_update / stage_proposal, commit / process_commit (with atomic state rollback on invalid commits), encrypt_application / decrypt_application, export_secret


    #Supported Cipher Suites & Scope Boundaries

    IDRFC 9420 CipherSuiteKEMAEADHashSignatureStatus
    0x0001MLS_128_DHKEMX25519_AES128GCM_SHA256_Ed25519X25519AES-128-GCMSHA-256Ed25519Supported & IETF verified
    0x0002MLS_128_DHKEMP256_AES128GCM_SHA256_P256P-256AES-128-GCMSHA-256ECDSA-P256Supported & IETF verified
    0x0003MLS_128_DHKEMX25519_CHACHA20POLY1305_SHA256_Ed25519X25519ChaCha20-Poly1305SHA-256Ed25519Supported & IETF verified
    0x0004MLS_256_DHKEMX448_AES256GCM_SHA512_Ed448X448AES-256-GCMSHA-512Ed448Supported & IETF verified
    0x0006MLS_256_DHKEMX448_CHACHA20POLY1305_SHA512_Ed448X448ChaCha20-Poly1305SHA-512Ed448Supported & IETF verified
    0x0005MLS_256_DHKEMP521_AES256GCM_SHA512_P521P-521AES-256-GCMSHA-512ECDSA-P521Out of scope (mooncry lacks P-521)
    0x0007MLS_256_DHKEMP384_AES256GCM_SHA384_P384P-384AES-256-GCMSHA-384ECDSA-P384Out of scope (mooncry lacks P-384)

    Additional explicit scope boundaries (see docs/RFC9420_CONFORMANCE.md):
    • Credentials: BasicCredential is fully verified; X509 chain-of-trust PKI validation is delegated to the application layer (wire encoding/decoding is supported).
    • Deterministic caller-supplied entropy: Core protocol APIs accept explicit seed/reuse-guard byte inputs so cryptographic operations remain deterministic across wasm-gc, wasm, js, and native; production callers MUST supply CSPRNG randomness.


    #Installation

    Add Ridge-Lab/moonmls to your MoonBit project:

    moon update moon add Ridge-Lab/moonmls

    Import the root package and types in your moon.pkg:

    import { "Ridge-Lab/moonmls", "Ridge-Lab/moonmls/types", }


    #Quick Start (MoonBit)

    let suite = @types.CipherSuite::MLS_128_DHKEMX25519_AES128GCM_SHA256_Ed25519

    // 1. Alice creates a new group (Epoch 0)
    let alice = @moonmls.Group::create(suite, b"team-room", b"alice", alice_seed)

    // 2. Bob publishes a signed KeyPackage
    let bob_kp = @moonmls.generate_key_package(suite, b"bob", bob_seed)

    // 3. Alice adds Bob in Epoch 1 and sends him the Welcome
    let c1 = alice.commit(
    inline_proposals=[Add(bob_kp.key_package)],
    commit_leaf_seed,
    commit_hpke_seed,
    )
    let bob = @moonmls.Group::join_from_welcome(c1.welcome.unwrap(), bob_kp)

    // 4. End-to-end encrypted messaging (PrivateMessage)
    let wire = alice.encrypt_application(b"Hello Bob over RFC 9420!")
    let dec = bob.decrypt_application(wire)
    assert_eq(dec.plaintext, b"Hello Bob over RFC 9420!")


    #Runnable Examples & Verified Outputs

    Run all three cross-backend examples directly with moon run:

    #1. Minimal 2-member E2EE (examples/basic)

    moon run --target wasm-gc examples/basic

    Exact output:
    MoonMLS basic: epoch=1, members=2, wire=179 bytes Verified epoch_authenticator=1441b383ffd8a864c4cc6f1311df32ee5255309e32f3dea8481d478e11738aaf Decrypted 37 bytes from leaf 0 gen 0

    #2. Full 5-member Multi-Epoch Lifecycle (examples/group_lifecycle)

    Demonstrates Group::create, Add + Welcome, out-of-order decryption, replay rejection, Update (PCS), External PSK, Remove, External Join (§12.4.3.2), and MLS-Exporter:

    moon run --target wasm-gc examples/group_lifecycle

    Exact output:
    MoonMLS lifecycle: CS3 epoch=4, active_members=4, exporter=24b0ff199d5c034d2149bf2b0b9fb7c7

    #3. All 5 Supported CipherSuites (examples/ciphersuites)

    moon run --target wasm-gc examples/ciphersuites

    Exact output:
    PASS CS1 (X25519/AES128GCM/SHA256/Ed25519): auth=273a7cebc996a7ec... PASS CS2 (P256/AES128GCM/SHA256/ECDSA-P256): auth=1e8a11eee04fb577... PASS CS3 (X25519/ChaCha20Poly1305/SHA256/Ed25519): auth=276cbcc7135c00ca... PASS CS4 (X448/AES256GCM/SHA512/Ed448): auth=387316e907084acd... PASS CS6 (X448/ChaCha20Poly1305/SHA512/Ed448): auth=a7f959520da006e2...


    #Node.js CLI & Browser TreeKEM Studio

    Build the JS bridge once (moon build --target js --release), then run the CLI or local Browser Studio:

    # Interactive RFC 9420 CLI demo (Add, E2EE, PCS Update, External Commit, Exporter) node scripts/moonmls.mjs demo --suite 1 # Generate a KeyPackage node scripts/moonmls.mjs keygen --identity alice --suite 3 # Inspect any RFC 9420 MLSMessage wire hex node scripts/moonmls.mjs inspect <hex> # Build and serve the zero-upload Browser TreeKEM Studio (http://127.0.0.1:4173/) npm run web:build npm run web:serve


    #IETF RFC 9420 Conformance & Verification

    Every verification check is reproducible through a single entry point (scripts/verify.py):

    # Quick profile: fmt, check --target all, unit/security tests, 3 examples, CLI, 12 fault-injection tests, web build & Studio tests python scripts/verify.py --profile quick --targets js wasm wasm-gc # Full profile: adds all 16 official IETF RFC 9420 test-vector suites (auto-fetched at pinned SHA) + benchmarks + moon package check python scripts/verify.py --profile full --targets js wasm wasm-gc --fetch-ietf

    #Official IETF Test-Vector Summary (mlswg/mls-implementations @ 66e31c5155)

    SuitePassedFailedSkipped (CS5/7)Coverage
    tree-math.json1000LBBT math for tree sizes 1..255
    deserialization.json1400Minimal QUIC varint & rejection rules
    crypto-basics.json502RefHash, ExpandWithLabel, DeriveSecret, DeriveTreeSecret, Sign/Encrypt
    secret-tree.json1506Handshake/Application ratchets & sender_data keys
    key-schedule.json502Multi-epoch Key Schedule & Exporter
    psk_secret.json55022PSK secret extraction & chaining
    transcript-hashes.json502Confirmed & Interim Transcript Hashes
    message-protection.json502PublicMessage & PrivateMessage protection/unprotection
    welcome.json502Welcome decrypt & GroupInfo verification
    tree-operations.json500Add / Update / Remove tree mutations
    tree-validation.json70028Resolution, tree hashes, parent hashes, leaf signatures
    treekem.json22 (55 full)022UpdatePath creation & processing across tree topologies
    messages.json300005,100 canonical wire struct roundtrips (all 17 types)
    passive-client-welcome.json40016End-to-end passive Welcome joins (with & without PSK)
    passive-client-handling-commit.json65026End-to-end passive Commit processing (Proposals, UpdatePath, External)
    passive-client-random.json100200 consecutive randomized multi-member epochs
    Total (16 / 16 suites)6220130100% pass rate on all supported suites


    #Documentation Index

    #License

    Licensed under the MIT License. Third-party dependency notices are documented in THIRD_PARTY.md.

    CommitResult

    Result of committing proposals and advancing the group by one epoch.

    DecryptedApplication

    pub(all) struct DecryptedApplication {
    sender_leaf : UInt
    generation : UInt
    authenticated_data : Bytes
    plaintext : Bytes
    } derive(Eq,
    Debug
    )

    Result of decrypting a PrivateMessage carrying Application data.

    DecryptedWelcome

    pub struct DecryptedWelcome {
    group_secrets :
    GroupSecrets

    group_info :
    GroupInfo

    psk_secret : Bytes
    }

    Group

    pub struct Group {
    suite :
    CipherSuite

    context :
    GroupContext

    ratchet_tree :
    RatchetTree

    priv_state :
    PrivateTreeState

    secrets :
    EpochSecrets

    secret_tree :
    SecretTree

    interim_transcript_hash : Bytes
    pending_proposals : Map[Bytes, (
    Proposal
    ,
    Sender
    )]
    pending_update_privs : Map[Bytes, Bytes]
    external_psks : Map[Bytes, Bytes]
    resumption_psks : Map[UInt64, Bytes]
    }

    Complete local state for one member of an MLS group.

    Group::commit

    fn Group::commit(self : Group, inline_proposals? : Array[
    Proposal
    ], include_staged? : Bool, leaf_secret_seed : Bytes, hpke_seed : Bytes, reuse_guard? : Bytes, encrypted? : Bool, include_ratchet_tree? : Bool, force_path? : Bool) -> CommitResult raise
    MlsError

    Commit a list of inline proposals (plus all currently staged proposals if include_staged=true), advancing the group to epoch + 1, and returning the Commit MLSMessage, optional Welcome MLSMessage (if any Adds), and signed GroupInfo.

    Group::confirmed_transcript_hash

    fn Group::confirmed_transcript_hash(self : Group) -> Bytes

    Group::create

    fn Group::create(suite :
    CipherSuite
    , group_id : Bytes, identity : Bytes, seed : Bytes, extensions? : Array[
    Extension
    ]) -> Group raise
    MlsError

    Create a new single-member MLS group at epoch 0 (RFC 9420 §11).

    Group::decrypt_application

    Decrypt and authenticate an encrypted RFC 9420 §6.3 PrivateMessage carrying Application data.

    Group::encrypt_application

    fn Group::encrypt_application(self : Group, plaintext : Bytes, authenticated_data? : Bytes, reuse_guard? : Bytes, padding_len? : Int) ->
    MLSMessage
    raise
    MlsError

    Encrypt application plaintext as an RFC 9420 §6.3 PrivateMessage.

    Group::epoch

    fn Group::epoch(self : Group) -> UInt64

    Group::epoch_authenticator

    fn Group::epoch_authenticator(self : Group) -> Bytes

    Group::export_ratchet_tree

    fn Group::export_ratchet_tree(self : Group) -> Bytes raise
    MlsError

    Group::export_secret

    fn Group::export_secret(self : Group, label : String, context : Bytes, length : Int) -> Bytes raise
    MlsError

    Export an application-specific secret via RFC 9420 §8.5 MLS-Exporter.

    Group::group_id

    fn Group::group_id(self : Group) -> Bytes

    Group::interim_transcript_hash

    fn Group::interim_transcript_hash(self : Group) -> Bytes

    Group::join_external

    fn Group::join_external(group_info :
    GroupInfo
    , identity : Bytes, seed : Bytes, leaf_secret_seed : Bytes, hpke_seed : Bytes, external_tree? : Bytes?) -> (Group,
    MLSMessage
    ) raise
    MlsError

    RFC 9420 §12.4.3.2 External Join: join a group solely from a signed GroupInfo (with external_pub and ratchet_tree), producing both the joined Group and the PublicMessage(Commit) with Sender::NewMemberCommit to broadcast to existing members.

    Group::join_from_welcome

    fn Group::join_from_welcome(welcome_msg :
    MLSMessage
    , kp_bundle : KeyPackageBundle, external_tree? : Bytes?, external_psks? : Map[Bytes, Bytes]) -> Group raise
    MlsError

    RFC 9420 §12.4.3.1 Join an existing group by processing a Welcome message.

    Group::leaf_index

    fn Group::leaf_index(self : Group) -> UInt

    Group::member_count

    fn Group::member_count(self : Group) -> Int

    Return the number of active non-blank members in the group.

    Group::members

    fn Group::members(self : Group) -> Array[(UInt, Bytes)]

    List all active (non-blank) members as (leaf_index, credential_identity).

    Group::process_commit

    Process a received Commit MLSMessage (PublicMessage or PrivateMessage) from another member, verifying proposals, UpdatePath, and confirmation_tag atomically before transitioning the group to epoch + 1.

    Group::propose

    fn Group::propose(self : Group, proposal :
    Proposal
    , reuse_guard? : Bytes, encrypted? : Bool) -> (
    MLSMessage
    , Bytes) raise
    MlsError

    Create and locally stage a Proposal message (Add, Update, Remove, PSK, or GroupContextExtensions).

    Group::propose_update

    fn Group::propose_update(self : Group, new_key_seed : Bytes, reuse_guard? : Bytes, encrypted? : Bool) -> (
    MLSMessage
    , Bytes) raise
    MlsError

    Create and locally stage a self-Update proposal with fresh leaf encryption key material.

    Group::register_external_psk

    fn Group::register_external_psk(self : Group, psk_id : Bytes, psk_bytes : Bytes) -> Unit

    Register an external pre-shared key (psk_id -> psk_bytes) for PSK proposals/Welcomes.

    Group::stage_proposal

    Receive and stage a Proposal (PublicMessage or PrivateMessage) from any group member.

    Group::tree_hash

    fn Group::tree_hash(self : Group) -> Bytes

    Group::tree_snapshot

    Inspect the current ratchet tree structure (for auditing/visualization).

    KeyPackageBundle

    pub(all) struct KeyPackageBundle {
    key_package :
    KeyPackage

    init_priv : Bytes
    encryption_priv : Bytes
    signature_priv : Bytes
    }

    A newly generated KeyPackage together with its corresponding private keys.

    KeyPackageBundle::encode_message

    Encode a KeyPackage inside an RFC 9420 MLSMessage envelope.

    decrypt_welcome

    Decrypt a Welcome message using the joiner's KeyPackage, init_priv, and a lookup callback for any referenced PreSharedKeyIDs.

    extract_external_pub_extension

    fn extract_external_pub_extension(extensions : Array[
    Extension
    ]) -> Bytes?

    Extract the external_pub extension (ExtensionType = 4) from GroupInfo extensions.

    extract_ratchet_tree_extension

    Extract an embedded ratchet_tree extension (ExtensionType = 2) if present.

    generate_key_package

    fn generate_key_package(suite :
    CipherSuite
    , identity : Bytes, seed : Bytes, not_before? : UInt64, not_after? : UInt64, extensions? : Array[
    Extension
    ]) -> KeyPackageBundle raise
    MlsError

    Generate a fresh, signed RFC 9420 §10 KeyPackage and its private key bundle. seed should be 32+ bytes of CSPRNG entropy in production (deterministic for tests).

    key_package_ref

    RFC 9420 §5.2 KeyPackageRef = RefHash("MLS 1.0 KeyPackage Reference", encode(KeyPackage)).

    proposal_ref

    RFC 9420 §5.2 ProposalRef = RefHash("MLS 1.0 Proposal Reference", encode(AuthenticatedContent)).

    verify_group_info

    Verify GroupInfo signature (using signer_pub) and confirmation_tag against the derived EpochSecrets. Returns the verified EpochSecrets.

    verify_key_package

    RFC 9420 §10.1 Validate a KeyPackage's version, ciphersuite, key distinctness, LeafNode signature, and KeyPackage signature.