| author | Stephen Paul Weber
<singpolyma@singpolyma.net> 2026-11-11 22:02:49 UTC |
| committer | Stephen Paul Weber
<singpolyma@singpolyma.net> 2026-11-16 16:24:27 UTC |
| parent | cfcc9c562e8b847bfe620b63cbff5bc560693324 |
| borogove/Chat.hx | +46 | -24 |
| borogove/Client.hx | +23 | -2 |
| borogove/EncryptionInfo.hx | +8 | -2 |
| borogove/OMEMO.hx | +12 | -6 |
| test/TestChat.hx | +5 | -2 |
| test/TestClient.hx | +64 | -0 |
| test/TestSqlite.hx | +2 | -2 |
| test/persistence-tests.ts | +2 | -2 |
diff --git a/borogove/Chat.hx b/borogove/Chat.hx index e503318..45b6940 100644 --- a/borogove/Chat.hx +++ b/borogove/Chat.hx @@ -271,7 +271,23 @@ abstract class Chat extends EventEmitter { @:allow(borogove) // Not abstract to work around https://github.com/HaxeFoundation/haxe/issues/11666 - private function sendMessageStanza(stanza: Stanza, ?outboxItem: OutboxItem, e2eePreference: OutgoingE2EEPreference = Default):Void { } + private function sendMessageStanza(stanza: Stanza, ?outboxItem: OutboxItem, e2eePreference: OutgoingE2EEPreference = Default):Promise<Null<EncryptionInfo>> { throw "Not implemented"; } + + private function defaultE2ee():OutgoingE2EEPreference { + return client.outgoingE2EEPreference[0]; + } + + private function intendedEncryption(e2eePreference:OutgoingE2EEPreference):Null<EncryptionInfo> { + #if NO_OMEMO + return null; + #else + return switch (e2eePreference) { + case OMEMO: EncryptionInfo.forSent(NS.OMEMO); + case NoE2EE: null; + case Default: defaultE2ee(); + }; + #end + } /** Signals that all messages up to and including this one have probably @@ -1270,7 +1286,7 @@ class DirectChat extends Chat { return message; } - private function prepareOutgoingMessage(message:ChatMessageBuilder) { + private function prepareOutgoingMessage(message:ChatMessageBuilder, e2eePreference:OutgoingE2EEPreference = Default) { message.timeSent = message.timeSent ?? Date.format(std.Date.now()); message.timeReceived = Date.format(std.Date.now()); message.direction = MessageSent; @@ -1280,6 +1296,7 @@ class DirectChat extends Chat { message.recipients = counterparts().map((p) -> JID.parse(p)); message.to = message.recipients[0]; if (message.localId == null) message.localId = ID.unique(); + if (message.encryption == null) message.encryption = intendedEncryption(e2eePreference); return message; } @@ -1293,7 +1310,7 @@ class DirectChat extends Chat { client.storeMessageBuilder(message).then((corrected) -> { message.versions = corrected.versions[corrected.versions.length - 1]?.localId == correct.localId ? cast corrected.versions : [message.build()]; message.localId = toSendId; - sendMessageStanza(message.build().asStanza(), outboxItem); + sendMessageStanza(message.build().asStanza(), outboxItem).then((encryptionInfo) -> client.applySentEncryption(this, message, encryptionInfo)); if (lastMessage == null || corrected.canReplace(lastMessage)) { setLastMessage(corrected).then(_ -> client.trigger("chats/update", [this]) @@ -1307,7 +1324,7 @@ class DirectChat extends Chat { if (uiState == Invited) uiState = Open; if (typingTimer != null) typingTimer.stop(); client.chatActivity(this); - message = prepareOutgoingMessage(message); + message = prepareOutgoingMessage(message, e2eePreference); message.to = message.recipients[0]; // Just pick one for the stanza we re-parse final fromStanza = Message.fromStanza(message.build().asStanza(), client.jid).parsed; switch (fromStanza) { @@ -1320,7 +1337,7 @@ class DirectChat extends Chat { activeThread = message.threadId; stanza.tag("active", { xmlns: "http://jabber.org/protocol/chatstates" }).up(); } - sendMessageStanza(stanza, outboxItem, e2eePreference); + sendMessageStanza(stanza, outboxItem, e2eePreference).then((encryptionInfo) -> client.applySentEncryption(this, message, encryptionInfo)); setLastMessage(stored).then(_ -> { client.notifyMessageHandlers(stored, stored.versions.length > 1 ? CorrectionEvent : DeliveryEvent); client.trigger("chats/update", [this]); @@ -1378,13 +1395,13 @@ class DirectChat extends Chat { }); } - override private function sendMessageStanza(stanza: Stanza, ?outboxItem: OutboxItem, e2eePreference: OutgoingE2EEPreference = Default) { + override private function sendMessageStanza(stanza: Stanza, ?outboxItem: OutboxItem, e2eePreference: OutgoingE2EEPreference = Default):Promise<Null<EncryptionInfo>> { if (stanza.name != "message") throw "Can only send message stanza this way"; if (outboxItem == null) outboxItem = outbox.newItem(); final counters = counterparts(); - thenshim.PromiseTools.all(counters.map(counterpart -> { + return thenshim.PromiseTools.all(counters.map(counterpart -> { final clone = stanza.clone(); clone.attr.set("to", counterpart); if (counters.length > 1 && stanza.getChild("addresses", "http://jabber.org/protocol/address") == null) { @@ -1400,26 +1417,27 @@ class DirectChat extends Chat { if (e2eePreference == Default) e2eePreference = client.outgoingE2EEPreference[0]; #if NO_OMEMO if (e2eePreference != NoE2EE) throw "Selected E2EE preference unsupported"; - return Promise.resolve(stanza); + return Promise.resolve({ stanza: stanza, encryptionInfo: null }); #else switch (e2eePreference) { case OMEMO: // As written this falls back to NoE2EE if allowed - return client.omemo.encryptMessage([JID.parse(counterpart)], stanza).then((encryptedStanza) -> { - return Promise.resolve(encryptedStanza); + return client.omemo.encryptMessage([JID.parse(counterpart)], stanza).then((outcome) -> { + return Promise.resolve({ stanza: outcome.stanza, encryptionInfo: outcome.encryptionInfo }); }); case NoE2EE: - return Promise.resolve(stanza); + return Promise.resolve({ stanza: stanza, encryptionInfo: null }); case Default: throw "Impossible"; } #end - })).then(stanzas -> { + })).then(outcomes -> { outboxItem.handle(() -> { - for (stanza in stanzas) { - client.sendStanza(stanza); + for (outcome in outcomes) { + client.sendStanza(outcome.stanza); } }); + return Promise.resolve(outcomes.fold((x, y) -> x.encryptionInfo == null || y == null ? null : x.encryptionInfo, outcomes[0].encryptionInfo)); }); } @@ -2495,7 +2513,7 @@ class Channel extends Chat { return message; } - private function prepareOutgoingMessage(message:ChatMessageBuilder) { + private function prepareOutgoingMessage(message:ChatMessageBuilder, e2eePreference:OutgoingE2EEPreference = Default) { message.type = MessageChannel; message.timeSent = message.timeSent ?? Date.format(std.Date.now()); message.timeReceived = Date.format(std.Date.now()); @@ -2516,6 +2534,7 @@ class Channel extends Chat { sortId: { method: "between", lower: lower, upper: null }, }; } + if (message.encryption == null) message.encryption = intendedEncryption(e2eePreference); return message; } @@ -2529,7 +2548,7 @@ class Channel extends Chat { client.storeMessageBuilder(message).then((corrected) -> { message.versions = corrected.versions[0]?.localId == correct.localId ? cast corrected.versions : [message.build()]; message.localId = toSendId; - sendMessageStanza(message.build().asStanza(), outboxItem); + sendMessageStanza(message.build().asStanza(), outboxItem).then((encryptionInfo) -> client.applySentEncryption(this, message, encryptionInfo)); client.notifyMessageHandlers(corrected, CorrectionEvent); if (lastMessage == null || corrected.canReplace(lastMessage)) { setLastMessage(corrected).then(_ -> @@ -2543,7 +2562,7 @@ class Channel extends Chat { if (uiState == Invited) uiState = Open; if (typingTimer != null) typingTimer.stop(); client.chatActivity(this); - message = prepareOutgoingMessage(message); + message = prepareOutgoingMessage(message, e2eePreference); final stanza = message.build().asStanza(); // Fake from as it will look on reflection for storage purposes stanza.attr.set("from", getFullJid().asString()); @@ -2561,7 +2580,7 @@ class Channel extends Chat { } final outboxItem = outbox.newItem(); client.storeMessageBuilder(message).then((stored) -> { - sendMessageStanza(stanza, outboxItem); + sendMessageStanza(stanza, outboxItem, e2eePreference).then((encryptionInfo) -> client.applySentEncryption(this, message, encryptionInfo)); setLastMessage(stored).then(_ -> { client.notifyMessageHandlers(stored, stored.versions.length > 1 ? CorrectionEvent : DeliveryEvent); client.trigger("chats/update", [this]); @@ -2615,7 +2634,7 @@ class Channel extends Chat { } // TODO: this is a gross heuristic. Large private groups that don't want e2ee are possible for example - private function defaultE2ee() { + override private function defaultE2ee() { if (!client.outgoingE2EEPreference.exists(p -> p == NoE2EE)) { // Must E2EE return client.outgoingE2EEPreference[0]; @@ -2626,7 +2645,7 @@ class Channel extends Chat { return client.outgoingE2EEPreference[0]; } - override private function sendMessageStanza(stanza: Stanza, ?outboxItem: OutboxItem, e2eePreference: OutgoingE2EEPreference = Default) { + override private function sendMessageStanza(stanza: Stanza, ?outboxItem: OutboxItem, e2eePreference: OutgoingE2EEPreference = Default):Promise<Null<EncryptionInfo>> { if (stanza.name != "message") throw "Can only send message stanza this way"; if (outboxItem == null) outboxItem = outbox.newItem(); @@ -2639,19 +2658,22 @@ class Channel extends Chat { #if NO_OMEMO if (e2eePreference != NoE2EE) throw "Selected E2EE preference unsupported"; outboxItem.handle(() -> client.sendStanza(stanza)); + return Promise.resolve(null); #else switch (e2eePreference) { case OMEMO: // As written this falls back to NoE2EE if allowed and no one has OMEMO // TODO: on some rooms, especially very large ones this may not be a full // list of members. In practise it is fine anywhere OMEMO could actually work - members().then(members -> + return members().then(members -> client.omemo.encryptMessage(members.map(member -> JID.parse(member.chat?.chatId)), stanza) - ).then((encryptedStanza) -> - outboxItem.handle(() -> client.sendStanza(encryptedStanza)) - ); + ).then((outcome) -> { + outboxItem.handle(() -> client.sendStanza(outcome.stanza)); + return Promise.resolve(outcome.encryptionInfo); + }); case NoE2EE: outboxItem.handle(() -> client.sendStanza(stanza)); + return Promise.resolve(null); case Default: throw "Impossible"; } diff --git a/borogove/Client.hx b/borogove/Client.hx index 05b5277..c47a545 100644 --- a/borogove/Client.hx +++ b/borogove/Client.hx @@ -2188,6 +2188,23 @@ class Client extends EventEmitter { })).then(updatedMessages -> persistence.storeMessages(accountId(), updatedMessages)); } + @:allow(borogove) + private function applySentEncryption(chat: Chat, builder: ChatMessageBuilder, encryption: Null<EncryptionInfo>) { + final stored = builder.encryption; + if (stored == encryption || (stored != null && encryption != null && stored.status == encryption.status && stored.method == encryption.method)) { + return Promise.resolve(null); + } + + builder.encryption = encryption; + return storeMessageBuilder(builder).then(updated -> { + if (chat.lastMessage != null && chat.lastMessage.canReplace(updated)) { + chat.setLastMessage(updated).then(_ -> trigger("chats/update", [chat])); + } + notifyMessageHandlers(updated, StatusEvent); + return null; + }); + } + private function checkForResends() { var tooOld = Date.format( DateTools.delta(std.Date.now(), DateTools.hours(-3)) @@ -2210,8 +2227,12 @@ class Client extends EventEmitter { from: accountId(), stamp: m.timeSent }); - // TODO: don't know if was originally send with OMEMO - chat.sendMessageStanza(stanza); + // Don't silently downgrade a message that was meant to be encrypted + var preference:OutgoingE2EEPreference = Default; + #if !NO_OMEMO + if (m.encryption != null) preference = OMEMO; + #end + chat.sendMessageStanza(stanza, null, preference).then((encryption) -> applySentEncryption(chat, ChatMessageBuilder.fromMessage(m), encryption)); } } } diff --git a/borogove/EncryptionInfo.hx b/borogove/EncryptionInfo.hx index a211501..32db00b 100644 --- a/borogove/EncryptionInfo.hx +++ b/borogove/EncryptionInfo.hx @@ -8,7 +8,7 @@ import HaxeCBridge; Outcome of decrypting an incoming message. **/ enum abstract EncryptionStatus(Int) { - var DecryptionSuccess; // Message was encrypted, and we decrypted it + var EncryptionInfoSuccess; // Incoming: message was encrypted and we decrypted it. Outgoing: message was encrypted var DecryptionFailure; // Message is encrypted, and we failed to decrypt it } @@ -48,7 +48,7 @@ class EncryptionInfo { final el = new Stanza("decryption-status", { xmlns: "https://borogove.dev/protocol/sdk", encryption: this.method, - result: status == DecryptionSuccess?"success":"failure", + result: status == EncryptionInfoSuccess?"success":"failure", }); if(reason != null) { el.textTag("reason", reason); @@ -59,6 +59,12 @@ class EncryptionInfo { return el; } + // We encrypted an outgoing message with this method + @:allow(borogove) + static private function forSent(method:String):EncryptionInfo { + return new EncryptionInfo(EncryptionInfoSuccess, method); + } + // Typically used to deduce an EncryptionInfo when none has been provided // May return null if the stanza is not recognizably encrypted. @:allow(borogove) diff --git a/borogove/OMEMO.hx b/borogove/OMEMO.hx index 6d76637..5750635 100644 --- a/borogove/OMEMO.hx +++ b/borogove/OMEMO.hx @@ -311,6 +311,11 @@ class OMEMODecryptionResult { } } +typedef OMEMOEncryptionOutcome = { + final stanza:Stanza; + final encryptionInfo:Null<EncryptionInfo>; +}; + @:expose class OMEMOSessionMetadata { // True when we have successfully received and decrypted any @@ -932,7 +937,7 @@ class OMEMO { return Promise.resolve(new OMEMODecryptionResult( stanza, new EncryptionInfo( - DecryptionSuccess, + EncryptionInfoSuccess, NS.OMEMO, ) )); @@ -959,7 +964,7 @@ class OMEMO { // No metadata in storage, so create a default metadata = new OMEMOSessionMetadata(false, false, false); } - final decryptedOk = decryptionResult.encryptionInfo.status == DecryptionSuccess; + final decryptedOk = decryptionResult.encryptionInfo.status == EncryptionInfoSuccess; var needUpdate = metadata.lastMessageDecryptedOk != decryptedOk; final receivedSessionMessage = deviceKey != null && !deviceKey.prekey; needUpdate = needUpdate || receivedSessionMessage != metadata.receivedSessionMessageOk; @@ -1093,7 +1098,7 @@ class OMEMO { }); } - public function encryptMessage(recipients: Array<JID>, stanza:Stanza):Promise<Stanza> { + public function encryptMessage(recipients: Array<JID>, stanza:Stanza):Promise<OMEMOEncryptionOutcome> { final promHeader = thenshim.PromiseTools.all(recipients.map(getContactDevices)).then(raddresses -> { final raddrs = raddresses.flatMap(addrs -> addrs); @@ -1125,7 +1130,7 @@ class OMEMO { newStanza.addChild(header); newStanza.textTag("encryption", "", { xmlns: "urn:xmpp:eme:0", namespace: "eu.siacs.conversations.axolotl" }); newStanza.textTag("body", "I sent you an OMEMO encrypted message but your client doesn’t seem to support that. Find more information on https://conversations.im/omemo"); - return newStanza; + return { stanza: newStanza, encryptionInfo: EncryptionInfo.forSent(NS.OMEMO) }; }, (failureReason) -> { final noRecipientSupport = failureReason == "no-devices"; var allowUnencrypted:Bool = client.outgoingE2EEPreference.exists(p -> p == NoE2EE); @@ -1152,9 +1157,10 @@ class OMEMO { trace("OMEMO: Skipping encryption (permitted by policy): " + errMsg); - // Encryption failed, but policy says this is ok. + // Encryption failed, but policy says this is ok. The message goes + // out unencrypted, so no EncryptionInfo is recorded for it. // Just pass through the original stanza to be sent. - return stanza; + return { stanza: stanza, encryptionInfo: null }; }); return promStanza; diff --git a/test/TestChat.hx b/test/TestChat.hx index 100efe2..13c065c 100644 --- a/test/TestChat.hx +++ b/test/TestChat.hx @@ -1209,10 +1209,13 @@ class TestChat extends utest.Test { final chat = client.getDirectChat("friend@example.com"); Reflect.setField(client, "omemo", { - encryptMessage: function(jid: borogove.JID, stanza: Stanza) { + encryptMessage: function(jids: Array<borogove.JID>, stanza: Stanza) { final encrypted = stanza.clone(); encrypted.tag("encrypted", { xmlns: "eu.siacs.conversations.axolotl" }).up(); - return Promise.resolve(encrypted); + return Promise.resolve({ + stanza: encrypted, + encryptionInfo: new borogove.EncryptionInfo(EncryptionInfoSuccess, "eu.siacs.conversations.axolotl") + }); } }); diff --git a/test/TestClient.hx b/test/TestClient.hx index 106734f..b9deb55 100644 --- a/test/TestClient.hx +++ b/test/TestClient.hx @@ -23,6 +23,7 @@ import borogove.Stanza; import borogove.Status; import borogove.persistence.Dummy; import borogove.Chat.OutgoingE2EEPreference; +import borogove.EncryptionInfo; import borogove.AttachmentUploadError; import borogove.AttachmentUploadErrorCode; #if !NO_OMEMO @@ -663,6 +664,69 @@ class TestClient extends utest.Test { }); } + #if !NO_OMEMO + public function testSentMessageRecordsEncryption(async: Async) { + final persistence = new MessageMockPersistence(); + final client = new Client("test@example.com", persistence); + final chat = client.getDirectChat("friend@example.com"); + + Reflect.setField(client, "omemo", { + encryptMessage: function(jids: Array<JID>, stanza: Stanza) { + final encrypted = stanza.clone(); + encrypted.tag("encrypted", { xmlns: "eu.siacs.conversations.axolotl" }).up(); + return Promise.resolve({ + stanza: encrypted, + encryptionInfo: new borogove.EncryptionInfo(EncryptionInfoSuccess, "eu.siacs.conversations.axolotl") + }); + } + }); + + client.stream.on("sendStanza", (stanza: Stanza) -> { + if (stanza.name != "message") return EventUnhandled; + final stored = persistence.messages.get(stanza.attr.get("id")); + Assert.notNull(stored); + Assert.notNull(stored?.encryption); + Assert.equals(EncryptionInfoSuccess, stored?.encryption?.status); + Assert.equals("eu.siacs.conversations.axolotl", stored?.encryption?.method); + Assert.equals("OMEMO", stored?.encryption?.methodName); + async.done(); + return EventHandled; + }); + + final builder = new ChatMessageBuilder(); + builder.text = "hello"; + chat.sendMessage(builder, borogove.Chat.OutgoingE2EEPreference.OMEMO); + } + + public function testSentMessageRecordsFallbackAsUnencrypted(async: Async) { + final persistence = new MessageMockPersistence(); + final client = new Client("test@example.com", persistence); + final chat = client.getDirectChat("friend@example.com"); + + Reflect.setField(client, "omemo", { + encryptMessage: function(jids: Array<JID>, stanza: Stanza) { + return Promise.resolve({ stanza: stanza.clone(), encryptionInfo: null }); + } + }); + + var finished = false; + client.on("message/new", (data: { message: ChatMessage, event: ChatMessageEvent }) -> { + if (data.event != StatusEvent || finished) return EventUnhandled; + Assert.isNull(data.message.encryption); + Assert.isNull(persistence.messages.get(data.message.localId)?.encryption); + Assert.equals(data.message.localId, chat.lastMessage?.localId); + Assert.isNull(chat.lastMessage?.encryption); + finished = true; + async.done(); + return EventHandled; + }); + + final builder = new ChatMessageBuilder(); + builder.text = "hello"; + chat.sendMessage(builder, borogove.Chat.OutgoingE2EEPreference.OMEMO); + } + #end + public function testDefaultDisplayName() { final persistence = new Dummy(); final client = new Client("test@example.com", persistence); diff --git a/test/TestSqlite.hx b/test/TestSqlite.hx index b8d60b7..aeda401 100644 --- a/test/TestSqlite.hx +++ b/test/TestSqlite.hx @@ -879,7 +879,7 @@ class TestSqlite extends utest.Test { final chatId = "encryption-correction-hatter@example.com"; final originalExpected = { text: "Original encrypted text", - encryption: new EncryptionInfo(DecryptionSuccess, "urn:xmpp:omemo:1", null, null, "OMEMO 1") + encryption: new EncryptionInfo(EncryptionInfoSuccess, "urn:xmpp:omemo:1", null, null, "OMEMO 1") }; final original = makeMessage({ timestamp: "2026-08-26T12:00:00Z", @@ -1011,7 +1011,7 @@ class TestSqlite extends utest.Test { public function testUpdateMessageStatus(async: Async) { final account = "alice@example.com"; - final expectedEncryption = new EncryptionInfo(DecryptionSuccess, "eu.siacs.conversations.axolotl", null, null, "OMEMO"); + final expectedEncryption = new EncryptionInfo(EncryptionInfoSuccess, "eu.siacs.conversations.axolotl", null, null, "OMEMO"); final builder = new ChatMessageBuilder(); builder.localId = "loc1"; builder.senderId = "alice@example.com"; diff --git a/test/persistence-tests.ts b/test/persistence-tests.ts index cc52ea9..eff2d2b 100644 --- a/test/persistence-tests.ts +++ b/test/persistence-tests.ts @@ -455,7 +455,7 @@ export function sharedPersistenceTests(test) { builder.recipients = [builder.to]; builder.replyTo = [builder.from]; builder.encryption = { - status: borogove.EncryptionStatus.DecryptionSuccess, + status: borogove.EncryptionStatus.EncryptionInfoSuccess, method: "eu.siacs.conversations.axolotl", methodName: "OMEMO", reason: null, @@ -503,7 +503,7 @@ export function sharedPersistenceTests(test) { originalBuilder.recipients = [originalBuilder.to]; originalBuilder.replyTo = [originalBuilder.from]; originalBuilder.encryption = { - status: borogove.EncryptionStatus.DecryptionSuccess, + status: borogove.EncryptionStatus.EncryptionInfoSuccess, method: "urn:xmpp:omemo:1", methodName: "OMEMO 1", reason: null,