Skip to content

Commit 28540ad

Browse files
committed
Use the last olm session that got a message
Implements matrix-org/matrix-spec-proposals#1596 For element-hq/element-web#3822 Requires matrix-org/olm-backup#77 (+release)
1 parent 62b2c07 commit 28540ad

File tree

1 file changed

+14
-5
lines changed

1 file changed

+14
-5
lines changed

src/crypto/OlmDevice.js

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -558,13 +558,20 @@ OlmDevice.prototype.getSessionIdsForDevice = async function(theirDeviceIdentityK
558558
* @return {Promise<?string>} session id, or null if no established session
559559
*/
560560
OlmDevice.prototype.getSessionIdForDevice = async function(theirDeviceIdentityKey) {
561-
const sessionIds = await this.getSessionIdsForDevice(theirDeviceIdentityKey);
562-
if (sessionIds.length === 0) {
561+
const sessionInfos = await this.getSessionInfoForDevice(theirDeviceIdentityKey);
562+
if (sessionInfos.length === 0) {
563563
return null;
564564
}
565-
// Use the session with the lowest ID.
566-
sessionIds.sort();
567-
return sessionIds[0];
565+
// Use the session that has most recently received a message
566+
sessionInfos.sort((a, b) => {
567+
if (a.lastReceivedMessageTs !== b.lastReceivedMessageTs) {
568+
return a.lastReceivedMessageTs - b.lastReceivedMessageTs;
569+
} else {
570+
if (a.sessionId === b.sessionId) return 0;
571+
return a.sessionId < b.sessionId ? -1 : 1;
572+
}
573+
});
574+
return sessionInfos[sessionInfos.length - 1].sessionId;
568575
};
569576

570577
/**
@@ -589,6 +596,7 @@ OlmDevice.prototype.getSessionInfoForDevice = async function(deviceIdentityKey)
589596
for (const sessionId of sessionIds) {
590597
this._unpickleSession(sessions[sessionId], (session) => {
591598
info.push({
599+
lastReceivedMessageTs: session.last_received_message_ts(),
592600
hasReceivedMessage: session.has_received_message(),
593601
sessionId: sessionId,
594602
});
@@ -649,6 +657,7 @@ OlmDevice.prototype.decryptMessage = async function(
649657
(txn) => {
650658
this._getSession(theirDeviceIdentityKey, sessionId, txn, (session) => {
651659
payloadString = session.decrypt(messageType, ciphertext);
660+
session.set_last_received_message_ts(Date.now());
652661
this._saveSession(theirDeviceIdentityKey, session, txn);
653662
});
654663
},

0 commit comments

Comments
 (0)