From a2f8731a2300aace71b4a1014ff43e875e3897f0 Mon Sep 17 00:00:00 2001 From: Bruno Windels Date: Mon, 14 Sep 2020 14:19:35 +0200 Subject: [PATCH] Keep room key with earliest index --- src/matrix/e2ee/megolm/Decryption.js | 27 +++++++++++++++++++-------- 1 file changed, 19 insertions(+), 8 deletions(-) diff --git a/src/matrix/e2ee/megolm/Decryption.js b/src/matrix/e2ee/megolm/Decryption.js index b3f1ea71..4d756dcb 100644 --- a/src/matrix/e2ee/megolm/Decryption.js +++ b/src/matrix/e2ee/megolm/Decryption.js @@ -138,12 +138,23 @@ export class Decryption { return; } - // TODO: compare first_known_index to see which session to keep - const hasSession = await txn.inboundGroupSessions.has(roomId, senderKey, sessionId); - if (!hasSession) { - const session = new this._olm.InboundGroupSession(); - try { - session.create(sessionKey); + const session = new this._olm.InboundGroupSession(); + try { + session.create(sessionKey); + + let incomingSessionIsBetter = true; + const existingSessionEntry = await txn.inboundGroupSessions.get(roomId, senderKey, sessionId); + if (existingSessionEntry) { + const existingSession = new this._olm.InboundGroupSession(); + try { + existingSession.unpickle(this._pickleKey, existingSessionEntry.session); + incomingSessionIsBetter = session.first_known_index() < existingSession.first_known_index(); + } finally { + existingSession.free(); + } + } + + if (incomingSessionIsBetter) { const sessionEntry = { roomId, senderKey, @@ -153,9 +164,9 @@ export class Decryption { }; txn.inboundGroupSessions.set(sessionEntry); newSessions.push(sessionEntry); - } finally { - session.free(); } + } finally { + session.free(); } }