Compare commits

..

248 Commits

Author SHA1 Message Date
RiotRobot d050261fa9 v11.2.0-rc.1 2021-06-01 16:09:49 +01:00
RiotRobot d29330815e Prepare changelog for v11.2.0-rc.1 2021-06-01 16:09:48 +01:00
Michael Telatynski 801b4022de Merge pull request #1720 from matrix-org/t3chguy/fix/17521
Switch to stable endpoint/fields for MSC2858
2021-06-01 12:07:25 +01:00
Michael Telatynski e78fbd1dff Switch to stable endpoint/fields for MSC2858 2021-06-01 11:01:10 +01:00
Travis Ralston ff2954839b Merge pull request #1715 from matrix-org/dependabot/npm_and_yarn/ws-7.4.6
Bump ws from 7.4.2 to 7.4.6
2021-05-29 21:44:48 -06:00
dependabot[bot] 1a91b88968 Bump ws from 7.4.2 to 7.4.6
Bumps [ws](https://github.com/websockets/ws) from 7.4.2 to 7.4.6.
- [Release notes](https://github.com/websockets/ws/releases)
- [Commits](https://github.com/websockets/ws/compare/7.4.2...7.4.6)

Signed-off-by: dependabot[bot] <support@github.com>
2021-05-29 21:09:19 +00:00
Germain 25ec81b6c7 Merge pull request #1712 from matrix-org/gsouquet/fix/17393
Make consistent call event type checks
2021-05-28 13:09:35 +01:00
J. Ryan Stinnett a50802a63f Merge pull request #1714 from matrix-org/jryans/babel-config
Apply new Babel linting config
2021-05-28 13:04:06 +01:00
J. Ryan Stinnett ce1d374a82 Merge pull request #1709 from matrix-org/dependabot/npm_and_yarn/browserslist-4.16.6
Bump browserslist from 4.16.1 to 4.16.6
2021-05-28 11:41:38 +01:00
J. Ryan Stinnett 6dca8ac460 Switch to new Babel lint config
This also adjusts the TypeScript project lint config to cover *.ts test files
too.
2021-05-28 11:39:06 +01:00
J. Ryan Stinnett 4dc21674d5 Fix log usage 2021-05-28 11:30:20 +01:00
J. Ryan Stinnett 8805dd8c01 Auto-fix lint errors 2021-05-28 11:15:10 +01:00
David Baker 73b624e761 Merge pull request #1713 from matrix-org/dbkr/user_busy
Add user_busy call hangup reason
2021-05-28 09:42:56 +01:00
David Baker c44fd972b6 Add user_busy call hangup reason
And fix hangup reasons in reject events
2021-05-27 18:56:27 +01:00
J. Ryan Stinnett ff344bc110 Switch lint parsers 2021-05-27 17:51:03 +01:00
J. Ryan Stinnett b0e2a38325 Auto-fix lint errors 2021-05-27 17:50:16 +01:00
J. Ryan Stinnett fbb741ab10 Switch to new Babel linting config 2021-05-27 17:49:35 +01:00
Germain 3a3be36f4c Merge pull request #1688 from matrix-org/gsouquet/pr-review-linting-rules 2021-05-27 16:03:36 +01:00
Germain Souquet cb91c4292c Merge branch 'develop' into gsouquet/pr-review-linting-rules 2021-05-27 16:00:12 +01:00
Germain Souquet 80722ce145 make consistent call event type checks 2021-05-27 09:55:50 +01:00
J. Ryan Stinnett cea1a3ff91 Merge pull request #1710 from matrix-org/jryans/hidden-events-reactions
Emit relations created when target event added later
2021-05-26 17:34:47 +01:00
J. Ryan Stinnett 270be2df7a Emit relations created when target event added later
This changes the "relations created" event to ensure it is properly emitted even
if the target event is added to the timeline after the relation event. There was
perhaps always a risk of this happening in the past, but is seems more likely to
bite now with delayed decryption.

Part of https://github.com/vector-im/element-web/issues/17461
2021-05-26 16:35:49 +01:00
dependabot[bot] 2c0549a772 Bump browserslist from 4.16.1 to 4.16.6
Bumps [browserslist](https://github.com/browserslist/browserslist) from 4.16.1 to 4.16.6.
- [Release notes](https://github.com/browserslist/browserslist/releases)
- [Changelog](https://github.com/browserslist/browserslist/blob/main/CHANGELOG.md)
- [Commits](https://github.com/browserslist/browserslist/compare/4.16.1...4.16.6)

Signed-off-by: dependabot[bot] <support@github.com>
2021-05-25 21:59:49 +00:00
RiotRobot acb9bc8cc5 Resetting package fields for development 2021-05-24 17:14:02 +01:00
RiotRobot 6f44aa39e8 Merge branch 'master' into develop 2021-05-24 17:13:42 +01:00
RiotRobot c706618229 v11.1.0 2021-05-24 17:09:09 +01:00
RiotRobot c26b571b1c Prepare changelog for v11.1.0 2021-05-24 17:09:08 +01:00
J. Ryan Stinnett cb3075b084 Merge pull request #1707 from matrix-org/jryans/olm-3.2.3-release
[Release] Bump libolm version and update package name
2021-05-24 16:49:25 +01:00
Hubert Chathi 66fb21bd0b bump olm to 3.2.3 2021-05-24 16:27:56 +01:00
Hubert Chathi 498109bd53 update test too 2021-05-24 16:27:56 +01:00
Hubert Chathi 6711ab5f9a Bump libolm version and update package name. 2021-05-24 16:27:56 +01:00
J. Ryan Stinnett ac8fa58845 Merge pull request #1705 from uhoreg/olm_3.2.2
Bump libolm version and update package name.
2021-05-24 16:22:15 +01:00
Hubert Chathi 095f656998 bump olm to 3.2.3 2021-05-24 11:10:52 -04:00
Hubert Chathi 9e30c4f7dd update test too 2021-05-21 16:28:37 -04:00
Hubert Chathi 56a2eeac77 Bump libolm version and update package name. 2021-05-21 16:04:54 -04:00
Michael Telatynski d104f2f4a7 Merge pull request #1703 from matrix-org/t3chguy/uploadContent
Fix uploadContent not rejecting promise when http status code >= 400
2021-05-20 18:43:12 +01:00
Michael Telatynski e8367ad241 fix httpStatus being resolved when response is undefined 2021-05-20 18:33:17 +01:00
Michael Telatynski f17cd142d5 Fix uploadContent not rejecting promise when http status code >= 400 2021-05-20 15:43:22 +01:00
J. Ryan Stinnett e8edc554a6 Merge pull request #1702 from matrix-org/jryans/test-noise
Reduce noise in tests
2021-05-20 13:42:31 +01:00
J. Ryan Stinnett bd8aca83ac Reduce noise in tests
This disables a common log message to cut down the test log size and make it
easier to read messages specific to each test.
2021-05-20 13:41:54 +01:00
J. Ryan Stinnett 7ebc1cfac5 Merge pull request #1700 from matrix-org/matthew/kill-invite-logspam
Only log once if a Room lacks an m.room.create event
2021-05-20 12:02:32 +01:00
Germain 2422204d6a Merge pull request #1701 from matrix-org/gsouquet/cache-normalized-name
Cache normalized room name
2021-05-20 11:12:00 +01:00
Germain Souquet 6c98c3c662 Remove reference to room name in utils 2021-05-20 10:58:20 +01:00
Germain Souquet 1d1310f034 Cache normalized room name 2021-05-20 10:44:47 +01:00
J. Ryan Stinnett 841888c480 Merge pull request #1699 from matrix-org/jryans/call-enc-release
[Release] Change call event handlers to adapt to undecrypted events
2021-05-19 21:28:19 +01:00
Matthew Hodgson 52c031f160 Only log once if a Room lacks an m.room.create event
Currently my account is logging ~20,000 warnings a minute about getType() being called
on invites which have no m.room.create events, which crashes my inspector and makes
my console unusable.  We still want the logline though, as it helps diagnose
space invite problems.  So instead, log this only once.  (Untested).
2021-05-19 19:02:31 +01:00
Germain Souquet 155113b75d move startEventCallHandler to MatrixClient prototype 2021-05-19 18:16:20 +01:00
Germain Souquet 2a863025c6 listen to call event handlers when sync is prepared 2021-05-19 18:15:39 +01:00
Germain Souquet b6763ce89f Change call event handlers to adapt to undecrypted events 2021-05-19 18:14:28 +01:00
Germain f346cd6b8d Merge pull request #1698 from matrix-org/gsouquet/fix-call-handlers 2021-05-19 17:23:51 +01:00
Germain Souquet 0c47412c75 move startEventCallHandler to MatrixClient prototype 2021-05-19 17:15:44 +01:00
Germain Souquet ea1ef3dbec listen to call event handlers when sync is prepared 2021-05-19 17:05:20 +01:00
Germain Souquet 61fd62ff81 Merge branch 'develop' into gsouquet/fix-call-handlers 2021-05-19 16:51:29 +01:00
Germain Souquet 32197ea903 Change call event handlers to adapt to undecrypted events 2021-05-19 15:45:21 +01:00
RiotRobot 65de184d88 v11.1.0-rc.1 2021-05-19 14:29:51 +01:00
RiotRobot 52764045ce Prepare changelog for v11.1.0-rc.1 2021-05-19 14:29:50 +01:00
J. Ryan Stinnett 4b0db6c472 Guard against duplicates in Relations model
The `Relations` model was relying on object reference equality to prevent
duplicates, which breaks down if we ever have two objects that represent the
same event.

This fixes things to additionally track event IDs we've seen before and discard
any attempts to add them twice.

Fixes https://github.com/vector-im/element-web/issues/11161
2021-05-19 13:20:40 +01:00
Germain 40cd4629db Decrypt relations before applying them to target event (#1696) 2021-05-18 17:21:06 +01:00
RiotRobot 52a893a811 Resetting package fields for development 2021-05-17 13:32:49 +01:00
RiotRobot 7cc94e1e1e Merge branch 'master' into develop 2021-05-17 13:32:48 +01:00
RiotRobot 88945a6d6d v11.0.0 2021-05-17 13:30:08 +01:00
RiotRobot 7203c5aaf0 Prepare changelog for v11.0.0 2021-05-17 13:30:07 +01:00
J. Ryan Stinnett c305058c46 Merge pull request #1695 from matrix-org/jryans/glare-streams-release
[Release] Fix regressed glare
2021-05-17 11:55:25 +01:00
Šimon Brandner 91bbf7d1a8 Fix glare
Signed-off-by: Šimon Brandner <simon.bra.ag@gmail.com>
2021-05-17 11:20:14 +01:00
J. Ryan Stinnett 2d5857f145 Merge pull request #1690 from SimonBrandner/fix/glare/17250
Fix regressed glare
2021-05-17 11:11:39 +01:00
Travis Ralston 91af9a411d Null-guard power level object usage (#1694) 2021-05-14 08:36:44 +01:00
Germain 9a9ed124f5 Use native Object and Array methods (#1693) 2021-05-13 17:20:09 +01:00
Michael Telatynski 4e5442d972 Merge pull request #1692 from matrix-org/t3chguy/fix/i80
Add m.reaction to EventType enum
2021-05-13 12:44:42 +01:00
Michael Telatynski b5fa54f91e Add m.reaction to EventType enum 2021-05-13 10:57:02 +01:00
Germain 2246aede4b Merge pull request #1684 from matrix-org/gsouquet/cache-decrypt 2021-05-12 12:19:59 +01:00
Šimon Brandner 4b2d409c69 Fix glare
Signed-off-by: Šimon Brandner <simon.bra.ag@gmail.com>
2021-05-12 07:47:48 +02:00
RiotRobot 684511ff06 v11.0.0-rc.1 2021-05-11 15:03:04 +01:00
RiotRobot 88b328df7e Prepare changelog for v11.0.0-rc.1 2021-05-11 15:03:03 +01:00
Michael Telatynski e3583dd04e Merge pull request #1679 from matrix-org/t3chguy/spaces-stable
Switch from MSC1772 unstable prefixes to stable
2021-05-11 13:39:47 +01:00
Germain Souquet e484a2ebb5 add missing coma to appease linter 2021-05-11 13:02:42 +01:00
Germain Souquet 5caf05cfa1 Apply new linting rules 2021-05-11 11:25:43 +01:00
Germain Souquet 72f86258d0 Add explainer for awaitDecryption 2021-05-11 10:05:24 +01:00
Germain Souquet 874cb3b779 make attemptDecryption backwards compatible 2021-05-11 10:02:32 +01:00
Germain f21e0228b4 Update documentation wording
Co-authored-by: Travis Ralston <travpc@gmail.com>
2021-05-11 09:20:14 +01:00
Germain Souquet 01cd82bc6a undo test timeout 2021-05-10 18:12:47 +01:00
Germain Souquet d2a6a8b283 Merge branch 'develop' into gsouquet/cache-decrypt 2021-05-10 17:35:05 +01:00
Germain Souquet f242e460ed fix tests 2021-05-10 17:28:00 +01:00
Germain Souquet 95e08253a6 Appease linter 2021-05-10 16:59:54 +01:00
Germain Souquet 202a4fa6f1 Better document new room methods 2021-05-10 15:55:16 +01:00
Germain Souquet 576f46cb88 Add flag to prevent emitting event.decrypted 2021-05-10 15:25:07 +01:00
J. Ryan Stinnett 2d73805ca3 Merge pull request #1680 from SimonBrandner/feed-example
Update the VoIP example to work with the new changes
2021-05-10 14:50:18 +01:00
J. Ryan Stinnett eedfa550a6 Merge pull request #1687 from matrix-org/dependabot/npm_and_yarn/hosted-git-info-2.8.9
Bump hosted-git-info from 2.8.8 to 2.8.9
2021-05-10 14:48:34 +01:00
dependabot[bot] 4ca718adc4 Bump hosted-git-info from 2.8.8 to 2.8.9
Bumps [hosted-git-info](https://github.com/npm/hosted-git-info) from 2.8.8 to 2.8.9.
- [Release notes](https://github.com/npm/hosted-git-info/releases)
- [Changelog](https://github.com/npm/hosted-git-info/blob/v2.8.9/CHANGELOG.md)
- [Commits](https://github.com/npm/hosted-git-info/compare/v2.8.8...v2.8.9)

Signed-off-by: dependabot[bot] <support@github.com>
2021-05-10 13:46:58 +00:00
RiotRobot 7c4ced8f46 Resetting package fields for development 2021-05-10 14:46:14 +01:00
RiotRobot 7018f4ab25 Merge branch 'master' into develop 2021-05-10 14:46:13 +01:00
RiotRobot fda13875ef v10.1.0 2021-05-10 14:43:18 +01:00
RiotRobot 8005917452 Prepare changelog for v10.1.0 2021-05-10 14:43:17 +01:00
Germain Souquet 91eee8587e extract shouldAttemptDecryption to event model 2021-05-07 15:16:04 +01:00
Germain Souquet e9132abc25 Do not attempt to decrypt already clear events 2021-05-07 12:58:53 +01:00
Germain Souquet 444eac5c6e consolidate critical event decryption implementation 2021-05-07 11:23:59 +01:00
Šimon Brandner a449c5f8c2 Merge branch 'develop' into feed-example 2021-05-06 16:44:29 +02:00
Germain Souquet 19d6dbaa52 Use read receipt instead of read marker 2021-05-06 14:07:38 +01:00
Germain Souquet 8820619e82 Pass decrypt flag to event mapper 2021-05-06 12:34:21 +01:00
Germain Souquet fb33bc7e07 Lazily decrypt event on room view 2021-05-06 11:46:14 +01:00
J. Ryan Stinnett 57d1fa8410 Merge pull request #1660 from SimonBrandner/feed
Support for multiple streams (not MSC3077)
2021-05-06 11:19:52 +01:00
Michael Telatynski 838e38d84c Merge pull request #1683 from matrix-org/t3chguy/spaces-logs
Tweak missing m.room.create errors to describe their source
2021-05-06 00:06:38 +01:00
Michael Telatynski fc29056530 Tweak missing m.room.create errors to describe their source 2021-05-05 23:58:40 +01:00
RiotRobot 4e967c979c v10.1.0-rc.1 2021-05-04 15:37:55 +01:00
RiotRobot 62a34848c7 Prepare changelog for v10.1.0-rc.1 2021-05-04 15:37:54 +01:00
Travis Ralston 01fe6cc542 Merge pull request #1681 from matrix-org/revert-1678-travis/event-logging
Revert "Raise logging dramatically to chase pending event errors"
2021-05-02 19:11:06 -06:00
Travis Ralston 3fdc25777d Revert "Raise logging dramatically to chase pending event errors" 2021-05-02 19:10:47 -06:00
Šimon Brandner 3b7d6f8334 This check doesn't seem to be necessary
Signed-off-by: Šimon Brandner <simon.bra.ag@gmail.com>
2021-04-30 14:43:00 +02:00
Šimon Brandner 4b3c8b2969 Update the example to work with the new feed code
Signed-off-by: Šimon Brandner <simon.bra.ag@gmail.com>
2021-04-30 14:18:20 +02:00
Šimon Brandner ad80d69369 Add some basic styling
Signed-off-by: Šimon Brandner <simon.bra.ag@gmail.com>
2021-04-30 14:17:30 +02:00
Michael Telatynski e2d2249686 Switch from MSC1772 unstable prefixes to stable 2021-04-30 11:33:45 +01:00
J. Ryan Stinnett dc64c34ccb Merge pull request #1677 from matrix-org/jryans/coverage
Add test coverage collection script
2021-04-28 17:18:07 +01:00
Travis Ralston 0bf50659ab Merge pull request #1678 from matrix-org/travis/event-logging
Raise logging dramatically to chase pending event errors
2021-04-28 09:30:04 -06:00
Travis Ralston ec26b16ddf Raise logging dramatically to chase pending event errors
For https://github.com/vector-im/element-web/issues/17090 and similar issues

This logging is expected to exist no longer than a day.
2021-04-28 09:24:19 -06:00
J. Ryan Stinnett a044b74a1d Add test coverage collection script
This makes it clear to how collect basic test coverage when desired.
2021-04-28 14:17:08 +01:00
J. Ryan Stinnett 1e7a1dce90 Move Jest options into config block 2021-04-28 12:58:39 +01:00
Šimon Brandner 41c2772cff Merge branch 'develop' into feed
Signed-off-by: Šimon Brandner <simon.bra.ag@gmail.com>
2021-04-28 10:57:59 +02:00
David Baker 1bba2bc0ed Merge pull request #1674 from matrix-org/dbkr/asserted_identity
Support MSC3086 asserted identity
2021-04-28 09:47:30 +01:00
Šimon Brandner e11c523a75 Add getLocalFeeds() and getRemoteFeeds()
Signed-off-by: Šimon Brandner <simon.bra.ag@gmail.com>
2021-04-27 10:06:21 +02:00
RiotRobot b911a890cf Add breaking notice 2021-04-26 18:03:19 +01:00
RiotRobot c8f69c0b79 Resetting package fields for development 2021-04-26 17:37:06 +01:00
RiotRobot 8a6248f120 Merge branch 'master' into develop 2021-04-26 17:37:06 +01:00
RiotRobot 340fa6c63e v10.0.0 2021-04-26 17:34:17 +01:00
RiotRobot 1177bf39a2 Prepare changelog for v10.0.0 2021-04-26 17:34:16 +01:00
Šimon Brandner 88b310c394 Rename stuff to make it easy to read
Signed-off-by: Šimon Brandner <simon.bra.ag@gmail.com>
2021-04-26 16:00:17 +02:00
Šimon Brandner 973de2db55 stopAllMedia() before deleteAllFeeds()
Signed-off-by: Šimon Brandner <simon.bra.ag@gmail.com>
2021-04-24 12:56:28 +02:00
Šimon Brandner 1fe92f10c1 Delint
Signed-off-by: Šimon Brandner <simon.bra.ag@gmail.com>
2021-04-24 12:26:54 +02:00
Šimon Brandner 0e2e906b24 Remove remoteStream prop
This is done in order to be more generic

Signed-off-by: Šimon Brandner <simon.bra.ag@gmail.com>
2021-04-24 12:24:15 +02:00
Šimon Brandner 4667f8be03 Use feeds in stopAllMedia()
Signed-off-by: Šimon Brandner <simon.bra.ag@gmail.com>
2021-04-24 12:08:45 +02:00
David Baker 4a51ac7a74 Move createNewMatrixCall to the client object
So we can mock it out it tests (and also I'm not sure why it was
like this in the first place: we passed the client in anyway...)

Deprecate createNewMatrixCall
2021-04-23 14:36:56 +01:00
J. Ryan Stinnett 6099efe41a Merge pull request #1670 from timokoesters/fix-undefined-results
Fix `/search` with no results field work again
2021-04-23 13:02:52 +01:00
Germain 4254d595fc Merge pull request #1672 from hannojg/patch-5 2021-04-22 09:27:22 +01:00
Timo Kösters 069ca4a89d fix: make /search with no results field work again 2021-04-21 22:56:36 +02:00
RiotRobot e3ba08fbbc v10.0.0-rc.1 2021-04-21 16:40:23 +01:00
RiotRobot dd84e51161 Prepare changelog for v10.0.0-rc.1 2021-04-21 16:40:22 +01:00
David Baker bca8568d64 missing semicolon 2021-04-20 12:58:33 +01:00
David Baker 5407717534 Assert event emitted 2021-04-20 12:57:11 +01:00
David Baker 74ef760591 Tests: They find bugs 2021-04-20 12:48:54 +01:00
Germain b435b582bd Merge pull request #1675 from matrix-org/gsouquet-powerlevels-perf
Restrict event emit for room members that had power levels changed
2021-04-20 11:57:18 +01:00
Germain Souquet d46021a05e Restrict event emit for room members that had power levels changed 2021-04-20 11:22:16 +01:00
David Baker 1b31d0622e Unit test for asserted identity messages 2021-04-20 11:08:06 +01:00
Michael Telatynski 68206a6e19 Merge pull request #1669 from hannojg/patch-3
Fix sync with misconfigured push rules
2021-04-20 08:57:16 +01:00
David Baker 56797948af lint 2021-04-19 20:36:00 +01:00
David Baker c0af2f25a1 Support MSC3086 asserted identity 2021-04-19 20:28:42 +01:00
Hanno J. Gödecke dc12b1df00 feat: room.getMembers
Signed-off-by: Hanno Gödecke <hgoedecke@cuvent.com>
2021-04-18 16:01:51 +02:00
Hanno J. Gödecke b13f5aebfd lint 2021-04-17 09:42:44 +02:00
Hanno J. Gödecke 338301bb5d fix: failure during sync 2021-04-17 09:34:31 +02:00
Šimon Brandner 72a0931663 Remove comment: // Fix when client is TSified
Signed-off-by: Šimon Brandner <simon.bra.ag@gmail.com>
2021-04-16 11:38:01 +02:00
Šimon Brandner 67584b9cc3 Merge branch 'feed' of https://github.com/SimonBrandner/matrix-js-sdk into feed 2021-04-16 11:10:22 +02:00
Šimon Brandner 1bfaa28f9c Fix missing types
Signed-off-by: Šimon Brandner <simon.bra.ag@gmail.com>
2021-04-16 11:09:28 +02:00
Hubert Chathi cbe9b59222 Merge pull request #1665 from uhoreg/dehydrated_device_missing_await
Add missing await
2021-04-14 10:47:09 -04:00
Hubert Chathi 276b52f0fe add missing await 2021-04-14 10:29:39 -04:00
Šimon Brandner 07f49bcc37 Merge branch 'develop' into feed 2021-04-13 12:33:23 +02:00
J. Ryan Stinnett 09fac77ce0 Merge pull request #1642 from matrix-org/jryans/rework-linting
Migrate to `eslint-plugin-matrix-org`
2021-04-13 11:12:39 +01:00
J. Ryan Stinnett 102704e91a Migrate to eslint-plugin-matrix-org
This migrates to the new plugin form of our custom ESLint configs. As part of
this, some packages are de-duplicated, configs streamlined, etc.
2021-04-13 11:00:41 +01:00
Michael Telatynski c5fb351baa Merge pull request #1664 from matrix-org/t3chguy/fix/8665
Add missing event type enum for key verification done
2021-04-13 10:05:00 +01:00
Michael Telatynski 98f8d4414d Add missing event type enum for key verification done 2021-04-13 09:41:53 +01:00
Germain 1dddcd4925 Merge pull request #1663 from matrix-org/gsouquet-timeline-jumpiness 2021-04-12 15:00:49 +01:00
Germain Souquet 2666a271a5 fix tests when pendingEventsList does not exist 2021-04-12 14:51:45 +01:00
RiotRobot e277de6e3d Resetting package fields for development 2021-04-12 14:42:29 +01:00
RiotRobot daa17b3287 Merge branch 'master' into develop 2021-04-12 14:42:29 +01:00
RiotRobot c7f887131e v9.11.0 2021-04-12 14:39:33 +01:00
RiotRobot 58546b80d0 Prepare changelog for v9.11.0 2021-04-12 14:39:32 +01:00
Germain Souquet 466f749b71 fix typo 2021-04-12 14:38:27 +01:00
Germain Souquet 4c2a83c470 Add explanation for events persistence 2021-04-12 14:29:10 +01:00
Germain Souquet d534ab18c7 fix event filtering logic 2021-04-12 13:07:57 +01:00
Germain Souquet 64aaed833b Only persist encrypted events for encrypted rooms 2021-04-12 12:53:27 +01:00
Germain Souquet 2f05be599c undo changes to event#toJSON and persist encrypted events 2021-04-12 12:26:27 +01:00
Germain Souquet 7371f8dd3a Persist txnId to ensure idempotency 2021-04-12 09:55:01 +01:00
Germain Souquet 79aefe9707 Fix timeline jumpiness by setting correct txnId 2021-04-12 09:37:19 +01:00
Michael Telatynski 6bc80577ee Merge pull request #1661 from janpawellek/janpawellek-fix-addEventListener
Fix calling addEventListener if it does not exist
2021-04-12 09:15:19 +01:00
Germain 837764190f Merge pull request #1655 from matrix-org/gsouquet-persist-unsent-messages 2021-04-09 17:48:01 +01:00
Germain Souquet 61948d70e3 Merge branch 'develop' into gsouquet-persist-unsent-messages 2021-04-09 17:05:19 +01:00
Jan Pawellek 9fb0385694 Fix calling addEventListener if it does not exist
Some platforms (e.g. React Native) register global.window, but do not have global.window.addEventListener. In this case, this function should not be called.
2021-04-09 10:18:47 +02:00
Šimon Brandner 193de8d3a9 Merge branch 'feed' of https://github.com/SimonBrandner/matrix-js-sdk into feed 2021-04-08 11:15:07 +02:00
Šimon Brandner 1f2b3512c1 Move SDPStreamMetadataPurpose into callEventTypes.ts
Signed-off-by: Šimon Brandner <simon.bra.ag@gmail.com>
2021-04-08 11:14:42 +02:00
Šimon Brandner ddc5bd3b36 Add prefixes to SDPStreamMetadataPurpose
Signed-off-by: Šimon Brandner <simon.bra.ag@gmail.com>
2021-04-08 11:07:53 +02:00
Šimon Brandner ee828d454a Rename CallFeedPurpose to SDPStreamMetadataPurpose
This is to match MSC3077

Signed-off-by: Šimon Brandner <simon.bra.ag@gmail.com>
2021-04-08 11:07:22 +02:00
Šimon Brandner 2916a73f4c Make selectDesktopCapturerSource optional 2021-04-08 11:01:17 +02:00
Šimon Brandner ae69af7e70 Merge branch 'develop' into feed 2021-04-07 19:14:17 +02:00
RiotRobot 1c6459fe65 v9.11.0-rc.1 2021-04-07 12:55:25 +01:00
RiotRobot adaeb42416 Prepare changelog for v9.11.0-rc.1 2021-04-07 12:55:24 +01:00
J. Ryan Stinnett f1e1daa194 Merge pull request #1657 from matrix-org/jryans/cs-keys-test
Only try to cache private keys we know exist
2021-04-06 10:09:04 +01:00
J. Ryan Stinnett 401e89ef78 Only try to cache private keys we know exist
This tweaks https://github.com/matrix-org/matrix-js-sdk/pull/1649 to only try
caching private keys locally once we've confirmed they exist first. This is most
likely only an issue in tests, where we sometimes create only some but not all
keys.
2021-04-06 09:49:20 +01:00
Travis Ralston 59e0bd467c Merge pull request #1654 from SimonBrandner/terminate-screen-share
Properly terminate screen-share calls if NoUserMedia
2021-04-05 10:55:02 -06:00
Šimon Brandner 7f4397f8ca Use getAudioTracks() and getVideoTracks()
This is much nicer. Before I hadn't realized this was possible

Signed-off-by: Šimon Brandner <simon.bra.ag@gmail.com>
2021-04-05 10:31:27 +02:00
Šimon Brandner 32830b93f1 Rename audioOnly to videoMuted
This makes more sense and will match a possible mute events MSC

Signed-off-by: Šimon Brandner <simon.bra.ag@gmail.com>
2021-04-04 08:50:27 +02:00
Šimon Brandner cdc0d5623b Rename to match MSC3077
Signed-off-by: Šimon Brandner <simon.bra.ag@gmail.com>
2021-04-04 08:37:09 +02:00
Šimon Brandner e78b415832 Add getMember() to CallFeed
Signed-off-by: Šimon Brandner <simon.bra.ag@gmail.com>
2021-04-04 08:33:51 +02:00
Šimon Brandner ff1379fd29 Merge branch 'develop' into feed 2021-04-03 08:35:05 +02:00
David Baker 3820c15ecf Merge pull request #1652 from matrix-org/dbkr/attended_transfer
Attended transfer
2021-04-01 17:34:18 +01:00
Germain Souquet 26ef33e4f3 No this assign 2021-04-01 17:29:21 +01:00
Germain Souquet 0534a4ed1b prevent removePendingEvent being called when not in detached mode 2021-04-01 17:23:55 +01:00
Germain Souquet f29a24a915 specify TestClient when testing room model 2021-04-01 15:22:13 +01:00
Germain Souquet cecbcd941e Persist unsent messages for subsequent sessions 2021-04-01 10:59:16 +01:00
David Baker 6be99d6397 Terminate the other call too 2021-03-30 12:13:28 +01:00
J. Ryan Stinnett 4e5947af51 Merge pull request #1653 from matrix-org/jryans/cancel-security-key
Remove catch handlers in private key retrieval
2021-03-29 17:58:07 +01:00
RiotRobot 4204b2170a Resetting package fields for development 2021-03-29 13:28:09 +01:00
RiotRobot 0a5ad489b6 Merge branch 'master' into develop 2021-03-29 13:28:08 +01:00
RiotRobot 5de34a5c99 v9.10.0 2021-03-29 13:25:27 +01:00
RiotRobot 08da6b8800 Prepare changelog for v9.10.0 2021-03-29 13:25:27 +01:00
Šimon Brandner 02b283be78 Properly terminate screenshare calls if NoUserMedia
Signed-off-by: Šimon Brandner <simon.bra.ag@gmail.com>
2021-03-27 09:13:44 +01:00
J. Ryan Stinnett 10c49c0fd1 Remove catch handlers in private key retrieval
This removes some catch blocks originally added by
https://github.com/matrix-org/matrix-js-sdk/pull/1472 so that higher level
operations can handle them as needed.

Part of https://github.com/vector-im/element-web/issues/15584
2021-03-26 17:57:23 +00:00
David Baker 9ecc0f5d95 Terminate calls once we've replaced them 2021-03-26 13:52:23 +00:00
Travis Ralston 972b59b99e Merge pull request #1651 from DantrazTrev/CallErrorFix
Fixed the media fail error on caller's side
2021-03-25 19:05:36 -06:00
David Baker 34bb05bd88 WIP attended transfer 2021-03-25 19:57:20 +00:00
Hubert Chathi 37fb21f726 Merge pull request #1640 from uhoreg/room-history-key-sharing2
Add function to share megolm keys for historical messages.
2021-03-25 14:18:12 -04:00
Ayush PS b42efa4a07 Fixed lint errors 2021-03-25 23:38:18 +05:30
Ayush PS 20b20738a7 Fixed a slight error back to orignal in ScreenShareCall 2021-03-25 23:02:44 +05:30
Ayush PS b28a191c4e Fixed the media fail error on caller's side 2021-03-25 22:43:18 +05:30
Hubert Chathi f92b620434 Merge branch 'develop' into room-history-key-sharing2 2021-03-25 12:24:42 -04:00
RiotRobot ae6e2cca27 v9.10.0-rc.1 2021-03-25 12:06:34 +00:00
RiotRobot bd920eef1f Prepare changelog for v9.10.0-rc.1 2021-03-25 12:06:34 +00:00
J. Ryan Stinnett bf25cb68da Merge pull request #1649 from matrix-org/jryans/get-keys-bootstrap-only
Cache cross-signing private keys if needed on bootstrap
2021-03-24 15:56:15 +00:00
J. Ryan Stinnett 0b063f6b8b Cache cross-signing private keys if needed on bootstrap
This is a revised version of
https://github.com/matrix-org/matrix-js-sdk/pull/1472 which was previously
reverted for causing security prompts to appear on device list sync. In this
version, we only allow private key requests (which are likely to trigger user
dialogs) if we are coming from the bootstrap path.

This allows sessions that have already synced cross-signing public keys but
never got the private keys for some reason to make forward progress when e.g.
the user triggers bootstrap from security settings.
2021-03-24 11:48:45 +00:00
Travis Ralston ed6d4e5f6c Merge pull request #1647 from SimonBrandner/dont-send-hangup
Don't send m.call.hangup if m.call.invite wasn't sent either
2021-03-22 00:42:04 -06:00
Travis Ralston accfa325b5 Merge pull request #1641 from NicolaiSoeborg/fix-registerGuest
docs: registerGuest()
2021-03-21 20:37:49 -06:00
Šimon Brandner b6ef8d95cd Don't send hangup if invite wasn't sent
Signed-off-by: Šimon Brandner <simon.bra.ag@gmail.com>
2021-03-21 21:29:00 +01:00
Travis Ralston c1144e3810 Merge pull request #1639 from Johennes/feature/chunk-device-keys
Download device keys in chunks of 250
2021-03-18 13:17:15 -06:00
Johannes Marbach 8663fd402b Download device keys in chunks of 250
Depending on the number of users in the request, the server might
overload. To prevent this, the download is broken into chunks of
250 users each. Additionally, no more than 3 requests are kicked off
at the same time to avoid running into rate limiting. Responses are
processed once all chunks have been downloaded.

Fixes: #1619

Signed-off-by: Johannes Marbach <n0-0ne+github@mailbox.org>
2021-03-17 20:56:25 +01:00
Šimon Brandner d8134aa168 Merge branch 'feed' into feed-audio 2021-03-17 16:16:33 +01:00
Šimon Brandner 702b3e8473 Merge branch 'develop' into feed
Signed-off-by: Šimon Brandner <simon.bra.ag@gmail.com>
2021-03-17 16:16:07 +01:00
David Baker f34052fd31 Merge pull request #1646 from matrix-org/dbkr/more_call_fixes
More VoIP connectivity fixes
2021-03-17 15:00:09 +00:00
David Baker 27d75a269f unintentional comment 2021-03-16 19:18:45 +00:00
David Baker d208a7fc5f Remove unintentionally committed stuff 2021-03-16 19:17:04 +00:00
David Baker 702e16e3df More VoIP connectivity fixes
* Don't ignore other candidates when we see a null one (continue
   rather than return)
 * await on addICECandidate()
 * Don't add ice candidates until we've set a remote description
 * More & better logging
2021-03-16 19:13:03 +00:00
Hubert Chathi 6381018658 add jsdoc and implementation for memory crypto store 2021-03-16 13:52:05 -04:00
Travis Ralston 12050b14f0 Merge pull request #1644 from SimonBrandner/fix-optional
Make selectDesktopCapturerSource param optional
2021-03-15 21:12:03 -06:00
Hubert Chathi 1c191b2278 use new terminology and field name from MSC 2021-03-15 22:49:43 -04:00
Nicolai Søborg 2d4a4f1736 docs: registerGuest 2021-03-15 22:46:43 +00:00
RiotRobot cd38fb9b4c Resetting package fields for development 2021-03-15 14:34:56 +00:00
RiotRobot 7941b16ec4 Merge branch 'master' into develop 2021-03-15 14:34:56 +00:00
Šimon Brandner 56ea4b8741 Make selectDesktopCapturerSource param optional
Signed-off-by: Šimon Brandner <simon.bra.ag@gmail.com>
2021-03-13 15:03:36 +01:00
Hubert Chathi a489691151 various fixes 2021-03-11 17:30:05 -05:00
Nicolai Søborg 6dabfcda6f setGuest(true) when registerGuest()
Signed-off-by: Nicolai Søborg <git@xn--sb-lka.org>
2021-03-11 22:39:51 +01:00
J. Ryan Stinnett 0b7b35f800 Merge pull request #1632 from matrix-org/matthew/rework-cross-signing-login
Expose APIs needed for reworked cross-signing login flow
2021-03-11 12:54:18 +00:00
Hubert Chathi 0bfcb5071d fix test, lint 2021-03-10 20:04:34 -05:00
Hubert Chathi ceb162eb01 initial work on room history key sharing, take 2 2021-03-10 19:51:22 -05:00
Šimon Brandner b307a177f4 Remove handling of audio from MatrixCall
Signed-off-by: Šimon Brandner <simon.bra.ag@gmail.com>
2021-03-10 12:24:48 +01:00
Šimon Brandner 059430bd0a Doc public methods
Signed-off-by: Šimon Brandner <simon.bra.ag@gmail.com>
2021-03-10 12:21:15 +01:00
Šimon Brandner 530b60cbc2 Make MatrixCall use CallFeed
Signed-off-by: Šimon Brandner <simon.bra.ag@gmail.com>
2021-03-10 12:21:07 +01:00
Šimon Brandner ba8577f268 Add CallFeed class
Signed-off-by: Šimon Brandner <simon.bra.ag@gmail.com>
2021-03-10 08:43:01 +01:00
Matthew Hodgson 9fb2fbaeec factor out getDehydratedDevice 2021-03-09 00:09:22 +00:00
Matthew Hodgson 977682d37f fix lint 2021-03-08 09:24:25 +00:00
Matthew Hodgson 0bafe263d7 fix lint 2021-03-08 05:05:14 +00:00
Matthew Hodgson 1a8fced80e Merge branch 'develop' into matthew/rework-cross-signing-login 2021-03-08 04:59:40 +00:00
Matthew Hodgson 1c4d0b5e99 expose getDevice API 2021-03-08 04:59:29 +00:00
Matthew Hodgson 844a2b457c expose getDehydratedDevice API 2021-03-08 04:59:19 +00:00
Matthew Hodgson ccf06f2216 don't cancel ourselves when selecting a self-verification partner 2021-03-08 04:58:55 +00:00
126 changed files with 2542 additions and 2456 deletions
+20 -7
View File
@@ -1,13 +1,14 @@
module.exports = {
extends: ["matrix-org"],
plugins: [
"babel",
"matrix-org",
],
extends: [
"plugin:matrix-org/babel",
],
env: {
browser: true,
node: true,
},
rules: {
"no-var": ["warn"],
"prefer-rest-params": ["warn"],
@@ -32,14 +33,26 @@ module.exports = {
"no-console": "error",
},
overrides: [{
"files": ["src/**/*.ts"],
"extends": ["matrix-org/ts"],
"rules": {
files: [
"**/*.ts",
],
extends: [
"plugin:matrix-org/typescript",
],
rules: {
// TypeScript has its own version of this
"@babel/no-invalid-this": "off",
// We're okay being explicit at the moment
"@typescript-eslint/no-empty-interface": "off",
// While we're converting to ts we make heavy use of this
// We disable this while we're transitioning
"@typescript-eslint/no-explicit-any": "off",
// We'd rather not do this but we do
"@typescript-eslint/ban-ts-comment": "off",
"quotes": "off",
// We use a `logger` intermediary module
"no-console": "error",
},
}],
};
+193
View File
@@ -1,3 +1,196 @@
Changes in [11.2.0-rc.1](https://github.com/matrix-org/matrix-js-sdk/releases/tag/v11.2.0-rc.1) (2021-06-01)
============================================================================================================
[Full Changelog](https://github.com/matrix-org/matrix-js-sdk/compare/v11.1.0...v11.2.0-rc.1)
* Switch to stable endpoint/fields for MSC2858
[\#1720](https://github.com/matrix-org/matrix-js-sdk/pull/1720)
* Bump ws from 7.4.2 to 7.4.6
[\#1715](https://github.com/matrix-org/matrix-js-sdk/pull/1715)
* Make consistent call event type checks
[\#1712](https://github.com/matrix-org/matrix-js-sdk/pull/1712)
* Apply new Babel linting config
[\#1714](https://github.com/matrix-org/matrix-js-sdk/pull/1714)
* Bump browserslist from 4.16.1 to 4.16.6
[\#1709](https://github.com/matrix-org/matrix-js-sdk/pull/1709)
* Add user_busy call hangup reason
[\#1713](https://github.com/matrix-org/matrix-js-sdk/pull/1713)
* 👕 New linting rules
[\#1688](https://github.com/matrix-org/matrix-js-sdk/pull/1688)
* Emit relations created when target event added later
[\#1710](https://github.com/matrix-org/matrix-js-sdk/pull/1710)
* Bump libolm version and update package name.
[\#1705](https://github.com/matrix-org/matrix-js-sdk/pull/1705)
* Fix uploadContent not rejecting promise when http status code >= 400
[\#1703](https://github.com/matrix-org/matrix-js-sdk/pull/1703)
* Reduce noise in tests
[\#1702](https://github.com/matrix-org/matrix-js-sdk/pull/1702)
* Only log once if a Room lacks an m.room.create event
[\#1700](https://github.com/matrix-org/matrix-js-sdk/pull/1700)
* Cache normalized room name
[\#1701](https://github.com/matrix-org/matrix-js-sdk/pull/1701)
* Change call event handlers to adapt to undecrypted events
[\#1698](https://github.com/matrix-org/matrix-js-sdk/pull/1698)
Changes in [11.1.0](https://github.com/matrix-org/matrix-js-sdk/releases/tag/v11.1.0) (2021-05-24)
==================================================================================================
[Full Changelog](https://github.com/matrix-org/matrix-js-sdk/compare/v11.1.0-rc.1...v11.1.0)
* [Release] Bump libolm version and update package name
[\#1707](https://github.com/matrix-org/matrix-js-sdk/pull/1707)
* [Release] Change call event handlers to adapt to undecrypted events
[\#1699](https://github.com/matrix-org/matrix-js-sdk/pull/1699)
Changes in [11.1.0-rc.1](https://github.com/matrix-org/matrix-js-sdk/releases/tag/v11.1.0-rc.1) (2021-05-19)
============================================================================================================
[Full Changelog](https://github.com/matrix-org/matrix-js-sdk/compare/v11.0.0...v11.1.0-rc.1)
* Fix regressed glare
[\#1690](https://github.com/matrix-org/matrix-js-sdk/pull/1690)
* Add m.reaction to EventType enum
[\#1692](https://github.com/matrix-org/matrix-js-sdk/pull/1692)
* Prioritise and reduce the amount of events decrypted on application startup
[\#1684](https://github.com/matrix-org/matrix-js-sdk/pull/1684)
* Decrypt relations before applying them to target event
[\#1696](https://github.com/matrix-org/matrix-js-sdk/pull/1696)
* Guard against duplicates in `Relations` model
Changes in [11.0.0](https://github.com/matrix-org/matrix-js-sdk/releases/tag/v11.0.0) (2021-05-17)
==================================================================================================
[Full Changelog](https://github.com/matrix-org/matrix-js-sdk/compare/v11.0.0-rc.1...v11.0.0)
* [Release] Fix regressed glare
[\#1695](https://github.com/matrix-org/matrix-js-sdk/pull/1695)
Changes in [11.0.0-rc.1](https://github.com/matrix-org/matrix-js-sdk/releases/tag/v11.0.0-rc.1) (2021-05-11)
============================================================================================================
[Full Changelog](https://github.com/matrix-org/matrix-js-sdk/compare/v10.1.0...v11.0.0-rc.1)
BREAKING CHANGES
---
* `MatrixCall` and related APIs have been redesigned to support multiple streams
(see [\#1660](https://github.com/matrix-org/matrix-js-sdk/pull/1660) for more details)
All changes
---
* Switch from MSC1772 unstable prefixes to stable
[\#1679](https://github.com/matrix-org/matrix-js-sdk/pull/1679)
* Update the VoIP example to work with the new changes
[\#1680](https://github.com/matrix-org/matrix-js-sdk/pull/1680)
* Bump hosted-git-info from 2.8.8 to 2.8.9
[\#1687](https://github.com/matrix-org/matrix-js-sdk/pull/1687)
* Support for multiple streams (not MSC3077)
[\#1660](https://github.com/matrix-org/matrix-js-sdk/pull/1660)
* Tweak missing m.room.create errors to describe their source
[\#1683](https://github.com/matrix-org/matrix-js-sdk/pull/1683)
Changes in [10.1.0](https://github.com/matrix-org/matrix-js-sdk/releases/tag/v10.1.0) (2021-05-10)
==================================================================================================
[Full Changelog](https://github.com/matrix-org/matrix-js-sdk/compare/v10.1.0-rc.1...v10.1.0)
* No changes since rc.1
Changes in [10.1.0-rc.1](https://github.com/matrix-org/matrix-js-sdk/releases/tag/v10.1.0-rc.1) (2021-05-04)
============================================================================================================
[Full Changelog](https://github.com/matrix-org/matrix-js-sdk/compare/v10.0.0...v10.1.0-rc.1)
* Revert "Raise logging dramatically to chase pending event errors"
[\#1681](https://github.com/matrix-org/matrix-js-sdk/pull/1681)
* Add test coverage collection script
[\#1677](https://github.com/matrix-org/matrix-js-sdk/pull/1677)
* Raise logging dramatically to chase pending event errors
[\#1678](https://github.com/matrix-org/matrix-js-sdk/pull/1678)
* Support MSC3086 asserted identity
[\#1674](https://github.com/matrix-org/matrix-js-sdk/pull/1674)
* Fix `/search` with no results field work again
[\#1670](https://github.com/matrix-org/matrix-js-sdk/pull/1670)
* Add room.getMembers method
[\#1672](https://github.com/matrix-org/matrix-js-sdk/pull/1672)
Changes in [10.0.0](https://github.com/matrix-org/matrix-js-sdk/releases/tag/v10.0.0) (2021-04-26)
==================================================================================================
[Full Changelog](https://github.com/matrix-org/matrix-js-sdk/compare/v10.0.0-rc.1...v10.0.0)
* No changes since rc.1
Changes in [10.0.0-rc.1](https://github.com/matrix-org/matrix-js-sdk/releases/tag/v10.0.0-rc.1) (2021-04-21)
============================================================================================================
[Full Changelog](https://github.com/matrix-org/matrix-js-sdk/compare/v9.11.0...v10.0.0-rc.1)
BREAKING CHANGES
---
* The `RoomState.members` event is now only emitted when the room member's power level or the room's normal power level actually changes
All changes
---
* Restrict event emit for room members that had power levels changed
[\#1675](https://github.com/matrix-org/matrix-js-sdk/pull/1675)
* Fix sync with misconfigured push rules
[\#1669](https://github.com/matrix-org/matrix-js-sdk/pull/1669)
* Add missing await
[\#1665](https://github.com/matrix-org/matrix-js-sdk/pull/1665)
* Migrate to `eslint-plugin-matrix-org`
[\#1642](https://github.com/matrix-org/matrix-js-sdk/pull/1642)
* Add missing event type enum for key verification done
[\#1664](https://github.com/matrix-org/matrix-js-sdk/pull/1664)
* Fix timeline jumpiness by setting correct txnId
[\#1663](https://github.com/matrix-org/matrix-js-sdk/pull/1663)
* Fix calling addEventListener if it does not exist
[\#1661](https://github.com/matrix-org/matrix-js-sdk/pull/1661)
* Persist unsent messages for subsequent sessions
[\#1655](https://github.com/matrix-org/matrix-js-sdk/pull/1655)
Changes in [9.11.0](https://github.com/matrix-org/matrix-js-sdk/releases/tag/v9.11.0) (2021-04-12)
==================================================================================================
[Full Changelog](https://github.com/matrix-org/matrix-js-sdk/compare/v9.11.0-rc.1...v9.11.0)
* No changes since rc.1
Changes in [9.11.0-rc.1](https://github.com/matrix-org/matrix-js-sdk/releases/tag/v9.11.0-rc.1) (2021-04-07)
============================================================================================================
[Full Changelog](https://github.com/matrix-org/matrix-js-sdk/compare/v9.10.0...v9.11.0-rc.1)
* Only try to cache private keys we know exist
[\#1657](https://github.com/matrix-org/matrix-js-sdk/pull/1657)
* Properly terminate screen-share calls if NoUserMedia
[\#1654](https://github.com/matrix-org/matrix-js-sdk/pull/1654)
* Attended transfer
[\#1652](https://github.com/matrix-org/matrix-js-sdk/pull/1652)
* Remove catch handlers in private key retrieval
[\#1653](https://github.com/matrix-org/matrix-js-sdk/pull/1653)
* Fixed the media fail error on caller's side
[\#1651](https://github.com/matrix-org/matrix-js-sdk/pull/1651)
* Add function to share megolm keys for historical messages, take 2
[\#1640](https://github.com/matrix-org/matrix-js-sdk/pull/1640)
* Cache cross-signing private keys if needed on bootstrap
[\#1649](https://github.com/matrix-org/matrix-js-sdk/pull/1649)
Changes in [9.10.0](https://github.com/matrix-org/matrix-js-sdk/releases/tag/v9.10.0) (2021-03-29)
==================================================================================================
[Full Changelog](https://github.com/matrix-org/matrix-js-sdk/compare/v9.10.0-rc.1...v9.10.0)
* No changes since rc.1
Changes in [9.10.0-rc.1](https://github.com/matrix-org/matrix-js-sdk/releases/tag/v9.10.0-rc.1) (2021-03-25)
============================================================================================================
[Full Changelog](https://github.com/matrix-org/matrix-js-sdk/compare/v9.9.0...v9.10.0-rc.1)
* Don't send m.call.hangup if m.call.invite wasn't sent either
[\#1647](https://github.com/matrix-org/matrix-js-sdk/pull/1647)
* docs: registerGuest()
[\#1641](https://github.com/matrix-org/matrix-js-sdk/pull/1641)
* Download device keys in chunks of 250
[\#1639](https://github.com/matrix-org/matrix-js-sdk/pull/1639)
* More VoIP connectivity fixes
[\#1646](https://github.com/matrix-org/matrix-js-sdk/pull/1646)
* Make selectDesktopCapturerSource param optional
[\#1644](https://github.com/matrix-org/matrix-js-sdk/pull/1644)
* Expose APIs needed for reworked cross-signing login flow
[\#1632](https://github.com/matrix-org/matrix-js-sdk/pull/1632)
Changes in [9.9.0](https://github.com/matrix-org/matrix-js-sdk/releases/tag/v9.9.0) (2021-03-15)
================================================================================================
[Full Changelog](https://github.com/matrix-org/matrix-js-sdk/compare/v9.9.0-rc.1...v9.9.0)
+18 -4
View File
@@ -31,6 +31,23 @@ function addListeners(call) {
call.hangup();
disableButtons(false, true, true);
});
call.on("feeds_changed", function(feeds) {
const localFeed = feeds.find((feed) => feed.isLocal());
const remoteFeed = feeds.find((feed) => !feed.isLocal());
const remoteElement = document.getElementById("remote");
const localElement = document.getElementById("local");
if (remoteFeed) {
remoteElement.srcObject = remoteFeed.stream;
remoteElement.play();
}
if (localFeed) {
localElement.muted = true;
localElement.srcObject = localFeed.stream;
localElement.play();
}
});
}
window.onload = function() {
@@ -62,10 +79,7 @@ function syncComplete() {
);
console.log("Call => %s", call);
addListeners(call);
call.placeVideoCall(
document.getElementById("remote"),
document.getElementById("local")
);
call.placeVideoCall();
document.getElementById("result").innerHTML = "<p>Placed call.</p>";
disableButtons(true, true, false);
};
+21 -13
View File
@@ -1,26 +1,34 @@
<html>
<head>
<title>VoIP Test</title>
<script src="lib/matrix.js"></script>
<script src="browserTest.js"></script>
<title>VoIP Test</title>
<script src="lib/matrix.js"></script>
<script src="browserTest.js"></script>
</head>
<body>
You can place and receive calls with this example. Make sure to edit the
You can place and receive calls with this example. Make sure to edit the
constants in <code>browserTest.js</code> first.
<div id="config"></div>
<div id="result"></div>
<button id="call">Place Call</button>
<button id="answer">Answer Call</button>
<button id="hangup">Hangup Call</button>
<div id="videoBackground">
<div id="videoContainer">
<video id="remote"></video>
</div>
</div>
<div id="videoBackground">
<div id="videoContainer">
<video id="local"></video>
</div>
<div id="videoBackground" class="video-background">
<video class="video-element" id="local"></video>
<video class="video-element" id="remote"></video>
</div>
</body>
</html>
<style>
.video-background {
height: 500px;
margin: 10px;
}
.video-element {
height: 100%;
}
</style>
+21 -8
View File
@@ -1,6 +1,6 @@
{
"name": "matrix-js-sdk",
"version": "9.9.0",
"version": "11.2.0-rc.1",
"description": "Matrix Client-Server SDK for Javascript",
"scripts": {
"prepublishOnly": "yarn build",
@@ -17,8 +17,9 @@
"lint": "yarn lint:types && yarn lint:js",
"lint:js": "eslint --max-warnings 72 src spec",
"lint:types": "tsc --noEmit",
"test": "jest spec/ --coverage --testEnvironment node",
"test:watch": "jest spec/ --coverage --testEnvironment node --watch"
"test": "jest",
"test:watch": "jest --watch",
"coverage": "yarn test --coverage"
},
"repository": {
"type": "git",
@@ -61,6 +62,8 @@
"devDependencies": {
"@babel/cli": "^7.12.10",
"@babel/core": "^7.12.10",
"@babel/eslint-parser": "^7.12.10",
"@babel/eslint-plugin": "^7.12.10",
"@babel/plugin-proposal-class-properties": "^7.12.1",
"@babel/plugin-proposal-numeric-separator": "^7.12.7",
"@babel/plugin-proposal-object-rest-spread": "^7.12.1",
@@ -69,32 +72,42 @@
"@babel/preset-env": "^7.12.11",
"@babel/preset-typescript": "^7.12.7",
"@babel/register": "^7.12.10",
"@matrix-org/olm": "https://gitlab.matrix.org/api/v4/projects/27/packages/npm/@matrix-org/olm/-/@matrix-org/olm-3.2.3.tgz",
"@types/jest": "^26.0.20",
"@types/node": "12",
"@types/request": "^2.48.5",
"babel-eslint": "^10.1.0",
"@typescript-eslint/eslint-plugin": "^4.17.0",
"@typescript-eslint/parser": "^4.17.0",
"babel-jest": "^26.6.3",
"babelify": "^10.0.0",
"better-docs": "^2.3.2",
"browserify": "^17.0.0",
"docdash": "^1.2.0",
"eslint": "7.18.0",
"eslint-config-matrix-org": "^0.2.0",
"eslint-plugin-babel": "^5.3.1",
"eslint-config-google": "^0.14.0",
"eslint-plugin-matrix-org": "github:matrix-org/eslint-plugin-matrix-org#main",
"exorcist": "^1.0.1",
"fake-indexeddb": "^3.1.2",
"jest": "^26.6.3",
"jest-localstorage-mock": "^2.4.6",
"jsdoc": "^3.6.6",
"matrix-mock-request": "^1.2.3",
"olm": "https://packages.matrix.org/npm/olm/olm-3.2.1.tgz",
"rimraf": "^3.0.2",
"terser": "^5.5.1",
"tsify": "^5.0.2",
"typescript": "^4.1.3"
},
"jest": {
"testEnvironment": "node"
"testEnvironment": "node",
"testMatch": [
"<rootDir>/spec/**/*.spec.{js,ts}"
],
"collectCoverageFrom": [
"<rootDir>/src/**/*.{js,ts}"
],
"coverageReporters": [
"text"
]
},
"typings": "./lib/index.d.ts"
}
+11 -14
View File
@@ -20,12 +20,12 @@ limitations under the License.
import './olm-loader';
import MockHttpBackend from 'matrix-mock-request';
import {LocalStorageCryptoStore} from '../src/crypto/store/localStorage-crypto-store';
import {logger} from '../src/logger';
import {WebStorageSessionStore} from "../src/store/session/webstorage";
import {syncPromise} from "./test-utils";
import {createClient} from "../src/matrix";
import {MockStorageApi} from "./MockStorageApi";
import { LocalStorageCryptoStore } from '../src/crypto/store/localStorage-crypto-store';
import { logger } from '../src/logger';
import { WebStorageSessionStore } from "../src/store/session/webstorage";
import { syncPromise } from "./test-utils";
import { createClient } from "../src/matrix";
import { MockStorageApi } from "./MockStorageApi";
/**
* Wrapper for a MockStorageApi, MockHttpBackend and MatrixClient
@@ -129,11 +129,10 @@ TestClient.prototype.expectDeviceKeyUpload = function() {
expect(Object.keys(self.oneTimeKeys).length).toEqual(0);
self.deviceKeys = content.device_keys;
return {one_time_key_counts: {signed_curve25519: 0}};
return { one_time_key_counts: { signed_curve25519: 0 } };
});
};
/**
* If one-time keys have already been uploaded, return them. Otherwise,
* set up an expectation that the keys will be uploaded, and wait for
@@ -151,9 +150,9 @@ TestClient.prototype.awaitOneTimeKeyUpload = function() {
.respond(200, (path, content) => {
expect(content.device_keys).toBe(undefined);
expect(content.one_time_keys).toBe(undefined);
return {one_time_key_counts: {
return { one_time_key_counts: {
signed_curve25519: Object.keys(this.oneTimeKeys).length,
}};
} };
});
this.httpBackend.when("POST", "/keys/upload")
@@ -164,9 +163,9 @@ TestClient.prototype.awaitOneTimeKeyUpload = function() {
logger.log('%s: received %i one-time keys', this,
Object.keys(content.one_time_keys).length);
this.oneTimeKeys = content.one_time_keys;
return {one_time_key_counts: {
return { one_time_key_counts: {
signed_curve25519: Object.keys(this.oneTimeKeys).length,
}};
} };
});
// this can take ages
@@ -197,7 +196,6 @@ TestClient.prototype.expectKeyQuery = function(response) {
});
};
/**
* get the uploaded curve25519 device key
*
@@ -208,7 +206,6 @@ TestClient.prototype.getDeviceKey = function() {
return this.deviceKeys.keys[keyId];
};
/**
* get the uploaded ed25519 device key
*
+4 -4
View File
@@ -17,10 +17,10 @@ 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 { 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 { LocalStorageCryptoStore } from "../../src/crypto/store/localStorage-crypto-store";
import * as utils from "../test-utils";
const USER_ID = "@user:test.server";
@@ -58,7 +58,7 @@ describe("Browserify Test", function() {
}
beforeEach(async () => {
({client, httpBackend} = await createTestClient());
({ client, httpBackend } = await createTestClient());
await client.startClient();
});
+7 -10
View File
@@ -16,9 +16,9 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
import {TestClient} from '../TestClient';
import { TestClient } from '../TestClient';
import * as testUtils from '../test-utils';
import {logger} from '../../src/logger';
import { logger } from '../../src/logger';
const ROOM_ID = "!room:id";
@@ -67,7 +67,6 @@ function getSyncResponse(roomMembers) {
return syncResponse;
}
describe("DeviceList management:", function() {
if (!global.Olm) {
logger.warn('not running deviceList tests: Olm not present');
@@ -98,7 +97,7 @@ describe("DeviceList management:", function() {
});
it("Alice shouldn't do a second /query for non-e2e-capable devices", function() {
aliceTestClient.expectKeyQuery({device_keys: {'@alice:localhost': {}}});
aliceTestClient.expectKeyQuery({ device_keys: { '@alice:localhost': {} } });
return aliceTestClient.start().then(function() {
const syncResponse = getSyncResponse(['@bob:xyz']);
aliceTestClient.httpBackend.when('GET', '/sync').respond(200, syncResponse);
@@ -137,11 +136,10 @@ describe("DeviceList management:", function() {
});
});
it("We should not get confused by out-of-order device query responses",
() => {
// https://github.com/vector-im/element-web/issues/3126
aliceTestClient.expectKeyQuery({device_keys: {'@alice:localhost': {}}});
aliceTestClient.expectKeyQuery({ device_keys: { '@alice:localhost': {} } });
return aliceTestClient.start().then(() => {
aliceTestClient.httpBackend.when('GET', '/sync').respond(
200, getSyncResponse(['@bob:xyz', '@chris:abc']));
@@ -160,7 +158,7 @@ describe("DeviceList management:", function() {
);
aliceTestClient.httpBackend.when('PUT', '/send/').respond(
200, {event_id: '$event1'});
200, { event_id: '$event1' });
return Promise.all([
aliceTestClient.client.sendTextMessage(ROOM_ID, 'test'),
@@ -199,7 +197,7 @@ describe("DeviceList management:", function() {
},
token: '3',
}).respond(200, {
device_keys: {'@chris:abc': {}},
device_keys: { '@chris:abc': {} },
});
return aliceTestClient.httpBackend.flush('/keys/query', 1);
}).then((flushed) => {
@@ -228,7 +226,7 @@ describe("DeviceList management:", function() {
},
token: '2',
}).respond(200, {
device_keys: {'@bob:xyz': {}},
device_keys: { '@bob:xyz': {} },
});
return aliceTestClient.httpBackend.flush('/keys/query', 1);
}).then((flushed) => {
@@ -323,7 +321,6 @@ describe("DeviceList management:", function() {
},
);
await aliceTestClient.flushSync();
await aliceTestClient.client._crypto._deviceList.saveIfDirty();
+19 -24
View File
@@ -28,11 +28,10 @@ limitations under the License.
// load olm before the sdk if possible
import '../olm-loader';
import {logger} from '../../src/logger';
import { logger } from '../../src/logger';
import * as testUtils from "../test-utils";
import * as utils from "../../src/utils";
import {TestClient} from "../TestClient";
import {CRYPTO_ENABLED} from "../../src/client";
import { TestClient } from "../TestClient";
import { CRYPTO_ENABLED } from "../../src/client";
let aliTestClient;
const roomId = "!room:localhost";
@@ -76,7 +75,7 @@ function expectAliQueryKeys() {
);
const result = {};
result[bobUserId] = bobKeys;
return {device_keys: result};
return { device_keys: result };
});
return aliTestClient.httpBackend.flush("/keys/query", 1);
}
@@ -104,7 +103,7 @@ function expectBobQueryKeys() {
);
const result = {};
result[aliUserId] = aliKeys;
return {device_keys: result};
return { device_keys: result };
});
return bobTestClient.httpBackend.flush("/keys/query", 1);
}
@@ -133,7 +132,7 @@ function expectAliClaimKeys() {
result[bobUserId] = {};
result[bobUserId][bobDeviceId] = {};
result[bobUserId][bobDeviceId][keyId] = keys[keyId];
return {one_time_keys: result};
return { one_time_keys: result };
});
}).then(() => {
// it can take a while to process the key query, so give it some extra
@@ -145,7 +144,6 @@ function expectAliClaimKeys() {
});
}
function aliDownloadsKeys() {
// can't query keys before bob has uploaded them
expect(bobTestClient.getSigningKey()).toBeTruthy();
@@ -244,7 +242,7 @@ function bobSendsReplyMessage() {
function expectAliSendMessageRequest() {
return expectSendMessageRequest(aliTestClient.httpBackend).then(function(content) {
aliMessages.push(content);
expect(utils.keys(content.ciphertext)).toEqual([bobTestClient.getDeviceKey()]);
expect(Object.keys(content.ciphertext)).toEqual([bobTestClient.getDeviceKey()]);
const ciphertext = content.ciphertext[bobTestClient.getDeviceKey()];
expect(ciphertext).toBeTruthy();
return ciphertext;
@@ -261,7 +259,7 @@ function expectBobSendMessageRequest() {
bobMessages.push(content);
const aliKeyId = "curve25519:" + aliDeviceId;
const aliDeviceCurve25519Key = aliTestClient.deviceKeys.keys[aliKeyId];
expect(utils.keys(content.ciphertext)).toEqual([aliDeviceCurve25519Key]);
expect(Object.keys(content.ciphertext)).toEqual([aliDeviceCurve25519Key]);
const ciphertext = content.ciphertext[aliDeviceCurve25519Key];
expect(ciphertext).toBeTruthy();
return ciphertext;
@@ -270,7 +268,7 @@ function expectBobSendMessageRequest() {
function sendMessage(client) {
return client.sendMessage(
roomId, {msgtype: "m.text", body: "Hello, World"},
roomId, { msgtype: "m.text", body: "Hello, World" },
);
}
@@ -358,7 +356,6 @@ function recvMessage(httpBackend, client, sender, message) {
});
}
/**
* Send an initial sync response to the client (which just includes the member
* list for our test room).
@@ -396,7 +393,6 @@ function firstSync(testClient) {
return testClient.flushSync();
}
describe("MatrixClient crypto", function() {
if (!CRYPTO_ENABLED) {
return;
@@ -478,7 +474,7 @@ describe("MatrixClient crypto", function() {
).respond(200, function(path, content) {
const result = {};
result[bobUserId] = bobKeys;
return {device_keys: result};
return { device_keys: result };
});
return Promise.all([
@@ -520,7 +516,7 @@ describe("MatrixClient crypto", function() {
).respond(200, function(path, content) {
const result = {};
result[bobUserId] = bobKeys;
return {device_keys: result};
return { device_keys: result };
});
return Promise.all([
@@ -534,7 +530,6 @@ describe("MatrixClient crypto", function() {
});
});
it("Bob starts his client and uploads device keys and one-time keys", function() {
return Promise.resolve()
.then(() => bobTestClient.start())
@@ -546,7 +541,7 @@ describe("MatrixClient crypto", function() {
});
it("Ali sends a message", function() {
aliTestClient.expectKeyQuery({device_keys: {[aliUserId]: {}}});
aliTestClient.expectKeyQuery({ device_keys: { [aliUserId]: {} } });
return Promise.resolve()
.then(() => aliTestClient.start())
.then(() => bobTestClient.start())
@@ -556,7 +551,7 @@ describe("MatrixClient crypto", function() {
});
it("Bob receives a message", function() {
aliTestClient.expectKeyQuery({device_keys: {[aliUserId]: {}}});
aliTestClient.expectKeyQuery({ device_keys: { [aliUserId]: {} } });
return Promise.resolve()
.then(() => aliTestClient.start())
.then(() => bobTestClient.start())
@@ -567,7 +562,7 @@ describe("MatrixClient crypto", function() {
});
it("Bob receives a message with a bogus sender", function() {
aliTestClient.expectKeyQuery({device_keys: {[aliUserId]: {}}});
aliTestClient.expectKeyQuery({ device_keys: { [aliUserId]: {} } });
return Promise.resolve()
.then(() => aliTestClient.start())
.then(() => bobTestClient.start())
@@ -621,7 +616,7 @@ describe("MatrixClient crypto", function() {
});
it("Ali blocks Bob's device", function() {
aliTestClient.expectKeyQuery({device_keys: {[aliUserId]: {}}});
aliTestClient.expectKeyQuery({ device_keys: { [aliUserId]: {} } });
return Promise.resolve()
.then(() => aliTestClient.start())
.then(() => bobTestClient.start())
@@ -641,7 +636,7 @@ describe("MatrixClient crypto", function() {
});
it("Bob receives two pre-key messages", function() {
aliTestClient.expectKeyQuery({device_keys: {[aliUserId]: {}}});
aliTestClient.expectKeyQuery({ device_keys: { [aliUserId]: {} } });
return Promise.resolve()
.then(() => aliTestClient.start())
.then(() => bobTestClient.start())
@@ -654,8 +649,8 @@ describe("MatrixClient crypto", function() {
});
it("Bob replies to the message", function() {
aliTestClient.expectKeyQuery({device_keys: {[aliUserId]: {}}});
bobTestClient.expectKeyQuery({device_keys: {[bobUserId]: {}}});
aliTestClient.expectKeyQuery({ device_keys: { [aliUserId]: {} } });
bobTestClient.expectKeyQuery({ device_keys: { [bobUserId]: {} } });
return Promise.resolve()
.then(() => aliTestClient.start())
.then(() => bobTestClient.start())
@@ -673,7 +668,7 @@ describe("MatrixClient crypto", function() {
it("Ali does a key query when encryption is enabled", function() {
// enabling encryption in the room should make alice download devices
// for both members.
aliTestClient.expectKeyQuery({device_keys: {[aliUserId]: {}}});
aliTestClient.expectKeyQuery({ device_keys: { [aliUserId]: {} } });
return Promise.resolve()
.then(() => aliTestClient.start())
.then(() => firstSync(aliTestClient))
@@ -1,5 +1,5 @@
import * as utils from "../test-utils";
import {TestClient} from "../TestClient";
import { TestClient } from "../TestClient";
describe("MatrixClient events", function() {
let client;
@@ -1,7 +1,7 @@
import * as utils from "../test-utils";
import {EventTimeline} from "../../src/matrix";
import {logger} from "../../src/logger";
import {TestClient} from "../TestClient";
import { EventTimeline } from "../../src/matrix";
import { logger } from "../../src/logger";
import { TestClient } from "../TestClient";
const userId = "@alice:localhost";
const userName = "Alice";
@@ -127,7 +127,7 @@ describe("getEventTimeline support", function() {
"DEVICE",
accessToken,
undefined,
{timelineSupport: true},
{ timelineSupport: true },
);
client = testClient.client;
httpBackend = testClient.httpBackend;
@@ -141,7 +141,6 @@ describe("getEventTimeline support", function() {
});
});
it("scrollback should be able to scroll back to before a gappy /sync",
function() {
// need a client with timelineSupport disabled to make this work
@@ -218,7 +217,7 @@ describe("MatrixClient event timelines", function() {
"DEVICE",
accessToken,
undefined,
{timelineSupport: true},
{ timelineSupport: true },
);
client = testClient.client;
httpBackend = testClient.httpBackend;
@@ -516,7 +515,7 @@ describe("MatrixClient event timelines", function() {
client.getEventTimeline(timelineSet, EVENTS[0].event_id,
).then(function(tl0) {
tl = tl0;
return client.paginateEventTimeline(tl, {backwards: true});
return client.paginateEventTimeline(tl, { backwards: true });
}).then(function(success) {
expect(success).toBeTruthy();
expect(tl.getEvents().length).toEqual(3);
@@ -532,7 +531,6 @@ describe("MatrixClient event timelines", function() {
]);
});
it("should allow you to paginate forwards", function() {
const room = client.getRoom(roomId);
const timelineSet = room.getTimelineSets()[0];
@@ -569,7 +567,7 @@ describe("MatrixClient event timelines", function() {
).then(function(tl0) {
tl = tl0;
return client.paginateEventTimeline(
tl, {backwards: false, limit: 20});
tl, { backwards: false, limit: 20 });
}).then(function(success) {
expect(success).toBeTruthy();
expect(tl.getEvents().length).toEqual(3);
@@ -591,7 +589,7 @@ describe("MatrixClient event timelines", function() {
const event = utils.mkMessage({
room: roomId, user: userId, msg: "a body",
});
event.unsigned = {transaction_id: TXN_ID};
event.unsigned = { transaction_id: TXN_ID };
beforeEach(function() {
// set up handlers for both the message send, and the
@@ -680,7 +678,6 @@ describe("MatrixClient event timelines", function() {
});
});
it("should handle gappy syncs after redactions", function() {
// https://github.com/vector-im/vector-web/issues/1389
+7 -8
View File
@@ -1,7 +1,7 @@
import * as utils from "../test-utils";
import {CRYPTO_ENABLED} from "../../src/client";
import {Filter, MemoryStore, Room} from "../../src/matrix";
import {TestClient} from "../TestClient";
import { CRYPTO_ENABLED } from "../../src/client";
import { Filter, MemoryStore, Room } from "../../src/matrix";
import { TestClient } from "../TestClient";
describe("MatrixClient", function() {
let client = null;
@@ -285,7 +285,6 @@ describe("MatrixClient", function() {
});
});
describe("downloadKeys", function() {
if (!CRYPTO_ENABLED) {
return;
@@ -346,10 +345,10 @@ describe("MatrixClient", function() {
*/
httpBackend.when("POST", "/keys/query").check(function(req) {
expect(req.data).toEqual({device_keys: {
expect(req.data).toEqual({ device_keys: {
'boris': [],
'chaz': [],
}});
} });
}).respond(200, {
device_keys: {
boris: borisKeys,
@@ -379,12 +378,12 @@ describe("MatrixClient", function() {
});
describe("deleteDevice", function() {
const auth = {a: 1};
const auth = { a: 1 };
it("should pass through an auth dict", function() {
httpBackend.when(
"DELETE", "/_matrix/client/r0/devices/my_device",
).check(function(req) {
expect(req.data).toEqual({auth: auth});
expect(req.data).toEqual({ auth: auth });
}).respond(200);
const prom = client.deleteDevice("my_device", auth);
+4 -4
View File
@@ -1,9 +1,9 @@
import * as utils from "../test-utils";
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";
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";
+5 -5
View File
@@ -1,7 +1,7 @@
import {EventStatus} from "../../src/matrix";
import {MatrixScheduler} from "../../src/scheduler";
import {Room} from "../../src/models/room";
import {TestClient} from "../TestClient";
import { EventStatus } from "../../src/matrix";
import { MatrixScheduler } from "../../src/scheduler";
import { Room } from "../../src/models/room";
import { TestClient } from "../TestClient";
describe("MatrixClient retrying", function() {
let client = null;
@@ -19,7 +19,7 @@ describe("MatrixClient retrying", function() {
"DEVICE",
accessToken,
undefined,
{scheduler},
{ scheduler },
);
httpBackend = testClient.httpBackend;
client = testClient.client;
+11 -12
View File
@@ -1,7 +1,6 @@
import * as utils from "../test-utils";
import {EventStatus} from "../../src/models/event";
import {TestClient} from "../TestClient";
import { EventStatus } from "../../src/models/event";
import { TestClient } from "../TestClient";
describe("MatrixClient room timelines", function() {
let client = null;
@@ -104,7 +103,7 @@ describe("MatrixClient room timelines", function() {
"DEVICE",
accessToken,
undefined,
{timelineSupport: true},
{ timelineSupport: true },
);
httpBackend = testClient.httpBackend;
client = testClient.client;
@@ -166,7 +165,7 @@ describe("MatrixClient room timelines", function() {
body: "I am a fish", user: userId, room: roomId,
});
ev.event_id = eventId;
ev.unsigned = {transaction_id: "txn1"};
ev.unsigned = { transaction_id: "txn1" };
setNextSyncData([ev]);
client.on("sync", function(state) {
@@ -198,7 +197,7 @@ describe("MatrixClient room timelines", function() {
body: "I am a fish", user: userId, room: roomId,
});
ev.event_id = eventId;
ev.unsigned = {transaction_id: "txn1"};
ev.unsigned = { transaction_id: "txn1" };
setNextSyncData([ev]);
client.on("sync", function(state) {
@@ -396,8 +395,8 @@ describe("MatrixClient room timelines", function() {
describe("new events", function() {
it("should be added to the right place in the timeline", function() {
const eventData = [
utils.mkMessage({user: userId, room: roomId}),
utils.mkMessage({user: userId, room: roomId}),
utils.mkMessage({ user: userId, room: roomId }),
utils.mkMessage({ user: userId, room: roomId }),
];
setNextSyncData(eventData);
@@ -434,11 +433,11 @@ describe("MatrixClient room timelines", function() {
it("should set the right event.sender values", function() {
const eventData = [
utils.mkMessage({user: userId, room: roomId}),
utils.mkMessage({ user: userId, room: roomId }),
utils.mkMembership({
user: userId, room: roomId, mship: "join", name: "New Name",
}),
utils.mkMessage({user: userId, room: roomId}),
utils.mkMessage({ user: userId, room: roomId }),
];
eventData[1].__prev_event = USER_MEMBERSHIP_EVENT;
setNextSyncData(eventData);
@@ -546,7 +545,7 @@ describe("MatrixClient room timelines", function() {
describe("gappy sync", function() {
it("should copy the last known state to the new timeline", function() {
const eventData = [
utils.mkMessage({user: userId, room: roomId}),
utils.mkMessage({ user: userId, room: roomId }),
];
setNextSyncData(eventData);
NEXT_SYNC_DATA.rooms.join[roomId].timeline.limited = true;
@@ -579,7 +578,7 @@ describe("MatrixClient room timelines", function() {
it("should emit a 'Room.timelineReset' event", function() {
const eventData = [
utils.mkMessage({user: userId, room: roomId}),
utils.mkMessage({ user: userId, room: roomId }),
];
setNextSyncData(eventData);
NEXT_SYNC_DATA.rooms.join[roomId].timeline.limited = true;
+5 -6
View File
@@ -1,7 +1,7 @@
import {MatrixEvent} from "../../src/models/event";
import {EventTimeline} from "../../src/models/event-timeline";
import { MatrixEvent } from "../../src/models/event";
import { EventTimeline } from "../../src/models/event-timeline";
import * as utils from "../test-utils";
import {TestClient} from "../TestClient";
import { TestClient } from "../TestClient";
describe("MatrixClient syncing", function() {
let client = null;
@@ -122,7 +122,6 @@ describe("MatrixClient syncing", function() {
resolveInvitesToProfiles: true,
});
return Promise.all([
httpBackend.flushAllExpected(),
awaitSyncEvent(),
@@ -677,8 +676,8 @@ describe("MatrixClient syncing", function() {
it("should create and use an appropriate filter", function() {
httpBackend.when("POST", "/filter").check(function(req) {
expect(req.data).toEqual({
room: { timeline: {limit: 1},
include_leave: true }});
room: { timeline: { limit: 1 },
include_leave: true } });
}).respond(200, { filter_id: "another_id" });
const prom = new Promise((resolve) => {
+14 -16
View File
@@ -16,10 +16,9 @@ limitations under the License.
*/
import anotherjson from "another-json";
import * as utils from "../../src/utils";
import * as testUtils from "../test-utils";
import {TestClient} from "../TestClient";
import {logger} from "../../src/logger";
import { TestClient } from "../TestClient";
import { logger } from "../../src/logger";
const ROOM_ID = "!room:id";
@@ -32,7 +31,7 @@ const ROOM_ID = "!room:id";
*/
function createOlmSession(olmAccount, recipientTestClient) {
return recipientTestClient.awaitOneTimeKeyUpload().then((keys) => {
const otkId = utils.keys(keys)[0];
const otkId = Object.keys(keys)[0];
const otk = keys[otkId];
const session = new global.Olm.Session();
@@ -197,7 +196,6 @@ function getSyncResponse(roomMembers) {
return syncResponse;
}
describe("megolm", function() {
if (!global.Olm) {
logger.warn('not running megolm tests: Olm not present');
@@ -257,7 +255,7 @@ describe("megolm", function() {
const testOneTimeKeys = JSON.parse(testOlmAccount.one_time_keys());
testOlmAccount.mark_keys_as_published();
const keyId = utils.keys(testOneTimeKeys.curve25519)[0];
const keyId = Object.keys(testOneTimeKeys.curve25519)[0];
const oneTimeKey = testOneTimeKeys.curve25519[keyId];
const keyResult = {
'key': oneTimeKey,
@@ -269,7 +267,7 @@ describe("megolm", function() {
'ed25519:DEVICE_ID': sig,
};
const claimResponse = {one_time_keys: {}};
const claimResponse = { one_time_keys: {} };
claimResponse.one_time_keys[userId] = {
'DEVICE_ID': {},
};
@@ -484,8 +482,9 @@ describe("megolm", function() {
return aliceTestClient.flushSync().then(() => {
return aliceTestClient.flushSync();
});
}).then(function() {
}).then(async function() {
const room = aliceTestClient.client.getRoom(ROOM_ID);
await room.decryptCriticalEvents();
const event = room.getLiveTimeline().getEvents()[0];
expect(event.getContent().body).toEqual('42');
});
@@ -494,7 +493,7 @@ describe("megolm", function() {
it('Alice sends a megolm message', function() {
let p2pSession;
aliceTestClient.expectKeyQuery({device_keys: {'@alice:localhost': {}}});
aliceTestClient.expectKeyQuery({ device_keys: { '@alice:localhost': {} } });
return aliceTestClient.start().then(() => {
// establish an olm session with alice
return createOlmSession(testOlmAccount, aliceTestClient);
@@ -577,7 +576,7 @@ describe("megolm", function() {
});
it("We shouldn't attempt to send to blocked devices", function() {
aliceTestClient.expectKeyQuery({device_keys: {'@alice:localhost': {}}});
aliceTestClient.expectKeyQuery({ device_keys: { '@alice:localhost': {} } });
return aliceTestClient.start().then(() => {
// establish an olm session with alice
return createOlmSession(testOlmAccount, aliceTestClient);
@@ -634,7 +633,7 @@ describe("megolm", function() {
let p2pSession;
let megolmSessionId;
aliceTestClient.expectKeyQuery({device_keys: {'@alice:localhost': {}}});
aliceTestClient.expectKeyQuery({ device_keys: { '@alice:localhost': {} } });
return aliceTestClient.start().then(() => {
// establish an olm session with alice
return createOlmSession(testOlmAccount, aliceTestClient);
@@ -841,13 +840,12 @@ describe("megolm", function() {
});
});
it('Alice should wait for device list to complete when sending a megolm message',
function() {
let downloadPromise;
let sendPromise;
aliceTestClient.expectKeyQuery({device_keys: {'@alice:localhost': {}}});
aliceTestClient.expectKeyQuery({ device_keys: { '@alice:localhost': {} } });
return aliceTestClient.start().then(() => {
// establish an olm session with alice
return createOlmSession(testOlmAccount, aliceTestClient);
@@ -887,11 +885,10 @@ describe("megolm", function() {
});
});
it("Alice exports megolm keys and imports them to a new device", function() {
let messageEncrypted;
aliceTestClient.expectKeyQuery({device_keys: {'@alice:localhost': {}}});
aliceTestClient.expectKeyQuery({ device_keys: { '@alice:localhost': {} } });
return aliceTestClient.start().then(() => {
// establish an olm session with alice
return createOlmSession(testOlmAccount, aliceTestClient);
@@ -933,8 +930,9 @@ describe("megolm", function() {
aliceTestClient.httpBackend.when("GET", "/sync").respond(200, syncResponse);
return aliceTestClient.flushSync();
}).then(function() {
}).then(async function() {
const room = aliceTestClient.client.getRoom(ROOM_ID);
await room.decryptCriticalEvents();
const event = room.getLiveTimeline().getEvents()[0];
expect(event.getContent().body).toEqual('42');
+2 -2
View File
@@ -15,12 +15,12 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
import {logger} from '../src/logger';
import { logger } from '../src/logger';
import * as utils from "../src/utils";
// try to load the olm library.
try {
global.Olm = require('olm');
global.Olm = require('@matrix-org/olm');
logger.log('loaded libolm');
} catch (e) {
logger.warn("unable to run crypto tests: libolm not available");
+15 -15
View File
@@ -1,8 +1,8 @@
// load olm before the sdk if possible
import './olm-loader';
import {logger} from '../src/logger';
import {MatrixEvent} from "../src/models/event";
import { logger } from '../src/logger';
import { MatrixEvent } from "../src/models/event";
/**
* Return a promise that is resolved when the client next emits a
@@ -177,7 +177,6 @@ export function mkMessage(opts) {
return mkEvent(opts);
}
/**
* A mock implementation of webstorage
*
@@ -204,7 +203,6 @@ MockStorageApi.prototype = {
},
};
/**
* If an event is being decrypted, wait for it to finish being decrypted.
*
@@ -212,21 +210,23 @@ MockStorageApi.prototype = {
* @returns {Promise} promise which resolves (to `event`) when the event has been decrypted
*/
export function awaitDecryption(event) {
if (!event.isBeingDecrypted()) {
return Promise.resolve(event);
}
// An event is not always decrypted ahead of time
// getClearContent is a good signal to know whether an event has been decrypted
// already
if (event.getClearContent() !== null) {
return event;
} else {
logger.log(`${Date.now()} event ${event.getId()} is being decrypted; waiting`);
logger.log(`${Date.now()} event ${event.getId()} is being decrypted; waiting`);
return new Promise((resolve, reject) => {
event.once('Event.decrypted', (ev) => {
logger.log(`${Date.now()} event ${event.getId()} now decrypted`);
resolve(ev);
return new Promise((resolve, reject) => {
event.once('Event.decrypted', (ev) => {
logger.log(`${Date.now()} event ${event.getId()} now decrypted`);
resolve(ev);
});
});
});
}
}
export function HttpResponse(
httpLookups, acceptKeepalives, ignoreUnhandledSync,
) {
+1 -1
View File
@@ -17,7 +17,7 @@ limitations under the License.
import MockHttpBackend from "matrix-mock-request";
import * as sdk from "../../src";
import {AutoDiscovery} from "../../src/autodiscovery";
import { AutoDiscovery } from "../../src/autodiscovery";
describe("AutoDiscovery", function() {
let httpBackend = null;
+1 -1
View File
@@ -1,4 +1,4 @@
import {getHttpUriForMxc} from "../../src/content-repo";
import { getHttpUriForMxc } from "../../src/content-repo";
describe("ContentRepo", function() {
const baseUrl = "https://my.home.server";
+12 -12
View File
@@ -1,16 +1,16 @@
import '../olm-loader';
import {Crypto} from "../../src/crypto";
import {WebStorageSessionStore} from "../../src/store/session/webstorage";
import {MemoryCryptoStore} from "../../src/crypto/store/memory-crypto-store";
import {MockStorageApi} from "../MockStorageApi";
import {TestClient} from "../TestClient";
import {MatrixEvent} from "../../src/models/event";
import {Room} from "../../src/models/room";
import { Crypto } from "../../src/crypto";
import { WebStorageSessionStore } from "../../src/store/session/webstorage";
import { MemoryCryptoStore } from "../../src/crypto/store/memory-crypto-store";
import { MockStorageApi } from "../MockStorageApi";
import { TestClient } from "../TestClient";
import { MatrixEvent } from "../../src/models/event";
import { Room } from "../../src/models/room";
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";
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;
@@ -46,7 +46,7 @@ describe("Crypto", function() {
// unknown sender (e.g. deleted device), forwarded megolm key (untrusted)
event.getSenderKey = () => 'YmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmI';
event.getWireContent = () => {return {algorithm: olmlib.MEGOLM_ALGORITHM};};
event.getWireContent = () => {return { algorithm: olmlib.MEGOLM_ALGORITHM };};
event.getForwardingCurve25519KeyChain = () => ["not empty"];
event.isKeySourceUntrusted = () => false;
event.getClaimedEd25519Key =
+4 -4
View File
@@ -22,11 +22,11 @@ import {
import {
IndexedDBCryptoStore,
} from '../../../src/crypto/store/indexeddb-crypto-store';
import {MemoryCryptoStore} from '../../../src/crypto/store/memory-crypto-store';
import { MemoryCryptoStore } from '../../../src/crypto/store/memory-crypto-store';
import 'fake-indexeddb/auto';
import 'jest-localstorage-mock';
import {OlmDevice} from "../../../src/crypto/OlmDevice";
import {logger} from '../../../src/logger';
import { OlmDevice } from "../../../src/crypto/OlmDevice";
import { logger } from '../../../src/logger';
const userId = "@alice:example.com";
@@ -66,7 +66,7 @@ describe("CrossSigningInfo.getCrossSigningKey", function() {
});
it.each(types)("should throw if the callback returns falsey",
async ({type, shouldCache}) => {
async ({ type, shouldCache }) => {
const info = new CrossSigningInfo(userId, {
getCrossSigningKey: () => false,
});
+61 -5
View File
@@ -16,10 +16,10 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
import {logger} from "../../../src/logger";
import { logger } from "../../../src/logger";
import * as utils from "../../../src/utils";
import {MemoryCryptoStore} from "../../../src/crypto/store/memory-crypto-store";
import {DeviceList} from "../../../src/crypto/DeviceList";
import { MemoryCryptoStore } from "../../../src/crypto/store/memory-crypto-store";
import { DeviceList } from "../../../src/crypto/DeviceList";
const signedDeviceList = {
"failures": {},
@@ -51,6 +51,36 @@ const signedDeviceList = {
},
};
const signedDeviceList2 = {
"failures": {},
"device_keys": {
"@test2:sw1v.org": {
"QJVRHWAKGH": {
"signatures": {
"@test2:sw1v.org": {
"ed25519:QJVRHWAKGH":
"w1xxdLe1iIqzEFHLRVYQeuiM6t2N2ZRiI8s5nDKxf054BP8" +
"1CPEX/AQXh5BhkKAVMlKnwg4T9zU1/wBALeajk3",
},
},
"user_id": "@test2:sw1v.org",
"keys": {
"ed25519:QJVRHWAKGH":
"Ig0/C6T+bBII1l2By2Wnnvtjp1nm/iXBlLU5/QESFXL",
"curve25519:QJVRHWAKGH":
"YR3eQnUvTQzGlWih4rsmJkKxpDxzgkgIgsBd1DEZIbm",
},
"algorithms": [
"m.olm.v1.curve25519-aes-sha2",
"m.megolm.v1.aes-sha2",
],
"device_id": "QJVRHWAKGH",
"unsigned": {},
},
},
},
};
describe('DeviceList', function() {
let downloadSpy;
let cryptoStore;
@@ -69,7 +99,7 @@ describe('DeviceList', function() {
}
});
function createTestDeviceList() {
function createTestDeviceList(keyDownloadChunkSize = 250) {
const baseApis = {
downloadKeysForUsers: downloadSpy,
getUserId: () => '@test1:sw1v.org',
@@ -78,7 +108,7 @@ describe('DeviceList', function() {
const mockOlm = {
verifySignature: function(key, message, signature) {},
};
const dl = new DeviceList(baseApis, cryptoStore, mockOlm);
const dl = new DeviceList(baseApis, cryptoStore, mockOlm, keyDownloadChunkSize);
deviceLists.push(dl);
return dl;
}
@@ -150,4 +180,30 @@ describe('DeviceList', function() {
expect(Object.keys(storedKeys)).toEqual(['HGKAWHRVJQ']);
});
});
it("should download device keys in batches", function() {
const dl = createTestDeviceList(1);
dl.startTrackingDeviceList('@test1:sw1v.org');
dl.startTrackingDeviceList('@test2:sw1v.org');
const queryDefer1 = utils.defer();
downloadSpy.mockReturnValueOnce(queryDefer1.promise);
const queryDefer2 = utils.defer();
downloadSpy.mockReturnValueOnce(queryDefer2.promise);
const prom1 = dl.refreshOutdatedDeviceLists();
expect(downloadSpy).toBeCalledTimes(2);
expect(downloadSpy).toHaveBeenNthCalledWith(1, ['@test1:sw1v.org'], {});
expect(downloadSpy).toHaveBeenNthCalledWith(2, ['@test2:sw1v.org'], {});
queryDefer1.resolve(utils.deepCopy(signedDeviceList));
queryDefer2.resolve(utils.deepCopy(signedDeviceList2));
return prom1.then(() => {
const storedKeys1 = dl.getRawStoredDevicesForUser('@test1:sw1v.org');
expect(Object.keys(storedKeys1)).toEqual(['HGKAWHRVJQ']);
const storedKeys2 = dl.getRawStoredDevicesForUser('@test2:sw1v.org');
expect(Object.keys(storedKeys2)).toEqual(['QJVRHWAKGH']);
});
});
});
+12 -13
View File
@@ -1,14 +1,14 @@
import '../../../olm-loader';
import * as algorithms from "../../../../src/crypto/algorithms";
import {MemoryCryptoStore} from "../../../../src/crypto/store/memory-crypto-store";
import {MockStorageApi} from "../../../MockStorageApi";
import { MemoryCryptoStore } from "../../../../src/crypto/store/memory-crypto-store";
import { MockStorageApi } from "../../../MockStorageApi";
import * as testUtils from "../../../test-utils";
import {OlmDevice} from "../../../../src/crypto/OlmDevice";
import {Crypto} from "../../../../src/crypto";
import {logger} from "../../../../src/logger";
import {MatrixEvent} from "../../../../src/models/event";
import {TestClient} from "../../../TestClient";
import {Room} from "../../../../src/models/room";
import { OlmDevice } from "../../../../src/crypto/OlmDevice";
import { Crypto } from "../../../../src/crypto";
import { logger } from "../../../../src/logger";
import { MatrixEvent } from "../../../../src/models/event";
import { TestClient } from "../../../TestClient";
import { Room } from "../../../../src/models/room";
import * as olmlib from "../../../../src/crypto/olmlib";
const MegolmDecryption = algorithms.DECRYPTION_CLASSES['m.megolm.v1.aes-sha2'];
@@ -50,7 +50,6 @@ describe("MegolmDecryption", function() {
roomId: ROOM_ID,
});
// we stub out the olm encryption bits
mockOlmLib = {};
mockOlmLib.ensureOlmSessionsForDevices = jest.fn();
@@ -136,9 +135,9 @@ describe("MegolmDecryption", function() {
mockCrypto.getStoredDevice.mockReturnValue(deviceInfo);
mockOlmLib.ensureOlmSessionsForDevices.mockResolvedValue({
'@alice:foo': {'alidevice': {
'@alice:foo': { 'alidevice': {
sessionId: 'alisession',
}},
} },
});
const awaitEncryptForDevice = new Promise((res, rej) => {
@@ -313,7 +312,7 @@ describe("MegolmDecryption", function() {
});
const mockRoom = {
getEncryptionTargetMembers: jest.fn().mockReturnValue(
[{userId: "@alice:home.server"}],
[{ userId: "@alice:home.server" }],
),
getBlacklistUnverifiedDevices: jest.fn().mockReturnValue(false),
};
@@ -373,7 +372,7 @@ describe("MegolmDecryption", function() {
const roomId = "!someroom";
const room = new Room(roomId, aliceClient, "@alice:example.com", {});
room.getEncryptionTargetMembers = async function() {
return [{userId: "@bob:example.com"}];
return [{ userId: "@bob:example.com" }];
};
room.setBlacklistUnverifiedDevices(true);
aliceClient.store.storeRoom(room);
+5 -5
View File
@@ -16,12 +16,12 @@ limitations under the License.
*/
import '../../../olm-loader';
import {MemoryCryptoStore} from "../../../../src/crypto/store/memory-crypto-store";
import {MockStorageApi} from "../../../MockStorageApi";
import {logger} from "../../../../src/logger";
import {OlmDevice} from "../../../../src/crypto/OlmDevice";
import { MemoryCryptoStore } from "../../../../src/crypto/store/memory-crypto-store";
import { MockStorageApi } from "../../../MockStorageApi";
import { logger } from "../../../../src/logger";
import { OlmDevice } from "../../../../src/crypto/OlmDevice";
import * as olmlib from "../../../../src/crypto/olmlib";
import {DeviceInfo} from "../../../../src/crypto/deviceinfo";
import { DeviceInfo } from "../../../../src/crypto/deviceinfo";
function makeOlmDevice() {
const mockStorage = new MockStorageApi();
+9 -9
View File
@@ -16,18 +16,18 @@ limitations under the License.
*/
import '../../olm-loader';
import {logger} from "../../../src/logger";
import { logger } from "../../../src/logger";
import * as olmlib from "../../../src/crypto/olmlib";
import {MatrixClient} from "../../../src/client";
import {MatrixEvent} from "../../../src/models/event";
import { MatrixClient } from "../../../src/client";
import { MatrixEvent } from "../../../src/models/event";
import * as algorithms from "../../../src/crypto/algorithms";
import {WebStorageSessionStore} from "../../../src/store/session/webstorage";
import {MemoryCryptoStore} from "../../../src/crypto/store/memory-crypto-store";
import {MockStorageApi} from "../../MockStorageApi";
import { WebStorageSessionStore } from "../../../src/store/session/webstorage";
import { MemoryCryptoStore } from "../../../src/crypto/store/memory-crypto-store";
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";
import { OlmDevice } from "../../../src/crypto/OlmDevice";
import { Crypto } from "../../../src/crypto";
import { resetCrossSigningKeys } from "./crypto-utils";
const Olm = global.Olm;
+16 -14
View File
@@ -18,11 +18,11 @@ limitations under the License.
import '../../olm-loader';
import anotherjson from 'another-json';
import * as olmlib from "../../../src/crypto/olmlib";
import {TestClient} from '../../TestClient';
import {HttpResponse, setHttpResponses} from '../../test-utils';
import { TestClient } from '../../TestClient';
import { HttpResponse, setHttpResponses } from '../../test-utils';
import { resetCrossSigningKeys } from "./crypto-utils";
import { MatrixError } from '../../../src/http-api';
import {logger} from '../../../src/logger';
import { logger } from '../../../src/logger';
async function makeTestClient(userInfo, options, keys) {
if (!keys) keys = {};
@@ -60,7 +60,7 @@ describe("Cross Signing", function() {
it("should sign the master key with the device key", async function() {
const alice = await makeTestClient(
{userId: "@alice:example.com", deviceId: "Osborne2"},
{ userId: "@alice:example.com", deviceId: "Osborne2" },
);
alice.uploadDeviceSigningKeys = jest.fn(async (auth, keys) => {
await olmlib.verifySignature(
@@ -80,7 +80,7 @@ describe("Cross Signing", function() {
it("should abort bootstrap if device signing auth fails", async function() {
const alice = await makeTestClient(
{userId: "@alice:example.com", deviceId: "Osborne2"},
{ userId: "@alice:example.com", deviceId: "Osborne2" },
);
alice.uploadDeviceSigningKeys = async (auth, keys) => {
const errorResponse = {
@@ -131,7 +131,7 @@ describe("Cross Signing", function() {
it("should upload a signature when a user is verified", async function() {
const alice = await makeTestClient(
{userId: "@alice:example.com", deviceId: "Osborne2"},
{ userId: "@alice:example.com", deviceId: "Osborne2" },
);
alice.uploadDeviceSigningKeys = async () => {};
alice.uploadKeySignatures = async () => {};
@@ -175,7 +175,7 @@ describe("Cross Signing", function() {
]);
const alice = await makeTestClient(
{userId: "@alice:example.com", deviceId: "Osborne2"},
{ userId: "@alice:example.com", deviceId: "Osborne2" },
{
cryptoCallbacks: {
// will be called to sign our own device
@@ -193,7 +193,9 @@ describe("Cross Signing", function() {
const keyChangePromise = new Promise((resolve, reject) => {
alice.once("crossSigning.keysChanged", async (e) => {
resolve(e);
await alice.checkOwnCrossSigningTrust();
await alice.checkOwnCrossSigningTrust({
allowPrivateKeyRequests: true,
});
});
});
@@ -326,7 +328,7 @@ describe("Cross Signing", function() {
it("should use trust chain to determine device verification", async function() {
const alice = await makeTestClient(
{userId: "@alice:example.com", deviceId: "Osborne2"},
{ userId: "@alice:example.com", deviceId: "Osborne2" },
);
alice.uploadDeviceSigningKeys = async () => {};
alice.uploadKeySignatures = async () => {};
@@ -411,7 +413,7 @@ describe("Cross Signing", function() {
it("should trust signatures received from other devices", async function() {
const aliceKeys = {};
const alice = await makeTestClient(
{userId: "@alice:example.com", deviceId: "Osborne2"},
{ userId: "@alice:example.com", deviceId: "Osborne2" },
null,
aliceKeys,
);
@@ -573,7 +575,7 @@ describe("Cross Signing", function() {
it("should dis-trust an unsigned device", async function() {
const alice = await makeTestClient(
{userId: "@alice:example.com", deviceId: "Osborne2"},
{ userId: "@alice:example.com", deviceId: "Osborne2" },
);
alice.uploadDeviceSigningKeys = async () => {};
alice.uploadKeySignatures = async () => {};
@@ -642,7 +644,7 @@ describe("Cross Signing", function() {
it("should dis-trust a user when their ssk changes", async function() {
const alice = await makeTestClient(
{userId: "@alice:example.com", deviceId: "Osborne2"},
{ userId: "@alice:example.com", deviceId: "Osborne2" },
);
alice.uploadDeviceSigningKeys = async () => {};
alice.uploadKeySignatures = async () => {};
@@ -780,7 +782,7 @@ describe("Cross Signing", function() {
let upgradeResolveFunc;
const alice = await makeTestClient(
{userId: "@alice:example.com", deviceId: "Osborne2"},
{ userId: "@alice:example.com", deviceId: "Osborne2" },
{
cryptoCallbacks: {
shouldUpgradeDeviceVerifications: (verifs) => {
@@ -792,7 +794,7 @@ describe("Cross Signing", function() {
},
);
const bob = await makeTestClient(
{userId: "@bob:example.com", deviceId: "Dynabook"},
{ userId: "@bob:example.com", deviceId: "Dynabook" },
);
bob.uploadDeviceSigningKeys = async () => {};
+1 -2
View File
@@ -1,5 +1,4 @@
import {IndexedDBCryptoStore} from '../../../src/crypto/store/indexeddb-crypto-store';
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.
@@ -17,7 +17,7 @@ limitations under the License.
import {
IndexedDBCryptoStore,
} from '../../../src/crypto/store/indexeddb-crypto-store';
import {MemoryCryptoStore} from '../../../src/crypto/store/memory-crypto-store';
import { MemoryCryptoStore } from '../../../src/crypto/store/memory-crypto-store';
import 'fake-indexeddb/auto';
import 'jest-localstorage-mock';
+25 -25
View File
@@ -16,13 +16,13 @@ limitations under the License.
import '../../olm-loader';
import * as olmlib from "../../../src/crypto/olmlib";
import {SECRET_STORAGE_ALGORITHM_V1_AES} from "../../../src/crypto/SecretStorage";
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 {logger} from '../../../src/logger';
import { SECRET_STORAGE_ALGORITHM_V1_AES } from "../../../src/crypto/SecretStorage";
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 { logger } from '../../../src/logger';
import * as utils from "../../../src/utils";
@@ -91,7 +91,7 @@ describe("Secrets", function() {
});
const alice = await makeTestClient(
{userId: "@alice:example.com", deviceId: "Osborne2"},
{ userId: "@alice:example.com", deviceId: "Osborne2" },
{
cryptoCallbacks: {
getCrossSigningKey: t => signingKey,
@@ -141,7 +141,7 @@ describe("Secrets", function() {
it("should throw if given a key that doesn't exist", async function() {
const alice = await makeTestClient(
{userId: "@alice:example.com", deviceId: "Osborne2"},
{ userId: "@alice:example.com", deviceId: "Osborne2" },
);
try {
@@ -155,7 +155,7 @@ describe("Secrets", function() {
it("should refuse to encrypt with zero keys", async function() {
const alice = await makeTestClient(
{userId: "@alice:example.com", deviceId: "Osborne2"},
{ userId: "@alice:example.com", deviceId: "Osborne2" },
);
try {
@@ -175,7 +175,7 @@ describe("Secrets", function() {
let keys = {};
const alice = await makeTestClient(
{userId: "@alice:example.com", deviceId: "Osborne2"},
{ userId: "@alice:example.com", deviceId: "Osborne2" },
{
cryptoCallbacks: {
getCrossSigningKey: t => keys[t],
@@ -208,7 +208,7 @@ describe("Secrets", function() {
it("should refuse to encrypt if no keys given and no default key", async function() {
const alice = await makeTestClient(
{userId: "@alice:example.com", deviceId: "Osborne2"},
{ userId: "@alice:example.com", deviceId: "Osborne2" },
);
try {
@@ -221,8 +221,8 @@ describe("Secrets", function() {
it("should request secrets from other clients", async function() {
const [osborne2, vax] = await makeTestClients(
[
{userId: "@alice:example.com", deviceId: "Osborne2"},
{userId: "@alice:example.com", deviceId: "VAX"},
{ userId: "@alice:example.com", deviceId: "Osborne2" },
{ userId: "@alice:example.com", deviceId: "VAX" },
],
{
cryptoCallbacks: {
@@ -419,12 +419,12 @@ describe("Secrets", function() {
key_id: SSSSKey,
};
const alice = await makeTestClient(
{userId: "@alice:example.com", deviceId: "Osborne2"},
{ userId: "@alice:example.com", deviceId: "Osborne2" },
{
cryptoCallbacks: {
getCrossSigningKey: t => crossSigningKeys[t],
saveCrossSigningKeys: k => crossSigningKeys = k,
getSecretStorageKey: ({keys}, name) => {
getSecretStorageKey: ({ keys }, name) => {
for (const keyId of Object.keys(keys)) {
if (secretStorageKeys[keyId]) {
return [keyId, secretStorageKeys[keyId]];
@@ -458,7 +458,7 @@ describe("Secrets", function() {
type: "m.cross_signing.master",
content: {
encrypted: {
key_id: {ciphertext: "bla", mac: "bla", iv: "bla"},
key_id: { ciphertext: "bla", mac: "bla", iv: "bla" },
},
},
}),
@@ -466,7 +466,7 @@ describe("Secrets", function() {
type: "m.cross_signing.self_signing",
content: {
encrypted: {
key_id: {ciphertext: "bla", mac: "bla", iv: "bla"},
key_id: { ciphertext: "bla", mac: "bla", iv: "bla" },
},
},
}),
@@ -474,7 +474,7 @@ describe("Secrets", function() {
type: "m.cross_signing.user_signing",
content: {
encrypted: {
key_id: {ciphertext: "bla", mac: "bla", iv: "bla"},
key_id: { ciphertext: "bla", mac: "bla", iv: "bla" },
},
},
}),
@@ -525,7 +525,7 @@ describe("Secrets", function() {
await alice.bootstrapSecretStorage();
expect(alice.getAccountData("m.secret_storage.default_key").getContent())
.toEqual({key: "key_id"});
.toEqual({ key: "key_id" });
const keyInfo = alice.getAccountData("m.secret_storage.key.key_id")
.getContent();
expect(keyInfo.algorithm)
@@ -550,12 +550,12 @@ describe("Secrets", function() {
key_id: SSSSKey,
};
const alice = await makeTestClient(
{userId: "@alice:example.com", deviceId: "Osborne2"},
{ userId: "@alice:example.com", deviceId: "Osborne2" },
{
cryptoCallbacks: {
getCrossSigningKey: t => crossSigningKeys[t],
saveCrossSigningKeys: k => crossSigningKeys = k,
getSecretStorageKey: ({keys}, name) => {
getSecretStorageKey: ({ keys }, name) => {
for (const keyId of Object.keys(keys)) {
if (secretStorageKeys[keyId]) {
return [keyId, secretStorageKeys[keyId]];
@@ -587,7 +587,7 @@ describe("Secrets", function() {
type: "m.cross_signing.master",
content: {
encrypted: {
key_id: {ciphertext: "bla", mac: "bla", iv: "bla"},
key_id: { ciphertext: "bla", mac: "bla", iv: "bla" },
},
},
}),
@@ -595,7 +595,7 @@ describe("Secrets", function() {
type: "m.cross_signing.self_signing",
content: {
encrypted: {
key_id: {ciphertext: "bla", mac: "bla", iv: "bla"},
key_id: { ciphertext: "bla", mac: "bla", iv: "bla" },
},
},
}),
@@ -603,7 +603,7 @@ describe("Secrets", function() {
type: "m.cross_signing.user_signing",
content: {
encrypted: {
key_id: {ciphertext: "bla", mac: "bla", iv: "bla"},
key_id: { ciphertext: "bla", mac: "bla", iv: "bla" },
},
},
}),
@@ -13,9 +13,9 @@ 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.
*/
import {InRoomChannel} from "../../../../src/crypto/verification/request/InRoomChannel";
import { InRoomChannel } from "../../../../src/crypto/verification/request/InRoomChannel";
"../../../../src/crypto/verification/request/ToDeviceChannel";
import {MatrixEvent} from "../../../../src/models/event";
import { MatrixEvent } from "../../../../src/models/event";
describe("InRoomChannel tests", function() {
const ALICE = "@alice:hs.tld";
@@ -15,7 +15,7 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
import "../../../olm-loader";
import {logger} from "../../../../src/logger";
import { logger } from "../../../../src/logger";
const Olm = global.Olm;
@@ -15,10 +15,10 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
import "../../../olm-loader";
import {verificationMethods} from "../../../../src/crypto";
import {logger} from "../../../../src/logger";
import {SAS} from "../../../../src/crypto/verification/SAS";
import {makeTestClients, setupWebcrypto, teardownWebcrypto} from './util';
import { verificationMethods } from "../../../../src/crypto";
import { logger } from "../../../../src/logger";
import { SAS } from "../../../../src/crypto/verification/SAS";
import { makeTestClients, setupWebcrypto, teardownWebcrypto } from './util';
const Olm = global.Olm;
@@ -42,8 +42,8 @@ describe("verification request integration tests with crypto layer", function()
it("should request and accept a verification", async function() {
const [alice, bob] = await makeTestClients(
[
{userId: "@alice:example.com", deviceId: "Osborne2"},
{userId: "@bob:example.com", deviceId: "Dynabook"},
{ userId: "@alice:example.com", deviceId: "Osborne2" },
{ userId: "@bob:example.com", deviceId: "Dynabook" },
],
{
verificationMethods: [verificationMethods.SAS],
+13 -13
View File
@@ -15,14 +15,14 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
import "../../../olm-loader";
import {makeTestClients, setupWebcrypto, teardownWebcrypto} from './util';
import {MatrixEvent} from "../../../../src/models/event";
import {SAS} from "../../../../src/crypto/verification/SAS";
import {DeviceInfo} from "../../../../src/crypto/deviceinfo";
import {verificationMethods} from "../../../../src/crypto";
import { makeTestClients, setupWebcrypto, teardownWebcrypto } from './util';
import { MatrixEvent } from "../../../../src/models/event";
import { SAS } from "../../../../src/crypto/verification/SAS";
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";
import { logger } from "../../../../src/logger";
import { resetCrossSigningKeys } from "../crypto-utils";
const Olm = global.Olm;
@@ -79,8 +79,8 @@ describe("SAS verification", function() {
beforeEach(async () => {
[alice, bob] = await makeTestClients(
[
{userId: "@alice:example.com", deviceId: "Osborne2"},
{userId: "@bob:example.com", deviceId: "Dynabook"},
{ userId: "@alice:example.com", deviceId: "Osborne2" },
{ userId: "@bob:example.com", deviceId: "Dynabook" },
],
{
verificationMethods: [verificationMethods.SAS],
@@ -336,8 +336,8 @@ describe("SAS verification", function() {
it("should send a cancellation message on error", async function() {
const [alice, bob] = await makeTestClients(
[
{userId: "@alice:example.com", deviceId: "Osborne2"},
{userId: "@bob:example.com", deviceId: "Dynabook"},
{ userId: "@alice:example.com", deviceId: "Osborne2" },
{ userId: "@bob:example.com", deviceId: "Dynabook" },
],
{
verificationMethods: [verificationMethods.SAS],
@@ -390,8 +390,8 @@ describe("SAS verification", function() {
beforeEach(async function() {
[alice, bob] = await makeTestClients(
[
{userId: "@alice:example.com", deviceId: "Osborne2"},
{userId: "@bob:example.com", deviceId: "Dynabook"},
{ userId: "@alice:example.com", deviceId: "Osborne2" },
{ userId: "@bob:example.com", deviceId: "Dynabook" },
],
{
verificationMethods: [verificationMethods.SAS],
@@ -14,10 +14,10 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
import {VerificationBase} from '../../../../src/crypto/verification/Base';
import {CrossSigningInfo} from '../../../../src/crypto/CrossSigning';
import {encodeBase64} from "../../../../src/crypto/olmlib";
import {setupWebcrypto, teardownWebcrypto} from './util';
import { VerificationBase } from '../../../../src/crypto/verification/Base';
import { CrossSigningInfo } from '../../../../src/crypto/CrossSigning';
import { encodeBase64 } from "../../../../src/crypto/olmlib";
import { setupWebcrypto, teardownWebcrypto } from './util';
jest.useFakeTimers();
+9 -9
View File
@@ -15,10 +15,10 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
import {TestClient} from '../../../TestClient';
import {MatrixEvent} from "../../../../src/models/event";
import { TestClient } from '../../../TestClient';
import { MatrixEvent } from "../../../../src/models/event";
import nodeCrypto from "crypto";
import {logger} from '../../../../src/logger';
import { logger } from '../../../../src/logger';
export async function makeTestClients(userInfos, options) {
const clients = [];
@@ -30,7 +30,7 @@ export async function makeTestClients(userInfos, options) {
for (const [deviceId, msg] of Object.entries(devMap)) {
if (deviceId in clientMap[userId]) {
const event = new MatrixEvent({
sender: this.getUserId(), // eslint-disable-line babel/no-invalid-this
sender: this.getUserId(), // eslint-disable-line @babel/no-invalid-this
type: type,
content: msg,
});
@@ -49,9 +49,9 @@ export async function makeTestClients(userInfos, options) {
};
const sendEvent = function(room, type, content) {
// make up a unique ID as the event ID
const eventId = "$" + this.makeTxnId(); // eslint-disable-line babel/no-invalid-this
const eventId = "$" + this.makeTxnId(); // eslint-disable-line @babel/no-invalid-this
const rawEvent = {
sender: this.getUserId(), // eslint-disable-line babel/no-invalid-this
sender: this.getUserId(), // eslint-disable-line @babel/no-invalid-this
type: type,
content: content,
room_id: room,
@@ -61,13 +61,13 @@ export async function makeTestClients(userInfos, options) {
const event = new MatrixEvent(rawEvent);
const remoteEcho = new MatrixEvent(Object.assign({}, rawEvent, {
unsigned: {
transaction_id: this.makeTxnId(), // eslint-disable-line babel/no-invalid-this
transaction_id: this.makeTxnId(), // eslint-disable-line @babel/no-invalid-this
},
}));
setImmediate(() => {
for (const tc of clients) {
if (tc.client === this) { // eslint-disable-line babel/no-invalid-this
if (tc.client === this) { // eslint-disable-line @babel/no-invalid-this
logger.log("sending remote echo!!");
tc.client.emit("Room.timeline", remoteEcho);
} else {
@@ -76,7 +76,7 @@ export async function makeTestClients(userInfos, options) {
}
});
return Promise.resolve({event_id: eventId});
return Promise.resolve({ event_id: eventId });
};
for (const userInfo of userInfos) {
@@ -13,13 +13,13 @@ 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.
*/
import {VerificationRequest, READY_TYPE, START_TYPE, DONE_TYPE} from
import { VerificationRequest, READY_TYPE, START_TYPE, DONE_TYPE } from
"../../../../src/crypto/verification/request/VerificationRequest";
import {InRoomChannel} from "../../../../src/crypto/verification/request/InRoomChannel";
import {ToDeviceChannel} from
import { InRoomChannel } from "../../../../src/crypto/verification/request/InRoomChannel";
import { ToDeviceChannel } from
"../../../../src/crypto/verification/request/ToDeviceChannel";
import {MatrixEvent} from "../../../../src/models/event";
import {setupWebcrypto, teardownWebcrypto} from "./util";
import { MatrixEvent } from "../../../../src/models/event";
import { setupWebcrypto, teardownWebcrypto } from "./util";
function makeMockClient(userId, deviceId) {
let counter = 1;
@@ -40,7 +40,7 @@ function makeMockClient(userId, deviceId) {
content,
origin_server_ts: Date.now(),
}));
return Promise.resolve({event_id: eventId});
return Promise.resolve({ event_id: eventId });
},
sendToDevice(type, msgMap) {
@@ -48,7 +48,7 @@ function makeMockClient(userId, deviceId) {
const deviceMap = msgMap[userId];
for (const deviceId of Object.keys(deviceMap)) {
const content = deviceMap[deviceId];
const event = new MatrixEvent({content, type});
const event = new MatrixEvent({ content, type });
deviceEvents[userId] = deviceEvents[userId] || {};
deviceEvents[userId][deviceId] = deviceEvents[userId][deviceId] || [];
deviceEvents[userId][deviceId].push(event);
@@ -90,7 +90,7 @@ class MockVerifier {
if (this._startEvent) {
await this._channel.send(DONE_TYPE, {});
} else {
await this._channel.send(START_TYPE, {method: MOCK_METHOD});
await this._channel.send(START_TYPE, { method: MOCK_METHOD });
}
}
@@ -226,7 +226,7 @@ describe("verification request unit tests", function() {
new ToDeviceChannel(bob1, bob1.getUserId(), ["device1", "device2"],
ToDeviceChannel.makeTransactionId(), "device2"),
new Map([[MOCK_METHOD, MockVerifier]]), bob1);
const to = {userId: "@bob:matrix.tld", deviceId: "device2"};
const to = { userId: "@bob:matrix.tld", deviceId: "device2" };
const verifier = bob1Request.beginKeyVerification(MOCK_METHOD, to);
expect(verifier).toBeInstanceOf(MockVerifier);
await verifier.start();
+7 -9
View File
@@ -1,6 +1,6 @@
import * as utils from "../test-utils";
import {EventTimeline} from "../../src/models/event-timeline";
import {RoomState} from "../../src/models/room-state";
import { EventTimeline } from "../../src/models/event-timeline";
import { RoomState } from "../../src/models/room-state";
function mockRoomStates(timeline) {
timeline._startState = utils.mock(RoomState, "startState");
@@ -15,7 +15,7 @@ describe("EventTimeline", function() {
beforeEach(function() {
// XXX: this is a horrid hack; should use sinon or something instead to mock
const timelineSet = { room: { roomId: roomId }};
const timelineSet = { room: { roomId: roomId } };
timelineSet.room.getUnfilteredTimelineSet = function() {
return timelineSet;
};
@@ -94,7 +94,6 @@ describe("EventTimeline", function() {
});
});
describe("neighbouringTimelines", function() {
it("neighbouring timelines should start null", function() {
expect(timeline.getNeighbouringTimeline(EventTimeline.BACKWARDS)).toBe(null);
@@ -102,8 +101,8 @@ describe("EventTimeline", function() {
});
it("setNeighbouringTimeline should set neighbour", function() {
const prev = {a: "a"};
const next = {b: "b"};
const prev = { a: "a" };
const next = { b: "b" };
timeline.setNeighbouringTimeline(prev, EventTimeline.BACKWARDS);
timeline.setNeighbouringTimeline(next, EventTimeline.FORWARDS);
expect(timeline.getNeighbouringTimeline(EventTimeline.BACKWARDS)).toBe(prev);
@@ -111,8 +110,8 @@ describe("EventTimeline", function() {
});
it("setNeighbouringTimeline should throw if called twice", function() {
const prev = {a: "a"};
const next = {b: "b"};
const prev = { a: "a" };
const next = { b: "b" };
expect(function() {
timeline.setNeighbouringTimeline(prev, EventTimeline.BACKWARDS);
}).not.toThrow();
@@ -278,7 +277,6 @@ describe("EventTimeline", function() {
not.toHaveBeenCalled();
});
it("should call setStateEvents on the right RoomState with the right " +
"forwardLooking value for old events", function() {
const events = [
+2 -2
View File
@@ -15,8 +15,8 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
import {logger} from "../../src/logger";
import {MatrixEvent} from "../../src/models/event";
import { logger } from "../../src/logger";
import { MatrixEvent } from "../../src/models/event";
describe("MatrixEvent", () => {
describe(".attemptDecryption", () => {
+2 -2
View File
@@ -1,5 +1,5 @@
import {FilterComponent} from "../../src/filter-component";
import {mkEvent} from '../test-utils';
import { FilterComponent } from "../../src/filter-component";
import { mkEvent } from '../test-utils';
describe("Filter Component", function() {
describe("types", function() {
+1 -1
View File
@@ -1,4 +1,4 @@
import {Filter} from "../../src/filter";
import { Filter } from "../../src/filter";
describe("Filter", function() {
const filterId = "f1lt3ring15g00d4ursoul";
+5 -5
View File
@@ -15,9 +15,9 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
import {logger} from "../../src/logger";
import {InteractiveAuth} from "../../src/interactive-auth";
import {MatrixError} from "../../src/http-api";
import { logger } from "../../src/logger";
import { InteractiveAuth } from "../../src/interactive-auth";
import { MatrixError } from "../../src/http-api";
// Trivial client object to test interactive auth
// (we do not need TestClient here)
@@ -63,7 +63,7 @@ describe("InteractiveAuth", function() {
});
// .. which should trigger a call here
const requestRes = {"a": "b"};
const requestRes = { "a": "b" };
doRequest.mockImplementation(function(authData) {
logger.log('cccc');
expect(authData).toEqual({
@@ -112,7 +112,7 @@ describe("InteractiveAuth", function() {
});
// .. which should be followed by a call to stateUpdated
const requestRes = {"a": "b"};
const requestRes = { "a": "b" };
stateUpdated.mockImplementation(function(stage) {
expect(stage).toEqual("logintype");
expect(ia.getSessionId()).toEqual("sessionId");
+1 -1
View File
@@ -1,4 +1,4 @@
import {TestClient} from '../TestClient';
import { TestClient } from '../TestClient';
describe('Login request', function() {
let client;
+4 -4
View File
@@ -1,6 +1,6 @@
import {logger} from "../../src/logger";
import {MatrixClient} from "../../src/client";
import {Filter} from "../../src/filter";
import { logger } from "../../src/logger";
import { MatrixClient } from "../../src/client";
import { Filter } from "../../src/filter";
jest.useFakeTimers();
@@ -178,7 +178,7 @@ describe("MatrixClient", function() {
const filterId = "ehfewf";
store.getFilterIdByName.mockReturnValue(filterId);
const filter = new Filter(0, filterId);
filter.setDefinition({"room": {"timeline": {"limit": 8}}});
filter.setDefinition({ "room": { "timeline": { "limit": 8 } } });
store.getFilter.mockReturnValue(filter);
const syncPromise = new Promise((resolve, reject) => {
client.on("sync", function syncListener(state) {
+1 -1
View File
@@ -1,5 +1,5 @@
import * as utils from "../test-utils";
import {PushProcessor} from "../../src/pushprocessor";
import { PushProcessor } from "../../src/pushprocessor";
describe('NotificationService', function() {
const testUserId = "@ali:matrix.org";
+2 -2
View File
@@ -46,8 +46,8 @@ describe("realtime-callbacks", function() {
it("should set 'this' to the global object", function() {
let passed = false;
const callback = function() {
expect(this).toBe(global); // eslint-disable-line babel/no-invalid-this
expect(this.console).toBeTruthy(); // eslint-disable-line babel/no-invalid-this
expect(this).toBe(global); // eslint-disable-line @babel/no-invalid-this
expect(this.console).toBeTruthy(); // eslint-disable-line @babel/no-invalid-this
passed = true;
};
callbacks.setTimeout(callback);
+133
View File
@@ -0,0 +1,133 @@
/*
Copyright 2021 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.
*/
import { EventTimelineSet } from "../../src/models/event-timeline-set";
import { MatrixEvent } from "../../src/models/event";
import { Relations } from "../../src/models/relations";
describe("Relations", function() {
it("should deduplicate annotations", function() {
const relations = new Relations("m.annotation", "m.reaction");
// Create an instance of an annotation
const eventData = {
"sender": "@bob:example.com",
"type": "m.reaction",
"event_id": "$cZ1biX33ENJqIm00ks0W_hgiO_6CHrsAc3ZQrnLeNTw",
"room_id": "!pzVjCQSoQPpXQeHpmK:example.com",
"content": {
"m.relates_to": {
"event_id": "$2s4yYpEkVQrPglSCSqB_m6E8vDhWsg0yFNyOJdVIb_o",
"key": "👍️",
"rel_type": "m.annotation",
},
},
};
const eventA = new MatrixEvent(eventData);
// Add the event once and check results
{
relations.addEvent(eventA);
const annotationsByKey = relations.getSortedAnnotationsByKey();
expect(annotationsByKey.length).toEqual(1);
const [key, events] = annotationsByKey[0];
expect(key).toEqual("👍️");
expect(events.size).toEqual(1);
}
// Add the event again and expect the same
{
relations.addEvent(eventA);
const annotationsByKey = relations.getSortedAnnotationsByKey();
expect(annotationsByKey.length).toEqual(1);
const [key, events] = annotationsByKey[0];
expect(key).toEqual("👍️");
expect(events.size).toEqual(1);
}
// Create a fresh object with the same event content
const eventB = new MatrixEvent(eventData);
// Add the event again and expect the same
{
relations.addEvent(eventB);
const annotationsByKey = relations.getSortedAnnotationsByKey();
expect(annotationsByKey.length).toEqual(1);
const [key, events] = annotationsByKey[0];
expect(key).toEqual("👍️");
expect(events.size).toEqual(1);
}
});
it("should emit created regardless of ordering", async function() {
const targetEvent = new MatrixEvent({
"sender": "@bob:example.com",
"type": "m.room.message",
"event_id": "$2s4yYpEkVQrPglSCSqB_m6E8vDhWsg0yFNyOJdVIb_o",
"room_id": "!pzVjCQSoQPpXQeHpmK:example.com",
"content": {},
});
const relationEvent = new MatrixEvent({
"sender": "@bob:example.com",
"type": "m.reaction",
"event_id": "$cZ1biX33ENJqIm00ks0W_hgiO_6CHrsAc3ZQrnLeNTw",
"room_id": "!pzVjCQSoQPpXQeHpmK:example.com",
"content": {
"m.relates_to": {
"event_id": "$2s4yYpEkVQrPglSCSqB_m6E8vDhWsg0yFNyOJdVIb_o",
"key": "👍️",
"rel_type": "m.annotation",
},
},
});
// Stub the room
const room = {
getPendingEvent() { return null; },
getUnfilteredTimelineSet() { return null; },
};
// Add the target event first, then the relation event
{
const relationsCreated = new Promise(resolve => {
targetEvent.once("Event.relationsCreated", resolve);
})
const timelineSet = new EventTimelineSet(room, {
unstableClientRelationAggregation: true,
});
timelineSet.addLiveEvent(targetEvent);
timelineSet.addLiveEvent(relationEvent);
await relationsCreated;
}
// Add the relation event first, then the target event
{
const relationsCreated = new Promise(resolve => {
targetEvent.once("Event.relationsCreated", resolve);
})
const timelineSet = new EventTimelineSet(room, {
unstableClientRelationAggregation: true,
});
timelineSet.addLiveEvent(relationEvent);
timelineSet.addLiveEvent(targetEvent);
await relationsCreated;
}
});
});
+1 -1
View File
@@ -1,5 +1,5 @@
import * as utils from "../test-utils";
import {RoomMember} from "../../src/models/room-member";
import { RoomMember } from "../../src/models/room-member";
describe("RoomMember", function() {
const roomId = "!foo:bar";
+26 -26
View File
@@ -1,6 +1,6 @@
import * as utils from "../test-utils";
import {RoomState} from "../../src/models/room-state";
import {RoomMember} from "../../src/models/room-member";
import { RoomState } from "../../src/models/room-state";
import { RoomMember } from "../../src/models/room-member";
describe("RoomState", function() {
const roomId = "!foo:bar";
@@ -471,13 +471,13 @@ describe("RoomState", function() {
it("should update after adding joined member", function() {
state.setStateEvents([
utils.mkMembership({event: true, mship: "join",
user: userA, room: roomId}),
utils.mkMembership({ event: true, mship: "join",
user: userA, room: roomId }),
]);
expect(state.getJoinedMemberCount()).toEqual(1);
state.setStateEvents([
utils.mkMembership({event: true, mship: "join",
user: userC, room: roomId}),
utils.mkMembership({ event: true, mship: "join",
user: userC, room: roomId }),
]);
expect(state.getJoinedMemberCount()).toEqual(2);
});
@@ -490,13 +490,13 @@ describe("RoomState", function() {
it("should update after adding invited member", function() {
state.setStateEvents([
utils.mkMembership({event: true, mship: "invite",
user: userA, room: roomId}),
utils.mkMembership({ event: true, mship: "invite",
user: userA, room: roomId }),
]);
expect(state.getInvitedMemberCount()).toEqual(1);
state.setStateEvents([
utils.mkMembership({event: true, mship: "invite",
user: userC, room: roomId}),
utils.mkMembership({ event: true, mship: "invite",
user: userC, room: roomId }),
]);
expect(state.getInvitedMemberCount()).toEqual(2);
});
@@ -509,15 +509,15 @@ describe("RoomState", function() {
it("should, once used, override counting members from state", function() {
state.setStateEvents([
utils.mkMembership({event: true, mship: "join",
user: userA, room: roomId}),
utils.mkMembership({ event: true, mship: "join",
user: userA, room: roomId }),
]);
expect(state.getJoinedMemberCount()).toEqual(1);
state.setJoinedMemberCount(100);
expect(state.getJoinedMemberCount()).toEqual(100);
state.setStateEvents([
utils.mkMembership({event: true, mship: "join",
user: userC, room: roomId}),
utils.mkMembership({ event: true, mship: "join",
user: userC, room: roomId }),
]);
expect(state.getJoinedMemberCount()).toEqual(100);
});
@@ -525,14 +525,14 @@ describe("RoomState", function() {
it("should, once used, override counting members from state, " +
"also after clone", function() {
state.setStateEvents([
utils.mkMembership({event: true, mship: "join",
user: userA, room: roomId}),
utils.mkMembership({ event: true, mship: "join",
user: userA, room: roomId }),
]);
state.setJoinedMemberCount(100);
const copy = state.clone();
copy.setStateEvents([
utils.mkMembership({event: true, mship: "join",
user: userC, room: roomId}),
utils.mkMembership({ event: true, mship: "join",
user: userC, room: roomId }),
]);
expect(state.getJoinedMemberCount()).toEqual(100);
});
@@ -545,15 +545,15 @@ describe("RoomState", function() {
it("should, once used, override counting members from state", function() {
state.setStateEvents([
utils.mkMembership({event: true, mship: "invite",
user: userB, room: roomId}),
utils.mkMembership({ event: true, mship: "invite",
user: userB, room: roomId }),
]);
expect(state.getInvitedMemberCount()).toEqual(1);
state.setInvitedMemberCount(100);
expect(state.getInvitedMemberCount()).toEqual(100);
state.setStateEvents([
utils.mkMembership({event: true, mship: "invite",
user: userC, room: roomId}),
utils.mkMembership({ event: true, mship: "invite",
user: userC, room: roomId }),
]);
expect(state.getInvitedMemberCount()).toEqual(100);
});
@@ -561,14 +561,14 @@ describe("RoomState", function() {
it("should, once used, override counting members from state, " +
"also after clone", function() {
state.setStateEvents([
utils.mkMembership({event: true, mship: "invite",
user: userB, room: roomId}),
utils.mkMembership({ event: true, mship: "invite",
user: userB, room: roomId }),
]);
state.setInvitedMemberCount(100);
const copy = state.clone();
copy.setStateEvents([
utils.mkMembership({event: true, mship: "invite",
user: userC, room: roomId}),
utils.mkMembership({ event: true, mship: "invite",
user: userC, room: roomId }),
]);
expect(state.getInvitedMemberCount()).toEqual(100);
});
+33 -27
View File
@@ -1,8 +1,9 @@
import * as utils from "../test-utils";
import {EventStatus, MatrixEvent} from "../../src/models/event";
import {EventTimeline} from "../../src/models/event-timeline";
import {RoomState} from "../../src/models/room-state";
import {Room} from "../../src/models/room";
import { EventStatus, MatrixEvent } from "../../src/models/event";
import { EventTimeline } from "../../src/models/event-timeline";
import { RoomState } from "../../src/models/room-state";
import { Room } from "../../src/models/room";
import { TestClient } from "../TestClient";
describe("Room", function() {
const roomId = "!foo:bar";
@@ -190,7 +191,7 @@ describe("Room", function() {
const remoteEvent = utils.mkMessage({
room: roomId, user: userA, event: true,
});
remoteEvent.event.unsigned = {transaction_id: "TXN_ID"};
remoteEvent.event.unsigned = { transaction_id: "TXN_ID" };
const remoteEventId = remoteEvent.getId();
let callCount = 0;
@@ -374,7 +375,7 @@ describe("Room", function() {
let events = null;
beforeEach(function() {
room = new Room(roomId, null, null, {timelineSupport: timelineSupport});
room = new Room(roomId, null, null, { timelineSupport: timelineSupport });
// set events each time to avoid resusing Event objects (which
// doesn't work because they get frozen)
events = [
@@ -456,7 +457,7 @@ describe("Room", function() {
describe("compareEventOrdering", function() {
beforeEach(function() {
room = new Room(roomId, null, null, {timelineSupport: true});
room = new Room(roomId, null, null, { timelineSupport: true });
});
const events = [
@@ -712,7 +713,7 @@ describe("Room", function() {
it("uses hero name from state", function() {
const name = "Mr B";
addMember(userA, "invite");
addMember(userB, "join", {name});
addMember(userB, "join", { name });
room.setSummary({
"m.heroes": [userB],
});
@@ -723,7 +724,7 @@ describe("Room", function() {
it("uses counts from summary", function() {
const name = "Mr B";
addMember(userB, "join", {name});
addMember(userB, "join", { name });
room.setSummary({
"m.heroes": [userB],
"m.joined_member_count": 50,
@@ -736,8 +737,8 @@ describe("Room", function() {
it("relies on heroes in case of absent counts", function() {
const nameB = "Mr Bean";
const nameC = "Mel C";
addMember(userB, "join", {name: nameB});
addMember(userC, "join", {name: nameC});
addMember(userB, "join", { name: nameB });
addMember(userC, "join", { name: nameC });
room.setSummary({
"m.heroes": [userB, userC],
});
@@ -747,7 +748,7 @@ describe("Room", function() {
it("uses only heroes", function() {
const nameB = "Mr Bean";
addMember(userB, "join", {name: nameB});
addMember(userB, "join", { name: nameB });
addMember(userC, "join");
room.setSummary({
"m.heroes": [userB],
@@ -840,7 +841,7 @@ describe("Room", function() {
it("should show the other user's name for private" +
" (invite join_rules) rooms if you are invited to it.", function() {
setJoinRule("invite");
addMember(userA, "invite", {user: userB});
addMember(userA, "invite", { user: userB });
addMember(userB);
room.recalculate();
const name = room.name;
@@ -915,8 +916,8 @@ describe("Room", function() {
"available",
function() {
setJoinRule("invite");
addMember(userB, 'join', {name: "Alice"});
addMember(userA, "invite", {user: userA});
addMember(userB, 'join', { name: "Alice" });
addMember(userA, "invite", { user: userA });
room.recalculate();
const name = room.name;
expect(name).toEqual("Alice");
@@ -926,7 +927,7 @@ describe("Room", function() {
function() {
setJoinRule("invite");
addMember(userB);
addMember(userA, "invite", {user: userA});
addMember(userA, "invite", { user: userA });
room.recalculate();
const name = room.name;
expect(name).toEqual(userB);
@@ -1176,7 +1177,10 @@ describe("Room", function() {
describe("addPendingEvent", function() {
it("should add pending events to the pendingEventList if " +
"pendingEventOrdering == 'detached'", function() {
const room = new Room(roomId, null, userA, {
const client = (new TestClient(
"@alice:example.com", "alicedevice",
)).client;
const room = new Room(roomId, client, userA, {
pendingEventOrdering: "detached",
});
const eventA = utils.mkMessage({
@@ -1226,7 +1230,10 @@ describe("Room", function() {
describe("updatePendingEvent", function() {
it("should remove cancelled events from the pending list", function() {
const room = new Room(roomId, null, userA, {
const client = (new TestClient(
"@alice:example.com", "alicedevice",
)).client;
const room = new Room(roomId, client, userA, {
pendingEventOrdering: "detached",
});
const eventA = utils.mkMessage({
@@ -1260,7 +1267,6 @@ describe("Room", function() {
expect(callCount).toEqual(1);
});
it("should remove cancelled events from the timeline", function() {
const room = new Room(roomId, null, userA);
const eventA = utils.mkMessage({
@@ -1314,7 +1320,7 @@ describe("Room", function() {
if (this.serverResponse instanceof Error) {
return Promise.reject(this.serverResponse);
} else {
return Promise.resolve({chunk: this.serverResponse});
return Promise.resolve({ chunk: this.serverResponse });
}
},
},
@@ -1344,7 +1350,7 @@ describe("Room", function() {
it("should load members from server on first call", async function() {
const client = createClientMock([memberEvent]);
const room = new Room(roomId, client, null, {lazyLoadMembers: true});
const room = new Room(roomId, client, null, { lazyLoadMembers: true });
await room.loadMembersIfNeeded();
const memberA = room.getMember("@user_a:bar");
expect(memberA.name).toEqual("User A");
@@ -1359,7 +1365,7 @@ describe("Room", function() {
room: roomId, event: true, name: "Ms A",
});
const client = createClientMock([memberEvent2], [memberEvent]);
const room = new Room(roomId, client, null, {lazyLoadMembers: true});
const room = new Room(roomId, client, null, { lazyLoadMembers: true });
await room.loadMembersIfNeeded();
@@ -1369,7 +1375,7 @@ describe("Room", function() {
it("should allow retry on error", async function() {
const client = createClientMock(new Error("server says no"));
const room = new Room(roomId, client, null, {lazyLoadMembers: true});
const room = new Room(roomId, client, null, { lazyLoadMembers: true });
let hasThrown = false;
try {
await room.loadMembersIfNeeded();
@@ -1397,17 +1403,17 @@ describe("Room", function() {
const room = new Room(roomId, null, userA);
const events = [];
room.on("Room.myMembership", (_room, membership, oldMembership) => {
events.push({membership, oldMembership});
events.push({ membership, oldMembership });
});
room.updateMyMembership("invite");
expect(room.getMyMembership()).toEqual("invite");
expect(events[0]).toEqual({membership: "invite", oldMembership: null});
expect(events[0]).toEqual({ membership: "invite", oldMembership: null });
events.splice(0); //clear
room.updateMyMembership("invite");
expect(events.length).toEqual(0);
room.updateMyMembership("join");
expect(room.getMyMembership()).toEqual("join");
expect(events[0]).toEqual({membership: "join", oldMembership: "invite"});
expect(events[0]).toEqual({ membership: "join", oldMembership: "invite" });
});
});
@@ -1415,7 +1421,7 @@ describe("Room", function() {
it("should return first hero id",
function() {
const room = new Room(roomId, null, userA);
room.setSummary({'m.heroes': [userB]});
room.setSummary({ 'm.heroes': [userB] });
expect(room.guessDMUserId()).toEqual(userB);
});
it("should return first member that isn't self",
+8 -8
View File
@@ -1,9 +1,9 @@
// This file had a function whose name is all caps, which displeases eslint
/* eslint new-cap: "off" */
import {defer} from '../../src/utils';
import {MatrixError} from "../../src/http-api";
import {MatrixScheduler} from "../../src/scheduler";
import { defer } from '../../src/utils';
import { MatrixError } from "../../src/http-api";
import { MatrixScheduler } from "../../src/scheduler";
import * as utils from "../test-utils";
jest.useFakeTimers();
@@ -62,8 +62,8 @@ describe("MatrixScheduler", function() {
scheduler.queueEvent(eventA),
scheduler.queueEvent(eventB),
]);
deferB.resolve({b: true});
deferA.resolve({a: true});
deferB.resolve({ b: true });
deferA.resolve({ a: true });
const [a, b] = await abPromise;
expect(a.a).toEqual(true);
expect(b.b).toEqual(true);
@@ -156,8 +156,8 @@ describe("MatrixScheduler", function() {
// Expect to have processFn invoked for A&B.
// Resolve A.
// Expect to have processFn invoked for D.
const eventC = utils.mkMessage({user: "@a:bar", room: roomId, event: true});
const eventD = utils.mkMessage({user: "@b:bar", room: roomId, event: true});
const eventC = utils.mkMessage({ user: "@a:bar", room: roomId, event: true });
const eventD = utils.mkMessage({ user: "@b:bar", room: roomId, event: true });
const buckets = {};
buckets[eventA.getId()] = "queue_A";
@@ -241,7 +241,7 @@ describe("MatrixScheduler", function() {
expect(queue).toEqual([eventA, eventB]);
// modify the queue
const eventC = utils.mkMessage(
{user: "@a:bar", room: roomId, event: true},
{ user: "@a:bar", room: roomId, event: true },
);
queue.push(eventC);
const queueAgain = scheduler.getQueueForEvent(eventA);
+1 -1
View File
@@ -15,7 +15,7 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
import {SyncAccumulator} from "../../src/sync-accumulator";
import { SyncAccumulator } from "../../src/sync-accumulator";
// The event body & unsigned object get frozen to assert that they don't get altered
// by the impl
+11 -15
View File
@@ -1,5 +1,5 @@
import {EventTimeline} from "../../src/models/event-timeline";
import {TimelineIndex, TimelineWindow} from "../../src/timeline-window";
import { EventTimeline } from "../../src/models/event-timeline";
import { TimelineIndex, TimelineWindow } from "../../src/timeline-window";
import * as utils from "../test-utils";
const ROOM_ID = "roomId";
@@ -18,7 +18,7 @@ function createTimeline(numEvents, baseIndex) {
}
// XXX: this is a horrid hack
const timelineSet = { room: { roomId: ROOM_ID }};
const timelineSet = { room: { roomId: ROOM_ID } };
timelineSet.room.getUnfilteredTimelineSet = function() {
return timelineSet;
};
@@ -46,7 +46,6 @@ function addEventsToTimeline(timeline, numEvents, atStart) {
}
}
/*
* create a pair of linked timelines
*/
@@ -58,7 +57,6 @@ function createLinkedTimelines() {
return [tl1, tl2];
}
describe("TimelineIndex", function() {
describe("minIndex", function() {
it("should return the min index relative to BaseIndex", function() {
@@ -133,7 +131,6 @@ describe("TimelineIndex", function() {
});
});
describe("TimelineWindow", function() {
/**
* create a dummy eventTimelineSet and client, and a TimelineWindow
@@ -142,7 +139,7 @@ describe("TimelineWindow", function() {
let timelineSet;
let client;
function createWindow(timeline, opts) {
timelineSet = {getTimelineForEvent: () => null};
timelineSet = { getTimelineForEvent: () => null };
client = {};
client.getEventTimeline = function(timelineSet0, eventId0) {
expect(timelineSet0).toBe(timelineSet);
@@ -171,7 +168,7 @@ describe("TimelineWindow", function() {
const timeline = createTimeline();
const eventId = timeline.getEvents()[1].getId();
const timelineSet = {getTimelineForEvent: () => null};
const timelineSet = { getTimelineForEvent: () => null };
const client = {};
client.getEventTimeline = function(timelineSet0, eventId0) {
expect(timelineSet0).toBe(timelineSet);
@@ -193,7 +190,7 @@ describe("TimelineWindow", function() {
const eventId = timeline.getEvents()[1].getId();
const timelineSet = {getTimelineForEvent: () => null};
const timelineSet = { getTimelineForEvent: () => null };
const client = {};
const timelineWindow = new TimelineWindow(client, timelineSet);
@@ -266,7 +263,7 @@ describe("TimelineWindow", function() {
it("should advance into next timeline", function() {
const tls = createLinkedTimelines();
const eventId = tls[0].getEvents()[1].getId();
const timelineWindow = createWindow(tls[0], {windowLimit: 5});
const timelineWindow = createWindow(tls[0], { windowLimit: 5 });
return timelineWindow.load(eventId, 3).then(function() {
const expectedEvents = tls[0].getEvents();
@@ -311,7 +308,7 @@ describe("TimelineWindow", function() {
it("should retreat into previous timeline", function() {
const tls = createLinkedTimelines();
const eventId = tls[1].getEvents()[1].getId();
const timelineWindow = createWindow(tls[1], {windowLimit: 5});
const timelineWindow = createWindow(tls[1], { windowLimit: 5 });
return timelineWindow.load(eventId, 3).then(function() {
const expectedEvents = tls[1].getEvents();
@@ -357,7 +354,7 @@ describe("TimelineWindow", function() {
const timeline = createTimeline();
timeline.setPaginationToken("toktok", EventTimeline.FORWARDS);
const timelineWindow = createWindow(timeline, {windowLimit: 5});
const timelineWindow = createWindow(timeline, { windowLimit: 5 });
const eventId = timeline.getEvents()[1].getId();
client.paginateEventTimeline = function(timeline0, opts) {
@@ -385,12 +382,11 @@ describe("TimelineWindow", function() {
});
});
it("should make backward pagination requests", function() {
const timeline = createTimeline();
timeline.setPaginationToken("toktok", EventTimeline.BACKWARDS);
const timelineWindow = createWindow(timeline, {windowLimit: 5});
const timelineWindow = createWindow(timeline, { windowLimit: 5 });
const eventId = timeline.getEvents()[1].getId();
client.paginateEventTimeline = function(timeline0, opts) {
@@ -422,7 +418,7 @@ describe("TimelineWindow", function() {
const timeline = createTimeline();
timeline.setPaginationToken("toktok", EventTimeline.FORWARDS);
const timelineWindow = createWindow(timeline, {windowLimit: 5});
const timelineWindow = createWindow(timeline, { windowLimit: 5 });
const eventId = timeline.getEvents()[1].getId();
let paginateCount = 0;
+1 -1
View File
@@ -1,4 +1,4 @@
import {User} from "../../src/models/user";
import { User } from "../../src/models/user";
import * as utils from "../test-utils";
describe("User", function() {
+37 -60
View File
@@ -26,40 +26,6 @@ describe("utils", function() {
});
});
describe("forEach", function() {
it("should be invoked for each element", function() {
const arr = [];
utils.forEach([55, 66, 77], function(element) {
arr.push(element);
});
expect(arr).toEqual([55, 66, 77]);
});
});
describe("findElement", function() {
it("should find only 1 element if there is a match", function() {
const matchFn = function() {
return true;
};
const arr = [55, 66, 77];
expect(utils.findElement(arr, matchFn)).toEqual(55);
});
it("should be able to find in reverse order", function() {
const matchFn = function() {
return true;
};
const arr = [55, 66, 77];
expect(utils.findElement(arr, matchFn, true)).toEqual(77);
});
it("should find nothing if the function never returns true", function() {
const matchFn = function() {
return false;
};
const arr = [55, 66, 77];
expect(utils.findElement(arr, matchFn)).toBeFalsy();
});
});
describe("removeElement", function() {
it("should remove only 1 element if there is a match", function() {
const matchFn = function() {
@@ -103,20 +69,6 @@ describe("utils", function() {
});
});
describe("isArray", function() {
it("should return true for arrays", function() {
expect(utils.isArray([])).toBe(true);
expect(utils.isArray([5, 3, 7])).toBe(true);
expect(utils.isArray()).toBe(false);
expect(utils.isArray(null)).toBe(false);
expect(utils.isArray({})).toBe(false);
expect(utils.isArray("foo")).toBe(false);
expect(utils.isArray(555)).toBe(false);
expect(utils.isArray(function() {})).toBe(false);
});
});
describe("checkObjectHasKeys", function() {
it("should throw for missing keys", function() {
expect(function() {
@@ -188,19 +140,19 @@ describe("utils", function() {
it("should handle simple objects", function() {
assert.isTrue(utils.deepCompare({}, {}));
assert.isTrue(utils.deepCompare({a: 1, b: 2}, {a: 1, b: 2}));
assert.isTrue(utils.deepCompare({a: 1, b: 2}, {b: 2, a: 1}));
assert.isFalse(utils.deepCompare({a: 1, b: 2}, {a: 1, b: 3}));
assert.isTrue(utils.deepCompare({ a: 1, b: 2 }, { a: 1, b: 2 }));
assert.isTrue(utils.deepCompare({ a: 1, b: 2 }, { b: 2, a: 1 }));
assert.isFalse(utils.deepCompare({ a: 1, b: 2 }, { a: 1, b: 3 }));
assert.isTrue(utils.deepCompare({1: {name: "mhc", age: 28},
2: {name: "arb", age: 26}},
{1: {name: "mhc", age: 28},
2: {name: "arb", age: 26}}));
assert.isTrue(utils.deepCompare({ 1: { name: "mhc", age: 28 },
2: { name: "arb", age: 26 } },
{ 1: { name: "mhc", age: 28 },
2: { name: "arb", age: 26 } }));
assert.isFalse(utils.deepCompare({1: {name: "mhc", age: 28},
2: {name: "arb", age: 26}},
{1: {name: "mhc", age: 28},
2: {name: "arb", age: 27}}));
assert.isFalse(utils.deepCompare({ 1: { name: "mhc", age: 28 },
2: { name: "arb", age: 26 } },
{ 1: { name: "mhc", age: 28 },
2: { name: "arb", age: 27 } }));
assert.isFalse(utils.deepCompare({}, null));
assert.isFalse(utils.deepCompare({}, undefined));
@@ -223,7 +175,6 @@ describe("utils", function() {
});
});
describe("extend", function() {
const SOURCE = { "prop2": 1, "string2": "x", "newprop": "new" };
@@ -282,4 +233,30 @@ describe("utils", function() {
expect(target.nonenumerableProp).toBe(undefined);
});
});
describe("chunkPromises", function() {
it("should execute promises in chunks", async function() {
let promiseCount = 0;
function fn1() {
return new Promise(async function(resolve, reject) {
await utils.sleep(1);
expect(promiseCount).toEqual(0);
++promiseCount;
resolve();
});
}
function fn2() {
return new Promise(function(resolve, reject) {
expect(promiseCount).toEqual(1);
++promiseCount;
resolve();
});
}
await utils.chunkPromises([fn1, fn2], 1);
expect(promiseCount).toEqual(2);
});
});
});
+46 -2
View File
@@ -14,8 +14,8 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
import {TestClient} from '../../TestClient';
import {MatrixCall, CallErrorCode} from '../../../src/webrtc/call';
import { TestClient } from '../../TestClient';
import { MatrixCall, CallErrorCode, CallEvent } from '../../../src/webrtc/call';
const DUMMY_SDP = (
"v=0\r\n" +
@@ -254,4 +254,48 @@ describe('Call', function() {
sdpMid: '',
});
});
it('should map asserted identity messages to remoteAssertedIdentity', async function() {
const callPromise = call.placeVoiceCall();
await client.httpBackend.flush();
await callPromise;
await call.onAnswerReceived({
getContent: () => {
return {
version: 1,
call_id: call.callId,
party_id: 'party_id',
answer: {
sdp: DUMMY_SDP,
},
};
},
});
const identChangedCallback = jest.fn();
call.on(CallEvent.AssertedIdentityChanged, identChangedCallback);
await call.onAssertedIdentityReceived({
getContent: () => {
return {
version: 1,
call_id: call.callId,
party_id: 'party_id',
asserted_identity: {
id: "@steve:example.com",
display_name: "Steve Gibbons",
},
};
},
});
expect(identChangedCallback).toHaveBeenCalled();
const ident = call.getRemoteAssertedIdentity();
expect(ident.id).toEqual("@steve:example.com");
expect(ident.displayName).toEqual("Steve Gibbons");
// Hangup to stop timers
call.hangup(CallErrorCode.UserHangup, true);
});
});
+8 -5
View File
@@ -36,9 +36,8 @@ export enum EventType {
*/
RoomAliases = "m.room.aliases", // deprecated https://matrix.org/docs/spec/client_server/r0.6.1#historical-events
// Spaces MSC1772
SpaceChild = "org.matrix.msc1772.space.child",
SpaceParent = "org.matrix.msc1772.space.parent",
SpaceChild = "m.space.child",
SpaceParent = "m.space.parent",
// Room timeline events
RoomRedaction = "m.room.redaction",
@@ -53,12 +52,16 @@ export enum EventType {
CallSelectAnswer = "m.call.select_answer",
CallNegotiate = "m.call.negotiate",
CallReplaces = "m.call.replaces",
CallAssertedIdentity = "m.call.asserted_identity",
CallAssertedIdentityPrefix = "org.matrix.call.asserted_identity",
KeyVerificationRequest = "m.key.verification.request",
KeyVerificationStart = "m.key.verification.start",
KeyVerificationCancel = "m.key.verification.cancel",
KeyVerificationMac = "m.key.verification.mac",
KeyVerificationDone = "m.key.verification.done",
// use of this is discouraged https://matrix.org/docs/spec/client_server/r0.6.1#m-room-message-feedback
RoomMessageFeedback = "m.room.message.feedback",
Reaction = "m.reaction",
// Room ephemeral events
Typing = "m.typing",
@@ -92,8 +95,8 @@ export enum MsgType {
Video = "m.video",
}
export const RoomCreateTypeField = "org.matrix.msc1772.type"; // Spaces MSC1772
export const RoomCreateTypeField = "type";
export enum RoomType {
Space = "org.matrix.msc1772.space", // Spaces MSC1772
Space = "m.space",
}
+1 -1
View File
@@ -15,7 +15,7 @@ limitations under the License.
*/
// this is needed to tell TS about global.Olm
import * as Olm from "olm"; // eslint-disable-line @typescript-eslint/no-unused-vars
import * as Olm from "@matrix-org/olm"; // eslint-disable-line @typescript-eslint/no-unused-vars
export {};
+4 -4
View File
@@ -17,8 +17,8 @@ limitations under the License.
/** @module auto-discovery */
import {logger} from './logger';
import {URL as NodeURL} from "url";
import { logger } from './logger';
import { URL as NodeURL } from "url";
// Dev note: Auto discovery is part of the spec.
// See: https://matrix.org/docs/spec/client_server/r0.4.0.html#server-discovery
@@ -511,12 +511,12 @@ export class AutoDiscovery {
action = "IGNORE";
reason = AutoDiscovery.ERROR_MISSING_WELLKNOWN;
}
resolve({raw: {}, action: action, reason: reason, error: err});
resolve({ raw: {}, action: action, reason: reason, error: err });
return;
}
try {
resolve({raw: JSON.parse(body), action: "SUCCESS"});
resolve({ raw: JSON.parse(body), action: "SUCCESS" });
} catch (e) {
let reason = AutoDiscovery.ERROR_INVALID;
if (e.name === "SyntaxError") {
+72 -53
View File
@@ -24,11 +24,11 @@ limitations under the License.
* @module base-apis
*/
import {SERVICE_TYPES} from './service-types';
import {logger} from './logger';
import {PushProcessor} from "./pushprocessor";
import { SERVICE_TYPES } from './service-types';
import { logger } from './logger';
import { PushProcessor } from "./pushprocessor";
import * as utils from "./utils";
import {MatrixHttpApi, PREFIX_IDENTITY_V2, PREFIX_R0, PREFIX_UNSTABLE} from "./http-api";
import { MatrixHttpApi, PREFIX_IDENTITY_V2, PREFIX_R0, PREFIX_UNSTABLE } from "./http-api";
function termsUrlForService(serviceType, baseUrl) {
switch (serviceType) {
@@ -158,7 +158,6 @@ MatrixBaseApis.prototype.makeTxnId = function() {
return "m" + new Date().getTime() + "." + (this._txnCtr++);
};
// Registration/Login operations
// =============================
@@ -197,7 +196,7 @@ MatrixBaseApis.prototype.register = function(
) {
// backwards compat
if (bindThreepids === true) {
bindThreepids = {email: true};
bindThreepids = { email: true };
} else if (bindThreepids === null || bindThreepids === undefined) {
bindThreepids = {};
}
@@ -246,10 +245,25 @@ MatrixBaseApis.prototype.register = function(
/**
* Register a guest account.
* This method returns the auth info needed to create a new authenticated client,
* Remember to call `setGuest(true)` on the (guest-)authenticated client, e.g:
* ```javascript
* const tmpClient = await sdk.createClient(MATRIX_INSTANCE);
* const { user_id, device_id, access_token } = tmpClient.registerGuest();
* const client = createClient({
* baseUrl: MATRIX_INSTANCE,
* accessToken: access_token,
* userId: user_id,
* deviceId: device_id,
* })
* client.setGuest(true);
* ```
*
* @param {Object=} opts Registration options
* @param {Object} opts.body JSON HTTP body to provide.
* @param {module:client.callback} callback Optional.
* @return {Promise} Resolves: TODO
* @return {Promise} Resolves: JSON object that contains:
* { user_id, device_id, access_token, home_server }
* @return {module:http-api.MatrixError} Rejects: with an error response.
*/
MatrixBaseApis.prototype.registerGuest = function(opts, callback) {
@@ -364,14 +378,12 @@ MatrixBaseApis.prototype.getSsoLoginUrl = function(redirectUrl, loginType, idpId
loginType = "sso";
}
let prefix = PREFIX_R0;
let url = "/login/" + loginType + "/redirect";
if (idpId) {
url += "/" + idpId;
prefix = "/_matrix/client/unstable/org.matrix.msc2858";
}
return this._http.getUrl(url, { redirectUrl }, prefix);
return this._http.getUrl(url, { redirectUrl }, PREFIX_R0);
};
/**
@@ -386,7 +398,6 @@ MatrixBaseApis.prototype.loginWithToken = function(token, callback) {
}, callback);
};
/**
* Logs out the current session.
* Obviously, further calls that require authorisation should fail after this
@@ -532,7 +543,7 @@ MatrixBaseApis.prototype.fetchRelations =
* @return {module:http-api.MatrixError} Rejects: with an error response.
*/
MatrixBaseApis.prototype.roomState = function(roomId, callback) {
const path = utils.encodeUri("/rooms/$roomId/state", {$roomId: roomId});
const path = utils.encodeUri("/rooms/$roomId/state", { $roomId: roomId });
return this._http.authedRequest(callback, "GET", path);
};
@@ -580,7 +591,7 @@ function(roomId, includeMembership, excludeMembership, atEventId, callback) {
const queryString = utils.encodeParams(queryParams);
const path = utils.encodeUri("/rooms/$roomId/members?" + queryString,
{$roomId: roomId});
{ $roomId: roomId });
return this._http.authedRequest(callback, "GET", path);
};
@@ -592,20 +603,19 @@ function(roomId, includeMembership, excludeMembership, atEventId, callback) {
* @return {module:http-api.MatrixError} Rejects: with an error response.
*/
MatrixBaseApis.prototype.upgradeRoom = function(roomId, newVersion) {
const path = utils.encodeUri("/rooms/$roomId/upgrade", {$roomId: roomId});
const path = utils.encodeUri("/rooms/$roomId/upgrade", { $roomId: roomId });
return this._http.authedRequest(
undefined, "POST", path, undefined, {new_version: newVersion},
undefined, "POST", path, undefined, { new_version: newVersion },
);
};
/**
* @param {string} groupId
* @return {Promise} Resolves: Group summary object
* @return {module:http-api.MatrixError} Rejects: with an error response.
*/
MatrixBaseApis.prototype.getGroupSummary = function(groupId) {
const path = utils.encodeUri("/groups/$groupId/summary", {$groupId: groupId});
const path = utils.encodeUri("/groups/$groupId/summary", { $groupId: groupId });
return this._http.authedRequest(undefined, "GET", path);
};
@@ -615,7 +625,7 @@ MatrixBaseApis.prototype.getGroupSummary = function(groupId) {
* @return {module:http-api.MatrixError} Rejects: with an error response.
*/
MatrixBaseApis.prototype.getGroupProfile = function(groupId) {
const path = utils.encodeUri("/groups/$groupId/profile", {$groupId: groupId});
const path = utils.encodeUri("/groups/$groupId/profile", { $groupId: groupId });
return this._http.authedRequest(undefined, "GET", path);
};
@@ -630,7 +640,7 @@ MatrixBaseApis.prototype.getGroupProfile = function(groupId) {
* @return {module:http-api.MatrixError} Rejects: with an error response.
*/
MatrixBaseApis.prototype.setGroupProfile = function(groupId, profile) {
const path = utils.encodeUri("/groups/$groupId/profile", {$groupId: groupId});
const path = utils.encodeUri("/groups/$groupId/profile", { $groupId: groupId });
return this._http.authedRequest(
undefined, "POST", path, undefined, profile,
);
@@ -648,7 +658,7 @@ MatrixBaseApis.prototype.setGroupProfile = function(groupId, profile) {
MatrixBaseApis.prototype.setGroupJoinPolicy = function(groupId, policy) {
const path = utils.encodeUri(
"/groups/$groupId/settings/m.join_policy",
{$groupId: groupId},
{ $groupId: groupId },
);
return this._http.authedRequest(
undefined, "PUT", path, undefined, {
@@ -663,7 +673,7 @@ MatrixBaseApis.prototype.setGroupJoinPolicy = function(groupId, policy) {
* @return {module:http-api.MatrixError} Rejects: with an error response.
*/
MatrixBaseApis.prototype.getGroupUsers = function(groupId) {
const path = utils.encodeUri("/groups/$groupId/users", {$groupId: groupId});
const path = utils.encodeUri("/groups/$groupId/users", { $groupId: groupId });
return this._http.authedRequest(undefined, "GET", path);
};
@@ -673,7 +683,7 @@ MatrixBaseApis.prototype.getGroupUsers = function(groupId) {
* @return {module:http-api.MatrixError} Rejects: with an error response.
*/
MatrixBaseApis.prototype.getGroupInvitedUsers = function(groupId) {
const path = utils.encodeUri("/groups/$groupId/invited_users", {$groupId: groupId});
const path = utils.encodeUri("/groups/$groupId/invited_users", { $groupId: groupId });
return this._http.authedRequest(undefined, "GET", path);
};
@@ -683,7 +693,7 @@ MatrixBaseApis.prototype.getGroupInvitedUsers = function(groupId) {
* @return {module:http-api.MatrixError} Rejects: with an error response.
*/
MatrixBaseApis.prototype.getGroupRooms = function(groupId) {
const path = utils.encodeUri("/groups/$groupId/rooms", {$groupId: groupId});
const path = utils.encodeUri("/groups/$groupId/rooms", { $groupId: groupId });
return this._http.authedRequest(undefined, "GET", path);
};
@@ -696,7 +706,7 @@ MatrixBaseApis.prototype.getGroupRooms = function(groupId) {
MatrixBaseApis.prototype.inviteUserToGroup = function(groupId, userId) {
const path = utils.encodeUri(
"/groups/$groupId/admin/users/invite/$userId",
{$groupId: groupId, $userId: userId},
{ $groupId: groupId, $userId: userId },
);
return this._http.authedRequest(undefined, "PUT", path, undefined, {});
};
@@ -710,7 +720,7 @@ MatrixBaseApis.prototype.inviteUserToGroup = function(groupId, userId) {
MatrixBaseApis.prototype.removeUserFromGroup = function(groupId, userId) {
const path = utils.encodeUri(
"/groups/$groupId/admin/users/remove/$userId",
{$groupId: groupId, $userId: userId},
{ $groupId: groupId, $userId: userId },
);
return this._http.authedRequest(undefined, "PUT", path, undefined, {});
};
@@ -727,7 +737,7 @@ MatrixBaseApis.prototype.addUserToGroupSummary = function(groupId, userId, roleI
roleId ?
"/groups/$groupId/summary/$roleId/users/$userId" :
"/groups/$groupId/summary/users/$userId",
{$groupId: groupId, $roleId: roleId, $userId: userId},
{ $groupId: groupId, $roleId: roleId, $userId: userId },
);
return this._http.authedRequest(undefined, "PUT", path, undefined, {});
};
@@ -741,7 +751,7 @@ MatrixBaseApis.prototype.addUserToGroupSummary = function(groupId, userId, roleI
MatrixBaseApis.prototype.removeUserFromGroupSummary = function(groupId, userId) {
const path = utils.encodeUri(
"/groups/$groupId/summary/users/$userId",
{$groupId: groupId, $userId: userId},
{ $groupId: groupId, $userId: userId },
);
return this._http.authedRequest(undefined, "DELETE", path, undefined, {});
};
@@ -758,7 +768,7 @@ MatrixBaseApis.prototype.addRoomToGroupSummary = function(groupId, roomId, categ
categoryId ?
"/groups/$groupId/summary/$categoryId/rooms/$roomId" :
"/groups/$groupId/summary/rooms/$roomId",
{$groupId: groupId, $categoryId: categoryId, $roomId: roomId},
{ $groupId: groupId, $categoryId: categoryId, $roomId: roomId },
);
return this._http.authedRequest(undefined, "PUT", path, undefined, {});
};
@@ -772,7 +782,7 @@ MatrixBaseApis.prototype.addRoomToGroupSummary = function(groupId, roomId, categ
MatrixBaseApis.prototype.removeRoomFromGroupSummary = function(groupId, roomId) {
const path = utils.encodeUri(
"/groups/$groupId/summary/rooms/$roomId",
{$groupId: groupId, $roomId: roomId},
{ $groupId: groupId, $roomId: roomId },
);
return this._http.authedRequest(undefined, "DELETE", path, undefined, {});
};
@@ -790,7 +800,7 @@ MatrixBaseApis.prototype.addRoomToGroup = function(groupId, roomId, isPublic) {
}
const path = utils.encodeUri(
"/groups/$groupId/admin/rooms/$roomId",
{$groupId: groupId, $roomId: roomId},
{ $groupId: groupId, $roomId: roomId },
);
return this._http.authedRequest(undefined, "PUT", path, undefined,
{ "m.visibility": { type: isPublic ? "public" : "private" } },
@@ -812,7 +822,7 @@ MatrixBaseApis.prototype.updateGroupRoomVisibility = function(groupId, roomId, i
const path = utils.encodeUri(
"/groups/$groupId/admin/rooms/$roomId/config/m.visibility",
{$groupId: groupId, $roomId: roomId},
{ $groupId: groupId, $roomId: roomId },
);
return this._http.authedRequest(undefined, "PUT", path, undefined,
{ type: isPublic ? "public" : "private" },
@@ -828,7 +838,7 @@ MatrixBaseApis.prototype.updateGroupRoomVisibility = function(groupId, roomId, i
MatrixBaseApis.prototype.removeRoomFromGroup = function(groupId, roomId) {
const path = utils.encodeUri(
"/groups/$groupId/admin/rooms/$roomId",
{$groupId: groupId, $roomId: roomId},
{ $groupId: groupId, $roomId: roomId },
);
return this._http.authedRequest(undefined, "DELETE", path, undefined, {});
};
@@ -842,7 +852,7 @@ MatrixBaseApis.prototype.removeRoomFromGroup = function(groupId, roomId) {
MatrixBaseApis.prototype.acceptGroupInvite = function(groupId, opts = null) {
const path = utils.encodeUri(
"/groups/$groupId/self/accept_invite",
{$groupId: groupId},
{ $groupId: groupId },
);
return this._http.authedRequest(undefined, "PUT", path, undefined, opts || {});
};
@@ -855,7 +865,7 @@ MatrixBaseApis.prototype.acceptGroupInvite = function(groupId, opts = null) {
MatrixBaseApis.prototype.joinGroup = function(groupId) {
const path = utils.encodeUri(
"/groups/$groupId/self/join",
{$groupId: groupId},
{ $groupId: groupId },
);
return this._http.authedRequest(undefined, "PUT", path, undefined, {});
};
@@ -868,7 +878,7 @@ MatrixBaseApis.prototype.joinGroup = function(groupId) {
MatrixBaseApis.prototype.leaveGroup = function(groupId) {
const path = utils.encodeUri(
"/groups/$groupId/self/leave",
{$groupId: groupId},
{ $groupId: groupId },
);
return this._http.authedRequest(undefined, "PUT", path, undefined, {});
};
@@ -925,7 +935,7 @@ MatrixBaseApis.prototype.getPublicisedGroups = function(userIds) {
MatrixBaseApis.prototype.setGroupPublicity = function(groupId, isPublic) {
const path = utils.encodeUri(
"/groups/$groupId/self/update_publicity",
{$groupId: groupId},
{ $groupId: groupId },
);
return this._http.authedRequest(undefined, "PUT", path, undefined, {
publicise: isPublic,
@@ -993,7 +1003,7 @@ MatrixBaseApis.prototype.roomInitialSync = function(roomId, limit, callback) {
callback = limit; limit = undefined;
}
const path = utils.encodeUri("/rooms/$roomId/initialSync",
{$roomId: roomId},
{ $roomId: roomId },
);
if (!limit) {
limit = 30;
@@ -1144,7 +1154,7 @@ MatrixBaseApis.prototype.deleteAlias = function(alias, callback) {
MatrixBaseApis.prototype.unstableGetLocalAliases =
function(roomId, callback) {
const path = utils.encodeUri("/rooms/$roomId/aliases",
{$roomId: roomId});
{ $roomId: roomId });
const prefix = PREFIX_UNSTABLE + "/org.matrix.msc2432";
return this._http.authedRequest(callback, "GET", path,
null, null, { prefix });
@@ -1175,7 +1185,7 @@ MatrixBaseApis.prototype.getRoomIdForAlias = function(alias, callback) {
*/
MatrixBaseApis.prototype.resolveRoomAlias = function(roomAlias, callback) {
// TODO: deprecate this or getRoomIdForAlias
const path = utils.encodeUri("/directory/room/$alias", {$alias: roomAlias});
const path = utils.encodeUri("/directory/room/$alias", { $alias: roomAlias });
return this._http.request(callback, "GET", path);
};
@@ -1263,7 +1273,6 @@ MatrixBaseApis.prototype.searchUserDirectory = function(opts) {
);
};
// Media operations
// ================
@@ -1332,7 +1341,6 @@ MatrixBaseApis.prototype.getCurrentUploads = function() {
return this._http.getCurrentUploads();
};
// Profile operations
// ==================
@@ -1357,7 +1365,6 @@ MatrixBaseApis.prototype.getProfileInfo = function(userId, info, callback) {
return this._http.authedRequest(callback, "GET", path);
};
// Account operations
// ==================
@@ -1503,7 +1510,6 @@ MatrixBaseApis.prototype.setPassword = function(authDict, newPassword, callback)
);
};
// Device operations
// =================
@@ -1518,6 +1524,21 @@ MatrixBaseApis.prototype.getDevices = function() {
);
};
/**
* Gets specific device details for the logged-in user
* @param {string} device_id device to query
* @return {Promise} Resolves: result object
* @return {module:http-api.MatrixError} Rejects: with an error response.
*/
MatrixBaseApis.prototype.getDevice = function(device_id) {
const path = utils.encodeUri("/devices/$device_id", {
$device_id: device_id,
});
return this._http.authedRequest(
undefined, 'GET', path, undefined, undefined,
);
};
/**
* Update the given device
*
@@ -1565,7 +1586,7 @@ MatrixBaseApis.prototype.deleteDevice = function(device_id, auth) {
* @return {module:http-api.MatrixError} Rejects: with an error response.
*/
MatrixBaseApis.prototype.deleteMultipleDevices = function(devices, auth) {
const body = {devices};
const body = { devices };
if (auth) {
body.auth = auth;
@@ -1575,7 +1596,6 @@ MatrixBaseApis.prototype.deleteMultipleDevices = function(devices, auth) {
return this._http.authedRequest(undefined, "POST", path, undefined, body);
};
// Push operations
// ===============
@@ -1673,7 +1693,7 @@ MatrixBaseApis.prototype.setPushRuleEnabled = function(scope, kind,
$ruleId: ruleId,
});
return this._http.authedRequest(
callback, "PUT", path, undefined, {"enabled": enabled},
callback, "PUT", path, undefined, { "enabled": enabled },
);
};
@@ -1694,11 +1714,10 @@ MatrixBaseApis.prototype.setPushRuleActions = function(scope, kind,
$ruleId: ruleId,
});
return this._http.authedRequest(
callback, "PUT", path, undefined, {"actions": actions},
callback, "PUT", path, undefined, { "actions": actions },
);
};
// Search
// ======
@@ -1812,7 +1831,7 @@ MatrixBaseApis.prototype.claimOneTimeKeys = function(devices, key_algorithm, tim
queries[userId] = query;
query[deviceId] = key_algorithm;
}
const content = {one_time_keys: queries};
const content = { one_time_keys: queries };
if (timeout) {
content.timeout = timeout;
}
@@ -1842,7 +1861,7 @@ MatrixBaseApis.prototype.getKeyChanges = function(oldToken, newToken) {
MatrixBaseApis.prototype.uploadDeviceSigningKeys = function(auth, keys) {
const data = Object.assign({}, keys);
if (auth) Object.assign(data, {auth});
if (auth) Object.assign(data, { auth });
return this._http.authedRequest(
undefined, "POST", "/keys/device_signing/upload", undefined, data, {
prefix: PREFIX_UNSTABLE,
@@ -2136,7 +2155,7 @@ MatrixBaseApis.prototype.identityHashedLookup = async function(
throw new Error("Identity server returned more results than expected");
}
foundAddresses.push({address: plainAddress, mxid});
foundAddresses.push({ address: plainAddress, mxid });
}
return foundAddresses;
};
@@ -2227,7 +2246,7 @@ MatrixBaseApis.prototype.bulkLookupThreePids = async function(
]);
}
return {threepids: v1results};
return { threepids: v1results };
};
/**
@@ -2371,7 +2390,7 @@ MatrixBaseApis.prototype.reportEvent = function(roomId, eventId, score, reason)
$eventId: eventId,
});
return this._http.authedRequest(undefined, "POST", path, null, {score, reason});
return this._http.authedRequest(undefined, "POST", path, null, { score, reason });
};
/**
+158 -78
View File
@@ -17,46 +17,45 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* This is an internal module. See {@link MatrixClient} for the public class.
* @module client
*/
import url from "url";
import {EventEmitter} from "events";
import {MatrixBaseApis} from "./base-apis";
import {Filter} from "./filter";
import {SyncApi} from "./sync";
import {EventStatus, MatrixEvent} from "./models/event";
import {EventTimeline} from "./models/event-timeline";
import {SearchResult} from "./models/search-result";
import {StubStore} from "./store/stub";
import {createNewMatrixCall} from "./webrtc/call";
import {CallEventHandler} from './webrtc/callEventHandler';
import { EventEmitter } from "events";
import { MatrixBaseApis } from "./base-apis";
import { Filter } from "./filter";
import { SyncApi } from "./sync";
import { EventStatus, MatrixEvent } from "./models/event";
import { EventTimeline } from "./models/event-timeline";
import { SearchResult } from "./models/search-result";
import { StubStore } from "./store/stub";
import { createNewMatrixCall } from "./webrtc/call";
import { CallEventHandler } from './webrtc/callEventHandler';
import * as utils from './utils';
import {sleep} from './utils';
import { sleep } from './utils';
import {
MatrixError,
PREFIX_MEDIA_R0,
PREFIX_UNSTABLE,
retryNetworkOperation,
} from "./http-api";
import {getHttpUriForMxc} from "./content-repo";
import { getHttpUriForMxc } from "./content-repo";
import * as ContentHelpers from "./content-helpers";
import * as olmlib from "./crypto/olmlib";
import {ReEmitter} from './ReEmitter';
import {RoomList} from './crypto/RoomList';
import {logger} from './logger';
import {Crypto, isCryptoAvailable, fixBackupKey} from './crypto';
import {decodeRecoveryKey} from './crypto/recoverykey';
import {keyFromAuthData} from './crypto/key_passphrase';
import {randomString} from './randomstring';
import {PushProcessor} from "./pushprocessor";
import {encodeBase64, decodeBase64} from "./crypto/olmlib";
import { ReEmitter } from './ReEmitter';
import { RoomList } from './crypto/RoomList';
import { logger } from './logger';
import { Crypto, isCryptoAvailable, fixBackupKey } from './crypto';
import { decodeRecoveryKey } from './crypto/recoverykey';
import { keyFromAuthData } from './crypto/key_passphrase';
import { randomString } from './randomstring';
import { PushProcessor } from "./pushprocessor";
import { encodeBase64, decodeBase64 } from "./crypto/olmlib";
import { User } from "./models/user";
import {AutoDiscovery} from "./autodiscovery";
import {DEHYDRATION_ALGORITHM} from "./crypto/dehydration";
import { AutoDiscovery } from "./autodiscovery";
import { DEHYDRATION_ALGORITHM } from "./crypto/dehydration";
const SCROLLBACK_DELAY_MS = 3000;
export const CRYPTO_ENABLED = isCryptoAvailable();
@@ -353,6 +352,10 @@ export function MatrixClient(opts) {
if (call) {
this._callEventHandler = new CallEventHandler(this);
this._supportsVoip = true;
// Start listening for calls after the initial sync is done
// We do not need to backfill the call event buffer
// with encrypted events that might never get decrypted
this.on("sync", this._startCallEventHandler);
} else {
this._callEventHandler = null;
}
@@ -500,19 +503,8 @@ MatrixClient.prototype.rehydrateDevice = async function() {
return;
}
let getDeviceResult;
try {
getDeviceResult = await this._http.authedRequest(
undefined,
"GET",
"/dehydrated_device",
undefined, undefined,
{
prefix: "/_matrix/client/unstable/org.matrix.msc2697.v2",
},
);
} catch (e) {
logger.info("could not get dehydrated device", e.toString());
const getDeviceResult = await this.getDehydratedDevice();
if (!getDeviceResult) {
return;
}
@@ -574,6 +566,27 @@ MatrixClient.prototype.rehydrateDevice = async function() {
}
};
/**
* Get the current dehydrated device, if any
* @return {Promise} A promise of an object containing the dehydrated device
*/
MatrixClient.prototype.getDehydratedDevice = async function() {
try {
return await this._http.authedRequest(
undefined,
"GET",
"/dehydrated_device",
undefined, undefined,
{
prefix: "/_matrix/client/unstable/org.matrix.msc2697.v2",
},
);
} catch (e) {
logger.info("could not get dehydrated device", e.toString());
return;
}
};
/**
* Set the dehydration key. This will also periodically dehydrate devices to
* the server.
@@ -692,7 +705,6 @@ MatrixClient.prototype.getDeviceId = function() {
return this.deviceId;
};
/**
* Check if the runtime environment supports VoIP calling.
* @return {boolean} True if VoIP is supported.
@@ -719,6 +731,17 @@ MatrixClient.prototype.setSupportsCallTransfer = function(supportsCallTransfer)
this._supportsCallTransfer = supportsCallTransfer;
};
/**
* Creates a new call.
* The place*Call methods on the returned call can be used to actually place a call
*
* @param {string} roomId The room the call is to be placed in.
* @return {MatrixCall} the call or null if the browser doesn't support calling.
*/
MatrixClient.prototype.createCall = function(roomId) {
return createNewMatrixCall(this, roomId);
};
/**
* Get the current sync state.
* @return {?string} the sync state, which may be null.
@@ -944,14 +967,12 @@ MatrixClient.prototype.initCrypto = async function() {
this.olmVersion = Crypto.getOlmVersion();
// if crypto initialisation was successful, tell it to attach its event
// handlers.
crypto.registerEventHandlers(this);
this._crypto = crypto;
};
/**
* Is end-to-end crypto enabled for this client.
* @return {boolean} True if end-to-end is enabled.
@@ -1765,7 +1786,7 @@ MatrixClient.prototype.checkKeyBackup = function() {
MatrixClient.prototype.getKeyBackupVersion = function() {
return this._http.authedRequest(
undefined, "GET", "/room_keys/version", undefined, undefined,
{prefix: PREFIX_UNSTABLE},
{ prefix: PREFIX_UNSTABLE },
).then((res) => {
if (res.algorithm !== olmlib.MEGOLM_BACKUP_ALGORITHM) {
const err = "Unknown backup algorithm: " + res.algorithm;
@@ -1943,7 +1964,7 @@ MatrixClient.prototype.createKeyBackupVersion = async function(info) {
const res = await this._http.authedRequest(
undefined, "POST", "/room_keys/version", undefined, data,
{prefix: PREFIX_UNSTABLE},
{ prefix: PREFIX_UNSTABLE },
);
// We could assume everything's okay and enable directly, but this ensures
@@ -1975,7 +1996,7 @@ MatrixClient.prototype.deleteKeyBackupVersion = function(version) {
return this._http.authedRequest(
undefined, "DELETE", path, undefined, undefined,
{prefix: PREFIX_UNSTABLE},
{ prefix: PREFIX_UNSTABLE },
);
};
@@ -2017,7 +2038,7 @@ MatrixClient.prototype.sendKeyBackup = function(roomId, sessionId, version, data
const path = this._makeKeyBackupPath(roomId, sessionId, version);
return this._http.authedRequest(
undefined, "PUT", path.path, path.queryData, data,
{prefix: PREFIX_UNSTABLE},
{ prefix: PREFIX_UNSTABLE },
);
};
@@ -2217,7 +2238,7 @@ MatrixClient.prototype._restoreKeyBackup = function(
// doesn't match the one in the auth_data, the user has enetered
// a different recovery key / the wrong passphrase.
if (backupPubKey !== backupInfo.auth_data.public_key) {
return Promise.reject({errcode: MatrixClient.RESTORE_BACKUP_ERROR_BAD_KEY});
return Promise.reject({ errcode: MatrixClient.RESTORE_BACKUP_ERROR_BAD_KEY });
}
// Cache the key, if possible.
@@ -2235,7 +2256,7 @@ MatrixClient.prototype._restoreKeyBackup = function(
return this._http.authedRequest(
undefined, "GET", path.path, path.queryData, undefined,
{prefix: PREFIX_UNSTABLE},
{ prefix: PREFIX_UNSTABLE },
).then((res) => {
if (res.rooms) {
for (const [roomId, roomData] of Object.entries(res.rooms)) {
@@ -2275,7 +2296,7 @@ MatrixClient.prototype._restoreKeyBackup = function(
}).then(() => {
return this._crypto.setTrustedBackupPubKey(backupPubKey);
}).then(() => {
return {total: totalKeyCount, imported: keys.length};
return { total: totalKeyCount, imported: keys.length };
}).finally(() => {
decryption.free();
});
@@ -2289,10 +2310,43 @@ MatrixClient.prototype.deleteKeysFromBackup = function(roomId, sessionId, versio
const path = this._makeKeyBackupPath(roomId, sessionId, version);
return this._http.authedRequest(
undefined, "DELETE", path.path, path.queryData, undefined,
{prefix: PREFIX_UNSTABLE},
{ prefix: PREFIX_UNSTABLE },
);
};
/**
* Share shared-history decryption keys with the given users.
*
* @param {string} roomId the room for which keys should be shared.
* @param {array} userIds a list of users to share with. The keys will be sent to
* all of the user's current devices.
*/
MatrixClient.prototype.sendSharedHistoryKeys = async function(roomId, userIds) {
if (this._crypto === null) {
throw new Error("End-to-end encryption disabled");
}
const roomEncryption = this._roomList.getRoomEncryption(roomId);
if (!roomEncryption) {
// unknown room, or unencrypted room
logger.error("Unknown room. Not sharing decryption keys");
return;
}
const deviceInfos = await this._crypto.downloadKeys(userIds);
const devicesByUser = {};
for (const [userId, devices] of Object.entries(deviceInfos)) {
devicesByUser[userId] = Object.values(devices);
}
const alg = this._crypto._getRoomDecryptor(roomId, roomEncryption.algorithm);
if (alg.sendSharedHistoryInboundSessions) {
await alg.sendSharedHistoryInboundSessions(devicesByUser);
} else {
logger.warning("Algorithm does not support sharing previous keys", roomEncryption.algorithm);
}
};
// Group ops
// =========
// Operations on groups that come down the sync stream (ie. ones the
@@ -2491,7 +2545,7 @@ MatrixClient.prototype.getIgnoredUsers = function() {
* @return {module:http-api.MatrixError} Rejects: with an error response.
*/
MatrixClient.prototype.setIgnoredUsers = function(userIds, callback) {
const content = {ignored_users: {}};
const content = { ignored_users: {} };
userIds.map((u) => content.ignored_users[u] = {});
return this.setAccountData("m.ignored_user_list", content, callback);
};
@@ -2552,7 +2606,7 @@ MatrixClient.prototype.joinRoom = function(roomIdOrAlias, opts, callback) {
queryString["server_name"] = opts.viaServers;
}
const reqOpts = {qsStringifyOptions: {arrayFormat: 'repeat'}};
const reqOpts = { qsStringifyOptions: { arrayFormat: 'repeat' } };
const self = this;
const prom = new Promise((resolve, reject) => {
@@ -2562,7 +2616,7 @@ MatrixClient.prototype.joinRoom = function(roomIdOrAlias, opts, callback) {
data.third_party_signed = signed_invite_object;
}
const path = utils.encodeUri("/join/$roomid", { $roomid: roomIdOrAlias});
const path = utils.encodeUri("/join/$roomid", { $roomid: roomIdOrAlias });
return self._http.authedRequest(
undefined, "POST", path, queryString, data, reqOpts);
}).then(function(res) {
@@ -2626,7 +2680,7 @@ MatrixClient.prototype.cancelPendingEvent = function(event) {
* @return {module:http-api.MatrixError} Rejects: with an error response.
*/
MatrixClient.prototype.setRoomName = function(roomId, name, callback) {
return this.sendStateEvent(roomId, "m.room.name", {name: name},
return this.sendStateEvent(roomId, "m.room.name", { name: name },
undefined, callback);
};
@@ -2638,7 +2692,7 @@ MatrixClient.prototype.setRoomName = function(roomId, name, callback) {
* @return {module:http-api.MatrixError} Rejects: with an error response.
*/
MatrixClient.prototype.setRoomTopic = function(roomId, topic, callback) {
return this.sendStateEvent(roomId, "m.room.topic", {topic: topic},
return this.sendStateEvent(roomId, "m.room.topic", { topic: topic },
undefined, callback);
};
@@ -2824,7 +2878,6 @@ MatrixClient.prototype._sendCompleteEvent = function(roomId, eventObject, txnId,
return _sendEvent(this, room, localEvent, callback);
};
// encrypts the event if necessary
// adds the event to the queue, or sends it
// marks the event as sent/unsent
@@ -3672,7 +3725,7 @@ function _setMembershipState(client, roomId, userId, membershipValue, reason,
const path = utils.encodeUri(
"/rooms/$roomId/state/m.room.member/$userId",
{ $roomId: roomId, $userId: userId},
{ $roomId: roomId, $userId: userId },
);
return client._http.authedRequest(callback, "PUT", path, undefined, {
@@ -3922,9 +3975,9 @@ MatrixClient.prototype.scrollback = function(room, limit, callback) {
limit,
'b');
}).then(function(res) {
const matrixEvents = utils.map(res.chunk, _PojoToMatrixEventMapper(self));
const matrixEvents = res.chunk.map(_PojoToMatrixEventMapper(self));
if (res.state) {
const stateEvents = utils.map(res.state, _PojoToMatrixEventMapper(self));
const stateEvents = res.state.map(_PojoToMatrixEventMapper(self));
room.currentState.setUnknownStateEvents(stateEvents);
}
room.addEventsToTimeline(matrixEvents, true, room.getLiveTimeline());
@@ -3987,7 +4040,7 @@ MatrixClient.prototype.getEventTimeline = function(timelineSet, eventId) {
let params = undefined;
if (this._clientOpts.lazyLoadMembers) {
params = {filter: JSON.stringify(Filter.LAZY_LOADING_MESSAGES_FILTER)};
params = { filter: JSON.stringify(Filter.LAZY_LOADING_MESSAGES_FILTER) };
}
// TODO: we should implement a backoff (as per scrollback()) to deal more
@@ -4013,16 +4066,16 @@ MatrixClient.prototype.getEventTimeline = function(timelineSet, eventId) {
const events = res.events_after
.concat([res.event])
.concat(res.events_before);
const matrixEvents = utils.map(events, self.getEventMapper());
const matrixEvents = events.map(self.getEventMapper());
let timeline = timelineSet.getTimelineForEvent(matrixEvents[0].getId());
if (!timeline) {
timeline = timelineSet.addTimeline();
timeline.initialiseState(utils.map(res.state,
timeline.initialiseState(res.state.map(
self.getEventMapper()));
timeline.getState(EventTimeline.FORWARDS).paginationToken = res.end;
} else {
const stateEvents = utils.map(res.state, self.getEventMapper());
const stateEvents = res.state.map(self.getEventMapper());
timeline.getState(EventTimeline.BACKWARDS).setUnknownStateEvents(stateEvents);
}
timelineSet.addEventsToTimeline(matrixEvents, true, timeline, res.start);
@@ -4053,7 +4106,7 @@ MatrixClient.prototype.getEventTimeline = function(timelineSet, eventId) {
MatrixClient.prototype._createMessagesRequest =
function(roomId, fromToken, limit, dir, timelineFilter = undefined) {
const path = utils.encodeUri(
"/rooms/$roomId/messages", {$roomId: roomId},
"/rooms/$roomId/messages", { $roomId: roomId },
);
if (limit === undefined) {
limit = 30;
@@ -4185,11 +4238,11 @@ MatrixClient.prototype.paginateEventTimeline = function(eventTimeline, opts) {
promise.then(function(res) {
if (res.state) {
const roomState = eventTimeline.getState(dir);
const stateEvents = utils.map(res.state, self.getEventMapper());
const stateEvents = res.state.map(self.getEventMapper());
roomState.setUnknownStateEvents(stateEvents);
}
const token = res.end;
const matrixEvents = utils.map(res.chunk, self.getEventMapper());
const matrixEvents = res.chunk.map(self.getEventMapper());
eventTimeline.getTimelineSet()
.addEventsToTimeline(matrixEvents, backwards, eventTimeline, token);
@@ -4508,7 +4561,6 @@ MatrixClient.prototype._requestTokenFromEndpoint = async function(endpoint, para
);
};
// Push operations
// ===============
@@ -4687,7 +4739,7 @@ MatrixClient.prototype.searchRoomEvents = function(opts) {
highlights: [],
};
return this.search({body: body}).then(
return this.search({ body: body }).then(
this._processRoomEventsSearch.bind(this, searchResults),
);
};
@@ -4756,14 +4808,14 @@ MatrixClient.prototype._processRoomEventsSearch = function(searchResults, respon
searchResults.highlights = Object.keys(highlights);
// append the new results to our existing results
for (let i = 0; i < room_events.results.length; i++) {
const resultsLength = room_events.results ? room_events.results.length : 0;
for (let i = 0; i < resultsLength; i++) {
const sr = SearchResult.fromJson(room_events.results[i], this.getEventMapper());
searchResults.results.push(sr);
}
return searchResults;
};
/**
* Populate the store with rooms the user has left.
* @return {Promise} Resolves: TODO - Resolved when the rooms have
@@ -4909,7 +4961,6 @@ MatrixClient.prototype.getOrCreateFilter = async function(filterName, filter) {
return createdFilter.filterId;
};
/**
* Gets a bearer token from the Home Server that the user can
* present to a third party in order to prove their ownership
@@ -4927,10 +4978,16 @@ MatrixClient.prototype.getOpenIdToken = function() {
);
};
// VoIP operations
// ===============
MatrixClient.prototype._startCallEventHandler = function() {
if (this.isInitialSyncComplete()) {
this._callEventHandler.start();
this.off("sync", this._startCallEventHandler);
}
};
/**
* @param {module:client.callback} callback Optional.
* @return {Promise} Resolves: TODO
@@ -5037,7 +5094,7 @@ MatrixClient.prototype.isSynapseAdministrator = function() {
{ $userId: this.getUserId() },
);
return this._http.authedRequest(
undefined, 'GET', path, undefined, undefined, {prefix: ''},
undefined, 'GET', path, undefined, undefined, { prefix: '' },
).then(r => r['admin']); // pull out the specific boolean we want
};
@@ -5054,7 +5111,7 @@ MatrixClient.prototype.whoisSynapseUser = function(userId) {
{ $userId: userId },
);
return this._http.authedRequest(
undefined, 'GET', path, undefined, undefined, {prefix: ''},
undefined, 'GET', path, undefined, undefined, { prefix: '' },
);
};
@@ -5070,7 +5127,7 @@ MatrixClient.prototype.deactivateSynapseUser = function(userId) {
{ $userId: userId },
);
return this._http.authedRequest(
undefined, 'POST', path, undefined, undefined, {prefix: ''},
undefined, 'POST', path, undefined, undefined, { prefix: '' },
);
};
@@ -5088,7 +5145,6 @@ MatrixClient.prototype.deactivateSynapseUser = function(userId) {
// due to ambiguity (or should this be on a chat-specific layer)?
// reconnect after connectivity outages
/**
* High level helper method to begin syncing and poll for new events. To listen for these
* events, add a listener for {@link module:client~MatrixClient#event:"event"}
@@ -5239,7 +5295,7 @@ MatrixClient.prototype._unstable_getSharedRooms = async function(userId) {
});
const res = await this._http.authedRequest(
undefined, "GET", path, undefined, undefined,
{prefix: PREFIX_UNSTABLE},
{ prefix: PREFIX_UNSTABLE },
);
return res.joined;
};
@@ -5499,8 +5555,9 @@ function _resolve(callback, resolve, res) {
resolve(res);
}
function _PojoToMatrixEventMapper(client, options) {
const preventReEmit = Boolean(options && options.preventReEmit);
function _PojoToMatrixEventMapper(client, options = {}) {
const preventReEmit = Boolean(options.preventReEmit);
const decrypt = options.decrypt !== false;
function mapper(plainOldJsObject) {
const event = new MatrixEvent(plainOldJsObject);
if (event.isEncrypted()) {
@@ -5509,7 +5566,9 @@ function _PojoToMatrixEventMapper(client, options) {
"Event.decrypted",
]);
}
event.attemptDecryption(client._crypto);
if (decrypt) {
client.decryptEventIfNeeded(event);
}
}
if (!preventReEmit) {
client.reEmitter.reEmit(event, ["Event.replaced"]);
@@ -5522,6 +5581,7 @@ function _PojoToMatrixEventMapper(client, options) {
/**
* @param {object} [options]
* @param {bool} options.preventReEmit don't reemit events emitted on an event mapped by this mapper on the client
* @param {bool} options.decrypt decrypt event proactively
* @return {Function}
*/
MatrixClient.prototype.getEventMapper = function(options = undefined) {
@@ -5549,6 +5609,26 @@ MatrixClient.prototype.generateClientSecret = function() {
return randomString(32);
};
/**
* Attempts to decrypt an event
* @param {MatrixEvent} event The event to decrypt
* @returns {Promise<void>} A decryption promise
* @param {object} options
* @param {bool} options.isRetry True if this is a retry (enables more logging)
* @param {bool} options.emit Emits "event.decrypted" if set to true
*/
MatrixClient.prototype.decryptEventIfNeeded = function(event, options) {
if (event.shouldAttemptDecryption()) {
event.attemptDecryption(this._crypto, options);
}
if (event.isBeingDecrypted()) {
return event._decryptionPromise;
} else {
return Promise.resolve();
}
};
// MatrixClient Event JSDocs
/**
+2 -2
View File
@@ -59,7 +59,7 @@ export function getHttpUriForMxc(baseUrl, mxc, width, height,
if (resizeMethod) {
params.method = resizeMethod;
}
if (utils.keys(params).length > 0) {
if (Object.keys(params).length > 0) {
// these are thumbnailing params so they probably want the
// thumbnailing API...
prefix = "/_matrix/media/r0/thumbnail/";
@@ -72,6 +72,6 @@ export function getHttpUriForMxc(baseUrl, mxc, width, height,
serverAndMediaId = serverAndMediaId.substr(0, fragmentOffset);
}
return baseUrl + prefix + serverAndMediaId +
(utils.keys(params).length === 0 ? "" :
(Object.keys(params).length === 0 ? "" :
("?" + utils.encodeParams(params))) + fragment;
}
+5 -5
View File
@@ -20,11 +20,11 @@ limitations under the License.
* @module crypto/CrossSigning
*/
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';
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;
+21 -17
View File
@@ -22,14 +22,13 @@ limitations under the License.
* Manages the list of other users' devices
*/
import {EventEmitter} from 'events';
import {logger} from '../logger';
import {DeviceInfo} from './deviceinfo';
import {CrossSigningInfo} from './CrossSigning';
import { EventEmitter } from 'events';
import { logger } from '../logger';
import { DeviceInfo } from './deviceinfo';
import { CrossSigningInfo } from './CrossSigning';
import * as olmlib from './olmlib';
import {IndexedDBCryptoStore} from './store/indexeddb-crypto-store';
import {defer, sleep} from '../utils';
import { IndexedDBCryptoStore } from './store/indexeddb-crypto-store';
import { chunkPromises, defer, sleep } from '../utils';
/* State transition diagram for DeviceList._deviceTrackingStatus
*
@@ -51,7 +50,6 @@ import {defer, sleep} from '../utils';
* +----------------------- UP_TO_DATE ------------------------+
*/
// constants for DeviceList._deviceTrackingStatus
const TRACKING_STATUS_NOT_TRACKED = 0;
const TRACKING_STATUS_PENDING_DOWNLOAD = 1;
@@ -62,7 +60,7 @@ const TRACKING_STATUS_UP_TO_DATE = 3;
* @alias module:crypto/DeviceList
*/
export class DeviceList extends EventEmitter {
constructor(baseApis, cryptoStore, olmDevice) {
constructor(baseApis, cryptoStore, olmDevice, keyDownloadChunkSize = 250) {
super();
this._cryptoStore = cryptoStore;
@@ -98,6 +96,9 @@ export class DeviceList extends EventEmitter {
// userId -> promise
this._keyDownloadsInProgressByUser = {};
// Maximum number of user IDs per request to prevent server overload (#1619)
this._keyDownloadChunkSize = keyDownloadChunkSize;
// Set whenever changes are made other than setting the sync token
this._dirty = false;
@@ -780,13 +781,17 @@ class DeviceListUpdateSerialiser {
opts.token = this._syncToken;
}
this._baseApis.downloadKeysForUsers(
downloadUsers, opts,
).then(async (res) => {
const dk = res.device_keys || {};
const masterKeys = res.master_keys || {};
const ssks = res.self_signing_keys || {};
const usks = res.user_signing_keys || {};
const factories = [];
for (let i = 0; i < downloadUsers.length; i += this._deviceList._keyDownloadChunkSize) {
const userSlice = downloadUsers.slice(i, i + this._deviceList._keyDownloadChunkSize);
factories.push(() => this._baseApis.downloadKeysForUsers(userSlice, opts));
}
chunkPromises(factories, 3).then(async (responses) => {
const dk = Object.assign({}, ...(responses.map(res => res.device_keys || {})));
const masterKeys = Object.assign({}, ...(responses.map(res => res.master_keys || {})));
const ssks = Object.assign({}, ...(responses.map(res => res.self_signing_keys || {})));
const usks = Object.assign({}, ...(responses.map(res => res.user_signing_keys || {})));
// yield to other things that want to execute in between users, to
// avoid wedging the CPU
@@ -885,7 +890,6 @@ class DeviceListUpdateSerialiser {
}
}
async function _updateStoredDeviceKeysForUser(
_olmDevice, userId, userStore, userResult, localUserId, localDeviceId,
) {
+9 -11
View File
@@ -1,8 +1,8 @@
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 { 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";
@@ -43,7 +43,7 @@ export class EncryptionSetupBuilder {
* @param {Object} keys the new keys
*/
addCrossSigningKeys(authUpload, keys) {
this._crossSigningKeys = {authUpload, keys};
this._crossSigningKeys = { authUpload, keys };
}
/**
@@ -86,7 +86,6 @@ export class EncryptionSetupBuilder {
userSignatures[deviceId] = signature;
}
/**
* @param {String} type
* @param {Object} content
@@ -211,21 +210,20 @@ export class EncryptionSetupOperation {
algorithm: this._keyBackupInfo.algorithm,
auth_data: this._keyBackupInfo.auth_data,
},
{prefix: PREFIX_UNSTABLE},
{ prefix: PREFIX_UNSTABLE },
);
} else {
// add new key backup
await baseApis._http.authedRequest(
undefined, "POST", "/room_keys/version",
undefined, this._keyBackupInfo,
{prefix: PREFIX_UNSTABLE},
{ prefix: PREFIX_UNSTABLE },
);
}
}
}
}
/**
* Catches account data set by SecretStorage during bootstrapping by
* implementing the methods related to account data in MatrixClient
@@ -276,7 +274,7 @@ class AccountDataClientAdapter extends EventEmitter {
// 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});
const event = new MatrixEvent({ type, content });
this.emit("accountData", event, lastEvent);
});
}
@@ -335,7 +333,7 @@ class SSSSCryptoCallbacks {
// for it to the general crypto callbacks and cache it
if (this._delegateCryptoCallbacks) {
const result = await this._delegateCryptoCallbacks.
getSecretStorageKey({keys}, name);
getSecretStorageKey({ keys }, name);
if (result) {
const [keyId, privateKey] = result;
this._privateKeys.set(keyId, privateKey);
+25 -15
View File
@@ -16,8 +16,8 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
import {logger} from '../logger';
import {IndexedDBCryptoStore} from './store/indexeddb-crypto-store';
import { logger } from '../logger';
import { IndexedDBCryptoStore } from './store/indexeddb-crypto-store';
import * as algorithms from './algorithms';
// The maximum size of an event is 65K, and we base64 the content, so this is a
@@ -48,7 +48,6 @@ function checkPayloadLength(payloadString) {
}
}
/**
* The type of object we use for importing and exporting megolm session data.
*
@@ -62,7 +61,6 @@ function checkPayloadLength(payloadString) {
* @property {String} session_key Base64'ed key data
*/
/**
* Manages the olm cryptography functions. Each OlmDevice has a single
* OlmAccount and a number of OlmSessions.
@@ -350,7 +348,7 @@ OlmDevice.prototype._unpickleSession = function(sessionInfo, func) {
const session = new global.Olm.Session();
try {
session.unpickle(this._pickleKey, sessionInfo.session);
const unpickledSessInfo = Object.assign({}, sessionInfo, {session});
const unpickledSessInfo = Object.assign({}, sessionInfo, { session });
func(unpickledSessInfo);
} finally {
@@ -376,7 +374,6 @@ OlmDevice.prototype._saveSession = function(deviceKey, sessionInfo, txn) {
);
};
/**
* get an OlmUtility and call the given function
*
@@ -393,7 +390,6 @@ OlmDevice.prototype._getUtility = function(func) {
}
};
/**
* Signs a message with the ed25519 key for this account.
*
@@ -434,7 +430,6 @@ OlmDevice.prototype.getOneTimeKeys = async function() {
return result;
};
/**
* Get the maximum number of one-time keys we can store.
*
@@ -550,7 +545,6 @@ OlmDevice.prototype.createOutboundSession = async function(
return newSessionId;
};
/**
* Generate a new inbound session, given an incoming message
*
@@ -612,7 +606,6 @@ OlmDevice.prototype.createInboundSession = async function(
return result;
};
/**
* Get a list of known session IDs for the given device
*
@@ -856,7 +849,6 @@ OlmDevice.prototype.filterOutNotifiedErrorDevices = async function(devices) {
return await this._cryptoStore.filterOutNotifiedErrorDevices(devices);
};
// Outbound group session
// ======================
@@ -871,7 +863,6 @@ OlmDevice.prototype._saveOutboundGroupSession = function(session) {
this._outboundGroupSessionStore[session.session_id()] = pickledSession;
};
/**
* extract an OutboundGroupSession from _outboundGroupSessionStore and call the
* given function
@@ -896,7 +887,6 @@ OlmDevice.prototype._getOutboundGroupSession = function(sessionId, func) {
}
};
/**
* Generate a new outbound group session
*
@@ -913,7 +903,6 @@ OlmDevice.prototype.createOutboundGroupSession = function() {
}
};
/**
* Encrypt an outgoing message with an outbound group session
*
@@ -953,7 +942,6 @@ OlmDevice.prototype.getOutboundGroupSessionKey = function(sessionId) {
});
};
// Inbound group session
// =====================
@@ -1048,6 +1036,7 @@ OlmDevice.prototype.addInboundGroupSession = async function(
'readwrite', [
IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS,
IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS_WITHHELD,
IndexedDBCryptoStore.STORE_SHARED_HISTORY_INBOUND_GROUP_SESSIONS,
], (txn) => {
/* if we already have this session, consider updating it */
this._getInboundGroupSession(
@@ -1104,6 +1093,12 @@ OlmDevice.prototype.addInboundGroupSession = async function(
this._cryptoStore.storeEndToEndInboundGroupSession(
senderKey, sessionId, sessionData, txn,
);
if (!existingSession && extraSessionData.sharedHistory) {
this._cryptoStore.addSharedHistoryInboundGroupSession(
roomId, senderKey, sessionId, txn,
);
}
} finally {
session.free();
}
@@ -1383,6 +1378,7 @@ OlmDevice.prototype.getInboundGroupSessionKey = async function(
"forwarding_curve25519_key_chain":
sessionData.forwardingCurve25519KeyChain || [],
"sender_claimed_ed25519_key": senderEd25519Key,
"shared_history": sessionData.sharedHistory || false,
};
},
);
@@ -1415,10 +1411,24 @@ OlmDevice.prototype.exportInboundGroupSession = function(
"session_key": session.export_session(messageIndex),
"forwarding_curve25519_key_chain": session.forwardingCurve25519KeyChain || [],
"first_known_index": session.first_known_index(),
"org.matrix.msc3061.shared_history": sessionData.sharedHistory || false,
};
});
};
OlmDevice.prototype.getSharedHistoryInboundGroupSessions = async function(roomId) {
let result;
await this._cryptoStore.doTxn(
'readonly', [
IndexedDBCryptoStore.STORE_SHARED_HISTORY_INBOUND_GROUP_SESSIONS,
], (txn) => {
result = this._cryptoStore.getSharedHistoryInboundGroupSessions(roomId, txn);
},
logger.withPrefix("[getSharedHistoryInboundGroupSessionsForRoom]"),
);
return result;
};
// Utilities
// =========
+2 -3
View File
@@ -14,8 +14,7 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
import {logger} from '../logger';
import * as utils from '../utils';
import { logger } from '../logger';
/**
* Internal module. Management of outgoing room key requests.
@@ -496,7 +495,7 @@ function stringifyRequestBody(requestBody) {
function stringifyRecipientList(recipients) {
return '['
+ utils.map(recipients, (r) => `${r.userId}:${r.deviceId}`).join(",")
+ recipients.map((r) => `${r.userId}:${r.deviceId}`).join(",")
+ ']';
}
+1 -1
View File
@@ -20,7 +20,7 @@ limitations under the License.
* Manages the list of encrypted rooms
*/
import {IndexedDBCryptoStore} from './store/indexeddb-crypto-store';
import { IndexedDBCryptoStore } from './store/indexeddb-crypto-store';
/**
* @alias module:crypto/RoomList
+10 -10
View File
@@ -14,12 +14,12 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
import {EventEmitter} from 'events';
import {logger} from '../logger';
import { EventEmitter } from 'events';
import { logger } from '../logger';
import * as olmlib from './olmlib';
import {randomString} from '../randomstring';
import {encryptAES, decryptAES} from './aes';
import {encodeBase64} 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";
@@ -86,7 +86,7 @@ export class SecretStorage extends EventEmitter {
* keyInfo: {object} details about the key (iv, mac, passphrase)
*/
async addKey(algorithm, opts, keyId) {
const keyInfo = {algorithm};
const keyInfo = { algorithm };
if (!opts) opts = {};
@@ -99,7 +99,7 @@ export class SecretStorage extends EventEmitter {
keyInfo.passphrase = opts.passphrase;
}
if (opts.key) {
const {iv, mac} = await SecretStorage._calculateKeyCheck(opts.key);
const { iv, mac } = await SecretStorage._calculateKeyCheck(opts.key);
keyInfo.iv = iv;
keyInfo.mac = mac;
}
@@ -171,7 +171,7 @@ export class SecretStorage extends EventEmitter {
async checkKey(key, info) {
if (info.algorithm === SECRET_STORAGE_ALGORITHM_V1_AES) {
if (info.mac) {
const {mac} = await SecretStorage._calculateKeyCheck(key, info.iv);
const { mac } = await SecretStorage._calculateKeyCheck(key, info.iv);
return info.mac.replace(/=+$/g, '') === mac.replace(/=+$/g, '');
} else {
// if we have no information, we have to assume the key is right
@@ -220,7 +220,7 @@ export class SecretStorage extends EventEmitter {
// encrypt secret, based on the algorithm
if (keyInfo.algorithm === SECRET_STORAGE_ALGORITHM_V1_AES) {
const keys = {[keyId]: keyInfo};
const keys = { [keyId]: keyInfo };
const [, encryption] = await this._getSecretStorageKey(keys, name);
encrypted[keyId] = await encryption.encrypt(secret);
} else {
@@ -231,7 +231,7 @@ export class SecretStorage extends EventEmitter {
}
// save encrypted secret
await this._baseApis.setAccountData(name, {encrypted});
await this._baseApis.setAccountData(name, { encrypted });
}
/**
+7 -7
View File
@@ -14,8 +14,8 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
import {getCrypto} from '../utils';
import {decodeBase64, encodeBase64} from './olmlib';
import { getCrypto } from '../utils';
import { decodeBase64, encodeBase64 } from './olmlib';
const subtleCrypto = (typeof window !== "undefined" && window.crypto) ?
(window.crypto.subtle || window.crypto.webkitSubtle) : null;
@@ -148,7 +148,7 @@ async function encryptBrowser(data, key, name, ivStr) {
);
const hmac = await subtleCrypto.sign(
{name: 'HMAC'},
{ name: 'HMAC' },
hmacKey,
ciphertext,
);
@@ -176,7 +176,7 @@ async function decryptBrowser(data, key, name) {
const ciphertext = decodeBase64(data.ciphertext);
if (!await subtleCrypto.verify(
{name: "HMAC"},
{ name: "HMAC" },
hmacKey,
decodeBase64(data.mac),
ciphertext,
@@ -201,7 +201,7 @@ async function deriveKeysBrowser(key, name) {
const hkdfkey = await subtleCrypto.importKey(
'raw',
key,
{name: "HKDF"},
{ name: "HKDF" },
false,
["deriveBits"],
);
@@ -222,7 +222,7 @@ async function deriveKeysBrowser(key, name) {
const aesProm = subtleCrypto.importKey(
'raw',
aesKey,
{name: 'AES-CTR'},
{ name: 'AES-CTR' },
false,
['encrypt', 'decrypt'],
);
@@ -232,7 +232,7 @@ async function deriveKeysBrowser(key, name) {
hmacKey,
{
name: 'HMAC',
hash: {name: 'SHA-256'},
hash: { name: 'SHA-256' },
},
false,
['sign', 'verify'],
+160 -47
View File
@@ -22,9 +22,9 @@ limitations under the License.
* @module crypto/algorithms/megolm
*/
import {logger} from '../../logger';
import { logger } from '../../logger';
import * as utils from "../../utils";
import {polyfillSuper} from "../../utils";
import { polyfillSuper } from "../../utils";
import * as olmlib from "../olmlib";
import {
DecryptionAlgorithm,
@@ -34,13 +34,29 @@ import {
UnknownDeviceError,
} from "./base";
import {WITHHELD_MESSAGES} from '../OlmDevice';
import { WITHHELD_MESSAGES } from '../OlmDevice';
// determine whether the key can be shared with invitees
function isRoomSharedHistory(room) {
const visibilityEvent = room.currentState &&
room.currentState.getStateEvents("m.room.history_visibility", "");
// NOTE: if the room visibility is unset, it would normally default to
// "world_readable".
// (https://spec.matrix.org/unstable/client-server-api/#server-behaviour-5)
// But we will be paranoid here, and treat it as a situation where the room
// is not shared-history
const visibility = visibilityEvent && visibilityEvent.getContent() &&
visibilityEvent.getContent().history_visibility;
return ["world_readable", "shared"].includes(visibility);
}
/**
* @private
* @constructor
*
* @param {string} sessionId
* @param {boolean} sharedHistory whether the session can be freely shared with
* other group members, according to the room history visibility settings
*
* @property {string} sessionId
* @property {Number} useCount number of times this session has been used
@@ -50,15 +66,15 @@ import {WITHHELD_MESSAGES} from '../OlmDevice';
* devices with which we have shared the session key
* userId -> {deviceId -> msgindex}
*/
function OutboundSessionInfo(sessionId) {
function OutboundSessionInfo(sessionId, sharedHistory = false) {
this.sessionId = sessionId;
this.useCount = 0;
this.creationTime = new Date().getTime();
this.sharedWithDevices = {};
this.blockedDevicesNotified = {};
this.sharedHistory = sharedHistory;
}
/**
* Check if it's time to rotate the session
*
@@ -141,7 +157,6 @@ OutboundSessionInfo.prototype.sharedWithTooManyDevices = function(
}
};
/**
* Megolm encryption implementation
*
@@ -183,6 +198,7 @@ utils.inherits(MegolmEncryption, EncryptionAlgorithm);
/**
* @private
*
* @param {module:models/room} room
* @param {Object} devicesInRoom The devices in this room, indexed by user ID
* @param {Object} blocked The devices that are blocked, indexed by user ID
* @param {boolean} [singleOlmCreationPhase] Only perform one round of olm
@@ -192,7 +208,7 @@ utils.inherits(MegolmEncryption, EncryptionAlgorithm);
* OutboundSessionInfo when setup is complete.
*/
MegolmEncryption.prototype._ensureOutboundSession = async function(
devicesInRoom, blocked, singleOlmCreationPhase,
room, devicesInRoom, blocked, singleOlmCreationPhase,
) {
let session;
@@ -204,6 +220,13 @@ MegolmEncryption.prototype._ensureOutboundSession = async function(
const prepareSession = async (oldSession) => {
session = oldSession;
const sharedHistory = isRoomSharedHistory(room);
// history visibility changed
if (session && sharedHistory !== session.sharedHistory) {
session = null;
}
// need to make a brand new session?
if (session && session.needsRotation(this._sessionRotationPeriodMsgs,
this._sessionRotationPeriodMs)
@@ -219,7 +242,7 @@ MegolmEncryption.prototype._ensureOutboundSession = async function(
if (!session) {
logger.log(`Starting new megolm session for room ${this._roomId}`);
session = await this._prepareNewSession();
session = await this._prepareNewSession(sharedHistory);
logger.log(`Started new megolm session ${session.sessionId} ` +
`for room ${this._roomId}`);
this._outboundSessions[session.sessionId] = session;
@@ -250,11 +273,12 @@ MegolmEncryption.prototype._ensureOutboundSession = async function(
const payload = {
type: "m.room_key",
content: {
algorithm: olmlib.MEGOLM_ALGORITHM,
room_id: this._roomId,
session_id: session.sessionId,
session_key: key.key,
chain_index: key.chain_index,
"algorithm": olmlib.MEGOLM_ALGORITHM,
"room_id": this._roomId,
"session_id": session.sessionId,
"session_key": key.key,
"chain_index": key.chain_index,
"org.matrix.msc3061.shared_history": sharedHistory,
},
};
const [devicesWithoutSession, olmSessions] = await olmlib.getExistingOlmSessions(
@@ -302,7 +326,7 @@ MegolmEncryption.prototype._ensureOutboundSession = async function(
failedServerMap.add(server);
}
const failedDevices = [];
for (const {userId, deviceInfo} of errorDevices) {
for (const { userId, deviceInfo } of errorDevices) {
const userHS = userId.slice(userId.indexOf(":") + 1);
if (failedServerMap.has(userHS)) {
retryDevices[userId] = retryDevices[userId] || [];
@@ -310,7 +334,7 @@ MegolmEncryption.prototype._ensureOutboundSession = async function(
} else {
// if we aren't going to retry, then handle it
// as a failed device
failedDevices.push({userId, deviceInfo});
failedDevices.push({ userId, deviceInfo });
}
}
@@ -374,15 +398,18 @@ MegolmEncryption.prototype._ensureOutboundSession = async function(
/**
* @private
*
* @param {boolean} sharedHistory
*
* @return {module:crypto/algorithms/megolm.OutboundSessionInfo} session
*/
MegolmEncryption.prototype._prepareNewSession = async function() {
MegolmEncryption.prototype._prepareNewSession = async function(sharedHistory) {
const sessionId = this._olmDevice.createOutboundGroupSession();
const key = this._olmDevice.getOutboundGroupSessionKey(sessionId);
await this._olmDevice.addInboundGroupSession(
this._roomId, this._olmDevice.deviceCurve25519Key, [], sessionId,
key.key, {ed25519: this._olmDevice.deviceEd25519Key},
key.key, { ed25519: this._olmDevice.deviceEd25519Key }, false,
{ sharedHistory: sharedHistory },
);
// don't wait for it to complete
@@ -391,7 +418,7 @@ MegolmEncryption.prototype._prepareNewSession = async function() {
sessionId, key.key,
);
return new OutboundSessionInfo(sessionId);
return new OutboundSessionInfo(sessionId, sharedHistory);
};
/**
@@ -425,7 +452,7 @@ MegolmEncryption.prototype._getDevicesWithoutSessions = function(
// no session with this device, probably because there
// were no one-time keys.
noOlmDevices.push({userId, deviceInfo});
noOlmDevices.push({ userId, deviceInfo });
delete sessionResults[deviceId];
// ensureOlmSessionsForUsers has already done the logging,
@@ -672,14 +699,15 @@ MegolmEncryption.prototype.reshareKeyWithDevice = async function(
const payload = {
type: "m.forwarded_room_key",
content: {
algorithm: olmlib.MEGOLM_ALGORITHM,
room_id: this._roomId,
session_id: sessionId,
session_key: key.key,
chain_index: key.chain_index,
sender_key: senderKey,
sender_claimed_ed25519_key: key.sender_claimed_ed25519_key,
forwarding_curve25519_key_chain: key.forwarding_curve25519_key_chain,
"algorithm": olmlib.MEGOLM_ALGORITHM,
"room_id": this._roomId,
"session_id": sessionId,
"session_key": key.key,
"chain_index": key.chain_index,
"sender_key": senderKey,
"sender_claimed_ed25519_key": key.sender_claimed_ed25519_key,
"forwarding_curve25519_key_chain": key.forwarding_curve25519_key_chain,
"org.matrix.msc3061.shared_history": key.shared_history || false,
},
};
@@ -789,7 +817,7 @@ MegolmEncryption.prototype._notifyFailedOlmDevices = async function(
// mark the devices that failed as "handled" because we don't want to try
// to claim a one-time-key for dead devices on every message.
for (const {userId, deviceInfo} of failedDevices) {
for (const { userId, deviceInfo } of failedDevices) {
const deviceId = deviceInfo.deviceId;
session.markSharedWithDevice(
@@ -806,7 +834,7 @@ MegolmEncryption.prototype._notifyFailedOlmDevices = async function(
`in ${this._roomId}`,
);
const blockedMap = {};
for (const {userId, deviceInfo} of filteredFailedDevices) {
for (const { userId, deviceInfo } of filteredFailedDevices) {
blockedMap[userId] = blockedMap[userId] || {};
// we use a similar format to what
// olmlib.ensureOlmSessionsForDevices returns, so that
@@ -901,7 +929,7 @@ MegolmEncryption.prototype.prepareToEncrypt = function(room) {
}
logger.debug(`Ensuring outbound session in ${this._roomId}`);
await this._ensureOutboundSession(devicesInRoom, blocked, true);
await this._ensureOutboundSession(room, devicesInRoom, blocked, true);
logger.debug(`Ready to encrypt events for ${this._roomId}`);
} catch (e) {
@@ -945,7 +973,7 @@ MegolmEncryption.prototype.encryptMessage = async function(room, eventType, cont
this._checkForUnknownDevices(devicesInRoom);
}
const session = await this._ensureOutboundSession(devicesInRoom, blocked);
const session = await this._ensureOutboundSession(room, devicesInRoom, blocked);
const payloadJson = {
room_id: this._roomId,
type: eventType,
@@ -1046,7 +1074,7 @@ MegolmEncryption.prototype._removeUnknownDevices = function(devicesInRoom) {
*/
MegolmEncryption.prototype._getDevicesInRoom = async function(room) {
const members = await room.getEncryptionTargetMembers();
const roomMembers = utils.map(members, function(u) {
const roomMembers = members.map(function(u) {
return u.userId;
});
@@ -1311,7 +1339,6 @@ MegolmDecryption.prototype._removeEventFromPendingList = function(event) {
}
};
/**
* @inheritdoc
*
@@ -1341,7 +1368,7 @@ MegolmDecryption.prototype.onRoomKeyEvent = function(event) {
if (event.getType() == "m.forwarded_room_key") {
exportFormat = true;
forwardingKeyChain = content.forwarding_curve25519_key_chain;
if (!utils.isArray(forwardingKeyChain)) {
if (!Array.isArray(forwardingKeyChain)) {
forwardingKeyChain = [];
}
@@ -1370,10 +1397,14 @@ MegolmDecryption.prototype.onRoomKeyEvent = function(event) {
keysClaimed = event.getKeysClaimed();
}
const extraSessionData = {};
if (content["org.matrix.msc3061.shared_history"]) {
extraSessionData.sharedHistory = true;
}
return this._olmDevice.addInboundGroupSession(
content.room_id, senderKey, forwardingKeyChain, sessionId,
content.session_key, keysClaimed,
exportFormat,
exportFormat, extraSessionData,
).then(() => {
// have another go at decrypting events sent with this session.
this._retryDecryption(senderKey, sessionId)
@@ -1455,7 +1486,7 @@ MegolmDecryption.prototype.onRoomKeyWithheldEvent = async function(event) {
}
}
await olmlib.ensureOlmSessionsForDevices(
this._olmDevice, this._baseApis, {[sender]: [device]}, false,
this._olmDevice, this._baseApis, { [sender]: [device] }, false,
);
const encryptedContent = {
algorithm: olmlib.OLM_ALGORITHM,
@@ -1469,7 +1500,7 @@ MegolmDecryption.prototype.onRoomKeyWithheldEvent = async function(event) {
this._olmDevice,
sender,
device,
{type: "m.dummy"},
{ type: "m.dummy" },
);
await this._olmDevice.recordSessionProblem(senderKey, "no_olm", true);
@@ -1573,14 +1604,15 @@ MegolmDecryption.prototype._buildKeyForwardingMessage = async function(
return {
type: "m.forwarded_room_key",
content: {
algorithm: olmlib.MEGOLM_ALGORITHM,
room_id: roomId,
sender_key: senderKey,
sender_claimed_ed25519_key: key.sender_claimed_ed25519_key,
session_id: sessionId,
session_key: key.key,
chain_index: key.chain_index,
forwarding_curve25519_key_chain: key.forwarding_curve25519_key_chain,
"algorithm": olmlib.MEGOLM_ALGORITHM,
"room_id": roomId,
"sender_key": senderKey,
"sender_claimed_ed25519_key": key.sender_claimed_ed25519_key,
"session_id": sessionId,
"session_key": key.key,
"chain_index": key.chain_index,
"forwarding_curve25519_key_chain": key.forwarding_curve25519_key_chain,
"org.matrix.msc3061.shared_history": key.shared_history || false,
},
};
};
@@ -1594,6 +1626,13 @@ MegolmDecryption.prototype._buildKeyForwardingMessage = async function(
* @param {string} [opts.source] where the key came from
*/
MegolmDecryption.prototype.importRoomKey = function(session, opts = {}) {
const extraSessionData = {};
if (opts.untrusted) {
extraSessionData.untrusted = true;
}
if (session["org.matrix.msc3061.shared_history"]) {
extraSessionData.sharedHistory = true;
}
return this._olmDevice.addInboundGroupSession(
session.room_id,
session.sender_key,
@@ -1602,7 +1641,7 @@ MegolmDecryption.prototype.importRoomKey = function(session, opts = {}) {
session.session_key,
session.sender_claimed_keys,
true,
opts.untrusted ? { untrusted: opts.untrusted } : {},
extraSessionData,
).then(() => {
if (opts.source !== "backup") {
// don't wait for it to complete
@@ -1650,7 +1689,7 @@ MegolmDecryption.prototype._retryDecryption = async function(senderKey, sessionI
await Promise.all([...pending].map(async (ev) => {
try {
await ev.attemptDecryption(this._crypto, true);
await ev.attemptDecryption(this._crypto, { isRetry: true });
} catch (e) {
// don't die if something goes wrong
}
@@ -1681,6 +1720,80 @@ MegolmDecryption.prototype.retryDecryptionFromSender = async function(senderKey)
return !this._pendingEvents[senderKey];
};
MegolmDecryption.prototype.sendSharedHistoryInboundSessions = async function(devicesByUser) {
await olmlib.ensureOlmSessionsForDevices(
this._olmDevice, this._baseApis, devicesByUser,
);
logger.log("sendSharedHistoryInboundSessions to users", Object.keys(devicesByUser));
const sharedHistorySessions =
await this._olmDevice.getSharedHistoryInboundGroupSessions(
this._roomId,
);
logger.log("shared-history sessions", sharedHistorySessions);
for (const [senderKey, sessionId] of sharedHistorySessions) {
const payload = await this._buildKeyForwardingMessage(
this._roomId, senderKey, sessionId,
);
const promises = [];
const contentMap = {};
for (const [userId, devices] of Object.entries(devicesByUser)) {
contentMap[userId] = {};
for (const deviceInfo of devices) {
const encryptedContent = {
algorithm: olmlib.OLM_ALGORITHM,
sender_key: this._olmDevice.deviceCurve25519Key,
ciphertext: {},
};
contentMap[userId][deviceInfo.deviceId] = encryptedContent;
promises.push(
olmlib.encryptMessageForDevice(
encryptedContent.ciphertext,
this._userId,
this._deviceId,
this._olmDevice,
userId,
deviceInfo,
payload,
),
);
}
}
await Promise.all(promises);
// 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;
}
await this._baseApis.sendToDevice("m.room.encrypted", contentMap);
}
};
registerAlgorithm(
olmlib.MEGOLM_ALGORITHM, MegolmEncryption, MegolmDecryption,
);
+4 -5
View File
@@ -20,11 +20,11 @@ limitations under the License.
* @module crypto/algorithms/olm
*/
import {logger} from '../../logger';
import { logger } from '../../logger';
import * as utils from "../../utils";
import {polyfillSuper} from "../../utils";
import { polyfillSuper } from "../../utils";
import * as olmlib from "../olmlib";
import {DeviceInfo} from "../deviceinfo";
import { DeviceInfo } from "../deviceinfo";
import {
DecryptionAlgorithm,
DecryptionError,
@@ -95,7 +95,7 @@ OlmEncryption.prototype.encryptMessage = async function(room, eventType, content
const members = await room.getEncryptionTargetMembers();
const users = utils.map(members, function(u) {
const users = members.map(function(u) {
return u.userId;
});
@@ -358,5 +358,4 @@ OlmDecryption.prototype._reallyDecryptMessage = async function(
return res.payload;
};
registerAlgorithm(olmlib.OLM_ALGORITHM, OlmEncryption, OlmDecryption);
+7 -7
View File
@@ -14,11 +14,11 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
import {decodeBase64, encodeBase64} from './olmlib';
import {IndexedDBCryptoStore} from '../crypto/store/indexeddb-crypto-store';
import {decryptAES, encryptAES} from './aes';
import { decodeBase64, encodeBase64 } from './olmlib';
import { IndexedDBCryptoStore } from '../crypto/store/indexeddb-crypto-store';
import { decryptAES, encryptAES } from './aes';
import anotherjson from "another-json";
import {logger} from '../logger';
import { logger } from '../logger';
// FIXME: these types should eventually go in a different file
type Signatures = Record<string, Record<string, string>>;
@@ -59,7 +59,7 @@ export class DehydrationManager {
txn,
async (result) => {
if (result) {
const {key, keyInfo, deviceDisplayName, time} = result;
const { key, keyInfo, deviceDisplayName, time } = result;
const pickleKey = Buffer.from(this.crypto._olmDevice._pickleKey);
const decrypted = await decryptAES(key, pickleKey, DEHYDRATION_ALGORITHM);
this.key = decodeBase64(decrypted);
@@ -231,7 +231,7 @@ export class DehydrationManager {
logger.log("Preparing one-time keys");
const oneTimeKeys = {};
for (const [keyId, key] of Object.entries(otks.curve25519)) {
const k: OneTimeKey = {key};
const k: OneTimeKey = { key };
const signature = account.sign(anotherjson.stringify(k));
k.signatures = {
[this.crypto._userId]: {
@@ -244,7 +244,7 @@ export class DehydrationManager {
logger.log("Preparing fallback keys");
const fallbackKeys = {};
for (const [keyId, key] of Object.entries(fallbacks.curve25519)) {
const k: OneTimeKey = {key, fallback: true};
const k: OneTimeKey = { key, fallback: true };
const signature = account.sign(anotherjson.stringify(k));
k.signatures = {
[this.crypto._userId]: {
+76 -53
View File
@@ -22,15 +22,15 @@ limitations under the License.
*/
import anotherjson from "another-json";
import {EventEmitter} from 'events';
import {ReEmitter} from '../ReEmitter';
import {logger} from '../logger';
import { EventEmitter } from 'events';
import { ReEmitter } from '../ReEmitter';
import { logger } from '../logger';
import * as utils from "../utils";
import {sleep} from "../utils";
import {OlmDevice} from "./OlmDevice";
import { sleep } from "../utils";
import { OlmDevice } from "./OlmDevice";
import * as olmlib from "./olmlib";
import {DeviceList} from "./DeviceList";
import {DeviceInfo} from "./deviceinfo";
import { DeviceList } from "./DeviceList";
import { DeviceInfo } from "./deviceinfo";
import * as algorithms from "./algorithms";
import {
CrossSigningInfo,
@@ -38,25 +38,25 @@ import {
UserTrustLevel,
createCryptoStoreCacheCallbacks,
} from './CrossSigning';
import {EncryptionSetupBuilder} from "./EncryptionSetup";
import {SECRET_STORAGE_ALGORITHM_V1_AES, SecretStorage} from './SecretStorage';
import {OutgoingRoomKeyRequestManager} from './OutgoingRoomKeyRequestManager';
import {IndexedDBCryptoStore} from './store/indexeddb-crypto-store';
import { EncryptionSetupBuilder } from "./EncryptionSetup";
import { SECRET_STORAGE_ALGORITHM_V1_AES, SecretStorage } from './SecretStorage';
import { OutgoingRoomKeyRequestManager } from './OutgoingRoomKeyRequestManager';
import { IndexedDBCryptoStore } from './store/indexeddb-crypto-store';
import {
ReciprocateQRCode,
SCAN_QR_CODE_METHOD,
SHOW_QR_CODE_METHOD,
} from './verification/QRCode';
import {SAS} from './verification/SAS';
import {keyFromPassphrase} from './key_passphrase';
import {encodeRecoveryKey, decodeRecoveryKey} from './recoverykey';
import {VerificationRequest} from "./verification/request/VerificationRequest";
import {InRoomChannel, InRoomRequests} from "./verification/request/InRoomChannel";
import {ToDeviceChannel, ToDeviceRequests} from "./verification/request/ToDeviceChannel";
import {IllegalMethod} from "./verification/IllegalMethod";
import {KeySignatureUploadError} from "../errors";
import {decryptAES, encryptAES} from './aes';
import {DehydrationManager} from './dehydration';
import { SAS } from './verification/SAS';
import { keyFromPassphrase } from './key_passphrase';
import { encodeRecoveryKey, decodeRecoveryKey } from './recoverykey';
import { VerificationRequest } from "./verification/request/VerificationRequest";
import { InRoomChannel, InRoomRequests } from "./verification/request/InRoomChannel";
import { ToDeviceChannel, ToDeviceRequests } from "./verification/request/ToDeviceChannel";
import { IllegalMethod } from "./verification/IllegalMethod";
import { KeySignatureUploadError } from "../errors";
import { decryptAES, encryptAES } from './aes';
import { DehydrationManager } from './dehydration';
import { MatrixEvent } from "../models/event";
const DeviceVerification = DeviceInfo.DeviceVerification;
@@ -186,7 +186,7 @@ export function Crypto(baseApis, sessionStore, userId, deviceId,
// map from algorithm to DecryptionAlgorithm instance, for each room
this._roomDecryptors = {};
this._supportedAlgorithms = utils.keys(
this._supportedAlgorithms = Object.keys(
algorithms.DECRYPTION_CLASSES,
);
@@ -568,7 +568,9 @@ Crypto.prototype.bootstrapCrossSigning = async function({
"Cross-signing private keys not found locally, but they are available " +
"in secret storage, reading storage and caching locally",
);
await this.checkOwnCrossSigningTrust();
await this.checkOwnCrossSigningTrust({
allowPrivateKeyRequests: true,
});
}
// Assuming no app-supplied callback, default to storing new private keys in
@@ -680,12 +682,12 @@ Crypto.prototype.bootstrapSecretStorage = async function({
const ensureCanCheckPassphrase = async (keyId, keyInfo) => {
if (!keyInfo.mac) {
const key = await this._baseApis._cryptoCallbacks.getSecretStorageKey(
{keys: {[keyId]: keyInfo}}, "",
{ keys: { [keyId]: keyInfo } }, "",
);
if (key) {
const privateKey = key[1];
builder.ssssCryptoCallbacks.addPrivateKey(keyId, keyInfo, privateKey);
const {iv, mac} = await SecretStorage._calculateKeyCheck(privateKey);
const { iv, mac } = await SecretStorage._calculateKeyCheck(privateKey);
keyInfo.iv = iv;
keyInfo.mac = mac;
@@ -1300,13 +1302,19 @@ Crypto.prototype._onDeviceListUserCrossSigningUpdated = async function(userId) {
* Check the copy of our cross-signing key that we have in the device list and
* see if we can get the private key. If so, mark it as trusted.
*/
Crypto.prototype.checkOwnCrossSigningTrust = async function() {
Crypto.prototype.checkOwnCrossSigningTrust = async function({
allowPrivateKeyRequests = false,
} = {}) {
const userId = this._userId;
// Before proceeding, ensure our cross-signing public keys have been
// downloaded via the device list.
await this.downloadKeys([this._userId]);
// Also check which private keys are locally cached.
const crossSigningPrivateKeys =
await this._crossSigningInfo.getCrossSigningKeysFromCache();
// If we see an update to our own master key, check it against the master
// key we have and, if it matches, mark it as verified
@@ -1322,18 +1330,26 @@ Crypto.prototype.checkOwnCrossSigningTrust = async function() {
const seenPubkey = newCrossSigning.getId();
const masterChanged = this._crossSigningInfo.getId() !== seenPubkey;
const masterExistsNotLocallyCached =
newCrossSigning.getId() && !crossSigningPrivateKeys.has("master");
if (masterChanged) {
logger.info("Got new master public key", seenPubkey);
}
if (
allowPrivateKeyRequests &&
(masterChanged || masterExistsNotLocallyCached)
) {
logger.info("Attempting to retrieve cross-signing master private key");
let signing = null;
// It's important for control flow that we leave any errors alone for
// higher levels to handle so that e.g. cancelling access properly
// aborts any larger operation as well.
try {
const ret = await this._crossSigningInfo.getCrossSigningKey(
'master', seenPubkey,
);
signing = ret[1];
logger.info("Got cross-signing master private key");
} catch (e) {
logger.error("Cross-signing master private key not available", e);
} finally {
if (signing) signing.free();
}
@@ -1348,10 +1364,24 @@ Crypto.prototype.checkOwnCrossSigningTrust = async function() {
const selfSigningChanged = oldSelfSigningId !== newCrossSigning.getId("self_signing");
const userSigningChanged = oldUserSigningId !== newCrossSigning.getId("user_signing");
const selfSigningExistsNotLocallyCached = (
newCrossSigning.getId("self_signing") &&
!crossSigningPrivateKeys.has("self_signing")
);
const userSigningExistsNotLocallyCached = (
newCrossSigning.getId("user_signing") &&
!crossSigningPrivateKeys.has("user_signing")
);
const keySignatures = {};
if (selfSigningChanged) {
logger.info("Got new self-signing key", newCrossSigning.getId("self_signing"));
}
if (
allowPrivateKeyRequests &&
(selfSigningChanged || selfSigningExistsNotLocallyCached)
) {
logger.info("Attempting to retrieve cross-signing self-signing private key");
let signing = null;
try {
@@ -1360,8 +1390,6 @@ Crypto.prototype.checkOwnCrossSigningTrust = async function() {
);
signing = ret[1];
logger.info("Got cross-signing self-signing private key");
} catch (e) {
logger.error("Cross-signing self-signing private key not available", e);
} finally {
if (signing) signing.free();
}
@@ -1374,6 +1402,11 @@ Crypto.prototype.checkOwnCrossSigningTrust = async function() {
}
if (userSigningChanged) {
logger.info("Got new user-signing key", newCrossSigning.getId("user_signing"));
}
if (
allowPrivateKeyRequests &&
(userSigningChanged || userSigningExistsNotLocallyCached)
) {
logger.info("Attempting to retrieve cross-signing user-signing private key");
let signing = null;
try {
@@ -1382,8 +1415,6 @@ Crypto.prototype.checkOwnCrossSigningTrust = async function() {
);
signing = ret[1];
logger.info("Got cross-signing user-signing private key");
} catch (e) {
logger.error("Cross-signing user-signing private key not available", e);
} finally {
if (signing) signing.free();
}
@@ -1568,7 +1599,7 @@ Crypto.prototype._checkAndStartKeyBackup = async function() {
}
}
return {backupInfo, trustInfo};
return { backupInfo, trustInfo };
};
Crypto.prototype.setTrustedBackupPubKey = async function(trustedPubKey) {
@@ -1743,7 +1774,6 @@ Crypto.prototype.registerEventHandlers = function(eventEmitter) {
eventEmitter.on("Event.decrypted", timelineHandler);
};
/** Start background processes related to crypto */
Crypto.prototype.start = function() {
this._outgoingRoomKeyRequestManager.start();
@@ -2200,7 +2230,7 @@ Crypto.prototype.setDeviceVerification = async function(
}
if (device) {
const upload = async ({shouldEmit}) => {
const upload = async ({ shouldEmit }) => {
logger.info("Uploading signature for " + deviceId);
const response = await this._baseApis.uploadKeySignatures({
[userId]: {
@@ -2220,7 +2250,7 @@ Crypto.prototype.setDeviceVerification = async function(
throw new KeySignatureUploadError("Key upload failed", { failures });
}
};
await upload({shouldEmit: true});
await upload({ shouldEmit: true });
// XXX: we'll need to wait for the device list to be updated
}
}
@@ -2313,7 +2343,7 @@ Crypto.prototype.beginKeyVerification = function(
this._toDeviceVerificationRequests.setRequestBySenderAndTxnId(
userId, transactionId, request);
}
return request.beginKeyVerification(method, {userId, deviceId});
return request.beginKeyVerification(method, { userId, deviceId });
};
Crypto.prototype.legacyDeviceVerification = async function(
@@ -2326,7 +2356,7 @@ Crypto.prototype.legacyDeviceVerification = async function(
channel, this._verificationMethods, this._baseApis);
this._toDeviceVerificationRequests.setRequestBySenderAndTxnId(
userId, transactionId, request);
const verifier = request.beginKeyVerification(method, {userId, deviceId});
const verifier = request.beginKeyVerification(method, { userId, deviceId });
// either reject by an error from verify() while sending .start
// or resolve when the request receives the
// local (fake remote) echo for sending the .start event
@@ -2337,7 +2367,6 @@ Crypto.prototype.legacyDeviceVerification = async function(
return request;
};
/**
* Get information on the active olm sessions with a user
* <p>
@@ -2368,7 +2397,6 @@ Crypto.prototype.getOlmSessionsForUser = async function(userId) {
return result;
};
/**
* Get the device which sent an event
*
@@ -2613,7 +2641,6 @@ Crypto.prototype.setRoomEncryption = async function(roomId, config, inhibitDevic
}
};
/**
* Make sure we are tracking the device lists for all users in this room.
*
@@ -2836,7 +2863,7 @@ Crypto.prototype._backupPendingKeys = async function(limit) {
for (const session of sessions) {
const roomId = session.sessionData.room_id;
if (data[roomId] === undefined) {
data[roomId] = {sessions: {}};
data[roomId] = { sessions: {} };
}
const sessionData = await this._olmDevice.exportInboundGroupSession(
@@ -2870,7 +2897,7 @@ Crypto.prototype._backupPendingKeys = async function(limit) {
await this._baseApis.sendKeyBackup(
undefined, undefined, this.backupInfo.version,
{rooms: data},
{ rooms: data },
);
await this._cryptoStore.unmarkSessionsNeedingBackup(sessions);
@@ -3270,7 +3297,6 @@ Crypto.prototype._getTrackedE2eRooms = function() {
});
};
Crypto.prototype._onToDeviceEvent = function(event) {
try {
logger.log(`received to_device ${event.getType()} from: ` +
@@ -3291,7 +3317,10 @@ Crypto.prototype._onToDeviceEvent = function(event) {
this._onKeyVerificationMessage(event);
} else if (event.getContent().msgtype === "m.bad.encrypted") {
this._onToDeviceBadEncrypted(event);
} else if (event.isBeingDecrypted()) {
} else if (event.isBeingDecrypted() || event.shouldAttemptDecryption()) {
if (!event.isBeingDecrypted()) {
event.attemptDecryption(this);
}
// once the event has been decrypted, try again
event.once('Event.decrypted', (ev) => {
this._onToDeviceEvent(ev);
@@ -3408,7 +3437,7 @@ Crypto.prototype._onKeyVerificationMessage = function(event) {
* @param {bool} data.liveEvent whether this is a live event
*/
Crypto.prototype._onTimelineEvent = function(
event, room, atStart, removed, {liveEvent} = {},
event, room, atStart, removed, { liveEvent } = {},
) {
if (!InRoomChannel.validateEvent(event, this._baseApis)) {
return;
@@ -3546,7 +3575,7 @@ Crypto.prototype._onToDeviceBadEncrypted = async function(event) {
this._olmDevice,
sender,
device,
{type: "m.dummy"},
{ type: "m.dummy" },
);
await this._olmDevice.recordSessionProblem(deviceKey, "wedged", true);
@@ -3558,7 +3587,6 @@ Crypto.prototype._onToDeviceBadEncrypted = async function(event) {
},
});
// Most of the time this probably won't be necessary since we'll have queued up a key request when
// we failed to decrypt the message and will be waiting a bit for the key to arrive before sending
// it. This won't always be the case though so we need to re-send any that have already been sent
@@ -3615,7 +3643,6 @@ Crypto.prototype._onRoomMembership = function(event, member, oldMembership) {
alg.onRoomMembership(event, member, oldMembership);
};
/**
* Called when we get an m.room_key_request event.
*
@@ -3768,7 +3795,6 @@ Crypto.prototype._processReceivedRoomKeyRequest = async function(req) {
this.emit("crypto.roomKeyRequest", req);
};
/**
* Helper for processReceivedRoomKeyRequests
*
@@ -3844,7 +3870,6 @@ Crypto.prototype._getRoomDecryptor = function(roomId, algorithm) {
return alg;
};
/**
* Get all the room decryptors for a given encryption algorithm.
*
@@ -3862,7 +3887,6 @@ Crypto.prototype._getRoomDecryptors = function(algorithm) {
return decryptors;
};
/**
* sign the given object with our ed25519 key
*
@@ -3882,7 +3906,6 @@ Crypto.prototype._signObject = async function(obj) {
if (unsigned !== undefined) obj.unsigned = unsigned;
};
/**
* The parameters of a room key request. The details of the request may
* vary with the crypto algorithm, but the management and storage layers for
+2 -2
View File
@@ -15,7 +15,7 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
import {randomString} from '../randomstring';
import { randomString } from '../randomstring';
const DEFAULT_ITERATIONS = 500000;
@@ -63,7 +63,7 @@ export async function deriveKey(password, salt, iterations, numBits = DEFAULT_BI
const key = await subtleCrypto.importKey(
'raw',
new TextEncoder().encode(password),
{name: 'PBKDF2'},
{ name: 'PBKDF2' },
false,
['deriveBits'],
);
+1 -3
View File
@@ -22,7 +22,7 @@ limitations under the License.
* Utilities common to olm encryption algorithms
*/
import {logger} from '../logger';
import { logger } from '../logger';
import * as utils from "../utils";
import anotherjson from "another-json";
@@ -41,7 +41,6 @@ export const MEGOLM_ALGORITHM = "m.megolm.v1.aes-sha2";
*/
export const MEGOLM_BACKUP_ALGORITHM = "m.megolm_backup.v1.curve25519-aes-sha2";
/**
* Encrypt an event payload for an Olm device
*
@@ -408,7 +407,6 @@ async function _verifyKeyAndStartSession(olmDevice, oneTimeKey, userId, deviceIn
return sid;
}
/**
* Verify the signature on an object
*
@@ -16,10 +16,10 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
import {logger} from '../../logger';
import { logger } from '../../logger';
import * as utils from "../../utils";
export const VERSION = 9;
export const VERSION = 10;
const PROFILE_TRANSACTIONS = false;
/**
@@ -230,7 +230,7 @@ export class Backend {
const cursor = ev.target.result;
if (cursor) {
const keyReq = cursor.value;
if (keyReq.recipients.includes({userId, deviceId})) {
if (keyReq.recipients.includes({ userId, deviceId })) {
results.push(keyReq);
}
cursor.continue();
@@ -496,7 +496,7 @@ export class Backend {
const lastProblem = problems[problems.length - 1];
for (const problem of problems) {
if (problem.time > timestamp) {
result = Object.assign({}, problem, {fixed: lastProblem.fixed});
result = Object.assign({}, problem, { fixed: lastProblem.fixed });
return;
}
}
@@ -519,11 +519,11 @@ export class Backend {
await Promise.all(devices.map((device) => {
return new Promise((resolve) => {
const {userId, deviceInfo} = device;
const { userId, deviceInfo } = device;
const getReq = objectStore.get([userId, deviceInfo.deviceId]);
getReq.onsuccess = function() {
if (!getReq.result) {
objectStore.put({userId, deviceId: deviceInfo.deviceId});
objectStore.put({ userId, deviceId: deviceInfo.deviceId });
ret.push(device);
}
resolve();
@@ -759,6 +759,38 @@ export class Backend {
}));
}
addSharedHistoryInboundGroupSession(roomId, senderKey, sessionId, txn) {
if (!txn) {
txn = this._db.transaction(
"shared_history_inbound_group_sessions", "readwrite",
);
}
const objectStore = txn.objectStore("shared_history_inbound_group_sessions");
const req = objectStore.get([roomId]);
req.onsuccess = () => {
const { sessions } = req.result || { sessions: [] };
sessions.push([senderKey, sessionId]);
objectStore.put({ roomId, sessions });
};
}
getSharedHistoryInboundGroupSessions(roomId, txn) {
if (!txn) {
txn = this._db.transaction(
"shared_history_inbound_group_sessions", "readonly",
);
}
const objectStore = txn.objectStore("shared_history_inbound_group_sessions");
const req = objectStore.get([roomId]);
return new Promise((resolve, reject) => {
req.onsuccess = () => {
const { sessions } = req.result || { sessions: [] };
resolve(sessions);
};
req.onerror = reject;
});
}
doTxn(mode, stores, func, log = logger) {
let startTime;
let description;
@@ -834,6 +866,11 @@ export function upgradeDatabase(db, oldVersion) {
keyPath: ["userId", "deviceId"],
});
}
if (oldVersion < 10) {
db.createObjectStore("shared_history_inbound_group_sessions", {
keyPath: ["roomId"],
});
}
// Expand as needed.
}
+29 -4
View File
@@ -16,11 +16,11 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
import {logger} from '../../logger';
import {LocalStorageCryptoStore} from './localStorage-crypto-store';
import {MemoryCryptoStore} from './memory-crypto-store';
import { logger } from '../../logger';
import { LocalStorageCryptoStore } from './localStorage-crypto-store';
import { MemoryCryptoStore } from './memory-crypto-store';
import * as IndexedDBCryptoStoreBackend from './indexeddb-crypto-store-backend';
import {InvalidCryptoStoreError} from '../../errors';
import { InvalidCryptoStoreError } from '../../errors';
import * as IndexedDBHelpers from "../../indexeddb-helpers";
/**
@@ -582,6 +582,29 @@ export class IndexedDBCryptoStore {
return this._backend.markSessionsNeedingBackup(sessions, txn);
}
/**
* Add a shared-history group session for a room.
* @param {string} roomId The room that the key belongs to
* @param {string} senderKey The sender's curve 25519 key
* @param {string} sessionId The ID of the session
* @param {*} txn An active transaction. See doTxn(). (optional)
*/
addSharedHistoryInboundGroupSession(roomId, senderKey, sessionId, txn) {
this._backend.addSharedHistoryInboundGroupSession(
roomId, senderKey, sessionId, txn,
);
}
/**
* Get the shared-history group session for a room.
* @param {string} roomId The room that the key belongs to
* @param {*} txn An active transaction. See doTxn(). (optional)
* @returns {Promise} Resolves to an array of [senderKey, sessionId]
*/
getSharedHistoryInboundGroupSessions(roomId, txn) {
return this._backend.getSharedHistoryInboundGroupSessions(roomId, txn);
}
/**
* Perform a transaction on the crypto store. Any store methods
* that require a transaction (txn) object to be passed in may
@@ -614,6 +637,8 @@ IndexedDBCryptoStore.STORE_SESSIONS = 'sessions';
IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS = 'inbound_group_sessions';
IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS_WITHHELD
= 'inbound_group_sessions_withheld';
IndexedDBCryptoStore.STORE_SHARED_HISTORY_INBOUND_GROUP_SESSIONS
= 'shared_history_inbound_group_sessions';
IndexedDBCryptoStore.STORE_DEVICE_DATA = 'device_data';
IndexedDBCryptoStore.STORE_ROOMS = 'rooms';
IndexedDBCryptoStore.STORE_BACKUP = 'sessions_needing_backup';
@@ -15,8 +15,8 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
import {logger} from '../../logger';
import {MemoryCryptoStore} from './memory-crypto-store';
import { logger } from '../../logger';
import { MemoryCryptoStore } from './memory-crypto-store';
/**
* Internal module. Partial localStorage backed storage for e2e.
@@ -136,7 +136,7 @@ export class LocalStorageCryptoStore extends MemoryCryptoStore {
async storeEndToEndSessionProblem(deviceKey, type, fixed) {
const key = keyEndToEndSessionProblems(deviceKey);
const problems = getJsonItem(this.store, key) || [];
problems.push({type, fixed, time: Date.now()});
problems.push({ type, fixed, time: Date.now() });
problems.sort((a, b) => {
return a.time - b.time;
});
@@ -152,7 +152,7 @@ export class LocalStorageCryptoStore extends MemoryCryptoStore {
const lastProblem = problems[problems.length - 1];
for (const problem of problems) {
if (problem.time > timestamp) {
return Object.assign({}, problem, {fixed: lastProblem.fixed});
return Object.assign({}, problem, { fixed: lastProblem.fixed });
}
}
if (lastProblem.fixed) {
@@ -168,7 +168,7 @@ export class LocalStorageCryptoStore extends MemoryCryptoStore {
const ret = [];
for (const device of devices) {
const {userId, deviceInfo} = device;
const { userId, deviceInfo } = device;
if (userId in notifiedErrorDevices) {
if (!(deviceInfo.deviceId in notifiedErrorDevices[userId])) {
ret.push(device);
@@ -176,7 +176,7 @@ export class LocalStorageCryptoStore extends MemoryCryptoStore {
}
} else {
ret.push(device);
notifiedErrorDevices[userId] = {[deviceInfo.deviceId]: true };
notifiedErrorDevices[userId] = { [deviceInfo.deviceId]: true };
}
}
+18 -6
View File
@@ -16,7 +16,7 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
import {logger} from '../../logger';
import { logger } from '../../logger';
import * as utils from "../../utils";
/**
@@ -51,6 +51,8 @@ export class MemoryCryptoStore {
this._rooms = {};
// Set of {senderCurve25519Key+'/'+sessionId}
this._sessionsNeedingBackup = {};
// roomId -> array of [senderKey, sessionId]
this._sharedHistoryInboundGroupSessions = {};
}
/**
@@ -184,7 +186,7 @@ export class MemoryCryptoStore {
for (const req of this._outgoingRoomKeyRequests) {
for (const state of wantedStates) {
if (req.state === state && req.recipients.includes({userId, deviceId})) {
if (req.state === state && req.recipients.includes({ userId, deviceId })) {
results.push(req);
}
}
@@ -322,7 +324,7 @@ export class MemoryCryptoStore {
async storeEndToEndSessionProblem(deviceKey, type, fixed) {
const problems = this._sessionProblems[deviceKey]
= this._sessionProblems[deviceKey] || [];
problems.push({type, fixed, time: Date.now()});
problems.push({ type, fixed, time: Date.now() });
problems.sort((a, b) => {
return a.time - b.time;
});
@@ -336,7 +338,7 @@ export class MemoryCryptoStore {
const lastProblem = problems[problems.length - 1];
for (const problem of problems) {
if (problem.time > timestamp) {
return Object.assign({}, problem, {fixed: lastProblem.fixed});
return Object.assign({}, problem, { fixed: lastProblem.fixed });
}
}
if (lastProblem.fixed) {
@@ -351,7 +353,7 @@ export class MemoryCryptoStore {
const ret = [];
for (const device of devices) {
const {userId, deviceInfo} = device;
const { userId, deviceInfo } = device;
if (userId in notifiedErrorDevices) {
if (!(deviceInfo.deviceId in notifiedErrorDevices[userId])) {
ret.push(device);
@@ -359,7 +361,7 @@ export class MemoryCryptoStore {
}
} else {
ret.push(device);
notifiedErrorDevices[userId] = {[deviceInfo.deviceId]: true };
notifiedErrorDevices[userId] = { [deviceInfo.deviceId]: true };
}
}
@@ -467,6 +469,16 @@ export class MemoryCryptoStore {
return Promise.resolve();
}
addSharedHistoryInboundGroupSession(roomId, senderKey, sessionId) {
const sessions = this._sharedHistoryInboundGroupSessions[roomId] || [];
sessions.push([senderKey, sessionId]);
this._sharedHistoryInboundGroupSessions[roomId] = sessions;
}
getSharedHistoryInboundGroupSessions(roomId) {
return Promise.resolve(this._sharedHistoryInboundGroupSessions[roomId] || []);
}
// Session key backups
doTxn(mode, stores, func) {
+8 -8
View File
@@ -20,12 +20,12 @@ limitations under the License.
* @module crypto/verification/Base
*/
import {MatrixEvent} from '../../models/event';
import {EventEmitter} from 'events';
import {logger} from '../../logger';
import {DeviceInfo} from '../deviceinfo';
import {newTimeoutError} from "./Error";
import {requestKeysDuringVerification} from "../CrossSigning";
import { MatrixEvent } from '../../models/event';
import { EventEmitter } from 'events';
import { logger } from '../../logger';
import { DeviceInfo } from '../deviceinfo';
import { newTimeoutError } from "./Error";
import { requestKeysDuringVerification } from "../CrossSigning";
const timeoutException = new Error("Verification timed out");
@@ -138,7 +138,7 @@ export class VerificationBase extends EventEmitter {
switchStartEvent(event) {
if (this.canSwitchStartEvent(event)) {
logger.log("Verification Base: switching verification start event",
{restartingFlow: !!this._rejectEvent});
{ restartingFlow: !!this._rejectEvent });
if (this._rejectEvent) {
const reject = this._rejectEvent;
this._rejectEvent = undefined;
@@ -167,7 +167,7 @@ export class VerificationBase extends EventEmitter {
// there is only promise to reject if verify has been called
if (reject) {
const content = e.getContent();
const {reason, code} = content;
const { reason, code } = content;
reject(new Error(`Other side cancelled verification ` +
`because ${reason} (${code})`));
}
+5 -5
View File
@@ -20,10 +20,10 @@ limitations under the License.
* @module crypto/verification/Error
*/
import {MatrixEvent} from "../../models/event";
import { MatrixEvent } from "../../models/event";
export function newVerificationError(code, reason, extradata) {
const content = Object.assign({}, {code, reason}, extradata);
const content = Object.assign({}, { code, reason }, extradata);
return new MatrixEvent({
type: "m.key.verification.cancel",
content,
@@ -87,9 +87,9 @@ export const newInvalidMessageError = errorFactory(
export function errorFromEvent(event) {
const content = event.getContent();
if (content) {
const {code, reason} = content;
return {code, reason};
const { code, reason } = content;
return { code, reason };
} else {
return {code: "Unknown error", reason: "m.unknown"};
return { code: "Unknown error", reason: "m.unknown" };
}
}
+1 -1
View File
@@ -20,7 +20,7 @@ limitations under the License.
* @module crypto/verification/IllegalMethod
*/
import {VerificationBase as Base} from "./Base";
import { VerificationBase as Base } from "./Base";
/**
* @class crypto/verification/IllegalMethod/IllegalMethod
+4 -4
View File
@@ -20,13 +20,13 @@ limitations under the License.
* @module crypto/verification/QRCode
*/
import {VerificationBase as Base} from "./Base";
import { VerificationBase as Base } from "./Base";
import {
newKeyMismatchError,
newUserCancelledError,
} from './Error';
import {encodeUnpaddedBase64, decodeBase64} from "../olmlib";
import {logger} from '../../logger';
import { encodeUnpaddedBase64, decodeBase64 } from "../olmlib";
import { logger } from '../../logger';
export const SHOW_QR_CODE_METHOD = "m.qr_code.show.v1";
export const SCAN_QR_CODE_METHOD = "m.qr_code.scan.v1";
@@ -51,7 +51,7 @@ export class ReciprocateQRCode extends Base {
"with this method yet.");
}
const {qrCodeData} = this.request;
const { qrCodeData } = this.request;
// 1. check the secret
if (this.startEvent.getContent()['secret'] !== qrCodeData.encodedSharedSecret) {
throw newKeyMismatchError();
+2 -6
View File
@@ -19,7 +19,7 @@ limitations under the License.
* @module crypto/verification/SAS
*/
import {VerificationBase as Base, SwitchStartEventError} from "./Base";
import { VerificationBase as Base, SwitchStartEventError } from "./Base";
import anotherjson from 'another-json';
import {
errorFactory,
@@ -28,7 +28,7 @@ import {
newUnknownMethodError,
newUserCancelledError,
} from './Error';
import {logger} from '../../logger';
import { logger } from '../../logger';
const START_TYPE = "m.key.verification.start";
@@ -323,7 +323,6 @@ export class SAS extends Base {
key: this.ourSASPubKey,
});
e = await this._waitForEvent("m.key.verification.key");
// FIXME: make sure event is properly formed
content = e.getContent();
@@ -353,7 +352,6 @@ export class SAS extends Base {
this.emit("show_sas", this.sasEvent);
});
[e] = await Promise.all([
this._waitForEvent("m.key.verification.mac")
.then((e) => {
@@ -411,7 +409,6 @@ export class SAS extends Base {
commitment: olmutil.sha256(commitmentStr),
});
let e = await this._waitForEvent("m.key.verification.key");
// FIXME: make sure event is properly formed
content = e.getContent();
@@ -440,7 +437,6 @@ export class SAS extends Base {
this.emit("show_sas", this.sasEvent);
});
[e] = await Promise.all([
this._waitForEvent("m.key.verification.mac")
.then((e) => {
@@ -21,7 +21,7 @@ import {
READY_TYPE,
START_TYPE,
} from "./VerificationRequest";
import {logger} from '../../../logger';
import { logger } from '../../../logger';
const MESSAGE_TYPE = "m.room.message";
const M_REFERENCE = "m.reference";
@@ -157,7 +157,7 @@ export class InRoomChannel {
if (type === MESSAGE_TYPE) {
const content = event.getContent();
if (content) {
const {msgtype} = content;
const { msgtype } = content;
if (msgtype === REQUEST_TYPE) {
return REQUEST_TYPE;
}
@@ -15,8 +15,8 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
import {randomString} from '../../../randomstring';
import {logger} from '../../../logger';
import { randomString } from '../../../randomstring';
import { logger } from '../../../logger';
import {
CANCEL_TYPE,
PHASE_STARTED,
@@ -26,8 +26,8 @@ import {
START_TYPE,
VerificationRequest,
} from "./VerificationRequest";
import {errorFromEvent, newUnexpectedMessageError} from "../Error";
import {MatrixEvent} from "../../../models/event";
import { errorFromEvent, newUnexpectedMessageError } from "../Error";
import { MatrixEvent } from "../../../models/event";
/**
* A key verification channel that sends verification events over to_device messages.
@@ -179,7 +179,9 @@ export class ToDeviceChannel {
const isAcceptingEvent = type === START_TYPE || type === READY_TYPE;
// the request has picked a ready or start event, tell the other devices about it
if (isAcceptingEvent && !wasStarted && isStarted && this._deviceId) {
const nonChosenDevices = this._devices.filter(d => d !== this._deviceId);
const nonChosenDevices = this._devices.filter(
d => d !== this._deviceId && d !== this._client.getDeviceId(),
);
if (nonChosenDevices.length) {
const message = this.completeContent({
code: "m.accepted",
@@ -275,7 +277,7 @@ export class ToDeviceChannel {
msgMap[deviceId] = content;
}
return this._client.sendToDevice(type, {[this.userId]: msgMap});
return this._client.sendToDevice(type, { [this.userId]: msgMap });
} else {
return Promise.resolve();
}
@@ -290,7 +292,6 @@ export class ToDeviceChannel {
}
}
export class ToDeviceRequests {
constructor() {
this._requestsByUserId = new Map();
@@ -15,15 +15,15 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
import {logger} from '../../../logger';
import {EventEmitter} from 'events';
import { logger } from '../../../logger';
import { EventEmitter } from 'events';
import {
errorFactory,
errorFromEvent,
newUnexpectedMessageError,
newUnknownMethodError,
} from "../Error";
import {QRCodeData, SCAN_QR_CODE_METHOD} from "../QRCode";
import { QRCodeData, SCAN_QR_CODE_METHOD } from "../QRCode";
// How long after the event's timestamp that the request times out
const TIMEOUT_FROM_EVENT_TS = 10 * 60 * 1000; // 10 minutes
@@ -37,7 +37,6 @@ const TIMEOUT_FROM_EVENT_RECEIPT = 2 * 60 * 1000; // 2 minutes
// are this amount of time away from expiring.
const VERIFICATION_REQUEST_MARGIN = 3 * 1000; // 3 seconds
export const EVENT_PREFIX = "m.key.verification.";
export const REQUEST_TYPE = EVENT_PREFIX + "request";
export const START_TYPE = EVENT_PREFIX + "start";
@@ -52,7 +51,6 @@ export const PHASE_STARTED = 4;
export const PHASE_CANCELLED = 5;
export const PHASE_DONE = 6;
/**
* State machine for verification requests.
* Things that differ based on what channel is used to
@@ -98,7 +96,6 @@ export class VerificationRequest extends EventEmitter {
static validateEvent(type, event, client) {
const content = event.getContent();
if (!type || !type.startsWith(EVENT_PREFIX)) {
return false;
}
@@ -265,7 +262,7 @@ export class VerificationRequest extends EventEmitter {
if (!content) {
return false;
}
const {methods} = content;
const { methods } = content;
if (!Array.isArray(methods)) {
return false;
}
@@ -355,7 +352,6 @@ export class VerificationRequest extends EventEmitter {
return this._observeOnly;
}
/**
* Gets which device the verification should be started with
* given the events sent so far in the verification. This is the
@@ -414,7 +410,7 @@ export class VerificationRequest extends EventEmitter {
async sendRequest() {
if (!this.observeOnly && this._phase === PHASE_UNSENT) {
const methods = [...this._verificationMethods.keys()];
await this.channel.send(REQUEST_TYPE, {methods});
await this.channel.send(REQUEST_TYPE, { methods });
}
}
@@ -424,7 +420,7 @@ export class VerificationRequest extends EventEmitter {
* @param {string?} error.code the error code to send the cancellation with
* @returns {Promise} resolves when the event has been sent.
*/
async cancel({reason = "User declined", code = "m.user"} = {}) {
async cancel({ reason = "User declined", code = "m.user" } = {}) {
if (!this.observeOnly && this._phase !== PHASE_CANCELLED) {
this._declining = true;
this.emit("change");
@@ -432,7 +428,7 @@ export class VerificationRequest extends EventEmitter {
return this._verifier.cancel(errorFactory(code, reason)());
} else {
this._cancellingUserId = this._client.getUserId();
await this.channel.send(CANCEL_TYPE, {code, reason});
await this.channel.send(CANCEL_TYPE, { code, reason });
}
}
}
@@ -446,7 +442,7 @@ export class VerificationRequest extends EventEmitter {
const methods = [...this._verificationMethods.keys()];
this._accepting = true;
this.emit("change");
await this.channel.send(READY_TYPE, {methods});
await this.channel.send(READY_TYPE, { methods });
}
}
@@ -499,20 +495,20 @@ export class VerificationRequest extends EventEmitter {
}
_calculatePhaseTransitions() {
const transitions = [{phase: PHASE_UNSENT}];
const transitions = [{ phase: PHASE_UNSENT }];
const phase = () => transitions[transitions.length - 1].phase;
// always pass by .request first to be sure channel.userId has been set
const hasRequestByThem = this._eventsByThem.has(REQUEST_TYPE);
const requestEvent = this._getEventBy(REQUEST_TYPE, hasRequestByThem);
if (requestEvent) {
transitions.push({phase: PHASE_REQUESTED, event: requestEvent});
transitions.push({ phase: PHASE_REQUESTED, event: requestEvent });
}
const readyEvent =
requestEvent && this._getEventBy(READY_TYPE, !hasRequestByThem);
if (readyEvent && phase() === PHASE_REQUESTED) {
transitions.push({phase: PHASE_READY, event: readyEvent});
transitions.push({ phase: PHASE_READY, event: readyEvent });
}
let startEvent;
@@ -535,18 +531,18 @@ export class VerificationRequest extends EventEmitter {
const fromUnsentPhase = phase() === PHASE_UNSENT &&
this.channel.constructor.canCreateRequest(START_TYPE);
if (fromRequestPhase || phase() === PHASE_READY || fromUnsentPhase) {
transitions.push({phase: PHASE_STARTED, event: startEvent});
transitions.push({ phase: PHASE_STARTED, event: startEvent });
}
}
const ourDoneEvent = this._eventsByUs.get(DONE_TYPE);
if (this._verifierHasFinished || (ourDoneEvent && phase() === PHASE_STARTED)) {
transitions.push({phase: PHASE_DONE});
transitions.push({ phase: PHASE_DONE });
}
const cancelEvent = this._getEventByEither(CANCEL_TYPE);
if ((this._cancelled || cancelEvent) && phase() !== PHASE_DONE) {
transitions.push({phase: PHASE_CANCELLED, event: cancelEvent});
transitions.push({ phase: PHASE_CANCELLED, event: cancelEvent });
return transitions;
}
@@ -554,7 +550,7 @@ export class VerificationRequest extends EventEmitter {
}
_transitionToPhase(transition) {
const {phase, event} = transition;
const { phase, event } = transition;
// get common methods
if (phase === PHASE_REQUESTED || phase === PHASE_READY) {
if (!this._wasSentByOwnDevice(event)) {
@@ -581,7 +577,7 @@ export class VerificationRequest extends EventEmitter {
}
// create verifier
if (phase === PHASE_STARTED) {
const {method} = event.getContent();
const { method } = event.getContent();
if (!this._verifier && !this.observeOnly) {
this._verifier = this._createVerifier(method, event);
if (!this._verifier) {
@@ -731,7 +727,7 @@ export class VerificationRequest extends EventEmitter {
}
const lastTransition = newTransitions[newTransitions.length - 1];
const {phase} = lastTransition;
const { phase } = lastTransition;
this._setupTimeout(phase);
// set phase as last thing as this emits the "change" event
@@ -809,7 +805,7 @@ export class VerificationRequest extends EventEmitter {
logger.warn(`Cancelling, unexpected ${type} verification ` +
`event from ${event.getSender()}`);
const reason = `Unexpected ${type} event in phase ${this.phase}`;
await this.cancel(errorFromEvent(newUnexpectedMessageError({reason})));
await this.cancel(errorFromEvent(newUnexpectedMessageError({ reason })));
return true;
}
return false;
@@ -849,7 +845,7 @@ export class VerificationRequest extends EventEmitter {
if (!targetDevice) {
targetDevice = this.targetDevice;
}
const {userId, deviceId} = targetDevice;
const { userId, deviceId } = targetDevice;
const VerifierCtor = this._verificationMethods.get(method);
if (!VerifierCtor) {
-1
View File
@@ -22,7 +22,6 @@ InvalidStoreError.prototype = Object.create(Error.prototype, {
});
Reflect.setPrototypeOf(InvalidStoreError, Error);
export function InvalidCryptoStoreError(reason) {
const message = `Crypto store is invalid because ${reason}, ` +
`please stop the client, delete all data and start the client again`;
+1 -1
View File
@@ -19,7 +19,7 @@ limitations under the License.
* @module filter
*/
import {FilterComponent} from "./filter-component";
import { FilterComponent } from "./filter-component";
/**
* @param {Object} obj
+8 -8
View File
@@ -20,9 +20,9 @@ limitations under the License.
* @module http-api
*/
import {parse as parseContentType} from "content-type";
import { parse as parseContentType } from "content-type";
import * as utils from "./utils";
import {logger} from './logger';
import { logger } from './logger';
// we use our own implementation of setTimeout, so that if we get suspended in
// the middle of a /sync, we cancel the sync as soon as we awake, rather than
@@ -271,10 +271,10 @@ MatrixHttpApi.prototype = {
xhr.timeout_timer = callbacks.setTimeout(timeout_fn, 30000);
xhr.onreadystatechange = function() {
let resp;
switch (xhr.readyState) {
case global.XMLHttpRequest.DONE:
callbacks.clearTimeout(xhr.timeout_timer);
var resp;
try {
if (xhr.status === 0) {
throw new AbortError();
@@ -344,7 +344,7 @@ MatrixHttpApi.prototype = {
promise = this.authedRequest(
opts.callback, "POST", "/upload", queryParams, body, {
prefix: "/_matrix/media/r0",
headers: {"Content-Type": contentType},
headers: { "Content-Type": contentType },
json: false,
bodyParser: bodyParser,
},
@@ -803,7 +803,8 @@ const requestCallback = function(
}
if (!err) {
try {
if (response.statusCode >= 400) {
const httpStatus = response.status || response.statusCode; // XMLHttpRequest vs http.IncomingMessage
if (httpStatus >= 400) {
err = parseErrorResponse(response, body);
} else if (bodyParser) {
body = bodyParser(body);
@@ -818,7 +819,7 @@ const requestCallback = function(
userDefinedCallback(err);
} else {
const res = {
code: response.statusCode,
code: response.status || response.statusCode, // XMLHttpRequest vs http.IncomingMessage
// XXX: why do we bother with this? it doesn't work for
// XMLHttpRequest, so clearly we don't use it.
@@ -842,7 +843,7 @@ const requestCallback = function(
* @returns {Error}
*/
function parseErrorResponse(response, body) {
const httpStatus = response.statusCode;
const httpStatus = response.status || response.statusCode; // XMLHttpRequest vs http.IncomingMessage
const contentType = getResponseContentType(response);
let err;
@@ -862,7 +863,6 @@ function parseErrorResponse(response, body) {
return err;
}
/**
* extract the Content-Type header from the response object, and
* parse it to a `{type, parameters}` object.
+2 -2
View File
@@ -16,17 +16,17 @@ limitations under the License.
import * as matrixcs from "./matrix";
import * as utils from "./utils";
import { logger } from './logger';
import request from "request";
matrixcs.request(request);
utils.runPolyfills();
try {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const crypto = require('crypto');
utils.setCrypto(crypto);
} catch (err) {
console.log('nodejs was compiled without crypto support');
logger.log('nodejs was compiled without crypto support');
}
export * from "./matrix";
+1 -1
View File
@@ -21,5 +21,5 @@ limitations under the License.
*/
/** The {@link module:indexeddb-store-worker~IndexedDBStoreWorker} class. */
export {IndexedDBStoreWorker} from "./store/indexeddb-store-worker";
export { IndexedDBStoreWorker } from "./store/indexeddb-store-worker";
+1 -1
View File
@@ -20,7 +20,7 @@ limitations under the License.
import url from "url";
import * as utils from "./utils";
import {logger} from './logger';
import { logger } from './logger';
const EMAIL_STAGE_TYPE = "m.login.email.identity";
const MSISDN_STAGE_TYPE = "m.login.msisdn";
+2 -2
View File
@@ -36,11 +36,11 @@ const DEFAULT_NAMESPACE = "matrix";
// when logging so we always get the current value of console methods.
log.methodFactory = function(methodName, logLevel, loggerName) {
return function(...args) {
/* eslint-disable babel/no-invalid-this */
/* eslint-disable @typescript-eslint/no-invalid-this */
if (this.prefix) {
args.unshift(this.prefix);
}
/* eslint-enable babel/no-invalid-this */
/* eslint-enable @typescript-eslint/no-invalid-this */
const supportedByConsole = methodName === "error" ||
methodName === "warn" ||
methodName === "trace" ||
+9 -11
View File
@@ -18,15 +18,15 @@ 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";
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";
export * from "./client";
export * from "./http-api";
@@ -55,12 +55,10 @@ export * from "./content-repo";
export * as ContentHelpers from "./content-helpers";
export {
createNewMatrixCall,
setAudioOutput as setMatrixCallAudioOutput,
setAudioInput as setMatrixCallAudioInput,
setVideoInput as setMatrixCallVideoInput,
} from "./webrtc/call";
// expose the underlying request object so different environments can use
// different request libs (e.g. request or browser-request)
let requestInstance;
+2 -2
View File
@@ -36,10 +36,10 @@ limitations under the License.
export function EventContext(ourEvent) {
this._timeline = [ourEvent];
this._ourEventIndex = 0;
this._paginateTokens = {b: null, f: null};
this._paginateTokens = { b: null, f: null };
// this is used by MatrixClient to keep track of active requests
this._paginateRequests = {b: null, f: null};
this._paginateRequests = { b: null, f: null };
}
/**
+12 -25
View File
@@ -19,12 +19,12 @@ limitations under the License.
* @module models/event-timeline-set
*/
import {EventEmitter} from "events";
import {EventTimeline} from "./event-timeline";
import {EventStatus} from "./event";
import { EventEmitter } from "events";
import { EventTimeline } from "./event-timeline";
import { EventStatus } from "./event";
import * as utils from "../utils";
import {logger} from '../logger';
import {Relations} from './relations';
import { logger } from '../logger';
import { Relations } from './relations';
// var DEBUG = false;
const DEBUG = true;
@@ -249,7 +249,7 @@ EventTimelineSet.prototype.findEventById = function(eventId) {
if (!tl) {
return undefined;
}
return utils.findElement(tl.getEvents(), function(ev) {
return tl.getEvents().find(function(ev) {
return ev.getId() == eventId;
});
};
@@ -271,7 +271,6 @@ EventTimelineSet.prototype.addTimeline = function() {
return timeline;
};
/**
* Add events to a timeline
*
@@ -474,7 +473,7 @@ EventTimelineSet.prototype.addEventsToTimeline = function(events, toStartOfTimel
// timeline we ended up on.
if (lastEventWasNew || !didUpdate) {
if (direction === EventTimeline.FORWARDS && timeline === this._liveTimeline) {
logger.warn({lastEventWasNew, didUpdate}); // for debugging
logger.warn({ lastEventWasNew, didUpdate }); // for debugging
logger.warn(
`Refusing to set forwards pagination token of live timeline ` +
`${timeline} to ${paginationToken}`,
@@ -740,16 +739,11 @@ EventTimelineSet.prototype.setRelationsTarget = function(event) {
if (!relationsForEvent) {
return;
}
// don't need it for non m.replace relations for now
const relationsWithRelType = relationsForEvent["m.replace"];
if (!relationsWithRelType) {
return;
}
// only doing replacements for messages for now (e.g. edits)
const relationsWithEventType = relationsWithRelType["m.room.message"];
if (relationsWithEventType) {
relationsWithEventType.setTargetEvent(event);
for (const relationsWithRelType of Object.values(relationsForEvent)) {
for (const relationsWithEventType of Object.values(relationsWithRelType)) {
relationsWithEventType.setTargetEvent(event);
}
}
};
@@ -769,7 +763,7 @@ EventTimelineSet.prototype.aggregateRelations = function(event) {
}
// If the event is currently encrypted, wait until it has been decrypted.
if (event.isBeingDecrypted()) {
if (event.isBeingDecrypted() || event.shouldAttemptDecryption()) {
event.once("Event.decrypted", () => {
this.aggregateRelations(event);
});
@@ -797,7 +791,6 @@ EventTimelineSet.prototype.aggregateRelations = function(event) {
}
let relationsWithEventType = relationsWithRelType[eventType];
let isNewRelations = false;
let relatesToEvent;
if (!relationsWithEventType) {
relationsWithEventType = relationsWithRelType[eventType] = new Relations(
@@ -805,7 +798,6 @@ EventTimelineSet.prototype.aggregateRelations = function(event) {
eventType,
this.room,
);
isNewRelations = true;
relatesToEvent = this.findEventById(relatesToEventId) || this.room.getPendingEvent(relatesToEventId);
if (relatesToEvent) {
relationsWithEventType.setTargetEvent(relatesToEvent);
@@ -813,11 +805,6 @@ EventTimelineSet.prototype.aggregateRelations = function(event) {
}
relationsWithEventType.addEvent(event);
// only emit once event has been added to relations
if (isNewRelations && relatesToEvent) {
relatesToEvent.emit("Event.relationsCreated", relationType, eventType);
}
};
/**
+2 -2
View File
@@ -19,7 +19,7 @@ limitations under the License.
* @module models/event-timeline
*/
import {RoomState} from "./room-state";
import { RoomState } from "./room-state";
/**
* Construct a new EventTimeline
@@ -55,7 +55,7 @@ export function EventTimeline(eventTimelineSet) {
this._nextTimeline = null;
// this is used by client.js
this._paginationRequests = {'b': null, 'f': null};
this._paginationRequests = { 'b': null, 'f': null };
this._name = this._roomId + ":" + new Date().toISOString();
}

Some files were not shown because too many files have changed in this diff Show More