All notable changes to this project will be documented in this file.
The format is based on Keep a Changelog, and this project adheres to Semantic Versioning.
- Group signature verification is now mandatory. Both
ValidateGroupMessageandProcessDistributionMessagepreviously skipped verification when a message carried no signature, treating it as valid. BecauseSenderIdentityKeyis public and the transport is untrusted, an attacker able to write to the transport could send an unsigned sender-key distribution bearing a member's identity key and an attacker-chosen chain key, then impersonate that member. No sending path in the library ever produced an unsigned message, so this rejects only forgeries. (One receive path,LibEmiddleClient.Helpers.cs'sRouteGroupMessageAsync, does construct anEncryptedGroupMessagewithout aSignature— but it also omitsRotationEpoch, taking the type's default of0against an always-non-zero real value, which already broke the AES associated data and made it unable to decrypt anything before this release. Nothing in the library sends that message type and no test exercises it; it is a pre-existing, non-functional route, not a consequence of this change.) - Null ciphertext no longer crashes the process (denial of service). A malformed group
message with a null
Ciphertext, a valid member'sSenderIdentityKey, and a well-formed nonce reached the AES decryption path uncaught:Ciphertext?.Length == 0is false whenCiphertextis null, so the guard intended to reject empty ciphertext accepted null, and the resultingArgumentNullExceptionpropagated out ofDecryptMessageAsyncbecause the wrappingtryhad only afinally, nocatch. This was remotely triggerable by any party able to submit a group message. Null ciphertext is now rejected explicitly before it reaches the signing/decryption path. - Wrong-length signature no longer crashes the process (denial of service). A malformed
group message could carry a
Signaturethat was non-null and non-empty but not exactly 64 bytes.ValidateGroupMessageandProcessDistributionMessagerejected only a null or zero-length signature, so a wrong-length one reachedSodium.SignVerifyDetached, which throwsArgumentExceptionrather than returningfalsefor any length other thanConstants.ED25519_SIGNATURE_SIZE. That exception propagated out ofDecryptMessageAsync/ProcessDistributionMessageuncaught, crashing the receiving session. Both guards now reject a wrong-length signature the same way they reject an absent one. - Replay-set eviction is now insertion-ordered. Eviction used
ConcurrentDictionary.Keys.Take(), which guarantees no ordering, so a recently seen message ID could be evicted while older ones survived.
-
Group signature format changed. Fields in the signed byte string are now length-prefixed with a 4-byte big-endian length,
SenderIdentityKeyis always included, and a one-byte domain-separation tag (0x01for messages,0x02for sender-key distributions) is prepended to the signed payload. Previously fields were concatenated without prefixes, so distinct field decompositions could produce identical signing input and a signature did not uniquely commit to the message it covered; and without the domain tag, a byte string valid for one payload type could in principle parse as the other, since both signing contexts share a single Ed25519 identity key. Not exploitable in the shipped code today, but closed now because the wire format is about to be frozen by golden vectors.2.8.0 peers cannot verify group messages or sender-key distributions from 2.7.x peers, or vice versa. All members of a group must upgrade together. One-to-one chat sessions are unaffected.
This failure is silent. Group messages carry no protocol-version field, and
ProtocolVersion.IsCompatibletreats every 2.x peer as compatible, so a mixed-version group does not detect the mismatch. Cross-version messages are rejected one at a time andDecryptMessageAsyncreturnsnull— no exception reaches the caller. The rejections are recorded viaLoggingManager.LogSecurityEvent(message: "signature verification failed"), so enable security-event logging before upgrading a group incrementally, or the symptom is simply that some members stop receiving messages with no error surfaced.Note on version numbering.
VERSIONING.mdreserves MAJOR for "breaking changes to the public API or protocol", so by that rule this change belongs in 3.0.0. It ships as a minor deliberately: the public API is unchanged, and the backward-compatible security fixes above were judged too important to hold behind the v3.0 milestone. Do not infer from the version number that 2.7.x and 2.8.0 group members interoperate — they do not.
Security and protocol-correctness release. Fixes two key-handling defects that could zero or
corrupt live private keys, three Double Ratchet deviations from the Signal specification, and a
password-KDF weakness. All 546 unit tests pass on net8.0 and net10.0.
- Double Ratchet
PNheader field:EncryptedMessage.PreviousChainLengthandDoubleRatchetSession.PreviousSendChainLengthimplement the Signal header's previous-chain-length field, which is required to recover message keys left unclaimed in a receiving chain when a DH ratchet step replaces it. Absent on messages from older versions, where it defaults to0. - Explicit key-format conversion:
KeyConversion.ConvertPublicKeyToX25519(byte[], bool inputIsEd25519)converts a public key using a caller-declared format instead of guessing. Prefer it over the format-sniffingConvertEd25519PublicKeyToX25519(byte[]).
- Ed25519/X25519 key type confusion (critical):
KeyConversion.ConvertEd25519PublicKeyToX25519()identified a key's format by trying Ed25519 validation first. Ed25519 and X25519 public keys are both 32 opaque bytes, and roughly 12.4% of X25519 public keys (measured 2 486 / 20 000) also decode as valid Ed25519 points, so that fraction of already-X25519 keys was silently converted into a different key.DeviceManager.ProcessSyncMessage()now matches a sender hint against the stored key verbatim before attempting any conversion, making device lookup deterministic. This was the cause of intermittentMultiDeviceSynchronization_ShouldRecoverFromMessageLossfailures. - Private key destroyed by its own callers (critical):
CryptoProvider.ConvertEd25519PrivateKeyToX25519()returned the caller's array unchanged when given a 32-byte key. All four call sites clear the returned buffer in afinallyblock, so the call zeroed the live device/identity private key. It now returns a copy.MailboxManagerlikewise no longer aliases_identityKeyPair.PrivateKey. - Unilateral ratchet rotation broke sessions:
KeyRotationStrategy.Standardrotated the sender's DH ratchet key every 20 messages regardless of whether the peer had received it. A DH ratchet step is only valid as a response to a new peer ratchet key; when both parties rotated before receiving the other's key, their DH inputs diverged and the session became permanently unrecoverable. Rotation is now driven solely byDecrypt()on receipt of a newSenderDHKey. - Out-of-order messages lost across ratchet steps:
SkipReceiverMessageKeysAsync()was a no-op. It is replaced bySkipReceiverMessageKeys(), which uses the newPNfield to derive and retain the unclaimed keys of the outgoing chain before it is discarded. - Sent message keys retained (forward secrecy):
Encrypt()stored up to 100 used message keys inDoubleRatchetSession.SentMessages, which is serialized to disk. Anyone obtaining a persisted session could decrypt previously sent traffic. Message keys are no longer retained after use. - Fixed application-wide Argon2id salt:
StoreKeyAsync()/RetrieveKeyAsync()derived their encryption key with a hardcoded salt, so every user sharing a password shared an encryption key and a single precomputation table applied to all installations. Each stored key now carries a fresh random 16-byte salt. Breaking: the stored blob layout changed fromnonce‖ciphertexttosalt‖nonce‖ciphertext; password-protected keys written by earlier versions cannot be read. - X25519 small-order point blocklist was inert: one of the three entries in
Sodium.SMALL_ORDER_POINTSwas a hex string passed toConvert.FromBase64String(), decoding to 48 bytes and therefore never matching a 32-byte key. Replaced with the full 12-entry libsodium blacklist, hex-decoded, including the non-canonical high-bit-set encodings. - Session clone shared key material:
DeepCloneSession()copied every byte array exceptRootKeyand the ratchet key pair, which were shared by reference — so clearing the clone destroyed the caller's session state. All arrays are now copied. - Superseded keys left in memory: retired root keys, chain keys, ratchet private keys, evicted
skipped-message keys, and decrypted plaintext buffers are now zeroed via
SecureMemory.SecureClear()on both success and failure paths. - Skipped-key eviction order: the skipped-message-key cache evicted via
Dictionary.Keys.Take(), whose enumeration order is unspecified and unrelated to age. Eviction is now ordered by message number, and every evicted key is zeroed. - Skipped-key consumption on failure: a skipped message key was removed from the cache before decryption was attempted, discarding it if decryption failed. It is now consumed only on success.
Nonce.GenerateNonce(ReadOnlySpan<byte>, uint)always threw: the method allocated aConstants.NONCE_SIZE(12-byte) buffer and then sliced[..16], guaranteeingArgumentOutOfRangeException. The salt buffer is now sized independently of the nonce.- Redundant key copies in
AES:Decrypt()calledkey.ToArray()twice — once purely as a null check on a freshly allocated array, which can never be null — leaving both copies of the key on the heap unzeroed. BothEncrypt()andDecrypt()now use a single copy, cleared in afinally.
- Multi-Framework Targeting: Library now targets both
net8.0andnet10.0(both LTS). NuGet package ships alib/net8.0/andlib/net10.0/asset, giving consumers first-class builds on either runtime. - Centralized Package Management: All NuGet dependency versions centralised in
Directory.Packages.props; no inlineVersion=attributes in project files. - NuGet Package Source Mapping:
NuGet.configrestricts all package resolution tonuget.org, preventing dependency-confusion attacks. - Package Validation:
EnablePackageValidation=trueenforces identical public API surface across both TFMs on everydotnet pack. - CI TFM Matrix: GitHub Actions now runs a
tfm: [net8.0, net10.0]matrix axis so each framework is independently built and tested on every push.
- MSTest upgraded: Test project bumped from 2.2.10 to 3.11.1.
- Microsoft.Extensions.* upgraded:
DependencyInjection.AbstractionsandLogging.Abstractionsupgraded from 9.0.4 to 10.0.0, picking up nativenet10.0TFMs. - Microsoft.CodeAnalysis.NetAnalyzers upgraded: 8.0.0 → 10.0.100 (SDK RTM build).
- CA2264: Removed five dead
ArgumentNullException.ThrowIfNull()calls onKeyPair readonly structparameters (DeviceLinkingService,ProtocolAdapter,DoubleRatchetProtocol,SessionPersistenceManager,X3DHProtocol).ThrowIfNullon a non-nullable value type is a no-op; struct fields are already validated in the constructor. - Microsoft.TestPlatform removed from library project: The test-runner package was incorrectly referenced as a production dependency of
LibEmiddle.csproj; it has been removed.
- Bundle Caching:
SessionPersistenceManagernow includesSaveKeyBundleAsync()andLoadKeyBundleByIdentityKeyAsync()for caching recipient X3DH key bundles to disk, enabling session creation from a bare identity key after the first exchange - Password KDF Overload: New
CryptoProvider.DeriveKeyFromPassword(string password, byte[] salt)overload accepting a caller-supplied random salt for non-deterministic key derivation - Shared Key Conversion Helper: New
LibEmiddle.Core.KeyConversion.ConvertEd25519PublicKeyToX25519()consolidating duplicate Ed25519→X25519 conversion logic previously spread acrossDeviceManagerandDeviceLinkingService - Unit Tests: Added 60+ new unit tests covering
MessageSigning,AESdetached encryption,Noncethread-safety,EnhancedFileStorageProvider,PostQuantumCrypto, stub infrastructure visibility, andSessionManagerbundle/group session paths - Group Replay Protection:
GroupSessionnow detects and rejects duplicate messages using a per-sender_seenMessageIdsset (capped at 1 000 entries) checked before decryption; replay attempts returnnullwithout exposing ciphertext errors - Group Member-Removal Key Rotation:
GroupSession.RemoveMemberAsync()automatically rotates the chain key viaRotateKeyInternalAsync()after each successful removal, ensuring forward secrecy for the remaining group; attempting to remove a non-member is a no-op and does not rotate the key - Chat Session Replay Protection:
ChatSessiontracks processed message IDs in a 500-entry FIFO ring buffer (_processedMessageIds); duplicate messages returnnullby default or throwInvalidOperationExceptionwhenthrowOnReplay: trueis passed toDecryptAsync - Device List Persistence: New
DeviceStorageclass persists the linked-device list to an AES-GCM–encrypted file (fresh key and nonce per write, atomic temp-then-rename) so devices survive process restarts;DeviceManageraccepts an optionalstoragePathand lazily loads the list on first access via double-checked locking LibEmiddleException: New domain exception type (LibEmiddle.Domain.Exceptions.LibEmiddleException) inheriting fromException, carrying a typedErrorCodeproperty (LibEmiddleErrorCodeenum with 12 values:Unknown,InvalidBundle,ReplayDetected,DecryptionFailed,TransportError,KeyNotFound,SessionNotFound,DeviceNotFound,OPKExhausted,InvalidKey,InvalidMessage,PermissionDenied)- Mailbox Listener Auto-Start:
LibEmiddleClient.StartListeningAsync()now automatically calls_mailboxManager.Start()so incoming-message polling begins without a separate call - Sender Identity Routing:
EncryptedMessagenow carries aSenderIdentityKeyfield;ProcessChatMessageAsyncuses it for O(1) session lookup by sender key rather than iterating all sessions - OPK Consumption Tracking:
OPKManager.TryConsume()marks one-time prekeys as consumed and triggers automatic replenishment when the available count falls below the configured threshold IAsyncDisposableonLibEmiddleClient:LibEmiddleClientnow implementsIAsyncDisposablein addition toIDisposable, using the canonicalDisposeAsync → Dispose(true) → GC.SuppressFinalizepattern for safeawait usingcleanup
- Password Key Derivation: Migrated from HKDF with a fixed static salt to Argon2id (via libsodium's
crypto_pwhash) for memory-hard password-based key derivation (64 MB, 2 passes). The deterministic overload uses a fixed application-specific salt; the new overload accepts a random salt - CreateSessionAsync Bundle Handling: Now accepts a serialized
X3DHPublicBundleas UTF-8 JSON bytes and automatically caches the bundle viaSaveKeyBundleAsync()for future bare-key lookups - GetOrCreateRecipientBundleAsync: Replaced stub implementation (threw
InvalidOperationException) with a proper lookup using the newLoadKeyBundleByIdentityKeyAsync(). ThrowsArgumentExceptionwith a descriptive message if no cached bundle is found - Batch Serialization: Replaced reflection-based
MakeGenericMethodinBatchAsyncwith the BCL'sJsonSerializer.Serialize(object?, Type, JsonSerializerOptions?)overload, eliminating runtime reflection - Disposal Guards: Changed all
bool _disposedfields tovolatile bool _disposedacross allIDisposableclasses for correct thread-safe disposal checks - Timer Callback:
EnhancedFileStorageProvider.CleanupExpiredItemsrefactored toasync void+ innerDoCleanupExpiredItemsAsync()pattern, eliminating the.Wait()call that could deadlock on synchronization contexts SecureWebSocketClientExceptions: Transport-layer failures now throwLibEmiddleExceptionwithLibEmiddleErrorCode.TransportError(wrapping the original exception asInnerException) instead of genericException, giving callers structured error handling
- AES-GCM Detached Decryption: Corrected the P/Invoke signature for
crypto_aead_aes256gcm_decrypt_detached_afternminSodium.cs— removed the erroneousout ulong mlen_psecond parameter that does not exist in this libsodium entry point, which was causing all AES-GCM detached decryption to fail - MessageSigning Verification: Fixed reversed argument order in
Sodium.SignVerifyDetached()call insideMessageSigning.VerifyObject<T>()— signature and message bytes were swapped, causing all signature verification to fail - Session File Integrity:
EncryptAndSaveSessionAsyncnow checks the return value ofStoreKeyAsyncand removes the orphaned session file if the encryption key cannot be persisted
- Argon2id Password Hardening: The Argon2id KDF (64 MB memory, 2 iterations) is orders of magnitude more resistant to GPU/ASIC brute-force attacks than the previous HKDF-with-fixed-salt approach
- Group Replay Attack Prevention: Each
GroupSessionmaintains per-sender message ID sets; replayed or duplicated ciphertexts are silently dropped before decryption is attempted - Post-Removal Forward Secrecy: Removing a group member immediately generates a new cryptographically independent chain key; the removed member's previously held key material cannot decrypt any subsequent message
- Chat Replay Attack Prevention:
ChatSessionrejects message-ID duplicates within a 500-message sliding window, preventing replay of captured ciphertexts - Encrypted Device Persistence: Linked-device lists are stored with AES-GCM authenticated encryption; any tampered or corrupted file is rejected at load time
- Comprehensive Mailbox Transport Documentation: New complete guide explaining the mailbox transport system architecture, usage patterns, and integration (Documentation/Mailbox-Transport-Guide.md)
- Detailed Message Flow Diagrams: Mermaid sequence diagrams showing complete message sending and receiving flows through all layers (Documentation/Message-Flow-Sequence.md)
- Enhanced XML Documentation: Improved code documentation for transport implementations with implementation guidance and usage examples
- LICENSE CHANGE: Changed from MIT License to GNU Affero General Public License v3.0 (AGPL-3.0) - Network use requires source disclosure
- Refactored Transport Polling Logic: Extracted duplicate polling code from HttpMailboxTransport and InMemoryMailboxTransport into BaseMailboxTransport helper method, reducing code duplication by ~120 lines
- Clarified WebRTC Status: Updated README and CHANGELOG to clearly indicate WebRTC is under development (stub only) and planned for v3.0, not production-ready in v2.5
- Improved README: Added dedicated "Mailbox Transport System" section with practical code examples and architecture overview
- Added complete mailbox transport system guide with architecture overview, usage examples, best practices, and troubleshooting
- Added Mermaid sequence diagrams for complete message flow visualization
- Enhanced transport implementation XML documentation with guidance for custom transport development
- Clarified WebRTC transport status across all documentation
- Added "Future Roadmap" section to README with planned features
- Eliminated duplicate polling logic between transport implementations (DRY principle)
- Improved code maintainability through shared helper methods
- Feature Flags System: Gradual rollout and configuration of new capabilities
- Message Batching: Efficient bulk messaging with configurable compression levels
- Post-Quantum Cryptography Preparation: Interface definitions and hybrid mode support for quantum-resistant algorithms (Kyber1024, Dilithium)
- Enterprise Monitoring & Diagnostics: Built-in health monitoring, metrics collection, and diagnostic capabilities
- Connection Pooling: Optimized connection management with configurable pool sizes and load balancing
- Advanced Key Rotation: Sophisticated rotation policies with time-based, usage-based, and risk-based triggers
- Session Backup Management: Automated backup and recovery capabilities for session data
- Resilience Manager: Automatic failover, retry policies, and connection restoration
- Async Message Streams: IAsyncEnumerable support for reactive programming patterns
- Advanced Group Management: Granular permissions system with fine-grained member control
- Compression Support: Multiple compression levels (None, Fast, Balanced, Maximum) for message batching
- Network Quality Monitoring: Real-time network quality assessment for WebRTC connections
- Group Statistics: Comprehensive analytics and statistics for group sessions
- Group Invitations: Enhanced invitation system with expiration and validation
- Message Priority System: Priority-based message handling and delivery
- Enhanced Security Policies: Expanded security policy options with quantum-readiness preparation
- Enhanced
LibEmiddleClientOptionswith new configuration sections for advanced features - Improved
TransportTypeenum to include WebRTC support - Extended
MemberRoleandGroupMemberwith advanced permission capabilities - Updated session management to support backup and recovery operations
- Enhanced error handling and logging throughout the system
- Improved performance optimizations for high-throughput scenarios
- Improved memory management in long-running sessions
- Enhanced thread safety in multi-device scenarios
- Better handling of network connectivity issues
- Optimized key rotation timing and coordination
- Improved group synchronization reliability
- Hybrid Cryptography Support: Preparation for classical + post-quantum cryptographic combinations
- Enhanced Key Rotation: More sophisticated rotation strategies with configurable policies
- Improved Forward Secrecy: Better key isolation and cleanup procedures
- Quantum-Resistant Preparation: Infrastructure for future post-quantum algorithm integration
- Advanced Authentication: Enhanced device and session authentication mechanisms
- Security Monitoring: Real-time security event monitoring and alerting capabilities
- Connection Pooling: Significant performance improvements for high-throughput scenarios
- Message Batching: Reduced network overhead through intelligent message batching and compression
- Optimized Memory Usage: Better memory management and reduced allocations
- Parallel Processing: Enhanced parallel processing capabilities for concurrent operations
- Efficient Serialization: Improved serialization performance for large messages and batches
- Added comprehensive sequence diagrams for all major operations
- Enhanced technical documentation with detailed architecture descriptions
- Added Mermaid diagrams for visual protocol flow representation
- Expanded API documentation with v2.5 feature coverage
- Updated migration guide for v2.0 to v2.5 transition
- NEW: Added complete Mailbox Transport System guide (Documentation/Mailbox-Transport-Guide.md)
- NEW: Added detailed message flow sequence diagrams (Documentation/Message-Flow-Sequence.md)
- Complete architectural rewrite with improved separation of concerns
- New
LibEmiddleClientAPI for simplified end-to-end encryption - Comprehensive abstractions layer with interfaces for all major components
- New domain models with better encapsulation and validation
- Advanced session management with persistence capabilities
- Multi-device support with device linking and synchronization
- Group messaging with enhanced security features
- Improved key management with rotation strategies
- Protocol adapters for X3DH and Double Ratchet
- Enhanced transport layer with multiple transport options
- Comprehensive test suite with over 90% coverage
- Advanced error recovery mechanisms
- Performance optimizations for large groups and high-throughput scenarios
- BREAKING: Complete API redesign - not backward compatible with v1.x
- BREAKING: Protocol version updated to 2.0
- BREAKING: Database schema changes require migration
- Improved cryptographic implementations with better security
- Enhanced logging and debugging capabilities
- Better memory management and secure memory handling
- Modernized codebase with latest C# features and patterns
- BREAKING: Legacy v1.x API methods and classes
- BREAKING: Old session persistence format
- BREAKING: Deprecated cryptographic methods
- Multiple security vulnerabilities identified in v1.x
- Memory leaks in long-running sessions
- Race conditions in multi-threaded scenarios
- Key rotation edge cases
- Group membership synchronization issues
- Enhanced key derivation functions
- Improved forward secrecy guarantees
- Better protection against timing attacks
- Strengthened group key management
- Enhanced device authentication mechanisms
- Initial release of LibEmiddle
- Basic X3DH key exchange implementation
- Double Ratchet protocol for forward secrecy
- Group messaging capabilities
- Device management features
- WebSocket transport support
- Basic session persistence
- End-to-end encryption for individual and group messages
- Forward secrecy through Double Ratchet
- Post-compromise security features
✅ BACKWARD COMPATIBLE: Version 2.5 is backward compatible with v2.0.
New features in v2.5 are opt-in through the Feature Flags system:
var options = new LibEmiddleClientOptions
{
// Existing v2.0 configuration works unchanged
TransportType = TransportType.Http,
ServerEndpoint = "https://your-server.com",
// New v2.5 features are opt-in
FeatureFlags = new FeatureFlags
{
EnableMessageBatching = true, // Opt-in to message batching
EnableDiagnostics = true, // Opt-in to monitoring
EnableAdvancedGroupManagement = true, // Opt-in to enhanced groups
EnableAsyncMessageStreams = true, // Opt-in to reactive streams
EnableWebRTCTransport = true // Opt-in to WebRTC support
},
// Configure new optional features
WebRTCOptions = new WebRTCOptions { /* configuration */ },
BatchingOptions = new BatchingOptions { /* configuration */ },
PostQuantumOptions = new PostQuantumOptions { /* configuration */ }
};- Performance: Message batching and connection pooling improvements
- Monitoring: Built-in diagnostics and health monitoring
- Future-Ready: Post-quantum cryptography preparation
- Enterprise: Advanced features for high-scale deployments
WebRTC transport was initially planned for v2.5 but remains under development. The current implementation is a stub for API development only and is not production-ready. Full WebRTC support is targeted for v3.0.
- API Redesign: Complete rewrite of public APIs
- Protocol Update: New protocol version with enhanced security
- Data Migration: Existing sessions and keys need migration
- Backup existing data before upgrading
- Review new API documentation in README.md
- Update your code to use new
LibEmiddleClientAPI - Run migration tools (if available) for existing data
- Test thoroughly in development environment
// Old v1.x API (deprecated)
var oldClient = new LibEmiddleManager();
await oldClient.InitializeAsync();
// New v2.x API
var options = new LibEmiddleClientOptions
{
UserId = "user123",
DeviceId = "device456"
};
var newClient = new LibEmiddleClient(options);
await newClient.InitializeAsync();For detailed migration instructions, see the Migration Guide.
| Version | Status | Support Level | End of Life |
|---|---|---|---|
| 2.5.x | Current | Full support | TBD |
| 2.0.x | Maintenance | Security fixes and critical bugs | 2025-12-31 |
| 1.x.x | Legacy | Security fixes only | 2025-06-30 |