Compare commits
365 Commits
v5.3.1-rc.2
...
v8.1.0
| Author | SHA1 | Date | |
|---|---|---|---|
| 64cdd73b93 | |||
| 48a9236ea8 | |||
| 8b3126e9d8 | |||
| 74d497cd2d | |||
| 5070a5c598 | |||
| 2e30b08e74 | |||
| 8bf63f5f0b | |||
| 11665d18ee | |||
| a8a9fc0c9d | |||
| 098cd1b8d4 | |||
| 3166a4880d | |||
| 9d1c7136cc | |||
| e100943edf | |||
| a6fe4cdf1c | |||
| 8b5213c09a | |||
| 23a133c825 | |||
| 69c4496dfe | |||
| 4d74cca206 | |||
| 955e081699 | |||
| b7e73422ab | |||
| a9a4ba33aa | |||
| 7116ad9f58 | |||
| 3d18bdb2aa | |||
| 4c14581606 | |||
| a9c9ec3977 | |||
| 694d1f9631 | |||
| 2b9cfae18a | |||
| 800d8380ce | |||
| 621ca28f68 | |||
| 4792241ff6 | |||
| 0b984df5f9 | |||
| 2e260155ea | |||
| b15c8a2d1c | |||
| 94ab317f23 | |||
| 02b37e1219 | |||
| 9d25848a21 | |||
| 3958768e1f | |||
| cec00cd303 | |||
| 45cfef4294 | |||
| 2a01e99635 | |||
| a9c3aee447 | |||
| c669382e12 | |||
| 19251c427a | |||
| a7aec9e2a4 | |||
| 99d7622b42 | |||
| 8728619d2c | |||
| f6d51fdfb8 | |||
| 0ffaa8d617 | |||
| 8a974172ab | |||
| 72675f7266 | |||
| 0f559050d8 | |||
| 58084774bf | |||
| c7aee7cebd | |||
| c68d135ae8 | |||
| 9ed6c99ec8 | |||
| 7d398d41d0 | |||
| 0af763252c | |||
| 1c9dbbbb19 | |||
| 2a688bdac8 | |||
| 3c53c818cb | |||
| 8e53cb324e | |||
| efbd454775 | |||
| 68c7273f56 | |||
| 8b56ff4eff | |||
| 8134eedd93 | |||
| a87ae770cc | |||
| 355da0f9a9 | |||
| 10bdd63762 | |||
| 69dc518c2c | |||
| fa1dddf06c | |||
| f683f4544a | |||
| bc5b587651 | |||
| 8083031029 | |||
| 7b8102a42c | |||
| dbe2f5e4db | |||
| f27791b7de | |||
| 2a78170395 | |||
| cfca1c7b06 | |||
| fb7a67025f | |||
| 8a6cd48b8e | |||
| e21d1f539d | |||
| f62049559c | |||
| 1fe9dd03a3 | |||
| c3283a7297 | |||
| f423164a1c | |||
| 75fe596e24 | |||
| c5eb290e66 | |||
| d3b2c8246d | |||
| c11796af4b | |||
| 8591815d66 | |||
| b82870adb2 | |||
| 3c5b304b6b | |||
| f656698061 | |||
| d4b4bc5031 | |||
| 9bcf33b6d3 | |||
| fa550e8f03 | |||
| 2d73564eba | |||
| 1bd80247fd | |||
| 1c194e8163 | |||
| db7848c9ba | |||
| 97497ed9d5 | |||
| 60fcc652de | |||
| cb57717424 | |||
| 590f7786eb | |||
| 0024edcb7f | |||
| aa2d0d9a08 | |||
| fd126b8563 | |||
| bc97e7a5ea | |||
| 3dece4f46b | |||
| be05452c70 | |||
| 583650cf7d | |||
| 505915528f | |||
| ace8a787b4 | |||
| ed2ea9ac8e | |||
| 8d09a4abe6 | |||
| 1da959ab02 | |||
| 997dd9b88a | |||
| ebe66bdd6e | |||
| 12b573bc63 | |||
| cc8c163e0f | |||
| abc7f76679 | |||
| eee04895fe | |||
| f520b88f79 | |||
| f0f1c113e4 | |||
| 84a15761ad | |||
| 013fbb87a7 | |||
| 73764d23dc | |||
| 8f62703bf2 | |||
| 6dedae2e4d | |||
| d32131b2b8 | |||
| 0a790b2ae3 | |||
| ef1d5e3d76 | |||
| 30720bfdd7 | |||
| 234a18f016 | |||
| c525a19df5 | |||
| a987a31667 | |||
| 10329c3436 | |||
| 29f10bcd44 | |||
| 19fe9b8ac7 | |||
| 76da708352 | |||
| 145f01ff2d | |||
| 2c2d531e7f | |||
| 91e0f7fbc4 | |||
| bebeec7d84 | |||
| 18b1e00875 | |||
| 86d448c285 | |||
| 73f8867a6f | |||
| d021498fa9 | |||
| b83aa54661 | |||
| 429550ca3e | |||
| 2a6d8c2b1d | |||
| 01c9159830 | |||
| 3b3ed5159c | |||
| 636661dd45 | |||
| 0d7cb2bf25 | |||
| 991f590056 | |||
| 0e6758ccbc | |||
| 1d9c6520e5 | |||
| c81f11df0a | |||
| f39a1e70de | |||
| f0fa249d36 | |||
| 8f72197817 | |||
| 1556ac84da | |||
| b6da6bb835 | |||
| b1a882ea79 | |||
| 3305f2cc72 | |||
| c589a5211b | |||
| ff0d91979b | |||
| 9d6888cf74 | |||
| a4a7097c10 | |||
| cf2b058e7c | |||
| 048d7a9b63 | |||
| d6e37d0288 | |||
| 3cd562fa96 | |||
| bd569cb041 | |||
| e3c6a0e1a0 | |||
| b29176507c | |||
| db25e9719b | |||
| 661901b00d | |||
| b9352cfcc1 | |||
| e381b1901e | |||
| ebdff505eb | |||
| f806e4342e | |||
| 7f32d7d320 | |||
| b1b4b21d45 | |||
| 486e8b5445 | |||
| 9fe0e1e85f | |||
| 8d81240c58 | |||
| bdadcd4532 | |||
| 1de9a24677 | |||
| 6335f14a34 | |||
| da2ef381ac | |||
| 7b173f4c74 | |||
| d49eb0bbc4 | |||
| 91556d5bcd | |||
| 039abe1f75 | |||
| bc32faf467 | |||
| 74a4dfeb67 | |||
| f120533fad | |||
| a1baf39299 | |||
| 9f0f1bcc68 | |||
| 246963e181 | |||
| e3134ab0de | |||
| b38d52da72 | |||
| 411c4f40d9 | |||
| 694a85b652 | |||
| c84e72f53a | |||
| cb7e1a9d82 | |||
| 3c9dfc195e | |||
| a5c13041c6 | |||
| d699e98346 | |||
| 135a76febd | |||
| fae2856e7e | |||
| 98426b6186 | |||
| a63d9d2ccd | |||
| c567139e28 | |||
| 3d495b0753 | |||
| 4946b55c21 | |||
| ad7d7154f4 | |||
| e5b6a9f8cb | |||
| 04f27d36ef | |||
| 683fc98fdc | |||
| c303e83444 | |||
| ae5a40d686 | |||
| 409b7068bb | |||
| f2a12c7154 | |||
| efac2eac07 | |||
| f3f6f3e39a | |||
| f905586dbd | |||
| f393cea2c2 | |||
| e937998b40 | |||
| f85ec08886 | |||
| 7ff68f3844 | |||
| 04529bd524 | |||
| 2c681d93d9 | |||
| 1451fcb040 | |||
| 4986f3c2ca | |||
| e9edb85a32 | |||
| dca60ae4ae | |||
| 025f964b0b | |||
| ff46a8fa9e | |||
| 59412aba51 | |||
| a351ee9f76 | |||
| a5b14092cd | |||
| 90f1de9c3f | |||
| a516f06946 | |||
| 7c1f3e4519 | |||
| 3bb1a6336b | |||
| 7dc926596f | |||
| e775515c38 | |||
| c116f2b1bc | |||
| f24993d6aa | |||
| f053cf1fdb | |||
| 251318eaf0 | |||
| a66e7d79ad | |||
| 38884083a2 | |||
| 0b1088d9a8 | |||
| 875f9ca388 | |||
| 25cd1f25f1 | |||
| 7152ece70a | |||
| 896c76ce9d | |||
| 21d3dd4506 | |||
| 300b32c8d7 | |||
| 19e3b35fc7 | |||
| 320811f9ed | |||
| 991457496f | |||
| 1cb6134758 | |||
| a255b8e450 | |||
| 324f036b35 | |||
| 479a284e10 | |||
| e0660ce01c | |||
| 3a3f6cb7ca | |||
| 9797e6021b | |||
| a9212d33b1 | |||
| d32d3fd864 | |||
| a19cdd06cf | |||
| f4d0f89fda | |||
| ca34cb951e | |||
| 4c2d1b0385 | |||
| 6b4fefc123 | |||
| 86913dccb0 | |||
| 30101a4428 | |||
| 668e8f6f24 | |||
| 2f51e206c7 | |||
| 78b8b36a87 | |||
| af3ef86d19 | |||
| 50febaf477 | |||
| 907f317b04 | |||
| 6edb78d015 | |||
| b58846ab6e | |||
| 32233a2c7b | |||
| 8b2752441d | |||
| e6af29df94 | |||
| 4ae5404fe4 | |||
| 7f0bdc8ddb | |||
| 39836f115b | |||
| 4a699fe6a7 | |||
| 7cc61a887c | |||
| 8f73f1ed3c | |||
| 67fb027d39 | |||
| c6b61ea0ea | |||
| 32841234a7 | |||
| 6f6520ed0f | |||
| b3860f3754 | |||
| 0958917317 | |||
| f42fa7e791 | |||
| 7022d1f3bf | |||
| b592c41f96 | |||
| 62188571d7 | |||
| 8cca3392f6 | |||
| 7082516664 | |||
| 77a1fc9e60 | |||
| e2b1dd6532 | |||
| 7b7fdb0a65 | |||
| 414279f644 | |||
| be91c8580d | |||
| befaa782f6 | |||
| 8e29dae36a | |||
| d2438d10a6 | |||
| b3752bb2c6 | |||
| 02e145b0de | |||
| 0fcf8777a1 | |||
| 26cae5543b | |||
| b0573dec77 | |||
| c5f4e762e5 | |||
| f4c08477d0 | |||
| 4342ee6d4a | |||
| 7b73561923 | |||
| 87c0cf233c | |||
| 145cd7894b | |||
| 6cf8a76c29 | |||
| 7ea09ebe4a | |||
| 1dcb16365b | |||
| 83b33d9d7a | |||
| 83879fa945 | |||
| c3903f2796 | |||
| 18564553ad | |||
| fe3e87a9d6 | |||
| 78c734d2e9 | |||
| 5afa16d454 | |||
| 57233416d9 | |||
| f56ce29210 | |||
| 149f59e9be | |||
| 761892d6b1 | |||
| 4b639d5f9a | |||
| da8ed77aae | |||
| 12f46909f7 | |||
| 919189db1a | |||
| f814a96eac | |||
| 218aa423c3 | |||
| ea8362ed63 | |||
| 3a1508c2ab | |||
| f914391aaf | |||
| cc8e8434ec | |||
| 1b94b3c4de | |||
| 379322db0d | |||
| bf6d1f6555 | |||
| 9faeac4c83 | |||
| a863cf3d72 | |||
| 45a92bcf9c | |||
| 0a0441756b | |||
| c1de2ebbf9 | |||
| 557c2db955 | |||
| ed8d064a13 | |||
| 9da1f7b8d5 |
+21
-68
@@ -1,71 +1,15 @@
|
||||
module.exports = {
|
||||
parser: "babel-eslint", // now needed for class properties
|
||||
parserOptions: {
|
||||
sourceType: "module",
|
||||
ecmaFeatures: {
|
||||
}
|
||||
},
|
||||
extends: ["matrix-org"],
|
||||
plugins: [
|
||||
"babel",
|
||||
],
|
||||
env: {
|
||||
browser: true,
|
||||
node: true,
|
||||
|
||||
// babel's transform-runtime converts references to ES6 globals such as
|
||||
// Promise and Map to core-js polyfills, so we can use ES6 globals.
|
||||
es6: true,
|
||||
jest: true,
|
||||
},
|
||||
extends: ["eslint:recommended", "google"],
|
||||
plugins: [
|
||||
"babel",
|
||||
"jest",
|
||||
],
|
||||
|
||||
rules: {
|
||||
// rules we've always adhered to or now do
|
||||
"max-len": ["error", {
|
||||
code: 90,
|
||||
ignoreComments: true,
|
||||
}],
|
||||
curly: ["error", "multi-line"],
|
||||
"prefer-const": ["error"],
|
||||
"comma-dangle": ["error", {
|
||||
arrays: "always-multiline",
|
||||
objects: "always-multiline",
|
||||
imports: "always-multiline",
|
||||
exports: "always-multiline",
|
||||
functions: "always-multiline",
|
||||
}],
|
||||
|
||||
// loosen jsdoc requirements a little
|
||||
"require-jsdoc": ["error", {
|
||||
require: {
|
||||
FunctionDeclaration: false,
|
||||
}
|
||||
}],
|
||||
"valid-jsdoc": ["error", {
|
||||
requireParamDescription: false,
|
||||
requireReturn: false,
|
||||
requireReturnDescription: false,
|
||||
}],
|
||||
|
||||
// rules we do not want from eslint-recommended
|
||||
"no-console": ["off"],
|
||||
"no-constant-condition": ["off"],
|
||||
"no-empty": ["error", { "allowEmptyCatch": true }],
|
||||
|
||||
// rules we do not want from the google styleguide
|
||||
"object-curly-spacing": ["off"],
|
||||
"spaced-comment": ["off"],
|
||||
"guard-for-in": ["off"],
|
||||
|
||||
// in principle we prefer single quotes, but life is too short
|
||||
quotes: ["off"],
|
||||
|
||||
// rules we'd ideally like to adhere to, but the current
|
||||
// code does not (in most cases because it's still ES5)
|
||||
// we set these to warnings, and assert that the number
|
||||
// of warnings doesn't exceed a given threshold
|
||||
"no-var": ["warn"],
|
||||
"brace-style": ["warn", "1tbs", {"allowSingleLine": true}],
|
||||
"prefer-rest-params": ["warn"],
|
||||
"prefer-spread": ["warn"],
|
||||
"one-var": ["warn"],
|
||||
@@ -79,10 +23,19 @@ module.exports = {
|
||||
"asyncArrow": "always",
|
||||
}],
|
||||
"arrow-parens": "off",
|
||||
|
||||
// eslint's built in no-invalid-this rule breaks with class properties
|
||||
"no-invalid-this": "off",
|
||||
// so we replace it with a version that is class property aware
|
||||
"babel/no-invalid-this": "error",
|
||||
}
|
||||
}
|
||||
"prefer-promise-reject-errors": "off",
|
||||
"quotes": "off",
|
||||
"indent": "off",
|
||||
"no-constant-condition": "off",
|
||||
"no-async-promise-executor": "off",
|
||||
},
|
||||
overrides: [{
|
||||
"files": ["src/**/*.{ts, tsx}"],
|
||||
"extends": ["matrix-org/ts"],
|
||||
"rules": {
|
||||
// While we're converting to ts we make heavy use of this
|
||||
"@typescript-eslint/no-explicit-any": "off",
|
||||
"quotes": "off",
|
||||
},
|
||||
}],
|
||||
};
|
||||
|
||||
+319
@@ -1,3 +1,322 @@
|
||||
Changes in [8.1.0](https://github.com/matrix-org/matrix-js-sdk/releases/tag/v8.1.0) (2020-08-17)
|
||||
================================================================================================
|
||||
[Full Changelog](https://github.com/matrix-org/matrix-js-sdk/compare/v8.1.0-rc.1...v8.1.0)
|
||||
|
||||
* No changes since rc.1
|
||||
|
||||
Changes in [8.1.0-rc.1](https://github.com/matrix-org/matrix-js-sdk/releases/tag/v8.1.0-rc.1) (2020-08-13)
|
||||
==========================================================================================================
|
||||
[Full Changelog](https://github.com/matrix-org/matrix-js-sdk/compare/v8.0.1...v8.1.0-rc.1)
|
||||
|
||||
* Update on Promises
|
||||
[\#1438](https://github.com/matrix-org/matrix-js-sdk/pull/1438)
|
||||
* Store and request master cross-signing key
|
||||
[\#1437](https://github.com/matrix-org/matrix-js-sdk/pull/1437)
|
||||
* Filter out non-string display names
|
||||
[\#1433](https://github.com/matrix-org/matrix-js-sdk/pull/1433)
|
||||
* Bump elliptic from 6.5.2 to 6.5.3
|
||||
[\#1427](https://github.com/matrix-org/matrix-js-sdk/pull/1427)
|
||||
* Replace Riot with Element in docs and comments
|
||||
[\#1431](https://github.com/matrix-org/matrix-js-sdk/pull/1431)
|
||||
* Remove leftover bits of TSLint
|
||||
[\#1430](https://github.com/matrix-org/matrix-js-sdk/pull/1430)
|
||||
|
||||
Changes in [8.0.1](https://github.com/matrix-org/matrix-js-sdk/releases/tag/v8.0.1) (2020-08-05)
|
||||
================================================================================================
|
||||
[Full Changelog](https://github.com/matrix-org/matrix-js-sdk/compare/v8.0.1-rc.1...v8.0.1)
|
||||
|
||||
* Filter out non-string display names
|
||||
[\#1434](https://github.com/matrix-org/matrix-js-sdk/pull/1434)
|
||||
|
||||
Changes in [8.0.1-rc.1](https://github.com/matrix-org/matrix-js-sdk/releases/tag/v8.0.1-rc.1) (2020-07-31)
|
||||
==========================================================================================================
|
||||
[Full Changelog](https://github.com/matrix-org/matrix-js-sdk/compare/v8.0.0...v8.0.1-rc.1)
|
||||
|
||||
* Remove redundant lint dependencies
|
||||
[\#1426](https://github.com/matrix-org/matrix-js-sdk/pull/1426)
|
||||
* Upload all keys when we start using a new key backup version
|
||||
[\#1428](https://github.com/matrix-org/matrix-js-sdk/pull/1428)
|
||||
* Expose countSessionsNeedingBackup
|
||||
[\#1429](https://github.com/matrix-org/matrix-js-sdk/pull/1429)
|
||||
* Configure and use new eslint package
|
||||
[\#1422](https://github.com/matrix-org/matrix-js-sdk/pull/1422)
|
||||
|
||||
Changes in [8.0.0](https://github.com/matrix-org/matrix-js-sdk/releases/tag/v8.0.0) (2020-07-27)
|
||||
================================================================================================
|
||||
[Full Changelog](https://github.com/matrix-org/matrix-js-sdk/compare/v7.1.0...v8.0.0)
|
||||
|
||||
BREAKING CHANGES
|
||||
---
|
||||
|
||||
* `RoomState` events changed to use a Map instead of an object, which changes the collection APIs available to access them.
|
||||
|
||||
All Changes
|
||||
---
|
||||
|
||||
* Properly support txnId
|
||||
[\#1424](https://github.com/matrix-org/matrix-js-sdk/pull/1424)
|
||||
* [BREAKING] Remove deprecated getIdenticonUri
|
||||
[\#1423](https://github.com/matrix-org/matrix-js-sdk/pull/1423)
|
||||
* Bump lodash from 4.17.15 to 4.17.19
|
||||
[\#1421](https://github.com/matrix-org/matrix-js-sdk/pull/1421)
|
||||
* [BREAKING] Convert RoomState's stored state map to a real map
|
||||
[\#1419](https://github.com/matrix-org/matrix-js-sdk/pull/1419)
|
||||
|
||||
Changes in [7.1.0](https://github.com/matrix-org/matrix-js-sdk/releases/tag/v7.1.0) (2020-07-03)
|
||||
================================================================================================
|
||||
[Full Changelog](https://github.com/matrix-org/matrix-js-sdk/compare/v7.1.0-rc.1...v7.1.0)
|
||||
|
||||
* No changes since rc.1
|
||||
|
||||
Changes in [7.1.0-rc.1](https://github.com/matrix-org/matrix-js-sdk/releases/tag/v7.1.0-rc.1) (2020-07-01)
|
||||
==========================================================================================================
|
||||
[Full Changelog](https://github.com/matrix-org/matrix-js-sdk/compare/v7.0.0...v7.1.0-rc.1)
|
||||
|
||||
* Ask general crypto callbacks for 4S privkey if operation adapter doesn't
|
||||
have it yet
|
||||
[\#1414](https://github.com/matrix-org/matrix-js-sdk/pull/1414)
|
||||
* Fix ICreateClientOpts missing idBaseUrl
|
||||
[\#1413](https://github.com/matrix-org/matrix-js-sdk/pull/1413)
|
||||
* Increase max event listeners for rooms
|
||||
[\#1411](https://github.com/matrix-org/matrix-js-sdk/pull/1411)
|
||||
* Don't trust keys megolm received from backup for verifying the sender
|
||||
[\#1406](https://github.com/matrix-org/matrix-js-sdk/pull/1406)
|
||||
* Raise the last known account data / state event for an update
|
||||
[\#1410](https://github.com/matrix-org/matrix-js-sdk/pull/1410)
|
||||
* Isolate encryption bootstrap side-effects
|
||||
[\#1380](https://github.com/matrix-org/matrix-js-sdk/pull/1380)
|
||||
* Add method to get current in-flight to-device requests
|
||||
[\#1405](https://github.com/matrix-org/matrix-js-sdk/pull/1405)
|
||||
|
||||
Changes in [7.0.0](https://github.com/matrix-org/matrix-js-sdk/releases/tag/v7.0.0) (2020-06-23)
|
||||
================================================================================================
|
||||
[Full Changelog](https://github.com/matrix-org/matrix-js-sdk/compare/v7.0.0-rc.1...v7.0.0)
|
||||
|
||||
* No changes since rc.1
|
||||
|
||||
Changes in [7.0.0-rc.1](https://github.com/matrix-org/matrix-js-sdk/releases/tag/v7.0.0-rc.1) (2020-06-17)
|
||||
==========================================================================================================
|
||||
[Full Changelog](https://github.com/matrix-org/matrix-js-sdk/compare/v6.2.2...v7.0.0-rc.1)
|
||||
|
||||
BREAKING CHANGES
|
||||
---
|
||||
|
||||
* Presence lists were removed from the spec in r0.5.0, and the corresponding methods have now been removed here as well:
|
||||
* `getPresenceList`
|
||||
* `inviteToPresenceList`
|
||||
* `dropFromPresenceList`
|
||||
|
||||
All changes
|
||||
---
|
||||
|
||||
* Remove support for unspecced device-specific push rules
|
||||
[\#1404](https://github.com/matrix-org/matrix-js-sdk/pull/1404)
|
||||
* Use existing session id for fetching flows as to not get a new session
|
||||
[\#1403](https://github.com/matrix-org/matrix-js-sdk/pull/1403)
|
||||
* Upgrade deps
|
||||
[\#1400](https://github.com/matrix-org/matrix-js-sdk/pull/1400)
|
||||
* Bring back backup key format migration
|
||||
[\#1398](https://github.com/matrix-org/matrix-js-sdk/pull/1398)
|
||||
* Fix: more informative error message when we cant find a key to decrypt with
|
||||
[\#1313](https://github.com/matrix-org/matrix-js-sdk/pull/1313)
|
||||
* Add js-sdk mechanism for polling client well-known for config
|
||||
[\#1394](https://github.com/matrix-org/matrix-js-sdk/pull/1394)
|
||||
* Fix verification request timeouts to match spec
|
||||
[\#1388](https://github.com/matrix-org/matrix-js-sdk/pull/1388)
|
||||
* Drop presence list methods
|
||||
[\#1391](https://github.com/matrix-org/matrix-js-sdk/pull/1391)
|
||||
* Batch up URL previews to prevent excessive requests
|
||||
[\#1395](https://github.com/matrix-org/matrix-js-sdk/pull/1395)
|
||||
|
||||
Changes in [6.2.2](https://github.com/matrix-org/matrix-js-sdk/releases/tag/v6.2.2) (2020-06-16)
|
||||
================================================================================================
|
||||
[Full Changelog](https://github.com/matrix-org/matrix-js-sdk/compare/v6.2.1...v6.2.2)
|
||||
|
||||
* Use existing session id for fetching flows as to not get a new session
|
||||
[\#1407](https://github.com/matrix-org/matrix-js-sdk/pull/1407)
|
||||
|
||||
Changes in [6.2.1](https://github.com/matrix-org/matrix-js-sdk/releases/tag/v6.2.1) (2020-06-05)
|
||||
================================================================================================
|
||||
[Full Changelog](https://github.com/matrix-org/matrix-js-sdk/compare/v6.2.0...v6.2.1)
|
||||
|
||||
* Bring back backup key format migration
|
||||
[\#1399](https://github.com/matrix-org/matrix-js-sdk/pull/1399)
|
||||
|
||||
Changes in [6.2.0](https://github.com/matrix-org/matrix-js-sdk/releases/tag/v6.2.0) (2020-06-04)
|
||||
================================================================================================
|
||||
[Full Changelog](https://github.com/matrix-org/matrix-js-sdk/compare/v6.2.0-rc.1...v6.2.0)
|
||||
|
||||
* No changes since rc.1
|
||||
|
||||
Changes in [6.2.0-rc.1](https://github.com/matrix-org/matrix-js-sdk/releases/tag/v6.2.0-rc.1) (2020-06-02)
|
||||
==========================================================================================================
|
||||
[Full Changelog](https://github.com/matrix-org/matrix-js-sdk/compare/v6.1.0...v6.2.0-rc.1)
|
||||
|
||||
* Make auth argument in the register request compliant with r0.6.0
|
||||
[\#1304](https://github.com/matrix-org/matrix-js-sdk/pull/1304)
|
||||
* Send the wrong auth params with the right auth params
|
||||
[\#1393](https://github.com/matrix-org/matrix-js-sdk/pull/1393)
|
||||
* encrypt cached keys with pickle key
|
||||
[\#1387](https://github.com/matrix-org/matrix-js-sdk/pull/1387)
|
||||
* Fix replying to key share requests
|
||||
[\#1385](https://github.com/matrix-org/matrix-js-sdk/pull/1385)
|
||||
* Add dist to package.json files so CDNs can serve it
|
||||
[\#1384](https://github.com/matrix-org/matrix-js-sdk/pull/1384)
|
||||
* Fix getVersion warning saying undefined room
|
||||
[\#1382](https://github.com/matrix-org/matrix-js-sdk/pull/1382)
|
||||
* Combine the two places we processed client-level default push rules
|
||||
[\#1379](https://github.com/matrix-org/matrix-js-sdk/pull/1379)
|
||||
* make MAC check robust against unpadded vs padded base64 differences
|
||||
[\#1378](https://github.com/matrix-org/matrix-js-sdk/pull/1378)
|
||||
* Remove key backup format migration
|
||||
[\#1375](https://github.com/matrix-org/matrix-js-sdk/pull/1375)
|
||||
* Add simple browserify browser-matrix.js tests
|
||||
[\#1241](https://github.com/matrix-org/matrix-js-sdk/pull/1241)
|
||||
* support new key agreement method for SAS
|
||||
[\#1376](https://github.com/matrix-org/matrix-js-sdk/pull/1376)
|
||||
|
||||
Changes in [6.1.0](https://github.com/matrix-org/matrix-js-sdk/releases/tag/v6.1.0) (2020-05-19)
|
||||
================================================================================================
|
||||
[Full Changelog](https://github.com/matrix-org/matrix-js-sdk/compare/v6.1.0-rc.1...v6.1.0)
|
||||
|
||||
* No changes since rc.1
|
||||
|
||||
Changes in [6.1.0-rc.1](https://github.com/matrix-org/matrix-js-sdk/releases/tag/v6.1.0-rc.1) (2020-05-14)
|
||||
==========================================================================================================
|
||||
[Full Changelog](https://github.com/matrix-org/matrix-js-sdk/compare/v6.0.0...v6.1.0-rc.1)
|
||||
|
||||
* Remove support for asymmetric 4S encryption
|
||||
[\#1373](https://github.com/matrix-org/matrix-js-sdk/pull/1373)
|
||||
* Increase timeout for 2nd phase of Olm session creation
|
||||
[\#1367](https://github.com/matrix-org/matrix-js-sdk/pull/1367)
|
||||
* Add logging on decryption retries
|
||||
[\#1366](https://github.com/matrix-org/matrix-js-sdk/pull/1366)
|
||||
* Emit event when a trusted self-key is stored
|
||||
[\#1364](https://github.com/matrix-org/matrix-js-sdk/pull/1364)
|
||||
* Customize error payload for oversized messages
|
||||
[\#1352](https://github.com/matrix-org/matrix-js-sdk/pull/1352)
|
||||
* Return null for key backup state when we haven't checked yet
|
||||
[\#1363](https://github.com/matrix-org/matrix-js-sdk/pull/1363)
|
||||
* Added a progressCallback for backup key loading
|
||||
[\#1351](https://github.com/matrix-org/matrix-js-sdk/pull/1351)
|
||||
* Add initialFetch param to willUpdateDevices / devicesUpdated
|
||||
[\#1360](https://github.com/matrix-org/matrix-js-sdk/pull/1360)
|
||||
* Fix race between sending .request and receiving .ready over to_device
|
||||
[\#1359](https://github.com/matrix-org/matrix-js-sdk/pull/1359)
|
||||
* Handle race between sending and await next event from other party
|
||||
[\#1357](https://github.com/matrix-org/matrix-js-sdk/pull/1357)
|
||||
* Add crypto.willUpdateDevices event and make
|
||||
getStoredDevices/getStoredDevicesForUser synchronous
|
||||
[\#1354](https://github.com/matrix-org/matrix-js-sdk/pull/1354)
|
||||
* Fix sender of local echo events in unsigned redactions
|
||||
[\#1350](https://github.com/matrix-org/matrix-js-sdk/pull/1350)
|
||||
* Remove redundant key backup setup path
|
||||
[\#1353](https://github.com/matrix-org/matrix-js-sdk/pull/1353)
|
||||
* Remove some dead code from _retryDecryption
|
||||
[\#1349](https://github.com/matrix-org/matrix-js-sdk/pull/1349)
|
||||
* Don't send key requests until after sync processing is finished
|
||||
[\#1348](https://github.com/matrix-org/matrix-js-sdk/pull/1348)
|
||||
* Prevent attempts to send olm messages to ourselves
|
||||
[\#1346](https://github.com/matrix-org/matrix-js-sdk/pull/1346)
|
||||
* Retry account data upload requests
|
||||
[\#1345](https://github.com/matrix-org/matrix-js-sdk/pull/1345)
|
||||
* Log first known index with megolm session updates
|
||||
[\#1344](https://github.com/matrix-org/matrix-js-sdk/pull/1344)
|
||||
* Prune to_device messages to avoid sending empty messages
|
||||
[\#1343](https://github.com/matrix-org/matrix-js-sdk/pull/1343)
|
||||
* Convert bunch of things to TypeScript
|
||||
[\#1335](https://github.com/matrix-org/matrix-js-sdk/pull/1335)
|
||||
* Add logging when making new Olm sessions
|
||||
[\#1342](https://github.com/matrix-org/matrix-js-sdk/pull/1342)
|
||||
* Fix: handle filter not found
|
||||
[\#1340](https://github.com/matrix-org/matrix-js-sdk/pull/1340)
|
||||
* Make getAccountDataFromServer return null if not found
|
||||
[\#1338](https://github.com/matrix-org/matrix-js-sdk/pull/1338)
|
||||
* Fix setDefaultKeyId to fail if the request fails
|
||||
[\#1336](https://github.com/matrix-org/matrix-js-sdk/pull/1336)
|
||||
* Document setRoomEncryption not modifying room state
|
||||
[\#1328](https://github.com/matrix-org/matrix-js-sdk/pull/1328)
|
||||
* Fix: don't do extra /filter request when enabling lazy loading of members
|
||||
[\#1332](https://github.com/matrix-org/matrix-js-sdk/pull/1332)
|
||||
* Reject attemptAuth promise if no auth flow found
|
||||
[\#1329](https://github.com/matrix-org/matrix-js-sdk/pull/1329)
|
||||
* Fix FilterComponent allowed_values check
|
||||
[\#1327](https://github.com/matrix-org/matrix-js-sdk/pull/1327)
|
||||
* Serialise Olm prekey decryptions
|
||||
[\#1326](https://github.com/matrix-org/matrix-js-sdk/pull/1326)
|
||||
* Fix: crash when backup key needs fixing from corruption issue
|
||||
[\#1324](https://github.com/matrix-org/matrix-js-sdk/pull/1324)
|
||||
* Fix cross-signing/SSSS reset
|
||||
[\#1322](https://github.com/matrix-org/matrix-js-sdk/pull/1322)
|
||||
* Implement QR code reciprocate for self-verification with untrusted MSK
|
||||
[\#1320](https://github.com/matrix-org/matrix-js-sdk/pull/1320)
|
||||
|
||||
Changes in [6.0.0](https://github.com/matrix-org/matrix-js-sdk/releases/tag/v6.0.0) (2020-05-05)
|
||||
================================================================================================
|
||||
[Full Changelog](https://github.com/matrix-org/matrix-js-sdk/compare/v6.0.0-rc.2...v6.0.0)
|
||||
|
||||
* Add progress callback for key backups
|
||||
[\#1368](https://github.com/matrix-org/matrix-js-sdk/pull/1368)
|
||||
|
||||
Changes in [6.0.0-rc.2](https://github.com/matrix-org/matrix-js-sdk/releases/tag/v6.0.0-rc.2) (2020-05-01)
|
||||
==========================================================================================================
|
||||
[Full Changelog](https://github.com/matrix-org/matrix-js-sdk/compare/v6.0.0-rc.1...v6.0.0-rc.2)
|
||||
|
||||
* Emit event when a trusted self-key is stored
|
||||
[\#1365](https://github.com/matrix-org/matrix-js-sdk/pull/1365)
|
||||
|
||||
Changes in [6.0.0-rc.1](https://github.com/matrix-org/matrix-js-sdk/releases/tag/v6.0.0-rc.1) (2020-04-30)
|
||||
==========================================================================================================
|
||||
[Full Changelog](https://github.com/matrix-org/matrix-js-sdk/compare/v5.3.1-rc.4...v6.0.0-rc.1)
|
||||
|
||||
BREAKING CHANGES
|
||||
---
|
||||
|
||||
* client.getStoredDevicesForUser and client.getStoredDevices are no longer async
|
||||
|
||||
All Changes
|
||||
---
|
||||
|
||||
* Add initialFetch param to willUpdateDevices / devicesUpdated
|
||||
[\#1362](https://github.com/matrix-org/matrix-js-sdk/pull/1362)
|
||||
* Fix race between sending .request and receiving .ready over to_device
|
||||
[\#1361](https://github.com/matrix-org/matrix-js-sdk/pull/1361)
|
||||
* Handle race between sending and await next event from other party
|
||||
[\#1358](https://github.com/matrix-org/matrix-js-sdk/pull/1358)
|
||||
* Add crypto.willUpdateDevices event and make
|
||||
getStoredDevices/getStoredDevicesForUser synchronous
|
||||
[\#1356](https://github.com/matrix-org/matrix-js-sdk/pull/1356)
|
||||
* Remove redundant key backup setup path
|
||||
[\#1355](https://github.com/matrix-org/matrix-js-sdk/pull/1355)
|
||||
|
||||
Changes in [5.3.1-rc.4](https://github.com/matrix-org/matrix-js-sdk/releases/tag/v5.3.1-rc.4) (2020-04-23)
|
||||
==========================================================================================================
|
||||
[Full Changelog](https://github.com/matrix-org/matrix-js-sdk/compare/v5.3.1-rc.3...v5.3.1-rc.4)
|
||||
|
||||
* Retry account data upload requests
|
||||
[\#1347](https://github.com/matrix-org/matrix-js-sdk/pull/1347)
|
||||
* Fix: handle filter not found
|
||||
[\#1341](https://github.com/matrix-org/matrix-js-sdk/pull/1341)
|
||||
* Make getAccountDataFromServer return null if not found
|
||||
[\#1339](https://github.com/matrix-org/matrix-js-sdk/pull/1339)
|
||||
* Fix setDefaultKeyId to fail if the request fails
|
||||
[\#1337](https://github.com/matrix-org/matrix-js-sdk/pull/1337)
|
||||
* Fix: don't do extra /filter request when enabling lazy loading of members
|
||||
[\#1333](https://github.com/matrix-org/matrix-js-sdk/pull/1333)
|
||||
* Reject attemptAuth promise if no auth flow found
|
||||
[\#1331](https://github.com/matrix-org/matrix-js-sdk/pull/1331)
|
||||
* Serialise Olm prekey decryptions
|
||||
[\#1330](https://github.com/matrix-org/matrix-js-sdk/pull/1330)
|
||||
|
||||
Changes in [5.3.1-rc.3](https://github.com/matrix-org/matrix-js-sdk/releases/tag/v5.3.1-rc.3) (2020-04-17)
|
||||
==========================================================================================================
|
||||
[Full Changelog](https://github.com/matrix-org/matrix-js-sdk/compare/v5.3.1-rc.2...v5.3.1-rc.3)
|
||||
|
||||
* Fix cross-signing/SSSS reset
|
||||
[\#1323](https://github.com/matrix-org/matrix-js-sdk/pull/1323)
|
||||
* Fix: crash when backup key needs fixing from corruption issue
|
||||
[\#1325](https://github.com/matrix-org/matrix-js-sdk/pull/1325)
|
||||
|
||||
Changes in [5.3.1-rc.2](https://github.com/matrix-org/matrix-js-sdk/releases/tag/v5.3.1-rc.2) (2020-04-16)
|
||||
==========================================================================================================
|
||||
[Full Changelog](https://github.com/matrix-org/matrix-js-sdk/compare/v5.3.1-rc.1...v5.3.1-rc.2)
|
||||
|
||||
@@ -182,10 +182,8 @@ you can pass the result of the promise into it with something like:
|
||||
matrixClient.someMethod(arg1, arg2).nodeify(callback);
|
||||
```
|
||||
|
||||
The main thing to note is that it is an error to discard the result of a
|
||||
promise-returning function, as that will cause exceptions to go unobserved. If
|
||||
you have nothing better to do with the result, just call ``.done()`` on it. See
|
||||
http://documentup.com/kriskowal/q/#the-end for more information.
|
||||
The main thing to note is that it is problematic to discard the result of a
|
||||
promise-returning function, as that will cause exceptions to go unobserved.
|
||||
|
||||
Methods which return a promise show this in their documentation.
|
||||
|
||||
|
||||
@@ -288,7 +288,7 @@ function printMemberList(room) {
|
||||
}
|
||||
|
||||
function printRoomInfo(room) {
|
||||
var eventDict = room.currentState.events;
|
||||
var eventMap = room.currentState.events;
|
||||
var eTypeHeader = " Event Type(state_key) ";
|
||||
var sendHeader = " Sender ";
|
||||
// pad content to 100
|
||||
@@ -300,14 +300,15 @@ function printRoomInfo(room) {
|
||||
var contentHeader = padSide + "Content" + padSide;
|
||||
print(eTypeHeader+sendHeader+contentHeader);
|
||||
print(new Array(100).join("-"));
|
||||
Object.keys(eventDict).forEach(function(eventType) {
|
||||
eventMap.keys().forEach(function(eventType) {
|
||||
if (eventType === "m.room.member") { return; } // use /members instead.
|
||||
Object.keys(eventDict[eventType]).forEach(function(stateKey) {
|
||||
var eventEventMap = eventMap.get(eventType);
|
||||
eventEventMap.keys().forEach(function(stateKey) {
|
||||
var typeAndKey = eventType + (
|
||||
stateKey.length > 0 ? "("+stateKey+")" : ""
|
||||
);
|
||||
var typeStr = fixWidth(typeAndKey, eTypeHeader.length);
|
||||
var event = eventDict[eventType][stateKey];
|
||||
var event = eventEventMap.get(stateKey);
|
||||
var sendStr = fixWidth(event.getSender(), sendHeader.length);
|
||||
var contentStr = fixWidth(
|
||||
JSON.stringify(event.getContent()), contentHeader.length
|
||||
|
||||
+7
-8
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "matrix-js-sdk",
|
||||
"version": "5.3.1-rc.2",
|
||||
"version": "8.1.0",
|
||||
"description": "Matrix Client-Server SDK for Javascript",
|
||||
"scripts": {
|
||||
"prepare": "yarn build",
|
||||
@@ -13,10 +13,9 @@
|
||||
"build:compile-browser": "mkdirp dist && browserify -d src/browser-index.js -p [ tsify -p ./tsconfig.json ] -t [ babelify --sourceMaps=inline --presets [ @babel/preset-env @babel/preset-typescript ] ] | exorcist dist/browser-matrix.js.map > dist/browser-matrix.js",
|
||||
"build:minify-browser": "terser dist/browser-matrix.js --compress --mangle --source-map --output dist/browser-matrix.min.js",
|
||||
"gendoc": "jsdoc -c jsdoc.json -P package.json",
|
||||
"lint": "yarn lint:types && yarn lint:ts && yarn lint:js",
|
||||
"lint:js": "eslint --max-warnings 81 src spec",
|
||||
"lint": "yarn lint:types && yarn lint:js",
|
||||
"lint:js": "eslint --max-warnings 76 src spec",
|
||||
"lint:types": "tsc --noEmit",
|
||||
"lint:ts": "tslint --project ./tsconfig.json -t stylish",
|
||||
"test": "jest spec/ --coverage --testEnvironment node",
|
||||
"test:watch": "jest spec/ --coverage --testEnvironment node --watch"
|
||||
},
|
||||
@@ -35,6 +34,7 @@
|
||||
"author": "matrix.org",
|
||||
"license": "Apache-2.0",
|
||||
"files": [
|
||||
"dist",
|
||||
"lib",
|
||||
"src",
|
||||
"git-revision.txt",
|
||||
@@ -68,15 +68,15 @@
|
||||
"@babel/preset-typescript": "^7.7.4",
|
||||
"@babel/register": "^7.7.4",
|
||||
"@types/node": "12",
|
||||
"@types/request": "^2.48.4",
|
||||
"babel-eslint": "^10.0.3",
|
||||
"babel-jest": "^24.9.0",
|
||||
"babelify": "^10.0.0",
|
||||
"better-docs": "^1.4.7",
|
||||
"browserify": "^16.5.0",
|
||||
"eslint": "^5.12.0",
|
||||
"eslint-config-google": "^0.7.1",
|
||||
"eslint": "7.3.1",
|
||||
"eslint-config-matrix-org": "^0.1.2",
|
||||
"eslint-plugin-babel": "^5.3.0",
|
||||
"eslint-plugin-jest": "^23.0.4",
|
||||
"exorcist": "^1.0.1",
|
||||
"fake-indexeddb": "^3.0.0",
|
||||
"jest": "^24.9.0",
|
||||
@@ -87,7 +87,6 @@
|
||||
"rimraf": "^3.0.0",
|
||||
"terser": "^4.4.3",
|
||||
"tsify": "^4.0.1",
|
||||
"tslint": "^5.20.1",
|
||||
"typescript": "^3.7.3"
|
||||
},
|
||||
"jest": {
|
||||
|
||||
+1
-1
@@ -10,7 +10,7 @@
|
||||
# npm; typically installed by Node.js
|
||||
# yarn; install via brew (macOS) or similar (https://yarnpkg.com/docs/install/)
|
||||
#
|
||||
# Note: this script is also used to release matrix-react-sdk and riot-web.
|
||||
# Note: this script is also used to release matrix-react-sdk and element-web.
|
||||
|
||||
set -e
|
||||
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
/*
|
||||
Copyright 2020 The Matrix.org Foundation C.I.C.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
// stub for browser-matrix browserify tests
|
||||
global.XMLHttpRequest = jest.fn();
|
||||
|
||||
afterAll(() => {
|
||||
// clean up XMLHttpRequest mock
|
||||
global.XMLHttpRequest = undefined;
|
||||
});
|
||||
@@ -0,0 +1,103 @@
|
||||
/*
|
||||
Copyright 2020 The Matrix.org Foundation C.I.C.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
// load XmlHttpRequest mock
|
||||
import "./setupTests";
|
||||
import "../../dist/browser-matrix"; // uses browser-matrix instead of the src
|
||||
import {MockStorageApi} from "../MockStorageApi";
|
||||
import {WebStorageSessionStore} from "../../src/store/session/webstorage";
|
||||
import MockHttpBackend from "matrix-mock-request";
|
||||
import {LocalStorageCryptoStore} from "../../src/crypto/store/localStorage-crypto-store";
|
||||
import * as utils from "../test-utils";
|
||||
|
||||
const USER_ID = "@user:test.server";
|
||||
const DEVICE_ID = "device_id";
|
||||
const ACCESS_TOKEN = "access_token";
|
||||
const ROOM_ID = "!room_id:server.test";
|
||||
|
||||
/* global matrixcs */
|
||||
|
||||
describe("Browserify Test", function() {
|
||||
let client;
|
||||
let httpBackend;
|
||||
|
||||
async function createTestClient() {
|
||||
const sessionStoreBackend = new MockStorageApi();
|
||||
const sessionStore = new WebStorageSessionStore(sessionStoreBackend);
|
||||
const httpBackend = new MockHttpBackend();
|
||||
|
||||
const options = {
|
||||
baseUrl: "http://" + USER_ID + ".test.server",
|
||||
userId: USER_ID,
|
||||
accessToken: ACCESS_TOKEN,
|
||||
deviceId: DEVICE_ID,
|
||||
sessionStore: sessionStore,
|
||||
request: httpBackend.requestFn,
|
||||
cryptoStore: new LocalStorageCryptoStore(sessionStoreBackend),
|
||||
};
|
||||
|
||||
const client = matrixcs.createClient(options);
|
||||
|
||||
httpBackend.when("GET", "/pushrules").respond(200, {});
|
||||
httpBackend.when("POST", "/filter").respond(200, { filter_id: "fid" });
|
||||
|
||||
return { client, httpBackend };
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
({client, httpBackend} = await createTestClient());
|
||||
await client.startClient();
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
client.stopClient();
|
||||
await httpBackend.stop();
|
||||
});
|
||||
|
||||
it("Sync", async function() {
|
||||
const event = utils.mkMembership({
|
||||
room: ROOM_ID,
|
||||
mship: "join",
|
||||
user: "@other_user:server.test",
|
||||
name: "Displayname",
|
||||
});
|
||||
|
||||
const syncData = {
|
||||
next_batch: "batch1",
|
||||
rooms: {
|
||||
join: {},
|
||||
},
|
||||
};
|
||||
syncData.rooms.join[ROOM_ID] = {
|
||||
timeline: {
|
||||
events: [
|
||||
event,
|
||||
],
|
||||
limited: false,
|
||||
},
|
||||
};
|
||||
|
||||
httpBackend.when("GET", "/sync").respond(200, syncData);
|
||||
await Promise.race([
|
||||
Promise.all([
|
||||
httpBackend.flushAllExpected(),
|
||||
]),
|
||||
new Promise((_, reject) => {
|
||||
client.once("sync.unexpectedError", reject);
|
||||
}),
|
||||
]);
|
||||
}, 10000);
|
||||
});
|
||||
@@ -140,7 +140,7 @@ describe("DeviceList management:", function() {
|
||||
|
||||
it("We should not get confused by out-of-order device query responses",
|
||||
() => {
|
||||
// https://github.com/vector-im/riot-web/issues/3126
|
||||
// https://github.com/vector-im/element-web/issues/3126
|
||||
aliceTestClient.expectKeyQuery({device_keys: {'@alice:localhost': {}}});
|
||||
return aliceTestClient.start().then(() => {
|
||||
aliceTestClient.httpBackend.when('GET', '/sync').respond(
|
||||
@@ -271,7 +271,7 @@ describe("DeviceList management:", function() {
|
||||
});
|
||||
}).timeout(3000);
|
||||
|
||||
// https://github.com/vector-im/riot-web/issues/4983
|
||||
// https://github.com/vector-im/element-web/issues/4983
|
||||
describe("Alice should know she has stale device lists", () => {
|
||||
beforeEach(async function() {
|
||||
await aliceTestClient.start();
|
||||
|
||||
@@ -3,6 +3,7 @@ import HttpBackend from "matrix-mock-request";
|
||||
import {MatrixClient} from "../../src/matrix";
|
||||
import {MatrixScheduler} from "../../src/scheduler";
|
||||
import {MemoryStore} from "../../src/store/memory";
|
||||
import {MatrixError} from "../../src/http-api";
|
||||
|
||||
describe("MatrixClient opts", function() {
|
||||
const baseUrl = "http://localhost.or.something";
|
||||
@@ -132,10 +133,10 @@ describe("MatrixClient opts", function() {
|
||||
});
|
||||
|
||||
it("shouldn't retry sending events", function(done) {
|
||||
httpBackend.when("PUT", "/txn1").fail(500, {
|
||||
httpBackend.when("PUT", "/txn1").fail(500, new MatrixError({
|
||||
errcode: "M_SOMETHING",
|
||||
error: "Ruh roh",
|
||||
});
|
||||
}));
|
||||
client.sendTextMessage("!foo:bar", "a body", "txn1").then(function(res) {
|
||||
expect(false).toBe(true, "sendTextMessage resolved but shouldn't");
|
||||
}, function(err) {
|
||||
|
||||
@@ -90,7 +90,7 @@ describe("MatrixClient retrying", function() {
|
||||
// wait for the localecho of ev1 to be updated
|
||||
const p3 = new Promise((resolve, reject) => {
|
||||
room.on("Room.localEchoUpdated", (ev0) => {
|
||||
if(ev0 === ev1) {
|
||||
if (ev0 === ev1) {
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -346,7 +346,7 @@ describe("megolm", function() {
|
||||
});
|
||||
|
||||
it("Alice receives a megolm message before the session keys", function() {
|
||||
// https://github.com/vector-im/riot-web/issues/2273
|
||||
// https://github.com/vector-im/element-web/issues/2273
|
||||
let roomKeyEncrypted;
|
||||
|
||||
return aliceTestClient.start().then(() => {
|
||||
@@ -726,7 +726,7 @@ describe("megolm", function() {
|
||||
});
|
||||
});
|
||||
|
||||
// https://github.com/vector-im/riot-web/issues/2676
|
||||
// https://github.com/vector-im/element-web/issues/2676
|
||||
it("Alice should send to her other devices", function() {
|
||||
// for this test, we make the testOlmAccount be another of Alice's devices.
|
||||
// it ought to get included in messages Alice sends.
|
||||
|
||||
@@ -16,6 +16,7 @@ limitations under the License.
|
||||
*/
|
||||
|
||||
import {logger} from '../src/logger';
|
||||
import * as utils from "../src/utils";
|
||||
|
||||
// try to load the olm library.
|
||||
try {
|
||||
@@ -24,3 +25,11 @@ try {
|
||||
} catch (e) {
|
||||
logger.warn("unable to run crypto tests: libolm not available");
|
||||
}
|
||||
|
||||
// also try to set node crypto
|
||||
try {
|
||||
const crypto = require('crypto');
|
||||
utils.setCrypto(crypto);
|
||||
} catch (err) {
|
||||
console.log('nodejs was compiled without crypto support: some tests will fail');
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import {getHttpUriForMxc, getIdenticonUri} from "../../src/content-repo";
|
||||
import {getHttpUriForMxc} from "../../src/content-repo";
|
||||
|
||||
describe("ContentRepo", function() {
|
||||
const baseUrl = "https://my.home.server";
|
||||
@@ -56,31 +56,4 @@ describe("ContentRepo", function() {
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getIdenticonUri", function() {
|
||||
it("should do nothing for null input", function() {
|
||||
expect(getIdenticonUri(null)).toEqual(null);
|
||||
});
|
||||
|
||||
it("should set w/h by default to 96", function() {
|
||||
expect(getIdenticonUri(baseUrl, "foobar")).toEqual(
|
||||
baseUrl + "/_matrix/media/unstable/identicon/foobar" +
|
||||
"?width=96&height=96",
|
||||
);
|
||||
});
|
||||
|
||||
it("should be able to set custom w/h", function() {
|
||||
expect(getIdenticonUri(baseUrl, "foobar", 32, 64)).toEqual(
|
||||
baseUrl + "/_matrix/media/unstable/identicon/foobar" +
|
||||
"?width=32&height=64",
|
||||
);
|
||||
});
|
||||
|
||||
it("should URL encode the identicon string", function() {
|
||||
expect(getIdenticonUri(baseUrl, "foo#bar", 32, 64)).toEqual(
|
||||
baseUrl + "/_matrix/media/unstable/identicon/foo%23bar" +
|
||||
"?width=32&height=64",
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -10,6 +10,7 @@ import * as olmlib from "../../src/crypto/olmlib";
|
||||
import {sleep} from "../../src/utils";
|
||||
import {EventEmitter} from "events";
|
||||
import {CRYPTO_ENABLED} from "../../src/client";
|
||||
import {DeviceInfo} from "../../src/crypto/deviceinfo";
|
||||
|
||||
const Olm = global.Olm;
|
||||
|
||||
@@ -26,6 +27,66 @@ describe("Crypto", function() {
|
||||
expect(Crypto.getOlmVersion()[0]).toEqual(3);
|
||||
});
|
||||
|
||||
describe("encrypted events", function() {
|
||||
it("provides encryption information", async function() {
|
||||
const client = (new TestClient(
|
||||
"@alice:example.com", "deviceid",
|
||||
)).client;
|
||||
await client.initCrypto();
|
||||
|
||||
// unencrypted event
|
||||
const event = {
|
||||
getId: () => "$event_id",
|
||||
getSenderKey: () => null,
|
||||
getWireContent: () => {return {};},
|
||||
};
|
||||
|
||||
let encryptionInfo = client.getEventEncryptionInfo(event);
|
||||
expect(encryptionInfo.encrypted).toBeFalsy();
|
||||
|
||||
// unknown sender (e.g. deleted device), forwarded megolm key (untrusted)
|
||||
event.getSenderKey = () => 'YmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmI';
|
||||
event.getWireContent = () => {return {algorithm: olmlib.MEGOLM_ALGORITHM};};
|
||||
event.getForwardingCurve25519KeyChain = () => ["not empty"];
|
||||
event.isKeySourceUntrusted = () => false;
|
||||
event.getClaimedEd25519Key =
|
||||
() => 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA';
|
||||
|
||||
encryptionInfo = client.getEventEncryptionInfo(event);
|
||||
expect(encryptionInfo.encrypted).toBeTruthy();
|
||||
expect(encryptionInfo.authenticated).toBeFalsy();
|
||||
expect(encryptionInfo.sender).toBeFalsy();
|
||||
|
||||
// known sender, megolm key from backup
|
||||
event.getForwardingCurve25519KeyChain = () => [];
|
||||
event.isKeySourceUntrusted = () => true;
|
||||
const device = new DeviceInfo("FLIBBLE");
|
||||
device.keys["curve25519:FLIBBLE"] =
|
||||
'YmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmI';
|
||||
device.keys["ed25519:FLIBBLE"] =
|
||||
'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA';
|
||||
client._crypto._deviceList.getDeviceByIdentityKey = () => device;
|
||||
|
||||
encryptionInfo = client.getEventEncryptionInfo(event);
|
||||
expect(encryptionInfo.encrypted).toBeTruthy();
|
||||
expect(encryptionInfo.authenticated).toBeFalsy();
|
||||
expect(encryptionInfo.sender).toBeTruthy();
|
||||
expect(encryptionInfo.mismatchedSender).toBeFalsy();
|
||||
|
||||
// known sender, trusted megolm key, but bad ed25519key
|
||||
event.isKeySourceUntrusted = () => false;
|
||||
device.keys["ed25519:FLIBBLE"] =
|
||||
'BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB';
|
||||
|
||||
encryptionInfo = client.getEventEncryptionInfo(event);
|
||||
expect(encryptionInfo.encrypted).toBeTruthy();
|
||||
expect(encryptionInfo.authenticated).toBeTruthy();
|
||||
expect(encryptionInfo.sender).toBeTruthy();
|
||||
expect(encryptionInfo.mismatchedSender).toBeTruthy();
|
||||
|
||||
client.stopClient();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Session management', function() {
|
||||
const otkResponse = {
|
||||
@@ -313,6 +374,10 @@ describe("Crypto", function() {
|
||||
// make a room key request, and record the transaction ID for the
|
||||
// sendToDevice call
|
||||
await aliceClient.cancelAndResendEventRoomKeyRequest(event);
|
||||
// key requests get queued until the sync has finished, but we don't
|
||||
// let the client set up enough for that to happen, so gut-wrench a bit
|
||||
// to force it to send now.
|
||||
aliceClient._crypto._outgoingRoomKeyRequestManager.sendQueuedRequests();
|
||||
jest.runAllTimers();
|
||||
await Promise.resolve();
|
||||
expect(aliceClient.sendToDevice).toBeCalledTimes(1);
|
||||
|
||||
@@ -25,6 +25,7 @@ import {
|
||||
import {MemoryCryptoStore} from '../../../src/crypto/store/memory-crypto-store';
|
||||
import 'fake-indexeddb/auto';
|
||||
import 'jest-localstorage-mock';
|
||||
import {OlmDevice} from "../../../src/crypto/OlmDevice";
|
||||
|
||||
const userId = "@alice:example.com";
|
||||
|
||||
@@ -37,7 +38,7 @@ const testKey = new Uint8Array([
|
||||
]);
|
||||
|
||||
const types = [
|
||||
{ type: "master", shouldCache: false },
|
||||
{ type: "master", shouldCache: true },
|
||||
{ type: "self_signing", shouldCache: true },
|
||||
{ type: "user_signing", shouldCache: true },
|
||||
{ type: "invalid", shouldCache: false },
|
||||
@@ -233,8 +234,9 @@ describe.each([
|
||||
|
||||
it("should cache data to the store and retrieve it", async () => {
|
||||
await store.startup();
|
||||
const olmDevice = new OlmDevice(store);
|
||||
const { getCrossSigningKeyCache, storeCrossSigningKeyCache } =
|
||||
createCryptoStoreCacheCallbacks(store);
|
||||
createCryptoStoreCacheCallbacks(store, olmDevice);
|
||||
await storeCrossSigningKeyCache("self_signing", testKey);
|
||||
|
||||
// If we've not saved anything, don't expect anything
|
||||
@@ -243,6 +245,6 @@ describe.each([
|
||||
expect(nokey).toBeNull();
|
||||
|
||||
const key = await getCrossSigningKeyCache("self_signing", "");
|
||||
expect(key).toEqual(testKey);
|
||||
expect(new Uint8Array(key)).toEqual(testKey);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -27,6 +27,7 @@ import {MockStorageApi} from "../../MockStorageApi";
|
||||
import * as testUtils from "../../test-utils";
|
||||
import {OlmDevice} from "../../../src/crypto/OlmDevice";
|
||||
import {Crypto} from "../../../src/crypto";
|
||||
import {resetCrossSigningKeys} from "./crypto-utils";
|
||||
|
||||
const Olm = global.Olm;
|
||||
|
||||
@@ -332,7 +333,7 @@ describe("MegolmBackup", function() {
|
||||
client.on("crossSigning.getKey", function(e) {
|
||||
e.done(privateKeys[e.type]);
|
||||
});
|
||||
await client.resetCrossSigningKeys();
|
||||
await resetCrossSigningKeys(client);
|
||||
let numCalls = 0;
|
||||
await new Promise((resolve, reject) => {
|
||||
client._http.authedRequest = function(
|
||||
@@ -517,6 +518,7 @@ describe("MegolmBackup", function() {
|
||||
return megolmDecryption.decryptEvent(ENCRYPTED_EVENT);
|
||||
}).then((res) => {
|
||||
expect(res.clearEvent.content).toEqual('testytest');
|
||||
expect(res.untrusted).toBeTruthy(); // keys from backup are untrusted
|
||||
});
|
||||
});
|
||||
|
||||
@@ -546,7 +548,7 @@ describe("MegolmBackup", function() {
|
||||
const key = Uint8Array.from([1, 2, 3, 4, 5, 6, 7, 8]);
|
||||
await client._crypto.storeSessionBackupPrivateKey(key);
|
||||
const result = await client._crypto.getSessionBackupPrivateKey();
|
||||
expect(result).toEqual(key);
|
||||
expect(new Uint8Array(result)).toEqual(key);
|
||||
});
|
||||
|
||||
it('caches session backup keys as it encounters them', async function() {
|
||||
|
||||
@@ -20,6 +20,7 @@ import anotherjson from 'another-json';
|
||||
import * as olmlib from "../../../src/crypto/olmlib";
|
||||
import {TestClient} from '../../TestClient';
|
||||
import {HttpResponse, setHttpResponses} from '../../test-utils';
|
||||
import {resetCrossSigningKeys, createSecretStorageKey} from "./crypto-utils";
|
||||
|
||||
async function makeTestClient(userInfo, options, keys) {
|
||||
if (!keys) keys = {};
|
||||
@@ -66,8 +67,13 @@ describe("Cross Signing", function() {
|
||||
);
|
||||
});
|
||||
alice.uploadKeySignatures = async () => {};
|
||||
alice.setAccountData = async () => {};
|
||||
alice.getAccountDataFromServer = async () => {};
|
||||
// set Alice's cross-signing key
|
||||
await alice.resetCrossSigningKeys();
|
||||
await alice.bootstrapSecretStorage({
|
||||
createSecretStorageKey,
|
||||
authUploadDeviceSigningKeys: async func => await func({}),
|
||||
});
|
||||
expect(alice.uploadDeviceSigningKeys).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
@@ -78,7 +84,7 @@ describe("Cross Signing", function() {
|
||||
alice.uploadDeviceSigningKeys = async () => {};
|
||||
alice.uploadKeySignatures = async () => {};
|
||||
// set Alice's cross-signing key
|
||||
await alice.resetCrossSigningKeys();
|
||||
await resetCrossSigningKeys(alice);
|
||||
// Alice downloads Bob's device key
|
||||
alice._crypto._deviceList.storeCrossSigningForUser("@bob:example.com", {
|
||||
keys: {
|
||||
@@ -273,7 +279,7 @@ describe("Cross Signing", function() {
|
||||
alice.uploadDeviceSigningKeys = async () => {};
|
||||
alice.uploadKeySignatures = async () => {};
|
||||
// set Alice's cross-signing key
|
||||
await alice.resetCrossSigningKeys();
|
||||
await resetCrossSigningKeys(alice);
|
||||
// Alice downloads Bob's ssk and device key
|
||||
const bobMasterSigning = new global.Olm.PkSigning();
|
||||
const bobMasterPrivkey = bobMasterSigning.generate_seed();
|
||||
@@ -363,7 +369,7 @@ describe("Cross Signing", function() {
|
||||
alice.uploadKeySignatures = async () => {};
|
||||
|
||||
// set Alice's cross-signing key
|
||||
await alice.resetCrossSigningKeys();
|
||||
await resetCrossSigningKeys(alice);
|
||||
|
||||
const selfSigningKey = new Uint8Array([
|
||||
0x1e, 0xf4, 0x01, 0x6d, 0x4f, 0xa1, 0x73, 0x66,
|
||||
@@ -520,7 +526,7 @@ describe("Cross Signing", function() {
|
||||
alice.uploadDeviceSigningKeys = async () => {};
|
||||
alice.uploadKeySignatures = async () => {};
|
||||
// set Alice's cross-signing key
|
||||
await alice.resetCrossSigningKeys();
|
||||
await resetCrossSigningKeys(alice);
|
||||
// Alice downloads Bob's ssk and device key
|
||||
// (NOTE: device key is not signed by ssk)
|
||||
const bobMasterSigning = new global.Olm.PkSigning();
|
||||
@@ -588,7 +594,7 @@ describe("Cross Signing", function() {
|
||||
);
|
||||
alice.uploadDeviceSigningKeys = async () => {};
|
||||
alice.uploadKeySignatures = async () => {};
|
||||
await alice.resetCrossSigningKeys();
|
||||
await resetCrossSigningKeys(alice);
|
||||
// Alice downloads Bob's keys
|
||||
const bobMasterSigning = new global.Olm.PkSigning();
|
||||
const bobMasterPrivkey = bobMasterSigning.generate_seed();
|
||||
@@ -740,7 +746,7 @@ describe("Cross Signing", function() {
|
||||
bob.uploadDeviceSigningKeys = async () => {};
|
||||
bob.uploadKeySignatures = async () => {};
|
||||
// set Bob's cross-signing key
|
||||
await bob.resetCrossSigningKeys();
|
||||
await resetCrossSigningKeys(bob);
|
||||
alice._crypto._deviceList.storeDevicesForUser("@bob:example.com", {
|
||||
Dynabook: {
|
||||
algorithms: ["m.olm.curve25519-aes-sha256", "m.megolm.v1.aes-sha"],
|
||||
@@ -766,7 +772,7 @@ describe("Cross Signing", function() {
|
||||
let upgradePromise = new Promise((resolve) => {
|
||||
upgradeResolveFunc = resolve;
|
||||
});
|
||||
await alice.resetCrossSigningKeys();
|
||||
await resetCrossSigningKeys(alice);
|
||||
await upgradePromise;
|
||||
|
||||
const bobTrust = alice.checkUserTrust("@bob:example.com");
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
import {IndexedDBCryptoStore} from '../../../src/crypto/store/indexeddb-crypto-store';
|
||||
|
||||
|
||||
// needs to be phased out and replaced with bootstrapSecretStorage,
|
||||
// but that is doing too much extra stuff for it to be an easy transition.
|
||||
export async function resetCrossSigningKeys(client, {
|
||||
level,
|
||||
authUploadDeviceSigningKeys = async func => await func(),
|
||||
} = {}) {
|
||||
const crypto = client._crypto;
|
||||
|
||||
const oldKeys = Object.assign({}, crypto._crossSigningInfo.keys);
|
||||
try {
|
||||
await crypto._crossSigningInfo.resetKeys(level);
|
||||
await crypto._signObject(crypto._crossSigningInfo.keys.master);
|
||||
// write a copy locally so we know these are trusted keys
|
||||
await crypto._cryptoStore.doTxn(
|
||||
'readwrite', [IndexedDBCryptoStore.STORE_ACCOUNT],
|
||||
(txn) => {
|
||||
crypto._cryptoStore.storeCrossSigningKeys(
|
||||
txn, crypto._crossSigningInfo.keys);
|
||||
},
|
||||
);
|
||||
} catch (e) {
|
||||
// If anything failed here, revert the keys so we know to try again from the start
|
||||
// next time.
|
||||
crypto._crossSigningInfo.keys = oldKeys;
|
||||
throw e;
|
||||
}
|
||||
crypto._baseApis.emit("crossSigning.keysChanged", {});
|
||||
await crypto._afterCrossSigningLocalKeyChange();
|
||||
}
|
||||
|
||||
export async function createSecretStorageKey() {
|
||||
const decryption = new global.Olm.PkDecryption();
|
||||
const storagePublicKey = decryption.generate_key();
|
||||
const storagePrivateKey = decryption.get_private_key();
|
||||
decryption.free();
|
||||
return {
|
||||
// `pubkey` not used anymore with symmetric 4S
|
||||
keyInfo: { pubkey: storagePublicKey },
|
||||
privateKey: storagePrivateKey,
|
||||
};
|
||||
}
|
||||
@@ -21,6 +21,7 @@ import {MatrixEvent} from "../../../src/models/event";
|
||||
import {TestClient} from '../../TestClient';
|
||||
import {makeTestClients} from './verification/util';
|
||||
import {encryptAES} from "../../../src/crypto/aes";
|
||||
import {resetCrossSigningKeys, createSecretStorageKey} from "./crypto-utils";
|
||||
|
||||
import * as utils from "../../../src/utils";
|
||||
|
||||
@@ -190,7 +191,7 @@ describe("Secrets", function() {
|
||||
}),
|
||||
]);
|
||||
};
|
||||
alice.resetCrossSigningKeys();
|
||||
resetCrossSigningKeys(alice);
|
||||
|
||||
const newKeyId = await alice.addSecretStorageKey(
|
||||
SECRET_STORAGE_ALGORITHM_V1_AES,
|
||||
@@ -288,17 +289,11 @@ describe("Secrets", function() {
|
||||
olmlib.decodeBase64("1R6JVlXX99UcfUZzKuCDGQgJTw8ur1/ofgPD8pp+96M="),
|
||||
);
|
||||
const SSPubKey = "0DfNsRDzEvkCLA0gD3m7VAGJ5VClhjEsewI35xq873Q";
|
||||
const backupKey = new Uint8Array(
|
||||
olmlib.decodeBase64(
|
||||
"OTmOKrPsWP1qxmt0s2qat4vYxULG+U9cmFAWFco3A5U=",
|
||||
),
|
||||
);
|
||||
const SSSSKey = new Uint8Array(
|
||||
olmlib.decodeBase64(
|
||||
"XrmITOOdBhw6yY5Bh7trb/bgp1FRdIGyCUxxMP873R0=",
|
||||
),
|
||||
);
|
||||
const SSSSPubKey = "v3A8HTypbccUm6jaRCRw5l+7lSdzQUACeY9xpQ5BVmE";
|
||||
|
||||
it("bootstraps when no storage or cross-signing keys locally", async function() {
|
||||
const key = new Uint8Array(16);
|
||||
@@ -331,7 +326,10 @@ describe("Secrets", function() {
|
||||
this.emit("accountData", event);
|
||||
};
|
||||
|
||||
await bob.bootstrapSecretStorage();
|
||||
await bob.bootstrapSecretStorage({
|
||||
createSecretStorageKey,
|
||||
authUploadDeviceSigningKeys: async func => await func({}),
|
||||
});
|
||||
|
||||
const crossSigning = bob._crypto._crossSigningInfo;
|
||||
const secretStorage = bob._crypto._secretStorage;
|
||||
@@ -387,6 +385,7 @@ describe("Secrets", function() {
|
||||
keyInfo: { pubkey: storagePublicKey },
|
||||
privateKey: storagePrivateKey,
|
||||
}),
|
||||
authUploadDeviceSigningKeys: async func => await func({}),
|
||||
});
|
||||
|
||||
// Clear local cross-signing keys and read from secret storage
|
||||
@@ -395,7 +394,9 @@ describe("Secrets", function() {
|
||||
crossSigning.toStorage(),
|
||||
);
|
||||
crossSigning.keys = {};
|
||||
await bob.bootstrapSecretStorage();
|
||||
await bob.bootstrapSecretStorage({
|
||||
authUploadDeviceSigningKeys: async func => await func({}),
|
||||
});
|
||||
|
||||
expect(crossSigning.getId()).toBeTruthy();
|
||||
expect(await crossSigning.isStoredInSecretStorage(secretStorage))
|
||||
@@ -403,319 +404,6 @@ describe("Secrets", function() {
|
||||
expect(await secretStorage.hasKey()).toBeTruthy();
|
||||
});
|
||||
|
||||
it("converts asymmetric SSSS to symmetric SSSS", async function() {
|
||||
let crossSigningKeys = {};
|
||||
const secretStorageKeys = {
|
||||
"old_key_id": SSSSKey,
|
||||
"new_key_id": SSSSKey,
|
||||
};
|
||||
const alice = await makeTestClient(
|
||||
{userId: "@alice:example.com", deviceId: "Osborne2"},
|
||||
{
|
||||
cryptoCallbacks: {
|
||||
getCrossSigningKey: t => crossSigningKeys[t],
|
||||
saveCrossSigningKeys: k => crossSigningKeys = k,
|
||||
getSecretStorageKey: ({keys}, name) => {
|
||||
for (const keyId of Object.keys(keys)) {
|
||||
if (secretStorageKeys[keyId]) {
|
||||
return [keyId, secretStorageKeys[keyId]];
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
},
|
||||
);
|
||||
const encryption = new global.Olm.PkEncryption();
|
||||
encryption.set_recipient_key(SSSSPubKey);
|
||||
alice.store.storeAccountDataEvents([
|
||||
new MatrixEvent({
|
||||
type: "m.secret_storage.default_key",
|
||||
content: {
|
||||
key: "old_key_id",
|
||||
},
|
||||
}),
|
||||
new MatrixEvent({
|
||||
type: "m.secret_storage.key.old_key_id",
|
||||
content: sign({
|
||||
algorithm: "m.secret_storage.v1.curve25519-aes-sha2",
|
||||
passphrase: {
|
||||
algorithm: "m.pbkdf2",
|
||||
iterations: 500000,
|
||||
salt: "GbkvwKHVMveo1zGVSb2GMMdCinG2npJK",
|
||||
},
|
||||
pubkey: SSSSPubKey,
|
||||
}, XSK, "@alice:example.com"),
|
||||
}),
|
||||
new MatrixEvent({
|
||||
type: "m.cross_signing.master",
|
||||
content: {
|
||||
encrypted: {
|
||||
old_key_id: encryption.encrypt(olmlib.encodeBase64(XSK)),
|
||||
},
|
||||
},
|
||||
}),
|
||||
new MatrixEvent({
|
||||
type: "m.cross_signing.self_signing",
|
||||
content: {
|
||||
encrypted: {
|
||||
old_key_id: encryption.encrypt(olmlib.encodeBase64(SSK)),
|
||||
},
|
||||
},
|
||||
}),
|
||||
new MatrixEvent({
|
||||
type: "m.cross_signing.user_signing",
|
||||
content: {
|
||||
encrypted: {
|
||||
old_key_id: encryption.encrypt(olmlib.encodeBase64(USK)),
|
||||
},
|
||||
},
|
||||
}),
|
||||
new MatrixEvent({
|
||||
type: "m.megolm_backup.v1",
|
||||
content: {
|
||||
encrypted: {
|
||||
old_key_id: encryption.encrypt(
|
||||
olmlib.encodeBase64(backupKey),
|
||||
),
|
||||
},
|
||||
},
|
||||
}),
|
||||
]);
|
||||
encryption.free();
|
||||
alice._crypto._deviceList.storeCrossSigningForUser("@alice:example.com", {
|
||||
keys: {
|
||||
master: {
|
||||
user_id: "@alice:example.com",
|
||||
usage: ["master"],
|
||||
keys: {
|
||||
[`ed25519:${XSPubKey}`]: XSPubKey,
|
||||
},
|
||||
},
|
||||
self_signing: sign({
|
||||
user_id: "@alice:example.com",
|
||||
usage: ["self_signing"],
|
||||
keys: {
|
||||
[`ed25519:${SSPubKey}`]: SSPubKey,
|
||||
},
|
||||
}, XSK, "@alice:example.com"),
|
||||
user_signing: sign({
|
||||
user_id: "@alice:example.com",
|
||||
usage: ["user_signing"],
|
||||
keys: {
|
||||
[`ed25519:${USPubKey}`]: USPubKey,
|
||||
},
|
||||
}, XSK, "@alice:example.com"),
|
||||
},
|
||||
});
|
||||
alice.getKeyBackupVersion = async () => {
|
||||
return {
|
||||
version: "1",
|
||||
algorithm: "m.megolm_backup.v1.curve25519-aes-sha2",
|
||||
auth_data: sign({
|
||||
public_key: "pxEXhg+4vdMf/kFwP4bVawFWdb0EmytL3eFJx++zQ0A",
|
||||
}, XSK, "@alice:example.com"),
|
||||
};
|
||||
};
|
||||
const origAddSecretStorageKey = alice._crypto.addSecretStorageKey;
|
||||
alice._crypto.addSecretStorageKey = async function(algorithm, opts, keyId) {
|
||||
return await origAddSecretStorageKey.call(
|
||||
alice._crypto, algorithm, opts, keyId || "new_key_id",
|
||||
);
|
||||
};
|
||||
alice.setAccountData = async function(name, data) {
|
||||
const event = new MatrixEvent({
|
||||
type: name,
|
||||
content: data,
|
||||
});
|
||||
alice.store.storeAccountDataEvents([event]);
|
||||
this.emit("accountData", event);
|
||||
};
|
||||
|
||||
await alice.bootstrapSecretStorage();
|
||||
|
||||
// it should create a new key with the same parameters
|
||||
expect(alice.getAccountData("m.secret_storage.default_key").getContent())
|
||||
.toEqual({key: "new_key_id"});
|
||||
const newKeyInfo = alice.getAccountData("m.secret_storage.key.new_key_id")
|
||||
.getContent();
|
||||
expect(newKeyInfo.algorithm)
|
||||
.toEqual("m.secret_storage.v1.aes-hmac-sha2");
|
||||
expect(newKeyInfo.passphrase).toEqual({
|
||||
algorithm: "m.pbkdf2",
|
||||
iterations: 500000,
|
||||
salt: "GbkvwKHVMveo1zGVSb2GMMdCinG2npJK",
|
||||
});
|
||||
expect(newKeyInfo).toHaveProperty("iv");
|
||||
expect(newKeyInfo).toHaveProperty("mac");
|
||||
expect(alice.checkSecretStorageKey(secretStorageKeys.new_key_id, newKeyInfo))
|
||||
.toBeTruthy();
|
||||
|
||||
const crossSigningMaster = alice.getAccountData("m.cross_signing.master")
|
||||
.getContent();
|
||||
expect(crossSigningMaster.encrypted).toHaveProperty("new_key_id");
|
||||
expect(crossSigningMaster.encrypted).not.toHaveProperty("old_key_id");
|
||||
expect(await alice.getSecret("m.cross_signing.master"))
|
||||
.toEqual(olmlib.encodeBase64(XSK));
|
||||
|
||||
const USKInfo = alice.getAccountData("m.cross_signing.self_signing")
|
||||
.getContent();
|
||||
expect(USKInfo.encrypted).toHaveProperty("new_key_id");
|
||||
expect(USKInfo.encrypted).not.toHaveProperty("old_key_id");
|
||||
expect(await alice.getSecret("m.cross_signing.user_signing"))
|
||||
.toEqual(olmlib.encodeBase64(USK));
|
||||
|
||||
const SSKInfo = alice.getAccountData("m.cross_signing.self_signing")
|
||||
.getContent();
|
||||
expect(SSKInfo.encrypted).toHaveProperty("new_key_id");
|
||||
expect(SSKInfo.encrypted).not.toHaveProperty("old_key_id");
|
||||
expect(await alice.getSecret("m.cross_signing.self_signing"))
|
||||
.toEqual(olmlib.encodeBase64(SSK));
|
||||
|
||||
const backupKeyInfo = alice.getAccountData("m.megolm_backup.v1")
|
||||
.getContent();
|
||||
expect(backupKeyInfo.encrypted).toHaveProperty("new_key_id");
|
||||
expect(backupKeyInfo.encrypted).not.toHaveProperty("old_key_id");
|
||||
expect(await alice.getSecret("m.megolm_backup.v1"))
|
||||
.toEqual(olmlib.encodeBase64(backupKey));
|
||||
});
|
||||
it("converts asymmetric SSSS with passthrough", async function() {
|
||||
let crossSigningKeys = {};
|
||||
const secretStorageKeys = {
|
||||
"old_key_id": SSSSKey,
|
||||
"new_key_id": SSSSKey,
|
||||
};
|
||||
const alice = await makeTestClient(
|
||||
{userId: "@alice:example.com", deviceId: "Osborne2"},
|
||||
{
|
||||
cryptoCallbacks: {
|
||||
getCrossSigningKey: t => crossSigningKeys[t],
|
||||
saveCrossSigningKeys: k => crossSigningKeys = k,
|
||||
getSecretStorageKey: ({keys}, name) => {
|
||||
for (const keyId of Object.keys(keys)) {
|
||||
if (secretStorageKeys[keyId]) {
|
||||
return [keyId, secretStorageKeys[keyId]];
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
},
|
||||
);
|
||||
const encryption = new global.Olm.PkEncryption();
|
||||
encryption.set_recipient_key(SSSSPubKey);
|
||||
alice.store.storeAccountDataEvents([
|
||||
new MatrixEvent({
|
||||
type: "m.secret_storage.default_key",
|
||||
content: {
|
||||
key: "old_key_id",
|
||||
},
|
||||
}),
|
||||
new MatrixEvent({
|
||||
type: "m.secret_storage.key.old_key_id",
|
||||
content: sign({
|
||||
algorithm: "m.secret_storage.v1.curve25519-aes-sha2",
|
||||
passphrase: {
|
||||
algorithm: "m.pbkdf2",
|
||||
iterations: 500000,
|
||||
salt: "GbkvwKHVMveo1zGVSb2GMMdCinG2npJK",
|
||||
},
|
||||
pubkey: "v3A8HTypbccUm6jaRCRw5l+7lSdzQUACeY9xpQ5BVmE",
|
||||
}, XSK, "@alice:example.com"),
|
||||
}),
|
||||
new MatrixEvent({
|
||||
type: "m.cross_signing.master",
|
||||
content: {
|
||||
encrypted: {
|
||||
old_key_id: encryption.encrypt(olmlib.encodeBase64(XSK)),
|
||||
},
|
||||
},
|
||||
}),
|
||||
new MatrixEvent({
|
||||
type: "m.cross_signing.self_signing",
|
||||
content: {
|
||||
encrypted: {
|
||||
old_key_id: encryption.encrypt(olmlib.encodeBase64(SSK)),
|
||||
},
|
||||
},
|
||||
}),
|
||||
new MatrixEvent({
|
||||
type: "m.cross_signing.user_signing",
|
||||
content: {
|
||||
encrypted: {
|
||||
old_key_id: encryption.encrypt(olmlib.encodeBase64(USK)),
|
||||
},
|
||||
},
|
||||
}),
|
||||
new MatrixEvent({
|
||||
type: "m.megolm_backup.v1",
|
||||
content: {
|
||||
encrypted: {
|
||||
old_key_id: {
|
||||
passthrough: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
]);
|
||||
encryption.free();
|
||||
alice._crypto._deviceList.storeCrossSigningForUser("@alice:example.com", {
|
||||
keys: {
|
||||
master: {
|
||||
user_id: "@alice:example.com",
|
||||
usage: ["master"],
|
||||
keys: {
|
||||
[`ed25519:${XSPubKey}`]: XSPubKey,
|
||||
},
|
||||
},
|
||||
self_signing: sign({
|
||||
user_id: "@alice:example.com",
|
||||
usage: ["self_signing"],
|
||||
keys: {
|
||||
[`ed25519:${SSPubKey}`]: SSPubKey,
|
||||
},
|
||||
}, XSK, "@alice:example.com"),
|
||||
user_signing: sign({
|
||||
user_id: "@alice:example.com",
|
||||
usage: ["user_signing"],
|
||||
keys: {
|
||||
[`ed25519:${USPubKey}`]: USPubKey,
|
||||
},
|
||||
}, XSK, "@alice:example.com"),
|
||||
},
|
||||
});
|
||||
alice.getKeyBackupVersion = async () => {
|
||||
return {
|
||||
version: "1",
|
||||
algorithm: "m.megolm_backup.v1.curve25519-aes-sha2",
|
||||
auth_data: sign({
|
||||
public_key: "v3A8HTypbccUm6jaRCRw5l+7lSdzQUACeY9xpQ5BVmE",
|
||||
}, XSK, "@alice:example.com"),
|
||||
};
|
||||
};
|
||||
const origAddSecretStorageKey = alice._crypto.addSecretStorageKey;
|
||||
alice._crypto.addSecretStorageKey = async function(algorithm, opts, keyId) {
|
||||
return await origAddSecretStorageKey.call(
|
||||
alice._crypto, algorithm, opts, keyId || "new_key_id",
|
||||
);
|
||||
};
|
||||
alice.setAccountData = async function(name, data) {
|
||||
const event = new MatrixEvent({
|
||||
type: name,
|
||||
content: data,
|
||||
});
|
||||
alice.store.storeAccountDataEvents([event]);
|
||||
this.emit("accountData", event);
|
||||
};
|
||||
|
||||
await alice.bootstrapSecretStorage();
|
||||
|
||||
// the new backup key should be the encoded SSSS key
|
||||
const backupKeyInfo = alice.getAccountData("m.megolm_backup.v1")
|
||||
.getContent();
|
||||
expect(backupKeyInfo.encrypted).toHaveProperty("new_key_id");
|
||||
expect(backupKeyInfo.encrypted).not.toHaveProperty("old_key_id");
|
||||
expect(await alice.getSecret("m.megolm_backup.v1"))
|
||||
.toEqual(olmlib.encodeBase64(SSSSKey));
|
||||
});
|
||||
it("adds passphrase checking if it's lacking", async function() {
|
||||
let crossSigningKeys = {
|
||||
master: XSK,
|
||||
@@ -829,7 +517,9 @@ describe("Secrets", function() {
|
||||
this.emit("accountData", event);
|
||||
};
|
||||
|
||||
await alice.bootstrapSecretStorage();
|
||||
await alice.bootstrapSecretStorage({
|
||||
authUploadDeviceSigningKeys: async func => await func({}),
|
||||
});
|
||||
|
||||
expect(alice.getAccountData("m.secret_storage.default_key").getContent())
|
||||
.toEqual({key: "key_id"});
|
||||
@@ -969,7 +659,9 @@ describe("Secrets", function() {
|
||||
this.emit("accountData", event);
|
||||
};
|
||||
|
||||
await alice.bootstrapSecretStorage();
|
||||
await alice.bootstrapSecretStorage({
|
||||
authUploadDeviceSigningKeys: async func => await func({}),
|
||||
});
|
||||
|
||||
const backupKey = alice.getAccountData("m.megolm_backup.v1")
|
||||
.getContent();
|
||||
|
||||
@@ -22,6 +22,7 @@ import {DeviceInfo} from "../../../../src/crypto/deviceinfo";
|
||||
import {verificationMethods} from "../../../../src/crypto";
|
||||
import * as olmlib from "../../../../src/crypto/olmlib";
|
||||
import {logger} from "../../../../src/logger";
|
||||
import {resetCrossSigningKeys} from "../crypto-utils";
|
||||
|
||||
const Olm = global.Olm;
|
||||
|
||||
@@ -181,11 +182,14 @@ describe("SAS verification", function() {
|
||||
|
||||
it("should verify a key", async () => {
|
||||
let macMethod;
|
||||
let keyAgreement;
|
||||
const origSendToDevice = bob.client.sendToDevice.bind(bob.client);
|
||||
bob.client.sendToDevice = function(type, map) {
|
||||
if (type === "m.key.verification.accept") {
|
||||
macMethod = map[alice.client.getUserId()][alice.client.deviceId]
|
||||
.message_authentication_code;
|
||||
keyAgreement = map[alice.client.getUserId()][alice.client.deviceId]
|
||||
.key_agreement_protocol;
|
||||
}
|
||||
return origSendToDevice(type, map);
|
||||
};
|
||||
@@ -212,6 +216,7 @@ describe("SAS verification", function() {
|
||||
|
||||
// make sure that it uses the preferred method
|
||||
expect(macMethod).toBe("hkdf-hmac-sha256");
|
||||
expect(keyAgreement).toBe("curve25519-hkdf-sha256");
|
||||
|
||||
// make sure Alice and Bob verified each other
|
||||
const bobDevice
|
||||
@@ -284,12 +289,12 @@ describe("SAS verification", function() {
|
||||
);
|
||||
alice.httpBackend.when('POST', '/keys/signatures/upload').respond(200, {});
|
||||
alice.httpBackend.flush(undefined, 2);
|
||||
await alice.client.resetCrossSigningKeys();
|
||||
await resetCrossSigningKeys(alice.client);
|
||||
bob.httpBackend.when('POST', '/keys/device_signing/upload').respond(200, {});
|
||||
bob.httpBackend.when('POST', '/keys/signatures/upload').respond(200, {});
|
||||
bob.httpBackend.flush(undefined, 2);
|
||||
|
||||
await bob.client.resetCrossSigningKeys();
|
||||
await resetCrossSigningKeys(bob.client);
|
||||
|
||||
bob.client._crypto._deviceList.storeCrossSigningForUser(
|
||||
"@alice:example.com", {
|
||||
|
||||
@@ -54,6 +54,7 @@ describe("self-verifications", () => {
|
||||
cacheCallbacks,
|
||||
);
|
||||
_crossSigningInfo.keys = {
|
||||
master: { keys: { X: testKeyPub } },
|
||||
self_signing: { keys: { X: testKeyPub } },
|
||||
user_signing: { keys: { X: testKeyPub } },
|
||||
};
|
||||
@@ -96,9 +97,9 @@ describe("self-verifications", () => {
|
||||
|
||||
const result = await verification.done();
|
||||
|
||||
/* We should request, and store, two cross signing key and the key backup key */
|
||||
expect(cacheCallbacks.storeCrossSigningKeyCache.mock.calls.length).toBe(2);
|
||||
expect(_secretStorage.request.mock.calls.length).toBe(3);
|
||||
/* We should request, and store, 3 cross signing keys and the key backup key */
|
||||
expect(cacheCallbacks.storeCrossSigningKeyCache.mock.calls.length).toBe(3);
|
||||
expect(_secretStorage.request.mock.calls.length).toBe(4);
|
||||
|
||||
expect(cacheCallbacks.storeCrossSigningKeyCache.mock.calls[0][1])
|
||||
.toEqual(testKey);
|
||||
|
||||
@@ -119,6 +119,8 @@ async function distributeEvent(ownRequest, theirRequest, event) {
|
||||
await theirRequest.channel.handleEvent(event, theirRequest, true);
|
||||
}
|
||||
|
||||
jest.useFakeTimers();
|
||||
|
||||
describe("verification request unit tests", function() {
|
||||
beforeAll(function() {
|
||||
setupWebcrypto();
|
||||
@@ -246,4 +248,38 @@ describe("verification request unit tests", function() {
|
||||
expect(bob1Request.done).toBe(true);
|
||||
expect(bob2Request.done).toBe(true);
|
||||
});
|
||||
|
||||
it("request times out after 10 minutes", async function() {
|
||||
const alice = makeMockClient("@alice:matrix.tld", "device1");
|
||||
const bob = makeMockClient("@bob:matrix.tld", "device1");
|
||||
const aliceRequest = new VerificationRequest(
|
||||
new InRoomChannel(alice, "!room", bob.getUserId()), new Map(), alice);
|
||||
await aliceRequest.sendRequest();
|
||||
const [requestEvent] = alice.popEvents();
|
||||
await aliceRequest.channel.handleEvent(requestEvent, aliceRequest, true,
|
||||
true, true);
|
||||
|
||||
expect(aliceRequest.cancelled).toBe(false);
|
||||
expect(aliceRequest._cancellingUserId).toBe(undefined);
|
||||
jest.advanceTimersByTime(10 * 60 * 1000);
|
||||
expect(aliceRequest._cancellingUserId).toBe(alice.getUserId());
|
||||
});
|
||||
|
||||
it("request times out 2 minutes after receipt", async function() {
|
||||
const alice = makeMockClient("@alice:matrix.tld", "device1");
|
||||
const bob = makeMockClient("@bob:matrix.tld", "device1");
|
||||
const aliceRequest = new VerificationRequest(
|
||||
new InRoomChannel(alice, "!room", bob.getUserId()), new Map(), alice);
|
||||
await aliceRequest.sendRequest();
|
||||
const [requestEvent] = alice.popEvents();
|
||||
const bobRequest = new VerificationRequest(
|
||||
new InRoomChannel(bob, "!room"), new Map(), bob);
|
||||
|
||||
await bobRequest.channel.handleEvent(requestEvent, bobRequest, true);
|
||||
|
||||
expect(bobRequest.cancelled).toBe(false);
|
||||
expect(bobRequest._cancellingUserId).toBe(undefined);
|
||||
jest.advanceTimersByTime(2 * 60 * 1000);
|
||||
expect(bobRequest._cancellingUserId).toBe(bob.getUserId());
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import {FilterComponent} from "../../src/filter-component";
|
||||
import {mkEvent} from '../test-utils';
|
||||
|
||||
describe("Filter Component", function() {
|
||||
describe("types", function() {
|
||||
it("should filter out events with other types", function() {
|
||||
const filter = new FilterComponent({ types: ['m.room.message'] });
|
||||
const event = mkEvent({
|
||||
type: 'm.room.member',
|
||||
content: { },
|
||||
room: 'roomId',
|
||||
event: true,
|
||||
});
|
||||
|
||||
const checkResult = filter.check(event);
|
||||
|
||||
expect(checkResult).toBe(false);
|
||||
});
|
||||
|
||||
it("should validate events with the same type", function() {
|
||||
const filter = new FilterComponent({ types: ['m.room.message'] });
|
||||
const event = mkEvent({
|
||||
type: 'm.room.message',
|
||||
content: { },
|
||||
room: 'roomId',
|
||||
event: true,
|
||||
});
|
||||
|
||||
const checkResult = filter.check(event);
|
||||
|
||||
expect(checkResult).toBe(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -97,7 +97,7 @@ describe("InteractiveAuth", function() {
|
||||
// first we expect a call to doRequest
|
||||
doRequest.mockImplementation(function(authData) {
|
||||
logger.log("request1", authData);
|
||||
expect(authData).toEqual({});
|
||||
expect(authData).toEqual(null); // first request should be null
|
||||
const err = new MatrixError({
|
||||
session: "sessionId",
|
||||
flows: [
|
||||
@@ -143,4 +143,33 @@ describe("InteractiveAuth", function() {
|
||||
expect(stateUpdated).toBeCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
it("should start an auth stage and reject if no auth flow", function() {
|
||||
const doRequest = jest.fn();
|
||||
const stateUpdated = jest.fn();
|
||||
|
||||
const ia = new InteractiveAuth({
|
||||
matrixClient: new FakeClient(),
|
||||
doRequest: doRequest,
|
||||
stateUpdated: stateUpdated,
|
||||
});
|
||||
|
||||
doRequest.mockImplementation(function(authData) {
|
||||
logger.log("request1", authData);
|
||||
expect(authData).toEqual(null); // first request should be null
|
||||
const err = new MatrixError({
|
||||
session: "sessionId",
|
||||
flows: [],
|
||||
params: {
|
||||
"logintype": { param: "aa" },
|
||||
},
|
||||
});
|
||||
err.httpStatus = 401;
|
||||
throw err;
|
||||
});
|
||||
|
||||
return ia.attemptAuth().catch(function(error) {
|
||||
expect(error.message).toBe('No appropriate authentication flow found');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -33,12 +33,6 @@ describe("RoomMember", function() {
|
||||
expect(url.indexOf("flibble/wibble")).not.toEqual(-1);
|
||||
});
|
||||
|
||||
it("should return an identicon HTTP URL if allowDefault was set and there " +
|
||||
"was no m.room.member event", function() {
|
||||
const url = member.getAvatarUrl(hsUrl, 64, 64, "crop", true);
|
||||
expect(url.indexOf("http")).toEqual(0); // don't care about form
|
||||
});
|
||||
|
||||
it("should return nothing if there is no m.room.member and allowDefault=false",
|
||||
function() {
|
||||
const url = member.getAvatarUrl(hsUrl, 64, 64, "crop", false);
|
||||
|
||||
@@ -45,12 +45,6 @@ describe("Room", function() {
|
||||
expect(url.indexOf("flibble/wibble")).not.toEqual(-1);
|
||||
});
|
||||
|
||||
it("should return an identicon HTTP URL if allowDefault was set and there " +
|
||||
"was no m.room.avatar event", function() {
|
||||
const url = room.getAvatarUrl(hsUrl, 64, 64, "crop", true);
|
||||
expect(url.indexOf("http")).toEqual(0); // don't care about form
|
||||
});
|
||||
|
||||
it("should return nothing if there is no m.room.avatar and allowDefault=false",
|
||||
function() {
|
||||
const url = room.getAvatarUrl(hsUrl, 64, 64, "crop", false);
|
||||
@@ -1379,7 +1373,7 @@ describe("Room", function() {
|
||||
let hasThrown = false;
|
||||
try {
|
||||
await room.loadMembersIfNeeded();
|
||||
} catch(err) {
|
||||
} catch (err) {
|
||||
hasThrown = true;
|
||||
}
|
||||
expect(hasThrown).toEqual(true);
|
||||
|
||||
@@ -143,7 +143,7 @@ describe("MatrixScheduler", function() {
|
||||
deferA.reject({});
|
||||
try {
|
||||
await globalA;
|
||||
} catch(err) {
|
||||
} catch (err) {
|
||||
await Promise.resolve();
|
||||
expect(procCount).toEqual(2);
|
||||
}
|
||||
|
||||
Vendored
+25
@@ -0,0 +1,25 @@
|
||||
/*
|
||||
Copyright 2020 The Matrix.org Foundation C.I.C.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
export {};
|
||||
|
||||
declare global {
|
||||
namespace NodeJS {
|
||||
interface Global {
|
||||
localStorage: Storage;
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
-4
@@ -66,7 +66,7 @@ function termsUrlForService(serviceType, baseUrl) {
|
||||
* callback that returns a Promise<String> of an identity access token to supply
|
||||
* with identity requests. If the object is unset, no access token will be
|
||||
* supplied.
|
||||
* See also https://github.com/vector-im/riot-web/issues/10615 which seeks to
|
||||
* See also https://github.com/vector-im/element-web/issues/10615 which seeks to
|
||||
* replace the previous approach of manual access tokens params with this
|
||||
* callback throughout the SDK.
|
||||
*
|
||||
@@ -206,9 +206,6 @@ MatrixBaseApis.prototype.register = function(
|
||||
inhibitLogin = undefined;
|
||||
}
|
||||
|
||||
if (auth === undefined || auth === null) {
|
||||
auth = {};
|
||||
}
|
||||
if (sessionId) {
|
||||
auth.session = sessionId;
|
||||
}
|
||||
|
||||
@@ -34,7 +34,7 @@ matrixcs.request(function(opts, fn) {
|
||||
let indexedDB;
|
||||
try {
|
||||
indexedDB = global.indexedDB;
|
||||
} catch(e) {}
|
||||
} catch (e) {}
|
||||
|
||||
// if our browser (appears to) support indexeddb, use an indexeddb crypto store.
|
||||
if (indexedDB) {
|
||||
|
||||
+206
-143
@@ -35,7 +35,12 @@ import {StubStore} from "./store/stub";
|
||||
import {createNewMatrixCall} from "./webrtc/call";
|
||||
import * as utils from './utils';
|
||||
import {sleep} from './utils';
|
||||
import {MatrixError, PREFIX_MEDIA_R0, PREFIX_UNSTABLE} from "./http-api";
|
||||
import {
|
||||
MatrixError,
|
||||
PREFIX_MEDIA_R0,
|
||||
PREFIX_UNSTABLE,
|
||||
retryNetworkOperation,
|
||||
} from "./http-api";
|
||||
import {getHttpUriForMxc} from "./content-repo";
|
||||
import * as ContentHelpers from "./content-helpers";
|
||||
import * as olmlib from "./crypto/olmlib";
|
||||
@@ -49,6 +54,7 @@ import {randomString} from './randomstring';
|
||||
import {PushProcessor} from "./pushprocessor";
|
||||
import {encodeBase64, decodeBase64} from "./crypto/olmlib";
|
||||
import { User } from "./models/user";
|
||||
import {AutoDiscovery} from "./autodiscovery";
|
||||
|
||||
const SCROLLBACK_DELAY_MS = 3000;
|
||||
export const CRYPTO_ENABLED = isCryptoAvailable();
|
||||
@@ -105,12 +111,15 @@ function keyFromRecoverySession(session, decryptionKey) {
|
||||
* If provided, opts.deviceId and opts.userId should **NOT** be provided
|
||||
* (they are present in the exported data).
|
||||
*
|
||||
* @param {string} opts.pickleKey Key used to pickle olm objects or other
|
||||
* sensitive data.
|
||||
*
|
||||
* @param {IdentityServerProvider} [opts.identityServer]
|
||||
* Optional. A provider object with one function `getAccessToken`, which is a
|
||||
* callback that returns a Promise<String> of an identity access token to supply
|
||||
* with identity requests. If the object is unset, no access token will be
|
||||
* supplied.
|
||||
* See also https://github.com/vector-im/riot-web/issues/10615 which seeks to
|
||||
* See also https://github.com/vector-im/element-web/issues/10615 which seeks to
|
||||
* replace the previous approach of manual access tokens params with this
|
||||
* callback throughout the SDK.
|
||||
*
|
||||
@@ -279,6 +288,8 @@ export function MatrixClient(opts) {
|
||||
// will be used during async initialization of the crypto
|
||||
this._exportedOlmDeviceToImport = opts.deviceToImport.olmDevice;
|
||||
}
|
||||
} else if (opts.pickleKey) {
|
||||
this.pickleKey = opts.pickleKey;
|
||||
}
|
||||
|
||||
this.scheduler = opts.scheduler;
|
||||
@@ -319,7 +330,7 @@ export function MatrixClient(opts) {
|
||||
this._isGuest = false;
|
||||
this._ongoingScrollbacks = {};
|
||||
this.timelineSupport = Boolean(opts.timelineSupport);
|
||||
this.urlPreviewCache = {};
|
||||
this.urlPreviewCache = {}; // key=preview key, value=Promise for preview (may be an error)
|
||||
this._notifTimelineSet = null;
|
||||
this.unstableClientRelationAggregation = !!opts.unstableClientRelationAggregation;
|
||||
|
||||
@@ -369,7 +380,7 @@ export function MatrixClient(opts) {
|
||||
? !!actions.tweaks.highlight : false;
|
||||
if (oldHighlight !== newHighlight || currentCount > 0) {
|
||||
// TODO: Handle mentions received while the client is offline
|
||||
// See also https://github.com/vector-im/riot-web/issues/9069
|
||||
// See also https://github.com/vector-im/element-web/issues/9069
|
||||
if (!room.hasUserReadEvent(this.getUserId(), event.getId())) {
|
||||
let newCount = currentCount;
|
||||
if (newHighlight && !oldHighlight) newCount++;
|
||||
@@ -387,7 +398,7 @@ export function MatrixClient(opts) {
|
||||
|
||||
// Like above, we have to listen for read receipts from ourselves in order to
|
||||
// correctly handle notification counts on encrypted rooms.
|
||||
// This fixes https://github.com/vector-im/riot-web/issues/9421
|
||||
// This fixes https://github.com/vector-im/element-web/issues/9421
|
||||
this.on("Room.receipt", (event, room) => {
|
||||
if (room && this.isRoomEncrypted(room.roomId)) {
|
||||
// Figure out if we've read something or if it's just informational
|
||||
@@ -732,6 +743,7 @@ MatrixClient.prototype.initCrypto = async function() {
|
||||
"crypto.roomKeyRequestCancellation",
|
||||
"crypto.warning",
|
||||
"crypto.devicesUpdated",
|
||||
"crypto.willUpdateDevices",
|
||||
"deviceVerificationChanged",
|
||||
"userTrustStatusChanged",
|
||||
"crossSigning.keysChanged",
|
||||
@@ -740,6 +752,7 @@ MatrixClient.prototype.initCrypto = async function() {
|
||||
logger.log("Crypto: initialising crypto object...");
|
||||
await crypto.init({
|
||||
exportedOlmDevice: this._exportedOlmDeviceToImport,
|
||||
pickleKey: this.pickleKey,
|
||||
});
|
||||
delete this._exportedOlmDeviceToImport;
|
||||
|
||||
@@ -820,9 +833,9 @@ MatrixClient.prototype.downloadKeys = function(userIds, forceDownload) {
|
||||
*
|
||||
* @param {string} userId the user to list keys for.
|
||||
*
|
||||
* @return {Promise<module:crypto/deviceinfo[]>} list of devices
|
||||
* @return {module:crypto/deviceinfo[]} list of devices
|
||||
*/
|
||||
MatrixClient.prototype.getStoredDevicesForUser = async function(userId) {
|
||||
MatrixClient.prototype.getStoredDevicesForUser = function(userId) {
|
||||
if (this._crypto === null) {
|
||||
throw new Error("End-to-end encryption disabled");
|
||||
}
|
||||
@@ -835,9 +848,9 @@ MatrixClient.prototype.getStoredDevicesForUser = async function(userId) {
|
||||
* @param {string} userId the user to list keys for.
|
||||
* @param {string} deviceId unique identifier for the device
|
||||
*
|
||||
* @return {Promise<?module:crypto/deviceinfo>} device or null
|
||||
* @return {module:crypto/deviceinfo} device or null
|
||||
*/
|
||||
MatrixClient.prototype.getStoredDevice = async function(userId, deviceId) {
|
||||
MatrixClient.prototype.getStoredDevice = function(userId, deviceId) {
|
||||
if (this._crypto === null) {
|
||||
throw new Error("End-to-end encryption disabled");
|
||||
}
|
||||
@@ -956,6 +969,20 @@ MatrixClient.prototype.findVerificationRequestDMInProgress = function(roomId) {
|
||||
return this._crypto.findVerificationRequestDMInProgress(roomId);
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns all to-device verification requests that are already in progress for the given user id
|
||||
*
|
||||
* @param {string} userId the ID of the user to query
|
||||
*
|
||||
* @returns {module:crypto/verification/request/VerificationRequest[]} the VerificationRequests that are in progress
|
||||
*/
|
||||
MatrixClient.prototype.getVerificationRequestsToDeviceInProgress = function(userId) {
|
||||
if (this._crypto === null) {
|
||||
throw new Error("End-to-end encryption disabled");
|
||||
}
|
||||
return this._crypto.getVerificationRequestsToDeviceInProgress(userId);
|
||||
};
|
||||
|
||||
/**
|
||||
* Request a key verification from another user.
|
||||
*
|
||||
@@ -1062,17 +1089,6 @@ function wrapCryptoFuncs(MatrixClient, names) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate new cross-signing keys.
|
||||
* The cross-signing API is currently UNSTABLE and may change without notice.
|
||||
*
|
||||
* @function module:client~MatrixClient#resetCrossSigningKeys
|
||||
* @param {object} authDict Auth data to supply for User-Interactive auth.
|
||||
* @param {CrossSigningLevel} [level] the level of cross-signing to reset. New
|
||||
* keys will be created for the given level and below. Defaults to
|
||||
* regenerating all keys.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Get the user's cross-signing key ID.
|
||||
* The cross-signing API is currently UNSTABLE and may change without notice.
|
||||
@@ -1142,7 +1158,6 @@ function wrapCryptoFuncs(MatrixClient, names) {
|
||||
* @param {module:models/room} room the room the event is in
|
||||
*/
|
||||
wrapCryptoFuncs(MatrixClient, [
|
||||
"resetCrossSigningKeys",
|
||||
"getCrossSigningId",
|
||||
"getStoredCrossSigningForUser",
|
||||
"checkUserTrust",
|
||||
@@ -1154,23 +1169,27 @@ wrapCryptoFuncs(MatrixClient, [
|
||||
"isCrossSigningReady",
|
||||
"getCryptoTrustCrossSignedDevices",
|
||||
"setCryptoTrustCrossSignedDevices",
|
||||
"countSessionsNeedingBackup",
|
||||
]);
|
||||
|
||||
/**
|
||||
* Check if the sender of an event is verified
|
||||
* The cross-signing API is currently UNSTABLE and may change without notice.
|
||||
* Get information about the encryption of an event
|
||||
*
|
||||
* @param {MatrixEvent} event event to be checked
|
||||
* @function module:client~MatrixClient#getEventEncryptionInfo
|
||||
*
|
||||
* @returns {DeviceTrustLevel}
|
||||
* @param {module:models/event.MatrixEvent} event event to be checked
|
||||
*
|
||||
* @return {object} An object with the fields:
|
||||
* - encrypted: whether the event is encrypted (if not encrypted, some of the
|
||||
* other properties may not be set)
|
||||
* - senderKey: the sender's key
|
||||
* - algorithm: the algorithm used to encrypt the event
|
||||
* - authenticated: whether we can be sure that the owner of the senderKey
|
||||
* sent the event
|
||||
* - sender: the sender's device information, if available
|
||||
* - mismatchedSender: if the event's ed25519 and curve25519 keys don't match
|
||||
* (only meaningful if `sender` is set)
|
||||
*/
|
||||
MatrixClient.prototype.checkEventSenderTrust = async function(event) {
|
||||
const device = await this.getEventSenderDeviceInfo(event);
|
||||
if (!device) {
|
||||
return 0;
|
||||
}
|
||||
return await this._crypto.checkDeviceTrust(event.getSender(), device.deviceId);
|
||||
};
|
||||
|
||||
/**
|
||||
* Create a recovery key from a user-supplied passphrase.
|
||||
@@ -1300,11 +1319,11 @@ MatrixClient.prototype.checkEventSenderTrust = async function(event) {
|
||||
*/
|
||||
|
||||
wrapCryptoFuncs(MatrixClient, [
|
||||
"getEventEncryptionInfo",
|
||||
"createRecoveryKeyFromPassphrase",
|
||||
"bootstrapSecretStorage",
|
||||
"addSecretStorageKey",
|
||||
"hasSecretStorageKey",
|
||||
"secretStorageKeyNeedsUpgrade",
|
||||
"storeSecret",
|
||||
"getSecret",
|
||||
"isSecretStored",
|
||||
@@ -1358,7 +1377,8 @@ MatrixClient.prototype.cancelAndResendEventRoomKeyRequest = function(event) {
|
||||
};
|
||||
|
||||
/**
|
||||
* Enable end-to-end encryption for a room.
|
||||
* Enable end-to-end encryption for a room. This does not modify room state.
|
||||
* Any messages sent before the returned promise resolves will be sent unencrypted.
|
||||
* @param {string} roomId The room ID to enable encryption in.
|
||||
* @param {object} config The encryption config for the room.
|
||||
* @return {Promise} A promise that will resolve when encryption is set up.
|
||||
@@ -1430,15 +1450,17 @@ MatrixClient.prototype.exportRoomKeys = function() {
|
||||
* Import a list of room keys previously exported by exportRoomKeys
|
||||
*
|
||||
* @param {Object[]} keys a list of session export objects
|
||||
* @param {Object} opts
|
||||
* @param {Function} opts.progressCallback called with an object that has a "stage" param
|
||||
*
|
||||
* @return {Promise} a promise which resolves when the keys
|
||||
* have been imported
|
||||
*/
|
||||
MatrixClient.prototype.importRoomKeys = function(keys) {
|
||||
MatrixClient.prototype.importRoomKeys = function(keys, opts) {
|
||||
if (!this._crypto) {
|
||||
throw new Error("End-to-end encryption disabled");
|
||||
}
|
||||
return this._crypto.importRoomKeys(keys);
|
||||
return this._crypto.importRoomKeys(keys, opts);
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -1498,12 +1520,16 @@ MatrixClient.prototype.isKeyBackupTrusted = function(info) {
|
||||
|
||||
/**
|
||||
* @returns {bool} true if the client is configured to back up keys to
|
||||
* the server, otherwise false.
|
||||
* the server, otherwise false. If we haven't completed a successful check
|
||||
* of key backup status yet, returns null.
|
||||
*/
|
||||
MatrixClient.prototype.getKeyBackupEnabled = function() {
|
||||
if (this._crypto === null) {
|
||||
throw new Error("End-to-end encryption disabled");
|
||||
}
|
||||
if (!this._crypto._checkedForBackup) {
|
||||
return null;
|
||||
}
|
||||
return Boolean(this._crypto.backupKey);
|
||||
};
|
||||
|
||||
@@ -1822,7 +1848,7 @@ MatrixClient.prototype.restoreKeyBackupWithSecretStorage = async function(
|
||||
// store the fixed version
|
||||
const fixedKey = fixBackupKey(storedKey);
|
||||
if (fixedKey) {
|
||||
const [keyId] = await this.getSecretStorageKey();
|
||||
const [keyId] = await this._crypto.getSecretStorageKey();
|
||||
await this.storeSecret("m.megolm_backup.v1", fixedKey, [keyId]);
|
||||
}
|
||||
|
||||
@@ -1881,7 +1907,10 @@ MatrixClient.prototype.restoreKeyBackupWithCache = async function(
|
||||
|
||||
MatrixClient.prototype._restoreKeyBackup = function(
|
||||
privKey, targetRoomId, targetSessionId, backupInfo,
|
||||
{ cacheCompleteCallback }={}, // For sequencing during tests
|
||||
{
|
||||
cacheCompleteCallback, // For sequencing during tests
|
||||
progressCallback,
|
||||
}={},
|
||||
) {
|
||||
if (this._crypto === null) {
|
||||
throw new Error("End-to-end encryption disabled");
|
||||
@@ -1897,7 +1926,7 @@ MatrixClient.prototype._restoreKeyBackup = function(
|
||||
let backupPubKey;
|
||||
try {
|
||||
backupPubKey = decryption.init_with_private_key(privKey);
|
||||
} catch(e) {
|
||||
} catch (e) {
|
||||
decryption.free();
|
||||
throw e;
|
||||
}
|
||||
@@ -1916,6 +1945,12 @@ MatrixClient.prototype._restoreKeyBackup = function(
|
||||
console.warn("Error caching session backup key:", e);
|
||||
}).then(cacheCompleteCallback);
|
||||
|
||||
if (progressCallback) {
|
||||
progressCallback({
|
||||
stage: "fetch",
|
||||
});
|
||||
}
|
||||
|
||||
return this._http.authedRequest(
|
||||
undefined, "GET", path.path, path.queryData, undefined,
|
||||
{prefix: PREFIX_UNSTABLE},
|
||||
@@ -1950,7 +1985,11 @@ MatrixClient.prototype._restoreKeyBackup = function(
|
||||
}
|
||||
}
|
||||
|
||||
return this.importRoomKeys(keys);
|
||||
return this.importRoomKeys(keys, {
|
||||
progressCallback,
|
||||
untrusted: true,
|
||||
source: "backup",
|
||||
});
|
||||
}).then(() => {
|
||||
return this._crypto.setTrustedBackupPubKey(backupPubKey);
|
||||
}).then(() => {
|
||||
@@ -2086,6 +2125,7 @@ MatrixClient.prototype.getUsers = function() {
|
||||
|
||||
/**
|
||||
* Set account data event for the current user.
|
||||
* It will retry the request up to 5 times.
|
||||
* @param {string} eventType The event type
|
||||
* @param {Object} contents the contents object for the event
|
||||
* @param {module:client.callback} callback Optional.
|
||||
@@ -2097,9 +2137,13 @@ MatrixClient.prototype.setAccountData = function(eventType, contents, callback)
|
||||
$userId: this.credentials.userId,
|
||||
$type: eventType,
|
||||
});
|
||||
return this._http.authedRequest(
|
||||
callback, "PUT", path, undefined, contents,
|
||||
);
|
||||
const promise = retryNetworkOperation(5, () => {
|
||||
return this._http.authedRequest(undefined, "PUT", path, undefined, contents);
|
||||
});
|
||||
if (callback) {
|
||||
promise.then(result => callback(null, result), callback);
|
||||
}
|
||||
return promise;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -2134,9 +2178,17 @@ MatrixClient.prototype.getAccountDataFromServer = async function(eventType) {
|
||||
$userId: this.credentials.userId,
|
||||
$type: eventType,
|
||||
});
|
||||
return this._http.authedRequest(
|
||||
undefined, "GET", path, undefined,
|
||||
);
|
||||
try {
|
||||
const result = await this._http.authedRequest(
|
||||
undefined, "GET", path, undefined,
|
||||
);
|
||||
return result;
|
||||
} catch (e) {
|
||||
if (e.data && e.data.errcode === 'M_NOT_FOUND') {
|
||||
return null;
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -2450,6 +2502,7 @@ MatrixClient.prototype._sendCompleteEvent = function(roomId, eventObject, txnId,
|
||||
const localEvent = new MatrixEvent(Object.assign(eventObject, {
|
||||
event_id: "~" + roomId + ":" + txnId,
|
||||
user_id: this.credentials.userId,
|
||||
sender: this.credentials.userId,
|
||||
room_id: roomId,
|
||||
origin_server_ts: new Date().getTime(),
|
||||
}));
|
||||
@@ -2471,7 +2524,7 @@ MatrixClient.prototype._sendCompleteEvent = function(roomId, eventObject, txnId,
|
||||
const type = localEvent.getType();
|
||||
logger.log(`sendEvent of type ${type} in ${roomId} with txnId ${txnId}`);
|
||||
|
||||
localEvent._txnId = txnId;
|
||||
localEvent.setTxnId(txnId);
|
||||
localEvent.setStatus(EventStatus.SENDING);
|
||||
|
||||
// add this event immediately to the local store as 'sending'.
|
||||
@@ -2639,7 +2692,11 @@ function _updatePendingEventStatus(room, event, newStatus) {
|
||||
}
|
||||
|
||||
function _sendEventHttpRequest(client, event) {
|
||||
const txnId = event._txnId ? event._txnId : client.makeTxnId();
|
||||
let txnId = event.getTxnId();
|
||||
if (!txnId) {
|
||||
txnId = client.makeTxnId();
|
||||
event.setTxnId(txnId);
|
||||
}
|
||||
|
||||
const pathParams = {
|
||||
$roomId: event.getRoomId(),
|
||||
@@ -2960,25 +3017,32 @@ MatrixClient.prototype.setRoomReadMarkers = async function(
|
||||
* May return synthesized attributes if the URL lacked OG meta.
|
||||
*/
|
||||
MatrixClient.prototype.getUrlPreview = function(url, ts, callback) {
|
||||
// bucket the timestamp to the nearest minute to prevent excessive spam to the server
|
||||
// Surely 60-second accuracy is enough for anyone.
|
||||
ts = Math.floor(ts / 60000) * 60000;
|
||||
|
||||
const key = ts + "_" + url;
|
||||
const og = this.urlPreviewCache[key];
|
||||
if (og) {
|
||||
return Promise.resolve(og);
|
||||
|
||||
// If there's already a request in flight (or we've handled it), return that instead.
|
||||
const cachedPreview = this.urlPreviewCache[key];
|
||||
if (cachedPreview) {
|
||||
if (callback) {
|
||||
cachedPreview.then(callback).catch(callback);
|
||||
}
|
||||
return cachedPreview;
|
||||
}
|
||||
|
||||
const self = this;
|
||||
return this._http.authedRequest(
|
||||
const resp = this._http.authedRequest(
|
||||
callback, "GET", "/preview_url", {
|
||||
url: url,
|
||||
ts: ts,
|
||||
}, undefined, {
|
||||
prefix: PREFIX_MEDIA_R0,
|
||||
},
|
||||
).then(function(response) {
|
||||
// TODO: expire cache occasionally
|
||||
self.urlPreviewCache[key] = response;
|
||||
return response;
|
||||
});
|
||||
);
|
||||
// TODO: Expire the URL preview cache sometimes
|
||||
this.urlPreviewCache[key] = resp;
|
||||
return resp;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -3480,46 +3544,6 @@ MatrixClient.prototype.setPresence = function(opts, callback) {
|
||||
);
|
||||
};
|
||||
|
||||
function _presenceList(callback, client, opts, method) {
|
||||
const path = utils.encodeUri("/presence/list/$userId", {
|
||||
$userId: client.credentials.userId,
|
||||
});
|
||||
return client._http.authedRequest(callback, method, path, undefined, opts);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve current user presence list.
|
||||
* @param {module:client.callback} callback Optional.
|
||||
* @return {Promise} Resolves: TODO
|
||||
* @return {module:http-api.MatrixError} Rejects: with an error response.
|
||||
*/
|
||||
MatrixClient.prototype.getPresenceList = function(callback) {
|
||||
return _presenceList(callback, this, undefined, "GET");
|
||||
};
|
||||
|
||||
/**
|
||||
* Add users to the current user presence list.
|
||||
* @param {module:client.callback} callback Optional.
|
||||
* @param {string[]} userIds
|
||||
* @return {Promise} Resolves: TODO
|
||||
* @return {module:http-api.MatrixError} Rejects: with an error response.
|
||||
*/
|
||||
MatrixClient.prototype.inviteToPresenceList = function(callback, userIds) {
|
||||
const opts = {"invite": userIds};
|
||||
return _presenceList(callback, this, opts, "POST");
|
||||
};
|
||||
|
||||
/**
|
||||
* Drop users from the current user presence list.
|
||||
* @param {module:client.callback} callback Optional.
|
||||
* @param {string[]} userIds
|
||||
* @return {Promise} Resolves: TODO
|
||||
* @return {module:http-api.MatrixError} Rejects: with an error response.
|
||||
**/
|
||||
MatrixClient.prototype.dropFromPresenceList = function(callback, userIds) {
|
||||
const opts = {"drop": userIds};
|
||||
return _presenceList(callback, this, opts, "POST");
|
||||
};
|
||||
|
||||
/**
|
||||
* Retrieve older messages from the given room and put them in the timeline.
|
||||
@@ -3778,7 +3802,9 @@ MatrixClient.prototype.paginateEventTimeline = function(eventTimeline, opts) {
|
||||
return pendingRequest;
|
||||
}
|
||||
|
||||
let path, params, promise;
|
||||
let path;
|
||||
let params;
|
||||
let promise;
|
||||
const self = this;
|
||||
|
||||
if (isNotifTimeline) {
|
||||
@@ -4198,7 +4224,8 @@ MatrixClient.prototype.getRoomPushRule = function(scope, roomId) {
|
||||
*/
|
||||
MatrixClient.prototype.setRoomMutePushRule = function(scope, roomId, mute) {
|
||||
const self = this;
|
||||
let deferred, hasDontNotifyRule;
|
||||
let deferred;
|
||||
let hasDontNotifyRule;
|
||||
|
||||
// Get the existing room-kind push rule if any
|
||||
const roomPushRule = this.getRoomPushRule(scope, roomId);
|
||||
@@ -4510,64 +4537,54 @@ MatrixClient.prototype.getFilter = function(userId, filterId, allowCached) {
|
||||
* @param {Filter} filter
|
||||
* @return {Promise<String>} Filter ID
|
||||
*/
|
||||
MatrixClient.prototype.getOrCreateFilter = function(filterName, filter) {
|
||||
MatrixClient.prototype.getOrCreateFilter = async function(filterName, filter) {
|
||||
const filterId = this.store.getFilterIdByName(filterName);
|
||||
let promise = Promise.resolve();
|
||||
const self = this;
|
||||
let existingId = undefined;
|
||||
|
||||
if (filterId) {
|
||||
// check that the existing filter matches our expectations
|
||||
promise = self.getFilter(self.credentials.userId,
|
||||
filterId, true,
|
||||
).then(function(existingFilter) {
|
||||
const oldDef = existingFilter.getDefinition();
|
||||
const newDef = filter.getDefinition();
|
||||
try {
|
||||
const existingFilter =
|
||||
await this.getFilter(this.credentials.userId, filterId, true);
|
||||
if (existingFilter) {
|
||||
const oldDef = existingFilter.getDefinition();
|
||||
const newDef = filter.getDefinition();
|
||||
|
||||
if (utils.deepCompare(oldDef, newDef)) {
|
||||
// super, just use that.
|
||||
// debuglog("Using existing filter ID %s: %s", filterId,
|
||||
// JSON.stringify(oldDef));
|
||||
return Promise.resolve(filterId);
|
||||
if (utils.deepCompare(oldDef, newDef)) {
|
||||
// super, just use that.
|
||||
// debuglog("Using existing filter ID %s: %s", filterId,
|
||||
// JSON.stringify(oldDef));
|
||||
existingId = filterId;
|
||||
}
|
||||
}
|
||||
// debuglog("Existing filter ID %s: %s; new filter: %s",
|
||||
// filterId, JSON.stringify(oldDef), JSON.stringify(newDef));
|
||||
self.store.setFilterIdByName(filterName, undefined);
|
||||
return undefined;
|
||||
}, function(error) {
|
||||
} catch (error) {
|
||||
// Synapse currently returns the following when the filter cannot be found:
|
||||
// {
|
||||
// errcode: "M_UNKNOWN",
|
||||
// name: "M_UNKNOWN",
|
||||
// message: "No row found",
|
||||
// data: Object, httpStatus: 404
|
||||
// }
|
||||
if (error.httpStatus === 404 &&
|
||||
(error.errcode === "M_UNKNOWN" || error.errcode === "M_NOT_FOUND")) {
|
||||
// Clear existing filterId from localStorage
|
||||
// if it no longer exists on the server
|
||||
self.store.setFilterIdByName(filterName, undefined);
|
||||
// Return a undefined value for existingId further down the promise chain
|
||||
return undefined;
|
||||
} else {
|
||||
if (error.errcode !== "M_UNKNOWN" && error.errcode !== "M_NOT_FOUND") {
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
}
|
||||
// if the filter doesn't exist anymore on the server, remove from store
|
||||
if (!existingId) {
|
||||
this.store.setFilterIdByName(filterName, undefined);
|
||||
}
|
||||
}
|
||||
|
||||
return promise.then(function(existingId) {
|
||||
if (existingId) {
|
||||
return existingId;
|
||||
}
|
||||
if (existingId) {
|
||||
return existingId;
|
||||
}
|
||||
|
||||
// create a new filter
|
||||
return self.createFilter(filter.getDefinition(),
|
||||
).then(function(createdFilter) {
|
||||
// debuglog("Created new filter ID %s: %s", createdFilter.filterId,
|
||||
// JSON.stringify(createdFilter.getDefinition()));
|
||||
self.store.setFilterIdByName(filterName, createdFilter.filterId);
|
||||
return createdFilter.filterId;
|
||||
});
|
||||
});
|
||||
// create a new filter
|
||||
const createdFilter = await this.createFilter(filter.getDefinition());
|
||||
|
||||
// debuglog("Created new filter ID %s: %s", createdFilter.filterId,
|
||||
// JSON.stringify(createdFilter.getDefinition()));
|
||||
this.store.setFilterIdByName(filterName, createdFilter.filterId);
|
||||
return createdFilter.filterId;
|
||||
};
|
||||
|
||||
|
||||
@@ -4731,6 +4748,9 @@ MatrixClient.prototype.deactivateSynapseUser = function(userId) {
|
||||
* @param {Boolean=} opts.lazyLoadMembers True to not load all membership events during
|
||||
* initial sync but fetch them when needed by calling `loadOutOfBandMembers`
|
||||
* This will override the filter option at this moment.
|
||||
* @param {Number=} opts.clientWellKnownPollPeriod The number of seconds between polls
|
||||
* to /.well-known/matrix/client, undefined to disable. This should be in the order of hours.
|
||||
* Default: undefined.
|
||||
*/
|
||||
MatrixClient.prototype.startClient = async function(opts) {
|
||||
if (this.clientRunning) {
|
||||
@@ -4779,6 +4799,29 @@ MatrixClient.prototype.startClient = async function(opts) {
|
||||
this._clientOpts = opts;
|
||||
this._syncApi = new SyncApi(this, opts);
|
||||
this._syncApi.sync();
|
||||
|
||||
if (opts.clientWellKnownPollPeriod !== undefined) {
|
||||
this._clientWellKnownIntervalID =
|
||||
setInterval(() => {
|
||||
this._fetchClientWellKnown();
|
||||
}, 1000 * opts.clientWellKnownPollPeriod);
|
||||
this._fetchClientWellKnown();
|
||||
}
|
||||
};
|
||||
|
||||
MatrixClient.prototype._fetchClientWellKnown = async function() {
|
||||
try {
|
||||
this._clientWellKnown = await AutoDiscovery.getRawClientConfig(this.getDomain());
|
||||
this.emit("WellKnown.client", this._clientWellKnown);
|
||||
} catch (err) {
|
||||
logger.error("Failed to get client well-known", err);
|
||||
this._clientWellKnown = undefined;
|
||||
this.emit("WellKnown.error", err);
|
||||
}
|
||||
};
|
||||
|
||||
MatrixClient.prototype.getClientWellKnown = function() {
|
||||
return this._clientWellKnown;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -4820,6 +4863,9 @@ MatrixClient.prototype.stopClient = function() {
|
||||
this._peekSync.stopPeeking();
|
||||
}
|
||||
global.clearTimeout(this._checkTurnServersTimeoutID);
|
||||
if (this._clientWellKnownIntervalID !== undefined) {
|
||||
global.clearInterval(this._clientWellKnownIntervalID);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -5572,12 +5618,29 @@ MatrixClient.prototype.generateClientSecret = function() {
|
||||
* Fires whenever new user-scoped account_data is added.
|
||||
* @event module:client~MatrixClient#"accountData"
|
||||
* @param {MatrixEvent} event The event describing the account_data just added
|
||||
* @param {MatrixEvent} event The previous account data, if known.
|
||||
* @example
|
||||
* matrixClient.on("accountData", function(event){
|
||||
* matrixClient.on("accountData", function(event, oldEvent){
|
||||
* myAccountData[event.type] = event.content;
|
||||
* });
|
||||
*/
|
||||
|
||||
/**
|
||||
* Fires whenever the stored devices for a user have changed
|
||||
* @event module:client~MatrixClient#"crypto.devicesUpdated"
|
||||
* @param {String[]} users A list of user IDs that were updated
|
||||
* @param {bool} initialFetch If true, the store was empty (apart
|
||||
* from our own device) and has been seeded.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Fires whenever the stored devices for a user will be updated
|
||||
* @event module:client~MatrixClient#"crypto.willUpdateDevices"
|
||||
* @param {String[]} users A list of user IDs that will be updated
|
||||
* @param {bool} initialFetch If true, the store is empty (apart
|
||||
* from our own device) and is being seeded.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Fires whenever the status of e2e key backup changes, as returned by getKeyBackupEnabled()
|
||||
* @event module:client~MatrixClient#"crypto.keyBackupStatus"
|
||||
|
||||
@@ -75,35 +75,3 @@ export function getHttpUriForMxc(baseUrl, mxc, width, height,
|
||||
(utils.keys(params).length === 0 ? "" :
|
||||
("?" + utils.encodeParams(params))) + fragment;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get an identicon URL from an arbitrary string.
|
||||
* @param {string} baseUrl The base homeserver url which has a content repo.
|
||||
* @param {string} identiconString The string to create an identicon for.
|
||||
* @param {Number} width The desired width of the image in pixels. Default: 96.
|
||||
* @param {Number} height The desired height of the image in pixels. Default: 96.
|
||||
* @return {string} The complete URL to the identicon.
|
||||
* @deprecated This is no longer in the specification.
|
||||
*/
|
||||
export function getIdenticonUri(baseUrl, identiconString, width, height) {
|
||||
if (!identiconString) {
|
||||
return null;
|
||||
}
|
||||
if (!width) {
|
||||
width = 96;
|
||||
}
|
||||
if (!height) {
|
||||
height = 96;
|
||||
}
|
||||
const params = {
|
||||
width: width,
|
||||
height: height,
|
||||
};
|
||||
|
||||
const path = utils.encodeUri("/_matrix/media/unstable/identicon/$ident", {
|
||||
$ident: identiconString,
|
||||
});
|
||||
return baseUrl + path +
|
||||
(utils.keys(params).length === 0 ? "" :
|
||||
("?" + utils.encodeParams(params)));
|
||||
}
|
||||
|
||||
+114
-8
@@ -24,6 +24,9 @@ import {decodeBase64, encodeBase64, pkSign, pkVerify} from './olmlib';
|
||||
import {EventEmitter} from 'events';
|
||||
import {logger} from '../logger';
|
||||
import {IndexedDBCryptoStore} from '../crypto/store/indexeddb-crypto-store';
|
||||
import {decryptAES, encryptAES} from './aes';
|
||||
|
||||
const KEY_REQUEST_TIMEOUT_MS = 1000 * 60;
|
||||
|
||||
function publicKeyFromKeyInfo(keyInfo) {
|
||||
// `keys` is an object with { [`ed25519:${pubKey}`]: pubKey }
|
||||
@@ -71,7 +74,7 @@ export class CrossSigningInfo extends EventEmitter {
|
||||
* @returns {Array} An array with [ public key, Olm.PkSigning ]
|
||||
*/
|
||||
async getCrossSigningKey(type, expectedPubkey) {
|
||||
const shouldCache = ["self_signing", "user_signing"].indexOf(type) >= 0;
|
||||
const shouldCache = ["master", "self_signing", "user_signing"].indexOf(type) >= 0;
|
||||
|
||||
if (!this._callbacks.getCrossSigningKey) {
|
||||
throw new Error("No getCrossSigningKey callback supplied");
|
||||
@@ -177,12 +180,12 @@ export class CrossSigningInfo extends EventEmitter {
|
||||
* typically called in conjunction with the creation of new cross-signing
|
||||
* keys.
|
||||
*
|
||||
* @param {object} keys The keys to store
|
||||
* @param {Map} keys The keys to store
|
||||
* @param {SecretStorage} secretStorage The secret store using account data
|
||||
*/
|
||||
static async storeInSecretStorage(keys, secretStorage) {
|
||||
for (const type of Object.keys(keys)) {
|
||||
const encodedKey = encodeBase64(keys[type]);
|
||||
for (const [type, privateKey] of keys) {
|
||||
const encodedKey = encodeBase64(privateKey);
|
||||
await secretStorage.store(`m.cross_signing.${type}`, encodedKey);
|
||||
}
|
||||
}
|
||||
@@ -637,10 +640,10 @@ export class DeviceTrustLevel {
|
||||
}
|
||||
}
|
||||
|
||||
export function createCryptoStoreCacheCallbacks(store) {
|
||||
export function createCryptoStoreCacheCallbacks(store, olmdevice) {
|
||||
return {
|
||||
getCrossSigningKeyCache: function(type, _expectedPublicKey) {
|
||||
return new Promise((resolve) => {
|
||||
getCrossSigningKeyCache: async function(type, _expectedPublicKey) {
|
||||
const key = await new Promise((resolve) => {
|
||||
return store.doTxn(
|
||||
'readonly',
|
||||
[IndexedDBCryptoStore.STORE_ACCOUNT],
|
||||
@@ -649,13 +652,23 @@ export function createCryptoStoreCacheCallbacks(store) {
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
if (key && key.ciphertext) {
|
||||
const pickleKey = Buffer.from(olmdevice._pickleKey);
|
||||
const decrypted = await decryptAES(key, pickleKey, type);
|
||||
return decodeBase64(decrypted);
|
||||
} else {
|
||||
return key;
|
||||
}
|
||||
},
|
||||
storeCrossSigningKeyCache: function(type, key) {
|
||||
storeCrossSigningKeyCache: async function(type, key) {
|
||||
if (!(key instanceof Uint8Array)) {
|
||||
throw new Error(
|
||||
`storeCrossSigningKeyCache expects Uint8Array, got ${key}`,
|
||||
);
|
||||
}
|
||||
const pickleKey = Buffer.from(olmdevice._pickleKey);
|
||||
key = await encryptAES(encodeBase64(key), pickleKey, type);
|
||||
return store.doTxn(
|
||||
'readwrite',
|
||||
[IndexedDBCryptoStore.STORE_ACCOUNT],
|
||||
@@ -666,3 +679,96 @@ export function createCryptoStoreCacheCallbacks(store) {
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Request cross-signing keys from another device during verification.
|
||||
*
|
||||
* @param {module:base-apis~MatrixBaseApis} baseApis base Matrix API interface
|
||||
* @param {string} userId The user ID being verified
|
||||
* @param {string} deviceId The device ID being verified
|
||||
*/
|
||||
export async function requestKeysDuringVerification(baseApis, userId, deviceId) {
|
||||
// If this is a self-verification, ask the other party for keys
|
||||
if (baseApis.getUserId() !== userId) {
|
||||
return;
|
||||
}
|
||||
console.log("Cross-signing: Self-verification done; requesting keys");
|
||||
// This happens asynchronously, and we're not concerned about waiting for
|
||||
// it. We return here in order to test.
|
||||
return new Promise((resolve, reject) => {
|
||||
const client = baseApis;
|
||||
const original = client._crypto._crossSigningInfo;
|
||||
|
||||
// We already have all of the infrastructure we need to validate and
|
||||
// cache cross-signing keys, so instead of replicating that, here we set
|
||||
// up callbacks that request them from the other device and call
|
||||
// CrossSigningInfo.getCrossSigningKey() to validate/cache
|
||||
const crossSigning = new CrossSigningInfo(
|
||||
original.userId,
|
||||
{ getCrossSigningKey: async (type) => {
|
||||
console.debug("Cross-signing: requesting secret",
|
||||
type, deviceId);
|
||||
const { promise } = client.requestSecret(
|
||||
`m.cross_signing.${type}`, [deviceId],
|
||||
);
|
||||
const result = await promise;
|
||||
const decoded = decodeBase64(result);
|
||||
return Uint8Array.from(decoded);
|
||||
} },
|
||||
original._cacheCallbacks,
|
||||
);
|
||||
crossSigning.keys = original.keys;
|
||||
|
||||
// XXX: get all keys out if we get one key out
|
||||
// https://github.com/vector-im/element-web/issues/12604
|
||||
// then change here to reject on the timeout
|
||||
// Requests can be ignored, so don't wait around forever
|
||||
const timeout = new Promise((resolve, reject) => {
|
||||
setTimeout(
|
||||
resolve,
|
||||
KEY_REQUEST_TIMEOUT_MS,
|
||||
new Error("Timeout"),
|
||||
);
|
||||
});
|
||||
|
||||
// also request and cache the key backup key
|
||||
const backupKeyPromise = new Promise(async resolve => {
|
||||
const cachedKey = await client._crypto.getSessionBackupPrivateKey();
|
||||
if (!cachedKey) {
|
||||
logger.info("No cached backup key found. Requesting...");
|
||||
const secretReq = client.requestSecret(
|
||||
'm.megolm_backup.v1', [deviceId],
|
||||
);
|
||||
const base64Key = await secretReq.promise;
|
||||
logger.info("Got key backup key, decoding...");
|
||||
const decodedKey = decodeBase64(base64Key);
|
||||
logger.info("Decoded backup key, storing...");
|
||||
client._crypto.storeSessionBackupPrivateKey(
|
||||
Uint8Array.from(decodedKey),
|
||||
);
|
||||
logger.info("Backup key stored. Starting backup restore...");
|
||||
const backupInfo = await client.getKeyBackupVersion();
|
||||
// no need to await for this - just let it go in the bg
|
||||
client.restoreKeyBackupWithCache(
|
||||
undefined, undefined, backupInfo,
|
||||
).then(() => {
|
||||
logger.info("Backup restored.");
|
||||
});
|
||||
}
|
||||
resolve();
|
||||
});
|
||||
|
||||
// We call getCrossSigningKey() for its side-effects
|
||||
return Promise.race([
|
||||
Promise.all([
|
||||
crossSigning.getCrossSigningKey("master"),
|
||||
crossSigning.getCrossSigningKey("self_signing"),
|
||||
crossSigning.getCrossSigningKey("user_signing"),
|
||||
backupKeyPromise,
|
||||
]),
|
||||
timeout,
|
||||
]).then(resolve, reject);
|
||||
}).catch((e) => {
|
||||
console.warn("Cross-signing: failure while requesting keys:", e);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -109,6 +109,9 @@ export class DeviceList extends EventEmitter {
|
||||
this._savePromiseTime = null;
|
||||
// The timer used to delay the save
|
||||
this._saveTimer = null;
|
||||
// True if we have fetched data from the server or loaded a non-empty
|
||||
// set of device data from the store
|
||||
this._hasFetched = null;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -118,6 +121,7 @@ export class DeviceList extends EventEmitter {
|
||||
await this._cryptoStore.doTxn(
|
||||
'readonly', [IndexedDBCryptoStore.STORE_DEVICE_DATA], (txn) => {
|
||||
this._cryptoStore.getEndToEndDeviceData(txn, (deviceData) => {
|
||||
this._hasFetched = Boolean(deviceData && deviceData.devices);
|
||||
this._devices = deviceData ? deviceData.devices : {},
|
||||
this._crossSigningInfo = deviceData ?
|
||||
deviceData.crossSigningInfo || {} : {};
|
||||
@@ -652,6 +656,7 @@ export class DeviceList extends EventEmitter {
|
||||
});
|
||||
|
||||
const finished = (success) => {
|
||||
this.emit("crypto.willUpdateDevices", users, !this._hasFetched);
|
||||
users.forEach((u) => {
|
||||
this._dirty = true;
|
||||
|
||||
@@ -677,7 +682,8 @@ export class DeviceList extends EventEmitter {
|
||||
}
|
||||
});
|
||||
this.saveIfDirty();
|
||||
this.emit("crypto.devicesUpdated", users);
|
||||
this.emit("crypto.devicesUpdated", users, !this._hasFetched);
|
||||
this._hasFetched = true;
|
||||
};
|
||||
|
||||
return prom;
|
||||
@@ -784,7 +790,7 @@ class DeviceListUpdateSerialiser {
|
||||
|
||||
// yield to other things that want to execute in between users, to
|
||||
// avoid wedging the CPU
|
||||
// (https://github.com/vector-im/riot-web/issues/3158)
|
||||
// (https://github.com/vector-im/element-web/issues/3158)
|
||||
//
|
||||
// of course we ought to do this in a web worker or similar, but
|
||||
// this serves as an easy solution for now.
|
||||
|
||||
@@ -0,0 +1,341 @@
|
||||
import { logger } from "../logger";
|
||||
import {MatrixEvent} from "../models/event";
|
||||
import {EventEmitter} from "events";
|
||||
import {createCryptoStoreCacheCallbacks} from "./CrossSigning";
|
||||
import {IndexedDBCryptoStore} from './store/indexeddb-crypto-store';
|
||||
import {
|
||||
PREFIX_UNSTABLE,
|
||||
} from "../http-api";
|
||||
|
||||
/**
|
||||
* Builds an EncryptionSetupOperation by calling any of the add.. methods.
|
||||
* Once done, `buildOperation()` can be called which allows to apply to operation.
|
||||
*
|
||||
* This is used as a helper by Crypto to keep track of all the network requests
|
||||
* and other side-effects of bootstrapping, so it can be applied in one go (and retried in the future)
|
||||
* Also keeps track of all the private keys created during bootstrapping, so we don't need to prompt for them
|
||||
* more than once.
|
||||
*/
|
||||
export class EncryptionSetupBuilder {
|
||||
/**
|
||||
* @param {Object.<String, MatrixEvent>} accountData pre-existing account data, will only be read, not written.
|
||||
* @param {CryptoCallbacks} delegateCryptoCallbacks crypto callbacks to delegate to if the key isn't in cache yet
|
||||
*/
|
||||
constructor(accountData, delegateCryptoCallbacks) {
|
||||
this.accountDataClientAdapter = new AccountDataClientAdapter(accountData);
|
||||
this.crossSigningCallbacks = new CrossSigningCallbacks();
|
||||
this.ssssCryptoCallbacks = new SSSSCryptoCallbacks(delegateCryptoCallbacks);
|
||||
|
||||
this._crossSigningKeys = null;
|
||||
this._keySignatures = null;
|
||||
this._keyBackupInfo = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds new cross-signing public keys
|
||||
* @param {Object} auth auth dictionary needed to upload the new keys
|
||||
* @param {Object} keys the new keys
|
||||
*/
|
||||
addCrossSigningKeys(auth, keys) {
|
||||
this._crossSigningKeys = {auth, keys};
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds the key backup info to be updated on the server
|
||||
*
|
||||
* Used either to create a new key backup, or add signatures
|
||||
* from the new MSK.
|
||||
*
|
||||
* @param {Object} keyBackupInfo as received from/sent to the server
|
||||
*/
|
||||
addSessionBackup(keyBackupInfo) {
|
||||
this._keyBackupInfo = keyBackupInfo;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds the session backup private key to be updated in the local cache
|
||||
*
|
||||
* Used after fixing the format of the key
|
||||
*
|
||||
* @param {Uint8Array} privateKey
|
||||
*/
|
||||
addSessionBackupPrivateKeyToCache(privateKey) {
|
||||
this._sessionBackupPrivateKey = privateKey;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add signatures from a given user and device/x-sign key
|
||||
* Used to sign the new cross-signing key with the device key
|
||||
*
|
||||
* @param {String} userId
|
||||
* @param {String} deviceId
|
||||
* @param {String} signature
|
||||
*/
|
||||
addKeySignature(userId, deviceId, signature) {
|
||||
if (!this._keySignatures) {
|
||||
this._keySignatures = {};
|
||||
}
|
||||
const userSignatures = this._keySignatures[userId] || {};
|
||||
this._keySignatures[userId] = userSignatures;
|
||||
userSignatures[deviceId] = signature;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param {String} type
|
||||
* @param {Object} content
|
||||
* @return {Promise}
|
||||
*/
|
||||
setAccountData(type, content) {
|
||||
return this.accountDataClientAdapter.setAccountData(type, content);
|
||||
}
|
||||
|
||||
/**
|
||||
* builds the operation containing all the parts that have been added to the builder
|
||||
* @return {EncryptionSetupOperation}
|
||||
*/
|
||||
buildOperation() {
|
||||
const accountData = this.accountDataClientAdapter._values;
|
||||
return new EncryptionSetupOperation(
|
||||
accountData,
|
||||
this._crossSigningKeys,
|
||||
this._keyBackupInfo,
|
||||
this._keySignatures,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Stores the created keys locally.
|
||||
*
|
||||
* This does not yet store the operation in a way that it can be restored,
|
||||
* but that is the idea in the future.
|
||||
*
|
||||
* @param {Crypto} crypto
|
||||
* @return {Promise}
|
||||
*/
|
||||
async persist(crypto) {
|
||||
// store private keys in cache
|
||||
if (this._crossSigningKeys) {
|
||||
const cacheCallbacks = createCryptoStoreCacheCallbacks(
|
||||
crypto._cryptoStore, crypto._olmDevice);
|
||||
for (const type of ["master", "self_signing", "user_signing"]) {
|
||||
logger.log(`Cache ${type} cross-signing private key locally`);
|
||||
const privateKey = this.crossSigningCallbacks.privateKeys.get(type);
|
||||
await cacheCallbacks.storeCrossSigningKeyCache(type, privateKey);
|
||||
}
|
||||
// store own cross-sign pubkeys as trusted
|
||||
await crypto._cryptoStore.doTxn(
|
||||
'readwrite', [IndexedDBCryptoStore.STORE_ACCOUNT],
|
||||
(txn) => {
|
||||
crypto._cryptoStore.storeCrossSigningKeys(
|
||||
txn, this._crossSigningKeys.keys);
|
||||
},
|
||||
);
|
||||
}
|
||||
// store session backup key in cache
|
||||
if (this._sessionBackupPrivateKey) {
|
||||
await crypto.storeSessionBackupPrivateKey(this._sessionBackupPrivateKey);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Can be created from EncryptionSetupBuilder, or
|
||||
* (in a follow-up PR, not implemented yet) restored from storage, to retry.
|
||||
*
|
||||
* It does not have knowledge of any private keys, unlike the builder.
|
||||
*/
|
||||
export class EncryptionSetupOperation {
|
||||
/**
|
||||
* @param {Map<String, Object>} accountData
|
||||
* @param {Object} crossSigningKeys
|
||||
* @param {Object} keyBackupInfo
|
||||
* @param {Object} keySignatures
|
||||
*/
|
||||
constructor(accountData, crossSigningKeys, keyBackupInfo, keySignatures) {
|
||||
this._accountData = accountData;
|
||||
this._crossSigningKeys = crossSigningKeys;
|
||||
this._keyBackupInfo = keyBackupInfo;
|
||||
this._keySignatures = keySignatures;
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs the (remaining part of, in the future) operation by sending requests to the server.
|
||||
* @param {Crypto} crypto
|
||||
*/
|
||||
async apply(crypto) {
|
||||
const baseApis = crypto._baseApis;
|
||||
// set account data
|
||||
if (this._accountData) {
|
||||
for (const [type, content] of this._accountData) {
|
||||
await baseApis.setAccountData(type, content);
|
||||
}
|
||||
}
|
||||
// upload cross-signing keys
|
||||
if (this._crossSigningKeys) {
|
||||
const keys = {};
|
||||
for (const [name, key] of Object.entries(this._crossSigningKeys.keys)) {
|
||||
keys[name + "_key"] = key;
|
||||
}
|
||||
await baseApis.uploadDeviceSigningKeys(
|
||||
this._crossSigningKeys.auth,
|
||||
keys,
|
||||
);
|
||||
// pass the new keys to the main instance of our own CrossSigningInfo.
|
||||
crypto._crossSigningInfo.setKeys(this._crossSigningKeys.keys);
|
||||
}
|
||||
// upload first cross-signing signatures with the new key
|
||||
// (e.g. signing our own device)
|
||||
if (this._keySignatures) {
|
||||
await baseApis.uploadKeySignatures(this._keySignatures);
|
||||
}
|
||||
// need to create/update key backup info
|
||||
if (this._keyBackupInfo) {
|
||||
if (this._keyBackupInfo.version) {
|
||||
// session backup signature
|
||||
// The backup is trusted because the user provided the private key.
|
||||
// Sign the backup with the cross signing key so the key backup can
|
||||
// be trusted via cross-signing.
|
||||
await baseApis._http.authedRequest(
|
||||
undefined, "PUT", "/room_keys/version/" + this._keyBackupInfo.version,
|
||||
undefined, {
|
||||
algorithm: this._keyBackupInfo.algorithm,
|
||||
auth_data: this._keyBackupInfo.auth_data,
|
||||
},
|
||||
{prefix: PREFIX_UNSTABLE},
|
||||
);
|
||||
} else {
|
||||
// add new key backup
|
||||
await baseApis._http.authedRequest(
|
||||
undefined, "POST", "/room_keys/version",
|
||||
undefined, this._keyBackupInfo,
|
||||
{prefix: PREFIX_UNSTABLE},
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Catches account data set by SecretStorage during bootstrapping by
|
||||
* implementing the methods related to account data in MatrixClient
|
||||
*/
|
||||
class AccountDataClientAdapter extends EventEmitter {
|
||||
/**
|
||||
* @param {Object.<String, MatrixEvent>} accountData existing account data
|
||||
*/
|
||||
constructor(accountData) {
|
||||
super();
|
||||
this._existingValues = accountData;
|
||||
this._values = new Map();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {String} type
|
||||
* @return {Promise<Object>} the content of the account data
|
||||
*/
|
||||
getAccountDataFromServer(type) {
|
||||
return Promise.resolve(this.getAccountData(type));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {String} type
|
||||
* @return {Object} the content of the account data
|
||||
*/
|
||||
getAccountData(type) {
|
||||
const modifiedValue = this._values.get(type);
|
||||
if (modifiedValue) {
|
||||
return modifiedValue;
|
||||
}
|
||||
const existingValue = this._existingValues[type];
|
||||
if (existingValue) {
|
||||
return existingValue.getContent();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {String} type
|
||||
* @param {Object} content
|
||||
* @return {Promise}
|
||||
*/
|
||||
setAccountData(type, content) {
|
||||
const lastEvent = this._values.get(type);
|
||||
this._values.set(type, content);
|
||||
// ensure accountData is emitted on the next tick,
|
||||
// as SecretStorage listens for it while calling this method
|
||||
// and it seems to rely on this.
|
||||
return Promise.resolve().then(() => {
|
||||
const event = new MatrixEvent({type, content});
|
||||
this.emit("accountData", event, lastEvent);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Catches the private cross-signing keys set during bootstrapping
|
||||
* by both cache callbacks (see createCryptoStoreCacheCallbacks) as non-cache callbacks.
|
||||
* See CrossSigningInfo constructor
|
||||
*/
|
||||
class CrossSigningCallbacks {
|
||||
constructor() {
|
||||
this.privateKeys = new Map();
|
||||
}
|
||||
|
||||
// cache callbacks
|
||||
getCrossSigningKeyCache(type, expectedPublicKey) {
|
||||
return this.getCrossSigningKey(type, expectedPublicKey);
|
||||
}
|
||||
|
||||
storeCrossSigningKeyCache(type, key) {
|
||||
this.privateKeys.set(type, key);
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
// non-cache callbacks
|
||||
getCrossSigningKey(type, _expectedPubkey) {
|
||||
return Promise.resolve(this.privateKeys.get(type));
|
||||
}
|
||||
|
||||
saveCrossSigningKeys(privateKeys) {
|
||||
for (const [type, privateKey] of Object.entries(privateKeys)) {
|
||||
this.privateKeys.set(type, privateKey);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Catches the 4S private key set during bootstrapping by implementing
|
||||
* the SecretStorage crypto callbacks
|
||||
*/
|
||||
class SSSSCryptoCallbacks {
|
||||
constructor(delegateCryptoCallbacks) {
|
||||
this._privateKeys = new Map();
|
||||
this._delegateCryptoCallbacks = delegateCryptoCallbacks;
|
||||
}
|
||||
|
||||
async getSecretStorageKey({ keys }, name) {
|
||||
for (const keyId of Object.keys(keys)) {
|
||||
const privateKey = this._privateKeys.get(keyId);
|
||||
if (privateKey) {
|
||||
return [keyId, privateKey];
|
||||
}
|
||||
}
|
||||
// if we don't have the key cached yet, ask
|
||||
// for it to the general crypto callbacks and cache it
|
||||
if (this._delegateCryptoCallbacks) {
|
||||
const result = await this._delegateCryptoCallbacks.
|
||||
getSecretStorageKey({keys}, name);
|
||||
if (result) {
|
||||
const [keyId, privateKey] = result;
|
||||
this._privateKeys.set(keyId, privateKey);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
addPrivateKey(keyId, privKey) {
|
||||
this._privateKeys.set(keyId, privKey);
|
||||
}
|
||||
}
|
||||
+20
-4
@@ -36,9 +36,15 @@ function checkPayloadLength(payloadString) {
|
||||
// Note that even if we manage to do the encryption, the message send may fail,
|
||||
// because by the time we've wrapped the ciphertext in the event object, it may
|
||||
// exceed 65K. But at least we won't just fail with "abort()" in that case.
|
||||
throw new Error("Message too long (" + payloadString.length + " bytes). " +
|
||||
const err = new Error("Message too long (" + payloadString.length + " bytes). " +
|
||||
"The maximum for an encrypted message is " +
|
||||
MAX_PLAINTEXT_LENGTH + " bytes.");
|
||||
// TODO: [TypeScript] We should have our own error types
|
||||
err.data = {
|
||||
errcode: "M_TOO_LARGE",
|
||||
error: "Payload too large for encrypted message",
|
||||
};
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -105,6 +111,9 @@ export function OlmDevice(cryptoStore) {
|
||||
// Keep track of sessions that we're starting, so that we don't start
|
||||
// multiple sessions for the same device at the same time.
|
||||
this._sessionsInProgress = {};
|
||||
|
||||
// Used by olm to serialise prekey message decryptions
|
||||
this._olmPrekeyPromise = Promise.resolve();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -983,11 +992,12 @@ OlmDevice.prototype._getInboundGroupSession = function(
|
||||
* @param {Object<string, string>} keysClaimed Other keys the sender claims.
|
||||
* @param {boolean} exportFormat true if the megolm keys are in export format
|
||||
* (ie, they lack an ed25519 signature)
|
||||
* @param {Object} [extraSessionData={}] any other data to be include with the session
|
||||
*/
|
||||
OlmDevice.prototype.addInboundGroupSession = async function(
|
||||
roomId, senderKey, forwardingCurve25519KeyChain,
|
||||
sessionId, sessionKey, keysClaimed,
|
||||
exportFormat,
|
||||
exportFormat, extraSessionData = {},
|
||||
) {
|
||||
await this._cryptoStore.doTxn(
|
||||
'readwrite', [
|
||||
@@ -1029,12 +1039,17 @@ OlmDevice.prototype.addInboundGroupSession = async function(
|
||||
}
|
||||
}
|
||||
|
||||
const sessionData = {
|
||||
logger.info(
|
||||
"Storing megolm session " + senderKey + "/" + sessionId +
|
||||
" with first index " + session.first_known_index(),
|
||||
);
|
||||
|
||||
const sessionData = Object.assign({}, extraSessionData, {
|
||||
room_id: roomId,
|
||||
session: session.pickle(this._pickleKey),
|
||||
keysClaimed: keysClaimed,
|
||||
forwardingCurve25519KeyChain: forwardingCurve25519KeyChain,
|
||||
};
|
||||
});
|
||||
|
||||
this._cryptoStore.storeEndToEndInboundGroupSession(
|
||||
senderKey, sessionId, sessionData, txn,
|
||||
@@ -1210,6 +1225,7 @@ OlmDevice.prototype.decryptGroupMessage = async function(
|
||||
forwardingCurve25519KeyChain: (
|
||||
sessionData.forwardingCurve25519KeyChain || []
|
||||
),
|
||||
untrusted: sessionData.untrusted,
|
||||
};
|
||||
},
|
||||
);
|
||||
|
||||
@@ -97,10 +97,6 @@ export class OutgoingRoomKeyRequestManager {
|
||||
*/
|
||||
start() {
|
||||
this._clientRunning = true;
|
||||
|
||||
// set the timer going, to handle any requests which didn't get sent
|
||||
// on the previous run of the client.
|
||||
this._startTimer();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -113,7 +109,14 @@ export class OutgoingRoomKeyRequestManager {
|
||||
}
|
||||
|
||||
/**
|
||||
* Send off a room key request, if we haven't already done so.
|
||||
* Send any requests that have been queued
|
||||
*/
|
||||
sendQueuedRequests() {
|
||||
this._startTimer();
|
||||
}
|
||||
|
||||
/**
|
||||
* Queue up a room key request, if we haven't already queued or sent one.
|
||||
*
|
||||
* The `requestBody` is compared (with a deep-equality check) against
|
||||
* previous queued or sent requests and if it matches, no change is made.
|
||||
@@ -129,7 +132,7 @@ export class OutgoingRoomKeyRequestManager {
|
||||
* pending list (or we have established that a similar request already
|
||||
* exists)
|
||||
*/
|
||||
async sendRoomKeyRequest(requestBody, recipients, resend=false) {
|
||||
async queueRoomKeyRequest(requestBody, recipients, resend=false) {
|
||||
const req = await this._cryptoStore.getOutgoingRoomKeyRequest(
|
||||
requestBody,
|
||||
);
|
||||
@@ -184,7 +187,7 @@ export class OutgoingRoomKeyRequestManager {
|
||||
// in state ROOM_KEY_REQUEST_STATES.SENT, so we must have
|
||||
// raced with another tab to mark the request cancelled.
|
||||
// Try again, to make sure the request is resent.
|
||||
return await this.sendRoomKeyRequest(
|
||||
return await this.queueRoomKeyRequest(
|
||||
requestBody, recipients, resend,
|
||||
);
|
||||
}
|
||||
@@ -220,9 +223,6 @@ export class OutgoingRoomKeyRequestManager {
|
||||
throw new Error('unhandled state: ' + req.state);
|
||||
}
|
||||
}
|
||||
// some of the branches require the timer to be started. Just start it
|
||||
// all the time, because it doesn't hurt to start it.
|
||||
this._startTimer();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -332,14 +332,14 @@ export class OutgoingRoomKeyRequestManager {
|
||||
* This is intended for situations where something substantial has changed, and we
|
||||
* don't really expect the other end to even care about the cancellation.
|
||||
* For example, after initialization or self-verification.
|
||||
* @return {Promise} An array of `sendRoomKeyRequest` outputs.
|
||||
* @return {Promise} An array of `queueRoomKeyRequest` outputs.
|
||||
*/
|
||||
async cancelAndResendAllOutgoingRequests() {
|
||||
const outgoings = await this._cryptoStore.getAllOutgoingRoomKeyRequestsByState(
|
||||
ROOM_KEY_REQUEST_STATES.SENT,
|
||||
);
|
||||
return Promise.all(outgoings.map(({ requestBody, recipients }) =>
|
||||
this.sendRoomKeyRequest(requestBody, recipients, true)));
|
||||
this.queueRoomKeyRequest(requestBody, recipients, true)));
|
||||
}
|
||||
|
||||
// start the background timer to send queued requests, if the timer isn't
|
||||
@@ -381,15 +381,12 @@ export class OutgoingRoomKeyRequestManager {
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
logger.log("Looking for queued outgoing room key requests");
|
||||
|
||||
return this._cryptoStore.getOutgoingRoomKeyRequestByState([
|
||||
ROOM_KEY_REQUEST_STATES.CANCELLATION_PENDING,
|
||||
ROOM_KEY_REQUEST_STATES.CANCELLATION_PENDING_AND_WILL_RESEND,
|
||||
ROOM_KEY_REQUEST_STATES.UNSENT,
|
||||
]).then((req) => {
|
||||
if (!req) {
|
||||
logger.log("No more outgoing room key requests");
|
||||
this._sendOutgoingRoomKeyRequestsTimer = null;
|
||||
return;
|
||||
}
|
||||
@@ -413,7 +410,6 @@ export class OutgoingRoomKeyRequestManager {
|
||||
}).catch((e) => {
|
||||
logger.error("Error sending room key request; will retry later.", e);
|
||||
this._sendOutgoingRoomKeyRequestsTimer = null;
|
||||
this._startTimer();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
+37
-173
@@ -17,16 +17,12 @@ limitations under the License.
|
||||
import {EventEmitter} from 'events';
|
||||
import {logger} from '../logger';
|
||||
import * as olmlib from './olmlib';
|
||||
import {pkVerify} from './olmlib';
|
||||
import {randomString} from '../randomstring';
|
||||
import {encryptAES, decryptAES} from './aes';
|
||||
import {encodeBase64} from "./olmlib";
|
||||
|
||||
export const SECRET_STORAGE_ALGORITHM_V1_AES
|
||||
= "m.secret_storage.v1.aes-hmac-sha2";
|
||||
// don't use curve25519 for writing data.
|
||||
export const SECRET_STORAGE_ALGORITHM_V1_CURVE25519
|
||||
= "m.secret_storage.v1.curve25519-aes-sha2";
|
||||
|
||||
const ZERO_STR = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
|
||||
|
||||
@@ -35,11 +31,10 @@ const ZERO_STR = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0
|
||||
* @module crypto/SecretStorage
|
||||
*/
|
||||
export class SecretStorage extends EventEmitter {
|
||||
constructor(baseApis, cryptoCallbacks, crossSigningInfo) {
|
||||
constructor(baseApis, cryptoCallbacks) {
|
||||
super();
|
||||
this._baseApis = baseApis;
|
||||
this._cryptoCallbacks = cryptoCallbacks;
|
||||
this._crossSigningInfo = crossSigningInfo;
|
||||
this._requests = {};
|
||||
this._incomingRequests = {};
|
||||
}
|
||||
@@ -53,7 +48,7 @@ export class SecretStorage extends EventEmitter {
|
||||
}
|
||||
|
||||
setDefaultKeyId(keyId) {
|
||||
return new Promise((resolve) => {
|
||||
return new Promise(async (resolve, reject) => {
|
||||
const listener = (ev) => {
|
||||
if (
|
||||
ev.getType() === 'm.secret_storage.default_key' &&
|
||||
@@ -65,10 +60,15 @@ export class SecretStorage extends EventEmitter {
|
||||
};
|
||||
this._baseApis.on('accountData', listener);
|
||||
|
||||
this._baseApis.setAccountData(
|
||||
'm.secret_storage.default_key',
|
||||
{ key: keyId },
|
||||
);
|
||||
try {
|
||||
await this._baseApis.setAccountData(
|
||||
'm.secret_storage.default_key',
|
||||
{ key: keyId },
|
||||
);
|
||||
} catch (e) {
|
||||
this._baseApis.removeListener('accountData', listener);
|
||||
reject(e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -92,9 +92,7 @@ export class SecretStorage extends EventEmitter {
|
||||
keyData.name = opts.name;
|
||||
}
|
||||
|
||||
switch (algorithm) {
|
||||
case SECRET_STORAGE_ALGORITHM_V1_AES:
|
||||
{
|
||||
if (algorithm === SECRET_STORAGE_ALGORITHM_V1_AES) {
|
||||
if (opts.passphrase) {
|
||||
keyData.passphrase = opts.passphrase;
|
||||
}
|
||||
@@ -103,9 +101,7 @@ export class SecretStorage extends EventEmitter {
|
||||
keyData.iv = iv;
|
||||
keyData.mac = mac;
|
||||
}
|
||||
break;
|
||||
}
|
||||
default:
|
||||
} else {
|
||||
throw new Error(`Unknown key algorithm ${opts.algorithm}`);
|
||||
}
|
||||
|
||||
@@ -119,8 +115,6 @@ export class SecretStorage extends EventEmitter {
|
||||
);
|
||||
}
|
||||
|
||||
await this._crossSigningInfo.signObject(keyData, 'master');
|
||||
|
||||
await this._baseApis.setAccountData(
|
||||
`m.secret_storage.key.${keyId}`, keyData,
|
||||
);
|
||||
@@ -128,33 +122,6 @@ export class SecretStorage extends EventEmitter {
|
||||
return keyId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Signs a given secret storage key with the cross-signing master key.
|
||||
*
|
||||
* @param {string} [keyId = default key's ID] The ID of the key to sign.
|
||||
* Defaults to the default key ID if not provided.
|
||||
*/
|
||||
async signKey(keyId) {
|
||||
if (!keyId) {
|
||||
keyId = await this.getDefaultKeyId();
|
||||
}
|
||||
if (!keyId) {
|
||||
throw new Error("signKey requires a key ID");
|
||||
}
|
||||
|
||||
const keyInfo = await this._baseApis.getAccountDataFromServer(
|
||||
`m.secret_storage.key.${keyId}`,
|
||||
);
|
||||
if (!keyInfo) {
|
||||
throw new Error(`Key ${keyId} does not exist in account data`);
|
||||
}
|
||||
|
||||
await this._crossSigningInfo.signObject(keyInfo, 'master');
|
||||
await this._baseApis.setAccountData(
|
||||
`m.secret_storage.key.${keyId}`, keyInfo,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the key information for a given ID.
|
||||
*
|
||||
@@ -188,15 +155,6 @@ export class SecretStorage extends EventEmitter {
|
||||
return !!(await this.getKey(keyId));
|
||||
}
|
||||
|
||||
async keyNeedsUpgrade(keyId) {
|
||||
const keyInfo = await this.getKey(keyId);
|
||||
if (keyInfo && keyInfo[1].algorithm === SECRET_STORAGE_ALGORITHM_V1_CURVE25519) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether a key matches what we expect based on the key info
|
||||
*
|
||||
@@ -206,32 +164,15 @@ export class SecretStorage extends EventEmitter {
|
||||
* @return {boolean} whether or not the key matches
|
||||
*/
|
||||
async checkKey(key, info) {
|
||||
switch (info.algorithm) {
|
||||
case SECRET_STORAGE_ALGORITHM_V1_AES:
|
||||
{
|
||||
if (info.algorithm === SECRET_STORAGE_ALGORITHM_V1_AES) {
|
||||
if (info.mac) {
|
||||
const {mac} = await SecretStorage._calculateKeyCheck(key, info.iv);
|
||||
return info.mac === mac;
|
||||
return info.mac.replace(/=+$/g, '') === mac.replace(/=+$/g, '');
|
||||
} else {
|
||||
// if we have no information, we have to assume the key is right
|
||||
return true;
|
||||
}
|
||||
}
|
||||
case SECRET_STORAGE_ALGORITHM_V1_CURVE25519:
|
||||
{
|
||||
let decryption = null;
|
||||
try {
|
||||
decryption = new global.Olm.PkDecryption();
|
||||
const gotPubkey = decryption.init_with_private_key(key);
|
||||
// make sure it agrees with the given pubkey
|
||||
return gotPubkey === info.pubkey;
|
||||
} catch (e) {
|
||||
return false;
|
||||
} finally {
|
||||
if (decryption) decryption.free();
|
||||
}
|
||||
}
|
||||
default:
|
||||
} else {
|
||||
throw new Error("Unknown algorithm");
|
||||
}
|
||||
}
|
||||
@@ -273,15 +214,11 @@ export class SecretStorage extends EventEmitter {
|
||||
}
|
||||
|
||||
// encrypt secret, based on the algorithm
|
||||
switch (keyInfo.algorithm) {
|
||||
case SECRET_STORAGE_ALGORITHM_V1_AES:
|
||||
{
|
||||
if (keyInfo.algorithm === SECRET_STORAGE_ALGORITHM_V1_AES) {
|
||||
const keys = {[keyId]: keyInfo};
|
||||
const [, encryption] = await this._getSecretStorageKey(keys, name);
|
||||
encrypted[keyId] = await encryption.encrypt(secret);
|
||||
break;
|
||||
}
|
||||
default:
|
||||
} else {
|
||||
logger.warn("unknown algorithm for secret storage key " + keyId
|
||||
+ ": " + keyInfo.algorithm);
|
||||
// do nothing if we don't understand the encryption algorithm
|
||||
@@ -347,27 +284,19 @@ export class SecretStorage extends EventEmitter {
|
||||
"m.secret_storage.key." + keyId,
|
||||
);
|
||||
const encInfo = secretInfo.encrypted[keyId];
|
||||
switch (keyInfo.algorithm) {
|
||||
case SECRET_STORAGE_ALGORITHM_V1_AES:
|
||||
// only use keys we understand the encryption algorithm of
|
||||
if (keyInfo.algorithm === SECRET_STORAGE_ALGORITHM_V1_AES) {
|
||||
if (encInfo.iv && encInfo.ciphertext && encInfo.mac) {
|
||||
keys[keyId] = keyInfo;
|
||||
}
|
||||
break;
|
||||
case SECRET_STORAGE_ALGORITHM_V1_CURVE25519:
|
||||
if (
|
||||
keyInfo.pubkey && (
|
||||
(encInfo.ciphertext && encInfo.mac && encInfo.ephemeral) ||
|
||||
encInfo.passthrough
|
||||
)
|
||||
) {
|
||||
keys[keyId] = keyInfo;
|
||||
}
|
||||
break;
|
||||
default:
|
||||
// do nothing if we don't understand the encryption algorithm
|
||||
}
|
||||
}
|
||||
|
||||
if (Object.keys(keys).length === 0) {
|
||||
throw new Error(`Could not decrypt ${name} because none of ` +
|
||||
`the keys it is encrypted with are for a supported algorithm`);
|
||||
}
|
||||
|
||||
let keyId;
|
||||
let decryption;
|
||||
try {
|
||||
@@ -413,8 +342,7 @@ export class SecretStorage extends EventEmitter {
|
||||
|
||||
const ret = {};
|
||||
|
||||
// check if secret is encrypted by a known/trusted secret and
|
||||
// encryption looks sane
|
||||
// filter secret encryption keys with supported algorithm
|
||||
for (const keyId of Object.keys(secretInfo.encrypted)) {
|
||||
// get key information from key storage
|
||||
const keyInfo = await this._baseApis.getAccountDataFromServer(
|
||||
@@ -423,49 +351,11 @@ export class SecretStorage extends EventEmitter {
|
||||
if (!keyInfo) continue;
|
||||
const encInfo = secretInfo.encrypted[keyId];
|
||||
|
||||
// We don't actually need the decryption object if it's a passthrough
|
||||
// since we just want to return the key itself.
|
||||
if (encInfo.passthrough) {
|
||||
try {
|
||||
pkVerify(
|
||||
keyInfo,
|
||||
this._crossSigningInfo.getId('master'),
|
||||
this._crossSigningInfo.userId,
|
||||
);
|
||||
} catch (e) {
|
||||
// not trusted, so move on to the next key
|
||||
continue;
|
||||
}
|
||||
ret[keyId] = keyInfo;
|
||||
continue;
|
||||
}
|
||||
|
||||
switch (keyInfo.algorithm) {
|
||||
case SECRET_STORAGE_ALGORITHM_V1_AES:
|
||||
// only use keys we understand the encryption algorithm of
|
||||
if (keyInfo.algorithm === SECRET_STORAGE_ALGORITHM_V1_AES) {
|
||||
if (encInfo.iv && encInfo.ciphertext && encInfo.mac) {
|
||||
ret[keyId] = keyInfo;
|
||||
}
|
||||
break;
|
||||
case SECRET_STORAGE_ALGORITHM_V1_CURVE25519:
|
||||
if (keyInfo.pubkey && encInfo.ciphertext && encInfo.mac
|
||||
&& encInfo.ephemeral) {
|
||||
if (checkKey) {
|
||||
try {
|
||||
pkVerify(
|
||||
keyInfo,
|
||||
this._crossSigningInfo.getId('master'),
|
||||
this._crossSigningInfo.userId,
|
||||
);
|
||||
} catch (e) {
|
||||
// not trusted, so move on to the next key
|
||||
continue;
|
||||
}
|
||||
}
|
||||
ret[keyId] = keyInfo;
|
||||
}
|
||||
break;
|
||||
default:
|
||||
// do nothing if we don't understand the encryption algorithm
|
||||
}
|
||||
}
|
||||
return Object.keys(ret).length ? ret : null;
|
||||
@@ -483,6 +373,7 @@ export class SecretStorage extends EventEmitter {
|
||||
const requestId = this._baseApis.makeTxnId();
|
||||
|
||||
const requestControl = this._requests[requestId] = {
|
||||
name,
|
||||
devices,
|
||||
};
|
||||
const promise = new Promise((resolve, reject) => {
|
||||
@@ -592,7 +483,7 @@ export class SecretStorage extends EventEmitter {
|
||||
this._baseApis,
|
||||
{
|
||||
[sender]: [
|
||||
await this._baseApis.getStoredDevice(sender, deviceId),
|
||||
this._baseApis.getStoredDevice(sender, deviceId),
|
||||
],
|
||||
},
|
||||
);
|
||||
@@ -602,7 +493,7 @@ export class SecretStorage extends EventEmitter {
|
||||
this._baseApis.deviceId,
|
||||
this._baseApis._crypto._olmDevice,
|
||||
sender,
|
||||
this._baseApis._crypto.getStoredDevice(sender, deviceId),
|
||||
this._baseApis.getStoredDevice(sender, deviceId),
|
||||
payload,
|
||||
);
|
||||
const contentMap = {
|
||||
@@ -646,6 +537,10 @@ export class SecretStorage extends EventEmitter {
|
||||
return;
|
||||
}
|
||||
|
||||
logger.log(
|
||||
`Successfully received secret ${requestControl.name} ` +
|
||||
`from ${deviceInfo.deviceId}`,
|
||||
);
|
||||
requestControl.resolve(content.secret);
|
||||
}
|
||||
}
|
||||
@@ -669,9 +564,7 @@ export class SecretStorage extends EventEmitter {
|
||||
throw new Error("App returned unknown key from getSecretStorageKey!");
|
||||
}
|
||||
|
||||
switch (keys[keyId].algorithm) {
|
||||
case SECRET_STORAGE_ALGORITHM_V1_AES:
|
||||
{
|
||||
if (keys[keyId].algorithm === SECRET_STORAGE_ALGORITHM_V1_AES) {
|
||||
const decryption = {
|
||||
encrypt: async function(secret) {
|
||||
return await encryptAES(secret, privateKey, name);
|
||||
@@ -681,36 +574,7 @@ export class SecretStorage extends EventEmitter {
|
||||
},
|
||||
};
|
||||
return [keyId, decryption];
|
||||
}
|
||||
case SECRET_STORAGE_ALGORITHM_V1_CURVE25519:
|
||||
{
|
||||
const pkDecryption = new global.Olm.PkDecryption();
|
||||
let pubkey;
|
||||
try {
|
||||
pubkey = pkDecryption.init_with_private_key(privateKey);
|
||||
} catch (e) {
|
||||
pkDecryption.free();
|
||||
throw new Error("getSecretStorageKey callback returned invalid key");
|
||||
}
|
||||
if (pubkey !== keys[keyId].pubkey) {
|
||||
pkDecryption.free();
|
||||
throw new Error(
|
||||
"getSecretStorageKey callback returned incorrect key",
|
||||
);
|
||||
}
|
||||
const decryption = {
|
||||
free: pkDecryption.free.bind(pkDecryption),
|
||||
decrypt: async function(encInfo) {
|
||||
return pkDecryption.decrypt(
|
||||
encInfo.ephemeral, encInfo.mac, encInfo.ciphertext,
|
||||
);
|
||||
},
|
||||
// needed for passthrough
|
||||
get_private_key: pkDecryption.get_private_key.bind(pkDecryption),
|
||||
};
|
||||
return [keyId, decryption];
|
||||
}
|
||||
default:
|
||||
} else {
|
||||
throw new Error("Unknown key type: " + keys[keyId].algorithm);
|
||||
}
|
||||
}
|
||||
|
||||
+2
-2
@@ -84,9 +84,9 @@ async function decryptNode(data, key, name) {
|
||||
const [aesKey, hmacKey] = deriveKeysNode(key, name);
|
||||
|
||||
const hmac = crypto.createHmac("sha256", hmacKey)
|
||||
.update(data.ciphertext, "base64").digest("base64");
|
||||
.update(data.ciphertext, "base64").digest("base64").replace(/=+$/g, '');
|
||||
|
||||
if (hmac !== data.mac) {
|
||||
if (hmac !== data.mac.replace(/=+$/g, '')) {
|
||||
throw new Error(`Error decrypting secret ${name}: bad MAC`);
|
||||
}
|
||||
|
||||
|
||||
@@ -311,7 +311,7 @@ MegolmEncryption.prototype._ensureOutboundSession = async function(
|
||||
}
|
||||
|
||||
await this._shareKeyWithDevices(
|
||||
session, key, payload, retryDevices, failedDevices,
|
||||
session, key, payload, retryDevices, failedDevices, 30000,
|
||||
);
|
||||
|
||||
await this._notifyFailedOlmDevices(session, key, failedDevices);
|
||||
@@ -521,6 +521,33 @@ MegolmEncryption.prototype._encryptAndSendKeysToDevices = function(
|
||||
}
|
||||
|
||||
return Promise.all(promises).then(() => {
|
||||
// prune out any devices that encryptMessageForDevice could not encrypt for,
|
||||
// in which case it will have just not added anything to the ciphertext object.
|
||||
// There's no point sending messages to devices if we couldn't encrypt to them,
|
||||
// since that's effectively a blank message.
|
||||
for (const userId of Object.keys(contentMap)) {
|
||||
for (const deviceId of Object.keys(contentMap[userId])) {
|
||||
if (Object.keys(contentMap[userId][deviceId].ciphertext).length === 0) {
|
||||
logger.log(
|
||||
"No ciphertext for device " +
|
||||
userId + ":" + deviceId + ": pruning",
|
||||
);
|
||||
delete contentMap[userId][deviceId];
|
||||
}
|
||||
}
|
||||
// No devices left for that user? Strip that too.
|
||||
if (Object.keys(contentMap[userId]).length === 0) {
|
||||
logger.log("Pruned all devices for user " + userId);
|
||||
delete contentMap[userId];
|
||||
}
|
||||
}
|
||||
|
||||
// Is there anything left?
|
||||
if (Object.keys(contentMap).length === 0) {
|
||||
logger.log("No users left to send to: aborting");
|
||||
return;
|
||||
}
|
||||
|
||||
return this._baseApis.sendToDevice("m.room.encrypted", contentMap).then(() => {
|
||||
// store that we successfully uploaded the keys of the current slice
|
||||
for (const userId of Object.keys(contentMap)) {
|
||||
@@ -988,7 +1015,7 @@ MegolmEncryption.prototype._getDevicesInRoom = async function(room) {
|
||||
// with them, which means that they will have announced any new devices via
|
||||
// device_lists in their /sync response. This cache should then be maintained
|
||||
// using all the device_lists changes and left fields.
|
||||
// See https://github.com/vector-im/riot-web/issues/2305 for details.
|
||||
// See https://github.com/vector-im/element-web/issues/2305 for details.
|
||||
const devices = await this._crypto.downloadKeys(roomMembers, false);
|
||||
const blocked = {};
|
||||
// remove any blocked devices
|
||||
@@ -1082,7 +1109,7 @@ MegolmDecryption.prototype.decryptEvent = async function(event) {
|
||||
//
|
||||
// then, if the key turns up while decryption is in progress (and
|
||||
// decryption fails), we will schedule a retry.
|
||||
// (fixes https://github.com/vector-im/riot-web/issues/5001)
|
||||
// (fixes https://github.com/vector-im/element-web/issues/5001)
|
||||
this._addEventToPendingList(event);
|
||||
|
||||
let res;
|
||||
@@ -1174,6 +1201,7 @@ MegolmDecryption.prototype.decryptEvent = async function(event) {
|
||||
senderCurve25519Key: res.senderKey,
|
||||
claimedEd25519Key: res.keysClaimed.ed25519,
|
||||
forwardingCurve25519KeyChain: res.forwardingCurve25519KeyChain,
|
||||
untrusted: res.untrusted,
|
||||
};
|
||||
};
|
||||
|
||||
@@ -1296,7 +1324,6 @@ MegolmDecryption.prototype.onRoomKeyEvent = function(event) {
|
||||
keysClaimed = event.getKeysClaimed();
|
||||
}
|
||||
|
||||
logger.log(`Received and adding key for megolm session ${senderKey}|${sessionId}`);
|
||||
return this._olmDevice.addInboundGroupSession(
|
||||
content.room_id, senderKey, forwardingKeyChain, sessionId,
|
||||
content.session_key, keysClaimed,
|
||||
@@ -1522,8 +1549,11 @@ MegolmDecryption.prototype._buildKeyForwardingMessage = async function(
|
||||
* @inheritdoc
|
||||
*
|
||||
* @param {module:crypto/OlmDevice.MegolmSessionData} session
|
||||
* @param {object} [opts={}] options for the import
|
||||
* @param {boolean} [opts.untrusted] whether the key should be considered as untrusted
|
||||
* @param {string} [opts.source] where the key came from
|
||||
*/
|
||||
MegolmDecryption.prototype.importRoomKey = function(session) {
|
||||
MegolmDecryption.prototype.importRoomKey = function(session, opts = {}) {
|
||||
return this._olmDevice.addInboundGroupSession(
|
||||
session.room_id,
|
||||
session.sender_key,
|
||||
@@ -1532,8 +1562,9 @@ MegolmDecryption.prototype.importRoomKey = function(session) {
|
||||
session.session_key,
|
||||
session.sender_claimed_keys,
|
||||
true,
|
||||
opts.untrusted ? { untrusted: opts.untrusted } : {},
|
||||
).then(() => {
|
||||
if (this._crypto.backupInfo) {
|
||||
if (this._crypto.backupInfo && opts.source !== "backup") {
|
||||
// don't wait for it to complete
|
||||
this._crypto.backupGroupSession(
|
||||
session.room_id,
|
||||
@@ -1555,7 +1586,8 @@ MegolmDecryption.prototype.importRoomKey = function(session) {
|
||||
};
|
||||
|
||||
/**
|
||||
* Have another go at decrypting events after we receive a key
|
||||
* Have another go at decrypting events after we receive a key. Resolves once
|
||||
* decryption has been re-attempted on all events.
|
||||
*
|
||||
* @private
|
||||
* @param {String} senderKey
|
||||
@@ -1574,21 +1606,17 @@ MegolmDecryption.prototype._retryDecryption = async function(senderKey, sessionI
|
||||
return true;
|
||||
}
|
||||
|
||||
pending.delete(sessionId);
|
||||
if (pending.size === 0) {
|
||||
this._pendingEvents[senderKey];
|
||||
}
|
||||
logger.debug("Retrying decryption on events", [...pending]);
|
||||
|
||||
await Promise.all([...pending].map(async (ev) => {
|
||||
try {
|
||||
await ev.attemptDecryption(this._crypto);
|
||||
await ev.attemptDecryption(this._crypto, true);
|
||||
} catch (e) {
|
||||
// don't die if something goes wrong
|
||||
}
|
||||
}));
|
||||
|
||||
// ev.attemptDecryption will re-add to this._pendingEvents if an event
|
||||
// couldn't be decrypted
|
||||
// If decrypted successfully, they'll have been removed from _pendingEvents
|
||||
return !((this._pendingEvents[senderKey] || {})[sessionId]);
|
||||
};
|
||||
|
||||
|
||||
@@ -264,6 +264,25 @@ OlmDecryption.prototype.decryptEvent = async function(event) {
|
||||
*/
|
||||
OlmDecryption.prototype._decryptMessage = async function(
|
||||
theirDeviceIdentityKey, message,
|
||||
) {
|
||||
// This is a wrapper that serialises decryptions of prekey messages, because
|
||||
// otherwise we race between deciding we have no active sessions for the message
|
||||
// and creating a new one, which we can only do once because it removes the OTK.
|
||||
if (message.type !== 0) {
|
||||
// not a prekey message: we can safely just try & decrypt it
|
||||
return this._reallyDecryptMessage(theirDeviceIdentityKey, message);
|
||||
} else {
|
||||
const myPromise = this._olmDevice._olmPrekeyPromise.then(() => {
|
||||
return this._reallyDecryptMessage(theirDeviceIdentityKey, message);
|
||||
});
|
||||
// we want the error, but don't propagate it to the next decryption
|
||||
this._olmDevice._olmPrekeyPromise = myPromise.catch(() => {});
|
||||
return await myPromise;
|
||||
}
|
||||
};
|
||||
|
||||
OlmDecryption.prototype._reallyDecryptMessage = async function(
|
||||
theirDeviceIdentityKey, message,
|
||||
) {
|
||||
const sessionIds = await this._olmDevice.getSessionIdsForDevice(
|
||||
theirDeviceIdentityKey,
|
||||
|
||||
+414
-343
File diff suppressed because it is too large
Load Diff
@@ -207,6 +207,25 @@ export async function ensureOlmSessionsForDevices(
|
||||
for (const deviceInfo of devices) {
|
||||
const deviceId = deviceInfo.deviceId;
|
||||
const key = deviceInfo.getIdentityKey();
|
||||
|
||||
if (key === olmDevice.deviceCurve25519Key) {
|
||||
// We should never be trying to start a session with ourself.
|
||||
// Apart from talking to yourself being the first sign of madness,
|
||||
// olm sessions can't do this because they get confused when
|
||||
// they get a message and see that the 'other side' has started a
|
||||
// new chain when this side has an active sender chain.
|
||||
// If you see this message being logged in the wild, we should find
|
||||
// the thing that is trying to send Olm messages to itself and fix it.
|
||||
logger.info("Attempted to start session with ourself! Ignoring");
|
||||
// We must fill in the section in the return value though, as callers
|
||||
// expect it to be there.
|
||||
result[userId][deviceId] = {
|
||||
device: deviceInfo,
|
||||
sessionId: null,
|
||||
};
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!olmDevice._sessionsInProgress[key]) {
|
||||
// pre-emptively mark the session as in-progress to avoid race
|
||||
// conditions. If we find that we already have a session, then
|
||||
@@ -238,6 +257,11 @@ export async function ensureOlmSessionsForDevices(
|
||||
delete resolveSession[key];
|
||||
}
|
||||
if (sessionId === null || force) {
|
||||
if (force) {
|
||||
logger.info("Forcing new Olm session for " + userId + ":" + deviceId);
|
||||
} else {
|
||||
logger.info("Making new Olm session for " + userId + ":" + deviceId);
|
||||
}
|
||||
devicesWithoutSession.push([userId, deviceId]);
|
||||
}
|
||||
result[userId][deviceId] = {
|
||||
@@ -277,6 +301,14 @@ export async function ensureOlmSessionsForDevices(
|
||||
const deviceInfo = devices[j];
|
||||
const deviceId = deviceInfo.deviceId;
|
||||
const key = deviceInfo.getIdentityKey();
|
||||
|
||||
if (key === olmDevice.deviceCurve25519Key) {
|
||||
// We've already logged about this above. Skip here too
|
||||
// otherwise we'll log saying there are no one-time keys
|
||||
// which will be confusing.
|
||||
continue;
|
||||
}
|
||||
|
||||
if (result[userId][deviceId].sessionId && !force) {
|
||||
// we already have a result for this device
|
||||
continue;
|
||||
|
||||
@@ -131,7 +131,7 @@ export class Backend {
|
||||
|
||||
cursorReq.onsuccess = (ev) => {
|
||||
const cursor = ev.target.result;
|
||||
if(!cursor) {
|
||||
if (!cursor) {
|
||||
// no match found
|
||||
callback(null);
|
||||
return;
|
||||
|
||||
@@ -369,7 +369,7 @@ export class LocalStorageCryptoStore extends MemoryCryptoStore {
|
||||
|
||||
getSecretStorePrivateKey(txn, func, type) {
|
||||
const key = getJsonItem(this.store, E2E_PREFIX + `ssss_cache.${type}`);
|
||||
func(key ? Uint8Array.from(key) : key);
|
||||
func(key);
|
||||
}
|
||||
|
||||
storeCrossSigningKeys(txn, keys) {
|
||||
@@ -380,7 +380,7 @@ export class LocalStorageCryptoStore extends MemoryCryptoStore {
|
||||
|
||||
storeSecretStorePrivateKey(txn, type, key) {
|
||||
setJsonItem(
|
||||
this.store, E2E_PREFIX + `ssss_cache.${type}`, Array.from(key),
|
||||
this.store, E2E_PREFIX + `ssss_cache.${type}`, key,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -25,8 +25,7 @@ import {EventEmitter} from 'events';
|
||||
import {logger} from '../../logger';
|
||||
import {DeviceInfo} from '../deviceinfo';
|
||||
import {newTimeoutError} from "./Error";
|
||||
import {CrossSigningInfo} from "../CrossSigning";
|
||||
import {decodeBase64} from "../olmlib";
|
||||
import {requestKeysDuringVerification} from "../CrossSigning";
|
||||
|
||||
const timeoutException = new Error("Verification timed out");
|
||||
|
||||
@@ -79,8 +78,6 @@ export class VerificationBase extends EventEmitter {
|
||||
this._transactionTimeoutTimer = null;
|
||||
}
|
||||
|
||||
static keyRequestTimeoutMs = 1000 * 60;
|
||||
|
||||
get initiatedByMe() {
|
||||
// if there is no start event yet,
|
||||
// we probably want to send it,
|
||||
@@ -122,6 +119,11 @@ export class VerificationBase extends EventEmitter {
|
||||
if (this._done) {
|
||||
return Promise.reject(new Error("Verification is already done"));
|
||||
}
|
||||
const existingEvent = this.request.getEventFromOtherParty(type);
|
||||
if (existingEvent) {
|
||||
return Promise.resolve(existingEvent);
|
||||
}
|
||||
|
||||
this._expectedEvent = type;
|
||||
return new Promise((resolve, reject) => {
|
||||
this._resolveEvent = resolve;
|
||||
@@ -193,93 +195,7 @@ export class VerificationBase extends EventEmitter {
|
||||
if (!this._done) {
|
||||
this.request.onVerifierFinished();
|
||||
this._resolve();
|
||||
|
||||
//#region Cross-signing keys request
|
||||
// If this is a self-verification, ask the other party for keys
|
||||
if (this._baseApis.getUserId() !== this.userId) {
|
||||
return;
|
||||
}
|
||||
// FIXME: This is a lot of logic that isn't anything to do with verification
|
||||
// and probably ought to be somewhere else.
|
||||
console.log("VerificationBase.done: Self-verification done; requesting keys");
|
||||
/* This happens asynchronously, and we're not concerned about
|
||||
* waiting for it. We return here in order to test. */
|
||||
return new Promise((resolve, reject) => {
|
||||
const client = this._baseApis;
|
||||
const original = client._crypto._crossSigningInfo;
|
||||
|
||||
/* We already have all of the infrastructure we need to validate and
|
||||
* cache cross-signing keys, so instead of replicating that, here we
|
||||
* set up callbacks that request them from the other device and call
|
||||
* CrossSigningInfo.getCrossSigningKey() to validate/cache */
|
||||
const crossSigning = new CrossSigningInfo(
|
||||
original.userId,
|
||||
{ getCrossSigningKey: async (type) => {
|
||||
console.debug("VerificationBase.done: requesting secret",
|
||||
type, this.deviceId);
|
||||
const { promise } = client.requestSecret(
|
||||
`m.cross_signing.${type}`, [this.deviceId],
|
||||
);
|
||||
const result = await promise;
|
||||
const decoded = decodeBase64(result);
|
||||
return Uint8Array.from(decoded);
|
||||
} },
|
||||
original._cacheCallbacks,
|
||||
);
|
||||
crossSigning.keys = original.keys;
|
||||
|
||||
// XXX: get all keys out if we get one key out
|
||||
// https://github.com/vector-im/riot-web/issues/12604
|
||||
// then change here to reject on the timeout
|
||||
/* Requests can be ignored, so don't wait around forever */
|
||||
const timeout = new Promise((resolve, reject) => {
|
||||
setTimeout(
|
||||
resolve,
|
||||
VerificationBase.keyRequestTimeoutMs,
|
||||
new Error("Timeout"),
|
||||
);
|
||||
});
|
||||
|
||||
// also request and cache the key backup key
|
||||
const backupKeyPromise = new Promise(async resolve => {
|
||||
const cachedKey = await client._crypto.getSessionBackupPrivateKey();
|
||||
if (!cachedKey) {
|
||||
logger.info("No cached backup key found. Requesting...");
|
||||
const secretReq = client.requestSecret(
|
||||
'm.megolm_backup.v1', [this.deviceId],
|
||||
);
|
||||
const base64Key = await secretReq.promise;
|
||||
logger.info("Got key backup key, decoding...");
|
||||
const decodedKey = decodeBase64(base64Key);
|
||||
logger.info("Decoded backup key, storing...");
|
||||
client._crypto.storeSessionBackupPrivateKey(
|
||||
Uint8Array.from(decodedKey),
|
||||
);
|
||||
logger.info("Backup key stored. Starting backup restore...");
|
||||
const backupInfo = await client.getKeyBackupVersion();
|
||||
// no need to await for this - just let it go in the bg
|
||||
client.restoreKeyBackupWithCache(
|
||||
undefined, undefined, backupInfo,
|
||||
).then(() => {
|
||||
logger.info("Backup restored.");
|
||||
});
|
||||
}
|
||||
resolve();
|
||||
});
|
||||
|
||||
/* We call getCrossSigningKey() for its side-effects */
|
||||
return Promise.race([
|
||||
Promise.all([
|
||||
crossSigning.getCrossSigningKey("self_signing"),
|
||||
crossSigning.getCrossSigningKey("user_signing"),
|
||||
backupKeyPromise,
|
||||
]),
|
||||
timeout,
|
||||
]).then(resolve, reject);
|
||||
}).catch((e) => {
|
||||
console.warn("VerificationBase: failure while requesting keys:", e);
|
||||
});
|
||||
//#endregion
|
||||
return requestKeysDuringVerification(this._baseApis, this.userId, this.deviceId);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -370,7 +286,7 @@ export class VerificationBase extends EventEmitter {
|
||||
|
||||
for (const [keyId, keyInfo] of Object.entries(keys)) {
|
||||
const deviceId = keyId.split(':', 2)[1];
|
||||
const device = await this._baseApis.getStoredDevice(userId, deviceId);
|
||||
const device = this._baseApis.getStoredDevice(userId, deviceId);
|
||||
if (device) {
|
||||
await verifier(keyId, device, keyInfo);
|
||||
verifiedDevices.push(deviceId);
|
||||
|
||||
@@ -207,7 +207,7 @@ export class QRCodeData {
|
||||
const myUserId = client.getUserId();
|
||||
const otherDevice = request.targetDevice;
|
||||
const otherDeviceId = otherDevice ? otherDevice.deviceId : null;
|
||||
const device = await client.getStoredDevice(myUserId, otherDeviceId);
|
||||
const device = client.getStoredDevice(myUserId, otherDeviceId);
|
||||
if (!device) {
|
||||
throw new Error("could not find device " + otherDeviceId);
|
||||
}
|
||||
|
||||
@@ -175,11 +175,33 @@ function calculateMAC(olmSAS, method) {
|
||||
};
|
||||
}
|
||||
|
||||
const calculateKeyAgreement = {
|
||||
"curve25519-hkdf-sha256": function(sas, olmSAS, bytes) {
|
||||
const ourInfo = `${sas._baseApis.getUserId()}|${sas._baseApis.deviceId}|`
|
||||
+ `${sas.ourSASPubKey}|`;
|
||||
const theirInfo = `${sas.userId}|${sas.deviceId}|${sas.theirSASPubKey}|`;
|
||||
const sasInfo =
|
||||
"MATRIX_KEY_VERIFICATION_SAS|"
|
||||
+ (sas.initiatedByMe ? ourInfo + theirInfo : theirInfo + ourInfo)
|
||||
+ sas._channel.transactionId;
|
||||
return olmSAS.generate_bytes(sasInfo, bytes);
|
||||
},
|
||||
"curve25519": function(sas, olmSAS, bytes) {
|
||||
const ourInfo = `${sas._baseApis.getUserId()}${sas._baseApis.deviceId}`;
|
||||
const theirInfo = `${sas.userId}${sas.deviceId}`;
|
||||
const sasInfo =
|
||||
"MATRIX_KEY_VERIFICATION_SAS"
|
||||
+ (sas.initiatedByMe ? ourInfo + theirInfo : theirInfo + ourInfo)
|
||||
+ sas._channel.transactionId;
|
||||
return olmSAS.generate_bytes(sasInfo, bytes);
|
||||
},
|
||||
};
|
||||
|
||||
/* lists of algorithms/methods that are supported. The key agreement, hashes,
|
||||
* and MAC lists should be sorted in order of preference (most preferred
|
||||
* first).
|
||||
*/
|
||||
const KEY_AGREEMENT_LIST = ["curve25519"];
|
||||
const KEY_AGREEMENT_LIST = ["curve25519-hkdf-sha256", "curve25519"];
|
||||
const HASHES_LIST = ["sha256"];
|
||||
const MAC_LIST = ["hkdf-hmac-sha256", "hmac-sha256"];
|
||||
const SAS_LIST = Object.keys(sasGenerators);
|
||||
@@ -291,12 +313,14 @@ export class SAS extends Base {
|
||||
if (typeof content.commitment !== "string") {
|
||||
throw newInvalidMessageError();
|
||||
}
|
||||
const keyAgreement = content.key_agreement_protocol;
|
||||
const macMethod = content.message_authentication_code;
|
||||
const hashCommitment = content.commitment;
|
||||
const olmSAS = new global.Olm.SAS();
|
||||
try {
|
||||
this.ourSASPubKey = olmSAS.get_pubkey();
|
||||
await this._send("m.key.verification.key", {
|
||||
key: olmSAS.get_pubkey(),
|
||||
key: this.ourSASPubKey,
|
||||
});
|
||||
|
||||
|
||||
@@ -308,13 +332,10 @@ export class SAS extends Base {
|
||||
if (olmutil.sha256(commitmentStr) !== hashCommitment) {
|
||||
throw newMismatchedCommitmentError();
|
||||
}
|
||||
this.theirSASPubKey = content.key;
|
||||
olmSAS.set_their_key(content.key);
|
||||
|
||||
const sasInfo = "MATRIX_KEY_VERIFICATION_SAS"
|
||||
+ this._baseApis.getUserId() + this._baseApis.deviceId
|
||||
+ this.userId + this.deviceId
|
||||
+ this._channel.transactionId;
|
||||
const sasBytes = olmSAS.generate_bytes(sasInfo, 6);
|
||||
const sasBytes = calculateKeyAgreement[keyAgreement](this, olmSAS, 6);
|
||||
const verifySAS = new Promise((resolve, reject) => {
|
||||
this.sasEvent = {
|
||||
sas: generateSas(sasBytes, sasMethods),
|
||||
@@ -394,16 +415,14 @@ export class SAS extends Base {
|
||||
let e = await this._waitForEvent("m.key.verification.key");
|
||||
// FIXME: make sure event is properly formed
|
||||
content = e.getContent();
|
||||
this.theirSASPubKey = content.key;
|
||||
olmSAS.set_their_key(content.key);
|
||||
this.ourSASPubKey = olmSAS.get_pubkey();
|
||||
await this._send("m.key.verification.key", {
|
||||
key: olmSAS.get_pubkey(),
|
||||
key: this.ourSASPubKey,
|
||||
});
|
||||
|
||||
const sasInfo = "MATRIX_KEY_VERIFICATION_SAS"
|
||||
+ this.userId + this.deviceId
|
||||
+ this._baseApis.getUserId() + this._baseApis.deviceId
|
||||
+ this._channel.transactionId;
|
||||
const sasBytes = olmSAS.generate_bytes(sasInfo, 6);
|
||||
const sasBytes = calculateKeyAgreement[keyAgreement](this, olmSAS, 6);
|
||||
const verifySAS = new Promise((resolve, reject) => {
|
||||
this.sasEvent = {
|
||||
sas: generateSas(sasBytes, sasMethods),
|
||||
@@ -411,7 +430,7 @@ export class SAS extends Base {
|
||||
try {
|
||||
await this._sendMAC(olmSAS, macMethod);
|
||||
resolve();
|
||||
} catch(err) {
|
||||
} catch (err) {
|
||||
reject(err);
|
||||
}
|
||||
},
|
||||
|
||||
@@ -356,4 +356,12 @@ export class ToDeviceRequests {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
getRequestsInProgress(userId) {
|
||||
const requestsByTxnId = this._requestsByUserId.get(userId);
|
||||
if (requestsByTxnId) {
|
||||
return Array.from(requestsByTxnId.values()).filter(r => r.pending);
|
||||
}
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,15 +25,17 @@ import {
|
||||
} from "../Error";
|
||||
import {QRCodeData, SCAN_QR_CODE_METHOD} from "../QRCode";
|
||||
|
||||
// the recommended amount of time before a verification request
|
||||
// should be (automatically) cancelled without user interaction
|
||||
// and ignored.
|
||||
const VERIFICATION_REQUEST_TIMEOUT = 10 * 60 * 1000; //10m
|
||||
// How long after the event's timestamp that the request times out
|
||||
const TIMEOUT_FROM_EVENT_TS = 10 * 60 * 1000; // 10 minutes
|
||||
|
||||
// How long after we receive the event that the request times out
|
||||
const TIMEOUT_FROM_EVENT_RECEIPT = 2 * 60 * 1000; // 2 minutes
|
||||
|
||||
// to avoid almost expired verification notifications
|
||||
// from showing a notification and almost immediately
|
||||
// disappearing, also ignore verification requests that
|
||||
// are this amount of time away from expiring.
|
||||
const VERIFICATION_REQUEST_MARGIN = 3 * 1000; //3s
|
||||
const VERIFICATION_REQUEST_MARGIN = 3 * 1000; // 3 seconds
|
||||
|
||||
|
||||
export const EVENT_PREFIX = "m.key.verification.";
|
||||
@@ -80,6 +82,9 @@ export class VerificationRequest extends EventEmitter {
|
||||
// cross-signing identity reset between the .ready and .start event
|
||||
// and signing the wrong key after .start
|
||||
this._qrCodeData = null;
|
||||
|
||||
// The timestamp when we received the request event from the other side
|
||||
this._requestReceivedAt = null;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -165,12 +170,26 @@ export class VerificationRequest extends EventEmitter {
|
||||
return this._chosenMethod;
|
||||
}
|
||||
|
||||
calculateEventTimeout(event) {
|
||||
let effectiveExpiresAt = this.channel.getTimestamp(event)
|
||||
+ TIMEOUT_FROM_EVENT_TS;
|
||||
|
||||
if (this._requestReceivedAt && !this.initiatedByMe &&
|
||||
this.phase <= PHASE_REQUESTED
|
||||
) {
|
||||
const expiresAtByReceipt = this._requestReceivedAt
|
||||
+ TIMEOUT_FROM_EVENT_RECEIPT;
|
||||
effectiveExpiresAt = Math.min(effectiveExpiresAt, expiresAtByReceipt);
|
||||
}
|
||||
|
||||
return Math.max(0, effectiveExpiresAt - Date.now());
|
||||
}
|
||||
|
||||
/** The current remaining amount of ms before the request should be automatically cancelled */
|
||||
get timeout() {
|
||||
const requestEvent = this._getEventByEither(REQUEST_TYPE);
|
||||
if (requestEvent) {
|
||||
const elapsed = Date.now() - this.channel.getTimestamp(requestEvent);
|
||||
return Math.max(0, VERIFICATION_REQUEST_TIMEOUT - elapsed);
|
||||
return this.calculateEventTimeout(requestEvent);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -735,7 +754,7 @@ export class VerificationRequest extends EventEmitter {
|
||||
|
||||
_setupTimeout(phase) {
|
||||
const shouldTimeout = !this._timeoutTimer && !this.observeOnly &&
|
||||
phase === PHASE_REQUESTED && this.initiatedByMe;
|
||||
phase === PHASE_REQUESTED;
|
||||
|
||||
if (shouldTimeout) {
|
||||
this._timeoutTimer = setTimeout(this._cancelOnTimeout, this.timeout);
|
||||
@@ -754,7 +773,17 @@ export class VerificationRequest extends EventEmitter {
|
||||
|
||||
_cancelOnTimeout = () => {
|
||||
try {
|
||||
this.cancel({reason: "Other party didn't accept in time", code: "m.timeout"});
|
||||
if (this.initiatedByMe) {
|
||||
this.cancel({
|
||||
reason: "Other party didn't accept in time",
|
||||
code: "m.timeout",
|
||||
});
|
||||
} else {
|
||||
this.cancel({
|
||||
reason: "User didn't accept in time",
|
||||
code: "m.timeout",
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
logger.error("Error while cancelling verification request", err);
|
||||
}
|
||||
@@ -791,16 +820,8 @@ export class VerificationRequest extends EventEmitter {
|
||||
if (!isLiveEvent) {
|
||||
this._observeOnly = true;
|
||||
}
|
||||
// a timestamp is not provided on all to_device events
|
||||
const timestamp = this.channel.getTimestamp(event);
|
||||
if (Number.isFinite(timestamp)) {
|
||||
const elapsed = Date.now() - timestamp;
|
||||
// don't allow interaction on old requests
|
||||
if (elapsed > (VERIFICATION_REQUEST_TIMEOUT - VERIFICATION_REQUEST_MARGIN) ||
|
||||
elapsed < -(VERIFICATION_REQUEST_TIMEOUT / 2)
|
||||
) {
|
||||
this._observeOnly = true;
|
||||
}
|
||||
if (this.calculateEventTimeout(event) < VERIFICATION_REQUEST_MARGIN) {
|
||||
this._observeOnly = true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -819,6 +840,8 @@ export class VerificationRequest extends EventEmitter {
|
||||
this._eventsByThem.delete(type);
|
||||
}
|
||||
}
|
||||
// also remember when we received the request event
|
||||
this._requestReceivedAt = Date.now();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -877,4 +900,8 @@ export class VerificationRequest extends EventEmitter {
|
||||
this._setPhase(newTransitions[newTransitions.length - 1].phase);
|
||||
}
|
||||
}
|
||||
|
||||
getEventFromOtherParty(type) {
|
||||
return this._eventsByThem.get(type);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -108,8 +108,9 @@ FilterComponent.prototype._checkFields =
|
||||
}
|
||||
|
||||
const allowed_values = self[name];
|
||||
if (allowed_values) {
|
||||
if (!allowed_values.map(match_func)) {
|
||||
if (allowed_values && allowed_values.length > 0) {
|
||||
const anyMatch = allowed_values.some(match_func);
|
||||
if (!anyMatch) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
+5
-7
@@ -56,13 +56,6 @@ Filter.LAZY_LOADING_MESSAGES_FILTER = {
|
||||
lazy_load_members: true,
|
||||
};
|
||||
|
||||
Filter.LAZY_LOADING_SYNC_FILTER = {
|
||||
room: {
|
||||
state: Filter.LAZY_LOADING_MESSAGES_FILTER,
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Get the ID of this filter on your homeserver (if known)
|
||||
* @return {?Number} The filter ID
|
||||
@@ -96,6 +89,7 @@ Filter.prototype.setDefinition = function(definition) {
|
||||
// "state": {
|
||||
// "types": ["m.room.*"],
|
||||
// "not_rooms": ["!726s6s6q:example.com"],
|
||||
// "lazy_load_members": true,
|
||||
// },
|
||||
// "timeline": {
|
||||
// "limit": 10,
|
||||
@@ -177,6 +171,10 @@ Filter.prototype.setTimelineLimit = function(limit) {
|
||||
setProp(this.definition, "room.timeline.limit", limit);
|
||||
};
|
||||
|
||||
Filter.prototype.setLazyLoadMembers = function(enabled) {
|
||||
setProp(this.definition, "room.state.lazy_load_members", !!enabled);
|
||||
};
|
||||
|
||||
/**
|
||||
* Control whether left rooms should be included in responses.
|
||||
* @param {boolean} includeLeave True to make rooms the user has left appear
|
||||
|
||||
+87
-9
@@ -276,6 +276,9 @@ MatrixHttpApi.prototype = {
|
||||
callbacks.clearTimeout(xhr.timeout_timer);
|
||||
var resp;
|
||||
try {
|
||||
if (xhr.status === 0) {
|
||||
throw new AbortError();
|
||||
}
|
||||
if (!xhr.responseText) {
|
||||
throw new Error('No response body.');
|
||||
}
|
||||
@@ -789,6 +792,17 @@ const requestCallback = function(
|
||||
userDefinedCallback = userDefinedCallback || function() {};
|
||||
|
||||
return function(err, response, body) {
|
||||
if (err) {
|
||||
// the unit tests use matrix-mock-request, which throw the string "aborted" when aborting a request.
|
||||
// See https://github.com/matrix-org/matrix-mock-request/blob/3276d0263a561b5b8326b47bae720578a2c7473a/src/index.js#L48
|
||||
const aborted = err.name === "AbortError" || err === "aborted";
|
||||
if (!aborted && !(err instanceof MatrixError)) {
|
||||
// browser-request just throws normal Error objects,
|
||||
// not `TypeError`s like fetch does. So just assume any
|
||||
// error is due to the connection.
|
||||
err = new ConnectionError("request failed", err);
|
||||
}
|
||||
}
|
||||
if (!err) {
|
||||
try {
|
||||
if (response.statusCode >= 400) {
|
||||
@@ -876,7 +890,7 @@ function getResponseContentType(response) {
|
||||
|
||||
try {
|
||||
return parseContentType(contentType);
|
||||
} catch(e) {
|
||||
} catch (e) {
|
||||
throw new Error(`Error parsing Content-Type '${contentType}': ${e}`);
|
||||
}
|
||||
}
|
||||
@@ -892,12 +906,76 @@ function getResponseContentType(response) {
|
||||
* @prop {Object} data The raw Matrix error JSON used to construct this object.
|
||||
* @prop {integer} httpStatus The numeric HTTP status code given
|
||||
*/
|
||||
export function MatrixError(errorJson) {
|
||||
errorJson = errorJson || {};
|
||||
this.errcode = errorJson.errcode;
|
||||
this.name = errorJson.errcode || "Unknown error code";
|
||||
this.message = errorJson.error || "Unknown message";
|
||||
this.data = errorJson;
|
||||
export class MatrixError extends Error {
|
||||
constructor(errorJson) {
|
||||
errorJson = errorJson || {};
|
||||
super(`MatrixError: ${errorJson.errcode}`);
|
||||
this.errcode = errorJson.errcode;
|
||||
this.name = errorJson.errcode || "Unknown error code";
|
||||
this.message = errorJson.error || "Unknown message";
|
||||
this.data = errorJson;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Construct a ConnectionError. This is a JavaScript Error indicating
|
||||
* that a request failed because of some error with the connection, either
|
||||
* CORS was not correctly configured on the server, the server didn't response,
|
||||
* the request timed out, or the internet connection on the client side went down.
|
||||
* @constructor
|
||||
*/
|
||||
export class ConnectionError extends Error {
|
||||
constructor(message, cause = undefined) {
|
||||
super(message + (cause ? `: ${cause.message}` : ""));
|
||||
this._cause = cause;
|
||||
}
|
||||
|
||||
get name() {
|
||||
return "ConnectionError";
|
||||
}
|
||||
|
||||
get cause() {
|
||||
return this._cause;
|
||||
}
|
||||
}
|
||||
|
||||
export class AbortError extends Error {
|
||||
constructor() {
|
||||
super("Operation aborted");
|
||||
}
|
||||
|
||||
get name() {
|
||||
return "AbortError";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Retries a network operation run in a callback.
|
||||
* @param {number} maxAttempts maximum attempts to try
|
||||
* @param {Function} callback callback that returns a promise of the network operation. If rejected with ConnectionError, it will be retried by calling the callback again.
|
||||
* @return {any} the result of the network operation
|
||||
* @throws {ConnectionError} If after maxAttempts the callback still throws ConnectionError
|
||||
*/
|
||||
export async function retryNetworkOperation(maxAttempts, callback) {
|
||||
let attempts = 0;
|
||||
let lastConnectionError = null;
|
||||
while (attempts < maxAttempts) {
|
||||
try {
|
||||
if (attempts > 0) {
|
||||
const timeout = 1000 * Math.pow(2, attempts);
|
||||
console.log(`network operation failed ${attempts} times,` +
|
||||
` retrying in ${timeout}ms...`);
|
||||
await new Promise(r => setTimeout(r, timeout));
|
||||
}
|
||||
return await callback();
|
||||
} catch (err) {
|
||||
if (err instanceof ConnectionError) {
|
||||
attempts += 1;
|
||||
lastConnectionError = err;
|
||||
} else {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
}
|
||||
throw lastConnectionError;
|
||||
}
|
||||
MatrixError.prototype = Object.create(Error.prototype);
|
||||
MatrixError.prototype.constructor = MatrixError;
|
||||
|
||||
@@ -22,6 +22,7 @@ matrixcs.request(request);
|
||||
utils.runPolyfills();
|
||||
|
||||
try {
|
||||
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
||||
const crypto = require('crypto');
|
||||
utils.setCrypto(crypto);
|
||||
} catch (err) {
|
||||
|
||||
+35
-12
@@ -143,11 +143,19 @@ InteractiveAuth.prototype = {
|
||||
this._resolveFunc = resolve;
|
||||
this._rejectFunc = reject;
|
||||
|
||||
// if we have no flows, try a request (we'll have
|
||||
// just a session ID in _data if resuming)
|
||||
if (!this._data.flows) {
|
||||
const hasFlows = this._data && this._data.flows;
|
||||
|
||||
// if we have no flows, try a request to acquire the flows
|
||||
if (!hasFlows) {
|
||||
if (this._busyChangedCallback) this._busyChangedCallback(true);
|
||||
this._doRequest(this._data).finally(() => {
|
||||
// use the existing sessionid, if one is present.
|
||||
let auth = null;
|
||||
if (this._data.session) {
|
||||
auth = {
|
||||
session: this._data.session,
|
||||
};
|
||||
}
|
||||
this._doRequest(auth).finally(() => {
|
||||
if (this._busyChangedCallback) this._busyChangedCallback(false);
|
||||
});
|
||||
} else {
|
||||
@@ -186,7 +194,11 @@ InteractiveAuth.prototype = {
|
||||
}
|
||||
authDict = {
|
||||
type: EMAIL_STAGE_TYPE,
|
||||
// TODO: Remove `threepid_creds` once servers support proper UIA
|
||||
// See https://github.com/matrix-org/synapse/issues/5665
|
||||
// See https://github.com/matrix-org/matrix-doc/issues/2220
|
||||
threepid_creds: creds,
|
||||
threepidCreds: creds,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -264,11 +276,16 @@ InteractiveAuth.prototype = {
|
||||
}
|
||||
}
|
||||
|
||||
// use the sessionid from the last request.
|
||||
const auth = {
|
||||
session: this._data.session,
|
||||
};
|
||||
utils.extend(auth, authData);
|
||||
// use the sessionid from the last request, if one is present.
|
||||
let auth;
|
||||
if (this._data.session) {
|
||||
auth = {
|
||||
session: this._data.session,
|
||||
};
|
||||
utils.extend(auth, authData);
|
||||
} else {
|
||||
auth = authData;
|
||||
}
|
||||
|
||||
try {
|
||||
// NB. the 'background' flag is deprecated by the busyChanged
|
||||
@@ -325,7 +342,7 @@ InteractiveAuth.prototype = {
|
||||
} catch (error) {
|
||||
// sometimes UI auth errors don't come with flows
|
||||
const errorFlows = error.data ? error.data.flows : null;
|
||||
const haveFlows = Boolean(this._data.flows) || Boolean(errorFlows);
|
||||
const haveFlows = this._data.flows || Boolean(errorFlows);
|
||||
if (error.httpStatus !== 401 || !error.data || !haveFlows) {
|
||||
// doesn't look like an interactive-auth failure.
|
||||
if (!background) {
|
||||
@@ -351,7 +368,13 @@ InteractiveAuth.prototype = {
|
||||
error.data.session = this._data.session;
|
||||
}
|
||||
this._data = error.data;
|
||||
this._startNextAuthStage();
|
||||
try {
|
||||
this._startNextAuthStage();
|
||||
} catch (e) {
|
||||
this._rejectFunc(e);
|
||||
this._resolveFunc = null;
|
||||
this._rejectFunc = null;
|
||||
}
|
||||
|
||||
if (
|
||||
!this._emailSid &&
|
||||
@@ -414,7 +437,7 @@ InteractiveAuth.prototype = {
|
||||
return;
|
||||
}
|
||||
|
||||
if (this._data.errcode || this._data.error) {
|
||||
if (this._data && this._data.errcode || this._data.error) {
|
||||
this._stateUpdatedCallback(nextStage, {
|
||||
errcode: this._data.errcode || "",
|
||||
error: this._data.error || "",
|
||||
|
||||
@@ -16,8 +16,15 @@ See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
import type Request from "request";
|
||||
|
||||
import {MemoryCryptoStore} from "./crypto/store/memory-crypto-store";
|
||||
import {LocalStorageCryptoStore} from "./crypto/store/localStorage-crypto-store";
|
||||
import {IndexedDBCryptoStore} from "./crypto/store/indexeddb-crypto-store";
|
||||
import {MemoryStore} from "./store/memory";
|
||||
import {StubStore} from "./store/stub";
|
||||
import {LocalIndexedDBStoreBackend} from "./store/indexeddb-local-backend";
|
||||
import {RemoteIndexedDBStoreBackend} from "./store/indexeddb-remote-backend";
|
||||
import {MatrixScheduler} from "./scheduler";
|
||||
import {MatrixClient} from "./client";
|
||||
|
||||
@@ -89,6 +96,10 @@ export function wrapRequest(wrapper) {
|
||||
};
|
||||
}
|
||||
|
||||
type Store =
|
||||
StubStore | MemoryStore | LocalIndexedDBStoreBackend | RemoteIndexedDBStoreBackend;
|
||||
|
||||
type CryptoStore = MemoryCryptoStore | LocalStorageCryptoStore | IndexedDBCryptoStore;
|
||||
|
||||
let cryptoStoreFactory = () => new MemoryCryptoStore;
|
||||
|
||||
@@ -102,6 +113,15 @@ export function setCryptoStoreFactory(fac) {
|
||||
cryptoStoreFactory = fac;
|
||||
}
|
||||
|
||||
interface ICreateClientOpts {
|
||||
baseUrl: string;
|
||||
idBaseUrl?: string;
|
||||
store?: Store;
|
||||
cryptoStore?: CryptoStore;
|
||||
scheduler?: MatrixScheduler;
|
||||
request?: Request;
|
||||
}
|
||||
|
||||
/**
|
||||
* Construct a Matrix Client. Similar to {@link module:client.MatrixClient}
|
||||
* except that the 'request', 'store' and 'scheduler' dependencies are satisfied.
|
||||
@@ -125,10 +145,10 @@ export function setCryptoStoreFactory(fac) {
|
||||
* @see {@link module:client.MatrixClient} for the full list of options for
|
||||
* <code>opts</code>.
|
||||
*/
|
||||
export function createClient(opts) {
|
||||
export function createClient(opts: ICreateClientOpts | string) {
|
||||
if (typeof opts === "string") {
|
||||
opts = {
|
||||
"baseUrl": opts,
|
||||
"baseUrl": opts as string,
|
||||
};
|
||||
}
|
||||
opts.request = opts.request || requestInstance;
|
||||
@@ -167,7 +187,7 @@ export function createClient(opts) {
|
||||
* @param {requestCallback} callback The request callback.
|
||||
*/
|
||||
|
||||
/**
|
||||
/**
|
||||
* The request callback interface for performing HTTP requests. This matches the
|
||||
* API for the {@link https://github.com/request/request#requestoptions-callback|
|
||||
* request NPM module}. The SDK will implement a callback which meets this
|
||||
@@ -647,7 +647,8 @@ EventTimelineSet.prototype.compareEventOrdering = function(eventId1, eventId2) {
|
||||
if (timeline1 === timeline2) {
|
||||
// both events are in the same timeline - figure out their
|
||||
// relative indices
|
||||
let idx1, idx2;
|
||||
let idx1;
|
||||
let idx2;
|
||||
const events = timeline1.getEvents();
|
||||
for (let idx = 0; idx < events.length &&
|
||||
(idx1 === undefined || idx2 === undefined); idx++) {
|
||||
|
||||
+40
-7
@@ -87,7 +87,7 @@ export const MatrixEvent = function(
|
||||
// amount of needless string duplication. This can save moderate amounts of
|
||||
// memory (~10% on a 350MB heap).
|
||||
// 'membership' at the event level (rather than the content level) is a legacy
|
||||
// field that Riot never otherwise looks at, but it will still take up a lot
|
||||
// field that Element never otherwise looks at, but it will still take up a lot
|
||||
// of space if we don't intern it.
|
||||
["state_key", "type", "sender", "room_id", "membership"].forEach((prop) => {
|
||||
if (!event[prop]) {
|
||||
@@ -144,6 +144,10 @@ export const MatrixEvent = function(
|
||||
*/
|
||||
this._forwardingCurve25519KeyChain = [];
|
||||
|
||||
/* where the decryption key is untrusted
|
||||
*/
|
||||
this._untrusted = null;
|
||||
|
||||
/* if we have a process decrypting this event, a Promise which resolves
|
||||
* when it is finished. Normally null.
|
||||
*/
|
||||
@@ -160,12 +164,16 @@ export const MatrixEvent = function(
|
||||
* so it can be easily accessed from the timeline.
|
||||
*/
|
||||
this.verificationRequest = null;
|
||||
|
||||
/* The txnId with which this event was sent if it was during this session,
|
||||
allows for a unique ID which does not change when the event comes back down sync.
|
||||
*/
|
||||
this._txnId = null;
|
||||
};
|
||||
utils.inherits(MatrixEvent, EventEmitter);
|
||||
|
||||
|
||||
utils.extend(MatrixEvent.prototype, {
|
||||
|
||||
/**
|
||||
* Get the event_id for this event.
|
||||
* @return {string} The event ID, e.g. <code>$143350589368169JsLZx:localhost
|
||||
@@ -390,11 +398,12 @@ utils.extend(MatrixEvent.prototype, {
|
||||
* @internal
|
||||
*
|
||||
* @param {module:crypto} crypto crypto module
|
||||
* @param {bool} isRetry True if this is a retry (enables more logging)
|
||||
*
|
||||
* @returns {Promise} promise which resolves (to undefined) when the decryption
|
||||
* attempt is completed.
|
||||
*/
|
||||
attemptDecryption: async function(crypto) {
|
||||
attemptDecryption: async function(crypto, isRetry) {
|
||||
// start with a couple of sanity checks.
|
||||
if (!this.isEncrypted()) {
|
||||
throw new Error("Attempt to decrypt event which isn't encrypted");
|
||||
@@ -406,7 +415,7 @@ utils.extend(MatrixEvent.prototype, {
|
||||
) {
|
||||
// we may want to just ignore this? let's start with rejecting it.
|
||||
throw new Error(
|
||||
"Attempt to decrypt event which has already been encrypted",
|
||||
"Attempt to decrypt event which has already been decrypted",
|
||||
);
|
||||
}
|
||||
|
||||
@@ -424,7 +433,7 @@ utils.extend(MatrixEvent.prototype, {
|
||||
return this._decryptionPromise;
|
||||
}
|
||||
|
||||
this._decryptionPromise = this._decryptionLoop(crypto);
|
||||
this._decryptionPromise = this._decryptionLoop(crypto, isRetry);
|
||||
return this._decryptionPromise;
|
||||
},
|
||||
|
||||
@@ -469,7 +478,7 @@ utils.extend(MatrixEvent.prototype, {
|
||||
return recipients;
|
||||
},
|
||||
|
||||
_decryptionLoop: async function(crypto) {
|
||||
_decryptionLoop: async function(crypto, isRetry) {
|
||||
// make sure that this method never runs completely synchronously.
|
||||
// (doing so would mean that we would clear _decryptionPromise *before*
|
||||
// it is set in attemptDecryption - and hence end up with a stuck
|
||||
@@ -486,13 +495,18 @@ utils.extend(MatrixEvent.prototype, {
|
||||
res = this._badEncryptedMessage("Encryption not enabled");
|
||||
} else {
|
||||
res = await crypto.decryptEvent(this);
|
||||
if (isRetry) {
|
||||
logger.info(`Decrypted event on retry (id=${this.getId()})`);
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
if (e.name !== "DecryptionError") {
|
||||
// not a decryption error: log the whole exception as an error
|
||||
// (and don't bother with a retry)
|
||||
const re = isRetry ? 're' : '';
|
||||
logger.error(
|
||||
`Error decrypting event (id=${this.getId()}): ${e.stack || e}`,
|
||||
`Error ${re}decrypting event ` +
|
||||
`(id=${this.getId()}): ${e.stack || e}`,
|
||||
);
|
||||
this._decryptionPromise = null;
|
||||
this._retryDecryption = false;
|
||||
@@ -593,6 +607,7 @@ utils.extend(MatrixEvent.prototype, {
|
||||
decryptionResult.claimedEd25519Key || null;
|
||||
this._forwardingCurve25519KeyChain =
|
||||
decryptionResult.forwardingCurve25519KeyChain || [];
|
||||
this._untrusted = decryptionResult.untrusted || false;
|
||||
},
|
||||
|
||||
/**
|
||||
@@ -683,6 +698,16 @@ utils.extend(MatrixEvent.prototype, {
|
||||
return this._forwardingCurve25519KeyChain;
|
||||
},
|
||||
|
||||
/**
|
||||
* Whether the decryption key was obtained from an untrusted source. If so,
|
||||
* we cannot verify the authenticity of the message.
|
||||
*
|
||||
* @return {boolean}
|
||||
*/
|
||||
isKeySourceUntrusted: function() {
|
||||
return this._untrusted;
|
||||
},
|
||||
|
||||
getUnsigned: function() {
|
||||
return this.event.unsigned || {};
|
||||
},
|
||||
@@ -1064,6 +1089,14 @@ utils.extend(MatrixEvent.prototype, {
|
||||
setVerificationRequest: function(request) {
|
||||
this.verificationRequest = request;
|
||||
},
|
||||
|
||||
setTxnId(txnId) {
|
||||
this._txnId = txnId;
|
||||
},
|
||||
|
||||
getTxnId() {
|
||||
return this._txnId;
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
|
||||
@@ -20,7 +20,7 @@ limitations under the License.
|
||||
*/
|
||||
|
||||
import {EventEmitter} from "events";
|
||||
import {getHttpUriForMxc, getIdenticonUri} from "../content-repo";
|
||||
import {getHttpUriForMxc} from "../content-repo";
|
||||
import * as utils from "../utils";
|
||||
|
||||
/**
|
||||
@@ -274,10 +274,6 @@ RoomMember.prototype.getAvatarUrl =
|
||||
);
|
||||
if (httpUrl) {
|
||||
return httpUrl;
|
||||
} else if (allowDefault) {
|
||||
return getIdenticonUri(
|
||||
baseUrl, this.userId, width, height,
|
||||
);
|
||||
}
|
||||
return null;
|
||||
};
|
||||
@@ -286,9 +282,9 @@ RoomMember.prototype.getAvatarUrl =
|
||||
* @return {string} the mxc avatar url
|
||||
*/
|
||||
RoomMember.prototype.getMxcAvatarUrl = function() {
|
||||
if(this.events.member) {
|
||||
if (this.events.member) {
|
||||
return this.events.member.getDirectionalContent().avatar_url;
|
||||
} else if(this.user) {
|
||||
} else if (this.user) {
|
||||
return this.user.avatarUrl;
|
||||
}
|
||||
return null;
|
||||
|
||||
+24
-17
@@ -68,9 +68,7 @@ export function RoomState(roomId, oobMemberFlags = undefined) {
|
||||
this.members = {
|
||||
// userId: RoomMember
|
||||
};
|
||||
this.events = {
|
||||
// eventType: { stateKey: MatrixEvent }
|
||||
};
|
||||
this.events = new Map(); // Map<eventType, Map<stateKey, MatrixEvent>>
|
||||
this.paginationToken = null;
|
||||
|
||||
this._sentinels = {
|
||||
@@ -211,14 +209,14 @@ RoomState.prototype.getSentinelMember = function(userId) {
|
||||
* <code>undefined</code>, else a single event (or null if no match found).
|
||||
*/
|
||||
RoomState.prototype.getStateEvents = function(eventType, stateKey) {
|
||||
if (!this.events[eventType]) {
|
||||
if (!this.events.has(eventType)) {
|
||||
// no match
|
||||
return stateKey === undefined ? [] : null;
|
||||
}
|
||||
if (stateKey === undefined) { // return all values
|
||||
return utils.values(this.events[eventType]);
|
||||
return Array.from(this.events.get(eventType).values());
|
||||
}
|
||||
const event = this.events[eventType][stateKey];
|
||||
const event = this.events.get(eventType).get(stateKey);
|
||||
return event ? event : null;
|
||||
};
|
||||
|
||||
@@ -238,9 +236,8 @@ RoomState.prototype.clone = function() {
|
||||
const status = this._oobMemberFlags.status;
|
||||
this._oobMemberFlags.status = OOB_STATUS_NOTSTARTED;
|
||||
|
||||
Object.values(this.events).forEach((eventsByStateKey) => {
|
||||
const eventsForType = Object.values(eventsByStateKey);
|
||||
copy.setStateEvents(eventsForType);
|
||||
Array.from(this.events.values()).forEach((eventsByStateKey) => {
|
||||
copy.setStateEvents(Array.from(eventsByStateKey.values()));
|
||||
});
|
||||
|
||||
// Ugly hack: see above
|
||||
@@ -276,8 +273,8 @@ RoomState.prototype.clone = function() {
|
||||
*/
|
||||
RoomState.prototype.setUnknownStateEvents = function(events) {
|
||||
const unknownStateEvents = events.filter((event) => {
|
||||
return this.events[event.getType()] === undefined ||
|
||||
this.events[event.getType()][event.getStateKey()] === undefined;
|
||||
return !this.events.has(event.getType()) ||
|
||||
!this.events.get(event.getType()).has(event.getStateKey());
|
||||
});
|
||||
|
||||
this.setStateEvents(unknownStateEvents);
|
||||
@@ -306,6 +303,7 @@ RoomState.prototype.setStateEvents = function(stateEvents) {
|
||||
return;
|
||||
}
|
||||
|
||||
const lastStateEvent = self._getStateEventMatching(event);
|
||||
self._setStateEvent(event);
|
||||
if (event.getType() === "m.room.member") {
|
||||
_updateDisplayNameCache(
|
||||
@@ -313,7 +311,7 @@ RoomState.prototype.setStateEvents = function(stateEvents) {
|
||||
);
|
||||
_updateThirdPartyTokenCache(self, event);
|
||||
}
|
||||
self.emit("RoomState.events", event, self);
|
||||
self.emit("RoomState.events", event, self, lastStateEvent);
|
||||
});
|
||||
|
||||
// update higher level data structures. This needs to be done AFTER the
|
||||
@@ -385,10 +383,15 @@ RoomState.prototype._getOrCreateMember = function(userId, event) {
|
||||
};
|
||||
|
||||
RoomState.prototype._setStateEvent = function(event) {
|
||||
if (this.events[event.getType()] === undefined) {
|
||||
this.events[event.getType()] = {};
|
||||
if (!this.events.has(event.getType())) {
|
||||
this.events.set(event.getType(), new Map());
|
||||
}
|
||||
this.events[event.getType()][event.getStateKey()] = event;
|
||||
this.events.get(event.getType()).set(event.getStateKey(), event);
|
||||
};
|
||||
|
||||
RoomState.prototype._getStateEventMatching = function(event) {
|
||||
if (!this.events.has(event.getType())) return null;
|
||||
return this.events.get(event.getType()).get(event.getStateKey());
|
||||
};
|
||||
|
||||
RoomState.prototype._updateMember = function(member) {
|
||||
@@ -670,7 +673,7 @@ RoomState.prototype._maySendEventOfType = function(eventType, userId, state) {
|
||||
const userPowerLevel = power_levels.users && power_levels.users[userId];
|
||||
if (Number.isFinite(userPowerLevel)) {
|
||||
powerLevel = userPowerLevel;
|
||||
} else if(Number.isFinite(power_levels.users_default)) {
|
||||
} else if (Number.isFinite(power_levels.users_default)) {
|
||||
powerLevel = power_levels.users_default;
|
||||
}
|
||||
|
||||
@@ -769,8 +772,12 @@ function _updateDisplayNameCache(roomState, userId, displayName) {
|
||||
* @param {MatrixEvent} event The matrix event which caused this event to fire.
|
||||
* @param {RoomState} state The room state whose RoomState.events dictionary
|
||||
* was updated.
|
||||
* @param {MatrixEvent} prevEvent The event being replaced by the new state, if
|
||||
* known. Note that this can differ from `getPrevContent()` on the new state event
|
||||
* as this is the store's view of the last state, not the previous state provided
|
||||
* by the server.
|
||||
* @example
|
||||
* matrixClient.on("RoomState.events", function(event, state){
|
||||
* matrixClient.on("RoomState.events", function(event, state, prevEvent){
|
||||
* var newStateEvent = event;
|
||||
* });
|
||||
*/
|
||||
|
||||
+14
-11
@@ -23,7 +23,7 @@ limitations under the License.
|
||||
import {EventEmitter} from "events";
|
||||
import {EventTimelineSet} from "./event-timeline-set";
|
||||
import {EventTimeline} from "./event-timeline";
|
||||
import {getHttpUriForMxc, getIdenticonUri} from "../content-repo";
|
||||
import {getHttpUriForMxc} from "../content-repo";
|
||||
import * as utils from "../utils";
|
||||
import {EventStatus, MatrixEvent} from "./event";
|
||||
import {RoomMember} from "./room-member";
|
||||
@@ -122,6 +122,10 @@ export function Room(roomId, client, myUserId, opts) {
|
||||
opts = opts || {};
|
||||
opts.pendingEventOrdering = opts.pendingEventOrdering || "chronological";
|
||||
|
||||
// In some cases, we add listeners for every displayed Matrix event, so it's
|
||||
// common to have quite a few more than the default limit.
|
||||
this.setMaxListeners(100);
|
||||
|
||||
this.reEmitter = new ReEmitter(this);
|
||||
|
||||
if (["chronological", "detached"].indexOf(opts.pendingEventOrdering) === -1) {
|
||||
@@ -209,7 +213,7 @@ utils.inherits(Room, EventEmitter);
|
||||
Room.prototype.getVersion = function() {
|
||||
const createEvent = this.currentState.getStateEvents("m.room.create", "");
|
||||
if (!createEvent) {
|
||||
logger.warn("Room " + this.room_id + " does not have an m.room.create event");
|
||||
logger.warn("Room " + this.roomId + " does not have an m.room.create event");
|
||||
return '1';
|
||||
}
|
||||
const ver = createEvent.getContent()['room_version'];
|
||||
@@ -675,7 +679,7 @@ Room.prototype.hasUnverifiedDevices = async function() {
|
||||
}
|
||||
const e2eMembers = await this.getEncryptionTargetMembers();
|
||||
for (const member of e2eMembers) {
|
||||
const devices = await this._client.getStoredDevicesForUser(member.userId);
|
||||
const devices = this._client.getStoredDevicesForUser(member.userId);
|
||||
if (devices.some((device) => device.isUnverified())) {
|
||||
return true;
|
||||
}
|
||||
@@ -814,10 +818,6 @@ Room.prototype.getAvatarUrl = function(baseUrl, width, height, resizeMethod,
|
||||
return getHttpUriForMxc(
|
||||
baseUrl, mainUrl, width, height, resizeMethod,
|
||||
);
|
||||
} else if (allowDefault) {
|
||||
return getIdenticonUri(
|
||||
baseUrl, this.roomId, width, height,
|
||||
);
|
||||
}
|
||||
|
||||
return null;
|
||||
@@ -1793,8 +1793,9 @@ Room.prototype.addAccountData = function(events) {
|
||||
if (event.getType() === "m.tag") {
|
||||
this.addTags(event);
|
||||
}
|
||||
const lastEvent = this.accountData[event.getType()];
|
||||
this.accountData[event.getType()] = event;
|
||||
this.emit("Room.accountData", event, this);
|
||||
this.emit("Room.accountData", event, this, lastEvent);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1899,14 +1900,14 @@ function calculateRoomName(room, userId, ignoreRoomNameEvent) {
|
||||
// let's try to figure out who was here before
|
||||
let leftNames = otherNames;
|
||||
// if we didn't have heroes, try finding them in the room state
|
||||
if(!leftNames.length) {
|
||||
if (!leftNames.length) {
|
||||
leftNames = room.currentState.getMembers().filter((m) => {
|
||||
return m.userId !== userId &&
|
||||
m.membership !== "invite" &&
|
||||
m.membership !== "join";
|
||||
}).map((m) => m.name);
|
||||
}
|
||||
if(leftNames.length) {
|
||||
if (leftNames.length) {
|
||||
return `Empty room (was ${memberNamesToRoomName(leftNames)})`;
|
||||
} else {
|
||||
return "Empty room";
|
||||
@@ -1991,8 +1992,10 @@ function memberNamesToRoomName(names, count = (names.length + 1)) {
|
||||
* @event module:client~MatrixClient#"Room.accountData"
|
||||
* @param {event} event The account_data event
|
||||
* @param {Room} room The room whose account_data was updated.
|
||||
* @param {MatrixEvent} prevEvent The event being replaced by
|
||||
* the new account data, if known.
|
||||
* @example
|
||||
* matrixClient.on("Room.accountData", function(event, room){
|
||||
* matrixClient.on("Room.accountData", function(event, room, oldEvent){
|
||||
* if (event.getType() === "m.room.colorscheme") {
|
||||
* applyColorScheme(event.getContents());
|
||||
* }
|
||||
|
||||
+10
-2
@@ -129,7 +129,11 @@ User.prototype.setPresenceEvent = function(event) {
|
||||
*/
|
||||
User.prototype.setDisplayName = function(name) {
|
||||
const oldName = this.displayName;
|
||||
this.displayName = name;
|
||||
if (typeof name === "string") {
|
||||
this.displayName = name;
|
||||
} else {
|
||||
this.displayName = undefined;
|
||||
}
|
||||
if (name !== oldName) {
|
||||
this._updateModifiedTime();
|
||||
}
|
||||
@@ -142,7 +146,11 @@ User.prototype.setDisplayName = function(name) {
|
||||
* @param {string} name The new display name.
|
||||
*/
|
||||
User.prototype.setRawDisplayName = function(name) {
|
||||
this.rawDisplayName = name;
|
||||
if (typeof name === "string") {
|
||||
this.rawDisplayName = name;
|
||||
} else {
|
||||
this.rawDisplayName = undefined;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
|
||||
+30
-70
@@ -23,9 +23,8 @@ import {escapeRegExp, globToRegexp, isNullOrUndefined} from "./utils";
|
||||
|
||||
const RULEKINDS_IN_ORDER = ['override', 'content', 'room', 'sender', 'underride'];
|
||||
|
||||
// The default override rules to apply when calculating actions for an event. These
|
||||
// defaults apply under no other circumstances to avoid confusing the client with server
|
||||
// state. We do this for two reasons:
|
||||
// The default override rules to apply to the push rules that arrive from the server.
|
||||
// We do this for two reasons:
|
||||
// 1. Synapse is unlikely to send us the push rule in an incremental sync - see
|
||||
// https://github.com/matrix-org/synapse/pull/4867#issuecomment-481446072 for
|
||||
// more details.
|
||||
@@ -85,12 +84,15 @@ export function PushProcessor(client) {
|
||||
// $glob: RegExp,
|
||||
};
|
||||
|
||||
const matchingRuleFromKindSet = (ev, kindset, device) => {
|
||||
const matchingRuleFromKindSet = (ev, kindset) => {
|
||||
for (let ruleKindIndex = 0;
|
||||
ruleKindIndex < RULEKINDS_IN_ORDER.length;
|
||||
++ruleKindIndex) {
|
||||
const kind = RULEKINDS_IN_ORDER[ruleKindIndex];
|
||||
const ruleset = kindset[kind];
|
||||
if (!ruleset) {
|
||||
continue;
|
||||
}
|
||||
|
||||
for (let ruleIndex = 0; ruleIndex < ruleset.length; ++ruleIndex) {
|
||||
const rule = ruleset[ruleIndex];
|
||||
@@ -98,7 +100,7 @@ export function PushProcessor(client) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const rawrule = templateRuleToRaw(kind, rule, device);
|
||||
const rawrule = templateRuleToRaw(kind, rule);
|
||||
if (!rawrule) {
|
||||
continue;
|
||||
}
|
||||
@@ -112,7 +114,7 @@ export function PushProcessor(client) {
|
||||
return null;
|
||||
};
|
||||
|
||||
const templateRuleToRaw = function(kind, tprule, device) {
|
||||
const templateRuleToRaw = function(kind, tprule) {
|
||||
const rawrule = {
|
||||
'rule_id': tprule.rule_id,
|
||||
'actions': tprule.actions,
|
||||
@@ -154,19 +156,12 @@ export function PushProcessor(client) {
|
||||
});
|
||||
break;
|
||||
}
|
||||
if (device) {
|
||||
rawrule.conditions.push({
|
||||
'kind': 'device',
|
||||
'profile_tag': device,
|
||||
});
|
||||
}
|
||||
return rawrule;
|
||||
};
|
||||
|
||||
const eventFulfillsCondition = function(cond, ev) {
|
||||
const condition_functions = {
|
||||
"event_match": eventFulfillsEventMatchCondition,
|
||||
"device": eventFulfillsDeviceCondition,
|
||||
"contains_display_name": eventFulfillsDisplayNameCondition,
|
||||
"room_member_count": eventFulfillsRoomMemberCountCondition,
|
||||
"sender_notification_permission": eventFulfillsSenderNotifPermCondition,
|
||||
@@ -258,10 +253,6 @@ export function PushProcessor(client) {
|
||||
return content.body.search(pat) > -1;
|
||||
};
|
||||
|
||||
const eventFulfillsDeviceCondition = function(cond, ev) {
|
||||
return false; // XXX: Allow a profile tag to be set for the web client instance
|
||||
};
|
||||
|
||||
const eventFulfillsEventMatchCondition = function(cond, ev) {
|
||||
if (!cond.key) {
|
||||
return false;
|
||||
@@ -326,23 +317,13 @@ export function PushProcessor(client) {
|
||||
};
|
||||
|
||||
const matchingRuleForEventWithRulesets = function(ev, rulesets) {
|
||||
if (!rulesets || !rulesets.device) {
|
||||
if (!rulesets) {
|
||||
return null;
|
||||
}
|
||||
if (ev.getSender() == client.credentials.userId) {
|
||||
if (ev.getSender() === client.credentials.userId) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const allDevNames = Object.keys(rulesets.device);
|
||||
for (let i = 0; i < allDevNames.length; ++i) {
|
||||
const devname = allDevNames[i];
|
||||
const devrules = rulesets.device[devname];
|
||||
|
||||
const matchingRule = matchingRuleFromKindSet(devrules, devname);
|
||||
if (matchingRule) {
|
||||
return matchingRule;
|
||||
}
|
||||
}
|
||||
return matchingRuleFromKindSet(ev, rulesets.global);
|
||||
};
|
||||
|
||||
@@ -364,33 +345,6 @@ export function PushProcessor(client) {
|
||||
return actionObj;
|
||||
};
|
||||
|
||||
const applyRuleDefaults = function(clientRuleset) {
|
||||
// Deep clone the object before we mutate it
|
||||
const ruleset = JSON.parse(JSON.stringify(clientRuleset));
|
||||
|
||||
if (!clientRuleset['global']) {
|
||||
clientRuleset['global'] = {};
|
||||
}
|
||||
if (!clientRuleset['global']['override']) {
|
||||
clientRuleset['global']['override'] = [];
|
||||
}
|
||||
|
||||
// Apply default overrides
|
||||
const globalOverrides = clientRuleset['global']['override'];
|
||||
for (const override of DEFAULT_OVERRIDE_RULES) {
|
||||
const existingRule = globalOverrides
|
||||
.find((r) => r.rule_id === override.rule_id);
|
||||
|
||||
if (!existingRule) {
|
||||
const ruleId = override.rule_id;
|
||||
console.warn(`Adding default global override for ${ruleId}`);
|
||||
globalOverrides.push(override);
|
||||
}
|
||||
}
|
||||
|
||||
return ruleset;
|
||||
};
|
||||
|
||||
this.ruleMatchesEvent = function(rule, ev) {
|
||||
let ret = true;
|
||||
for (let i = 0; i < rule.conditions.length; ++i) {
|
||||
@@ -410,8 +364,7 @@ export function PushProcessor(client) {
|
||||
* @return {PushAction}
|
||||
*/
|
||||
this.actionsForEvent = function(ev) {
|
||||
const rules = applyRuleDefaults(client.pushRules);
|
||||
return pushActionsForEventAndRulesets(ev, rules);
|
||||
return pushActionsForEventAndRulesets(ev, client.pushRules);
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -421,7 +374,7 @@ export function PushProcessor(client) {
|
||||
* @return {object} The push rule, or null if no such rule was found
|
||||
*/
|
||||
this.getPushRuleById = function(ruleId) {
|
||||
for (const scope of ['device', 'global']) {
|
||||
for (const scope of ['global']) {
|
||||
if (client.pushRules[scope] === undefined) continue;
|
||||
|
||||
for (const kind of RULEKINDS_IN_ORDER) {
|
||||
@@ -476,18 +429,25 @@ PushProcessor.rewriteDefaultRules = function(incomingRules) {
|
||||
if (!newRules.global) newRules.global = {};
|
||||
if (!newRules.global.override) newRules.global.override = [];
|
||||
|
||||
// Fix default override rules
|
||||
newRules.global.override = newRules.global.override.map(r => {
|
||||
const defaultRule = DEFAULT_OVERRIDE_RULES.find(d => d.rule_id === r.rule_id);
|
||||
if (!defaultRule) return r;
|
||||
// Merge the client-level defaults with the ones from the server
|
||||
const globalOverrides = newRules.global.override;
|
||||
for (const override of DEFAULT_OVERRIDE_RULES) {
|
||||
const existingRule = globalOverrides
|
||||
.find((r) => r.rule_id === override.rule_id);
|
||||
|
||||
// Copy over the actions, default, and conditions. Don't touch the user's
|
||||
// preference.
|
||||
r.default = defaultRule.default;
|
||||
r.conditions = defaultRule.conditions;
|
||||
r.actions = defaultRule.actions;
|
||||
return r;
|
||||
});
|
||||
if (existingRule) {
|
||||
// Copy over the actions, default, and conditions. Don't touch the user's
|
||||
// preference.
|
||||
existingRule.default = override.default;
|
||||
existingRule.conditions = override.conditions;
|
||||
existingRule.actions = override.actions;
|
||||
} else {
|
||||
// Add the rule
|
||||
const ruleId = override.rule_id;
|
||||
console.warn(`Adding default global override for ${ruleId}`);
|
||||
globalOverrides.push(override);
|
||||
}
|
||||
}
|
||||
|
||||
return newRules;
|
||||
};
|
||||
|
||||
@@ -185,8 +185,8 @@ function _runCallbacks() {
|
||||
*/
|
||||
function binarySearch(array, func) {
|
||||
// min is inclusive, max exclusive.
|
||||
let min = 0,
|
||||
max = array.length;
|
||||
let min = 0;
|
||||
let max = array.length;
|
||||
|
||||
while (min < max) {
|
||||
const mid = (min + max) >> 1;
|
||||
|
||||
+25
-2
@@ -25,6 +25,15 @@ limitations under the License.
|
||||
import {User} from "../models/user";
|
||||
import * as utils from "../utils";
|
||||
|
||||
function isValidFilterId(filterId) {
|
||||
const isValidStr = typeof filterId === "string" &&
|
||||
!!filterId &&
|
||||
filterId !== "undefined" && // exclude these as we've serialized undefined in localStorage before
|
||||
filterId !== "null";
|
||||
|
||||
return isValidStr || typeof filterId === "number";
|
||||
}
|
||||
|
||||
/**
|
||||
* Construct a new in-memory data store for the Matrix Client.
|
||||
* @constructor
|
||||
@@ -273,8 +282,17 @@ MemoryStore.prototype = {
|
||||
if (!this.localStorage) {
|
||||
return null;
|
||||
}
|
||||
const key = "mxjssdk_memory_filter_" + filterName;
|
||||
// XXX Storage.getItem doesn't throw ...
|
||||
// or are we using something different
|
||||
// than window.localStorage in some cases
|
||||
// that does throw?
|
||||
// that would be very naughty
|
||||
try {
|
||||
return this.localStorage.getItem("mxjssdk_memory_filter_" + filterName);
|
||||
const value = this.localStorage.getItem(key);
|
||||
if (isValidFilterId(value)) {
|
||||
return value;
|
||||
}
|
||||
} catch (e) {}
|
||||
return null;
|
||||
},
|
||||
@@ -288,8 +306,13 @@ MemoryStore.prototype = {
|
||||
if (!this.localStorage) {
|
||||
return;
|
||||
}
|
||||
const key = "mxjssdk_memory_filter_" + filterName;
|
||||
try {
|
||||
this.localStorage.setItem("mxjssdk_memory_filter_" + filterName, filterId);
|
||||
if (isValidFilterId(filterId)) {
|
||||
this.localStorage.setItem(key, filterId);
|
||||
} else {
|
||||
this.localStorage.removeItem(key);
|
||||
}
|
||||
} catch (e) {}
|
||||
},
|
||||
|
||||
|
||||
+21
-19
@@ -511,6 +511,12 @@ SyncApi.prototype.sync = function() {
|
||||
checkLazyLoadStatus(); // advance to the next stage
|
||||
}
|
||||
|
||||
function buildDefaultFilter() {
|
||||
const filter = new Filter(client.credentials.userId);
|
||||
filter.setTimelineLimit(self.opts.initialSyncLimit);
|
||||
return filter;
|
||||
}
|
||||
|
||||
const checkLazyLoadStatus = async () => {
|
||||
debuglog("Checking lazy load status...");
|
||||
if (this.opts.lazyLoadMembers && client.isGuest()) {
|
||||
@@ -520,19 +526,11 @@ SyncApi.prototype.sync = function() {
|
||||
debuglog("Checking server lazy load support...");
|
||||
const supported = await client.doesServerSupportLazyLoading();
|
||||
if (supported) {
|
||||
try {
|
||||
debuglog("Creating and storing lazy load sync filter...");
|
||||
this.opts.filter = await client.createFilter(
|
||||
Filter.LAZY_LOADING_SYNC_FILTER,
|
||||
);
|
||||
debuglog("Created and stored lazy load sync filter");
|
||||
} catch (err) {
|
||||
logger.error(
|
||||
"Creating and storing lazy load sync filter failed",
|
||||
err,
|
||||
);
|
||||
throw err;
|
||||
debuglog("Enabling lazy load on sync filter...");
|
||||
if (!this.opts.filter) {
|
||||
this.opts.filter = buildDefaultFilter();
|
||||
}
|
||||
this.opts.filter.setLazyLoadMembers(true);
|
||||
} else {
|
||||
debuglog("LL: lazy loading requested but not supported " +
|
||||
"by server, so disabling");
|
||||
@@ -575,8 +573,7 @@ SyncApi.prototype.sync = function() {
|
||||
if (self.opts.filter) {
|
||||
filter = self.opts.filter;
|
||||
} else {
|
||||
filter = new Filter(client.credentials.userId);
|
||||
filter.setTimelineLimit(self.opts.initialSyncLimit);
|
||||
filter = buildDefaultFilter();
|
||||
}
|
||||
|
||||
let filterId;
|
||||
@@ -704,7 +701,7 @@ SyncApi.prototype._syncFromCache = async function(savedSync) {
|
||||
|
||||
try {
|
||||
await this._processSyncResponse(syncEventData, data);
|
||||
} catch(e) {
|
||||
} catch (e) {
|
||||
logger.error("Error processing cached sync", e.stack || e);
|
||||
}
|
||||
|
||||
@@ -777,7 +774,7 @@ SyncApi.prototype._sync = async function(syncOptions) {
|
||||
|
||||
try {
|
||||
await this._processSyncResponse(syncEventData, data);
|
||||
} catch(e) {
|
||||
} catch (e) {
|
||||
// log the exception with stack if we have it, else fall back
|
||||
// to the plain description
|
||||
logger.error("Caught /sync error", e.stack || e);
|
||||
@@ -897,7 +894,7 @@ SyncApi.prototype._onSyncError = function(err, syncOptions) {
|
||||
logger.error("/sync error %s", err);
|
||||
logger.error(err);
|
||||
|
||||
if(this._shouldAbortSync(err)) {
|
||||
if (this._shouldAbortSync(err)) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1026,18 +1023,23 @@ SyncApi.prototype._processSyncResponse = async function(
|
||||
// handle non-room account_data
|
||||
if (data.account_data && utils.isArray(data.account_data.events)) {
|
||||
const events = data.account_data.events.map(client.getEventMapper());
|
||||
const prevEventsMap = events.reduce((m, c) => {
|
||||
m[c.getId()] = client.store.getAccountData(c.getType());
|
||||
return m;
|
||||
}, {});
|
||||
client.store.storeAccountDataEvents(events);
|
||||
events.forEach(
|
||||
function(accountDataEvent) {
|
||||
// Honour push rules that come down the sync stream but also
|
||||
// honour push rules that were previously cached. Base rules
|
||||
// will be updated when we recieve push rules via getPushRules
|
||||
// will be updated when we receive push rules via getPushRules
|
||||
// (see SyncApi.prototype.sync) before syncing over the network.
|
||||
if (accountDataEvent.getType() === 'm.push_rules') {
|
||||
const rules = accountDataEvent.getContent();
|
||||
client.pushRules = PushProcessor.rewriteDefaultRules(rules);
|
||||
}
|
||||
client.emit("accountData", accountDataEvent);
|
||||
const prevEvent = prevEventsMap[accountDataEvent.getId()];
|
||||
client.emit("accountData", accountDataEvent, prevEvent);
|
||||
return accountDataEvent;
|
||||
},
|
||||
);
|
||||
|
||||
@@ -396,7 +396,8 @@ TimelineWindow.prototype.getEvents = function() {
|
||||
// (Note that both this._start.index and this._end.index are relative
|
||||
// to their respective timelines' BaseIndex).
|
||||
//
|
||||
let startIndex = 0, endIndex = events.length;
|
||||
let startIndex = 0;
|
||||
let endIndex = events.length;
|
||||
if (timeline === this._start.timeline) {
|
||||
startIndex = this._start.index + timeline.getBaseIndex();
|
||||
}
|
||||
|
||||
+171
-161
@@ -49,7 +49,7 @@ export function encodeParams(params: Record<string, string>): string {
|
||||
* @return {string} The result of replacing all template variables e.g. '/foo/baz'.
|
||||
*/
|
||||
export function encodeUri(pathTemplate: string,
|
||||
variables: Record<string, string>): string {
|
||||
variables: Record<string, string>): string {
|
||||
for (const key in variables) {
|
||||
if (!variables.hasOwnProperty(key)) {
|
||||
continue;
|
||||
@@ -85,7 +85,7 @@ export function map<T, S>(array: T[], fn: (t: T) => S): S[] {
|
||||
* @return {Array} A new array with the results of the function.
|
||||
*/
|
||||
export function filter<T>(array: T[],
|
||||
fn: (t: T, i?: number, a?: T[]) => boolean): T[] {
|
||||
fn: (t: T, i?: number, a?: T[]) => boolean): T[] {
|
||||
const results: T[] = [];
|
||||
for (let i = 0; i < array.length; i++) {
|
||||
if (fn(array[i], i, array)) {
|
||||
@@ -151,10 +151,10 @@ export function forEach<T>(array: T[], fn: (t: T, i: number) => void) {
|
||||
* the given function.
|
||||
*/
|
||||
export function findElement<T>(
|
||||
array: T[],
|
||||
fn: (t: T, i?: number, a?: T[]) => boolean,
|
||||
reverse?: boolean
|
||||
) {
|
||||
array: T[],
|
||||
fn: (t: T, i?: number, a?: T[]) => boolean,
|
||||
reverse?: boolean,
|
||||
) {
|
||||
let i;
|
||||
if (reverse) {
|
||||
for (i = array.length - 1; i >= 0; i--) {
|
||||
@@ -182,10 +182,10 @@ export function findElement<T>(
|
||||
* @return {boolean} True if an element was removed.
|
||||
*/
|
||||
export function removeElement<T>(
|
||||
array: T[],
|
||||
fn: (t: T, i?: number, a?: T[]) => boolean,
|
||||
reverse?: boolean
|
||||
) {
|
||||
array: T[],
|
||||
fn: (t: T, i?: number, a?: T[]) => boolean,
|
||||
reverse?: boolean,
|
||||
) {
|
||||
let i;
|
||||
let removed;
|
||||
if (reverse) {
|
||||
@@ -265,7 +265,7 @@ export function checkObjectHasNoAdditionalKeys(obj: object, allowedKeys: string[
|
||||
* @param {Object} obj The object to deep copy.
|
||||
* @return {Object} A copy of the object without any references to the original.
|
||||
*/
|
||||
export function deepCopy(obj: object): object {
|
||||
export function deepCopy<T>(obj: T): T {
|
||||
return JSON.parse(JSON.stringify(obj));
|
||||
}
|
||||
|
||||
@@ -293,7 +293,7 @@ export function deepCompare(x: any, y: any): boolean {
|
||||
|
||||
// special-case NaN (since NaN !== NaN)
|
||||
if (typeof x === 'number' && isNaN(x) && isNaN(y)) {
|
||||
return true;
|
||||
return true;
|
||||
}
|
||||
|
||||
// special-case null (since typeof null == 'object', but null.constructor
|
||||
@@ -368,10 +368,11 @@ export function deepCompare(x: any, y: any): boolean {
|
||||
*
|
||||
* @return {Object} target
|
||||
*/
|
||||
export function extend() {
|
||||
const target = arguments[0] || {};
|
||||
for (let i = 1; i < arguments.length; i++) {
|
||||
const source = arguments[i];
|
||||
export function extend(...restParams) {
|
||||
const target = restParams[0] || {};
|
||||
for (let i = 1; i < restParams.length; i++) {
|
||||
const source = restParams[i];
|
||||
if (!source) continue;
|
||||
for (const propName in source) { // eslint-disable-line guard-for-in
|
||||
target[propName] = source[propName];
|
||||
}
|
||||
@@ -388,36 +389,36 @@ export function runPolyfills() {
|
||||
// SOURCE:
|
||||
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
|
||||
if (!Array.prototype.filter) {
|
||||
Array.prototype.filter = function(fun: Function/*, thisArg*/) {
|
||||
if (this === void 0 || this === null) {
|
||||
throw new TypeError();
|
||||
}
|
||||
|
||||
const t = Object(this);
|
||||
const len = t.length >>> 0;
|
||||
if (typeof fun !== 'function') {
|
||||
throw new TypeError();
|
||||
}
|
||||
|
||||
const res = [];
|
||||
const thisArg = arguments.length >= 2 ? arguments[1] : void 0;
|
||||
for (let i = 0; i < len; i++) {
|
||||
if (i in t) {
|
||||
const val = t[i];
|
||||
|
||||
// NOTE: Technically this should Object.defineProperty at
|
||||
// the next index, as push can be affected by
|
||||
// properties on Object.prototype and Array.prototype.
|
||||
// But that method's new, and collisions should be
|
||||
// rare, so use the more-compatible alternative.
|
||||
if (fun.call(thisArg, val, i, t)) {
|
||||
res.push(val);
|
||||
// eslint-disable-next-line no-extend-native
|
||||
Array.prototype.filter = function(fun: Function/*, thisArg*/, ...restProps) {
|
||||
if (this === void 0 || this === null) {
|
||||
throw new TypeError();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return res;
|
||||
};
|
||||
const t = Object(this);
|
||||
const len = t.length >>> 0;
|
||||
if (typeof fun !== 'function') {
|
||||
throw new TypeError();
|
||||
}
|
||||
|
||||
const res = [];
|
||||
const thisArg = restProps ? restProps[0] : void 0;
|
||||
for (let i = 0; i < len; i++) {
|
||||
if (i in t) {
|
||||
const val = t[i];
|
||||
|
||||
// NOTE: Technically this should Object.defineProperty at
|
||||
// the next index, as push can be affected by
|
||||
// properties on Object.prototype and Array.prototype.
|
||||
// But that method's new, and collisions should be
|
||||
// rare, so use the more-compatible alternative.
|
||||
if (fun.call(thisArg, val, i, t)) {
|
||||
res.push(val);
|
||||
}
|
||||
}
|
||||
}
|
||||
return res;
|
||||
};
|
||||
}
|
||||
|
||||
// Array.prototype.map
|
||||
@@ -427,151 +428,156 @@ export function runPolyfills() {
|
||||
// Production steps of ECMA-262, Edition 5, 15.4.4.19
|
||||
// Reference: http://es5.github.io/#x15.4.4.19
|
||||
if (!Array.prototype.map) {
|
||||
Array.prototype.map = function(callback, thisArg) {
|
||||
let T, k;
|
||||
// eslint-disable-next-line no-extend-native
|
||||
Array.prototype.map = function(callback, thisArg) {
|
||||
let T;
|
||||
let k;
|
||||
|
||||
if (this === null || this === undefined) {
|
||||
throw new TypeError(' this is null or not defined');
|
||||
}
|
||||
if (this === null || this === undefined) {
|
||||
throw new TypeError(' this is null or not defined');
|
||||
}
|
||||
|
||||
// 1. Let O be the result of calling ToObject passing the |this|
|
||||
// value as the argument.
|
||||
const O = Object(this);
|
||||
// 1. Let O be the result of calling ToObject passing the |this|
|
||||
// value as the argument.
|
||||
const O = Object(this);
|
||||
|
||||
// 2. Let lenValue be the result of calling the Get internal
|
||||
// method of O with the argument "length".
|
||||
// 3. Let len be ToUint32(lenValue).
|
||||
const len = O.length >>> 0;
|
||||
// 2. Let lenValue be the result of calling the Get internal
|
||||
// method of O with the argument "length".
|
||||
// 3. Let len be ToUint32(lenValue).
|
||||
const len = O.length >>> 0;
|
||||
|
||||
// 4. If IsCallable(callback) is false, throw a TypeError exception.
|
||||
// See: http://es5.github.com/#x9.11
|
||||
if (typeof callback !== 'function') {
|
||||
throw new TypeError(callback + ' is not a function');
|
||||
}
|
||||
// 4. If IsCallable(callback) is false, throw a TypeError exception.
|
||||
// See: http://es5.github.com/#x9.11
|
||||
if (typeof callback !== 'function') {
|
||||
throw new TypeError(callback + ' is not a function');
|
||||
}
|
||||
|
||||
// 5. If thisArg was supplied, let T be thisArg; else let T be undefined.
|
||||
if (arguments.length > 1) {
|
||||
T = thisArg;
|
||||
}
|
||||
// 5. If thisArg was supplied, let T be thisArg; else let T be undefined.
|
||||
if (arguments.length > 1) {
|
||||
T = thisArg;
|
||||
}
|
||||
|
||||
// 6. Let A be a new array created as if by the expression new Array(len)
|
||||
// where Array is the standard built-in constructor with that name and
|
||||
// len is the value of len.
|
||||
const A = new Array(len);
|
||||
// 6. Let A be a new array created as if by the expression new Array(len)
|
||||
// where Array is the standard built-in constructor with that name and
|
||||
// len is the value of len.
|
||||
const A = new Array(len);
|
||||
|
||||
// 7. Let k be 0
|
||||
k = 0;
|
||||
// 7. Let k be 0
|
||||
k = 0;
|
||||
|
||||
// 8. Repeat, while k < len
|
||||
while (k < len) {
|
||||
let kValue, mappedValue;
|
||||
// 8. Repeat, while k < len
|
||||
while (k < len) {
|
||||
let kValue;
|
||||
let mappedValue;
|
||||
|
||||
// a. Let Pk be ToString(k).
|
||||
// This is implicit for LHS operands of the in operator
|
||||
// b. Let kPresent be the result of calling the HasProperty internal
|
||||
// method of O with argument Pk.
|
||||
// This step can be combined with c
|
||||
// c. If kPresent is true, then
|
||||
if (k in O) {
|
||||
// i. Let kValue be the result of calling the Get internal
|
||||
// method of O with argument Pk.
|
||||
kValue = O[k];
|
||||
// a. Let Pk be ToString(k).
|
||||
// This is implicit for LHS operands of the in operator
|
||||
// b. Let kPresent be the result of calling the HasProperty internal
|
||||
// method of O with argument Pk.
|
||||
// This step can be combined with c
|
||||
// c. If kPresent is true, then
|
||||
if (k in O) {
|
||||
// i. Let kValue be the result of calling the Get internal
|
||||
// method of O with argument Pk.
|
||||
kValue = O[k];
|
||||
|
||||
// ii. Let mappedValue be the result of calling the Call internal
|
||||
// method of callback with T as the this value and argument
|
||||
// list containing kValue, k, and O.
|
||||
mappedValue = callback.call(T, kValue, k, O);
|
||||
// ii. Let mappedValue be the result of calling the Call internal
|
||||
// method of callback with T as the this value and argument
|
||||
// list containing kValue, k, and O.
|
||||
mappedValue = callback.call(T, kValue, k, O);
|
||||
|
||||
// iii. Call the DefineOwnProperty internal method of A with arguments
|
||||
// Pk, Property Descriptor
|
||||
// { Value: mappedValue,
|
||||
// Writable: true,
|
||||
// Enumerable: true,
|
||||
// Configurable: true },
|
||||
// and false.
|
||||
// iii. Call the DefineOwnProperty internal method of A with arguments
|
||||
// Pk, Property Descriptor
|
||||
// { Value: mappedValue,
|
||||
// Writable: true,
|
||||
// Enumerable: true,
|
||||
// Configurable: true },
|
||||
// and false.
|
||||
|
||||
// In browsers that support Object.defineProperty, use the following:
|
||||
// Object.defineProperty(A, k, {
|
||||
// value: mappedValue,
|
||||
// writable: true,
|
||||
// enumerable: true,
|
||||
// configurable: true
|
||||
// });
|
||||
// In browsers that support Object.defineProperty, use the following:
|
||||
// Object.defineProperty(A, k, {
|
||||
// value: mappedValue,
|
||||
// writable: true,
|
||||
// enumerable: true,
|
||||
// configurable: true
|
||||
// });
|
||||
|
||||
// For best browser support, use the following:
|
||||
A[k] = mappedValue;
|
||||
}
|
||||
// d. Increase k by 1.
|
||||
k++;
|
||||
}
|
||||
// For best browser support, use the following:
|
||||
A[k] = mappedValue;
|
||||
}
|
||||
// d. Increase k by 1.
|
||||
k++;
|
||||
}
|
||||
|
||||
// 9. return A
|
||||
return A;
|
||||
};
|
||||
// 9. return A
|
||||
return A;
|
||||
};
|
||||
}
|
||||
|
||||
// Array.prototype.forEach
|
||||
// ========================================================
|
||||
// SOURCE:
|
||||
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
|
||||
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
|
||||
// Production steps of ECMA-262, Edition 5, 15.4.4.18
|
||||
// Reference: http://es5.github.io/#x15.4.4.18
|
||||
if (!Array.prototype.forEach) {
|
||||
Array.prototype.forEach = function(callback, thisArg) {
|
||||
let T, k;
|
||||
// eslint-disable-next-line no-extend-native
|
||||
Array.prototype.forEach = function(callback, thisArg) {
|
||||
let T;
|
||||
let k;
|
||||
|
||||
if (this === null || this === undefined) {
|
||||
throw new TypeError(' this is null or not defined');
|
||||
}
|
||||
if (this === null || this === undefined) {
|
||||
throw new TypeError(' this is null or not defined');
|
||||
}
|
||||
|
||||
// 1. Let O be the result of calling ToObject passing the |this| value as the
|
||||
// argument.
|
||||
const O = Object(this);
|
||||
// 1. Let O be the result of calling ToObject passing the |this| value as the
|
||||
// argument.
|
||||
const O = Object(this);
|
||||
|
||||
// 2. Let lenValue be the result of calling the Get internal method of O with the
|
||||
// argument "length".
|
||||
// 3. Let len be ToUint32(lenValue).
|
||||
const len = O.length >>> 0;
|
||||
// 2. Let lenValue be the result of calling the Get internal method of O with the
|
||||
// argument "length".
|
||||
// 3. Let len be ToUint32(lenValue).
|
||||
const len = O.length >>> 0;
|
||||
|
||||
// 4. If IsCallable(callback) is false, throw a TypeError exception.
|
||||
// See: http://es5.github.com/#x9.11
|
||||
if (typeof callback !== "function") {
|
||||
throw new TypeError(callback + ' is not a function');
|
||||
}
|
||||
// 4. If IsCallable(callback) is false, throw a TypeError exception.
|
||||
// See: http://es5.github.com/#x9.11
|
||||
if (typeof callback !== "function") {
|
||||
throw new TypeError(callback + ' is not a function');
|
||||
}
|
||||
|
||||
// 5. If thisArg was supplied, let T be thisArg; else let T be undefined.
|
||||
if (arguments.length > 1) {
|
||||
T = thisArg;
|
||||
}
|
||||
// 5. If thisArg was supplied, let T be thisArg; else let T be undefined.
|
||||
if (arguments.length > 1) {
|
||||
T = thisArg;
|
||||
}
|
||||
|
||||
// 6. Let k be 0
|
||||
k = 0;
|
||||
// 6. Let k be 0
|
||||
k = 0;
|
||||
|
||||
// 7. Repeat, while k < len
|
||||
while (k < len) {
|
||||
let kValue;
|
||||
// 7. Repeat, while k < len
|
||||
while (k < len) {
|
||||
let kValue;
|
||||
|
||||
// a. Let Pk be ToString(k).
|
||||
// This is implicit for LHS operands of the in operator
|
||||
// b. Let kPresent be the result of calling the HasProperty internal
|
||||
// method of O with
|
||||
// argument Pk.
|
||||
// This step can be combined with c
|
||||
// c. If kPresent is true, then
|
||||
if (k in O) {
|
||||
// i. Let kValue be the result of calling the Get internal method of O with
|
||||
// argument Pk
|
||||
kValue = O[k];
|
||||
// a. Let Pk be ToString(k).
|
||||
// This is implicit for LHS operands of the in operator
|
||||
// b. Let kPresent be the result of calling the HasProperty internal
|
||||
// method of O with
|
||||
// argument Pk.
|
||||
// This step can be combined with c
|
||||
// c. If kPresent is true, then
|
||||
if (k in O) {
|
||||
// i. Let kValue be the result of calling the Get internal method of O with
|
||||
// argument Pk
|
||||
kValue = O[k];
|
||||
|
||||
// ii. Call the Call internal method of callback with T as the this value and
|
||||
// argument list containing kValue, k, and O.
|
||||
callback.call(T, kValue, k, O);
|
||||
}
|
||||
// d. Increase k by 1.
|
||||
k++;
|
||||
}
|
||||
// ii. Call the Call internal method of callback with T as the this value and
|
||||
// argument list containing kValue, k, and O.
|
||||
callback.call(T, kValue, k, O);
|
||||
}
|
||||
// d. Increase k by 1.
|
||||
k++;
|
||||
}
|
||||
// 8. return undefined
|
||||
};
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -655,7 +661,10 @@ export function isNumber(value: any): boolean {
|
||||
* @return {string} a string with the hidden characters removed
|
||||
*/
|
||||
export function removeHiddenChars(str: string): string {
|
||||
return unhomoglyph(str.normalize('NFD').replace(removeHiddenCharsRegex, ''));
|
||||
if (typeof str === "string") {
|
||||
return unhomoglyph(str.normalize('NFD').replace(removeHiddenCharsRegex, ''));
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
// Regex matching bunch of unicode control characters and otherwise misleading/invisible characters.
|
||||
@@ -665,6 +674,7 @@ export function removeHiddenChars(str: string): string {
|
||||
// LTR/RTL and other directional formatting marks U+202A - U+202F
|
||||
// Combining characters U+0300 - U+036F
|
||||
// Zero width no-break space (BOM) U+FEFF
|
||||
// eslint-disable-next-line no-misleading-character-class
|
||||
const removeHiddenCharsRegex = /[\u2000-\u200F\u202A-\u202F\u0300-\u036f\uFEFF\s]/g;
|
||||
|
||||
export function escapeRegExp(string: string): string {
|
||||
@@ -723,9 +733,9 @@ export function defer() {
|
||||
}
|
||||
|
||||
export async function promiseMapSeries<T>(
|
||||
promises: Promise<T>[],
|
||||
fn: (t: T) => void
|
||||
): Promise<void> {
|
||||
promises: Promise<T>[],
|
||||
fn: (t: T) => void,
|
||||
): Promise<void> {
|
||||
for (const o of await promises) {
|
||||
await fn(await o);
|
||||
}
|
||||
|
||||
+1
-1
@@ -176,7 +176,7 @@ MatrixCall.prototype.placeScreenSharingCall =
|
||||
debuglog("Got screen stream, requesting audio stream...");
|
||||
const audioConstraints = _getUserMediaVideoContraints('voice');
|
||||
_placeCallWithConstraints(self, audioConstraints);
|
||||
} catch(err) {
|
||||
} catch (err) {
|
||||
self.emit("error",
|
||||
callError(
|
||||
MatrixCall.ERR_NO_USER_MEDIA,
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
"compilerOptions": {
|
||||
"experimentalDecorators": true,
|
||||
"emitDecoratorMetadata": true,
|
||||
"esModuleInterop": true,
|
||||
"module": "commonjs",
|
||||
"moduleResolution": "node",
|
||||
"target": "es2016",
|
||||
|
||||
-72
@@ -1,72 +0,0 @@
|
||||
{
|
||||
"rules": {
|
||||
"class-name": false,
|
||||
"comment-format": [
|
||||
true
|
||||
],
|
||||
"curly": false,
|
||||
"eofline": false,
|
||||
"forin": false,
|
||||
"indent": [
|
||||
true,
|
||||
"spaces"
|
||||
],
|
||||
"label-position": true,
|
||||
"max-line-length": false,
|
||||
"member-access": false,
|
||||
"member-ordering": [
|
||||
true,
|
||||
"static-after-instance",
|
||||
"variables-before-functions"
|
||||
],
|
||||
"no-arg": true,
|
||||
"no-bitwise": false,
|
||||
"no-console": false,
|
||||
"no-construct": true,
|
||||
"no-debugger": true,
|
||||
"no-duplicate-variable": true,
|
||||
"no-empty": false,
|
||||
"no-eval": true,
|
||||
"no-inferrable-types": true,
|
||||
"no-shadowed-variable": true,
|
||||
"no-string-literal": false,
|
||||
"no-switch-case-fall-through": true,
|
||||
"no-trailing-whitespace": true,
|
||||
"no-unused-expression": true,
|
||||
"no-use-before-declare": false,
|
||||
"no-var-keyword": true,
|
||||
"object-literal-sort-keys": false,
|
||||
"one-line": [
|
||||
true,
|
||||
"check-open-brace",
|
||||
"check-catch",
|
||||
"check-else",
|
||||
"check-whitespace"
|
||||
],
|
||||
"quotemark": false,
|
||||
"radix": true,
|
||||
"semicolon": [
|
||||
"always"
|
||||
],
|
||||
"triple-equals": [],
|
||||
"typedef-whitespace": [
|
||||
true,
|
||||
{
|
||||
"call-signature": "nospace",
|
||||
"index-signature": "nospace",
|
||||
"parameter": "nospace",
|
||||
"property-declaration": "nospace",
|
||||
"variable-declaration": "nospace"
|
||||
}
|
||||
],
|
||||
"variable-name": false,
|
||||
"whitespace": [
|
||||
true,
|
||||
"check-branch",
|
||||
"check-decl",
|
||||
"check-operator",
|
||||
"check-separator",
|
||||
"check-type"
|
||||
]
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user