matrix-js-sdk 34.13.0 → 35.0.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 (167) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/README.md +25 -23
  3. package/git-revision.txt +1 -1
  4. package/lib/@types/global.d.js.map +1 -1
  5. package/lib/autodiscovery.d.ts +1 -1
  6. package/lib/autodiscovery.d.ts.map +1 -1
  7. package/lib/autodiscovery.js.map +1 -1
  8. package/lib/base64.d.ts +3 -6
  9. package/lib/base64.d.ts.map +1 -1
  10. package/lib/base64.js +43 -36
  11. package/lib/base64.js.map +1 -1
  12. package/lib/client.d.ts +15 -6
  13. package/lib/client.d.ts.map +1 -1
  14. package/lib/client.js +33 -28
  15. package/lib/client.js.map +1 -1
  16. package/lib/common-crypto/CryptoBackend.d.ts +2 -1
  17. package/lib/common-crypto/CryptoBackend.d.ts.map +1 -1
  18. package/lib/common-crypto/CryptoBackend.js.map +1 -1
  19. package/lib/crypto/EncryptionSetup.d.ts +1 -1
  20. package/lib/crypto/EncryptionSetup.d.ts.map +1 -1
  21. package/lib/crypto/EncryptionSetup.js +2 -1
  22. package/lib/crypto/EncryptionSetup.js.map +1 -1
  23. package/lib/crypto/dehydration.d.ts +3 -3
  24. package/lib/crypto/dehydration.d.ts.map +1 -1
  25. package/lib/crypto/dehydration.js.map +1 -1
  26. package/lib/crypto/index.d.ts +1 -2
  27. package/lib/crypto/index.d.ts.map +1 -1
  28. package/lib/crypto/index.js.map +1 -1
  29. package/lib/crypto/store/localStorage-crypto-store.js +4 -2
  30. package/lib/crypto/store/localStorage-crypto-store.js.map +1 -1
  31. package/lib/crypto/verification/request/VerificationRequest.d.ts +3 -3
  32. package/lib/crypto/verification/request/VerificationRequest.d.ts.map +1 -1
  33. package/lib/crypto/verification/request/VerificationRequest.js +2 -2
  34. package/lib/crypto/verification/request/VerificationRequest.js.map +1 -1
  35. package/lib/crypto-api/CryptoEventHandlerMap.d.ts +1 -0
  36. package/lib/crypto-api/CryptoEventHandlerMap.d.ts.map +1 -1
  37. package/lib/crypto-api/CryptoEventHandlerMap.js.map +1 -1
  38. package/lib/crypto-api/index.d.ts +9 -1
  39. package/lib/crypto-api/index.d.ts.map +1 -1
  40. package/lib/crypto-api/index.js +2 -0
  41. package/lib/crypto-api/index.js.map +1 -1
  42. package/lib/crypto-api/recovery-key.js +1 -1
  43. package/lib/crypto-api/recovery-key.js.map +1 -1
  44. package/lib/crypto-api/verification.d.ts +3 -3
  45. package/lib/crypto-api/verification.d.ts.map +1 -1
  46. package/lib/crypto-api/verification.js.map +1 -1
  47. package/lib/digest.d.ts +2 -2
  48. package/lib/digest.d.ts.map +1 -1
  49. package/lib/digest.js +2 -2
  50. package/lib/digest.js.map +1 -1
  51. package/lib/embedded.d.ts.map +1 -1
  52. package/lib/embedded.js +35 -2
  53. package/lib/embedded.js.map +1 -1
  54. package/lib/matrixrtc/MatrixRTCSession.d.ts.map +1 -1
  55. package/lib/matrixrtc/MatrixRTCSession.js +7 -3
  56. package/lib/matrixrtc/MatrixRTCSession.js.map +1 -1
  57. package/lib/models/event-timeline-set.d.ts +6 -10
  58. package/lib/models/event-timeline-set.d.ts.map +1 -1
  59. package/lib/models/event-timeline-set.js +28 -36
  60. package/lib/models/event-timeline-set.js.map +1 -1
  61. package/lib/models/event-timeline.d.ts +7 -2
  62. package/lib/models/event-timeline.d.ts.map +1 -1
  63. package/lib/models/event-timeline.js +8 -9
  64. package/lib/models/event-timeline.js.map +1 -1
  65. package/lib/models/event.d.ts +1 -1
  66. package/lib/models/event.d.ts.map +1 -1
  67. package/lib/models/event.js +11 -7
  68. package/lib/models/event.js.map +1 -1
  69. package/lib/models/relations.d.ts.map +1 -1
  70. package/lib/models/relations.js +3 -2
  71. package/lib/models/relations.js.map +1 -1
  72. package/lib/models/room-state.d.ts +2 -13
  73. package/lib/models/room-state.d.ts.map +1 -1
  74. package/lib/models/room-state.js +2 -31
  75. package/lib/models/room-state.js.map +1 -1
  76. package/lib/models/room.d.ts +2 -2
  77. package/lib/models/room.d.ts.map +1 -1
  78. package/lib/models/room.js +29 -16
  79. package/lib/models/room.js.map +1 -1
  80. package/lib/models/thread.d.ts.map +1 -1
  81. package/lib/models/thread.js +5 -3
  82. package/lib/models/thread.js.map +1 -1
  83. package/lib/rust-crypto/backup.d.ts +1 -1
  84. package/lib/rust-crypto/backup.d.ts.map +1 -1
  85. package/lib/rust-crypto/backup.js.map +1 -1
  86. package/lib/rust-crypto/libolm_migration.d.ts.map +1 -1
  87. package/lib/rust-crypto/libolm_migration.js.map +1 -1
  88. package/lib/rust-crypto/rust-crypto.d.ts +1 -1
  89. package/lib/rust-crypto/rust-crypto.d.ts.map +1 -1
  90. package/lib/rust-crypto/rust-crypto.js +26 -17
  91. package/lib/rust-crypto/rust-crypto.js.map +1 -1
  92. package/lib/rust-crypto/verification.d.ts +3 -3
  93. package/lib/rust-crypto/verification.d.ts.map +1 -1
  94. package/lib/rust-crypto/verification.js +2 -2
  95. package/lib/rust-crypto/verification.js.map +1 -1
  96. package/lib/sliding-sync-sdk.d.ts +1 -1
  97. package/lib/sliding-sync-sdk.d.ts.map +1 -1
  98. package/lib/sliding-sync-sdk.js +15 -13
  99. package/lib/sliding-sync-sdk.js.map +1 -1
  100. package/lib/sliding-sync.js +9 -6
  101. package/lib/sliding-sync.js.map +1 -1
  102. package/lib/store/indexeddb.d.ts +1 -1
  103. package/lib/store/indexeddb.d.ts.map +1 -1
  104. package/lib/store/indexeddb.js.map +1 -1
  105. package/lib/sync-accumulator.d.ts +6 -4
  106. package/lib/sync-accumulator.d.ts.map +1 -1
  107. package/lib/sync-accumulator.js +23 -12
  108. package/lib/sync-accumulator.js.map +1 -1
  109. package/lib/sync.d.ts +10 -1
  110. package/lib/sync.d.ts.map +1 -1
  111. package/lib/sync.js +95 -42
  112. package/lib/sync.js.map +1 -1
  113. package/lib/testing.d.ts.map +1 -1
  114. package/lib/testing.js +2 -1
  115. package/lib/testing.js.map +1 -1
  116. package/lib/utils/encryptAESSecretStorageItem.js +2 -2
  117. package/lib/utils/encryptAESSecretStorageItem.js.map +1 -1
  118. package/lib/webrtc/call.js +2 -1
  119. package/lib/webrtc/call.js.map +1 -1
  120. package/lib/webrtc/groupCall.js +1 -1
  121. package/lib/webrtc/groupCall.js.map +1 -1
  122. package/lib/webrtc/stats/callFeedStatsReporter.d.ts.map +1 -1
  123. package/lib/webrtc/stats/callFeedStatsReporter.js +2 -5
  124. package/lib/webrtc/stats/callFeedStatsReporter.js.map +1 -1
  125. package/lib/webrtc/stats/media/mediaTrackHandler.d.ts.map +1 -1
  126. package/lib/webrtc/stats/media/mediaTrackHandler.js +4 -8
  127. package/lib/webrtc/stats/media/mediaTrackHandler.js.map +1 -1
  128. package/package.json +6 -6
  129. package/src/@types/global.d.ts +21 -1
  130. package/src/autodiscovery.ts +1 -1
  131. package/src/base64.ts +38 -40
  132. package/src/client.ts +36 -34
  133. package/src/common-crypto/CryptoBackend.ts +2 -1
  134. package/src/crypto/EncryptionSetup.ts +1 -1
  135. package/src/crypto/dehydration.ts +3 -3
  136. package/src/crypto/index.ts +1 -3
  137. package/src/crypto/store/localStorage-crypto-store.ts +2 -2
  138. package/src/crypto/verification/request/VerificationRequest.ts +5 -4
  139. package/src/crypto-api/CryptoEventHandlerMap.ts +1 -0
  140. package/src/crypto-api/index.ts +10 -0
  141. package/src/crypto-api/recovery-key.ts +1 -1
  142. package/src/crypto-api/verification.ts +3 -3
  143. package/src/digest.ts +3 -3
  144. package/src/embedded.ts +35 -2
  145. package/src/matrixrtc/MatrixRTCSession.ts +7 -3
  146. package/src/models/event-timeline-set.ts +17 -38
  147. package/src/models/event-timeline.ts +10 -5
  148. package/src/models/event.ts +8 -6
  149. package/src/models/relations.ts +4 -2
  150. package/src/models/room-state.ts +2 -30
  151. package/src/models/room.ts +20 -8
  152. package/src/models/thread.ts +4 -2
  153. package/src/rust-crypto/backup.ts +1 -1
  154. package/src/rust-crypto/libolm_migration.ts +7 -2
  155. package/src/rust-crypto/rust-crypto.ts +32 -23
  156. package/src/rust-crypto/verification.ts +5 -5
  157. package/src/sliding-sync-sdk.ts +8 -11
  158. package/src/sliding-sync.ts +6 -6
  159. package/src/store/indexeddb.ts +1 -1
  160. package/src/sync-accumulator.ts +33 -16
  161. package/src/sync.ts +113 -45
  162. package/src/testing.ts +1 -2
  163. package/src/utils/encryptAESSecretStorageItem.ts +2 -2
  164. package/src/webrtc/call.ts +3 -3
  165. package/src/webrtc/groupCall.ts +1 -1
  166. package/src/webrtc/stats/callFeedStatsReporter.ts +2 -5
  167. package/src/webrtc/stats/media/mediaTrackHandler.ts +2 -8
package/CHANGELOG.md CHANGED
@@ -1,3 +1,34 @@
1
+ Changes in [35.0.0](https://github.com/matrix-org/matrix-js-sdk/releases/tag/v35.0.0) (2024-12-17)
2
+ ==================================================================================================
3
+ ## 🚨 BREAKING CHANGES
4
+
5
+ This release contains several breaking changes which will need code changes in your app. Most notably, `initCrypto()`
6
+ no longer exists and has been moved to `initLegacyCrypto()` in preparation for the eventual removal of Olm. You can
7
+ continue to use legacy Olm crypto for now by calling `initLegacyCrypto()` instead.
8
+
9
+ You may also need to make further changes if you use more advanced APIs. See the individual PRs (listed in order of size of change) for specific APIs changed and how to migrate.
10
+
11
+ * Rename `MatrixClient.initCrypto` into `MatrixClient.initLegacyCrypto` ([#4567](https://github.com/matrix-org/matrix-js-sdk/pull/4567)). Contributed by @florianduros.
12
+ * Support MSC4222 `state_after` ([#4487](https://github.com/matrix-org/matrix-js-sdk/pull/4487)). Contributed by @dbkr.
13
+ * Avoid use of Buffer as it does not exist in the Web natively ([#4569](https://github.com/matrix-org/matrix-js-sdk/pull/4569)). Contributed by @t3chguy.
14
+
15
+ ## 🦖 Deprecations
16
+
17
+ * Deprecate remaining legacy functions and move `CryptoEvent.LegacyCryptoStoreMigrationProgress` handler ([#4560](https://github.com/matrix-org/matrix-js-sdk/pull/4560)). Contributed by @florianduros.
18
+
19
+ ## ✨ Features
20
+
21
+ * Rename `MatrixClient.initCrypto` into `MatrixClient.initLegacyCrypto` ([#4567](https://github.com/matrix-org/matrix-js-sdk/pull/4567)). Contributed by @florianduros.
22
+ * Avoid use of Buffer as it does not exist in the Web natively ([#4569](https://github.com/matrix-org/matrix-js-sdk/pull/4569)). Contributed by @t3chguy.
23
+ * Re-send MatrixRTC media encryption keys for a new joiner even if a rotation is in progress ([#4561](https://github.com/matrix-org/matrix-js-sdk/pull/4561)). Contributed by @hughns.
24
+ * Support MSC4222 `state_after` ([#4487](https://github.com/matrix-org/matrix-js-sdk/pull/4487)). Contributed by @dbkr.
25
+ * Revert "Fix room state being updated with old (now overwritten) state and emitting for those updates. (#4242)" ([#4532](https://github.com/matrix-org/matrix-js-sdk/pull/4532)). Contributed by @toger5.
26
+
27
+ ## 🐛 Bug Fixes
28
+
29
+ * Fix age field check in event echo processing ([#3635](https://github.com/matrix-org/matrix-js-sdk/pull/3635)). Contributed by @stas-demydiuk.
30
+
31
+
1
32
  Changes in [34.13.0](https://github.com/matrix-org/matrix-js-sdk/releases/tag/v34.13.0) (2024-12-03)
2
33
  ====================================================================================================
3
34
  ## 🦖 Deprecations
package/README.md CHANGED
@@ -126,26 +126,26 @@ const img = await fetch(downloadUrl, {
126
126
  This SDK provides a full object model around the Matrix Client-Server API and emits
127
127
  events for incoming data and state changes. Aside from wrapping the HTTP API, it:
128
128
 
129
- - Handles syncing (via `/sync`)
130
- - Handles the generation of "friendly" room and member names.
131
- - Handles historical `RoomMember` information (e.g. display names).
132
- - Manages room member state across multiple events (e.g. it handles typing, power
133
- levels and membership changes).
134
- - Exposes high-level objects like `Rooms`, `RoomState`, `RoomMembers` and `Users`
135
- which can be listened to for things like name changes, new messages, membership
136
- changes, presence changes, and more.
137
- - Handle "local echo" of messages sent using the SDK. This means that messages
138
- that have just been sent will appear in the timeline as 'sending', until it
139
- completes. This is beneficial because it prevents there being a gap between
140
- hitting the send button and having the "remote echo" arrive.
141
- - Mark messages which failed to send as not sent.
142
- - Automatically retry requests to send messages due to network errors.
143
- - Automatically retry requests to send messages due to rate limiting errors.
144
- - Handle queueing of messages.
145
- - Handles pagination.
146
- - Handle assigning push actions for events.
147
- - Handles room initial sync on accepting invites.
148
- - Handles WebRTC calling.
129
+ - Handles syncing (via `/sync`)
130
+ - Handles the generation of "friendly" room and member names.
131
+ - Handles historical `RoomMember` information (e.g. display names).
132
+ - Manages room member state across multiple events (e.g. it handles typing, power
133
+ levels and membership changes).
134
+ - Exposes high-level objects like `Rooms`, `RoomState`, `RoomMembers` and `Users`
135
+ which can be listened to for things like name changes, new messages, membership
136
+ changes, presence changes, and more.
137
+ - Handle "local echo" of messages sent using the SDK. This means that messages
138
+ that have just been sent will appear in the timeline as 'sending', until it
139
+ completes. This is beneficial because it prevents there being a gap between
140
+ hitting the send button and having the "remote echo" arrive.
141
+ - Mark messages which failed to send as not sent.
142
+ - Automatically retry requests to send messages due to network errors.
143
+ - Automatically retry requests to send messages due to rate limiting errors.
144
+ - Handle queueing of messages.
145
+ - Handles pagination.
146
+ - Handle assigning push actions for events.
147
+ - Handles room initial sync on accepting invites.
148
+ - Handles WebRTC calling.
149
149
 
150
150
  # Usage
151
151
 
@@ -307,7 +307,7 @@ Then visit `http://localhost:8005` to see the API docs.
307
307
 
308
308
  ## Initialization
309
309
 
310
- **Do not use `matrixClient.initCrypto()`. This method is deprecated and no longer maintained.**
310
+ **Do not use `matrixClient.initLegacyCrypto()`. This method is deprecated and no longer maintained.**
311
311
 
312
312
  To initialize the end-to-end encryption support in the matrix client:
313
313
 
@@ -325,6 +325,8 @@ await matrixClient.initRustCrypto();
325
325
 
326
326
  After calling `initRustCrypto`, you can obtain a reference to the [`CryptoApi`](https://matrix-org.github.io/matrix-js-sdk/interfaces/crypto_api.CryptoApi.html) interface, which is the main entry point for end-to-end encryption, by calling [`MatrixClient.getCrypto`](https://matrix-org.github.io/matrix-js-sdk/classes/matrix.MatrixClient.html#getCrypto).
327
327
 
328
+ **WARNING**: the cryptography stack is not thread-safe. Having multiple `MatrixClient` instances connected to the same Indexed DB will cause data corruption and decryption failures. The application layer is responsible for ensuring that only one `MatrixClient` issue is instantiated at a time.
329
+
328
330
  ## Secret storage
329
331
 
330
332
  You should normally set up [secret storage](https://spec.matrix.org/v1.12/client-server-api/#secret-storage) before using the end-to-end encryption. To do this, call [`CryptoApi.bootstrapSecretStorage`](https://matrix-org.github.io/matrix-js-sdk/interfaces/crypto_api.CryptoApi.html#bootstrapSecretStorage).
@@ -396,10 +398,10 @@ Once the cross-signing is set up on one of your devices, you can verify another
396
398
 
397
399
  ## Migrating from the legacy crypto stack to Rust crypto
398
400
 
399
- If your application previously used the legacy crypto stack, (i.e, it called `MatrixClient.initCrypto()`), you will
401
+ If your application previously used the legacy crypto stack, (i.e, it called `MatrixClient.initLegacyCrypto()`), you will
400
402
  need to migrate existing devices to the Rust crypto stack.
401
403
 
402
- This migration happens automatically when you call `initRustCrypto()` instead of `initCrypto()`,
404
+ This migration happens automatically when you call `initRustCrypto()` instead of `initLegacyCrypto()`,
403
405
  but you need to provide the legacy [`cryptoStore`](https://matrix-org.github.io/matrix-js-sdk/interfaces/matrix.ICreateClientOpts.html#cryptoStore) and [`pickleKey`](https://matrix-org.github.io/matrix-js-sdk/interfaces/matrix.ICreateClientOpts.html#pickleKey) to [`createClient`](https://matrix-org.github.io/matrix-js-sdk/functions/matrix.createClient.html):
404
406
 
405
407
  ```javascript
package/git-revision.txt CHANGED
@@ -1 +1 @@
1
- d3f5526ec07dcbd0e4677a56b5e53f7d3a4cbcc2
1
+ bee65ff13f1796a540e493ec00e513949e0f366f
@@ -1 +1 @@
1
- {"version":3,"file":"global.d.js","names":[],"sources":["../../src/@types/global.d.ts"],"sourcesContent":["/*\nCopyright 2020 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\n// this is needed to tell TS about globalThis.Olm\nimport \"@matrix-org/olm\";\n\nexport {};\n\ndeclare global {\n // use `number` as the return type in all cases for globalThis.set{Interval,Timeout},\n // so we don't accidentally use the methods on NodeJS.Timeout - they only exist in a subset of environments.\n // The overload for clear{Interval,Timeout} is resolved as expected.\n // We use `ReturnType<typeof setTimeout>` in the code to be agnostic of if this definition gets loaded.\n function setInterval(handler: TimerHandler, timeout: number, ...arguments: any[]): number;\n function setTimeout(handler: TimerHandler, timeout: number, ...arguments: any[]): number;\n\n namespace NodeJS {\n interface Global {\n // marker variable used to detect both the browser & node entrypoints being used at once\n __js_sdk_entrypoint: unknown;\n }\n }\n\n interface MediaDevices {\n // This is experimental and types don't know about it yet\n // https://github.com/microsoft/TypeScript/issues/33232\n getDisplayMedia(constraints: MediaStreamConstraints | DesktopCapturerConstraints): Promise<MediaStream>;\n getUserMedia(constraints: MediaStreamConstraints | DesktopCapturerConstraints): Promise<MediaStream>;\n }\n\n interface DesktopCapturerConstraints {\n audio:\n | boolean\n | {\n mandatory: {\n chromeMediaSource: string;\n chromeMediaSourceId: string;\n };\n };\n video:\n | boolean\n | {\n mandatory: {\n chromeMediaSource: string;\n chromeMediaSourceId: string;\n };\n };\n }\n\n interface DummyInterfaceWeShouldntBeUsingThis {}\n\n interface Navigator {\n // We check for the webkit-prefixed getUserMedia to detect if we're\n // on webkit: we should check if we still need to do this\n webkitGetUserMedia: DummyInterfaceWeShouldntBeUsingThis;\n }\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,OAAO,iBAAiB;AAExB","ignoreList":[]}
1
+ {"version":3,"file":"global.d.js","names":[],"sources":["../../src/@types/global.d.ts"],"sourcesContent":["/*\nCopyright 2020 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\n// this is needed to tell TS about globalThis.Olm\nimport \"@matrix-org/olm\";\n\nexport {};\n\ndeclare global {\n // use `number` as the return type in all cases for globalThis.set{Interval,Timeout},\n // so we don't accidentally use the methods on NodeJS.Timeout - they only exist in a subset of environments.\n // The overload for clear{Interval,Timeout} is resolved as expected.\n // We use `ReturnType<typeof setTimeout>` in the code to be agnostic of if this definition gets loaded.\n function setInterval(handler: TimerHandler, timeout: number, ...arguments: any[]): number;\n function setTimeout(handler: TimerHandler, timeout: number, ...arguments: any[]): number;\n\n namespace NodeJS {\n interface Global {\n // marker variable used to detect both the browser & node entrypoints being used at once\n __js_sdk_entrypoint: unknown;\n }\n }\n\n interface MediaDevices {\n // This is experimental and types don't know about it yet\n // https://github.com/microsoft/TypeScript/issues/33232\n getDisplayMedia(constraints: MediaStreamConstraints | DesktopCapturerConstraints): Promise<MediaStream>;\n getUserMedia(constraints: MediaStreamConstraints | DesktopCapturerConstraints): Promise<MediaStream>;\n }\n\n interface DesktopCapturerConstraints {\n audio:\n | boolean\n | {\n mandatory: {\n chromeMediaSource: string;\n chromeMediaSourceId: string;\n };\n };\n video:\n | boolean\n | {\n mandatory: {\n chromeMediaSource: string;\n chromeMediaSourceId: string;\n };\n };\n }\n\n interface DummyInterfaceWeShouldntBeUsingThis {}\n\n interface Navigator {\n // We check for the webkit-prefixed getUserMedia to detect if we're\n // on webkit: we should check if we still need to do this\n webkitGetUserMedia?: DummyInterfaceWeShouldntBeUsingThis;\n }\n\n export interface Uint8ArrayToBase64Options {\n alphabet?: \"base64\" | \"base64url\";\n omitPadding?: boolean;\n }\n\n interface Uint8Array {\n // https://tc39.es/proposal-arraybuffer-base64/spec/#sec-uint8array.prototype.tobase64\n toBase64?(options?: Uint8ArrayToBase64Options): string;\n }\n\n export interface Uint8ArrayFromBase64Options {\n alphabet?: \"base64\"; // Our fallback code only handles base64.\n lastChunkHandling?: \"loose\"; // Our fallback code doesn't support other handling at this time.\n }\n\n interface Uint8ArrayConstructor {\n // https://tc39.es/proposal-arraybuffer-base64/spec/#sec-uint8array.frombase64\n fromBase64?(base64: string, options?: Uint8ArrayFromBase64Options): Uint8Array;\n }\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,OAAO,iBAAiB;AAExB","ignoreList":[]}
@@ -79,7 +79,7 @@ export declare class AutoDiscovery {
79
79
  * configuration, which may include error states. Rejects on unexpected
80
80
  * failure, not when verification fails.
81
81
  */
82
- static fromDiscoveryConfig(wellknown: IClientWellKnown): Promise<ClientConfig>;
82
+ static fromDiscoveryConfig(wellknown?: IClientWellKnown): Promise<ClientConfig>;
83
83
  /**
84
84
  * Attempts to automatically discover client configuration information
85
85
  * prior to logging in. Such information includes the homeserver URL
@@ -1 +1 @@
1
- {"version":3,"file":"autodiscovery.d.ts","sourceRoot":"","sources":["../src/autodiscovery.ts"],"names":[],"mappings":"AAiBA,OAAO,EAAE,gBAAgB,EAAE,gBAAgB,EAAmB,MAAM,aAAa,CAAC;AAQlF,oBAAY,mBAAmB;IAC3B,OAAO,YAAY;IACnB,MAAM,WAAW;IACjB,MAAM,WAAW;IACjB,WAAW,gBAAgB;IAC3B,UAAU,eAAe;CAC5B;AAED,oBAAY,kBAAkB;IAC1B,OAAO,0CAA0C;IACjD,cAAc,0DAA0D;IACxE,gBAAgB,sCAAsC;IACtD,iBAAiB,mEAAmE;IACpF,gBAAgB,2CAA2C;IAC3D,qBAAqB,sEAAsE;IAC3F,SAAS,+CAA+C;IAC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ryAction","AutoDiscoveryError","AutoDiscovery","fromDiscoveryConfig","wellknown","_this","_asyncToGenerator","_hsVersions$raw","clientConfig","state","FAIL_ERROR","error","ERROR_INVALID","base_url","PROMPT","FAIL_PROMPT","Promise","resolve","ERROR_INVALID_HS_BASE_URL","hsUrl","sanitizeWellKnownUrl","hsVersions","fetchWellKnownObject","concat","Array","isArray","raw","ERROR_INVALID_HOMESERVER","hsVersionSet","Set","supportedVersionFound","version","has","ERROR_UNSUPPORTED_HOMESERVER_SPEC_VERSION","SUCCESS","isUrl","failingClientConfig","ERROR_INVALID_IS","ERROR_INVALID_IS_BASE_URL","isResponse","action","ERROR_INVALID_IDENTITY_SERVER","toString","length","Object","keys","forEach","k","notProps","prop","includes","findClientConfig","domain","_this2","Error","domainWithProtocol","reason","IGNORE","getRawClientConfig","_this3","_response$raw","response","url","_parsed","parsed","URL","e","hostname","protocol","port","path","pathname","saferUrl","endsWith","substring","fetch","resource","options","fetchFn","globalThis","setFetchFn","method","Get","signal","status","ERROR_MISSING_WELLKNOWN","ok","err","message","json","name","ERROR_INVALID_JSON","_defineProperty","Invalid","GenericFailure","InvalidHsBaseUrl","InvalidHomeserver","InvalidIsBaseUrl","InvalidIdentityServer","InvalidIs","MissingWellknown","InvalidJson","UnsupportedHomeserverSpecVersion"],"sources":["../src/autodiscovery.ts"],"sourcesContent":["/*\nCopyright 2018 New Vector Ltd\nCopyright 2019 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 { IClientWellKnown, IWellKnownConfig, IServerVersions } from \"./client.ts\";\nimport { logger } from \"./logger.ts\";\nimport { MatrixError, Method, timeoutSignal } from \"./http-api/index.ts\";\nimport { SUPPORTED_MATRIX_VERSIONS } from \"./version-support.ts\";\n\n// Dev note: Auto discovery is part of the spec.\n// See: https://matrix.org/docs/spec/client_server/r0.4.0.html#server-discovery\n\nexport enum AutoDiscoveryAction {\n SUCCESS = \"SUCCESS\",\n IGNORE = \"IGNORE\",\n PROMPT = \"PROMPT\",\n FAIL_PROMPT = \"FAIL_PROMPT\",\n FAIL_ERROR = \"FAIL_ERROR\",\n}\n\nexport enum AutoDiscoveryError {\n Invalid = \"Invalid homeserver discovery response\",\n GenericFailure = \"Failed to get autodiscovery configuration from server\",\n InvalidHsBaseUrl = \"Invalid base_url for m.homeserver\",\n InvalidHomeserver = \"Homeserver URL does not appear to be a valid Matrix homeserver\",\n InvalidIsBaseUrl = \"Invalid base_url for m.identity_server\",\n InvalidIdentityServer = \"Identity server URL does not appear to be a valid identity server\",\n InvalidIs = \"Invalid identity server discovery response\",\n MissingWellknown = \"No .well-known JSON file found\",\n InvalidJson = \"Invalid JSON\",\n UnsupportedHomeserverSpecVersion = \"The homeserver does not meet the version requirements\",\n\n // TODO: Implement when Sydent supports the `/versions` endpoint - https://github.com/matrix-org/sydent/issues/424\n //IdentityServerTooOld = \"The identity server does not meet the minimum version requirements\",\n}\n\ninterface AutoDiscoveryState {\n state: AutoDiscoveryAction;\n error?: IWellKnownConfig[\"error\"] | null;\n}\ninterface WellKnownConfig extends Omit<IWellKnownConfig, \"error\">, AutoDiscoveryState {}\n\nexport interface ClientConfig extends Omit<IClientWellKnown, \"m.homeserver\" | \"m.identity_server\"> {\n \"m.homeserver\": WellKnownConfig;\n \"m.identity_server\": WellKnownConfig;\n}\n\n/**\n * Utilities for automatically discovery resources, such as homeservers\n * for users to log in to.\n */\nexport class AutoDiscovery {\n // Dev note: the constants defined here are related to but not\n // exactly the same as those in the spec. This is to hopefully\n // translate the meaning of the states in the spec, but also\n // support our own if needed.\n\n public static readonly ERROR_INVALID = AutoDiscoveryError.Invalid;\n\n public static readonly ERROR_GENERIC_FAILURE = AutoDiscoveryError.GenericFailure;\n\n public static readonly ERROR_INVALID_HS_BASE_URL = AutoDiscoveryError.InvalidHsBaseUrl;\n\n public static readonly ERROR_INVALID_HOMESERVER = AutoDiscoveryError.InvalidHomeserver;\n\n public static readonly ERROR_INVALID_IS_BASE_URL = AutoDiscoveryError.InvalidIsBaseUrl;\n\n public static readonly ERROR_INVALID_IDENTITY_SERVER = AutoDiscoveryError.InvalidIdentityServer;\n\n public static readonly ERROR_INVALID_IS = AutoDiscoveryError.InvalidIs;\n\n public static readonly ERROR_MISSING_WELLKNOWN = AutoDiscoveryError.MissingWellknown;\n\n public static readonly ERROR_INVALID_JSON = AutoDiscoveryError.InvalidJson;\n\n public static readonly ERROR_UNSUPPORTED_HOMESERVER_SPEC_VERSION =\n AutoDiscoveryError.UnsupportedHomeserverSpecVersion;\n\n public static readonly ALL_ERRORS = Object.keys(AutoDiscoveryError) as AutoDiscoveryError[];\n\n /**\n * The auto discovery failed. The client is expected to communicate\n * the error to the user and refuse logging in.\n */\n public static readonly FAIL_ERROR = AutoDiscoveryAction.FAIL_ERROR;\n\n /**\n * The auto discovery failed, however the client may still recover\n * from the problem. The client is recommended to that the same\n * action it would for PROMPT while also warning the user about\n * what went wrong. The client may also treat this the same as\n * a FAIL_ERROR state.\n */\n public static readonly FAIL_PROMPT = AutoDiscoveryAction.FAIL_PROMPT;\n\n /**\n * The auto discovery didn't fail but did not find anything of\n * interest. The client is expected to prompt the user for more\n * information, or fail if it prefers.\n */\n public static readonly PROMPT = AutoDiscoveryAction.PROMPT;\n\n /**\n * The auto discovery was successful.\n */\n public static readonly SUCCESS = AutoDiscoveryAction.SUCCESS;\n\n /**\n * Validates and verifies client configuration information for purposes\n * of logging in. Such information includes the homeserver URL\n * and identity server URL the client would want. Additional details\n * may also be included, and will be transparently brought into the\n * response object unaltered.\n * @param wellknown - The configuration object itself, as returned\n * by the .well-known auto-discovery endpoint.\n * @returns Promise which resolves to the verified\n * configuration, which may include error states. Rejects on unexpected\n * failure, not when verification fails.\n */\n public static async fromDiscoveryConfig(wellknown: IClientWellKnown): Promise<ClientConfig> {\n // Step 1 is to get the config, which is provided to us here.\n\n // We default to an error state to make the first few checks easier to\n // write. We'll update the properties of this object over the duration\n // of this function.\n const clientConfig: ClientConfig = {\n \"m.homeserver\": {\n state: AutoDiscovery.FAIL_ERROR,\n error: AutoDiscovery.ERROR_INVALID,\n base_url: null,\n },\n \"m.identity_server\": {\n // Technically, we don't have a problem with the identity server\n // config at this point.\n state: AutoDiscovery.PROMPT,\n error: null,\n base_url: null,\n },\n };\n\n if (!wellknown?.[\"m.homeserver\"]) {\n logger.error(\"No m.homeserver key in config\");\n\n clientConfig[\"m.homeserver\"].state = AutoDiscovery.FAIL_PROMPT;\n clientConfig[\"m.homeserver\"].error = AutoDiscovery.ERROR_INVALID;\n\n return Promise.resolve(clientConfig);\n }\n\n if (!wellknown[\"m.homeserver\"][\"base_url\"]) {\n logger.error(\"No m.homeserver base_url in config\");\n\n clientConfig[\"m.homeserver\"].state = AutoDiscovery.FAIL_PROMPT;\n clientConfig[\"m.homeserver\"].error = AutoDiscovery.ERROR_INVALID_HS_BASE_URL;\n\n return Promise.resolve(clientConfig);\n }\n\n // Step 2: Make sure the homeserver URL is valid *looking*. We'll make\n // sure it points to a homeserver in Step 3.\n const hsUrl = this.sanitizeWellKnownUrl(wellknown[\"m.homeserver\"][\"base_url\"]);\n if (!hsUrl) {\n logger.error(\"Invalid base_url for m.homeserver\");\n clientConfig[\"m.homeserver\"].error = AutoDiscovery.ERROR_INVALID_HS_BASE_URL;\n return Promise.resolve(clientConfig);\n }\n\n // Step 3: Make sure the homeserver URL points to a homeserver.\n const hsVersions = await this.fetchWellKnownObject<IServerVersions>(`${hsUrl}/_matrix/client/versions`);\n if (!hsVersions || !Array.isArray(hsVersions.raw?.[\"versions\"])) {\n logger.error(\"Invalid /versions response\");\n clientConfig[\"m.homeserver\"].error = AutoDiscovery.ERROR_INVALID_HOMESERVER;\n\n // Supply the base_url to the caller because they may be ignoring liveliness\n // errors, like this one.\n clientConfig[\"m.homeserver\"].base_url = hsUrl;\n\n return Promise.resolve(clientConfig);\n }\n\n // Step 3.1: Non-spec check to ensure the server will actually work for us. We need to check if\n // any of the versions in `SUPPORTED_MATRIX_VERSIONS` are listed in the /versions response.\n const hsVersionSet = new Set(hsVersions.raw![\"versions\"]);\n let supportedVersionFound = false;\n for (const version of SUPPORTED_MATRIX_VERSIONS) {\n if (hsVersionSet.has(version)) {\n supportedVersionFound = true;\n break;\n }\n }\n if (!supportedVersionFound) {\n logger.error(\"Homeserver does not meet version requirements\");\n clientConfig[\"m.homeserver\"].error = AutoDiscovery.ERROR_UNSUPPORTED_HOMESERVER_SPEC_VERSION;\n\n // Supply the base_url to the caller because they may be ignoring liveliness\n // errors, like this one.\n clientConfig[\"m.homeserver\"].base_url = hsUrl;\n\n return Promise.resolve(clientConfig);\n }\n\n // Step 4: Now that the homeserver looks valid, update our client config.\n clientConfig[\"m.homeserver\"] = {\n state: AutoDiscovery.SUCCESS,\n error: null,\n base_url: hsUrl,\n };\n\n // Step 5: Try to pull out the identity server configuration\n let isUrl: string | boolean = \"\";\n if (wellknown[\"m.identity_server\"]) {\n // We prepare a failing identity server response to save lines later\n // in this branch.\n const failingClientConfig: ClientConfig = {\n \"m.homeserver\": clientConfig[\"m.homeserver\"],\n \"m.identity_server\": {\n state: AutoDiscovery.FAIL_PROMPT,\n error: AutoDiscovery.ERROR_INVALID_IS,\n base_url: null,\n },\n };\n\n // Step 5a: Make sure the URL is valid *looking*. We'll make sure it\n // points to an identity server in Step 5b.\n isUrl = this.sanitizeWellKnownUrl(wellknown[\"m.identity_server\"][\"base_url\"]);\n if (!isUrl) {\n logger.error(\"Invalid base_url for m.identity_server\");\n failingClientConfig[\"m.identity_server\"].error = AutoDiscovery.ERROR_INVALID_IS_BASE_URL;\n return Promise.resolve(failingClientConfig);\n }\n\n // Step 5b: Verify there is an identity server listening on the provided\n // URL.\n const isResponse = await this.fetchWellKnownObject(`${isUrl}/_matrix/identity/v2`);\n if (!isResponse?.raw || isResponse.action !== AutoDiscoveryAction.SUCCESS) {\n logger.error(\"Invalid /v2 response\");\n failingClientConfig[\"m.identity_server\"].error = AutoDiscovery.ERROR_INVALID_IDENTITY_SERVER;\n\n // Supply the base_url to the caller because they may be ignoring\n // liveliness errors, like this one.\n failingClientConfig[\"m.identity_server\"].base_url = isUrl;\n\n return Promise.resolve(failingClientConfig);\n }\n }\n\n // Step 6: Now that the identity server is valid, or never existed,\n // populate the IS section.\n if (isUrl && isUrl.toString().length > 0) {\n clientConfig[\"m.identity_server\"] = {\n state: AutoDiscovery.SUCCESS,\n error: null,\n base_url: isUrl,\n };\n }\n\n // Step 7: Copy any other keys directly into the clientConfig. This is for\n // things like custom configuration of services.\n Object.keys(wellknown).forEach((k: keyof IClientWellKnown) => {\n if (k === \"m.homeserver\" || k === \"m.identity_server\") {\n // Only copy selected parts of the config to avoid overwriting\n // properties computed by the validation logic above.\n const notProps = [\"error\", \"state\", \"base_url\"];\n for (const prop of Object.keys(wellknown[k]!)) {\n if (notProps.includes(prop)) continue;\n type Prop = Exclude<keyof IWellKnownConfig, \"error\" | \"state\" | \"base_url\">;\n // @ts-ignore - ts gets unhappy as we're mixing types here\n clientConfig[k][prop as Prop] = wellknown[k]![prop as Prop];\n }\n } else {\n // Just copy the whole thing over otherwise\n clientConfig[k] = wellknown[k];\n }\n });\n\n // Step 8: Give the config to the caller (finally)\n return Promise.resolve(clientConfig);\n }\n\n /**\n * Attempts to automatically discover client configuration information\n * prior to logging in. Such information includes the homeserver URL\n * and identity server URL the client would want. Additional details\n * may also be discovered, and will be transparently included in the\n * response object unaltered.\n * @param domain - The homeserver domain to perform discovery\n * on. For example, \"matrix.org\".\n * @returns Promise which resolves to the discovered\n * configuration, which may include error states. Rejects on unexpected\n * failure, not when discovery fails.\n */\n public static async findClientConfig(domain: string): Promise<ClientConfig> {\n if (!domain || typeof domain !== \"string\" || domain.length === 0) {\n throw new Error(\"'domain' must be a string of non-zero length\");\n }\n\n // We use a .well-known lookup for all cases. According to the spec, we\n // can do other discovery mechanisms if we want such as custom lookups\n // however we won't bother with that here (mostly because the spec only\n // supports .well-known right now).\n //\n // By using .well-known, we need to ensure we at least pull out a URL\n // for the homeserver. We don't really need an identity server configuration\n // but will return one anyways (with state PROMPT) to make development\n // easier for clients. If we can't get a homeserver URL, all bets are\n // off on the rest of the config and we'll assume it is invalid too.\n\n // We default to an error state to make the first few checks easier to\n // write. We'll update the properties of this object over the duration\n // of this function.\n const clientConfig: ClientConfig = {\n \"m.homeserver\": {\n state: AutoDiscovery.FAIL_ERROR,\n error: AutoDiscovery.ERROR_INVALID,\n base_url: null,\n },\n \"m.identity_server\": {\n // Technically, we don't have a problem with the identity server\n // config at this point.\n state: AutoDiscovery.PROMPT,\n error: null,\n base_url: null,\n },\n };\n\n // Step 1: Actually request the .well-known JSON file and make sure it\n // at least has a homeserver definition.\n const domainWithProtocol = domain.includes(\"://\") ? domain : `https://${domain}`;\n const wellknown = await this.fetchWellKnownObject(`${domainWithProtocol}/.well-known/matrix/client`);\n if (!wellknown || wellknown.action !== AutoDiscoveryAction.SUCCESS) {\n logger.error(\"No response or error when parsing .well-known\");\n if (wellknown.reason) logger.error(wellknown.reason);\n if (wellknown.action === AutoDiscoveryAction.IGNORE) {\n clientConfig[\"m.homeserver\"] = {\n state: AutoDiscovery.PROMPT,\n error: null,\n base_url: null,\n };\n } else {\n // this can only ever be FAIL_PROMPT at this point.\n clientConfig[\"m.homeserver\"].state = AutoDiscovery.FAIL_PROMPT;\n clientConfig[\"m.homeserver\"].error = AutoDiscovery.ERROR_INVALID;\n }\n return Promise.resolve(clientConfig);\n }\n\n // Step 2: Validate and parse the config\n return AutoDiscovery.fromDiscoveryConfig(wellknown.raw!);\n }\n\n /**\n * Gets the raw discovery client configuration for the given domain name.\n * Should only be used if there's no validation to be done on the resulting\n * object, otherwise use findClientConfig().\n * @param domain - The domain to get the client config for.\n * @returns Promise which resolves to the domain's client config. Can\n * be an empty object.\n */\n public static async getRawClientConfig(domain?: string): Promise<IClientWellKnown> {\n if (!domain || typeof domain !== \"string\" || domain.length === 0) {\n throw new Error(\"'domain' must be a string of non-zero length\");\n }\n\n const response = await this.fetchWellKnownObject(`https://${domain}/.well-known/matrix/client`);\n if (!response) return {};\n return response.raw ?? {};\n }\n\n /**\n * Sanitizes a given URL to ensure it is either an HTTP or HTTP URL and\n * is suitable for the requirements laid out by .well-known auto discovery.\n * If valid, the URL will also be stripped of any trailing slashes.\n * @param url - The potentially invalid URL to sanitize.\n * @returns The sanitized URL or a falsey value if the URL is invalid.\n * @internal\n */\n private static sanitizeWellKnownUrl(url?: string | null): string | false {\n if (!url) return false;\n\n try {\n let parsed: URL | undefined;\n try {\n parsed = new URL(url);\n } catch (e) {\n logger.error(\"Could not parse url\", e);\n }\n\n if (!parsed?.hostname) return false;\n if (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") return false;\n\n const port = parsed.port ? `:${parsed.port}` : \"\";\n const path = parsed.pathname ? parsed.pathname : \"\";\n let saferUrl = `${parsed.protocol}//${parsed.hostname}${port}${path}`;\n if (saferUrl.endsWith(\"/\")) {\n saferUrl = saferUrl.substring(0, saferUrl.length - 1);\n }\n return saferUrl;\n } catch (e) {\n logger.error(e);\n return false;\n }\n }\n\n private static fetch(resource: URL | string, options?: RequestInit): ReturnType<typeof globalThis.fetch> {\n if (this.fetchFn) {\n return this.fetchFn(resource, options);\n }\n return globalThis.fetch(resource, options);\n }\n\n private static fetchFn?: typeof globalThis.fetch;\n\n public static setFetchFn(fetchFn: typeof globalThis.fetch): void {\n AutoDiscovery.fetchFn = fetchFn;\n }\n\n /**\n * Fetches a JSON object from a given URL, as expected by all .well-known\n * related lookups. If the server gives a 404 then the `action` will be\n * IGNORE. If the server returns something that isn't JSON, the `action`\n * will be FAIL_PROMPT. For any other failure the `action` will be FAIL_PROMPT.\n *\n * The returned object will be a result of the call in object form with\n * the following properties:\n * raw: The JSON object returned by the server.\n * action: One of SUCCESS, IGNORE, or FAIL_PROMPT.\n * reason: Relatively human-readable description of what went wrong.\n * error: The actual Error, if one exists.\n * @param url - The URL to fetch a JSON object from.\n * @returns Promise which resolves to the returned state.\n * @internal\n */\n private static async fetchWellKnownObject<T = IWellKnownConfig>(\n url: string,\n ): Promise<IWellKnownConfig<Partial<T>>> {\n let response: Response;\n\n try {\n response = await AutoDiscovery.fetch(url, {\n method: Method.Get,\n signal: timeoutSignal(5000),\n });\n\n if (response.status === 404) {\n return {\n raw: {},\n action: AutoDiscoveryAction.IGNORE,\n reason: AutoDiscovery.ERROR_MISSING_WELLKNOWN,\n };\n }\n\n if (!response.ok) {\n return {\n raw: {},\n action: AutoDiscoveryAction.FAIL_PROMPT,\n reason: \"General failure\",\n };\n }\n } catch (err) {\n const error = err as AutoDiscoveryError | string | undefined;\n let reason = \"\";\n if (typeof error === \"object\") {\n reason = (<Error>error)?.message;\n }\n\n return {\n error,\n raw: {},\n action: AutoDiscoveryAction.FAIL_PROMPT,\n reason: reason || \"General failure\",\n };\n }\n\n try {\n return {\n raw: await response.json(),\n action: AutoDiscoveryAction.SUCCESS,\n };\n } catch (err) {\n const error = err as Error;\n return {\n error,\n raw: {},\n action: AutoDiscoveryAction.FAIL_PROMPT,\n reason:\n (error as MatrixError)?.name === \"SyntaxError\"\n ? AutoDiscovery.ERROR_INVALID_JSON\n : AutoDiscovery.ERROR_INVALID,\n };\n }\n }\n}\n"],"mappings":";;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAGA,SAASA,MAAM,QAAQ,aAAa;AACpC,SAAsBC,MAAM,EAAEC,aAAa,QAAQ,qBAAqB;AACxE,SAASC,yBAAyB,QAAQ,sBAAsB;;AAEhE;AACA;;AAEA,WAAYC,mBAAmB,0BAAnBA,mBAAmB;EAAnBA,mBAAmB;EAAnBA,mBAAmB;EAAnBA,mBAAmB;EAA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U;AAElE;AACJ;AACA;AACA;AACA;AACA;AACA;AANIkF,eAAA,CAnCS1F,aAAa,iBA0CeF,mBAAmB,CAACe,WAAW;AAEpE;AACJ;AACA;AACA;AACA;AAJI6E,eAAA,CA5CS1F,aAAa,YAiDUF,mBAAmB,CAACc,MAAM;AAE1D;AACJ;AACA;AAFI8E,eAAA,CAnDS1F,aAAa,aAsDWF,mBAAmB,CAACkC,OAAO;AAAA0D,eAAA,CAtDnD1F,aAAa","ignoreList":[]}
1
+ {"version":3,"file":"autodiscovery.js","names":["logger","Method","timeoutSignal","SUPPORTED_MATRIX_VERSIONS","AutoDiscoveryAction","AutoDiscoveryError","AutoDiscovery","fromDiscoveryConfig","wellknown","_this","_asyncToGenerator","_hsVersions$raw","clientConfig","state","FAIL_ERROR","error","ERROR_INVALID","base_url","PROMPT","FAIL_PROMPT","Promise","resolve","ERROR_INVALID_HS_BASE_URL","hsUrl","sanitizeWellKnownUrl","hsVersions","fetchWellKnownObject","concat","Array","isArray","raw","ERROR_INVALID_HOMESERVER","hsVersionSet","Set","supportedVersionFound","version","has","ERROR_UNSUPPORTED_HOMESERVER_SPEC_VERSION","SUCCESS","isUrl","failingClientConfig","ERROR_INVALID_IS","ERROR_INVALID_IS_BASE_URL","isResponse","action","ERROR_INVALID_IDENTITY_SERVER","toString","length","Object","keys","forEach","k","notProps","prop","includes","findClientConfig","domain","_this2","Error","domainWithProtocol","reason","IGNORE","getRawClientConfig","_this3","_response$raw","response","url","_parsed","parsed","URL","e","hostname","protocol","port","path","pathname","saferUrl","endsWith","substring","fetch","resource","options","fetchFn","globalThis","setFetchFn","method","Get","signal","status","ERROR_MISSING_WELLKNOWN","ok","err","message","json","name","ERROR_INVALID_JSON","_defineProperty","Invalid","GenericFailure","InvalidHsBaseUrl","InvalidHomeserver","InvalidIsBaseUrl","InvalidIdentityServer","InvalidIs","MissingWellknown","InvalidJson","UnsupportedHomeserverSpecVersion"],"sources":["../src/autodiscovery.ts"],"sourcesContent":["/*\nCopyright 2018 New Vector Ltd\nCopyright 2019 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 { IClientWellKnown, IWellKnownConfig, IServerVersions } from \"./client.ts\";\nimport { logger } from \"./logger.ts\";\nimport { MatrixError, Method, timeoutSignal } from \"./http-api/index.ts\";\nimport { SUPPORTED_MATRIX_VERSIONS } from \"./version-support.ts\";\n\n// Dev note: Auto discovery is part of the spec.\n// See: https://matrix.org/docs/spec/client_server/r0.4.0.html#server-discovery\n\nexport enum AutoDiscoveryAction {\n SUCCESS = \"SUCCESS\",\n IGNORE = \"IGNORE\",\n PROMPT = \"PROMPT\",\n FAIL_PROMPT = \"FAIL_PROMPT\",\n FAIL_ERROR = \"FAIL_ERROR\",\n}\n\nexport enum AutoDiscoveryError {\n Invalid = \"Invalid homeserver discovery response\",\n GenericFailure = \"Failed to get autodiscovery configuration from server\",\n InvalidHsBaseUrl = \"Invalid base_url for m.homeserver\",\n InvalidHomeserver = \"Homeserver URL does not appear to be a valid Matrix homeserver\",\n InvalidIsBaseUrl = \"Invalid base_url for m.identity_server\",\n InvalidIdentityServer = \"Identity server URL does not appear to be a valid identity server\",\n InvalidIs = \"Invalid identity server discovery response\",\n MissingWellknown = \"No .well-known JSON file found\",\n InvalidJson = \"Invalid JSON\",\n UnsupportedHomeserverSpecVersion = \"The homeserver does not meet the version requirements\",\n\n // TODO: Implement when Sydent supports the `/versions` endpoint - https://github.com/matrix-org/sydent/issues/424\n //IdentityServerTooOld = \"The identity server does not meet the minimum version requirements\",\n}\n\ninterface AutoDiscoveryState {\n state: AutoDiscoveryAction;\n error?: IWellKnownConfig[\"error\"] | null;\n}\ninterface WellKnownConfig extends Omit<IWellKnownConfig, \"error\">, AutoDiscoveryState {}\n\nexport interface ClientConfig extends Omit<IClientWellKnown, \"m.homeserver\" | \"m.identity_server\"> {\n \"m.homeserver\": WellKnownConfig;\n \"m.identity_server\": WellKnownConfig;\n}\n\n/**\n * Utilities for automatically discovery resources, such as homeservers\n * for users to log in to.\n */\nexport class AutoDiscovery {\n // Dev note: the constants defined here are related to but not\n // exactly the same as those in the spec. This is to hopefully\n // translate the meaning of the states in the spec, but also\n // support our own if needed.\n\n public static readonly ERROR_INVALID = AutoDiscoveryError.Invalid;\n\n public static readonly ERROR_GENERIC_FAILURE = AutoDiscoveryError.GenericFailure;\n\n public static readonly ERROR_INVALID_HS_BASE_URL = AutoDiscoveryError.InvalidHsBaseUrl;\n\n public static readonly ERROR_INVALID_HOMESERVER = AutoDiscoveryError.InvalidHomeserver;\n\n public static readonly ERROR_INVALID_IS_BASE_URL = AutoDiscoveryError.InvalidIsBaseUrl;\n\n public static readonly ERROR_INVALID_IDENTITY_SERVER = AutoDiscoveryError.InvalidIdentityServer;\n\n public static readonly ERROR_INVALID_IS = AutoDiscoveryError.InvalidIs;\n\n public static readonly ERROR_MISSING_WELLKNOWN = AutoDiscoveryError.MissingWellknown;\n\n public static readonly ERROR_INVALID_JSON = AutoDiscoveryError.InvalidJson;\n\n public static readonly ERROR_UNSUPPORTED_HOMESERVER_SPEC_VERSION =\n AutoDiscoveryError.UnsupportedHomeserverSpecVersion;\n\n public static readonly ALL_ERRORS = Object.keys(AutoDiscoveryError) as AutoDiscoveryError[];\n\n /**\n * The auto discovery failed. The client is expected to communicate\n * the error to the user and refuse logging in.\n */\n public static readonly FAIL_ERROR = AutoDiscoveryAction.FAIL_ERROR;\n\n /**\n * The auto discovery failed, however the client may still recover\n * from the problem. The client is recommended to that the same\n * action it would for PROMPT while also warning the user about\n * what went wrong. The client may also treat this the same as\n * a FAIL_ERROR state.\n */\n public static readonly FAIL_PROMPT = AutoDiscoveryAction.FAIL_PROMPT;\n\n /**\n * The auto discovery didn't fail but did not find anything of\n * interest. The client is expected to prompt the user for more\n * information, or fail if it prefers.\n */\n public static readonly PROMPT = AutoDiscoveryAction.PROMPT;\n\n /**\n * The auto discovery was successful.\n */\n public static readonly SUCCESS = AutoDiscoveryAction.SUCCESS;\n\n /**\n * Validates and verifies client configuration information for purposes\n * of logging in. Such information includes the homeserver URL\n * and identity server URL the client would want. Additional details\n * may also be included, and will be transparently brought into the\n * response object unaltered.\n * @param wellknown - The configuration object itself, as returned\n * by the .well-known auto-discovery endpoint.\n * @returns Promise which resolves to the verified\n * configuration, which may include error states. Rejects on unexpected\n * failure, not when verification fails.\n */\n public static async fromDiscoveryConfig(wellknown?: IClientWellKnown): Promise<ClientConfig> {\n // Step 1 is to get the config, which is provided to us here.\n\n // We default to an error state to make the first few checks easier to\n // write. We'll update the properties of this object over the duration\n // of this function.\n const clientConfig: ClientConfig = {\n \"m.homeserver\": {\n state: AutoDiscovery.FAIL_ERROR,\n error: AutoDiscovery.ERROR_INVALID,\n base_url: null,\n },\n \"m.identity_server\": {\n // Technically, we don't have a problem with the identity server\n // config at this point.\n state: AutoDiscovery.PROMPT,\n error: null,\n base_url: null,\n },\n };\n\n if (!wellknown?.[\"m.homeserver\"]) {\n logger.error(\"No m.homeserver key in config\");\n\n clientConfig[\"m.homeserver\"].state = AutoDiscovery.FAIL_PROMPT;\n clientConfig[\"m.homeserver\"].error = AutoDiscovery.ERROR_INVALID;\n\n return Promise.resolve(clientConfig);\n }\n\n if (!wellknown[\"m.homeserver\"][\"base_url\"]) {\n logger.error(\"No m.homeserver base_url in config\");\n\n clientConfig[\"m.homeserver\"].state = AutoDiscovery.FAIL_PROMPT;\n clientConfig[\"m.homeserver\"].error = AutoDiscovery.ERROR_INVALID_HS_BASE_URL;\n\n return Promise.resolve(clientConfig);\n }\n\n // Step 2: Make sure the homeserver URL is valid *looking*. We'll make\n // sure it points to a homeserver in Step 3.\n const hsUrl = this.sanitizeWellKnownUrl(wellknown[\"m.homeserver\"][\"base_url\"]);\n if (!hsUrl) {\n logger.error(\"Invalid base_url for m.homeserver\");\n clientConfig[\"m.homeserver\"].error = AutoDiscovery.ERROR_INVALID_HS_BASE_URL;\n return Promise.resolve(clientConfig);\n }\n\n // Step 3: Make sure the homeserver URL points to a homeserver.\n const hsVersions = await this.fetchWellKnownObject<IServerVersions>(`${hsUrl}/_matrix/client/versions`);\n if (!hsVersions || !Array.isArray(hsVersions.raw?.[\"versions\"])) {\n logger.error(\"Invalid /versions response\");\n clientConfig[\"m.homeserver\"].error = AutoDiscovery.ERROR_INVALID_HOMESERVER;\n\n // Supply the base_url to the caller because they may be ignoring liveliness\n // errors, like this one.\n clientConfig[\"m.homeserver\"].base_url = hsUrl;\n\n return Promise.resolve(clientConfig);\n }\n\n // Step 3.1: Non-spec check to ensure the server will actually work for us. We need to check if\n // any of the versions in `SUPPORTED_MATRIX_VERSIONS` are listed in the /versions response.\n const hsVersionSet = new Set(hsVersions.raw![\"versions\"]);\n let supportedVersionFound = false;\n for (const version of SUPPORTED_MATRIX_VERSIONS) {\n if (hsVersionSet.has(version)) {\n supportedVersionFound = true;\n break;\n }\n }\n if (!supportedVersionFound) {\n logger.error(\"Homeserver does not meet version requirements\");\n clientConfig[\"m.homeserver\"].error = AutoDiscovery.ERROR_UNSUPPORTED_HOMESERVER_SPEC_VERSION;\n\n // Supply the base_url to the caller because they may be ignoring liveliness\n // errors, like this one.\n clientConfig[\"m.homeserver\"].base_url = hsUrl;\n\n return Promise.resolve(clientConfig);\n }\n\n // Step 4: Now that the homeserver looks valid, update our client config.\n clientConfig[\"m.homeserver\"] = {\n state: AutoDiscovery.SUCCESS,\n error: null,\n base_url: hsUrl,\n };\n\n // Step 5: Try to pull out the identity server configuration\n let isUrl: string | boolean = \"\";\n if (wellknown[\"m.identity_server\"]) {\n // We prepare a failing identity server response to save lines later\n // in this branch.\n const failingClientConfig: ClientConfig = {\n \"m.homeserver\": clientConfig[\"m.homeserver\"],\n \"m.identity_server\": {\n state: AutoDiscovery.FAIL_PROMPT,\n error: AutoDiscovery.ERROR_INVALID_IS,\n base_url: null,\n },\n };\n\n // Step 5a: Make sure the URL is valid *looking*. We'll make sure it\n // points to an identity server in Step 5b.\n isUrl = this.sanitizeWellKnownUrl(wellknown[\"m.identity_server\"][\"base_url\"]);\n if (!isUrl) {\n logger.error(\"Invalid base_url for m.identity_server\");\n failingClientConfig[\"m.identity_server\"].error = AutoDiscovery.ERROR_INVALID_IS_BASE_URL;\n return Promise.resolve(failingClientConfig);\n }\n\n // Step 5b: Verify there is an identity server listening on the provided\n // URL.\n const isResponse = await this.fetchWellKnownObject(`${isUrl}/_matrix/identity/v2`);\n if (!isResponse?.raw || isResponse.action !== AutoDiscoveryAction.SUCCESS) {\n logger.error(\"Invalid /v2 response\");\n failingClientConfig[\"m.identity_server\"].error = AutoDiscovery.ERROR_INVALID_IDENTITY_SERVER;\n\n // Supply the base_url to the caller because they may be ignoring\n // liveliness errors, like this one.\n failingClientConfig[\"m.identity_server\"].base_url = isUrl;\n\n return Promise.resolve(failingClientConfig);\n }\n }\n\n // Step 6: Now that the identity server is valid, or never existed,\n // populate the IS section.\n if (isUrl && isUrl.toString().length > 0) {\n clientConfig[\"m.identity_server\"] = {\n state: AutoDiscovery.SUCCESS,\n error: null,\n base_url: isUrl,\n };\n }\n\n // Step 7: Copy any other keys directly into the clientConfig. This is for\n // things like custom configuration of services.\n Object.keys(wellknown).forEach((k: keyof IClientWellKnown) => {\n if (k === \"m.homeserver\" || k === \"m.identity_server\") {\n // Only copy selected parts of the config to avoid overwriting\n // properties computed by the validation logic above.\n const notProps = [\"error\", \"state\", \"base_url\"];\n for (const prop of Object.keys(wellknown[k]!)) {\n if (notProps.includes(prop)) continue;\n type Prop = Exclude<keyof IWellKnownConfig, \"error\" | \"state\" | \"base_url\">;\n // @ts-ignore - ts gets unhappy as we're mixing types here\n clientConfig[k][prop as Prop] = wellknown[k]![prop as Prop];\n }\n } else {\n // Just copy the whole thing over otherwise\n clientConfig[k] = wellknown[k];\n }\n });\n\n // Step 8: Give the config to the caller (finally)\n return Promise.resolve(clientConfig);\n }\n\n /**\n * Attempts to automatically discover client configuration information\n * prior to logging in. Such information includes the homeserver URL\n * and identity server URL the client would want. Additional details\n * may also be discovered, and will be transparently included in the\n * response object unaltered.\n * @param domain - The homeserver domain to perform discovery\n * on. For example, \"matrix.org\".\n * @returns Promise which resolves to the discovered\n * configuration, which may include error states. Rejects on unexpected\n * failure, not when discovery fails.\n */\n public static async findClientConfig(domain: string): Promise<ClientConfig> {\n if (!domain || typeof domain !== \"string\" || domain.length === 0) {\n throw new Error(\"'domain' must be a string of non-zero length\");\n }\n\n // We use a .well-known lookup for all cases. According to the spec, we\n // can do other discovery mechanisms if we want such as custom lookups\n // however we won't bother with that here (mostly because the spec only\n // supports .well-known right now).\n //\n // By using .well-known, we need to ensure we at least pull out a URL\n // for the homeserver. We don't really need an identity server configuration\n // but will return one anyways (with state PROMPT) to make development\n // easier for clients. If we can't get a homeserver URL, all bets are\n // off on the rest of the config and we'll assume it is invalid too.\n\n // We default to an error state to make the first few checks easier to\n // write. We'll update the properties of this object over the duration\n // of this function.\n const clientConfig: ClientConfig = {\n \"m.homeserver\": {\n state: AutoDiscovery.FAIL_ERROR,\n error: AutoDiscovery.ERROR_INVALID,\n base_url: null,\n },\n \"m.identity_server\": {\n // Technically, we don't have a problem with the identity server\n // config at this point.\n state: AutoDiscovery.PROMPT,\n error: null,\n base_url: null,\n },\n };\n\n // Step 1: Actually request the .well-known JSON file and make sure it\n // at least has a homeserver definition.\n const domainWithProtocol = domain.includes(\"://\") ? domain : `https://${domain}`;\n const wellknown = await this.fetchWellKnownObject(`${domainWithProtocol}/.well-known/matrix/client`);\n if (!wellknown || wellknown.action !== AutoDiscoveryAction.SUCCESS) {\n logger.error(\"No response or error when parsing .well-known\");\n if (wellknown.reason) logger.error(wellknown.reason);\n if (wellknown.action === AutoDiscoveryAction.IGNORE) {\n clientConfig[\"m.homeserver\"] = {\n state: AutoDiscovery.PROMPT,\n error: null,\n base_url: null,\n };\n } else {\n // this can only ever be FAIL_PROMPT at this point.\n clientConfig[\"m.homeserver\"].state = AutoDiscovery.FAIL_PROMPT;\n clientConfig[\"m.homeserver\"].error = AutoDiscovery.ERROR_INVALID;\n }\n return Promise.resolve(clientConfig);\n }\n\n // Step 2: Validate and parse the config\n return AutoDiscovery.fromDiscoveryConfig(wellknown.raw!);\n }\n\n /**\n * Gets the raw discovery client configuration for the given domain name.\n * Should only be used if there's no validation to be done on the resulting\n * object, otherwise use findClientConfig().\n * @param domain - The domain to get the client config for.\n * @returns Promise which resolves to the domain's client config. Can\n * be an empty object.\n */\n public static async getRawClientConfig(domain?: string): Promise<IClientWellKnown> {\n if (!domain || typeof domain !== \"string\" || domain.length === 0) {\n throw new Error(\"'domain' must be a string of non-zero length\");\n }\n\n const response = await this.fetchWellKnownObject(`https://${domain}/.well-known/matrix/client`);\n if (!response) return {};\n return response.raw ?? {};\n }\n\n /**\n * Sanitizes a given URL to ensure it is either an HTTP or HTTP URL and\n * is suitable for the requirements laid out by .well-known auto discovery.\n * If valid, the URL will also be stripped of any trailing slashes.\n * @param url - The potentially invalid URL to sanitize.\n * @returns The sanitized URL or a falsey value if the URL is invalid.\n * @internal\n */\n private static sanitizeWellKnownUrl(url?: string | null): string | false {\n if (!url) return false;\n\n try {\n let parsed: URL | undefined;\n try {\n parsed = new URL(url);\n } catch (e) {\n logger.error(\"Could not parse url\", e);\n }\n\n if (!parsed?.hostname) return false;\n if (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") return false;\n\n const port = parsed.port ? `:${parsed.port}` : \"\";\n const path = parsed.pathname ? parsed.pathname : \"\";\n let saferUrl = `${parsed.protocol}//${parsed.hostname}${port}${path}`;\n if (saferUrl.endsWith(\"/\")) {\n saferUrl = saferUrl.substring(0, saferUrl.length - 1);\n }\n return saferUrl;\n } catch (e) {\n logger.error(e);\n return false;\n }\n }\n\n private static fetch(resource: URL | string, options?: RequestInit): ReturnType<typeof globalThis.fetch> {\n if (this.fetchFn) {\n return this.fetchFn(resource, options);\n }\n return globalThis.fetch(resource, options);\n }\n\n private static fetchFn?: typeof globalThis.fetch;\n\n public static setFetchFn(fetchFn: typeof globalThis.fetch): void {\n AutoDiscovery.fetchFn = fetchFn;\n }\n\n /**\n * Fetches a JSON object from a given URL, as expected by all .well-known\n * related lookups. If the server gives a 404 then the `action` will be\n * IGNORE. If the server returns something that isn't JSON, the `action`\n * will be FAIL_PROMPT. For any other failure the `action` will be FAIL_PROMPT.\n *\n * The returned object will be a result of the call in object form with\n * the following properties:\n * raw: The JSON object returned by the server.\n * action: One of SUCCESS, IGNORE, or FAIL_PROMPT.\n * reason: Relatively human-readable description of what went wrong.\n * error: The actual Error, if one exists.\n * @param url - The URL to fetch a JSON object from.\n * @returns Promise which resolves to the returned state.\n * @internal\n */\n private static async fetchWellKnownObject<T = IWellKnownConfig>(\n url: string,\n ): Promise<IWellKnownConfig<Partial<T>>> {\n let response: Response;\n\n try {\n response = await AutoDiscovery.fetch(url, {\n method: Method.Get,\n signal: timeoutSignal(5000),\n });\n\n if (response.status === 404) {\n return {\n raw: {},\n action: AutoDiscoveryAction.IGNORE,\n reason: AutoDiscovery.ERROR_MISSING_WELLKNOWN,\n };\n }\n\n if (!response.ok) {\n return {\n raw: {},\n action: AutoDiscoveryAction.FAIL_PROMPT,\n reason: \"General failure\",\n };\n }\n } catch (err) {\n const error = err as AutoDiscoveryError | string | undefined;\n let reason = \"\";\n if (typeof error === \"object\") {\n reason = (<Error>error)?.message;\n }\n\n return {\n error,\n raw: {},\n action: AutoDiscoveryAction.FAIL_PROMPT,\n reason: reason || \"General failure\",\n };\n }\n\n try {\n return {\n raw: await response.json(),\n action: AutoDiscoveryAction.SUCCESS,\n };\n } catch (err) {\n const error = err as Error;\n return {\n error,\n raw: {},\n action: AutoDiscoveryAction.FAIL_PROMPT,\n reason:\n (error as MatrixError)?.name === \"SyntaxError\"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a,sBAkBoBD,kBAAkB,CAACkG,SAAS;AAAAP,eAAA,CAlB7D1F,aAAa,6BAoB2BD,kBAAkB,CAACmG,gBAAgB;AAAAR,eAAA,CApB3E1F,aAAa,wBAsBsBD,kBAAkB,CAACoG,WAAW;AAAAT,eAAA,CAtBjE1F,aAAa,+CAyBlBD,kBAAkB,CAACqG,gCAAgC;AAAAV,eAAA,CAzB9C1F,aAAa,gBA2Bc0C,MAAM,CAACC,IAAI,CAAC5C,kBAAkB,CAAC;AAEnE;AACJ;AACA;AACA;AAHI2F,eAAA,CA7BS1F,aAAa,gBAiCcF,mBAAmB,CAACU,UAAU;AAElE;AACJ;AACA;AACA;AACA;AACA;AACA;AANIkF,eAAA,CAnCS1F,aAAa,iBA0CeF,mBAAmB,CAACe,WAAW;AAEpE;AACJ;AACA;AACA;AACA;AAJI6E,eAAA,CA5CS1F,aAAa,YAiDUF,mBAAmB,CAACc,MAAM;AAE1D;AACJ;AACA;AAFI8E,eAAA,CAnDS1F,aAAa,aAsDWF,mBAAmB,CAACkC,OAAO;AAAA0D,eAAA,CAtDnD1F,aAAa","ignoreList":[]}
package/lib/base64.d.ts CHANGED
@@ -1,24 +1,21 @@
1
- /**
2
- * Base64 encoding and decoding utilities
3
- */
4
1
  /**
5
2
  * Encode a typed array of uint8 as base64.
6
3
  * @param uint8Array - The data to encode.
7
4
  * @returns The base64.
8
5
  */
9
- export declare function encodeBase64(uint8Array: ArrayBuffer | Uint8Array): string;
6
+ export declare function encodeBase64(uint8Array: Uint8Array): string;
10
7
  /**
11
8
  * Encode a typed array of uint8 as unpadded base64.
12
9
  * @param uint8Array - The data to encode.
13
10
  * @returns The unpadded base64.
14
11
  */
15
- export declare function encodeUnpaddedBase64(uint8Array: ArrayBuffer | Uint8Array): string;
12
+ export declare function encodeUnpaddedBase64(uint8Array: Uint8Array): string;
16
13
  /**
17
14
  * Encode a typed array of uint8 as unpadded base64 using the URL-safe encoding.
18
15
  * @param uint8Array - The data to encode.
19
16
  * @returns The unpadded base64.
20
17
  */
21
- export declare function encodeUnpaddedBase64Url(uint8Array: ArrayBuffer | Uint8Array): string;
18
+ export declare function encodeUnpaddedBase64Url(uint8Array: Uint8Array): string;
22
19
  /**
23
20
  * Decode a base64 (or base64url) string to a typed array of uint8.
24
21
  * @param base64 - The base64 to decode.
@@ -1 +1 @@
1
- {"version":3,"file":"base64.d.ts","sourceRoot":"","sources":["../src/base64.ts"],"names":[],"mappings":"AAgBA;;GAEG;AAEH;;;;GAIG;AACH,wBAAgB,YAAY,CAAC,UAAU,EAAE,WAAW,GAAG,UAAU,GAAG,MAAM,CAmBzE;AAED;;;;GAIG;AACH,wBAAgB,oBAAoB,CAAC,UAAU,EAAE,WAAW,GAAG,UAAU,GAAG,MAAM,CAEjF;AAED;;;;GAIG;AACH,wBAAgB,uBAAuB,CAAC,UAAU,EAAE,WAAW,GAAG,UAAU,GAAG,MAAM,CAEpF;AAED;;;;GAIG;AACH,wBAAgB,YAAY,CAAC,MAAM,EAAE,MAAM,GAAG,UAAU,CAkBvD"}
1
+ {"version":3,"file":"base64.d.ts","sourceRoot":"","sources":["../src/base64.ts"],"names":[],"mappings":"AAuCA;;;;GAIG;AACH,wBAAgB,YAAY,CAAC,UAAU,EAAE,UAAU,GAAG,MAAM,CAE3D;AAED;;;;GAIG;AACH,wBAAgB,oBAAoB,CAAC,UAAU,EAAE,UAAU,GAAG,MAAM,CAEnE;AAED;;;;GAIG;AACH,wBAAgB,uBAAuB,CAAC,UAAU,EAAE,UAAU,GAAG,MAAM,CAEtE;AAaD;;;;GAIG;AACH,wBAAgB,YAAY,CAAC,MAAM,EAAE,MAAM,GAAG,UAAU,CAGvD"}
package/lib/base64.js CHANGED
@@ -18,30 +18,33 @@ limitations under the License.
18
18
  * Base64 encoding and decoding utilities
19
19
  */
20
20
 
21
+ function toBase64(uint8Array, options) {
22
+ if (typeof uint8Array.toBase64 === "function") {
23
+ // Currently this is only supported in Firefox,
24
+ // but we match the options in the hope in the future we can rely on it for all environments.
25
+ // https://tc39.es/proposal-arraybuffer-base64/spec/#sec-uint8array.prototype.tobase64
26
+ return uint8Array.toBase64(options);
27
+ }
28
+ var base64 = btoa(uint8Array.reduce((acc, current) => acc + String.fromCharCode(current), ""));
29
+ if (options.omitPadding) {
30
+ base64 = base64.replace(/={1,2}$/, "");
31
+ }
32
+ if (options.alphabet === "base64url") {
33
+ base64 = base64.replace(/\+/g, "-").replace(/\//g, "_");
34
+ }
35
+ return base64;
36
+ }
37
+
21
38
  /**
22
39
  * Encode a typed array of uint8 as base64.
23
40
  * @param uint8Array - The data to encode.
24
41
  * @returns The base64.
25
42
  */
26
43
  export function encodeBase64(uint8Array) {
27
- // A brief note on the state of base64 encoding in Javascript.
28
- // As of 2023, there is still no common native impl between both browsers and
29
- // node. Older Webpack provides an impl for Buffer and there is a polyfill class
30
- // for it. There are also plenty of pure js impls, eg. base64-js which has 2336
31
- // dependents at current count. Using this would probably be fine although it's
32
- // a little under-docced and run by an individual. The node impl works fine,
33
- // the browser impl works but predates Uint8Array and so only uses strings.
34
- // Right now, switching between native (or polyfilled) impls like this feels
35
- // like the least bad option, but... *shrugs*.
36
- if (typeof Buffer === "function") {
37
- return Buffer.from(uint8Array).toString("base64");
38
- } else if (typeof btoa === "function" && uint8Array instanceof Uint8Array) {
39
- // ArrayBuffer is a node concept so the param should always be a Uint8Array on
40
- // the browser. We need to check because ArrayBuffers don't have reduce.
41
- return btoa(uint8Array.reduce((acc, current) => acc + String.fromCharCode(current), ""));
42
- } else {
43
- throw new Error("No base64 impl found!");
44
- }
44
+ return toBase64(uint8Array, {
45
+ alphabet: "base64",
46
+ omitPadding: false
47
+ });
45
48
  }
46
49
 
47
50
  /**
@@ -50,7 +53,10 @@ export function encodeBase64(uint8Array) {
50
53
  * @returns The unpadded base64.
51
54
  */
52
55
  export function encodeUnpaddedBase64(uint8Array) {
53
- return encodeBase64(uint8Array).replace(/={1,2}$/, "");
56
+ return toBase64(uint8Array, {
57
+ alphabet: "base64",
58
+ omitPadding: true
59
+ });
54
60
  }
55
61
 
56
62
  /**
@@ -59,7 +65,19 @@ export function encodeUnpaddedBase64(uint8Array) {
59
65
  * @returns The unpadded base64.
60
66
  */
61
67
  export function encodeUnpaddedBase64Url(uint8Array) {
62
- return encodeUnpaddedBase64(uint8Array).replace(/\+/g, "-").replace(/\//g, "_");
68
+ return toBase64(uint8Array, {
69
+ alphabet: "base64url",
70
+ omitPadding: true
71
+ });
72
+ }
73
+ function fromBase64(base64, options) {
74
+ if (typeof Uint8Array.fromBase64 === "function") {
75
+ // Currently this is only supported in Firefox,
76
+ // but we match the options in the hope in the future we can rely on it for all environments.
77
+ // https://tc39.es/proposal-arraybuffer-base64/spec/#sec-uint8array.frombase64
78
+ return Uint8Array.fromBase64(base64, options);
79
+ }
80
+ return Uint8Array.from(atob(base64), c => c.charCodeAt(0));
63
81
  }
64
82
 
65
83
  /**
@@ -68,21 +86,10 @@ export function encodeUnpaddedBase64Url(uint8Array) {
68
86
  * @returns The decoded data.
69
87
  */
70
88
  export function decodeBase64(base64) {
71
- // See encodeBase64 for a short treatise on base64 en/decoding in JS
72
- if (typeof Buffer === "function") {
73
- return Buffer.from(base64, "base64");
74
- } else if (typeof atob === "function") {
75
- var itFunc = function* itFunc() {
76
- var decoded = atob(
77
- // built-in atob doesn't support base64url: convert so we support either
78
- base64.replace(/-/g, "+").replace(/_/g, "/"));
79
- for (var i = 0; i < decoded.length; ++i) {
80
- yield decoded.charCodeAt(i);
81
- }
82
- };
83
- return Uint8Array.from(itFunc());
84
- } else {
85
- throw new Error("No base64 impl found!");
86
- }
89
+ // The function requires us to select an alphabet, but we don't know if base64url was used so we convert.
90
+ return fromBase64(base64.replace(/-/g, "+").replace(/_/g, "/"), {
91
+ alphabet: "base64",
92
+ lastChunkHandling: "loose"
93
+ });
87
94
  }
88
95
  //# sourceMappingURL=base64.js.map
package/lib/base64.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"base64.js","names":["encodeBase64","uint8Array","Buffer","from","toString","btoa","Uint8Array","reduce","acc","current","String","fromCharCode","Error","encodeUnpaddedBase64","replace","encodeUnpaddedBase64Url","decodeBase64","base64","atob","itFunc","decoded","i","length","charCodeAt"],"sources":["../src/base64.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\n/**\n * Base64 encoding and decoding utilities\n */\n\n/**\n * Encode a typed array of uint8 as base64.\n * @param uint8Array - The data to encode.\n * @returns The base64.\n */\nexport function encodeBase64(uint8Array: ArrayBuffer | Uint8Array): string {\n // A brief note on the state of base64 encoding in Javascript.\n // As of 2023, there is still no common native impl between both browsers and\n // node. Older Webpack provides an impl for Buffer and there is a polyfill class\n // for it. There are also plenty of pure js impls, eg. base64-js which has 2336\n // dependents at current count. Using this would probably be fine although it's\n // a little under-docced and run by an individual. The node impl works fine,\n // the browser impl works but predates Uint8Array and so only uses strings.\n // Right now, switching between native (or polyfilled) impls like this feels\n // like the least bad option, but... *shrugs*.\n if (typeof Buffer === \"function\") {\n return Buffer.from(uint8Array).toString(\"base64\");\n } else if (typeof btoa === \"function\" && uint8Array instanceof Uint8Array) {\n // ArrayBuffer is a node concept so the param should always be a Uint8Array on\n // the browser. We need to check because ArrayBuffers don't have reduce.\n return btoa(uint8Array.reduce((acc, current) => acc + String.fromCharCode(current), \"\"));\n } else {\n throw new Error(\"No base64 impl found!\");\n }\n}\n\n/**\n * Encode a typed array of uint8 as unpadded base64.\n * @param uint8Array - The data to encode.\n * @returns The unpadded base64.\n */\nexport function encodeUnpaddedBase64(uint8Array: ArrayBuffer | Uint8Array): string {\n return encodeBase64(uint8Array).replace(/={1,2}$/, \"\");\n}\n\n/**\n * Encode a typed array of uint8 as unpadded base64 using the URL-safe encoding.\n * @param uint8Array - The data to encode.\n * @returns The unpadded base64.\n */\nexport function encodeUnpaddedBase64Url(uint8Array: ArrayBuffer | Uint8Array): string {\n return encodeUnpaddedBase64(uint8Array).replace(/\\+/g, \"-\").replace(/\\//g, \"_\");\n}\n\n/**\n * Decode a base64 (or base64url) string to a typed array of uint8.\n * @param base64 - The base64 to decode.\n * @returns The decoded data.\n */\nexport function decodeBase64(base64: string): Uint8Array {\n // See encodeBase64 for a short treatise on base64 en/decoding in JS\n if (typeof Buffer === \"function\") {\n return Buffer.from(base64, \"base64\");\n } else if (typeof atob === \"function\") {\n const itFunc = function* (): Generator<number> {\n const decoded = atob(\n // built-in atob doesn't support base64url: convert so we support either\n base64.replace(/-/g, \"+\").replace(/_/g, \"/\"),\n );\n for (let i = 0; i < decoded.length; ++i) {\n yield decoded.charCodeAt(i);\n }\n };\n return Uint8Array.from(itFunc());\n } else {\n throw new Error(\"No base64 impl found!\");\n }\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASA,YAAYA,CAACC,UAAoC,EAAU;EACvE;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,IAAI,OAAOC,MAAM,KAAK,UAAU,EAAE;IAC9B,OAAOA,MAAM,CAACC,IAAI,CAACF,UAAU,CAAC,CAACG,QAAQ,CAAC,QAAQ,CAAC;EACrD,CAAC,MAAM,IAAI,OAAOC,IAAI,KAAK,UAAU,IAAIJ,UAAU,YAAYK,UAAU,EAAE;IACvE;IACA;IACA,OAAOD,IAAI,CAACJ,UAAU,CAACM,MAAM,CAAC,CAACC,GAAG,EAAEC,OAAO,KAAKD,GAAG,GAAGE,MAAM,CAACC,YAAY,CAACF,OAAO,CAAC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64.js","names":["toBase64","uint8Array","options","base64","btoa","reduce","acc","current","String","fromCharCode","omitPadding","replace","alphabet","encodeBase64","encodeUnpaddedBase64","encodeUnpaddedBase64Url","fromBase64","Uint8Array","from","atob","c","charCodeAt","decodeBase64","lastChunkHandling"],"sources":["../src/base64.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\n/**\n * Base64 encoding and decoding utilities\n */\n\nfunction toBase64(uint8Array: Uint8Array, options: Uint8ArrayToBase64Options): string {\n if (typeof uint8Array.toBase64 === \"function\") {\n // Currently this is only supported in Firefox,\n // but we match the options in the hope in the future we can rely on it for all environments.\n // https://tc39.es/proposal-arraybuffer-base64/spec/#sec-uint8array.prototype.tobase64\n return uint8Array.toBase64(options);\n }\n\n let base64 = btoa(uint8Array.reduce((acc, current) => acc + String.fromCharCode(current), \"\"));\n if (options.omitPadding) {\n base64 = base64.replace(/={1,2}$/, \"\");\n }\n if (options.alphabet === \"base64url\") {\n base64 = base64.replace(/\\+/g, \"-\").replace(/\\//g, \"_\");\n }\n\n return base64;\n}\n\n/**\n * Encode a typed array of uint8 as base64.\n * @param uint8Array - The data to encode.\n * @returns The base64.\n */\nexport function encodeBase64(uint8Array: Uint8Array): string {\n return toBase64(uint8Array, { alphabet: \"base64\", omitPadding: false });\n}\n\n/**\n * Encode a typed array of uint8 as unpadded base64.\n * @param uint8Array - The data to encode.\n * @returns The unpadded base64.\n */\nexport function encodeUnpaddedBase64(uint8Array: Uint8Array): string {\n return toBase64(uint8Array, { alphabet: \"base64\", omitPadding: true });\n}\n\n/**\n * Encode a typed array of uint8 as unpadded base64 using the URL-safe encoding.\n * @param uint8Array - The data to encode.\n * @returns The unpadded base64.\n */\nexport function encodeUnpaddedBase64Url(uint8Array: Uint8Array): string {\n return toBase64(uint8Array, { alphabet: \"base64url\", omitPadding: true });\n}\n\nfunction fromBase64(base64: string, options: Uint8ArrayFromBase64Options): Uint8Array {\n if (typeof Uint8Array.fromBase64 === \"function\") {\n // Currently this is only supported in Firefox,\n // but we match the options in the hope in the future we can rely on it for all environments.\n // https://tc39.es/proposal-arraybuffer-base64/spec/#sec-uint8array.frombase64\n return Uint8Array.fromBase64(base64, options);\n }\n\n return Uint8Array.from(atob(base64), (c) => c.charCodeAt(0));\n}\n\n/**\n * Decode a base64 (or base64url) string to a typed array of uint8.\n * @param base64 - The base64 to decode.\n * @returns The decoded data.\n */\nexport function decodeBase64(base64: string): Uint8Array {\n // The function requires us to select an alphabet, but we don't know if base64url was used so we convert.\n return fromBase64(base64.replace(/-/g, \"+\").replace(/_/g, \"/\"), { alphabet: \"base64\", lastChunkHandling: \"loose\" });\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA,SAASA,QAAQA,CAACC,UAAsB,EAAEC,OAAkC,EAAU;EAClF,IAAI,OAAOD,UAAU,CAACD,QAAQ,KAAK,UAAU,EAAE;IAC3C;IACA;IACA;IACA,OAAOC,UAAU,CAACD,QAAQ,CAACE,OAAO,CAAC;EACvC;EAEA,IAAIC,MAAM,GAAGC,IAAI,CAACH,UAAU,CAACI,MAAM,CAAC,CAACC,GAAG,EAAEC,OAAO,KAAKD,GAAG,GAAGE,MAAM,CAACC,YAAY,CAACF,OAAO,CAAC,EAAE,EAAE,CAAC,CAAC;EAC9F,IAAIL,OAAO,CAACQ,WAAW,EAAE;IACrBP,MAAM,GAAGA,MAAM,CAACQ,OAAO,CAAC,SAAS,EAAE,EAAE,CAAC;EAC1C;EACA,IA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,GAAG,CAAC,EAAE;IAAEC,QAAQ,EAAE,QAAQ;IAAEW,iBAAiB,EAAE;EAAQ,CAAC,CAAC;AACvH","ignoreList":[]}
package/lib/client.d.ts CHANGED
@@ -79,6 +79,9 @@ import { ImageInfo } from "./@types/media.ts";
79
79
  import { Capabilities } from "./serverCapabilities.ts";
80
80
  export type Store = IStore;
81
81
  export type ResetTimelineCallback = (roomId: string) => boolean;
82
+ /**
83
+ * @deprecated Not supported for Rust Cryptography.
84
+ */
82
85
  export declare const CRYPTO_ENABLED: boolean;
83
86
  export declare const UNSTABLE_MSC3852_LAST_SEEN_UA: UnstableValue<"last_seen_user_agent", "org.matrix.msc3852.last_seen_user_agent">;
84
87
  interface IExportedDevice {
@@ -107,7 +110,7 @@ export interface ICreateClientOpts {
107
110
  * specified, uses a default implementation (indexeddb in the browser,
108
111
  * in-memory otherwise).
109
112
  *
110
- * This is only used for the legacy crypto implementation (as used by {@link MatrixClient#initCrypto}),
113
+ * This is only used for the legacy crypto implementation (as used by {@link MatrixClient#initLegacyCrypto}),
111
114
  * but if you use the rust crypto implementation ({@link MatrixClient#initRustCrypto}) and the device
112
115
  * previously used legacy crypto (so must be migrated), then this must still be provided, so that the
113
116
  * data can be migrated from the legacy store.
@@ -189,7 +192,7 @@ export interface ICreateClientOpts {
189
192
  *
190
193
  * This must be set to the same value every time the client is initialised for the same device.
191
194
  *
192
- * This is only used for the legacy crypto implementation (as used by {@link MatrixClient#initCrypto}),
195
+ * This is only used for the legacy crypto implementation (as used by {@link MatrixClient#initLegacyCrypto}),
193
196
  * but if you use the rust crypto implementation ({@link MatrixClient#initRustCrypto}) and the device
194
197
  * previously used legacy crypto (so must be migrated), then this must still be provided, so that the
195
198
  * data can be migrated from the legacy store.
@@ -946,7 +949,7 @@ export declare class MatrixClient extends TypedEventEmitter<EmittedEvents, Clien
946
949
  /**
947
950
  * Try to rehydrate a device if available. The client must have been
948
951
  * initialized with a `cryptoCallback.getDehydrationKey` option, and this
949
- * function must be called before initCrypto and startClient are called.
952
+ * function must be called before initLegacyCrypto and startClient are called.
950
953
  *
951
954
  * @returns Promise which resolves to undefined if a device could not be dehydrated, or
952
955
  * to the new device ID if the dehydration was successful.
@@ -1179,11 +1182,15 @@ export declare class MatrixClient extends TypedEventEmitter<EmittedEvents, Clien
1179
1182
  *
1180
1183
  * @deprecated libolm is deprecated. Prefer {@link initRustCrypto}.
1181
1184
  */
1182
- initCrypto(): Promise<void>;
1185
+ initLegacyCrypto(): Promise<void>;
1183
1186
  /**
1184
1187
  * Initialise support for end-to-end encryption in this client, using the rust matrix-sdk-crypto.
1185
1188
  *
1186
- * An alternative to {@link initCrypto}.
1189
+ * An alternative to {@link initLegacyCrypto}.
1190
+ *
1191
+ * **WARNING**: the cryptography stack is not thread-safe. Having multiple `MatrixClient` instances connected to
1192
+ * the same Indexed DB will cause data corruption and decryption failures. The application layer is responsible for
1193
+ * ensuring that only one `MatrixClient` issue is instantiated at a time.
1187
1194
  *
1188
1195
  * @param args.useIndexedDB - True to use an indexeddb store, false to use an in-memory store. Defaults to 'true'.
1189
1196
  * @param args.storageKey - A key with which to encrypt the indexeddb store. If provided, it must be exactly
@@ -1208,7 +1215,7 @@ export declare class MatrixClient extends TypedEventEmitter<EmittedEvents, Clien
1208
1215
  /**
1209
1216
  * Access the crypto API for this client.
1210
1217
  *
1211
- * If end-to-end encryption has been enabled for this client (via {@link initCrypto} or {@link initRustCrypto}),
1218
+ * If end-to-end encryption has been enabled for this client (via {@link initLegacyCrypto} or {@link initRustCrypto}),
1212
1219
  * returns an object giving access to the crypto API. Otherwise, returns `undefined`.
1213
1220
  */
1214
1221
  getCrypto(): CryptoApi | undefined;
@@ -1284,6 +1291,8 @@ export declare class MatrixClient extends TypedEventEmitter<EmittedEvents, Clien
1284
1291
  *
1285
1292
  * @remarks
1286
1293
  * Fires {@link CryptoEvent#DeviceVerificationChanged}
1294
+ *
1295
+ * @deprecated Not supported for Rust Cryptography.
1287
1296
  */
1288
1297
  setDeviceVerified(userId: string, deviceId: string, verified?: boolean): Promise<void>;
1289
1298
  /**