matrix-js-sdk 42.1.0 → 42.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (154) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/lib/@types/beacon.d.ts +1 -1
  3. package/lib/@types/beacon.js +1 -1
  4. package/lib/@types/beacon.js.map +1 -1
  5. package/lib/@types/extensible_events.d.ts.map +1 -1
  6. package/lib/@types/extensible_events.js.map +1 -1
  7. package/lib/autodiscovery.js.map +1 -1
  8. package/lib/browser-index.js.map +1 -1
  9. package/lib/client.d.ts +12 -5
  10. package/lib/client.d.ts.map +1 -1
  11. package/lib/client.js +23 -26
  12. package/lib/client.js.map +1 -1
  13. package/lib/common-crypto/key-passphrase.js +1 -1
  14. package/lib/common-crypto/key-passphrase.js.map +1 -1
  15. package/lib/crypto/store/indexeddb-crypto-store-backend.js +2 -1
  16. package/lib/crypto/store/indexeddb-crypto-store-backend.js.map +1 -1
  17. package/lib/crypto/store/indexeddb-crypto-store.d.ts.map +1 -1
  18. package/lib/crypto/store/indexeddb-crypto-store.js +1 -1
  19. package/lib/crypto/store/indexeddb-crypto-store.js.map +1 -1
  20. package/lib/crypto/store/memory-crypto-store.js.map +1 -1
  21. package/lib/embedded.d.ts +16 -0
  22. package/lib/embedded.d.ts.map +1 -1
  23. package/lib/embedded.js +19 -6
  24. package/lib/embedded.js.map +1 -1
  25. package/lib/matrixrtc/MatrixRTCSession.js.map +1 -1
  26. package/lib/matrixrtc/MembershipManager.js.map +1 -1
  27. package/lib/matrixrtc/MembershipManagerActionScheduler.js.map +1 -1
  28. package/lib/matrixrtc/RTCEncryptionManager.js.map +1 -1
  29. package/lib/matrixrtc/ToDeviceKeyTransport.js.map +1 -1
  30. package/lib/matrixrtc/membershipData/rtc.js.map +1 -1
  31. package/lib/matrixrtc/utils.d.ts +0 -1
  32. package/lib/matrixrtc/utils.d.ts.map +1 -1
  33. package/lib/matrixrtc/utils.js +0 -1
  34. package/lib/matrixrtc/utils.js.map +1 -1
  35. package/lib/models/event-timeline-set.js +3 -3
  36. package/lib/models/event-timeline-set.js.map +1 -1
  37. package/lib/models/event.d.ts.map +1 -1
  38. package/lib/models/event.js.map +1 -1
  39. package/lib/models/invites-ignorer.js.map +1 -1
  40. package/lib/models/poll.js.map +1 -1
  41. package/lib/models/read-receipt.js.map +1 -1
  42. package/lib/models/relations-container.d.ts +10 -0
  43. package/lib/models/relations-container.d.ts.map +1 -1
  44. package/lib/models/relations-container.js +39 -17
  45. package/lib/models/relations-container.js.map +1 -1
  46. package/lib/models/relations.js +1 -1
  47. package/lib/models/relations.js.map +1 -1
  48. package/lib/models/room.js +3 -3
  49. package/lib/models/room.js.map +1 -1
  50. package/lib/models/thread.d.ts +3 -0
  51. package/lib/models/thread.d.ts.map +1 -1
  52. package/lib/models/thread.js +36 -3
  53. package/lib/models/thread.js.map +1 -1
  54. package/lib/oauth/authorize.js +1 -1
  55. package/lib/oauth/authorize.js.map +1 -1
  56. package/lib/oauth/index.js +4 -2
  57. package/lib/oauth/index.js.map +1 -1
  58. package/lib/pollingCachedValue.d.ts +77 -0
  59. package/lib/pollingCachedValue.d.ts.map +1 -0
  60. package/lib/pollingCachedValue.js +160 -0
  61. package/lib/pollingCachedValue.js.map +1 -0
  62. package/lib/pushprocessor.js.map +1 -1
  63. package/lib/receipt-accumulator.d.ts.map +1 -1
  64. package/lib/receipt-accumulator.js.map +1 -1
  65. package/lib/rendezvous/MSC4108SignInWithQR.d.ts.map +1 -1
  66. package/lib/rendezvous/MSC4108SignInWithQR.js +2 -3
  67. package/lib/rendezvous/MSC4108SignInWithQR.js.map +1 -1
  68. package/lib/rtcTransportsCachedValue.d.ts +9 -0
  69. package/lib/rtcTransportsCachedValue.d.ts.map +1 -0
  70. package/lib/rtcTransportsCachedValue.js +38 -0
  71. package/lib/rtcTransportsCachedValue.js.map +1 -0
  72. package/lib/rust-crypto/PerSessionKeyBackupDownloader.js.map +1 -1
  73. package/lib/rust-crypto/backup.d.ts +2 -3
  74. package/lib/rust-crypto/backup.d.ts.map +1 -1
  75. package/lib/rust-crypto/backup.js.map +1 -1
  76. package/lib/rust-crypto/index.d.ts +10 -4
  77. package/lib/rust-crypto/index.d.ts.map +1 -1
  78. package/lib/rust-crypto/index.js +20 -3
  79. package/lib/rust-crypto/index.js.map +1 -1
  80. package/lib/rust-crypto/libolm_migration.js.map +1 -1
  81. package/lib/rust-crypto/rust-crypto.js.map +1 -1
  82. package/lib/sliding-sync-sdk.js.map +1 -1
  83. package/lib/sliding-sync.js.map +1 -1
  84. package/lib/store/indexeddb-local-backend.js +1 -1
  85. package/lib/store/indexeddb-local-backend.js.map +1 -1
  86. package/lib/store/indexeddb-store-worker.d.ts.map +1 -1
  87. package/lib/store/indexeddb-store-worker.js +1 -0
  88. package/lib/store/indexeddb-store-worker.js.map +1 -1
  89. package/lib/sync.d.ts.map +1 -1
  90. package/lib/sync.js.map +1 -1
  91. package/lib/utils.d.ts +1 -1
  92. package/lib/utils.d.ts.map +1 -1
  93. package/lib/utils.js +1 -0
  94. package/lib/utils.js.map +1 -1
  95. package/lib/webrtc/call.js.map +1 -1
  96. package/lib/webrtc/groupCall.js.map +1 -1
  97. package/lib/webrtc/mediaHandler.js.map +1 -1
  98. package/lib/webrtc/stats/callStatsReportGatherer.js.map +1 -1
  99. package/lib/webrtc/stats/transportStatsBuilder.js.map +1 -1
  100. package/lib/wellKnownCachedValue.d.ts +8 -0
  101. package/lib/wellKnownCachedValue.d.ts.map +1 -0
  102. package/lib/wellKnownCachedValue.js +34 -0
  103. package/lib/wellKnownCachedValue.js.map +1 -0
  104. package/package.json +4 -4
  105. package/src/@types/beacon.ts +1 -1
  106. package/src/@types/extensible_events.ts +3 -4
  107. package/src/autodiscovery.ts +2 -2
  108. package/src/browser-index.ts +1 -1
  109. package/src/client.ts +48 -40
  110. package/src/common-crypto/key-passphrase.ts +1 -1
  111. package/src/crypto/store/indexeddb-crypto-store-backend.ts +2 -1
  112. package/src/crypto/store/indexeddb-crypto-store.ts +1 -3
  113. package/src/crypto/store/memory-crypto-store.ts +1 -1
  114. package/src/embedded.ts +34 -11
  115. package/src/matrixrtc/MatrixRTCSession.ts +3 -3
  116. package/src/matrixrtc/MembershipManager.ts +1 -1
  117. package/src/matrixrtc/MembershipManagerActionScheduler.ts +1 -1
  118. package/src/matrixrtc/RTCEncryptionManager.ts +2 -2
  119. package/src/matrixrtc/ToDeviceKeyTransport.ts +3 -3
  120. package/src/matrixrtc/membershipData/rtc.ts +1 -1
  121. package/src/matrixrtc/utils.ts +0 -2
  122. package/src/models/event-timeline-set.ts +3 -3
  123. package/src/models/event.ts +7 -10
  124. package/src/models/invites-ignorer.ts +1 -1
  125. package/src/models/poll.ts +1 -1
  126. package/src/models/read-receipt.ts +1 -1
  127. package/src/models/relations-container.ts +55 -19
  128. package/src/models/relations.ts +1 -1
  129. package/src/models/room.ts +9 -9
  130. package/src/models/thread.ts +49 -4
  131. package/src/oauth/authorize.ts +1 -1
  132. package/src/oauth/index.ts +2 -2
  133. package/src/pollingCachedValue.ts +184 -0
  134. package/src/pushprocessor.ts +3 -3
  135. package/src/receipt-accumulator.ts +1 -2
  136. package/src/rendezvous/MSC4108SignInWithQR.ts +3 -4
  137. package/src/rtcTransportsCachedValue.ts +40 -0
  138. package/src/rust-crypto/PerSessionKeyBackupDownloader.ts +1 -1
  139. package/src/rust-crypto/backup.ts +1 -5
  140. package/src/rust-crypto/index.ts +23 -25
  141. package/src/rust-crypto/libolm_migration.ts +1 -1
  142. package/src/rust-crypto/rust-crypto.ts +3 -3
  143. package/src/sliding-sync-sdk.ts +1 -1
  144. package/src/sliding-sync.ts +1 -1
  145. package/src/store/indexeddb-local-backend.ts +1 -1
  146. package/src/store/indexeddb-store-worker.ts +1 -0
  147. package/src/sync.ts +4 -3
  148. package/src/utils.ts +3 -2
  149. package/src/webrtc/call.ts +6 -6
  150. package/src/webrtc/groupCall.ts +7 -7
  151. package/src/webrtc/mediaHandler.ts +1 -1
  152. package/src/webrtc/stats/callStatsReportGatherer.ts +2 -2
  153. package/src/webrtc/stats/transportStatsBuilder.ts +1 -1
  154. package/src/wellKnownCachedValue.ts +34 -0
@@ -1 +1 @@
1
- {"version":3,"file":"receipt-accumulator.js","names":[],"sources":["../src/receipt-accumulator.ts"],"sourcesContent":["/*\nCopyright 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { type IMinimalEvent } from \"./sync-accumulator.ts\";\nimport { EventType } from \"./@types/event.ts\";\nimport { isSupportedReceiptType, MapWithDefault, recursiveMapToObject } from \"./utils.ts\";\nimport { type IContent } from \"./models/event.ts\";\nimport { type ReceiptContent, type ReceiptType } from \"./@types/read_receipts.ts\";\n\ninterface AccumulatedReceipt {\n data: IMinimalEvent;\n type: ReceiptType;\n eventId: string;\n}\n\n/**\n * Summarises the read receipts within a room. Used by the sync accumulator.\n *\n * Given receipts for users, picks the most recently-received one and provides\n * the results in a new fake receipt event returned from\n * buildAccumulatedReceiptEvent().\n *\n * Handles unthreaded receipts and receipts in each thread separately, so the\n * returned event contains the most recently received unthreaded receipt, and\n * the most recently received receipt in each thread.\n */\nexport class ReceiptAccumulator {\n /** user_id -\\> most-recently-received unthreaded receipt */\n private unthreadedReadReceipts: Map<string, AccumulatedReceipt> = new Map();\n\n /** thread_id -\\> user_id -\\> most-recently-received receipt for this thread */\n private threadedReadReceipts: MapWithDefault<string, Map<string, AccumulatedReceipt>> = new MapWithDefault(\n () => new Map(),\n );\n\n /**\n * Provide an unthreaded receipt for this user. Overwrites any other\n * unthreaded receipt we have for this user.\n */\n private setUnthreaded(userId: string, receipt: AccumulatedReceipt): void {\n this.unthreadedReadReceipts.set(userId, receipt);\n }\n\n /**\n * Provide a receipt for this user in this thread. Overwrites any other\n * receipt we have for this user in this thread.\n */\n private setThreaded(threadId: string, userId: string, receipt: AccumulatedReceipt): void {\n this.threadedReadReceipts.getOrCreate(threadId).set(userId, receipt);\n }\n\n /**\n * @returns an iterator of pairs of [userId, AccumulatedReceipt] - all the\n * most recently-received unthreaded receipts for each user.\n * @yields pairs of [userId, AccumulatedReceipt]\n */\n private allUnthreaded(): IterableIterator<[string, AccumulatedReceipt]> {\n return this.unthreadedReadReceipts.entries();\n }\n\n /**\n * @returns an iterator of pairs of [userId, AccumulatedReceipt] - all the\n * most recently-received threaded receipts for each user, in all\n * threads.\n * @yields pairs of [userId, AccumulatedReceipt]\n */\n private *allThreaded(): IterableIterator<[string, AccumulatedReceipt]> {\n for (const receiptsForThread of this.threadedReadReceipts.values()) {\n for (const e of receiptsForThread.entries()) {\n yield e;\n }\n }\n }\n\n /**\n * Given a list of ephemeral events, find the receipts and store the\n * relevant ones to be returned later from buildAccumulatedReceiptEvent().\n */\n public consumeEphemeralEvents(events: IMinimalEvent[] | undefined): void {\n events?.forEach((e) => {\n if (e.type !== EventType.Receipt || !e.content) {\n // This means we'll drop unknown ephemeral events but that\n // seems okay.\n return;\n }\n\n // Handle m.receipt events. They clobber based on:\n // (user_id, receipt_type)\n // but they are keyed in the event as:\n // content:{ $event_id: { $receipt_type: { $user_id: {json} }}}\n // so store them in the former so we can accumulate receipt deltas\n // quickly and efficiently (we expect a lot of them). Fold the\n // receipt type into the key name since we only have 1 at the\n // moment (m.read) and nested JSON objects are slower and more\n // of a hassle to work with. We'll inflate this back out when\n // getJSON() is called.\n Object.keys(e.content).forEach((eventId) => {\n Object.entries<ReceiptContent>(e.content[eventId]).forEach(([key, value]) => {\n if (!isSupportedReceiptType(key)) return;\n\n for (const userId of Object.keys(value)) {\n const data = e.content[eventId][key][userId];\n\n const receipt = {\n data: e.content[eventId][key][userId],\n type: key as ReceiptType,\n eventId,\n };\n\n // In a world that supports threads, read receipts normally have\n // a `thread_id` which is either the thread they belong in or\n // `MAIN_ROOM_TIMELINE`, so we normally use `setThreaded(...)`\n // here. The `MAIN_ROOM_TIMELINE` is just treated as another\n // thread.\n //\n // We still encounter read receipts that are \"unthreaded\"\n // (missing the `thread_id` property). These come from clients\n // that don't support threads, and from threaded clients that\n // are doing a \"Mark room as read\" operation. Unthreaded\n // receipts mark everything \"before\" them as read, in all\n // threads, where \"before\" means in Sync Order i.e. the order\n // the events were received from the homeserver in a sync.\n // [Note: we have some bugs where we use timestamp order instead\n // of Sync Order, because we don't correctly remember the Sync\n // Order. See #3325.]\n //\n // Calling the wrong method will cause incorrect behavior like\n // messages re-appearing as \"new\" when you already read them\n // previously.\n if (!data.thread_id) {\n this.setUnthreaded(userId, receipt);\n } else {\n this.setThreaded(data.thread_id, userId, receipt);\n }\n }\n });\n });\n });\n }\n\n /**\n * Build a receipt event that contains all relevant information for this\n * room, taking the most recently received receipt for each user in an\n * unthreaded context, and in each thread.\n */\n public buildAccumulatedReceiptEvent(roomId: string): IMinimalEvent | null {\n const receiptEvent: IMinimalEvent = {\n type: EventType.Receipt,\n room_id: roomId,\n content: {\n // $event_id: { \"m.read\": { $user_id: $json } }\n } as IContent,\n };\n\n const receiptEventContent: MapWithDefault<\n string,\n MapWithDefault<ReceiptType, Map<string, object>>\n > = new MapWithDefault(() => new MapWithDefault(() => new Map()));\n\n for (const [userId, receiptData] of this.allUnthreaded()) {\n receiptEventContent\n .getOrCreate(receiptData.eventId)\n .getOrCreate(receiptData.type)\n .set(userId, receiptData.data);\n }\n\n for (const [userId, receiptData] of this.allThreaded()) {\n receiptEventContent\n .getOrCreate(receiptData.eventId)\n .getOrCreate(receiptData.type)\n .set(userId, receiptData.data);\n }\n\n receiptEvent.content = recursiveMapToObject(receiptEventContent);\n\n return receiptEventContent.size > 0 ? receiptEvent : null;\n }\n}\n"],"mappings":";AAAA;AACA;AACA;AACA;A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AI,cAAc,CAAC,MAAM,IAAI,cAAc,CAAC,MAAM,IAAI,GAAG,CAAC,CAAC,CAAC,CAAC;IAEjE,KAAK,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,IAAI,IAAI,CAAC,aAAa,CAAC,CAAC,EAAE;MACtD,mBAAmB,CACd,WAAW,CAAC,WAAW,CAAC,OAAO,CAAC,CAChC,WAAW,CAAC,WAAW,CAAC,IAAI,CAAC,CAC7B,GAAG,CAAC,MAAM,EAAE,WAAW,CAAC,IAAI,CAAC;IACtC;IAEA,KAAK,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,IAAI,IAAI,CAAC,WAAW,CAAC,CAAC,EAAE;MACpD,mBAAmB,CACd,WAAW,CAAC,WAAW,CAAC,OAAO,CAAC,CAChC,WAAW,CAAC,WAAW,CAAC,IAAI,CAAC,CAC7B,GAAG,CAAC,MAAM,EAAE,WAAW,CAAC,IAAI,CAAC;IACtC;IAEA,YAAY,CAAC,OAAO,GAAG,oBAAoB,CAAC,mBAAmB,CAAC;IAEhE,OAAO,mBAAmB,CAAC,IAAI,GAAG,CAAC,GAAG,YAAY,GAAG,IAAI;EAC7D;AACJ","ignoreList":[]}
1
+ {"version":3,"file":"receipt-accumulator.js","names":[],"sources":["../src/receipt-accumulator.ts"],"sourcesContent":["/*\nCopyright 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { type IMinimalEvent } from \"./sync-accumulator.ts\";\nimport { EventType } from \"./@types/event.ts\";\nimport { isSupportedReceiptType, MapWithDefault, recursiveMapToObject } from \"./utils.ts\";\nimport { type ReceiptContent, type ReceiptType } from \"./@types/read_receipts.ts\";\n\ninterface AccumulatedReceipt {\n data: IMinimalEvent;\n type: ReceiptType;\n eventId: string;\n}\n\n/**\n * Summarises the read receipts within a room. Used by the sync accumulator.\n *\n * Given receipts for users, picks the most recently-received one and provides\n * the results in a new fake receipt event returned from\n * buildAccumulatedReceiptEvent().\n *\n * Handles unthreaded receipts and receipts in each thread separately, so the\n * returned event contains the most recently received unthreaded receipt, and\n * the most recently received receipt in each thread.\n */\nexport class ReceiptAccumulator {\n /** user_id -\\> most-recently-received unthreaded receipt */\n private unthreadedReadReceipts: Map<string, AccumulatedReceipt> = new Map();\n\n /** thread_id -\\> user_id -\\> most-recently-received receipt for this thread */\n private threadedReadReceipts: MapWithDefault<string, Map<string, AccumulatedReceipt>> = new MapWithDefault(\n () => new Map(),\n );\n\n /**\n * Provide an unthreaded receipt for this user. Overwrites any other\n * unthreaded receipt we have for this user.\n */\n private setUnthreaded(userId: string, receipt: AccumulatedReceipt): void {\n this.unthreadedReadReceipts.set(userId, receipt);\n }\n\n /**\n * Provide a receipt for this user in this thread. Overwrites any other\n * receipt we have for this user in this thread.\n */\n private setThreaded(threadId: string, userId: string, receipt: AccumulatedReceipt): void {\n this.threadedReadReceipts.getOrCreate(threadId).set(userId, receipt);\n }\n\n /**\n * @returns an iterator of pairs of [userId, AccumulatedReceipt] - all the\n * most recently-received unthreaded receipts for each user.\n * @yields pairs of [userId, AccumulatedReceipt]\n */\n private allUnthreaded(): IterableIterator<[string, AccumulatedReceipt]> {\n return this.unthreadedReadReceipts.entries();\n }\n\n /**\n * @returns an iterator of pairs of [userId, AccumulatedReceipt] - all the\n * most recently-received threaded receipts for each user, in all\n * threads.\n * @yields pairs of [userId, AccumulatedReceipt]\n */\n private *allThreaded(): IterableIterator<[string, AccumulatedReceipt]> {\n for (const receiptsForThread of this.threadedReadReceipts.values()) {\n for (const e of receiptsForThread.entries()) {\n yield e;\n }\n }\n }\n\n /**\n * Given a list of ephemeral events, find the receipts and store the\n * relevant ones to be returned later from buildAccumulatedReceiptEvent().\n */\n public consumeEphemeralEvents(events: IMinimalEvent[] | undefined): void {\n events?.forEach((e) => {\n if (e.type !== EventType.Receipt || !e.content) {\n // This means we'll drop unknown ephemeral events but that\n // seems okay.\n return;\n }\n\n // Handle m.receipt events. They clobber based on:\n // (user_id, receipt_type)\n // but they are keyed in the event as:\n // content:{ $event_id: { $receipt_type: { $user_id: {json} }}}\n // so store them in the former so we can accumulate receipt deltas\n // quickly and efficiently (we expect a lot of them). Fold the\n // receipt type into the key name since we only have 1 at the\n // moment (m.read) and nested JSON objects are slower and more\n // of a hassle to work with. We'll inflate this back out when\n // getJSON() is called.\n Object.keys(e.content).forEach((eventId) => {\n Object.entries<ReceiptContent>(e.content[eventId]).forEach(([key, value]) => {\n if (!isSupportedReceiptType(key)) return;\n\n for (const userId of Object.keys(value)) {\n const data = e.content[eventId][key][userId];\n\n const receipt = {\n data: e.content[eventId][key][userId],\n type: key as ReceiptType,\n eventId,\n };\n\n // In a world that supports threads, read receipts normally have\n // a `thread_id` which is either the thread they belong in or\n // `MAIN_ROOM_TIMELINE`, so we normally use `setThreaded(...)`\n // here. The `MAIN_ROOM_TIMELINE` is just treated as another\n // thread.\n //\n // We still encounter read receipts that are \"unthreaded\"\n // (missing the `thread_id` property). These come from clients\n // that don't support threads, and from threaded clients that\n // are doing a \"Mark room as read\" operation. Unthreaded\n // receipts mark everything \"before\" them as read, in all\n // threads, where \"before\" means in Sync Order i.e. the order\n // the events were received from the homeserver in a sync.\n // [Note: we have some bugs where we use timestamp order instead\n // of Sync Order, because we don't correctly remember the Sync\n // Order. See #3325.]\n //\n // Calling the wrong method will cause incorrect behavior like\n // messages re-appearing as \"new\" when you already read them\n // previously.\n if (!data.thread_id) {\n this.setUnthreaded(userId, receipt);\n } else {\n this.setThreaded(data.thread_id, userId, receipt);\n }\n }\n });\n });\n });\n }\n\n /**\n * Build a receipt event that contains all relevant information for this\n * room, taking the most recently received receipt for each user in an\n * unthreaded context, and in each thread.\n */\n public buildAccumulatedReceiptEvent(roomId: string): IMinimalEvent | null {\n const receiptEvent: IMinimalEvent = {\n type: EventType.Receipt,\n room_id: roomId,\n content: {\n // $event_id: { \"m.read\": { $user_id: $json } }\n },\n };\n\n const receiptEventContent: MapWithDefault<\n string,\n MapWithDefault<ReceiptType, Map<string, object>>\n > = new MapWithDefault(() => new MapWithDefault(() => new Map()));\n\n for (const [userId, receiptData] of this.allUnthreaded()) {\n receiptEventContent\n .getOrCreate(receiptData.eventId)\n .getOrCreate(receiptData.type)\n .set(userId, receiptData.data);\n }\n\n for (const [userId, receiptData] of this.allThreaded()) {\n receiptEventContent\n .getOrCreate(receiptData.eventId)\n .getOrCreate(receiptData.type)\n .set(userId, receiptData.data);\n }\n\n receiptEvent.content = recursiveMapToObject(receiptEventContent);\n\n return receiptEventContent.size > 0 ? receiptEvent : null;\n }\n}\n"],"mappings":";AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAGA,SAAS,SAAS,QAAQ,mBAAmB;AAC7C,SAAS,sBAAsB,EAAE,cAAc,EAAE,oBAAoB,QAAQ,YAAY;AASzF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,MAAM,kBAAkB,CAAC;EAAA;IAC5B;IAAA,gDACkE,IAAI,GAAG,CAAC,CAAC;IAE3E;IAAA,8CACwF,IAAI,cAAc,CACtG,MAAM,IAAI,GAAG,CAAC,CAClB,CAAC;EAAA;EAED;AACJ;AACA;AACA;EACY,aAAa,CAAC,MAAc,EAAE,OAA2B,EAAQ;IACrE,IAAI,CAAC,sBAAsB,CAAC,GAAG,CAAC,MAAM,EAAE,OAAO,CAAC;EACpD;;EAEA;AACJ;AACA;AACA;EACY,WAAW,CAAC,QAAgB,EAAE,MAAc,EAAE,OAA2B,EAAQ;IACrF,IAAI,CAAC,oBAAoB,CAAC,WAAW,CAAC,QAAQ,CAAC,CAAC,GAAG,C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GG;IACU,YAAY,IAAI,OAAO,CAAC;QAAE,OAAO,CAAC,EAAE,IAAI,CAAC,cAAc,EAAE,MAAM,CAAC,CAAA;KAAE,CAAC,CAuF/E;YAEa,OAAO;YAIP,IAAI;IAIlB;;OAEG;IACU,4BAA4B,IAAI,OAAO,CAAC,IAAI,CAAC,CAQzD;IAED;;;OAGG;IACU,MAAM,CAAC,MAAM,EAAE,oBAAoB,GAAG,6BAA6B,GAAG,OAAO,CAAC,IAAI,CAAC,CAG/F;IAED;;OAEG;IACU,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAElC;CACJ"}
@@ -307,11 +307,10 @@ export class MSC4108SignInWithQR {
307
307
  } else if (res.error === "access_denied") {
308
308
  reason = MSC4108FailureReason.UserCancelled;
309
309
  }
310
- const payload = {
310
+ await this.send({
311
311
  type: PayloadType.Failure,
312
312
  reason
313
- };
314
- await this.send(payload);
313
+ });
315
314
  throw new RendezvousError("Rejection from device authorization endpoint", reason);
316
315
  }
317
316
  return res;
@@ -1 +1 @@
1
- {"version":3,"file":"MSC4108SignInWithQR.js","names":[],"sources":["../../src/rendezvous/MSC4108SignInWithQR.ts"],"sourcesContent":["/*\nCopyright 2024 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { QrCodeIntent } from \"@matrix-org/matrix-sdk-crypto-wasm\";\n\nimport {\n ClientRendezvousFailureReason,\n MSC4108FailureReason,\n RendezvousError,\n type RendezvousFailureListener,\n} from \"./index.ts\";\nimport { type MatrixClient } from \"../client.ts\";\nimport { logger } from \"../logger.ts\";\nimport { type MSC4108SecureChannel } from \"./channels/MSC4108SecureChannel.ts\";\nimport { MatrixError } from \"../http-api/index.ts\";\nimport { sleep } from \"../utils.ts\";\nimport {\n type DeviceAccessTokenResponse,\n type DeviceAuthorizationResponse,\n generateScope,\n OAuthGrantType,\n startDeviceAuthorization,\n type ValidatedAuthMetadata,\n waitForDeviceAuthorization,\n} from \"../oauth/index.ts\";\nimport { type CryptoApi } from \"../crypto-api/index.ts\";\n\n/**\n * Enum representing the payload types transmissible over [MSC4108](https://github.com/matrix-org/matrix-spec-proposals/pull/4108)\n * secure channels.\n * @experimental Note that this is UNSTABLE and may have breaking changes without notice.\n */\nexport enum PayloadType {\n Protocols = \"m.login.protocols\",\n Protocol = \"m.login.protocol\",\n Failure = \"m.login.failure\",\n Success = \"m.login.success\",\n Secrets = \"m.login.secrets\",\n ProtocolAccepted = \"m.login.protocol_accepted\",\n Declined = \"m.login.declined\",\n}\n\n/**\n * Type representing the base payload format for [MSC4108](https://github.com/matrix-org/matrix-spec-proposals/pull/4108)\n * messages sent over the secure channel.\n * @experimental Note that this is UNSTABLE and may have breaking changes without notice.\n */\nexport interface MSC4108Payload {\n type: PayloadType;\n}\n\ninterface ProtocolsPayload extends MSC4108Payload {\n type: PayloadType.Protocols;\n protocols: string[];\n homeserver: string;\n}\n\ninterface ProtocolPayload extends MSC4108Payload {\n type: PayloadType.Protocol;\n protocol: Exclude<string, \"device_authorization_grant\">;\n device_id: string;\n}\n\ninterface DeviceAuthorizationGrantProtocolPayload extends ProtocolPayload {\n protocol: \"device_authorization_grant\";\n device_authorization_grant: {\n verification_uri: string;\n verification_uri_complete?: string;\n };\n}\n\nfunction isDeviceAuthorizationGrantProtocolPayload(\n payload: ProtocolPayload,\n): payload is DeviceAuthorizationGrantProtocolPayload {\n return payload.protocol === \"device_authorization_grant\";\n}\n\ninterface FailurePayload extends MSC4108Payload {\n type: PayloadType.Failure;\n reason: MSC4108FailureReason;\n homeserver?: string;\n}\n\ninterface DeclinedPayload extends MSC4108Payload {\n type: PayloadType.Declined;\n}\n\ninterface SuccessPayload extends MSC4108Payload {\n type: PayloadType.Success;\n}\n\ninterface AcceptedPayload extends MSC4108Payload {\n type: PayloadType.ProtocolAccepted;\n}\n\ninterface SecretsPayload extends MSC4108Payload, Awaited<ReturnType<NonNullable<CryptoApi[\"exportSecretsBundle\"]>>> {\n type: PayloadType.Secrets;\n}\n\n/**\n * Prototype of the unstable [MSC4108](https://github.com/matrix-org/matrix-spec-proposals/pull/4108)\n * sign in with QR + OAuth2 flow.\n * @experimental Note that this is UNSTABLE and may have breaking changes without notice.\n */\nexport class MSC4108SignInWithQR {\n private readonly ourIntent: QrCodeIntent;\n private _code?: Uint8Array;\n private expectingNewDeviceId?: string;\n private metadata?: ValidatedAuthMetadata;\n private grantInProgress?: DeviceAuthorizationResponse;\n\n /**\n * Returns the check code for the secure channel or undefined if not generated yet.\n */\n public get checkCode(): string | undefined {\n return this.channel?.getCheckCode();\n }\n\n /**\n * @param channel - The secure channel used for communication\n * @param client - The Matrix client in used on the device already logged in\n * @param didScanCode - Whether this side of the channel scanned the QR code from the other party\n * @param onFailure - Callback for when the rendezvous fails\n */\n public constructor(\n private readonly channel: MSC4108SecureChannel,\n private readonly didScanCode: boolean,\n private readonly client?: MatrixClient,\n public onFailure?: RendezvousFailureListener,\n ) {\n this.ourIntent = client ? QrCodeIntent.Reciprocate : QrCodeIntent.Login;\n }\n\n /**\n * Returns the code representing the rendezvous suitable for rendering in a QR code or undefined if not generated yet.\n */\n public get code(): Uint8Array | undefined {\n return this._code;\n }\n\n /**\n * Generate the code including doing partial set up of the channel where required.\n */\n public async generateCode(): Promise<void> {\n if (this._code) {\n return;\n }\n\n if (this.ourIntent === QrCodeIntent.Reciprocate && this.client) {\n this._code = await this.channel.generateCode(this.ourIntent, this.client.getDomain()!);\n } else if (this.ourIntent === QrCodeIntent.Login) {\n this._code = await this.channel.generateCode(this.ourIntent);\n }\n }\n\n /**\n * Returns true if the device is the already logged in device reciprocating a new login on the other side of the channel.\n */\n public get isExistingDevice(): boolean {\n return this.ourIntent === QrCodeIntent.Reciprocate;\n }\n\n /**\n * Returns true if the device is the new device logging in being reciprocated by the device on the other side of the channel.\n */\n public get isNewDevice(): boolean {\n return !this.isExistingDevice;\n }\n\n /**\n * The first step in the OAuth2 QR login process.\n * To be called after the QR code has been rendered or scanned.\n * The scanning device has to discover the homeserver details, if they scanned the code then they already have it.\n * If the new device is the one rendering the QR code then it has to wait be sent the homeserver details via the rendezvous channel.\n */\n public async negotiateProtocols(): Promise<{ serverName?: string }> {\n logger.info(`negotiateProtocols(isNewDevice=${this.isNewDevice} didScanCode=${this.didScanCode})`);\n await this.channel.connect();\n\n if (this.didScanCode) {\n // Secure Channel step 6 completed, we trust the channel\n\n if (this.isNewDevice) {\n // MSC4108-Flow: ExistingScanned - take homeserver from QR code which should already be set\n } else {\n // MSC4108-Flow: NewScanned -send protocols message\n let authMetadata: ValidatedAuthMetadata | undefined;\n try {\n authMetadata = await this.client!.getAuthMetadata();\n } catch (e) {\n logger.error(\"Failed to discover OAuth2 metadata\", e);\n }\n\n if (authMetadata?.grant_types_supported.includes(OAuthGrantType.DeviceAuthorization)) {\n await this.send<ProtocolsPayload>({\n type: PayloadType.Protocols,\n protocols: [\"device_authorization_grant\"],\n homeserver: this.client!.getDomain()!,\n });\n } else {\n await this.send<FailurePayload>({\n type: PayloadType.Failure,\n reason: MSC4108FailureReason.UnsupportedProtocol,\n });\n throw new RendezvousError(\n \"Device code grant unsupported\",\n MSC4108FailureReason.UnsupportedProtocol,\n );\n }\n }\n } else if (this.isNewDevice) {\n // MSC4108-Flow: ExistingScanned - wait for protocols message\n logger.info(\"Waiting for protocols message\");\n const payload = await this.receive<ProtocolsPayload>();\n\n if (payload?.type === PayloadType.Failure) {\n throw new RendezvousError(\"Failed\", payload.reason);\n }\n\n if (payload?.type !== PayloadType.Protocols) {\n await this.send<FailurePayload>({\n type: PayloadType.Failure,\n reason: MSC4108FailureReason.UnexpectedMessageReceived,\n });\n throw new RendezvousError(\n \"Unexpected message received\",\n MSC4108FailureReason.UnexpectedMessageReceived,\n );\n }\n\n return { serverName: payload.homeserver };\n } else {\n // MSC4108-Flow: NewScanned - nothing to do\n }\n return {};\n }\n\n /**\n * The second & third step in the OAuth2 QR login process.\n * To be called after `negotiateProtocols` for the existing device.\n * To be called after OAuth2 negotiation for the new device.\n *\n * @param input - Required for the new device to start the device authorization grant, not required for the existing device reciprocating the login\n */\n public async deviceAuthorizationGrant(input?: {\n metadata: ValidatedAuthMetadata;\n clientId: string;\n deviceId: string;\n }): Promise<{\n verificationUri?: string;\n userCode?: string;\n }> {\n if (this.isNewDevice) {\n if (!input) {\n throw new Error(\"Input must be provided for new device\");\n }\n\n const { metadata, clientId, deviceId } = input;\n\n const scope = generateScope(deviceId);\n\n // MSC4108-Flow: NewDevice - start device authorization grant\n const dagResponse = await startDeviceAuthorization({\n clientId,\n scope,\n metadata,\n });\n\n this.metadata = metadata;\n this.grantInProgress = dagResponse;\n\n const protocol: DeviceAuthorizationGrantProtocolPayload = {\n type: PayloadType.Protocol,\n protocol: \"device_authorization_grant\",\n device_id: deviceId,\n device_authorization_grant: {\n verification_uri: dagResponse.verification_uri,\n verification_uri_complete: dagResponse.verification_uri_complete,\n },\n };\n\n await this.send(protocol);\n\n return {\n verificationUri: dagResponse.verification_uri_complete ?? dagResponse.verification_uri,\n userCode: dagResponse.user_code,\n };\n } else {\n // The user needs to do step 7 for the out-of-band confirmation\n // but, first we receive the protocol chosen by the other device so that\n // the confirmation_uri is ready to go\n logger.info(\"Waiting for protocol message\");\n const payload = await this.receive<ProtocolPayload | DeviceAuthorizationGrantProtocolPayload>();\n\n if (payload?.type === PayloadType.Failure) {\n throw new RendezvousError(\"Failed\", payload.reason);\n }\n\n if (payload?.type !== PayloadType.Protocol) {\n await this.send<FailurePayload>({\n type: PayloadType.Failure,\n reason: MSC4108FailureReason.UnexpectedMessageReceived,\n });\n throw new RendezvousError(\n \"Unexpected message received\",\n MSC4108FailureReason.UnexpectedMessageReceived,\n );\n }\n\n if (isDeviceAuthorizationGrantProtocolPayload(payload)) {\n const { device_authorization_grant: dag, device_id: expectingNewDeviceId } = payload;\n const { verification_uri: verificationUri, verification_uri_complete: verificationUriComplete } = dag;\n\n let deviceAlreadyExists = true;\n try {\n await this.client?.getDevice(expectingNewDeviceId);\n } catch (err: MatrixError | unknown) {\n if (err instanceof MatrixError && err.httpStatus === 404) {\n deviceAlreadyExists = false;\n }\n }\n\n if (deviceAlreadyExists) {\n await this.send<FailurePayload>({\n type: PayloadType.Failure,\n reason: MSC4108FailureReason.DeviceAlreadyExists,\n });\n throw new RendezvousError(\n \"Specified device ID already exists\",\n MSC4108FailureReason.DeviceAlreadyExists,\n );\n }\n\n this.expectingNewDeviceId = expectingNewDeviceId;\n\n return { verificationUri: verificationUriComplete ?? verificationUri };\n }\n\n await this.send<FailurePayload>({\n type: PayloadType.Failure,\n reason: MSC4108FailureReason.UnsupportedProtocol,\n });\n throw new RendezvousError(\n \"Received a request for an unsupported protocol\",\n MSC4108FailureReason.UnsupportedProtocol,\n );\n }\n }\n\n /**\n * The fourth step in the OAuth2 QR login process.\n * The reciprocating device must perform step 5 for this method to resolve.\n * To be called after {@link deviceAuthorizationGrant} only on the new device.\n */\n public async completeLoginOnNewDevice({\n clientId,\n }: {\n clientId: string;\n }): Promise<DeviceAccessTokenResponse | undefined> {\n if (!this.isNewDevice || !this.grantInProgress || !this.metadata) {\n throw new Error(\"Can only complete login on new device\");\n }\n\n logger.info(\"Waiting for protocol accepted message\");\n // wait for accepted message\n const payload = await this.receive<AcceptedPayload | FailurePayload>();\n\n if (!payload) {\n throw new RendezvousError(\n \"No response from existing device\",\n MSC4108FailureReason.UnexpectedMessageReceived,\n );\n }\n if (payload.type === PayloadType.Failure) {\n throw new RendezvousError(\"Failed\", (payload as FailurePayload).reason);\n }\n if (payload.type !== PayloadType.ProtocolAccepted) {\n throw new RendezvousError(\"Unexpected message received\", MSC4108FailureReason.UnexpectedMessageReceived);\n }\n\n // poll for DAG\n const res = await waitForDeviceAuthorization({\n session: this.grantInProgress,\n metadata: this.metadata,\n clientId,\n });\n\n if (!res) {\n throw new RendezvousError(\n \"No response from device authorization endpoint\",\n ClientRendezvousFailureReason.Unknown,\n );\n }\n\n if (\"error\" in res) {\n let reason: MSC4108FailureReason = MSC4108FailureReason.UnexpectedMessageReceived;\n if (res.error === \"expired_token\") {\n reason = MSC4108FailureReason.AuthorizationExpired;\n } else if (res.error === \"access_denied\") {\n reason = MSC4108FailureReason.UserCancelled;\n }\n const payload: FailurePayload = {\n type: PayloadType.Failure,\n reason,\n };\n await this.send(payload);\n\n throw new RendezvousError(\"Rejection from device authorization endpoint\", reason);\n }\n\n return res;\n }\n\n /**\n * The fifth (and final) step in the OAuth2 QR login process.\n * To be called after the new device has completed authentication.\n */\n public async shareSecrets(): Promise<{ secrets?: Omit<SecretsPayload, \"type\"> }> {\n if (this.isNewDevice) {\n await this.send<SuccessPayload>({\n type: PayloadType.Success,\n });\n // then wait for secrets\n logger.info(\"Waiting for secrets message\");\n const payload = await this.receive<SecretsPayload>();\n if (payload?.type === PayloadType.Failure) {\n throw new RendezvousError(\"Failed\", payload.reason);\n }\n\n if (payload?.type !== PayloadType.Secrets) {\n await this.send<FailurePayload>({\n type: PayloadType.Failure,\n reason: MSC4108FailureReason.UnexpectedMessageReceived,\n });\n throw new RendezvousError(\n \"Unexpected message received\",\n MSC4108FailureReason.UnexpectedMessageReceived,\n );\n }\n return { secrets: payload };\n // then done?\n } else {\n if (!this.expectingNewDeviceId) {\n throw new Error(\"No new device ID expected\");\n }\n await this.send<AcceptedPayload>({\n type: PayloadType.ProtocolAccepted,\n });\n\n logger.info(\"Waiting for outcome message\");\n const payload = await this.receive<SuccessPayload | DeclinedPayload>();\n\n if (payload?.type === PayloadType.Failure) {\n throw new RendezvousError(\"Failed\", payload.reason);\n }\n\n if (payload?.type === PayloadType.Declined) {\n throw new RendezvousError(\"User declined\", ClientRendezvousFailureReason.UserDeclined);\n }\n\n if (payload?.type !== PayloadType.Success) {\n await this.send<FailurePayload>({\n type: PayloadType.Failure,\n reason: MSC4108FailureReason.UnexpectedMessageReceived,\n });\n throw new RendezvousError(\"Unexpected message\", MSC4108FailureReason.UnexpectedMessageReceived);\n }\n\n const timeout = Date.now() + 10000; // wait up to 10 seconds\n do {\n // is the device visible via the Homeserver?\n try {\n const device = await this.client?.getDevice(this.expectingNewDeviceId);\n\n if (device) {\n // if so, return the secrets\n const secretsBundle = await this.client!.getCrypto()!.exportSecretsBundle!();\n if (this.channel.cancelled) {\n throw new RendezvousError(\"User cancelled\", MSC4108FailureReason.UserCancelled);\n }\n // send secrets\n await this.send<SecretsPayload>({\n type: PayloadType.Secrets,\n ...secretsBundle,\n });\n return { secrets: secretsBundle };\n // let the other side close the rendezvous session\n }\n } catch (err: MatrixError | unknown) {\n if (err instanceof MatrixError && err.httpStatus === 404) {\n // not found, so keep waiting until timeout\n } else {\n throw err;\n }\n }\n await sleep(1000);\n } while (Date.now() < timeout);\n\n await this.send<FailurePayload>({\n type: PayloadType.Failure,\n reason: MSC4108FailureReason.DeviceNotFound,\n });\n throw new RendezvousError(\"New device not found\", MSC4108FailureReason.DeviceNotFound);\n }\n }\n\n private async receive<T extends MSC4108Payload>(): Promise<T | FailurePayload | undefined> {\n return (await this.channel.secureReceive()) as T | undefined;\n }\n\n private async send<T extends MSC4108Payload>(payload: T): Promise<void> {\n await this.channel.secureSend(payload);\n }\n\n /**\n * Decline the login on the existing device.\n */\n public async declineLoginOnExistingDevice(): Promise<void> {\n if (!this.isExistingDevice) {\n throw new Error(\"Can only decline login on existing device\");\n }\n await this.send<FailurePayload>({\n type: PayloadType.Failure,\n reason: MSC4108FailureReason.UserCancelled,\n });\n }\n\n /**\n * Cancels the rendezvous session.\n * @param reason the reason for the cancellation\n */\n public async cancel(reason: MSC4108FailureReason | ClientRendezvousFailureReason): Promise<void> {\n this.onFailure?.(reason);\n await this.channel.cancel(reason);\n }\n\n /**\n * Closes the rendezvous session.\n */\n public async close(): Promise<void>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QACJ;QACA,MAAM,KAAK,CAAC,IAAI,CAAC;MACrB,CAAC,QAAQ,IAAI,CAAC,GAAG,CAAC,CAAC,GAAG,OAAO;MAE7B,MAAM,IAAI,CAAC,IAAI,CAAiB;QAC5B,IAAI,EAAE,WAAW,CAAC,OAAO;QACzB,MAAM,EAAE,oBAAoB,CAAC;MACjC,CAAC,CAAC;MACF,MAAM,IAAI,eAAe,CAAC,sBAAsB,EAAE,oBAAoB,CAAC,cAAc,CAAC;IAC1F;EACJ;EAEA,MAAc,OAAO,GAAsE;IACvF,OAAQ,MAAM,IAAI,CAAC,OAAO,CAAC,aAAa,CAAC,CAAC;EAC9C;EAEA,MAAc,IAAI,CAA2B,OAAU,EAAiB;IACpE,MAAM,IAAI,CAAC,OAAO,CAAC,UAAU,CAAC,OAAO,CAAC;EAC1C;;EAEA;AACJ;AACA;EACI,MAAa,4BAA4B,GAAkB;IACvD,IAAI,CAAC,IAAI,CAAC,gBAAgB,EAAE;MACxB,MAAM,IAAI,KAAK,CAAC,2CAA2C,CAAC;IAChE;IACA,MAAM,IAAI,CAAC,IAAI,CAAiB;MAC5B,IAAI,EAAE,WAAW,CAAC,OAAO;MACzB,MAAM,EAAE,oBAAoB,CAAC;IACjC,CAAC,CAAC;EACN;;EAEA;AACJ;AACA;AACA;EACI,MAAa,MAAM,CAAC,MAA4D,EAAiB;IAC7F,IAAI,CAAC,SAAS,GAAG,MAAM,CAAC;IACxB,MAAM,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC;EACrC;;EAEA;AACJ;AACA;EACI,MAAa,KAAK,GAAkB;IAChC,MAAM,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;EAC9B;AACJ","ignoreList":[]}
1
+ {"version":3,"file":"MSC4108SignInWithQR.js","names":[],"sources":["../../src/rendezvous/MSC4108SignInWithQR.ts"],"sourcesContent":["/*\nCopyright 2024 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { QrCodeIntent } from \"@matrix-org/matrix-sdk-crypto-wasm\";\n\nimport {\n ClientRendezvousFailureReason,\n MSC4108FailureReason,\n RendezvousError,\n type RendezvousFailureListener,\n} from \"./index.ts\";\nimport { type MatrixClient } from \"../client.ts\";\nimport { logger } from \"../logger.ts\";\nimport { type MSC4108SecureChannel } from \"./channels/MSC4108SecureChannel.ts\";\nimport { MatrixError } from \"../http-api/index.ts\";\nimport { sleep } from \"../utils.ts\";\nimport {\n type DeviceAccessTokenResponse,\n type DeviceAuthorizationResponse,\n generateScope,\n OAuthGrantType,\n startDeviceAuthorization,\n type ValidatedAuthMetadata,\n waitForDeviceAuthorization,\n} from \"../oauth/index.ts\";\nimport { type CryptoApi } from \"../crypto-api/index.ts\";\n\n/**\n * Enum representing the payload types transmissible over [MSC4108](https://github.com/matrix-org/matrix-spec-proposals/pull/4108)\n * secure channels.\n * @experimental Note that this is UNSTABLE and may have breaking changes without notice.\n */\nexport enum PayloadType {\n Protocols = \"m.login.protocols\",\n Protocol = \"m.login.protocol\",\n Failure = \"m.login.failure\",\n Success = \"m.login.success\",\n Secrets = \"m.login.secrets\",\n ProtocolAccepted = \"m.login.protocol_accepted\",\n Declined = \"m.login.declined\",\n}\n\n/**\n * Type representing the base payload format for [MSC4108](https://github.com/matrix-org/matrix-spec-proposals/pull/4108)\n * messages sent over the secure channel.\n * @experimental Note that this is UNSTABLE and may have breaking changes without notice.\n */\nexport interface MSC4108Payload {\n type: PayloadType;\n}\n\ninterface ProtocolsPayload extends MSC4108Payload {\n type: PayloadType.Protocols;\n protocols: string[];\n homeserver: string;\n}\n\ninterface ProtocolPayload extends MSC4108Payload {\n type: PayloadType.Protocol;\n protocol: Exclude<string, \"device_authorization_grant\">;\n device_id: string;\n}\n\ninterface DeviceAuthorizationGrantProtocolPayload extends ProtocolPayload {\n protocol: \"device_authorization_grant\";\n device_authorization_grant: {\n verification_uri: string;\n verification_uri_complete?: string;\n };\n}\n\nfunction isDeviceAuthorizationGrantProtocolPayload(\n payload: ProtocolPayload,\n): payload is DeviceAuthorizationGrantProtocolPayload {\n return payload.protocol === \"device_authorization_grant\";\n}\n\ninterface FailurePayload extends MSC4108Payload {\n type: PayloadType.Failure;\n reason: MSC4108FailureReason;\n homeserver?: string;\n}\n\ninterface DeclinedPayload extends MSC4108Payload {\n type: PayloadType.Declined;\n}\n\ninterface SuccessPayload extends MSC4108Payload {\n type: PayloadType.Success;\n}\n\ninterface AcceptedPayload extends MSC4108Payload {\n type: PayloadType.ProtocolAccepted;\n}\n\ninterface SecretsPayload extends MSC4108Payload, Awaited<ReturnType<NonNullable<CryptoApi[\"exportSecretsBundle\"]>>> {\n type: PayloadType.Secrets;\n}\n\n/**\n * Prototype of the unstable [MSC4108](https://github.com/matrix-org/matrix-spec-proposals/pull/4108)\n * sign in with QR + OAuth2 flow.\n * @experimental Note that this is UNSTABLE and may have breaking changes without notice.\n */\nexport class MSC4108SignInWithQR {\n private readonly ourIntent: QrCodeIntent;\n private _code?: Uint8Array;\n private expectingNewDeviceId?: string;\n private metadata?: ValidatedAuthMetadata;\n private grantInProgress?: DeviceAuthorizationResponse;\n\n /**\n * Returns the check code for the secure channel or undefined if not generated yet.\n */\n public get checkCode(): string | undefined {\n return this.channel?.getCheckCode();\n }\n\n /**\n * @param channel - The secure channel used for communication\n * @param client - The Matrix client in used on the device already logged in\n * @param didScanCode - Whether this side of the channel scanned the QR code from the other party\n * @param onFailure - Callback for when the rendezvous fails\n */\n public constructor(\n private readonly channel: MSC4108SecureChannel,\n private readonly didScanCode: boolean,\n private readonly client?: MatrixClient,\n public onFailure?: RendezvousFailureListener,\n ) {\n this.ourIntent = client ? QrCodeIntent.Reciprocate : QrCodeIntent.Login;\n }\n\n /**\n * Returns the code representing the rendezvous suitable for rendering in a QR code or undefined if not generated yet.\n */\n public get code(): Uint8Array | undefined {\n return this._code;\n }\n\n /**\n * Generate the code including doing partial set up of the channel where required.\n */\n public async generateCode(): Promise<void> {\n if (this._code) {\n return;\n }\n\n if (this.ourIntent === QrCodeIntent.Reciprocate && this.client) {\n this._code = await this.channel.generateCode(this.ourIntent, this.client.getDomain()!);\n } else if (this.ourIntent === QrCodeIntent.Login) {\n this._code = await this.channel.generateCode(this.ourIntent);\n }\n }\n\n /**\n * Returns true if the device is the already logged in device reciprocating a new login on the other side of the channel.\n */\n public get isExistingDevice(): boolean {\n return this.ourIntent === QrCodeIntent.Reciprocate;\n }\n\n /**\n * Returns true if the device is the new device logging in being reciprocated by the device on the other side of the channel.\n */\n public get isNewDevice(): boolean {\n return !this.isExistingDevice;\n }\n\n /**\n * The first step in the OAuth2 QR login process.\n * To be called after the QR code has been rendered or scanned.\n * The scanning device has to discover the homeserver details, if they scanned the code then they already have it.\n * If the new device is the one rendering the QR code then it has to wait be sent the homeserver details via the rendezvous channel.\n */\n public async negotiateProtocols(): Promise<{ serverName?: string }> {\n logger.info(`negotiateProtocols(isNewDevice=${this.isNewDevice} didScanCode=${this.didScanCode})`);\n await this.channel.connect();\n\n if (this.didScanCode) {\n // Secure Channel step 6 completed, we trust the channel\n\n if (this.isNewDevice) {\n // MSC4108-Flow: ExistingScanned - take homeserver from QR code which should already be set\n } else {\n // MSC4108-Flow: NewScanned -send protocols message\n let authMetadata: ValidatedAuthMetadata | undefined;\n try {\n authMetadata = await this.client!.getAuthMetadata();\n } catch (e) {\n logger.error(\"Failed to discover OAuth2 metadata\", e);\n }\n\n if (authMetadata?.grant_types_supported.includes(OAuthGrantType.DeviceAuthorization)) {\n await this.send<ProtocolsPayload>({\n type: PayloadType.Protocols,\n protocols: [\"device_authorization_grant\"],\n homeserver: this.client!.getDomain()!,\n });\n } else {\n await this.send<FailurePayload>({\n type: PayloadType.Failure,\n reason: MSC4108FailureReason.UnsupportedProtocol,\n });\n throw new RendezvousError(\n \"Device code grant unsupported\",\n MSC4108FailureReason.UnsupportedProtocol,\n );\n }\n }\n } else if (this.isNewDevice) {\n // MSC4108-Flow: ExistingScanned - wait for protocols message\n logger.info(\"Waiting for protocols message\");\n const payload = await this.receive<ProtocolsPayload>();\n\n if (payload?.type === PayloadType.Failure) {\n throw new RendezvousError(\"Failed\", payload.reason);\n }\n\n if (payload?.type !== PayloadType.Protocols) {\n await this.send<FailurePayload>({\n type: PayloadType.Failure,\n reason: MSC4108FailureReason.UnexpectedMessageReceived,\n });\n throw new RendezvousError(\n \"Unexpected message received\",\n MSC4108FailureReason.UnexpectedMessageReceived,\n );\n }\n\n return { serverName: payload.homeserver };\n } else {\n // MSC4108-Flow: NewScanned - nothing to do\n }\n return {};\n }\n\n /**\n * The second & third step in the OAuth2 QR login process.\n * To be called after `negotiateProtocols` for the existing device.\n * To be called after OAuth2 negotiation for the new device.\n *\n * @param input - Required for the new device to start the device authorization grant, not required for the existing device reciprocating the login\n */\n public async deviceAuthorizationGrant(input?: {\n metadata: ValidatedAuthMetadata;\n clientId: string;\n deviceId: string;\n }): Promise<{\n verificationUri?: string;\n userCode?: string;\n }> {\n if (this.isNewDevice) {\n if (!input) {\n throw new Error(\"Input must be provided for new device\");\n }\n\n const { metadata, clientId, deviceId } = input;\n\n const scope = generateScope(deviceId);\n\n // MSC4108-Flow: NewDevice - start device authorization grant\n const dagResponse = await startDeviceAuthorization({\n clientId,\n scope,\n metadata,\n });\n\n this.metadata = metadata;\n this.grantInProgress = dagResponse;\n\n const protocol: DeviceAuthorizationGrantProtocolPayload = {\n type: PayloadType.Protocol,\n protocol: \"device_authorization_grant\",\n device_id: deviceId,\n device_authorization_grant: {\n verification_uri: dagResponse.verification_uri,\n verification_uri_complete: dagResponse.verification_uri_complete,\n },\n };\n\n await this.send(protocol);\n\n return {\n verificationUri: dagResponse.verification_uri_complete ?? dagResponse.verification_uri,\n userCode: dagResponse.user_code,\n };\n } else {\n // The user needs to do step 7 for the out-of-band confirmation\n // but, first we receive the protocol chosen by the other device so that\n // the confirmation_uri is ready to go\n logger.info(\"Waiting for protocol message\");\n const payload = await this.receive<ProtocolPayload | DeviceAuthorizationGrantProtocolPayload>();\n\n if (payload?.type === PayloadType.Failure) {\n throw new RendezvousError(\"Failed\", payload.reason);\n }\n\n if (payload?.type !== PayloadType.Protocol) {\n await this.send<FailurePayload>({\n type: PayloadType.Failure,\n reason: MSC4108FailureReason.UnexpectedMessageReceived,\n });\n throw new RendezvousError(\n \"Unexpected message received\",\n MSC4108FailureReason.UnexpectedMessageReceived,\n );\n }\n\n if (isDeviceAuthorizationGrantProtocolPayload(payload)) {\n const { device_authorization_grant: dag, device_id: expectingNewDeviceId } = payload;\n const { verification_uri: verificationUri, verification_uri_complete: verificationUriComplete } = dag;\n\n let deviceAlreadyExists = true;\n try {\n await this.client?.getDevice(expectingNewDeviceId);\n } catch (err: MatrixError | unknown) {\n if (err instanceof MatrixError && err.httpStatus === 404) {\n deviceAlreadyExists = false;\n }\n }\n\n if (deviceAlreadyExists) {\n await this.send<FailurePayload>({\n type: PayloadType.Failure,\n reason: MSC4108FailureReason.DeviceAlreadyExists,\n });\n throw new RendezvousError(\n \"Specified device ID already exists\",\n MSC4108FailureReason.DeviceAlreadyExists,\n );\n }\n\n this.expectingNewDeviceId = expectingNewDeviceId;\n\n return { verificationUri: verificationUriComplete ?? verificationUri };\n }\n\n await this.send<FailurePayload>({\n type: PayloadType.Failure,\n reason: MSC4108FailureReason.UnsupportedProtocol,\n });\n throw new RendezvousError(\n \"Received a request for an unsupported protocol\",\n MSC4108FailureReason.UnsupportedProtocol,\n );\n }\n }\n\n /**\n * The fourth step in the OAuth2 QR login process.\n * The reciprocating device must perform step 5 for this method to resolve.\n * To be called after {@link deviceAuthorizationGrant} only on the new device.\n */\n public async completeLoginOnNewDevice({\n clientId,\n }: {\n clientId: string;\n }): Promise<DeviceAccessTokenResponse | undefined> {\n if (!this.isNewDevice || !this.grantInProgress || !this.metadata) {\n throw new Error(\"Can only complete login on new device\");\n }\n\n logger.info(\"Waiting for protocol accepted message\");\n // wait for accepted message\n const payload = await this.receive<AcceptedPayload | FailurePayload>();\n\n if (!payload) {\n throw new RendezvousError(\n \"No response from existing device\",\n MSC4108FailureReason.UnexpectedMessageReceived,\n );\n }\n if (payload.type === PayloadType.Failure) {\n throw new RendezvousError(\"Failed\", payload.reason);\n }\n if (payload.type !== PayloadType.ProtocolAccepted) {\n throw new RendezvousError(\"Unexpected message received\", MSC4108FailureReason.UnexpectedMessageReceived);\n }\n\n // poll for DAG\n const res = await waitForDeviceAuthorization({\n session: this.grantInProgress,\n metadata: this.metadata,\n clientId,\n });\n\n if (!res) {\n throw new RendezvousError(\n \"No response from device authorization endpoint\",\n ClientRendezvousFailureReason.Unknown,\n );\n }\n\n if (\"error\" in res) {\n let reason: MSC4108FailureReason = MSC4108FailureReason.UnexpectedMessageReceived;\n if (res.error === \"expired_token\") {\n reason = MSC4108FailureReason.AuthorizationExpired;\n } else if (res.error === \"access_denied\") {\n reason = MSC4108FailureReason.UserCancelled;\n }\n await this.send({\n type: PayloadType.Failure,\n reason,\n } satisfies FailurePayload);\n\n throw new RendezvousError(\"Rejection from device authorization endpoint\", reason);\n }\n\n return res;\n }\n\n /**\n * The fifth (and final) step in the OAuth2 QR login process.\n * To be called after the new device has completed authentication.\n */\n public async shareSecrets(): Promise<{ secrets?: Omit<SecretsPayload, \"type\"> }> {\n if (this.isNewDevice) {\n await this.send<SuccessPayload>({\n type: PayloadType.Success,\n });\n // then wait for secrets\n logger.info(\"Waiting for secrets message\");\n const payload = await this.receive<SecretsPayload>();\n if (payload?.type === PayloadType.Failure) {\n throw new RendezvousError(\"Failed\", payload.reason);\n }\n\n if (payload?.type !== PayloadType.Secrets) {\n await this.send<FailurePayload>({\n type: PayloadType.Failure,\n reason: MSC4108FailureReason.UnexpectedMessageReceived,\n });\n throw new RendezvousError(\n \"Unexpected message received\",\n MSC4108FailureReason.UnexpectedMessageReceived,\n );\n }\n return { secrets: payload };\n // then done?\n } else {\n if (!this.expectingNewDeviceId) {\n throw new Error(\"No new device ID expected\");\n }\n await this.send<AcceptedPayload>({\n type: PayloadType.ProtocolAccepted,\n });\n\n logger.info(\"Waiting for outcome message\");\n const payload = await this.receive<SuccessPayload | DeclinedPayload>();\n\n if (payload?.type === PayloadType.Failure) {\n throw new RendezvousError(\"Failed\", payload.reason);\n }\n\n if (payload?.type === PayloadType.Declined) {\n throw new RendezvousError(\"User declined\", ClientRendezvousFailureReason.UserDeclined);\n }\n\n if (payload?.type !== PayloadType.Success) {\n await this.send<FailurePayload>({\n type: PayloadType.Failure,\n reason: MSC4108FailureReason.UnexpectedMessageReceived,\n });\n throw new RendezvousError(\"Unexpected message\", MSC4108FailureReason.UnexpectedMessageReceived);\n }\n\n const timeout = Date.now() + 10000; // wait up to 10 seconds\n do {\n // is the device visible via the Homeserver?\n try {\n const device = await this.client?.getDevice(this.expectingNewDeviceId);\n\n if (device) {\n // if so, return the secrets\n const secretsBundle = await this.client!.getCrypto()!.exportSecretsBundle!();\n if (this.channel.cancelled) {\n throw new RendezvousError(\"User cancelled\", MSC4108FailureReason.UserCancelled);\n }\n // send secrets\n await this.send<SecretsPayload>({\n type: PayloadType.Secrets,\n ...secretsBundle,\n });\n return { secrets: secretsBundle };\n // let the other side close the rendezvous session\n }\n } catch (err: MatrixError | unknown) {\n if (err instanceof MatrixError && err.httpStatus === 404) {\n // not found, so keep waiting until timeout\n } else {\n throw err;\n }\n }\n await sleep(1000);\n } while (Date.now() < timeout);\n\n await this.send<FailurePayload>({\n type: PayloadType.Failure,\n reason: MSC4108FailureReason.DeviceNotFound,\n });\n throw new RendezvousError(\"New device not found\", MSC4108FailureReason.DeviceNotFound);\n }\n }\n\n private async receive<T extends MSC4108Payload>(): Promise<T | FailurePayload | undefined> {\n return (await this.channel.secureReceive()) as T | undefined;\n }\n\n private async send<T extends MSC4108Payload>(payload: T): Promise<void> {\n await this.channel.secureSend(payload);\n }\n\n /**\n * Decline the login on the existing device.\n */\n public async declineLoginOnExistingDevice(): Promise<void> {\n if (!this.isExistingDevice) {\n throw new Error(\"Can only decline login on existing device\");\n }\n await this.send<FailurePayload>({\n type: PayloadType.Failure,\n reason: MSC4108FailureReason.UserCancelled,\n });\n }\n\n /**\n * Cancels the rendezvous session.\n * @param reason the reason for the cancellation\n */\n public async cancel(reason: MSC4108FailureReason | ClientRendezvousFailureReason): Promise<void> {\n this.onFailure?.(reason);\n await this.channel.cancel(reason);\n }\n\n /**\n * Closes the rendezvous session.\n */\n public async close(): Promise<void> {\n await this.channel.close();\n }\n}\n"],"mappings":";;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAAS,YAAY,QAAQ,oCAAoC;AAEjE,SACI,6BAA6B,EAC7B,oBAAoB,EACpB,eAAe,QAEZ,YAAY;AAEnB,SAAS,MAAM,QAAQ,cAAc;AAErC,SAAS,WAAW,QAAQ,sBAAsB;AAClD,SAAS,KAAK,QAAQ,aAAa;AACnC,SAGI,aAAa,EACb,cAAc,EACd,wBAAwB,EAExB,0BAA0B,QACvB,mBAAmB;AAG1B;AACA;AACA;AACA;AACA;AACA,WAAY,WAAW,0BAAX,WAAW;EAAX,WAAW;EAAX,WAAW;EAAX,WAAW;EAAX,WAAW;EAAX,WAAW;EAAX,WAAW;EAAX,WAAW;EAAA,OAAX,WAAW;AAAA;;AAUvB;AACA;AACA;AACA;AACA;;AAyBA,SAAS,yCAAyC,CAC9C,OAAwB,EAC0B;EAClD,OAAO,OAAO,CAAC,QAAQ,KAAK,4BAA4B;AAC5D;AAwBA;AACA;AACA;AACA;AACA;AACA,OAAO,MAAM,mBAAmB,CAAC;EAO7B;AACJ;AACA;EACI,IAAW,SAAS,GAAuB;IACvC,OAAO,IAAI,CAAC,OAAO,EAAE,YAAY,CAAC,CAAC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,IAAI,CAAC,SAAS,GAAG,MAAM,CAAC;IACxB,MAAM,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC;EACrC;;EAEA;AACJ;AACA;EACI,MAAa,KAAK,GAAkB;IAChC,MAAM,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;EAC9B;AACJ","ignoreList":[]}
@@ -0,0 +1,9 @@
1
+ import { PollingCachedValue } from "./pollingCachedValue.ts";
2
+ import { type Transport } from "./matrixrtc/index.ts";
3
+ import { type MatrixClient } from "./client.ts";
4
+ import { type Logger } from "./logger.ts";
5
+ /**
6
+ * Builds a cache for the rtc/transport discovery end-point of the given client.
7
+ */
8
+ export declare function createRtcTransportsCachedValue(client: MatrixClient, logger: Logger): PollingCachedValue<Transport[]>;
9
+ //# sourceMappingURL=rtcTransportsCachedValue.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rtcTransportsCachedValue.d.ts","sourceRoot":"","sources":["../src/rtcTransportsCachedValue.ts"],"names":[],"mappings":"AAgBA,OAAO,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAC7D,OAAO,EAAE,KAAK,SAAS,EAAE,MAAM,sBAAsB,CAAC;AACtD,OAAO,EAAe,KAAK,YAAY,EAAE,MAAM,aAAa,CAAC;AAC7D,OAAO,EAAE,KAAK,MAAM,EAAE,MAAM,aAAa,CAAC;AAK1C;;GAEG;AACH,wBAAgB,8BAA8B,CAAC,MAAM,EAAE,YAAY,EAAE,MAAM,EAAE,MAAM,GAAG,kBAAkB,CAAC,SAAS,EAAE,CAAC,CAYpH"}
@@ -0,0 +1,38 @@
1
+ /*
2
+ Copyright 2026 The Matrix.org Foundation C.I.C.
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ */
16
+
17
+ import { PollingCachedValue } from "./pollingCachedValue.js";
18
+ import { ClientEvent } from "./client.js";
19
+ import { MatrixError } from "./http-api/index.js";
20
+ const TRANSPORT_CACHE_TTL_MILLISECONDS = 1000 * 60 * 60 * 24; // 1 day
21
+
22
+ /**
23
+ * Builds a cache for the rtc/transport discovery end-point of the given client.
24
+ */
25
+ export function createRtcTransportsCachedValue(client, logger) {
26
+ return new PollingCachedValue({
27
+ name: "RTCTransports",
28
+ logger,
29
+ ttlMillis: TRANSPORT_CACHE_TTL_MILLISECONDS,
30
+ fetch: () => client._unstable_getRTCTransports(),
31
+ onValueCached: transports => client.emit(ClientEvent.RtcTransportsUpdated, transports),
32
+ // If the end point is not supported by the homeserver it will be a 404 error.
33
+ // This is a final error, it can be cached, no need to retry everytime.
34
+ // It will retry when ttl has expired.
35
+ shouldCacheError: error => error instanceof MatrixError && error.httpStatus === 404
36
+ });
37
+ }
38
+ //# sourceMappingURL=rtcTransportsCachedValue.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rtcTransportsCachedValue.js","names":[],"sources":["../src/rtcTransportsCachedValue.ts"],"sourcesContent":["/*\nCopyright 2026 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { PollingCachedValue } from \"./pollingCachedValue.ts\";\nimport { type Transport } from \"./matrixrtc/index.ts\";\nimport { ClientEvent, type MatrixClient } from \"./client.ts\";\nimport { type Logger } from \"./logger.ts\";\nimport { MatrixError } from \"./http-api/index.ts\";\n\nconst TRANSPORT_CACHE_TTL_MILLISECONDS = 1000 * 60 * 60 * 24; // 1 day\n\n/**\n * Builds a cache for the rtc/transport discovery end-point of the given client.\n */\nexport function createRtcTransportsCachedValue(client: MatrixClient, logger: Logger): PollingCachedValue<Transport[]> {\n return new PollingCachedValue({\n name: \"RTCTransports\",\n logger,\n ttlMillis: TRANSPORT_CACHE_TTL_MILLISECONDS,\n fetch: () => client._unstable_getRTCTransports(),\n onValueCached: (transports) => client.emit(ClientEvent.RtcTransportsUpdated, transports),\n // If the end point is not supported by the homeserver it will be a 404 error.\n // This is a final error, it can be cached, no need to retry everytime.\n // It will retry when ttl has expired.\n shouldCacheError: (error) => error instanceof MatrixError && error.httpStatus === 404,\n });\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAAS,kBAAkB,QAAQ,yBAAyB;AAE5D,SAAS,WAAW,QAA2B,aAAa;AAE5D,SAAS,WAAW,QAAQ,qBAAqB;AAEjD,MAAM,gCAAgC,GAAG,IAAI,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,CAAC,CAAC;;AAE9D;AACA;AACA;AACA,OAAO,SAAS,8BAA8B,CAAC,MAAoB,EAAE,MAAc,EAAmC;EAClH,OAAO,IAAI,kBAAkB,CAAC;IAC1B,IAAI,EAAE,eAAe;IACrB,MAAM;IACN,SAAS,EAAE,gCAAgC;IAC3C,KAAK,EAAE,MAAM,MAAM,CAAC,0BAA0B,CAAC,CAAC;IAChD,aAAa,EAAG,UAAU,IAAK,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,oBAAoB,EAAE,UAAU,CAAC;IACxF;IACA;IACA;IACA,gBAAgB,EAAG,KAAK,IAAK,KAAK,YAAY,WAAW,IAAI,KAAK,CAAC,UAAU,KAAK;EACtF,CAAC,CAAC;AACN","ignoreList":[]}
@@ -1 +1 @@
1
- {"version":3,"file":"PerSessionKeyBackupDownloader.js","names":[],"sources":["../../src/rust-crypto/PerSessionKeyBackupDownloader.ts"],"sourcesContent":["/*\nCopyright 2023 - 2024 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { type OlmMachine } from \"@matrix-org/matrix-sdk-crypto-wasm\";\n\nimport type * as RustSdkCryptoJs from \"@matrix-org/matrix-sdk-crypto-wasm\";\nimport { type Curve25519AuthData, type KeyBackupInfo, type KeyBackupSession } from \"../crypto-api/keybackup.ts\";\nimport { CryptoEvent } from \"../crypto-api/index.ts\";\nimport { type Logger } from \"../logger.ts\";\nimport { ClientPrefix, type IHttpOpts, MatrixError, type MatrixHttpApi, Method } from \"../http-api/index.ts\";\nimport { type RustBackupManager } from \"./backup.ts\";\nimport { encodeUri, sleep } from \"../utils.ts\";\nimport { type BackupDecryptor } from \"../common-crypto/CryptoBackend.ts\";\n\n// The minimum time to wait between two retries in case of errors. To avoid hammering the server.\nconst KEY_BACKUP_BACKOFF = 5000; // ms\n\n/**\n * Enumerates the different kind of errors that can occurs when downloading and importing a key from backup.\n */\nenum KeyDownloadErrorCode {\n /** The requested key is not in the backup. */\n MISSING_DECRYPTION_KEY = \"MISSING_DECRYPTION_KEY\",\n /** A network error occurred while trying to download the key from backup. */\n NETWORK_ERROR = \"NETWORK_ERROR\",\n /** The loop has been stopped. */\n STOPPED = \"STOPPED\",\n}\n\nclass KeyDownloadError extends Error {\n public constructor(public readonly code: KeyDownloadErrorCode) {\n super(`Failed to get key from backup: ${code}`);\n this.name = \"KeyDownloadError\";\n }\n}\n\nclass KeyDownloadRateLimitError extends Error {\n public constructor(public readonly retryMillis: number) {\n super(`Failed to get key from backup: rate limited`);\n this.name = \"KeyDownloadRateLimitError\";\n }\n}\n\n/** Details of a megolm session whose key we are trying to fetch. */\ntype SessionInfo = { roomId: string; megolmSessionId: string };\n\n/** Holds the current backup decryptor and version that should be used.\n *\n * This is intended to be used as an immutable object (a new instance should be created if the configuration changes),\n * and some of the logic relies on that, so the properties are marked as `readonly`.\n */\ntype Configuration = {\n readonly backupVersion: string;\n readonly decryptor: BackupDecryptor;\n};\n\n/**\n * Used when an 'unable to decrypt' error occurs. It attempts to download the key from the backup.\n *\n * The current backup API lacks pagination, which can lead to lengthy key retrieval times for large histories (several 10s of minutes).\n * To mitigate this, keys are downloaded on demand as decryption errors occurs.\n * While this approach may result in numerous requests, it improves user experience by reducing wait times for message decryption.\n *\n * The PerSessionKeyBackupDownloader is resistant to backup configuration changes: it will automatically resume querying when\n * the backup is configured correctly.\n */\nexport class PerSessionKeyBackupDownloader {\n private stopped = false;\n\n /**\n * The version and decryption key to use with current backup if all set up correctly.\n *\n * Will not be set unless `hasConfigurationProblem` is `false`.\n */\n private configuration: Configuration | null = null;\n\n /** We remember when a session was requested and not found in backup to avoid query again too soon.\n * Map of session_id to timestamp */\n private sessionLastCheckAttemptedTime: Map<string, number> = new Map();\n\n /** The logger to use */\n private readonly logger: Logger;\n\n /** Whether the download loop is running. */\n private downloadLoopRunning = false;\n\n /** The list of requests that are queued. */\n private queuedRequests: SessionInfo[] = [];\n\n /** Remembers if we have a configuration problem. */\n private hasConfigurationProblem = false;\n\n /** The current server backup version check promise. To avoid doing a server call if one is in flight. */\n private currentBackupVersionCheck: Promise<Configuration | null> | null = null;\n\n /**\n * Creates a new instance of PerSessionKeyBackupDownloader.\n *\n * @param backupManager - The backup manager to use.\n * @param olmMachine - The olm machine to use.\n * @param http - The http instance to use.\n * @param logger - The logger to use.\n */\n public constructor(\n logger: Logger,\n private readonly olmMachine: OlmMachine,\n private readonly http: MatrixHttpApi<IHttpOpts & { onlyData: true }>,\n private readonly backupManager: RustBackupManager,\n ) {\n this.logger = logger.getChild(\"[PerSessionKeyBackupDownloader]\");\n\n backupManager.on(CryptoEvent.KeyBackupStatus, this.onBackupStatusChanged);\n backupManager.on(CryptoEvent.KeyBackupFailed, this.onBackupStatusChanged);\n backupManager.on(CryptoEvent.KeyBackupDecryptionKeyCached, this.onBackupStatusChanged);\n }\n\n /**\n * Check if key download is successfully configured and active.\n *\n * @returns `true` if key download is correctly configured and active; otherwise `false`.\n */\n public isKeyBackupDownloadConfigured(): boolean {\n return this.configuration !== null;\n }\n\n /**\n * Return the details of the latest backup on the server, when we last checked.\n *\n * This is just a convenience method to expose {@link RustBackupManager.getServerBackupInfo}.\n */\n public async getServerBackupInfo(): Promise<KeyBackupInfo | null | undefined> {\n return await this.backupManager.getServerBackupInfo();\n }\n\n /**\n * Called when a MissingRoomKey or UnknownMessageIndex decryption error is encountered.\n *\n * This will try to download the key from the backup if there is a trusted active backup.\n * In case of success the key will be imported and the onRoomKeysUpdated callback will be called\n * internally by the rust-sdk and decryption will be retried.\n *\n * @param roomId - The room ID of the room where the error occurred.\n * @param megolmSessionId - The megolm session ID that is missing.\n */\n public onDecryptionKeyMissingError(roomId: string, megolmSessionId: string): void {\n // Several messages encrypted with the same session may be decrypted at the same time,\n // so we need to be resistant and not query several time the same session.\n if (this.isAlreadyInQueue(roomId, megolmSessionId)) {\n // There is already a request queued for this session, no need to queue another one.\n this.logger.trace(`Not checking key backup for session ${megolmSessionId} as it is already queued`);\n return;\n }\n\n if (this.wasRequestedRecently(megolmSessionId)) {\n // We already tried to download this session recently and it was not in backup, no need to try again.\n this.logger.trace(\n `Not checking key backup for session ${megolmSessionId} as it was already requested recently`,\n );\n return;\n }\n\n // We always add the request to the queue, even if we have a configuration problem (can't access backup).\n // This is to make sure that if the configuration problem is resolved, we will try to download the key.\n // This will happen after an initial sync, at this point the backup will not yet be trusted and the decryption\n // key will not be available, but it will be just after the verification.\n // We don't need to persist it because currently on refresh the sdk will retry to decrypt the messages in error.\n this.queuedRequests.push({ roomId, megolmSessionId });\n\n // Start the download loop if it's not already running.\n this.downloadKeysLoop();\n }\n\n public stop(): void {\n this.stopped = true;\n this.backupManager.off(CryptoEvent.KeyBackupStatus, this.onBackupStatusChanged);\n this.backupManager.off(CryptoEvent.KeyBackupFailed, this.onBackupStatusChanged);\n this.backupManager.off(CryptoEvent.KeyBackupDecryptionKeyCached, this.onBackupStatusChanged);\n }\n\n /**\n * Called when the backup status changes (CryptoEvents)\n * This will trigger a check of the backup configuration.\n */\n private onBackupStatusChanged = (): void => {\n // we want to force check configuration, so we clear the current one.\n this.hasConfigurationProblem = false;\n this.configuration = null;\n this.getOrCreateBackupConfiguration().then((configuration) => {\n if (configuration) {\n // restart the download loop if it was stopped\n this.downloadKeysLoop();\n }\n });\n };\n\n /** Returns true if the megolm session is already queued for download. */\n private isAlreadyInQueue(roomId: string, megolmSessionId: string): boolean {\n return this.queuedRequests.some((info) => {\n return info.roomId == roomId && info.megolmSessionId == megolmSessionId;\n });\n }\n\n /**\n * Marks the session as not found in backup, to avoid retrying to soon for a key not in backup\n *\n * @param megolmSessionId - The megolm session ID that is missing.\n */\n private markAsNotFoundInBackup(megolmSessionId: string): void {\n const now = Date.now();\n this.sessionLastCheckAttemptedTime.set(megolmSessionId, now);\n // if too big make some cleaning to keep under control\n if (this.sessionLastCheckAttemptedTime.size > 100) {\n this.sessionLastCheckAttemptedTime = new Map(\n Array.from(this.sessionLastCheckAttemptedTime).filter((sid, ts) => {\n return Math.max(now - ts, 0) < KEY_BACKUP_BACKOFF;\n }),\n );\n }\n }\n\n /** Returns true if the session was requested recently. */\n private wasRequestedRecently(megolmSessionId: string): boolean {\n const lastCheck = this.sessionLastCheckAttemptedTime.get(megolmSessionId);\n if (!lastCheck) return false;\n return Math.max(Date.now() - lastCheck, 0) < KEY_BACKUP_BACKOFF;\n }\n\n private async getBackupDecryptionKey(): Promise<RustSdkCryptoJs.BackupKeys | null> {\n try {\n return await this.olmMachine.getBackupKeys();\n } catch {\n return null;\n }\n }\n\n /**\n * Requests a key from the server side backup.\n *\n * @param version - The backup version to use.\n * @param roomId - The room ID of the room where the error occurred.\n * @param sessionId - The megolm session ID that is missing.\n */\n private async requestRoomKeyFromBackup(\n version: string,\n roomId: string,\n sessionId: string,\n ): Promise<KeyBackupSession> {\n const path = encodeUri(\"/room_keys/keys/$roomId/$sessionId\", {\n $roomId: roomId,\n $sessionId: sessionId,\n });\n\n return await this.http.authedRequest<KeyBackupSession>(Method.Get, path, { version }, undefined, {\n prefix: ClientPrefix.V3,\n });\n }\n\n private async downloadKeysLoop(): Promise<void> {\n if (this.downloadLoopRunning) return;\n\n // If we have a configuration problem, we don't want to try to download.\n // If any configuration change is detected, we will retry and restart the loop.\n if (this.hasConfigurationProblem) return;\n\n this.downloadLoopRunning = true;\n\n try {\n while (this.queuedRequests.length > 0) {\n // we just peek the first one without removing it, so if a new request for same key comes in while we're\n // processing this one, it won't queue another request.\n const request = this.queuedRequests[0];\n try {\n // The backup could have changed between the time we queued the request and now, so we need to check\n const configuration = await this.getOrCreateBackupConfiguration();\n if (!configuration) {\n // Backup is not configured correctly, so stop the loop.\n this.downloadLoopRunning = false;\n return;\n }\n\n const result = await this.queryKeyBackup(request.roomId, request.megolmSessionId, configuration);\n\n if (this.stopped) {\n return;\n }\n // We got the encrypted key from backup, let's try to decrypt and import it.\n try {\n await this.decryptAndImport(request, result, configuration);\n } catch (e) {\n this.logger.error(\n `Error while decrypting and importing key backup for session ${request.megolmSessionId}`,\n e,\n );\n }\n // now remove the request from the queue as we've processed it.\n this.queuedRequests.shift();\n } catch (err) {\n if (err instanceof KeyDownloadError) {\n switch (err.code) {\n case KeyDownloadErrorCode.MISSING_DECRYPTION_KEY:\n this.markAsNotFoundInBackup(request.megolmSessionId);\n // continue for next one\n this.queuedRequests.shift();\n break;\n case KeyDownloadErrorCode.NETWORK_ERROR:\n // We don't want to hammer if there is a problem, so wait a bit.\n await sleep(KEY_BACKUP_BACKOFF);\n break;\n case KeyDownloadErrorCode.STOPPED:\n // If the downloader was stopped, we don't want to retry.\n this.downloadLoopRunning = false;\n return;\n }\n } else if (err instanceof KeyDownloadRateLimitError) {\n // we want to retry after the backoff time\n await sleep(err.retryMillis);\n }\n }\n }\n } finally {\n // all pending request have been processed, we can stop the loop.\n this.downloadLoopRunning = false;\n }\n }\n\n /**\n * Query the backup for a key.\n *\n * @param targetRoomId - ID of the room that the session is used in.\n * @param targetSessionId - ID of the session for which to check backup.\n * @param configuration - The backup configuration to use.\n */\n private async queryKeyBackup(\n targetRoomId: string,\n targetSessionId: string,\n configuration: Configuration,\n ): Promise<KeyBackupSession> {\n this.logger.debug(`Checking key backup for session ${targetSessionId}`);\n if (this.stopped) throw new KeyDownloadError(KeyDownloadErrorCode.STOPPED);\n try {\n const res = await this.requestRoomKeyFromBackup(configuration.backupVersion, targetRoomId, targetSessionId);\n this.logger.debug(`Got key from backup for sessionId:${targetSessionId}`);\n return res;\n } catch (e) {\n if (this.stopped) throw new KeyDownloadError(KeyDownloadErrorCode.STOPPED);\n\n this.logger.info(`No luck requesting key backup for session ${targetSessionId}: ${e}`);\n if (e instanceof MatrixError) {\n const errCode = e.data.errcode;\n if (errCode == \"M_NOT_FOUND\") {\n // Unfortunately the spec doesn't give us a way to differentiate between a missing key and a wrong version.\n // Synapse will return:\n // - \"error\": \"Unknown backup version\" if the version is wrong.\n // - \"error\": \"No room_keys found\" if the key is missing.\n // It's useful to know if the key is missing or if the version is wrong.\n // As it's not spec'ed, we fall back on considering the key is not in backup.\n // Notice that this request will be lost if instead the backup got out of sync (updated from other session).\n throw new KeyDownloadError(KeyDownloadErrorCode.MISSING_DECRYPTION_KEY);\n }\n if (e.isRateLimitError()) {\n let waitTime: number | undefined;\n try {\n waitTime = e.getRetryAfterMs() ?? undefined;\n } catch (error) {\n this.logger.warn(\"Error while retrieving a rate-limit retry delay\", error);\n }\n if (waitTime && waitTime > 0) {\n this.logger.info(`Rate limited by server, waiting ${waitTime}ms`);\n }\n throw new KeyDownloadRateLimitError(waitTime ?? KEY_BACKUP_BACKOFF);\n }\n }\n throw new KeyDownloadError(KeyDownloadErrorCode.NETWORK_ERROR);\n }\n }\n\n private async decryptAndImport(\n sessionInfo: SessionInfo,\n data: KeyBackupSession,\n configuration: Configuration,\n ): Promise<void> {\n const sessionsToImport: Record<string, KeyBackupSession> = { [sessionInfo.megolmSessionId]: data };\n\n const keys = await configuration!.decryptor.decryptSessions(sessionsToImport);\n for (const k of keys) {\n k.room_id = sessionInfo.roomId;\n }\n await this.backupManager.importBackedUpRoomKeys(keys, configuration.backupVersion);\n }\n\n /**\n * Gets the current backup configuration or create one if it doesn't exist.\n *\n * When a valid configuration is found it is cached and returned for subsequent calls.\n * Otherwise, if a check is forced or a check has not yet been done, a new check is done.\n *\n * @returns The backup configuration to use or null if there is a configuration problem.\n */\n private async getOrCreateBackupConfiguration(): Promise<Configuration | null> {\n if (this.configuration) {\n return this.configuration;\n }\n\n // We already tried to check the configuration and it failed.\n // We don't want to try again immediately, we will retry if a configuration change is detected.\n if (this.hasConfigurationProblem) {\n return null;\n }\n\n // This method can be called rapidly by several emitted CryptoEvent, so we need to make sure that we don't\n // query the server several times.\n if (this.currentBackupVersionCheck != null) {\n this.logger.debug(`Already checking server version, use current promise`);\n return await this.currentBackupVersionCheck;\n }\n\n this.currentBackupVersionCheck = this.internalCheckFromServer();\n try {\n return await this.currentBackupVersionCheck;\n } finally {\n this.currentBackupVersionCheck = null;\n }\n }\n\n private async internalCheckFromServer(): Promise<Configuration | null> {\n let currentServerVersion = null;\n try {\n currentServerVersion = await this.backupManager.getServerBackupInfo();\n } catch (e) {\n this.logger.debug(`Backup: error while checking server version: ${e}`);\n this.hasConfigurationProblem = true;\n return null;\n }\n this.logger.debug(`Got current backup version from server: ${currentServerVersion?.version}`);\n\n if (currentServerVersion?.algorithm != \"m.megolm_backup.v1.curve25519-aes-sha2\") {\n this.logger.info(`Unsupported algorithm ${currentServerVersion?.algorithm}`);\n this.hasConfigurationProblem = true;\n return null;\n }\n\n if (!currentServerVersion?.version) {\n this.logger.info(`No current key backup`);\n this.hasConfigurationProblem = true;\n return null;\n }\n\n const activeVersion = await this.backupManager.getActiveBackupVersion();\n if (activeVersion == null || currentServerVersion.version != activeVersion) {\n // Either the current backup version on server side is not trusted, or it is out of sync with the active version on the client side.\n this.logger.info(\n `The current backup version on the server (${currentServerVersion.version}) is not trusted. Version we are currently backing up to: ${activeVersion}`,\n );\n this.hasConfigurationProblem = true;\n return null;\n }\n\n const backupKeys = await this.getBackupDecryptionKey();\n if (!backupKeys?.decryptionKey) {\n this.logger.debug(`Not checking key backup for session (no decryption key)`);\n this.hasConfigurationProblem = true;\n return null;\n }\n\n if (activeVersion != backupKeys.backupVersion) {\n this.logger.debug(\n `Version for which we have a decryption key (${backupKeys.backupVersion}) doesn't match the version we are backing up to (${activeVersion})`,\n );\n this.hasConfigurationProblem = true;\n return null;\n }\n\n const authData = currentServerVersion.auth_data as Curve25519AuthData;\n if (authData.public_key != backupKeys.decryptionKey.megolmV1PublicKey.publicKeyBase64) {\n this.logger.debug(`Key backup on server does not match our decryption key`);\n this.hasConfigurationProblem = true;\n return null;\n }\n\n const backupDecryptor = this.backupManager.createBackupDecryptor(backupKeys.decryptionKey);\n this.hasConfigurationProblem = false;\n this.configuration = {\n decryptor: backupDecryptor,\n backupVersion: activeVersion,\n };\n return this.configuration;\n }\n}\n"],"mappings":";AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAMA,SAAS,WAAW,QAAQ,wBAAwB;AAEpD,SAAS,YAAY,EAAkB,WAAW,EAAsB,MAAM,QAAQ,sBAAsB;AAE5G,SAAS,SAAS,EAAE,KAAK,QAAQ,aAAa;AAG9C;AACA,MAAM,kBAAkB,GAAG,IAAI,CAAC,CAAC;;AAEjC;AACA;AACA;AAFA,IAGK,oBAAoB,0BAApB,oBAAoB;EACrB;EADC,oBAAoB;EAGrB;EAH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aAAa,CAAC,iBAAiB,CAAC,eAAe,EAAE;MACnF,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,wDAAwD,CAAC;MAC3E,IAAI,CAAC,uBAAuB,GAAG,IAAI;MACnC,OAAO,IAAI;IACf;IAEA,MAAM,eAAe,GAAG,IAAI,CAAC,aAAa,CAAC,qBAAqB,CAAC,UAAU,CAAC,aAAa,CAAC;IAC1F,IAAI,CAAC,uBAAuB,GAAG,KAAK;IACpC,IAAI,CAAC,aAAa,GAAG;MACjB,SAAS,EAAE,eAAe;MAC1B,aAAa,EAAE;IACnB,CAAC;IACD,OAAO,IAAI,CAAC,aAAa;EAC7B;AACJ","ignoreList":[]}
1
+ {"version":3,"file":"PerSessionKeyBackupDownloader.js","names":[],"sources":["../../src/rust-crypto/PerSessionKeyBackupDownloader.ts"],"sourcesContent":["/*\nCopyright 2023 - 2024 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { type OlmMachine } from \"@matrix-org/matrix-sdk-crypto-wasm\";\n\nimport type * as RustSdkCryptoJs from \"@matrix-org/matrix-sdk-crypto-wasm\";\nimport { type Curve25519AuthData, type KeyBackupInfo, type KeyBackupSession } from \"../crypto-api/keybackup.ts\";\nimport { CryptoEvent } from \"../crypto-api/index.ts\";\nimport { type Logger } from \"../logger.ts\";\nimport { ClientPrefix, type IHttpOpts, MatrixError, type MatrixHttpApi, Method } from \"../http-api/index.ts\";\nimport { type RustBackupManager } from \"./backup.ts\";\nimport { encodeUri, sleep } from \"../utils.ts\";\nimport { type BackupDecryptor } from \"../common-crypto/CryptoBackend.ts\";\n\n// The minimum time to wait between two retries in case of errors. To avoid hammering the server.\nconst KEY_BACKUP_BACKOFF = 5000; // ms\n\n/**\n * Enumerates the different kind of errors that can occurs when downloading and importing a key from backup.\n */\nenum KeyDownloadErrorCode {\n /** The requested key is not in the backup. */\n MISSING_DECRYPTION_KEY = \"MISSING_DECRYPTION_KEY\",\n /** A network error occurred while trying to download the key from backup. */\n NETWORK_ERROR = \"NETWORK_ERROR\",\n /** The loop has been stopped. */\n STOPPED = \"STOPPED\",\n}\n\nclass KeyDownloadError extends Error {\n public constructor(public readonly code: KeyDownloadErrorCode) {\n super(`Failed to get key from backup: ${code}`);\n this.name = \"KeyDownloadError\";\n }\n}\n\nclass KeyDownloadRateLimitError extends Error {\n public constructor(public readonly retryMillis: number) {\n super(`Failed to get key from backup: rate limited`);\n this.name = \"KeyDownloadRateLimitError\";\n }\n}\n\n/** Details of a megolm session whose key we are trying to fetch. */\ntype SessionInfo = { roomId: string; megolmSessionId: string };\n\n/** Holds the current backup decryptor and version that should be used.\n *\n * This is intended to be used as an immutable object (a new instance should be created if the configuration changes),\n * and some of the logic relies on that, so the properties are marked as `readonly`.\n */\ntype Configuration = {\n readonly backupVersion: string;\n readonly decryptor: BackupDecryptor;\n};\n\n/**\n * Used when an 'unable to decrypt' error occurs. It attempts to download the key from the backup.\n *\n * The current backup API lacks pagination, which can lead to lengthy key retrieval times for large histories (several 10s of minutes).\n * To mitigate this, keys are downloaded on demand as decryption errors occurs.\n * While this approach may result in numerous requests, it improves user experience by reducing wait times for message decryption.\n *\n * The PerSessionKeyBackupDownloader is resistant to backup configuration changes: it will automatically resume querying when\n * the backup is configured correctly.\n */\nexport class PerSessionKeyBackupDownloader {\n private stopped = false;\n\n /**\n * The version and decryption key to use with current backup if all set up correctly.\n *\n * Will not be set unless `hasConfigurationProblem` is `false`.\n */\n private configuration: Configuration | null = null;\n\n /** We remember when a session was requested and not found in backup to avoid query again too soon.\n * Map of session_id to timestamp */\n private sessionLastCheckAttemptedTime: Map<string, number> = new Map();\n\n /** The logger to use */\n private readonly logger: Logger;\n\n /** Whether the download loop is running. */\n private downloadLoopRunning = false;\n\n /** The list of requests that are queued. */\n private queuedRequests: SessionInfo[] = [];\n\n /** Remembers if we have a configuration problem. */\n private hasConfigurationProblem = false;\n\n /** The current server backup version check promise. To avoid doing a server call if one is in flight. */\n private currentBackupVersionCheck: Promise<Configuration | null> | null = null;\n\n /**\n * Creates a new instance of PerSessionKeyBackupDownloader.\n *\n * @param backupManager - The backup manager to use.\n * @param olmMachine - The olm machine to use.\n * @param http - The http instance to use.\n * @param logger - The logger to use.\n */\n public constructor(\n logger: Logger,\n private readonly olmMachine: OlmMachine,\n private readonly http: MatrixHttpApi<IHttpOpts & { onlyData: true }>,\n private readonly backupManager: RustBackupManager,\n ) {\n this.logger = logger.getChild(\"[PerSessionKeyBackupDownloader]\");\n\n backupManager.on(CryptoEvent.KeyBackupStatus, this.onBackupStatusChanged);\n backupManager.on(CryptoEvent.KeyBackupFailed, this.onBackupStatusChanged);\n backupManager.on(CryptoEvent.KeyBackupDecryptionKeyCached, this.onBackupStatusChanged);\n }\n\n /**\n * Check if key download is successfully configured and active.\n *\n * @returns `true` if key download is correctly configured and active; otherwise `false`.\n */\n public isKeyBackupDownloadConfigured(): boolean {\n return this.configuration !== null;\n }\n\n /**\n * Return the details of the latest backup on the server, when we last checked.\n *\n * This is just a convenience method to expose {@link RustBackupManager.getServerBackupInfo}.\n */\n public async getServerBackupInfo(): Promise<KeyBackupInfo | null | undefined> {\n return await this.backupManager.getServerBackupInfo();\n }\n\n /**\n * Called when a MissingRoomKey or UnknownMessageIndex decryption error is encountered.\n *\n * This will try to download the key from the backup if there is a trusted active backup.\n * In case of success the key will be imported and the onRoomKeysUpdated callback will be called\n * internally by the rust-sdk and decryption will be retried.\n *\n * @param roomId - The room ID of the room where the error occurred.\n * @param megolmSessionId - The megolm session ID that is missing.\n */\n public onDecryptionKeyMissingError(roomId: string, megolmSessionId: string): void {\n // Several messages encrypted with the same session may be decrypted at the same time,\n // so we need to be resistant and not query several time the same session.\n if (this.isAlreadyInQueue(roomId, megolmSessionId)) {\n // There is already a request queued for this session, no need to queue another one.\n this.logger.trace(`Not checking key backup for session ${megolmSessionId} as it is already queued`);\n return;\n }\n\n if (this.wasRequestedRecently(megolmSessionId)) {\n // We already tried to download this session recently and it was not in backup, no need to try again.\n this.logger.trace(\n `Not checking key backup for session ${megolmSessionId} as it was already requested recently`,\n );\n return;\n }\n\n // We always add the request to the queue, even if we have a configuration problem (can't access backup).\n // This is to make sure that if the configuration problem is resolved, we will try to download the key.\n // This will happen after an initial sync, at this point the backup will not yet be trusted and the decryption\n // key will not be available, but it will be just after the verification.\n // We don't need to persist it because currently on refresh the sdk will retry to decrypt the messages in error.\n this.queuedRequests.push({ roomId, megolmSessionId });\n\n // Start the download loop if it's not already running.\n this.downloadKeysLoop();\n }\n\n public stop(): void {\n this.stopped = true;\n this.backupManager.off(CryptoEvent.KeyBackupStatus, this.onBackupStatusChanged);\n this.backupManager.off(CryptoEvent.KeyBackupFailed, this.onBackupStatusChanged);\n this.backupManager.off(CryptoEvent.KeyBackupDecryptionKeyCached, this.onBackupStatusChanged);\n }\n\n /**\n * Called when the backup status changes (CryptoEvents)\n * This will trigger a check of the backup configuration.\n */\n private onBackupStatusChanged = (): void => {\n // we want to force check configuration, so we clear the current one.\n this.hasConfigurationProblem = false;\n this.configuration = null;\n this.getOrCreateBackupConfiguration().then((configuration) => {\n if (configuration) {\n // restart the download loop if it was stopped\n this.downloadKeysLoop();\n }\n });\n };\n\n /** Returns true if the megolm session is already queued for download. */\n private isAlreadyInQueue(roomId: string, megolmSessionId: string): boolean {\n return this.queuedRequests.some((info) => {\n return info.roomId == roomId && info.megolmSessionId == megolmSessionId;\n });\n }\n\n /**\n * Marks the session as not found in backup, to avoid retrying to soon for a key not in backup\n *\n * @param megolmSessionId - The megolm session ID that is missing.\n */\n private markAsNotFoundInBackup(megolmSessionId: string): void {\n const now = Date.now();\n this.sessionLastCheckAttemptedTime.set(megolmSessionId, now);\n // if too big make some cleaning to keep under control\n if (this.sessionLastCheckAttemptedTime.size > 100) {\n this.sessionLastCheckAttemptedTime = new Map(\n Array.from(this.sessionLastCheckAttemptedTime).filter((sid, ts) => {\n return Math.max(now - ts, 0) < KEY_BACKUP_BACKOFF;\n }),\n );\n }\n }\n\n /** Returns true if the session was requested recently. */\n private wasRequestedRecently(megolmSessionId: string): boolean {\n const lastCheck = this.sessionLastCheckAttemptedTime.get(megolmSessionId);\n if (!lastCheck) return false;\n return Math.max(Date.now() - lastCheck, 0) < KEY_BACKUP_BACKOFF;\n }\n\n private async getBackupDecryptionKey(): Promise<RustSdkCryptoJs.BackupKeys | null> {\n try {\n return await this.olmMachine.getBackupKeys();\n } catch {\n return null;\n }\n }\n\n /**\n * Requests a key from the server side backup.\n *\n * @param version - The backup version to use.\n * @param roomId - The room ID of the room where the error occurred.\n * @param sessionId - The megolm session ID that is missing.\n */\n private async requestRoomKeyFromBackup(\n version: string,\n roomId: string,\n sessionId: string,\n ): Promise<KeyBackupSession> {\n const path = encodeUri(\"/room_keys/keys/$roomId/$sessionId\", {\n $roomId: roomId,\n $sessionId: sessionId,\n });\n\n return await this.http.authedRequest<KeyBackupSession>(Method.Get, path, { version }, undefined, {\n prefix: ClientPrefix.V3,\n });\n }\n\n private async downloadKeysLoop(): Promise<void> {\n if (this.downloadLoopRunning) return;\n\n // If we have a configuration problem, we don't want to try to download.\n // If any configuration change is detected, we will retry and restart the loop.\n if (this.hasConfigurationProblem) return;\n\n this.downloadLoopRunning = true;\n\n try {\n while (this.queuedRequests.length > 0) {\n // we just peek the first one without removing it, so if a new request for same key comes in while we're\n // processing this one, it won't queue another request.\n const request = this.queuedRequests[0];\n try {\n // The backup could have changed between the time we queued the request and now, so we need to check\n const configuration = await this.getOrCreateBackupConfiguration();\n if (!configuration) {\n // Backup is not configured correctly, so stop the loop.\n this.downloadLoopRunning = false;\n return;\n }\n\n const result = await this.queryKeyBackup(request.roomId, request.megolmSessionId, configuration);\n\n if (this.stopped) {\n return;\n }\n // We got the encrypted key from backup, let's try to decrypt and import it.\n try {\n await this.decryptAndImport(request, result, configuration);\n } catch (e) {\n this.logger.error(\n `Error while decrypting and importing key backup for session ${request.megolmSessionId}`,\n e,\n );\n }\n // now remove the request from the queue as we've processed it.\n this.queuedRequests.shift();\n } catch (err) {\n if (err instanceof KeyDownloadError) {\n switch (err.code) {\n case KeyDownloadErrorCode.MISSING_DECRYPTION_KEY:\n this.markAsNotFoundInBackup(request.megolmSessionId);\n // continue for next one\n this.queuedRequests.shift();\n break;\n case KeyDownloadErrorCode.NETWORK_ERROR:\n // We don't want to hammer if there is a problem, so wait a bit.\n await sleep(KEY_BACKUP_BACKOFF);\n break;\n case KeyDownloadErrorCode.STOPPED:\n // If the downloader was stopped, we don't want to retry.\n this.downloadLoopRunning = false;\n return;\n }\n } else if (err instanceof KeyDownloadRateLimitError) {\n // we want to retry after the backoff time\n await sleep(err.retryMillis);\n }\n }\n }\n } finally {\n // all pending request have been processed, we can stop the loop.\n this.downloadLoopRunning = false;\n }\n }\n\n /**\n * Query the backup for a key.\n *\n * @param targetRoomId - ID of the room that the session is used in.\n * @param targetSessionId - ID of the session for which to check backup.\n * @param configuration - The backup configuration to use.\n */\n private async queryKeyBackup(\n targetRoomId: string,\n targetSessionId: string,\n configuration: Configuration,\n ): Promise<KeyBackupSession> {\n this.logger.debug(`Checking key backup for session ${targetSessionId}`);\n if (this.stopped) throw new KeyDownloadError(KeyDownloadErrorCode.STOPPED);\n try {\n const res = await this.requestRoomKeyFromBackup(configuration.backupVersion, targetRoomId, targetSessionId);\n this.logger.debug(`Got key from backup for sessionId:${targetSessionId}`);\n return res;\n } catch (e) {\n if (this.stopped) throw new KeyDownloadError(KeyDownloadErrorCode.STOPPED);\n\n this.logger.info(`No luck requesting key backup for session ${targetSessionId}: ${e}`);\n if (e instanceof MatrixError) {\n const errCode = e.data.errcode;\n if (errCode == \"M_NOT_FOUND\") {\n // Unfortunately the spec doesn't give us a way to differentiate between a missing key and a wrong version.\n // Synapse will return:\n // - \"error\": \"Unknown backup version\" if the version is wrong.\n // - \"error\": \"No room_keys found\" if the key is missing.\n // It's useful to know if the key is missing or if the version is wrong.\n // As it's not spec'ed, we fall back on considering the key is not in backup.\n // Notice that this request will be lost if instead the backup got out of sync (updated from other session).\n throw new KeyDownloadError(KeyDownloadErrorCode.MISSING_DECRYPTION_KEY);\n }\n if (e.isRateLimitError()) {\n let waitTime: number | undefined;\n try {\n waitTime = e.getRetryAfterMs() ?? undefined;\n } catch (error) {\n this.logger.warn(\"Error while retrieving a rate-limit retry delay\", error);\n }\n if (waitTime && waitTime > 0) {\n this.logger.info(`Rate limited by server, waiting ${waitTime}ms`);\n }\n throw new KeyDownloadRateLimitError(waitTime ?? KEY_BACKUP_BACKOFF);\n }\n }\n throw new KeyDownloadError(KeyDownloadErrorCode.NETWORK_ERROR);\n }\n }\n\n private async decryptAndImport(\n sessionInfo: SessionInfo,\n data: KeyBackupSession,\n configuration: Configuration,\n ): Promise<void> {\n const sessionsToImport: Record<string, KeyBackupSession> = { [sessionInfo.megolmSessionId]: data };\n\n const keys = await configuration.decryptor.decryptSessions(sessionsToImport);\n for (const k of keys) {\n k.room_id = sessionInfo.roomId;\n }\n await this.backupManager.importBackedUpRoomKeys(keys, configuration.backupVersion);\n }\n\n /**\n * Gets the current backup configuration or create one if it doesn't exist.\n *\n * When a valid configuration is found it is cached and returned for subsequent calls.\n * Otherwise, if a check is forced or a check has not yet been done, a new check is done.\n *\n * @returns The backup configuration to use or null if there is a configuration problem.\n */\n private async getOrCreateBackupConfiguration(): Promise<Configuration | null> {\n if (this.configuration) {\n return this.configuration;\n }\n\n // We already tried to check the configuration and it failed.\n // We don't want to try again immediately, we will retry if a configuration change is detected.\n if (this.hasConfigurationProblem) {\n return null;\n }\n\n // This method can be called rapidly by several emitted CryptoEvent, so we need to make sure that we don't\n // query the server several times.\n if (this.currentBackupVersionCheck != null) {\n this.logger.debug(`Already checking server version, use current promise`);\n return await this.currentBackupVersionCheck;\n }\n\n this.currentBackupVersionCheck = this.internalCheckFromServer();\n try {\n return await this.currentBackupVersionCheck;\n } finally {\n this.currentBackupVersionCheck = null;\n }\n }\n\n private async internalCheckFromServer(): Promise<Configuration | null> {\n let currentServerVersion = null;\n try {\n currentServerVersion = await this.backupManager.getServerBackupInfo();\n } catch (e) {\n this.logger.debug(`Backup: error while checking server version: ${e}`);\n this.hasConfigurationProblem = true;\n return null;\n }\n this.logger.debug(`Got current backup version from server: ${currentServerVersion?.version}`);\n\n if (currentServerVersion?.algorithm != \"m.megolm_backup.v1.curve25519-aes-sha2\") {\n this.logger.info(`Unsupported algorithm ${currentServerVersion?.algorithm}`);\n this.hasConfigurationProblem = true;\n return null;\n }\n\n if (!currentServerVersion?.version) {\n this.logger.info(`No current key backup`);\n this.hasConfigurationProblem = true;\n return null;\n }\n\n const activeVersion = await this.backupManager.getActiveBackupVersion();\n if (activeVersion == null || currentServerVersion.version != activeVersion) {\n // Either the current backup version on server side is not trusted, or it is out of sync with the active version on the client side.\n this.logger.info(\n `The current backup version on the server (${currentServerVersion.version}) is not trusted. Version we are currently backing up to: ${activeVersion}`,\n );\n this.hasConfigurationProblem = true;\n return null;\n }\n\n const backupKeys = await this.getBackupDecryptionKey();\n if (!backupKeys?.decryptionKey) {\n this.logger.debug(`Not checking key backup for session (no decryption key)`);\n this.hasConfigurationProblem = true;\n return null;\n }\n\n if (activeVersion != backupKeys.backupVersion) {\n this.logger.debug(\n `Version for which we have a decryption key (${backupKeys.backupVersion}) doesn't match the version we are backing up to (${activeVersion})`,\n );\n this.hasConfigurationProblem = true;\n return null;\n }\n\n const authData = currentServerVersion.auth_data as Curve25519AuthData;\n if (authData.public_key != backupKeys.decryptionKey.megolmV1PublicKey.publicKeyBase64) {\n this.logger.debug(`Key backup on server does not match our decryption key`);\n this.hasConfigurationProblem = true;\n return null;\n }\n\n const backupDecryptor = this.backupManager.createBackupDecryptor(backupKeys.decryptionKey);\n this.hasConfigurationProblem = false;\n this.configuration = {\n decryptor: backupDecryptor,\n backupVersion: activeVersion,\n };\n return this.configuration;\n }\n}\n"],"mappings":";AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAMA,SAAS,WAAW,QAAQ,wBAAwB;AAEpD,SAAS,YAAY,EAAkB,WAAW,EAAsB,MAAM,QAAQ,sBAAsB;AAE5G,SAAS,SAAS,EAAE,KAAK,QAAQ,aAAa;AAG9C;AACA,MAAM,kBAAkB,GAAG,IAAI,CAAC,CAAC;;AAEjC;AACA;AACA;AAFA,IAGK,oBAAoB,0BAApB,oBAAoB;EACrB;EADC,oBAAoB;EAGrB;EAHC,oBAAoB;EAKrB;EALC,oBAAoB;EAAA,OAApB,oBAAoB;AAAA,EAApB,oBAAoB;AASzB,MAAM,gBAAgB,SAAS,KAAK,CAAC;EAC1B,WAAW,CAAiB,IAA0B,EAAE;IAC3D,KAAK,CAAC,kCAAkC,IAAI,EAAE,CAAC;IAAC,KADjB,IAA0B,GAA1B,IAA0B;IAEzD,IAAI,CAAC,IAAI,GAAG,kBAAkB;EAClC;AACJ;AAEA,MAAM,yBAAyB,SAAS,KAAK,CAAC;EACnC,WAAW,CAAiB,WAAmB,EAAE;IACpD,KAAK,CAAC,6CAA6C,CAAC;IAAC,KADtB,WAAmB,GAAnB,WAAmB;IAElD,IAAI,CAAC,IAAI,GAAG,2BAA2B;EAC3C;AACJ;;AAEA;;AAGA;AACA;AACA;AACA;AACA;;AAMA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,MAAM,6BAA6B,CAAC;EA6BvC;AACJ;AACA;AACA;AACA;AACA;AACA;AACA;EACW,WAAW,CACd,MAAc,EACG,UAAsB,EACtB,IAAmD,EACnD,aAAgC,EACnD;IAAA,iCAzCgB,KAAK;IAEvB;AACJ;AACA;AACA;AACA;IAJI,uCAK8C,IAAI;IAElD;AACJ;IADI,uDAE6D,IAAI,GAAG,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E,aAAa,EAAE;MAC5B,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,yDAAyD,CAAC;MAC5E,IAAI,CAAC,uBAAuB,GAAG,IAAI;MACnC,OAAO,IAAI;IACf;IAEA,IAAI,aAAa,IAAI,UAAU,CAAC,aAAa,EAAE;MAC3C,IAAI,CAAC,MAAM,CAAC,KAAK,CACb,+CAA+C,UAAU,CAAC,aAAa,qDAAqD,aAAa,GAC7I,CAAC;MACD,IAAI,CAAC,uBAAuB,GAAG,IAAI;MACnC,OAAO,IAAI;IACf;IAEA,MAAM,QAAQ,GAAG,oBAAoB,CAAC,SAA+B;IACrE,IAAI,QAAQ,CAAC,UAAU,IAAI,UAAU,CAAC,aAAa,CAAC,iBAAiB,CAAC,eAAe,EAAE;MACnF,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,wDAAwD,CAAC;MAC3E,IAAI,CAAC,uBAAuB,GAAG,IAAI;MACnC,OAAO,IAAI;IACf;IAEA,MAAM,eAAe,GAAG,IAAI,CAAC,aAAa,CAAC,qBAAqB,CAAC,UAAU,CAAC,aAAa,CAAC;IAC1F,IAAI,CAAC,uBAAuB,GAAG,KAAK;IACpC,IAAI,CAAC,aAAa,GAAG;MACjB,SAAS,EAAE,eAAe;MAC1B,aAAa,EAAE;IACnB,CAAC;IACD,OAAO,IAAI,CAAC,aAAa;EAC7B;AACJ","ignoreList":[]}
@@ -1,13 +1,12 @@
1
1
  import { type OlmMachine } from "@matrix-org/matrix-sdk-crypto-wasm";
2
2
  import * as RustSdkCryptoJs from "@matrix-org/matrix-sdk-crypto-wasm";
3
- import { type BackupTrustInfo, type KeyBackupCheck, type KeyBackupInfo, type KeyBackupSession, type Curve25519SessionData, type KeyBackupRestoreOpts, type KeyBackupRestoreResult, type KeyBackupRoomSessions } from "../crypto-api/keybackup.ts";
3
+ import { type BackupTrustInfo, type KeyBackupCheck, type KeyBackupInfo, type KeyBackupSession, type KeyBackupRestoreOpts, type KeyBackupRestoreResult, type KeyBackupRoomSessions } from "../crypto-api/keybackup.ts";
4
4
  import { type Logger } from "../logger.ts";
5
5
  import { type IHttpOpts, type MatrixHttpApi } from "../http-api/index.ts";
6
6
  import { TypedEventEmitter } from "../models/typed-event-emitter.ts";
7
7
  import { type OutgoingRequestProcessor } from "./OutgoingRequestProcessor.ts";
8
8
  import { type BackupDecryptor } from "../common-crypto/CryptoBackend.ts";
9
9
  import { type ImportRoomKeysOpts, CryptoEvent } from "../crypto-api/index.ts";
10
- import { type AESEncryptedSecretStoragePayload } from "../@types/AESEncryptedSecretStoragePayload.ts";
11
10
  import { type IMegolmSessionData } from "../@types/crypto.ts";
12
11
  /** Authentification of the backup info, depends on algorithm */
13
12
  type AuthData = KeyBackupInfo["auth_data"];
@@ -257,7 +256,7 @@ export declare class RustBackupDecryptor implements BackupDecryptor {
257
256
  /**
258
257
  * Implements {@link BackupDecryptor#decryptSessions}
259
258
  */
260
- decryptSessions(ciphertexts: Record<string, KeyBackupSession<Curve25519SessionData | AESEncryptedSecretStoragePayload>>): Promise<IMegolmSessionData[]>;
259
+ decryptSessions(ciphertexts: Record<string, KeyBackupSession>): Promise<IMegolmSessionData[]>;
261
260
  /**
262
261
  * Implements {@link BackupDecryptor#free}
263
262
  */
@@ -1 +1 @@
1
- {"version":3,"file":"backup.d.ts","sourceRoot":"","sources":["../../src/rust-crypto/backup.ts"],"names":[],"mappings":"AAgBA,OAAO,EAAE,KAAK,UAAU,EAA8B,MAAM,oCAAoC,CAAC;AACjG,OAAO,KAAK,eAAe,MAAM,oCAAoC,CAAC;AAEtE,OAAO,EACH,KAAK,eAAe,EAEpB,KAAK,cAAc,EACnB,KAAK,aAAa,EAClB,KAAK,gBAAgB,EACrB,KAAK,qBAAqB,EAC1B,KAAK,oBAAoB,EACzB,KAAK,sBAAsB,EAC3B,KAAK,qBAAqB,EAE7B,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,KAAK,MAAM,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EAAgB,KAA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