@@ -478,16 +478,6 @@ export class CryptoClient {
478
478
try {
479
479
session . unpickle ( this . pickleKey , currentSession . pickled ) ;
480
480
481
- const encrypted = session . encrypt ( JSON . stringify ( {
482
- type : eventType ,
483
- content : content ,
484
- room_id : roomId ,
485
- } ) ) ;
486
-
487
- currentSession . pickled = session . pickle ( this . pickleKey ) ;
488
- currentSession . usesLeft -- ;
489
- await this . client . cryptoStore . storeOutboundGroupSession ( currentSession ) ;
490
-
491
481
const neededSessions : Record < string , string [ ] > = { } ;
492
482
for ( const userId of Object . keys ( devices ) ) {
493
483
neededSessions [ userId ] = devices [ userId ] . map ( d => d . device_id ) ;
@@ -502,7 +492,7 @@ export class CryptoClient {
502
492
continue ;
503
493
}
504
494
const lastSession = await this . client . cryptoStore . getLastSentOutboundGroupSession ( userId , device . device_id , roomId ) ;
505
- if ( lastSession ?. sessionId !== session . session_id ( ) || session . message_index ( ) <= ( lastSession ?. index ?? Number . MAX_SAFE_INTEGER ) ) {
495
+ if ( lastSession ?. sessionId !== session . session_id ( ) || session . message_index ( ) < ( lastSession ?. index ?? Number . MAX_SAFE_INTEGER ) ) {
506
496
await this . encryptAndSendOlmMessage ( device , olmSession , "m.room_key" , < IMRoomKey > {
507
497
algorithm : EncryptionAlgorithm . MegolmV1AesSha2 ,
508
498
room_id : roomId ,
@@ -514,6 +504,17 @@ export class CryptoClient {
514
504
}
515
505
}
516
506
507
+ // Encrypt after to avoid UNKNOWN_MESSAGE_INDEX errors on remote end
508
+ const encrypted = session . encrypt ( JSON . stringify ( {
509
+ type : eventType ,
510
+ content : content ,
511
+ room_id : roomId ,
512
+ } ) ) ;
513
+
514
+ currentSession . pickled = session . pickle ( this . pickleKey ) ;
515
+ currentSession . usesLeft -- ;
516
+ await this . client . cryptoStore . storeOutboundGroupSession ( currentSession ) ;
517
+
517
518
const body = {
518
519
sender_key : this . deviceCurve25519 ,
519
520
ciphertext : encrypted ,
0 commit comments