Compare commits

...

1063 Commits

Author SHA1 Message Date
Benjamin Kampmann fefd2a6b68 chore: crates.io only accepts versioned git deps 2022-09-28 17:15:09 +02:00
Benjamin Kampmann 269bf3a706 chore: remove old release notes 2022-09-28 17:07:37 +02:00
Benjamin Kampmann 91d1ee9f09 chore: fix typos in Upgrade guide 2022-09-28 17:07:37 +02:00
Benjamin Kampmann b22fe63476 chore: More minor changes of note 2022-09-28 17:07:37 +02:00
Benjamin Kampmann 92467af4a0 docs: Upgrading typo fixes 2022-09-28 17:07:37 +02:00
Benjamin Kampmann f1f1c1bba6 chore: Version bump 2022-09-28 17:07:37 +02:00
Benjamin Kampmann ff82d6420d chore: specify which crates to release and which not 2022-09-28 17:07:37 +02:00
Benjamin Kampmann b9409b7c0f docs: more migrations guide 2022-09-28 17:07:37 +02:00
Benjamin Kampmann ea51935601 docs: Clarifications in the Upgrade guide 2022-09-28 17:07:37 +02:00
Benjamin Kampmann 2fff5d916b docs: More Upgrade guidance 2022-09-28 17:07:37 +02:00
Benjamin Kampmann d16faee68b docs: First outline of upgrades guide 2022-09-28 17:07:37 +02:00
Benjamin Kampmann df9b60a5bc chore: Ignore flaky redaction tests 2022-09-28 17:07:10 +02:00
Damir Jelić 1a57170970 test(crypto): Make sure we don't accept megolm encrypted events over to-device 2022-09-28 16:03:17 +02:00
Damir Jelić 41449d2cc3 test(crypto): Test that we reject forwarded room keys from other users 2022-09-28 16:03:17 +02:00
Damir Jelić 093fb5d0aa fix(crypto): Only accept forwarded room keys from our own trusted devices 2022-09-28 16:03:17 +02:00
Ivan Enderlin 513afa57ef feat(indexeddb): Introduce the experimental-nodejs feature
feat(indexeddb): Introduce the `experimental-nodejs` feature
2022-09-28 14:57:55 +02:00
Ivan Enderlin 25632f04d4 feat(crypto-js): Update to napi-rs 2.9.1
feat(crypto-js): Update to `napi-rs` 2.9.1
2022-09-28 14:52:03 +02:00
Ivan Enderlin 7922786e0c chore: Fix formatting. 2022-09-28 14:34:16 +02:00
Ivan Enderlin 9a006c58f5 feat(crypto-js): Update to napi-rs 2.9.1 2022-09-28 14:30:40 +02:00
Ivan Enderlin 9f4385e639 feat(indexeddb): Introduce the experimental-nodejs feature.
By default, the new `experimental-nodejs` feature is
disabled. However, when enabled, it uses our own fork of
`indexed_db_futures` that make it work on Node.js, and so this entire
`matrix-sdk-indexebdb` crate.
2022-09-28 14:27:37 +02:00
Damir Jelić e79b683560 fix(crypto): Drop the redundant event_type field from ToDeviceEvent<C> 2022-09-28 11:27:44 +02:00
Damir Jelić 27e4675df0 fix(crypto) Fix the zeroizing serialization of to-device events
The crypto crate consumes to-device events, if needed decrypts them, and
in the end reserializes while zeroizing secrets.

It needs to do this reserialization cycle as loslessly as possible, this
is why we have a bunch of BTreeMaps lying in events and contents that
capture unknown fields.

The Deserialize implementation of ToDeviceEvent<C> put the event type
into this BTreeMap but the Serialize implementation figures it out from
the EventType trait of the content.

This patch simplifies things by putting the event type into
ToDeviceEvent<C>, this also means that we can just derive the Serialize
implementation for ToDeviceEvent<C>.
2022-09-27 21:33:06 +02:00
Benjamin Kampmann b5bd6dfee9 fix: Apply redactions to room state events in database, too (#917)
fixes #890
2022-09-27 09:24:53 +02:00
Ivan Enderlin f8b02d1a11 feat(crypto-js): Implement OlmMachine.export_room_keys and .import_room_keys
feat(crypto-js): Implement `OlmMachine.export_room_keys` and `.import_room_keys`
2022-09-27 07:26:51 +02:00
Jonas Platte 0a5ebe4dce feat(sdk): Make EventHandlerDropGuard public (#1055) 2022-09-26 18:18:12 +02:00
Benjamin Kampmann e8278b5d68 feat: add Result return value to sync_* (#1037)
Inspired by the changes in #1013 I was thinking about the use case for `sync_*` and how we handle error cases. Most notably while we give the callback the option to stop the loop, we don't really give an indication to the outside, how to interpret that cancellation: was there a failure? should we restart?

Take e.g. a connectivity issue on the wire, we'd constantly loop and just `warn`, what you might or might not see. Even if you handle that in the `sync_with_result_callback` and thus break the loop, the outer caller now still doesn't know whether everything is honky dory or whether they should restart. 

This Changes reworks that area by having all the `sync` return `Result<(), Error>`, where `()` means it was ended by the inner callback (which in `sync()` never occurs) or `Error` is the error either the inner `result_callback` found or the that was coming from the `send` in the first place. Thus allowing us to e.g. back down to sync as it was a dead wire or restart it if there was only a temporary problem. Making all that a just a bit more "rust-y".
2022-09-26 17:14:15 +02:00
Jonas Platte f054141e66 chore: Revert "feat(sdk): Make room actions return typed room objects" 2022-09-26 14:13:25 +02:00
Jonas Platte 1a6d5e7b26 Revert "feat(sdk): Make room actions return typed room objects"
This reverts commit febfcf9796.
2022-09-26 14:01:52 +02:00
Jonas Platte d3e5a3b7db Revert "test: Add test for repeated joining and leaving"
This partially reverts commit df4ee7db4c.
The changes to logging and ci-start.sh are kept.
2022-09-26 12:31:12 +02:00
Jonas Platte 92809590b1 Revert "feat(examples): Add an example that lets you create rooms"
This reverts commit 01f8ed10aa.
2022-09-26 12:23:08 +02:00
Jonas Platte 00d388f3d3 Revert "feat(sdk): Make room actions return typed room objects"
This reverts commit febfcf9796.
2022-09-26 12:19:36 +02:00
Jonas Platte 59901b6349 Update Cargo.lock 2022-09-26 12:19:36 +02:00
Johannes Becker 914ac5279e chore: Make clippy happy 2022-09-23 17:01:01 +02:00
Johannes Becker c23976f975 refactor(appservice): Move example to top-level 2022-09-23 17:01:01 +02:00
Emelie Graven cb94d60e0e feat(appservice): Add default request config
This adds a default RequestConfig to use when creating new virtual
clients.
2022-09-22 14:25:00 +02:00
Ivan Enderlin df50a5446f test(crypto-js): Test InboundGrounSession.sessionId and .hasBeenImported. 2022-09-22 11:31:28 +02:00
Ivan Enderlin 62ab263d0e test(crypto-js): Test OlmMachine.(en|de)crypt_exported_room_keys. 2022-09-22 11:27:12 +02:00
Emelie Graven 2818551d62 refactor(appservice)!: Use builder pattern 2022-09-22 10:38:17 +02:00
Emelie Graven c29b0f154a chore: Add rust.vim edition workaround 2022-09-22 10:38:17 +02:00
Ivan Enderlin 6fa04a0ba1 feat(crypto-js): Implement OlmMachine.(en|de)crypt_exported_room_keys. 2022-09-21 18:00:15 +02:00
Ivan Enderlin dee14c4ee4 doc(crypto-js): Improve documentation of OlmMachine.import_room_keys. 2022-09-21 17:50:28 +02:00
Ivan Enderlin 5b919dd840 test(crypto-js): Test OlmMachine.import_room_keys. 2022-09-21 17:46:23 +02:00
Ivan Enderlin 406fc58720 feat(crypto-js): Implement OlmMachine.import_room_keys. 2022-09-21 17:37:23 +02:00
Ivan Enderlin b4cec6e1bb feat(crypto-js): Implement OlmMachine.export_room_keys. 2022-09-21 16:03:51 +02:00
Ivan Enderlin 6be0fc1fae feat(sdk): Rename (export|import)_keys to (export|import)_room_keys
feat(sdk): Rename `(export|import)_keys` to `(export|import)_room_keys`
2022-09-21 16:03:29 +02:00
Ivan Enderlin 782b256ea9 test(crypto): Rename OlmMachine.export_keys to OlmMachine.export_room_keys. 2022-09-21 13:43:25 +02:00
Ivan Enderlin 82670022f9 feat(crypto-ffi): Update olm.udl. 2022-09-21 13:24:25 +02:00
Ivan Enderlin b8c41e805b feat(sdk): Rename decrypt_key_export to decrypt_room_key_export. 2022-09-21 13:18:24 +02:00
Ivan Enderlin e3d63c5593 feat(sdk): Rename encrypt_key_export to encrypt_room_key_export. 2022-09-21 13:16:08 +02:00
Ivan Enderlin 0222a8fec2 feat(sdk): Rename OlmMachine.import_keys to .import_room_keys.
Because that's what it does :-).
2022-09-21 13:12:07 +02:00
Ivan Enderlin b442247946 feat(sdk): Rename OlmMachine.export_keys to .export_room_keys.
Because that's what it does :-).
2022-09-21 13:03:42 +02:00
Ivan Enderlin c0ebeee730 feat(crypto-js): Implement OlmMachine.get_identity
feat(crypto-js): Implement `OlmMachine.get_identity`
2022-09-21 10:44:18 +02:00
Stefan Ceriu a46b8f392a Switch ffi layer logs output to stderr instead of stdout 2022-09-21 08:24:09 +02:00
Jonas Platte b12da9d4db refactor!: Move JS-specific functionality behind a Cargo feature
… for matrix-sdk, matrix-sdk-base, matrix-sdk-common and matrix-sdk-crypto.
matrix-sdk-indexeddb as well as the JS bindings and wasm_command_bot are
left as-is because they will likely always require JS.
2022-09-20 14:08:21 +02:00
Stefan Ceriu 6f5681f7c2 feat(bindings): Expose method for fetching media thumbnails 2022-09-19 10:56:22 +00:00
Jonas Platte fee0db03c8 ci: Don't collect coverage for labs 2022-09-19 12:15:13 +02:00
Jonas Platte b2ce906bce ci: Don't report coverage inside test code 2022-09-19 12:15:13 +02:00
Jonas Platte e45d6f45fd refactor: Replace str::to_string with to_owned 2022-09-16 17:45:43 +02:00
Ivan Enderlin 84aa85958c test(crypto-js): Test OlmMachine.getIdentity. 2022-09-16 11:23:32 +02:00
Jonas Platte b941c16b7d chore(sdk): Upgrade derive_builder 2022-09-16 11:17:24 +02:00
Ivan Enderlin 1a5379881e test(crypto-js): Test EventId. 2022-09-16 11:11:06 +02:00
Ivan Enderlin 0c4b85e1f9 feat(crypto-js): Implement OwnUserIdentity and UserIdentity. 2022-09-16 11:02:34 +02:00
Ivan Enderlin 602dbe42f2 doc(crypto): Fix a typo. 2022-09-16 10:57:02 +02:00
Ivan Enderlin d3d316ee6c chore(crypto-js): Add helper to cast from JS Array to Vec<T>. 2022-09-16 10:46:28 +02:00
Jonas Platte 494969ed49 chore: Fix clippy lints 2022-09-15 20:48:22 +02:00
Kévin Commaille 34ed04958f fix(sdk): Export RoomKeyImportError 2022-09-15 18:35:59 +02:00
Jonas Platte 8da456055d refactor: Use event handlers in emoji_verification example 2022-09-15 18:33:58 +02:00
Jonas Platte ef462c786a refactor(sdk): Clean up sync_with_callback implementation 2022-09-15 17:53:32 +02:00
Benjamin Kampmann 1a50f42402 fix(jack-in): limit log4rs features to minimum 2022-09-15 17:08:09 +02:00
Benjamin Kampmann 020a75d55c feat: implement " MSC 3575: sliding sync " behind a feature flag (#728)
* starting with jack-in

* starting by flying tui

* connecting to real server, showing info

* add .env to gitignore

* infrastructure for tests

* display loading time for syncv2

* minor design updates

* initial sync

* finalise first edition of sliding sync

* directly link to sliding sync and show rooms list

* nicer UI, toggle logs

* passing through sliding sync homeserver

* separate syncs and disable v2 autostart

* selecting rooms

* nicer view

* configurable batches and more default needed events

* selecting rooms

* calculate and show status info per room

* precalculated room stats

* restructure code to allow for cancellation of streams

* finish up merge updates

* fix calculation error in room list len

* cleaning up system flow

* fixing sync up

* new multi-view API

* move sliding sync in separate module

* fixing format

* adding and clearning views

* expose filters and timeline limits

* renamed

* adding room subscriptions to sliding sync

* update summary

* live fetching and subscriptions in jack-in

* subscribe to selected room

* starting to switch to tuireal - using example

* status bar and first linkup

* re-adding rooms

* implementing port for customised update event

* showing details and timeline

* fix formatting

* cleaner UI, updating details quickly

* make it green

* implement other Ops

* proper handling of invalidation

* saving sliding sync results to db, too

* saving new prev_batch field if given

* split events and timeline

* cleaning up

* live updates

* upgrading to latest ruma and matrix-sdk

* Update tui-logger to fix the broken build

* fixing latest ruma sliding-sync-branch updates

* feat: first set of ffi sliding sync

* expose sliding sync via FFI

* implement un-/subscribe

* implement view state updates

* updating to latest JSON format and ruma update

* implementing room selecting for new data model

* fixing room selection

* fixing feature flag requirements for sliding-sync

* fixing style, clippy and docs

* style(sliding-sync): fixing rust format styles

* fix(ffi): fixing sliding sync merge failure

* fix(jack-in): update jack-in to latest ruma

* fix(sliding-sync): need to have a version set before polling proxy

* expose sliding sync builder over ffi

* add SlidingSyncViewBuilder

* add forgotten changes on sdk itself

* new file logger feature on jack for deeper logging

* fix(http-client): log the raw request we are sending out

* feat(sliding-sync): better logging

* fix(sliding-sync): switch to full-listen after reaching live state in full-sync and make sure we replace the correct entries

* feat(ffi): expose sliding sync view ranges

* fix(ffi): fixing sliding sync start_sync loop to actually loop

* feat(sliding-sync): allow lookup of room data

* feat(sliding-sync-ffi): fetching name of room

* feat(ffi): expose unread_notifications of rooms

* feat(ffi): stoppable spawn for sliding sync

* fix(ffi): expose has_unread_notifications on room

* feat(sliding-sync): latest room message

* fix(sliding-sync): update to latest ruma layout

* doc(sliding-sync): adding docs to builder fns

* feat(sliding-sync): extra signal on the view to inform about general updates

* fix(sync-v4-ffi): expose new callbacks via ffi

* fix(sliding-sync): reduce default required states to make things faster

* fix(sliding-sync): fix build params

* feat(jack-in): extended instrumentation

* fix(sliding-sync): unbreak faulty feature-gate

* fix(sliding-sync-ffi): mut where mut is due

* fix(sdk): allow separate homeserver on every request to unbreak using send on client while in sliding sync on a proxy

* fix(jack-in): update to latest dependencies, that work

* feat(ffi): helper to patch sliding sync room into regular room

* style(jack-in): cargo fmt

* fix(sliding-sync): Update to latest ruma changes

* fix(sliding-sync): fix missing FFI updates to latest ruma

* feat(sliding-sync)!: simplify stream cancellation, cancel ffi sync if already existing

* fix: timeline backwards pagination must work without synctoken

* fix(sliding-sync): clarify order of messaes in alive TL; pick correct last item

* fix: update view delegate api for clarity

* style(jack-in): fix cargo warnings

* feat(sliding-sync): update room details

* fix(sliding-sync): only update room info selectively when given

* fix(sliding-sync-ffi): convert and store counts as u32, check against 0 for has notificaitons

* style: cargo fmt, file endings and a few other minor style fixes

* docs(jack-in): improving CLI and Readme

* feat(sliding-sync): allow setting of required event_states on viewbuilder

* style(sliding-sync): docs and minor fixes

* style(sliding-sync): various clippy fixes

* style(jack-in): clippy suggestions applied

* fix(sliding-sync): Delegate becomes observer

* test(sdk): adding test for request config

* docs: Fixing copyright header

* style(ffi): Nicer naming of params for observer

* fix(ffi): sliding sync is not optional for now

* fix(sdk): remove superflusous tracing instrumentation

* fix(sdk): use structured logging

* fix(jack-in): removed unneded log import

* fix(jack-in): use server_name rather than deprecated user_id on ClientBuilder

* style: typo and clippy

* style(sliding-sync): clippy and formatting

* fix(sliding-sync): cleaning up minor syntax issues

* fix: remove unneded feature-definition section

* fix(sliding-sync): minor fixes as per review

* fix(sliding-sync): Make Builders owned

* fix(sliding-sync): more minor style improvements

* fix(sliding-sync): minor style improvements

* fix(sliding-sync): remove homeserver from RequestConfig, use specific internal fn instead

Co-authored-by: Stefan Ceriu <stefanc@matrix.org>
2022-09-15 11:45:29 +00:00
Ivan Enderlin f4e0c6e243 feat(crypto-js): Start implementing OlmMachine.get_identity. 2022-09-15 10:32:57 +02:00
Ivan Enderlin 01f1b9b846 feat(crypto-js): Implement EventId. 2022-09-15 10:32:57 +02:00
Ivan Enderlin abcd287496 chore(crypto-js): Simplify code with a lovely macro. 2022-09-15 10:32:57 +02:00
Ivan Enderlin cf96a3ba2e feat(crypto-js): Implement key verification
feat(crypto-js): Implement key verification
2022-09-15 10:13:51 +02:00
Ivan Enderlin 9d2e0fe8ad doc(crypto-js): Fix typos. 2022-09-15 09:59:27 +02:00
Jonas Platte 83d5e567eb feat(bindings): Update send_reply to accept markdown 2022-09-14 22:10:16 +02:00
Benjamin Kampmann a47d8669cd feat: log out facilities
Merge pull request #1013 from matrix-org/ismail/logout

Add logout facilities to `client` and helpers to ffi for tracking the soft-logout issued by a server. Further more this adapts the `sync_with_callback` by adding a new `sync_with_result_callback` that hands the entire `Result` to the callback.
2022-09-14 15:15:47 +02:00
ismailgulek 0643292d76 Fix formatting 2022-09-14 15:07:05 +03:00
ismailgulek 8a26ba8343 Add a warning on sync error 2022-09-14 14:29:30 +03:00
ismailgulek cc1c6aedcb Revert sync_with_callback api call changes 2022-09-14 14:17:30 +03:00
ismailgulek 55cf573142 Implement the new sync with result callback method 2022-09-14 14:10:01 +03:00
Stefan Ceriu c5006081e6 feat(bindings): Add method for sending plain text replies 2022-09-14 10:21:23 +00:00
Ivan Enderlin 4c4fcf91c1 chore(crypto-js): Inline vodozemac dependency. 2022-09-14 10:01:03 +02:00
Ivan Enderlin 6842fb97fd chore(crypto-js): Make Clippy happy. 2022-09-14 09:58:09 +02:00
Ivan Enderlin 8027a3036c test(crypto-js): Remove dependency to canvas. 2022-09-14 09:58:09 +02:00
Ivan Enderlin 1d9ac6e60c chore(crypto-js): Fix typos. 2022-09-14 09:58:09 +02:00
Ivan Enderlin 2f35b2cfc6 feat(crypto-js): QrCodeScan implements Debug. 2022-09-14 09:58:09 +02:00
Ivan Enderlin 7edd6a148c doc(crypto-js): Fix module documentation. 2022-09-14 09:58:09 +02:00
Ivan Enderlin 3b526ea412 doc(crypto-js): Add missing documentation. 2022-09-14 09:58:09 +02:00
Ivan Enderlin 1c50cee5d7 feat(crypto-js): Implement Sas and Qr cancel* methods. 2022-09-14 09:58:09 +02:00
Ivan Enderlin cb95c59194 test(crypto-js): Test m.key.verification.start and .done for QR code. 2022-09-14 09:58:09 +02:00
Ivan Enderlin 792b4581ab feat(crypto-js): Implement Qr.reciprocate and .confirm_scanning. 2022-09-14 09:58:09 +02:00
Ivan Enderlin 58ea598c68 feat(crypto-js): Implement VerificationRequest.scan_qr_code. 2022-09-14 09:58:09 +02:00
Ivan Enderlin 581c537396 test(crypto-js): Properly test `Qr.toQrCode. 2022-09-14 09:58:09 +02:00
Ivan Enderlin 9834b67bd5 feat(crypto-js): QrCode.renderIntoBuffer returns an Uint8ClampedArray. 2022-09-14 09:58:09 +02:00
Ivan Enderlin 6f89d02599 test(crypto-js): Test QrCode.render_into_buffer. 2022-09-14 09:58:09 +02:00
Ivan Enderlin cbb5080837 test(crypto-js): Properly test Qr.toBytes. 2022-09-14 09:58:09 +02:00
Ivan Enderlin 6a05f834a9 test(crypto-js): Test Qr.toBytes. 2022-09-14 09:58:09 +02:00
Ivan Enderlin c7e0b3ee31 test(crypto-js): Testing key verification workflow until QR code generation. 2022-09-14 09:58:09 +02:00
Ivan Enderlin 0d57983e1b feat(crypto-js): Implement VerificationRequest.generate_qr_code. 2022-09-14 09:58:09 +02:00
Ivan Enderlin bbfc076c7f test(crypto-js): Inject bootstrap cross signing keys when setting up machines. 2022-09-14 09:58:09 +02:00
Ivan Enderlin e367d8574d feat(crypto-js): Implement OlmMachine.bootstrap_cross_signing. 2022-09-14 09:58:09 +02:00
Ivan Enderlin 1be17d354d feat(crypto-js): Implement OlmMachine.(export|import)_cross_signing_keys. 2022-09-14 09:58:09 +02:00
Ivan Enderlin e8331cc40c feat(crypto-js): Enable the qrcode feature by default. 2022-09-14 09:58:09 +02:00
Ivan Enderlin 71a2fac46f test(crypto-js): Reorganize the tests a little bit. 2022-09-14 09:58:09 +02:00
Ivan Enderlin 8948333e1e test(crypto-js): Test until m.key.verification.done \o/. 2022-09-14 09:58:09 +02:00
Ivan Enderlin c471a6fb4d test(crypto-js): Split the Key Verification test case into a test suite. 2022-09-14 09:58:09 +02:00
Ivan Enderlin 6239d31bcf test(crypto-js): Test the Emoji and decimals implementations. 2022-09-14 09:58:09 +02:00
Ivan Enderlin b5a8103023 feat(crypto-js): Implement Sas.accept. 2022-09-14 09:58:09 +02:00
Ivan Enderlin 95709bb4b3 test(crypto-js): Test the Sas implementation. 2022-09-14 09:58:09 +02:00
Ivan Enderlin 14f22979c0 feat(crypto-js): Implement VerificationRequest.start_sas. 2022-09-14 09:58:09 +02:00
Ivan Enderlin e6141d8efc test(crypto-js): Continue to test m.key.verification.request and .ready. 2022-09-14 09:58:09 +02:00
Ivan Enderlin 155b187d45 test(crypto-js): Write first tests for key verification. 2022-09-14 09:58:09 +02:00
Ivan Enderlin e659c724cd chore(crypto-js): Some methods have been renamed. 2022-09-14 09:58:09 +02:00
Ivan Enderlin e00b9221b9 feat(crypto-js): Implement Device.request_verification. 2022-09-14 09:58:09 +02:00
Ivan Enderlin b6f01b3cec feat(crypto-js): Implement the Device and UserDevice API. 2022-09-14 09:58:09 +02:00
Ivan Enderlin 53e21e0c26 feat(crypto-js): Start implementation key verification API. 2022-09-14 09:58:06 +02:00
Ivan Enderlin 9155989060 feat(crypto): Simplify code and add documentation. 2022-09-14 09:56:33 +02:00
Doug bb62437369 feat(bindings): Expose redact method to FFI 2022-09-13 23:06:11 +02:00
Damir Jelić 6e6c474bcb chore(base): Bump the lru crate 2022-09-13 16:03:42 +02:00
Damir Jelić 8ba33f6fd3 chore: Bump vodozemac to a released version 2022-09-13 16:03:42 +02:00
ismailgulek 2591bcbca9 Fix PR remarks 2022-09-13 15:47:26 +03:00
ismailgulek 18a8b2f275 Merge branch 'main' into ismail/logout 2022-09-13 13:01:57 +03:00
ismailgulek f4764bbd8a Fix PR comment 2022-09-13 13:01:38 +03:00
Jonas Platte e46e13d1bf chore: Upgrade Ruma 2022-09-13 08:32:59 +00:00
Kévin Commaille 97995b7bf6 fix(sdk): Re-export qrcode encoding and decoding error types 2022-09-12 19:27:30 +02:00
ismailgulek b4f0438c1a Move processing sync errors into a separate method 2022-09-12 18:40:50 +03:00
ismailgulek 076de488e7 Avoid too much indentation 2022-09-12 17:54:55 +03:00
ismailgulek d0d8e38a1d Merge branch 'main' into ismail/logout 2022-09-12 17:38:24 +03:00
Damir Jelić aac41fc82a refactor(crypto): Remove the forwarding chains
These aren't really useful since they can be easily spoofed by any room
key forwarder.
2022-09-12 16:03:05 +02:00
ismailgulek 268ecea7fe Fix new format error 2022-09-12 16:55:03 +03:00
ismailgulek 24be8a8e82 Update tests 2022-09-12 16:29:46 +03:00
ismailgulek 3cc6fe5dea Fix format errors 2022-09-12 15:35:45 +03:00
Ivan Enderlin d1b2bfcaa4 feat(qrcode): Remove decoding QR code from an image
feat(qrcode): Remove decoding QR code from an image
2022-09-12 13:33:42 +02:00
Ivan Enderlin a0edd2f8d8 test(qrcode): Restore image only for one test. 2022-09-12 12:42:18 +02:00
Ivan Enderlin 478529f230 chore: Update Cargo.lock. 2022-09-12 12:28:31 +02:00
Ivan Enderlin 9411801245 feat(qrcode): Remove decoding QR code from an image.
This patch removes the `decode_image` (default) feature for this
`matrix-sdk-qrcode` crate.

First reason is that `rqrr` panics for some particular QR codes, and
we don't want to panic.

Second reason is that it's not a feature that is used. For Element on
iOS and Android, it's very unlikely that every frame from the camera
will be sent to `matrix-sdk-qrcode` to see if it can be decoded. So
it's obvious that an external library is used to read the bytes from
the QR code, that are then sent to `matrix-sdk-qrcode`. For Element on
Web, it's basically the same argument.

This feature is actually used only in our tests to ensure the
generated QR code is valid, but it sometimes fails due to `rqrr`
(cf. First reason).
2022-09-12 12:15:49 +02:00
ismailgulek 361313fbea Merge branch 'main' into ismail/logout 2022-09-12 13:10:21 +03:00
Ivan Enderlin 2a94f575b8 feat(qrcode): Allow VerificationData to receive a flow ID
feat(qrcode): Allow `VerificationData` to receive a flow ID
2022-09-12 12:10:11 +02:00
Ivan Enderlin f9d09b60d5 chore(crypto): Reduce the size of AnyDecryptedOlmEvent.
`AnyDecryptedOlmEvent::Custom` contains at least 440 bytes, while the
second-largest variant (`RoomKey`) contains at least 0 bytes. Let's
box `Custom` so that the size of `AnyDecryptedOlmEvent` stays low.
2022-09-12 11:57:45 +02:00
ismailgulek 03477afb26 Add initial_device_name and device_id parameters to login method 2022-09-12 12:53:28 +03:00
ismailgulek 6b66a1de56 Introduce did_update_restore_token delegate method 2022-09-12 12:52:27 +03:00
ismailgulek 519a005d16 Introduce is_soft_logout flag on Client and did_receive_auth_error delegate method 2022-09-12 12:51:35 +03:00
Ivan Enderlin 7831e0cd89 chore(crypto): Use to_owned instead of to_string. 2022-09-12 09:49:30 +02:00
Ivan Enderlin 70eeffbbb0 doc(qrcode): Update documentation.
Since we have switched to Vodozemac, those values don't need to be
unpadded base64 anymore.
2022-09-12 09:47:38 +02:00
Jonas Platte 831e802dd0 refactor(bindings): Move some more functions and methods out of UDL 2022-09-09 14:30:23 +02:00
Jonas Platte ab0c144f51 chore: Upgrade UniFFI 2022-09-09 14:30:23 +02:00
Jonas Platte dc05c6e2b8 chore: Silence clippy lint 2022-09-09 12:51:57 +02:00
Jonas Platte 3a6397fdba chore: Update Cargo.lock 2022-09-09 12:51:57 +02:00
Jonas Platte 4a481f09d1 fix(base): Make tokio dev-dependency arch-dependent 2022-09-09 12:51:57 +02:00
Ivan Enderlin fa6745bb60 feat(qrcode): DecodingError::Identifier is no longer useful. 2022-09-08 16:14:30 +02:00
Ivan Enderlin cb21d89229 test(qrcode): Removing decode_invalid_room_id.
A room ID can no longer be invalid, it's just a string representing
either a `EventId` (we can validate that but…) or a `TransactionId`
(which is an opaque string, so it can be anything).
2022-09-08 16:12:21 +02:00
Ivan Enderlin 12b1ec5ef9 feat(crypto): VerificationData takes a flow ID, removing a panic.
This patch updates `QrVerification::new_cross`, by passing a flow ID
as an owned `String` to `VerificationData`, thus removing a panic, and
allowing QR code verification to happen outside a room.
2022-09-08 15:43:26 +02:00
Ivan Enderlin aa1a47831a chore(crypto): Use longer variable names. 2022-09-08 15:43:09 +02:00
Ivan Enderlin cc5034f4b9 feat(qrcode): Allow VerificationData to receive a flow ID.
This patch updates `VerificationData` to receive a flow ID,
represented as an owned `String`, instead of an `OwnedEventId`. Why?
Because QR code verification can happen outside a room. In such
scenario, there is no event ID, but a transaction ID, unified behind
the `matrix_sdk_crypto::FlowId` enum. `VerificationData` doesn't
really care about that details. Proof is that `QrVerificationData`
receives an owned `String`, which is then casted into an
`OwnedEventId` to match this API properly; but at the top, it just
receives a string.

This patch brings also a little bit of clean up while editing code
around.
2022-09-08 15:37:01 +02:00
Jonas Platte 3be8c9585d refactor(sdk): Make SyncSettings Debug repr more compact 2022-09-08 12:13:30 +02:00
Jonas Platte d810fa6883 test(sdk): Enable logging for tests 2022-09-08 12:13:30 +02:00
Jonas Platte a744447bb5 test: Respect RUST_LOG in integration-testing 2022-09-08 12:13:30 +02:00
Damir Jelić 9252e2c7a9 refactor(sdk): Fetch the content using the new account data methods
Co-authored-by: Jonas Platte <jplatte@matrix.org>
2022-09-07 13:38:42 +02:00
Damir Jelić 282072b6b0 chore(bindings): Fix a typo 2022-09-07 13:38:42 +02:00
Timothy Hobbs e997da0e72 feat(sdk): Make created_dm_room public 2022-09-07 13:38:42 +02:00
Benjamin Kampmann b3f3d0a95e fix(sdk): proper implementation of stripped info preference
Merge pull request #979 from FlixCoder/cleanup

Fixes a problem, where non-stripped information of the room had predecence in all scenarios of the memory-, sled- and indexeddb-store, thought according to the spec, we prefer the full info only until we've received new stripped info (from another invite). This fixes that to be in line with the spec by removing stripped data when we see a full-event and keep stripped info preferred if found (so, after you joined, stripped data is removed and when you knocked or are invited again, it is preferred), without ever deleting full data. It also adds nice unit- and integration tests to ensure this works as intended.
2022-09-06 15:47:14 +02:00
ismailgulek 42767968ec Implement logout method on Client 2022-09-06 15:56:14 +03:00
Benjamin Kampmann 68a8a214ee Update testing/matrix-sdk-integration-testing/assets/ci-start.sh 2022-09-06 12:42:54 +02:00
Jonas Platte 5adec41b6b test: Use a weak password hash for crypto-store testing
This speeds up the crypto-store tests a lot.
2022-09-05 16:58:12 +02:00
Flix b816307ea9 fix: Listen only to events after sending the request 2022-09-05 16:41:55 +02:00
Flix a182578722 fix: Fix rooms being returned in wrong state and having wrong state 2022-09-05 16:41:55 +02:00
Flix 8b5368ff06 chore: Clean up various mini things 2022-09-05 16:41:52 +02:00
Flix a368caf2b0 test: Add StateStore integration test for stripped/non-stripped 2022-09-05 16:33:31 +02:00
Flix df4ee7db4c test: Add test for repeated joining and leaving 2022-09-05 16:33:31 +02:00
Damir Jelić 321e56cff8 fix(examples): Listen to the done event in the emoji verification example
Nowadays all verifications send a done event, so this is the safer
option.
2022-09-05 15:54:45 +02:00
Damir Jelić a640312503 feat(crypto): Add method to format emojis
This patch adds a method to format a list of emojis in a a terminal
friendly way.

This method was borrowed from weechat-matrix but it's also quite useful
in our own emoji verification example.
2022-09-05 15:54:45 +02:00
Damir Jelić b2452ae92c feat(examples): Add a verbosity flag to the emoji example
Since this example prints out messages to stdout, it becomes quite hard
to see when we ask for user input if all the logging is going on.

This patch adds a standard verbosity flag which disables all logging by
default.
2022-09-05 15:54:45 +02:00
Jonas Platte a25b2d4418 refactor(crypto): Clean up cryptostore_integration_tests macro 2022-09-05 15:44:14 +02:00
Jonas Platte 5f6775f47c ci: Only cancel running CI for previous commits on PRs 2022-09-05 15:01:38 +02:00
Jonas Platte c2a222278d ci: Consistently indent job steps 2022-09-05 15:01:38 +02:00
Jonas Platte 567b230cb7 ci: Cache xtask binary 2022-09-05 15:01:38 +02:00
Jonas Platte 8535c16bc8 ci: Don't require fmt to run before typo check and clippy 2022-09-05 15:01:38 +02:00
Jonas Platte d009d0475e ci: Move appservice and style back into ci workflow
Required for job dependencies.
2022-09-05 15:01:38 +02:00
Jonas Platte 6b8cf3c02a chore: Remove pre-commit configuration and CI job
It was not really being used.
2022-09-05 15:01:38 +02:00
Jonas Platte edfc0cbe20 refactor(sdk): Deprecate ClientBuilder::user_id 2022-09-05 12:43:21 +02:00
Jonas Platte 91186d8a25 doc(sdk): Replace deprecated method in doctest 2022-09-05 11:55:49 +02:00
Jonas Platte 090d67b6ef refactor(sdk): Move module-level documentation inside the module files 2022-09-05 11:55:49 +02:00
Jonas Platte fd4957f533 test(sdk): Address commented-out code in a test 2022-09-05 11:55:49 +02:00
Jonas Platte 08760bd4c0 refactor(sdk): Make base_client field of Client private 2022-09-05 11:55:49 +02:00
Jonas Platte b769827313 refactor(sdk)!: Move media methods from Client to a new type 2022-09-05 11:55:49 +02:00
Jonas Platte 79b5854c83 feat(sdk): Add request_config method to Client 2022-09-05 11:55:49 +02:00
Jonas Platte 38324f6c60 refactor(sdk): Use Client::send in Client::upload 2022-09-05 11:55:49 +02:00
Jonas Platte 33bce0b18d refactor(sdk): Move RoomMember into room module 2022-09-05 11:55:49 +02:00
Jonas Platte 245ecea263 feat(sdk): Add support for AnySyncTimelineEvent in event handlers 2022-09-05 11:55:17 +02:00
Jonas Platte d4ac1bffd0 refactor(sdk): Rename EventKind to HandlerKind
It's somewhat different as MessageLike, OriginalMessageLike and
RedactedMessageLike are not three distinct event kinds in Ruma.
2022-09-05 11:55:17 +02:00
Jonas Platte d6af63e37b refactor(sdk): Run event handlers for the same event concurrently 2022-09-05 11:55:17 +02:00
Jonas Platte 57dde2c4d3 refactor(sdk): Avoid duplicate work and fix event handler call order
Previously, when both a possibly-redacted timeline event handler and a
non-redacted timeline timeline event handler would apply to multiple
events in a sync response, they would individually run for every event
in order. With this change, they will instead both be called
for one event before the next is processed.
2022-09-05 11:55:17 +02:00
Kévin Commaille 6f3813a65f Re-export vodozemac errors in a separate module 2022-09-05 11:44:42 +02:00
Kévin Commaille 433f75ae57 Remove dead error variants 2022-09-05 11:44:42 +02:00
Kévin Commaille 8f0fb08fe7 feat(sdk): Re-export matrix-sdk-crypto errors 2022-09-05 11:44:42 +02:00
Jonas Platte 4f6ff5c0d3 refactor(sdk): Make use of new Default impls from Ruma 2022-09-02 15:03:00 +02:00
Jonas Platte c4d46f233e chore: Upgrade ruma 2022-09-02 15:03:00 +02:00
Damir Jelić faf0ce5007 chore(examples): Remove some empty useless attributes 2022-09-02 14:54:33 +02:00
Damir Jelić c5e6178b70 refactor(examples): Add proxy support to the emoji verification example 2022-09-02 14:54:33 +02:00
Jonas Platte bf9f431e22 refactor(sdk): Use new account_data method internally 2022-09-02 14:09:17 +02:00
Damir Jelić 4b673cfe9c chore: Fix a bunch of clippy warnings 2022-09-02 11:39:06 +02:00
Benjamin Kampmann 0079f1d569 Merge pull request #977 from zecakeh/fix-examples-autojoin
fix(examples): Fix examples that accept invites
2022-09-02 11:14:40 +02:00
Damir Jelić a71292cb16 chore(crypto): Remove a bunch of unnecessary allow deprecated attributes 2022-09-01 17:08:24 +02:00
Damir Jelić cc813b049e fix(crypto): Set the correct algorithm when exporting a room key 2022-09-01 17:08:24 +02:00
Damir Jelić 1b06d8ca51 refactor(crypto): Start using the customized room key request event type 2022-09-01 17:08:24 +02:00
Damir Jelić 4338d5e534 refactor(crypto): Add a customized room key request event type 2022-09-01 17:08:24 +02:00
Jonas Platte 4c98dfb42a feat(bindings): Enable socks proxy support in matrix-sdk-ffi 2022-09-01 15:07:15 +02:00
Jonas Platte dacaef3ddd fix(bindings): Reduce scope of RwLock read lock
Fixes a clippy lint.
2022-09-01 13:40:47 +02:00
Jonas Platte e4267cc4fd refactor(sdk)! Make upload take &[u8] instead of impl Read
The use of `io::Read` wasn't helping since we had to buffer the whole
file in memory anyways, and we are unlikely to get around that in the
near future.
2022-09-01 13:40:47 +02:00
Jonas Platte 16ac69a967 chore: Simplify integration testing macro 2022-09-01 13:11:05 +02:00
Ivan Enderlin 193da88320 feat(crypto): Rename verified and deleted to is_*
feat(crypto): Rename `verified` and `deleted` to `is_*`
2022-09-01 10:50:05 +02:00
Ivan Enderlin 0d6a19e388 chore: verified has been renamed is_verified. 2022-09-01 10:35:51 +02:00
Flix f49e9be905 feat: Expose client of rooms for extensions 2022-09-01 10:01:18 +02:00
Jonas Platte a954518d73 ci: Stop ignoring .lock files in typos config explicitly
Typos now ignores .lock files automatically without any configuration.
2022-09-01 09:33:40 +02:00
Damir Jelić 16d9ed230a chore(examples): Use automatic links for some URLs 2022-08-31 18:43:47 +02:00
Ivan Enderlin 82b647a888 doc(crypto): Fix typos in the documentation
doc(crypto): Fix typos in the documentation
2022-08-31 17:26:56 +02:00
Ivan Enderlin 2e74983c79 chore: Fix other is_verified. 2022-08-31 17:16:05 +02:00
Ivan Enderlin ffebc7c313 doc(crypto): Fix typos in the documentation 2022-08-31 17:09:33 +02:00
Ivan Enderlin 7d1b60a3b1 doc(crypto): Fix a link. 2022-08-31 16:52:00 +02:00
Ivan Enderlin 53c5158eca doc(crypto): Update link to `is_verified. 2022-08-31 16:45:52 +02:00
Ivan Enderlin 3eab9ca8e5 feat(crypto): Rename verified and deleted to is_*. 2022-08-31 16:44:59 +02:00
Doug 36b41ac1c6 chore(bindings): Replace failing test. 2022-08-31 16:22:59 +02:00
Doug 8a8cc5f230 chore(bindings): Use Swift package for tests. 2022-08-31 16:22:59 +02:00
Jonas Platte 96384d9447 feat(bindings): Add account data interaction to sdk-ffi
Co-authored-by: Doug <douglase@element.io>
2022-08-31 14:40:23 +02:00
Stefan Ceriu bb04a1e041 chore(bindings): Fix Xcode project after sdk-ffi namespace change 2022-08-31 10:51:04 +00:00
Jonas Platte d416e64a7e refactor(sdk): Return only content from Account::account_data[_raw]
Since global account data events only consist of the type that is known
to the user anyways, and the content.
2022-08-31 12:19:35 +02:00
Jonas Platte aedf807025 doc(sdk): Add an example for set_account_data 2022-08-31 12:19:35 +02:00
Jonas Platte 77afa26217 feat(sdk): Add account_data[_raw] accessors to Account 2022-08-31 12:19:35 +02:00
Jonas Platte f1a03ececd feat(sdk): Add public set_account_data[_raw] to Account 2022-08-31 12:19:35 +02:00
Jonas Platte f8502720c3 fix(bindings): Pass library file to uniffi-bindgen
… so that functions bridged via #[uniffi::export] are included in the
generated Swift API.
2022-08-31 11:52:37 +02:00
Jonas Platte 84f9414aa4 refactor(bindings): Simplify debug build script 2022-08-31 11:52:37 +02:00
Jonas Platte 9cfddc4c65 refactor(bindings): Update namespace name for matrix-sdk-ffi 2022-08-31 11:52:37 +02:00
Damir Jelić 01f8ed10aa feat(examples): Add an example that lets you create rooms 2022-08-31 11:51:50 +02:00
Damir Jelić 6bb9a7a7d7 docs(crypto): Improve some docs about the forwarded curve chains
Co-authored-by: Denis Kasak <dkasak@termina.org.uk>
2022-08-30 17:14:29 +02:00
Damir Jelić 75fb3b81a7 fix(crypto): Fix the deserialization of exported inbound group sessions 2022-08-30 17:14:29 +02:00
Damir Jelić 504ad39c27 fix(crypto): Fix the deserialization of inbound group group_sessions
Inbound group sessions would fail to be deserialized if there was a
forwarding curve chain, this patch fixes it so we go through base64 when
we deserialize this field.
2022-08-30 17:14:29 +02:00
Benjamin Kampmann d20db7c7c1 Merge pull request #981 from Hywan/fix-crypto-js-npm-publish
chore(crypto-js): Add `npm run pack`
2022-08-30 08:50:39 +02:00
Ivan Enderlin 1bfcc52a1f chore(crypto-js): Add npm run pack.
This patch introduces a new `pack` NPM script, which runs `wasm-pack
pack` behind the scene.

This patch modifies the `publish` NPM script to run the `pack` script
as a pre-script (so… in the `prepublish` script).

Finally, this patch no longer uses `$npm_execpath` as it doesn't work
on Windows. It should be `%npm_execpath%`. It's not obvious to make
scripts interoperable, so we will stick with `npm` for now.
2022-08-29 14:22:39 +02:00
Damir Jelić a8362e389e Document the receive_supported_keys method in the gossiping module 2022-08-29 10:21:04 +02:00
Damir Jelić fe35e7c9fa ci: Test the experimental-algorithms feature of the crypto crate 2022-08-29 10:21:04 +02:00
Damir Jelić 5768188da8 Fix some clippy warnings 2022-08-29 10:21:04 +02:00
Damir Jelić 1e451a92e0 Add some missing docs to the Olm Session 2022-08-29 10:21:04 +02:00
Damir Jelić 12c1b80bc9 Remove a dead code allowed attribute 2022-08-29 10:21:04 +02:00
Damir Jelić 7fda431d5f Remove the usage of the Ruma EventEncryptionAlgorithm 2022-08-29 10:21:04 +02:00
Damir Jelić 337fbb591d Put the new megolm algorithm behind the experimental feature flag 2022-08-29 10:21:04 +02:00
Damir Jelić 8cca01369a Put the new olm algorithm behind a feature flag 2022-08-29 10:21:04 +02:00
Damir Jelić 8cdc609876 Move the EventEncryptionAlgorithm into a more logical place 2022-08-29 10:21:04 +02:00
Damir Jelić 0673ad315f Add support for megolm.v2 forwarded keys 2022-08-29 10:21:04 +02:00
Damir Jelić 3aaf70cb5a Support the new algorithms in the gossiping tests 2022-08-29 10:21:04 +02:00
Damir Jelić b00e963a21 Add support for the new algorithms in the bindings 2022-08-29 10:21:04 +02:00
Damir Jelić 7d98d87c5a Enable the new olm/megolm algorithms 2022-08-29 10:21:04 +02:00
Damir Jelić fb840f73a3 Add support for the m.megolm.v2.aes-sha2 room key content 2022-08-29 10:21:04 +02:00
Damir Jelić e935f59039 Add support for the m.megolm.v2.aes-sha2 algorithm 2022-08-29 10:21:04 +02:00
Damir Jelić 3df6797419 Add support for the m.olm.v1.curve25519-aes-sha2 algorithm 2022-08-29 10:21:04 +02:00
Damir Jelić eaf1f27831 refactor(crypto): Use our own enum for the encryption algorithms 2022-08-29 10:21:04 +02:00
Damir Jelić 748eff40f0 docs(crypto): Improve some docs around event trust states
Co-authored-by: Denis Kasak <dkasak@termina.org.uk>
2022-08-29 09:50:38 +02:00
Damir Jelić 0084117de9 docs(crypto): Fix some spelling and improve a couple of docs
Co-authored-by: Ivan Enderlin <ivan@mnt.io>
2022-08-29 09:50:38 +02:00
Damir Jelić a4af5bf4e1 fix(crypto): Improve the code checking if a decrypted event is trusted
This now takes into account if the room key was imported, i.e. received
as a forward. We also do the check of the Ed25519 key now.
2022-08-29 09:50:38 +02:00
Damir Jelić 27d4228269 fix(crypto): Check the Ed25519 key when we receive an Olm encrypted event 2022-08-29 09:50:38 +02:00
Kévin Commaille dc39c8d96b fix(examples): Fix examples that accept invites
Spawn a task for accepting the invite otherwise the call never returns and sync stops.
2022-08-26 18:15:56 +02:00
Jonas Platte d427632230 chore: Add more backticks in comments 2022-08-25 18:09:13 +02:00
Jonas Platte 6ddc8ba36f refactor!: Rename [Sync]RoomEvent to [Sync]TimelineEvent 2022-08-25 18:09:13 +02:00
Jonas Platte 4be2f3aa04 chore: Upgrade ruma 2022-08-25 18:09:13 +02:00
Jonas Platte f6c404cb32 feat(sdk): Allow event enums to be used as the first event handler argument 2022-08-25 17:19:44 +02:00
Jonas Platte 20a6a16152 refactor(sdk): Split EventHandlerMap into separate maps
One for room-specific event handlers, one for non-room-specific ones.
2022-08-25 17:19:44 +02:00
Jonas Platte 5a1853b0d5 refactor(sdk): Split event_handler module into more files 2022-08-25 17:19:44 +02:00
Jonas Platte 9183f5d4ef refactor(sdk): Move event handler fields from Client into a new struct 2022-08-25 17:19:44 +02:00
Ivan Enderlin 973833c643 feat(crypto-js): Add store configuration to the OlmMachine constructor
feat(crypto-js): Add store configuration to the `OlmMachine` constructor
2022-08-25 11:37:45 +02:00
Ivan Enderlin ce4f7e2254 Merge branch 'main' into feat-crypto-js-store 2022-08-25 11:22:22 +02:00
Jonas Platte 0018749e15 feat(sdk): Allow Raw<_> to be used as the first event handler argument 2022-08-24 18:35:09 +02:00
Ivan Enderlin 9c414bbe9f feat(crypto-js): Implement OlmMachine.sign and .cross_signing_status
feat(crypto-js): Implement `OlmMachine.sign` and `.cross_signing_status`
2022-08-24 09:48:03 +02:00
Jonas Platte 0b8462423a chore: Reduce indirect dependencies of examples 2022-08-23 18:30:44 +02:00
Jonas Platte 2313c099fa chore(bindings): Replace parking_lot RwLock by std RwLock 2022-08-23 18:30:44 +02:00
Ivan Enderlin 85795a92b6 chore(crypto-js): Make Clippy happy. 2022-08-23 17:38:32 +02:00
Ivan Enderlin ef8207fbaa chore(crypto-js): Make Clippy happy. 2022-08-23 17:06:07 +02:00
Jonas Platte f83292fc75 refactor: Start using UniFFI proc-macro frontend 2022-08-23 16:47:08 +02:00
Jonas Platte 5faed2e635 Upgrade UniFFI 2022-08-23 16:47:08 +02:00
Ivan Enderlin 9722a4c415 chore(crypto-js): Use IndexeddbCryptoStore only for wasm32. 2022-08-23 16:46:09 +02:00
Ivan Enderlin 432449b009 chore(crypto-js): Make cargo fmt happy. 2022-08-23 15:08:51 +02:00
Ivan Enderlin 04634d5f39 chore(crypto-js): Fix a typo in an error message. 2022-08-23 15:04:50 +02:00
Ivan Enderlin ef56f76978 doc(crypto-js): Fix a typo. 2022-08-23 15:03:26 +02:00
Ivan Enderlin 527c727e4a test(crypto-js): Improve test cases. 2022-08-23 15:00:39 +02:00
Ivan Enderlin d947448c64 test(crypto-js): Add more test case when store is not configured correctly. 2022-08-23 15:00:39 +02:00
Ivan Enderlin d497883669 doc(crypto-js): Add more docmuentation and more error messages. 2022-08-23 15:00:39 +02:00
Ivan Enderlin 7f07ac52ef feat(crypto-js): Add store configuration to the OlmMachine constructor.
The `OlmMachine` constructor now has 2 more optional arguments:
`store_name` and `store_passphrase`, to use Indexed DB as the backend
to store the Olm machine keys, rather than having an in-memory Olm
machine.

Node.js is used to test our binding. Indexed DB is absent of
Node.js. So, firstly, we are using the `fake-indexeddb` JavaScript
library to mimic the same API inside Node.js. And, secondly, we use
our own fork of the `indexed_db_futures` Rust crate to provide add
support for Node.js too ([PR is
here](https://github.com/Alorel/rust-indexed-db/pull/11)). It
basically looks in the Node.js global environment if the `indexedDB`
getter is present, just like it is already done for `Window` on any
browser, or `WorkerGlobalScope` for workers.
2022-08-23 15:00:33 +02:00
Jonas Platte 9462061a5a chore: Upgrade ruma 2022-08-23 14:28:21 +02:00
Ivan Enderlin d508237078 chore(crypto-js): Add a release workflow for crypto-js
chore(crypto-js): Add a release workflow for `crypto-js`
2022-08-23 10:49:29 +02:00
Ivan Enderlin 331f8b381f doc(crypto-js): Update documentation for the release workflow. 2022-08-22 15:10:01 +02:00
Ivan Enderlin 2481618608 chore(crypto-js): Create the Github release with the NPM package attached.
This patch updates the `publish` NPM script to explicitly run
`wasm-pack pack` to create the NPM package in the `pkg/`
directory. This patch also updates the Github Action workflow for the
`matrix-sdk-crypto-js` release, to create a new Github Release, with
the NPM package attached as an asset file.
2022-08-22 14:37:09 +02:00
Jonas Platte dd78a8cecd refactor(sdk)!: Make room type constructors private
… and avoid unnecessary clones before calling them.
2022-08-22 13:16:05 +02:00
Ivan Enderlin 39077b185b chore(crypto-js): Add a release workflow for crypto-js.
This patch adds a new `npm run publish` script that:

1. Run `npm run prepublish` (which runs the `build` and `test` scripts),
2. Run `wasm-pack publish`.

Note 1: The `prepublish` script is using the `$npm_execpath`
environment variable instead of just “`npm`”, so that if someone is
using `yarn` or another JavaScript package manager, it _should_ work
(not tested yet).

Note 2: `wasm-pack publish` is run without running `wasm-pack login`
before that. _But_ we are updating the registry URL in the NPM
configuration file in the Github Action workflow, see below.

This patch then creates a new Github Action workflow that is triggered
when a new tag of the form `matrix-sdk-crypto-js-v[0_9]+.*` is
pushed. This workflow runs `npm run publish` basically, but before
that, it updates the NPM configuration file by setting a value for
`//registry.npmjs.org/:_authToken`. Thus, running `wasm-pack login` is
not necessary.
2022-08-22 12:14:44 +02:00
Benjamin Kampmann 68107e6285 Merge pull request #963 from gnunicorn/ben-update-ruma
chore: Update ruma
2022-08-18 16:13:15 +02:00
Benjamin Kampmann 549c829000 chore: Update ruma 2022-08-18 15:52:08 +02:00
Jonas Platte 3581d83389 chore: Upgrade Ruma 2022-08-17 10:15:05 +02:00
Jonas Platte 260b604615 refactor(sdk)!: Split strongly-typed state event functions into two
One for empty state keys under the existing name, one for non-empty
state keys with a `_for_key` suffix.
2022-08-17 10:15:05 +02:00
Ivan Enderlin a1dca23c3c Merge pull request #958 from Hywan/feat-crypto-js-attachment 2022-08-17 10:12:04 +02:00
Benjamin Kampmann 9fd5a8b3b1 Merge pull request #960 from matrix-org/poljar/delete-device-log-improvement
Improve the log line when we think our device has been deleted
2022-08-17 09:46:26 +02:00
Damir Jelić 180822dd18 chore(crypto): Improve the message when we think that we have been deleted 2022-08-16 18:32:14 +02:00
Damir Jelić 20477ab7da chore(crypto): Log our identity keys when we think our device has been deleted 2022-08-16 18:31:30 +02:00
Damir Jelić 06f39696d3 chore(crypto): Improve some logs in the Olm message handling code 2022-08-16 16:18:50 +02:00
Damir Jelić 6f5443f8a0 chore(crypto): Log some info when we try to create an Olm session from a pre-key message 2022-08-16 16:18:50 +02:00
Ivan Enderlin 45a66f3321 doc(crypto-nodejs): Fix a typo. 2022-08-16 16:06:04 +02:00
Ivan Enderlin 7f35691236 feat(crypto-js): Implemented the Attachment API.
Implement the `Attachment.encrypt` and `Attachment.decrypt` methods,
along with its `EncryptedAttachment` companion.

The trick is to avoid copies as much as possible. Instead of dealing
with `Uint8Array` as I've initially done, `&[u8]` and `Vec<u8>` is
passed instead. `wasm-bindgen` is smart enough to do as few copies as
possible (from JavaScript to Wasm's memory is required, and we don't
want to do more), while typing everything as `Uint8Array`.

`EncryptedAttachment.encryptedData` returns a copy of the data
everytime it is called, and that's the last copy I'm not happy with.
2022-08-16 15:56:36 +02:00
Benjamin Kampmann e8d51a4cba Merge pull request #956 from gnunicorn/ben-fix-encode-key
fix(sled): Remove unused `from` on EncodeUnchecked
2022-08-16 15:51:36 +02:00
Benjamin Kampmann 7feffec9c0 fix(sled): feature-gate EncodeUnchecked::from 2022-08-16 15:18:46 +02:00
Ivan Enderlin 8e74834342 doc(crypto-js): Add missing module documentation. 2022-08-16 12:31:19 +02:00
Ivan Enderlin 070637b0ef chore(crypto-js): Fix style. 2022-08-16 12:21:02 +02:00
Ivan Enderlin 2dffe03c8d feat(crypto-js): Implement OlmMachine.sign. 2022-08-16 12:16:01 +02:00
Ivan Enderlin 3f0509e7b1 fix(crypto-js): Add missing Debug impl. 2022-08-16 12:16:01 +02:00
Ivan Enderlin 2275643ea0 chore(crypto-js): Move Vodozemac types into their own Rust module. 2022-08-16 12:16:01 +02:00
Ivan Enderlin 0fa6ff6955 feat(crypto-js): Add DeviceKeyId, DeviceKeyAlgorith and DeviceKeyAlgorithmName. 2022-08-16 12:16:01 +02:00
Ivan Enderlin 997a6ed0ad feat(crypto-js): Implement OlmMachine.cross_signing_status. 2022-08-16 12:16:01 +02:00
Ivan Enderlin fd220f197b doc: Add link to online documentation for crypto-js and crypto-nodejs
doc: Add link to online documentation for crypto-js and crypto-nodejs
2022-08-16 10:21:39 +02:00
Ivan Enderlin 655e62814b doc(crypto-nodejs) Add link to online documentation. 2022-08-16 10:06:22 +02:00
Ivan Enderlin c2468b2f2e doc(crypto-js) Add link to online documentation. 2022-08-16 10:04:54 +02:00
Benjamin Kampmann e0ae4f60e3 docs(examples): update instructions for wasm_command_bot example
Merge pull request #952 from chrisguida/chrisguida/wasm-bot-readme -
2022-08-16 09:48:33 +02:00
Chris Guida 2beb13cc3e update instructions for wasm_command_bot example 2022-08-15 17:56:54 -05:00
Damir Jelić 78dcff9259 chore(crypto): Fix an indentation issue
Co-authored-by: Jonas Platte <jplatte@matrix.org>
2022-08-15 11:39:43 +02:00
Damir Jelić 0bd58a7741 refactor(crypto): Simplify the Curve25519 check when fetching a device
Co-authored-by: Jonas Platte <jplatte@matrix.org>
2022-08-15 11:39:43 +02:00
Damir Jelić 405c3938b7 refactor(crypto): Use the Curve25519 key type in more places 2022-08-15 11:39:43 +02:00
Damir Jelić bd5ea8b0f7 fix(crypto): Fix some error messages 2022-08-15 11:39:43 +02:00
Jonas Platte 24c042e974 refactor(base): Deserialize events at the expected type
… rather than deserializing at an enum type and taking the same branch
for getting a different enum variant¹ as failed deserialization.

¹ which should be impossible anyways
2022-08-15 11:05:22 +02:00
Jonas Platte d236cde0c7 refactor(base): Use StateStoreExt in a few places 2022-08-15 11:05:22 +02:00
Jonas Platte d2f39bc18f feat(base): Add StateStoreExt for statically-typed event retrieval 2022-08-15 11:05:22 +02:00
Jonas Platte 96165f5602 chore(bindings): Use ? operator instead of and_then chaining 2022-08-15 11:05:22 +02:00
Damir Jelić 4a13b8d207 ci: Ignore thead when checking for spelling 2022-08-14 10:20:28 +02:00
Damir Jelić c9c09adb38 chore: Fix some newly detected typos 2022-08-14 10:20:28 +02:00
Jonas Platte aedbbcdde7 fix(sdk)!: Remove SyncEvent implementation for InitialStateEvent
Initial state events aren't actually received through sync, they're sent from
the client to the server when creating a room.

This change makes it impossible to register event handlers for initial state
events. Previously, this was allowed, but the event handler was never called.
2022-08-13 20:21:28 +02:00
Jonas Platte 97f37acb4a chore: Reduce indirect dependencies of sled-state-inspector 2022-08-13 13:08:11 +02:00
Damir Jelić 0b5bfeadea chore(crypto): Add a missing semicolon
Co-authored-by: Jonas Platte <jplatte@matrix.org>
2022-08-13 09:58:57 +02:00
Damir Jelić 6d60acfff4 chore(common): Fix a clippy warning 2022-08-13 09:58:57 +02:00
Damir Jelić 3d56af442d refactor(crypto): Utilize the decrypted Olm event type more
This patch adds some more stronger guarantees that received room key
events and other similarly security critical event types are only
handled if they have been received over a secure Olm channel.
2022-08-13 09:58:57 +02:00
Damir Jelić ae18b01c25 refactor(crypto): Use the SigningKeys collection for inbound group sessions 2022-08-11 16:43:42 +02:00
Damir Jelić 4692a12cd7 refactor(crypto): Create a custom collection type for signed keys 2022-08-11 16:43:42 +02:00
Jonas Platte 344309c1bf chore: Track Cargo.lock to make binding staticlibs reproducible 2022-08-11 13:32:32 +02:00
Jonas Platte 87094a9111 chore: Document dependency upgrade issues 2022-08-11 13:16:10 +02:00
Jonas Platte adf3f9d434 chore(appservice): Upgrade serde_yaml 2022-08-11 13:15:57 +02:00
Jonas Platte 158bd24b40 chore: Bump pprof dependency 2022-08-11 13:09:09 +02:00
Jonas Platte 8e368d86b7 chore: Use the latest git version of UniFFI 2022-08-11 12:56:17 +02:00
Jonas Platte 0fe714df86 chore: Upgrade sled-state-inspector dependencies 2022-08-11 11:59:50 +02:00
Jonas Platte 936f0371de chore: Use once_cell instead of lazy_static in integration test crate 2022-08-11 10:45:04 +02:00
Jonas Platte ecc800a319 chore: Sort dependencies of integration test crate 2022-08-11 10:32:12 +02:00
docweirdo febfcf9796 feat(sdk): Make room actions return typed room objects
… by waiting for the corresponding event confirming the action. Affects:

* Creating a room
* (Re-)Joining a room
* Leaving a room
* Accepting an invitation
* Rejecting an invitation
2022-08-10 17:32:38 +02:00
Damir Jelić 3f0a68082a feat(crypto): Add a setting to only send room keys to trusted devices 2022-08-10 13:31:15 +02:00
Damir Jelić 18861bb595 refactor(crypto): Add a dedicated error for inbound group session exporting 2022-08-10 13:28:54 +02:00
Damir Jelić 329d461a2f feat(crypto): Add customized event type for the forwarded room key 2022-08-10 13:28:54 +02:00
Jonas Platte 4914c595e9 fix(sdk): Further relax event / notification handler bounds on WASM
This allows capturing non-`Send` / -`Sync` values in handler closures.
2022-08-10 12:54:36 +02:00
Jonas Platte ad80839ffd fix(sdk): Make event handler futures non-Send on wasm 2022-08-09 14:25:57 +02:00
Jonas Platte 0701561e45 feat(common): Add SendOutsideWasm, SyncOutsideWasm 2022-08-09 14:25:57 +02:00
Jonas Platte 25030780b0 test(sdk): Run event handler tests on wasm 2022-08-09 14:25:57 +02:00
Jonas Platte 327a404d60 test(sdk): Move test client creation into separate module 2022-08-09 14:25:57 +02:00
Damir Jelić 06e096f6cc fix(examples): Fix the in-room emoji verification example 2022-08-09 14:04:11 +02:00
Damir Jelić a025163dae test(crypto): Test that we correctly preserve relations in an encryption cycle 2022-08-09 14:04:11 +02:00
Damir Jelić 19fcff56de chore(crypto): Make the relation copying code when decrypting a bit simpler 2022-08-09 14:04:11 +02:00
Damir Jelić edf81fb325 fix(crypto): Correctly copy over the relation when encrypting 2022-08-09 14:04:11 +02:00
Damir Jelić 08338acac2 fix(crypto): Fix the deserialization of relations 2022-08-09 14:04:11 +02:00
Kévin Commaille 52e70f1955 refactor(sdk): Don't require the whole session for sending
Allow to send requests when only the access token is available.

Remove the unreachable UserIdRequired error.
2022-08-09 12:26:33 +02:00
Jonas Platte e788ec6b07 ci: Only test one node.js version on macOS 2022-08-08 18:06:54 +02:00
Jonas Platte d3d108deb8 chore: Add missing copyright headers 2022-08-08 16:28:48 +02:00
Jonas Platte bd65d9b7a6 doc(sdk): Remove usage of deprecated function in doctest 2022-08-05 16:16:41 +02:00
Jonas Platte 230bb67763 refactor(sdk): Remove Clone requirement on event handlers 2022-08-05 16:16:41 +02:00
Jonas Platte 10a37f6d51 chore(sdk): Add EventHandlerDropGuard
It isn't used for now, but will be soon.
2022-08-05 16:16:41 +02:00
Jonas Platte 5156fb7dd4 refactor(sdk): Move add_event_handler_impl to event_handler module 2022-08-05 16:16:41 +02:00
Jonas Platte 3b03ad804f refactor(sdk)!: Swap the async lock around event handlers for a sync one 2022-08-05 16:16:41 +02:00
Damir Jelić 603176f521 chore(crypto): Bump vodozemac
Vodozemac got some new knobs to twiddle with. This patch updates
vodozemac and sets the knobs to use the olm/megolm v1 supported
encryption schemes.
2022-08-05 14:06:42 +02:00
Jonas Platte dfec17e6af chore: Disable testing of crates without tests
This reduces the amount of "running 0 tests" spam when testing the whole
workspace and makes testing a little faster overall.
2022-08-05 11:10:31 +02:00
Kévin Commaille 7623f93bb3 fix(sdk)!: Make set_homeserver private
A user shouldn't need to change the homeserver after creating the client.
2022-08-05 09:55:55 +02:00
Jonas Platte a60620306c ci: Update tarpaulin.toml 2022-08-04 23:43:49 +02:00
Jonas Platte 1fea48359d ci: Checkout head ref instead of merge commit for coverage
… this *should* fix bogus coverage change reporting.
2022-08-04 23:43:49 +02:00
Jonas Platte 054dfa98a0 ci: Upgrade checkout action 2022-08-04 23:43:49 +02:00
Damir Jelić 593d4e6062 perf(crypto): Use an RwLock for the OutboundGroupSession 2022-08-04 17:36:03 +02:00
Jonas Platte 5a94ba7b80 refactor(sled)!: Align open_with_database with its documentation
It now takes a passphrase instead of a store cipher as the second argument.
2022-08-04 17:04:31 +02:00
Jonas Platte e1b7f3be05 refactor(sled): Simplify test code 2022-08-04 17:04:31 +02:00
Jonas Platte 6bed51f016 refactor(indexeddb)!: Use &str for name in public API 2022-08-04 17:04:31 +02:00
Jonas Platte 4db162b8a2 chore(indexeddb): Clean up Result usage 2022-08-04 17:04:31 +02:00
Jonas Platte 0b1bdd66f9 refactor(indexeddb): Export error types 2022-08-04 17:04:31 +02:00
Jonas Platte a4f3c3a070 refactor!: Give sled / indexeddb types unique names 2022-08-04 17:04:31 +02:00
Jonas Platte df7895d2c6 chore(indexeddb): Rename cryptostore => crypto_store
… for consistency with state_store.
2022-08-04 17:04:31 +02:00
Jonas Platte 694c36d741 chore(sled): Rename cryptostore => crypto_store
… for consistency with state_store.
2022-08-04 17:04:31 +02:00
Benjamin Kampmann b5329f99f1 Merge pull request #903 from gnunicorn/ben-getting-started-example
Improving examples
2022-08-04 15:41:26 +02:00
Damir Jelić f055e939e7 refactor(crypto): Use the vodozemac method to decide if a session is better
This patch delegates the decision making if a session is better to
vodozemac. Vodozemac has better insights if a group session can be
considered to be better.
2022-08-04 15:09:09 +02:00
Benjamin Kampmann c4c7c2bb23 docs: remove unused import and fix style of custom events example 2022-08-04 15:02:39 +02:00
Benjamin Kampmann efc0556124 doc: follow naming convention and use generated types from ruma 2022-08-04 13:31:16 +02:00
Benjamin Kampmann 9d588f7e00 doc: add example for sending and reacting on custom events 2022-08-04 13:13:48 +02:00
Benjamin Kampmann 323974fe4c Merge remote-tracking branch 'origin/main' into ben-getting-started-example 2022-08-04 12:22:42 +02:00
Benjamin Kampmann 3bdb2f22ea build(crypto-js): Pin yarg-parser to 21.0.1 to prevent upgrade bug
We are effected by https://github.com/yargs/yargs-parser/issues/452
through the transient dependency of jest on yargs
2022-08-04 12:21:18 +02:00
Damir Jelić ddf8577c84 refactor(crypto): Start using our own event types when we encrypt 2022-08-04 11:16:02 +02:00
Benjamin Kampmann 90c2dcdbc0 style: fix clippy lints 2022-08-04 11:02:28 +02:00
Benjamin Kampmann fe4bc0dc75 doc: fix docs of getting started bot 2022-08-03 17:07:59 +02:00
Benjamin Kampmann 69c8cdf304 Revert "fix: limit indexeddb features to target arch to stop clippy from complaining"
This reverts commit d54612b6e2.
2022-08-03 16:40:17 +02:00
Benjamin Kampmann daf92d7745 Merge remote-tracking branch 'origin/main' into ben-getting-started-example 2022-08-03 16:39:50 +02:00
Benjamin Kampmann ccbd9e5712 chore: rename Readme.md to README.md 2022-08-03 16:39:14 +02:00
Jonas Platte 2430d7f267 chore: Remove unneeded docsrs Cargo features 2022-08-03 15:33:53 +02:00
Damir Jelić 3ca3016539 refactor(crypto): Use the curve 25519 key type for inbound group sessions 2022-08-03 15:28:24 +02:00
Jonas Platte bbbd7942b0 fix(indexeddb): Export MigrationConflictStrategy 2022-08-03 15:17:05 +02:00
Jonas Platte 1a5953e01e chore(indexeddb): Appease clippy 2022-08-03 15:17:05 +02:00
Jonas Platte 3a19d8e5bf chore(indexeddb): Reduce target_arch feature gates
This allows smoother development as a regular 'cargo check' will
validate most of the code. It also makes rust-analyzer work for the
crate without any configuration.
2022-08-03 15:17:05 +02:00
Jonas Platte 0b7d0aa780 chore(common): Make timeout tests deterministic
… as well as simpler, and faster.
2022-08-03 14:54:43 +02:00
Jonas Platte 82f4e57a2c feat(sled): Print a clear error message when attempting to build on wasm 2022-08-03 14:48:45 +02:00
Jonas Platte 9714ce9edf refactor(sdk): Check permissible feature configuration in build script
… instead of through `compile_error!` invocations. This helps avoid
unhelpful errors from the unsupported feature configuration by aborting
compilation earlier.
2022-08-03 14:48:45 +02:00
Benjamin Kampmann 9538596fbb doc: Add getting-started example autojoin & command bot with plenty of source docs 2022-08-03 13:05:25 +02:00
Benjamin Kampmann 35be128139 docs: add Readme to examples root 2022-08-03 12:06:50 +02:00
Benjamin Kampmann d54612b6e2 fix: limit indexeddb features to target arch to stop clippy from complaining 2022-08-03 12:00:54 +02:00
Benjamin Kampmann a1bf53a331 Merge remote-tracking branch 'origin/main' into ben-getting-started-example 2022-08-03 11:39:50 +02:00
Kévin Commaille 9064e7b02d feat(sdk): Add support for refresh tokens 2022-08-03 10:42:28 +02:00
Damir Jelić ae261c2091 refactor(crypto): Refactor the key sharing tests a bit 2022-08-02 16:48:05 +02:00
Damir Jelić 968792ea00 refactor(crypto): Split out the forwarded room key accepting method 2022-08-02 16:48:05 +02:00
Benjamin Kampmann 42c88e840f Merge pull request #905 from gnunicorn/ben-fix-integration-test-coverage
ci: add backend server for integration test with tarpaulin
2022-08-02 16:14:26 +02:00
Benjamin Kampmann 38a71972e5 ci: add backend server for integration test with tarpaulin 2022-08-02 15:42:45 +02:00
Benjamin Kampmann d8caaed1ce docs: only document default workspace members, not all 2022-08-02 15:24:48 +02:00
Benjamin Kampmann 67e63c0d35 ci: update xtask, add ci to build examples 2022-08-02 15:13:27 +02:00
Benjamin Kampmann 4c7ddd7512 refactor: move examples from crates/matrix-sdk into separate crates in examples/ 2022-08-02 15:06:04 +02:00
Jonas Platte 9fca639f9b feat(sdk): Add room::Common::add_event_handler 2022-08-02 13:38:30 +02:00
Benjamin Kampmann 6cb87c64b5 Merge pull request #855 from gnunicorn/gnunicorn/issue833
Integration tests against an actual synapse server
2022-08-02 12:22:48 +02:00
Benjamin Kampmann a5875ff75d ci: update codecov config to exclude all testing crates 2022-08-02 10:59:18 +02:00
Benjamin Kampmann 9bb02f2419 fix: fix path to testing crate 2022-08-02 10:58:53 +02:00
Benjamin Kampmann 65be06ebad Merge remote-tracking branch 'origin/main' into gnunicorn/issue833 2022-08-02 10:32:09 +02:00
Damir Jelić 154538c4c9 fix(crypto): Make the secret receiving logic more obvious.
This patch ensures that the received secret has been sent by one of our
verified devices. We already ensure so for the secrets we import, since
we check that the cross signing keys match the public keys of our own
user idenity.

No other secrets get imported by this method but it could quite easily
become an issue if we start accepting more secret types.
2022-08-02 09:35:38 +02:00
Damir Jelić f23c16cf88 refactor(crypto): Split out the methods to receive a secret 2022-08-02 09:35:38 +02:00
Jonas Platte 165973121c fix(sdk): Make remove_event_handler work with room-specific handlers
As part of that, store only the ID, not the whole key in
EventHandlerWrapper, because the key is getting bigger with room_id.
2022-08-01 23:57:00 +02:00
Jonas Platte 31903d3cbc chore(sdk): Simplify remove_event_handler test 2022-08-01 23:55:44 +02:00
Jonas Platte 108f299e92 refactor(sdk): Inline handle_sync_events_wrapped_with into all callers
It was too generic to be readable.
2022-08-01 23:55:44 +02:00
Jonas Platte eb78815be5 refactor(sdk): Create non-generic fn call_event_handlers
Extracted out of handle_sync_events_wrapped_with.
2022-08-01 23:55:44 +02:00
Jonas Platte 0716f6afaa feat(sdk): Add Client::add_room_event_handler 2022-08-01 23:55:44 +02:00
Jonas Platte 78169d516e refactor(sdk): Avoid unnecessary double map lookup 2022-08-01 23:55:44 +02:00
Jonas Platte 061fe104a9 chore(sdk): Move EventHandler{Fut,Fn} into event_handler module 2022-08-01 23:55:43 +02:00
Benjamin Kampmann f91bdb28ba Merge pull request #897 from gnunicorn/ben-fix-documentation-generation
Fix documentation generation
2022-08-01 22:37:21 +02:00
Benjamin Kampmann 14429af511 Update .github/workflows/documentation.yml
Co-authored-by: Jonas Platte <jplatte+git@posteo.de>
2022-08-01 22:19:46 +02:00
Benjamin Kampmann 1e6e00b0c0 ci(integration-testing): split integration test off from regular tests 2022-08-01 18:54:33 +02:00
docweirdo 744bd8d0d2 feat(common): Add a generically usable timeout function 2022-08-01 18:23:30 +02:00
Benjamin Kampmann 06ad079099 Merge pull request #895 from matrix-org/ben-add-editoconfig
build: Adding .editorconfig
2022-08-01 15:23:58 +02:00
Benjamin Kampmann 7dfadd1848 ci(integration-testing): split integration test off from regular tests 2022-08-01 15:20:13 +02:00
Benjamin Kampmann 5089c1a7e9 ci(docs): force npm generated bindings if existing 2022-08-01 14:56:26 +02:00
Benjamin Kampmann c15a4bcdd4 build: Adding .editorconfig 2022-08-01 14:33:05 +02:00
Benjamin Kampmann 729836cf70 Merge pull request #894 from gnunicorn/ben-add-js-docs
ci(js) add npm docs of bindings to pages
2022-08-01 13:35:17 +02:00
Benjamin Kampmann 2d21c30639 Merge remote-tracking branch 'origin/main' into gnunicorn/issue833 2022-08-01 13:28:28 +02:00
Benjamin Kampmann 3842426788 ci: Remove unneeded github action params 2022-08-01 13:27:00 +02:00
Benjamin Kampmann c27016b2e7 testing: fix review grumbles 2022-08-01 13:01:50 +02:00
Benjamin Kampmann d0f58d0879 ci(js) add npm docs of bindings to pages 2022-08-01 12:17:36 +02:00
Kévin Commaille 4cdc91844e chore(ci): Fix new clippy warnings 2022-07-30 12:58:18 +02:00
Jonas Platte fe5d8fb40e refactor: Deprecate ClientBuilder::{crypto_store, state_store} 2022-07-29 17:22:12 +02:00
Jonas Platte ffb4c6d6ef docs: Use new ClientBuilder methods in examples 2022-07-29 17:22:12 +02:00
Jonas Platte 93c4c5d128 feat(sdk): Add ClientBuilder::indexeddb_store 2022-07-29 17:22:12 +02:00
Jonas Platte ec3a6e4b15 feat(sdk): Add ClientBuilder::sled_store 2022-07-29 17:22:12 +02:00
Jonas Platte ecbcf734b9 docs(sled): Clean up make_store_config description 2022-07-29 17:22:12 +02:00
Jonas Platte 75f08aed69 docs(sdk): Fix outdated description of ClientBuilder::store_config 2022-07-29 17:22:12 +02:00
Jonas Platte 255955555d refactor(sdk): Add back register_event_handler[_context] as deprecated methods
… using their original signatures so upgrading matrix-sdk is easier.
2022-07-29 14:39:28 +02:00
Jonas Platte 27b858308c refactor(sdk)!: Rename {register => add}_event_handler[_context]
It's shorter and better fits with the new remove_event_handler method.
2022-07-29 14:39:28 +02:00
Jonas Platte a21ac5d6e4 Disable debug-info for the dev profile 2022-07-29 11:28:47 +02:00
Damir Jelić 4db041ce9a docs(crypto): Improve the wording on the recipient collection method
Co-authored-by: Jonas Platte <jplatte@matrix.org>
2022-07-29 10:20:36 +02:00
Damir Jelić c194e08942 fix(crypto): Rotate the outbound group session if the algorithm changes 2022-07-29 10:20:36 +02:00
Damir Jelić 713e96d3a8 fix(crypto): Store intermediate changes to the outbound group session
This fixes a bug where we would lose already generated to-device
requests carrying an m.room_key when the client gets restarted.

This only happens if the request was generated after the initial
share of the room key. Such requests get generated if a new device
or member join the group.
2022-07-29 10:01:58 +02:00
Jonas Platte b36f79a1bb doc: Make rustfmt format code blocks in documentation 2022-07-28 20:06:12 +02:00
Jonas Platte 504464c1e8 chore: Remove edition from .rustfmt.toml
It will be picked up from Cargo.toml.
2022-07-28 20:06:12 +02:00
Doug b884c5baae chore(bindings/ffi): Print each step when building XCFramework. 2022-07-28 13:37:02 +02:00
Doug c15fb5e5b7 fix(sdk): Reduce retry length on homeserver discovery 2022-07-28 13:37:02 +02:00
Damir Jelić 0555216f37 chore(crypto): Introduce a helper function to convert events in tests 2022-07-28 12:48:12 +02:00
Damir Jelić 03a4814a1a refactor(crypto): Use our own type for megolm 2022-07-28 12:48:12 +02:00
Damir Jelić 80c7f057cc refactor(crypto): Use our own struct for encrypted to-device events 2022-07-28 12:48:12 +02:00
Damir Jelić 7e70997e1c feat(crypto): Add customized m.room.encrypted events 2022-07-28 12:48:12 +02:00
Damir Jelić 2bb7914611 refactor(crypto): Make the event type an associated constant 2022-07-28 12:48:12 +02:00
Benjamin Kampmann c8c793da98 Merge pull request #768 from gnunicorn/gnunicorn/issue756
Bump db version, "upgrade" path to new db in sled and indexeddb
2022-07-28 09:51:27 +02:00
Damir Jelić e501979d92 feat(bindings/ffi): Allow setting the timeline limit for the sync setup 2022-07-27 19:23:10 +02:00
Doug 57c1e68893 Rename limit to timeline_limit.
Use a u16 instead.
2022-07-27 18:03:04 +01:00
Doug a875c4b373 Expose room membership in the FFI. 2022-07-27 17:23:09 +01:00
Doug f6e215dac3 Add limit parameter to start_sync. 2022-07-27 17:22:17 +01:00
Jonas Platte 4415ed9b58 refactor: Improve tracing events
* Use fields more
* Adjust some wording
2022-07-27 17:47:01 +02:00
Benjamin Kampmann 59fc81b957 ci(xtask): bump wasm timeout to make the ci pass 2022-07-27 16:58:20 +02:00
Benjamin Kampmann 770ac193a7 fix(indexeddb): import errors 2022-07-27 15:08:51 +02:00
Benjamin Kampmann fe40b3753a Merge pull request #870 from Hywan/feat-crypto-js-npm-publish
chore: Update or add `git-cliff` config' & prepare `crypto-js` for publishing
2022-07-27 14:28:40 +02:00
Benjamin Kampmann e871114436 docs(crypto-ffi): fixing path 2022-07-27 13:43:39 +02:00
Benjamin Kampmann fb4dd4d875 test(crypto-js): fixing path 2022-07-27 13:32:26 +02:00
Benjamin Kampmann 5806b3fbe9 ci(crypto-js): use a specific node version to run tests 2022-07-27 13:23:44 +02:00
Benjamin Kampmann e1be222558 style: fixing fmt 2022-07-27 13:09:08 +02:00
Benjamin Kampmann 37f0926832 chore: prefer to user Store::builder 2022-07-27 12:59:53 +02:00
Benjamin Kampmann 936731065b fix(indexeddb): specify futures import 2022-07-27 12:53:54 +02:00
Benjamin Kampmann 088699b6a4 docs(xtask): remove comment 2022-07-27 12:20:46 +02:00
Benjamin Kampmann b2da8b7dd7 fix(examples): update to renaming 2022-07-27 12:12:17 +02:00
Benjamin Kampmann b80d3c2f2d Merge remote-tracking branch 'origin/main' into gnunicorn/issue756 2022-07-27 12:04:56 +02:00
Benjamin Kampmann eb1dfd9690 docs(indexeddb): document builder functions 2022-07-27 11:52:13 +02:00
Benjamin Kampmann 54c181a9ad chore: cleaning up builder usage in sled and indexeddb 2022-07-27 11:51:56 +02:00
Benjamin Kampmann 003c946581 chore(sled): ascending order for dependencies 2022-07-27 10:59:02 +02:00
docweirdo 82731a5e89 feat(sdk): Add support for removing event handlers 2022-07-27 05:09:22 +00:00
Damir Jelić 4175e6badf feat(bindings/ffi): Allow clients to be restored using only an access token
This functionality is important to allow clients to log in using an OIDC server. The OIDC server returns only an access token, the client needs to fetch the user ID and device ID from the Matrix server separately.

This lives in the bindings for now since OIDC support in Matrix is being actively developed.
2022-07-26 17:10:50 +02:00
Benjamin Kampmann 008c0f4659 Merge pull request #860 from matrix-org/doug/client-path
Use a consistent store path when logging in through the FFI.
2022-07-26 16:33:32 +02:00
Doug a951a273e7 Rebase and rename method.
Add a device ID parameter to restore_with_access_token
2022-07-26 15:00:02 +01:00
Doug f13f590b7f Add login_access_token to the FFI auth service. 2022-07-26 15:00:02 +01:00
Doug 1eadd0ba2d Revert changes to store path. Use whoami for path. 2022-07-26 14:50:51 +01:00
Doug 3b8a2ca2d7 Add missing path method to IndexeddbStore. 2022-07-26 14:50:51 +01:00
Doug b6b1f904e0 Fix clippy warning. 2022-07-26 14:50:51 +01:00
Doug f31528c926 Allow a client to be built without a store path.
Throw an error on login if it is missing.
2022-07-26 14:50:51 +01:00
Doug 05fab8c394 Add a store_path method on the FFI client. 2022-07-26 14:48:37 +01:00
Jonas Platte e37e62c92c chore(sdk): Fix event handler test
It wasn't actually testing typing and power-levels event handlers before.
2022-07-26 11:11:10 +02:00
Jonas Platte d162dd07d5 refactor(sdk): Split SyncEvent::ID into KIND and TYPE
This should make things slightly easier to read.
2022-07-25 20:33:43 +02:00
Jonas Platte 42d3ebbe87 chore: Remove ugly commas right before closing parentheses 2022-07-25 20:30:13 +02:00
Jonas Platte 4e7bd6760a chore: Replace qualified uses of tracing macros with imports 2022-07-25 20:30:13 +02:00
Jonas Platte ab9476960b chore(sled): Fix line length overflow 2022-07-25 20:30:13 +02:00
Jonas Platte b3092bd1d9 chore(indexeddb): Remove unnecessary .to_string() call in test code 2022-07-25 20:30:13 +02:00
Jonas Platte c2ad4b7d82 fix(appservice): Respond with a non-stringified empty object
warp::reply::json() serializes its argument to JSON, passing it an
already-serialized JSON string doesn't do the right thing.
2022-07-25 20:30:13 +02:00
Jonas Platte f8e729f7f3 chore: Use implicit named arguments for formatting macros more 2022-07-25 20:30:12 +02:00
Jonas Platte 5c88bd1595 refactor(sdk): Remove ID from EventHandler
Turns out it wasn't actually needed.
2022-07-25 20:30:12 +02:00
Damir Jelić 204441f2b3 Fix a formatting issue in a doc example
Co-authored-by: Jonas Platte <jplatte@matrix.org>
2022-07-25 19:06:15 +02:00
Damir Jelić 79d13148fb chore: Remove TryFrom/TryInto imports 2022-07-25 19:06:15 +02:00
Julian Sparber c247de95b6 client: Remove redudant delay after sync error
If the last sync was less then a 1s ago we wait for a 1s, it doesn't
make sense to wait an additional second on an error. Also the stream
sync api returns the error after a delay of 1s, which doesn't make
sense.
2022-07-25 12:01:28 +02:00
Johannes Becker 6d87dd8011 refactor(appservice)!: Make USER_MEMBER const private" 2022-07-22 09:33:42 +02:00
Jonas Platte 4b6a28da0d chore(sdk): Fix line length overflow in common.rs 2022-07-21 19:24:42 +02:00
Benjamin Kampmann bf6e1b594d fix(integration-tests): requires multi-threading feature from tokio 2022-07-21 18:06:48 +02:00
Benjamin Kampmann 59332e46b5 switch to multithreaded tokio test runner 2022-07-21 17:58:50 +02:00
Benjamin Kampmann c070b96a68 Merge remote-tracking branch 'origin/main' into gnunicorn/issue833 2022-07-21 17:37:49 +02:00
Benjamin Kampmann d68d6ead69 chore: let's check the logs 2022-07-21 17:31:58 +02:00
Benjamin Kampmann f34c2f0574 ci: fix typos 2022-07-21 17:28:38 +02:00
Benjamin Kampmann aad167b792 style(indexeddb): fixing rust fmt 2022-07-21 17:25:43 +02:00
Benjamin Kampmann 814a30064f fix(sled-inspector): new builder fn 2022-07-21 17:18:43 +02:00
Ivan Enderlin 6ce5d0b507 chore(crypto-js): Add cliff.toml for git-cliff. 2022-07-21 15:50:11 +02:00
Ivan Enderlin db7824efbd chore(crypto-nodejs): Update Conventional Commits types. 2022-07-21 15:49:26 +02:00
Ivan Enderlin ee4702d04a feat(bindings/crypto-js) Update package name, and use package scope. 2022-07-21 15:47:55 +02:00
Ivan Enderlin d68b6ea64d doc: Fix formatting. 2022-07-21 15:47:00 +02:00
Ivan Enderlin 49bc950fdd doc: Add missing scope for matrix-sdk-crypto. 2022-07-21 15:46:21 +02:00
Ivan Enderlin 7001113877 doc: Propose conventional commits scopes & types
doc: Propose conventional commits scopes & types
2022-07-21 15:44:43 +02:00
Ivan Enderlin c0d3099e2e doc: Propose conventional commits types. 2022-07-21 15:43:31 +02:00
Ivan Enderlin 49e5d73d83 doc: Propose conventional commits scopes. 2022-07-21 13:59:31 +02:00
Benjamin Kampmann 2ffaaeeae2 docs(sled): fixing examples and utils 2022-07-21 13:18:15 +02:00
Benjamin Kampmann 60eef8967f fix(sled-store): apply review requests 2022-07-21 11:52:04 +02:00
Benjamin Kampmann ed893ed5b0 Merge remote-tracking branch 'origin/main' into gnunicorn/issue756 2022-07-21 11:38:10 +02:00
Jonas Platte 4e2bd14a27 chore: Silence buggy clippy lint 2022-07-21 11:30:13 +02:00
Jonas Platte 0b3b757120 refactor: Make Store type internal to base crate 2022-07-21 11:30:13 +02:00
Jonas Platte 63d01dd20e refactor(base): Stop using Store type in store integration tests 2022-07-21 11:30:13 +02:00
Jonas Platte a43005dec2 refactor(base): Add RoomInfo::new constructor 2022-07-21 11:30:13 +02:00
Jonas Platte 4187aa400f refactor: Remove Store type usage from sled-state-inspector
Requires using more explicit syntax for some calls because SledStore has
methods of the same names with different (harder to use) signatures.
2022-07-21 11:30:13 +02:00
Jonas Platte cf8f3bf7cc refactor(sdk)!: Update MessageOptions API once again
… to match the latest changes in Ruma.
2022-07-21 11:18:09 +02:00
Jonas Platte 5b66bed1f0 chore: Remove unused imports from example 2022-07-21 11:18:09 +02:00
Benjamin Kampmann 1668c173e6 Merge pull request #836 from matrix-org/ben-release-crypto-nodes-beta0
Release crypto-nodejs beta1
2022-07-21 10:59:46 +02:00
Jonas Platte 76fd9bd963 fix(sdk): Call to-device handlers 2022-07-21 10:30:13 +02:00
Benjamin Kampmann 6f18e35b72 Merge remote-tracking branch 'origin/main' into ben-release-crypto-nodes-beta0 2022-07-21 10:25:26 +02:00
Johannes Becker 5f7e91c2e7 refactor(appservice)!: Cleanup 2022-07-21 09:01:53 +02:00
Jonas Platte 45829efa7e feat(bindings): Tracing configuration through FFI 2022-07-20 16:38:51 +02:00
Kévin Commaille a6bd7fc82f chore: Update Ruma 2022-07-20 12:18:06 +00:00
Stefan Ceriu 5c53a5f699 chore(bindings/apple): Remove unnecessary +nightly flag from debug builds 2022-07-20 14:53:00 +03:00
Stefan Ceriu 021bf55074 feat(bindings/sdk-ffi): Expose full tracing configuration string through ffi. 2022-07-20 13:39:15 +03:00
Stefan Ceriu 0043de4028 Update bindings/matrix-sdk-ffi/Cargo.toml
Co-authored-by: Jonas Platte <jplatte@matrix.org>
2022-07-20 13:28:58 +03:00
Stefan Ceriu f9bb86c52f feat(bindings/sdk-ffi): Allow ffi users to configure tracing and log levels 2022-07-20 12:56:42 +03:00
Stefan Ceriu 1cd18f49aa chore(bindings/apple): Remove now unnecessary debug script module import following module map rename 2022-07-20 12:29:36 +03:00
Benjamin Kampmann 8b160dfd38 Merge pull request #857 from matrix-org/doug/homeserver-details
Add a `HomeserverLoginDetails` to the FFI's auth service.
2022-07-20 10:27:09 +02:00
Doug 77f7dbbbc8 Support server URLs. Join homeserver details futures. 2022-07-19 16:16:03 +01:00
Ivan Enderlin fe590735c1 fix(bindings/crypto-nodejs): Fix CI typo
fix(bindings/crypto-nodejs): Rrrrr
2022-07-19 16:43:40 +02:00
Ivan Enderlin 0360b13cdb fix(bindings/crypto-nodejs): Rrrrr 2022-07-19 16:12:43 +02:00
Jonas Platte f30419446f refactor(sdk)!: Make from in MessageOptions optional 2022-07-19 15:25:16 +02:00
Doug 93d879f356 Add homeserver_details property. 2022-07-19 12:48:00 +01:00
Benjamin Kampmann c20c23bc19 Merge pull request #856 from matrix-org/fixing-clippy-lint
style(crypto): use matches for legibility
2022-07-19 12:54:44 +02:00
Johannes Becker a174d0f669 sdk: Make from in MessageOptions optional 2022-07-19 12:46:48 +02:00
Doug a10a26a68d Tidy up authentication service.
Add HomeserverLoginDetails
2022-07-19 11:36:34 +01:00
Benjamin Kampmann 1940ebefcb style(crypto): use matches for legibility 2022-07-19 12:22:53 +02:00
Benjamin Kampmann b91217f53b Merge remote-tracking branch 'origin/main' into gnunicorn/issue833 2022-07-19 12:19:20 +02:00
Benjamin Kampmann 3d3db96734 style(integration-tests): minor rust fmt fixes 2022-07-19 12:11:13 +02:00
Benjamin Kampmann b24f7b7ad7 ci(integration-tests): switch to non-docker github action 2022-07-19 12:05:49 +02:00
Benjamin Kampmann 9502d32941 Merge remote-tracking branch 'origin/main' into gnunicorn/issue833 2022-07-19 12:03:47 +02:00
Benjamin Kampmann 9318c2f1e8 ci(crypto-nodejs): switch to main branch 2022-07-19 11:36:30 +02:00
Benjamin Kampmann 2d03cb5c79 Merge pull request #852 from zecakeh/test-bulk-member
test(sdk): Split tests for permalinks
2022-07-19 11:34:48 +02:00
Johannes Becker aa8206d6c8 chore: Bump ruma 2022-07-18 19:32:16 +02:00
Johannes Becker f937d82336 chore: Bump ruma 2022-07-18 16:46:34 +00:00
Benjamin Kampmann 3f71818704 ci(test): switch from docker to compose 2022-07-18 18:10:41 +02:00
Benjamin Kampmann 025db83af3 ci(test): cancel previous calls and fix the docker logs cmd 2022-07-18 18:06:54 +02:00
Benjamin Kampmann 8520976417 style(test): fix styles of integration tests 2022-07-18 17:55:31 +02:00
Benjamin Kampmann 06cab75df3 ci(sdk): Add integration tests to CI 2022-07-18 17:39:51 +02:00
Benjamin Kampmann 47a8c62f44 fix(sdk): fetch invitiation details without sync 2022-07-18 17:39:29 +02:00
Benjamin Kampmann e2f1f01cb2 test(sdk): creating integration tests for invitations 2022-07-18 17:33:09 +02:00
Ivan Enderlin fdef2dd86d feat(bindings/crypto-js): Redirect panics and logs into JavaScript console
feat(bindings/crypto-js): Redirect panics and logs into JavaScript console
2022-07-18 14:59:50 +02:00
Ivan Enderlin c72ec36b3a chore(style) Make cargo fmt happy. 2022-07-18 14:39:39 +02:00
Benjamin Kampmann e3febd6f1f refactore(test): move testing out of regular build environment 2022-07-18 14:37:51 +02:00
Kévin Commaille b98e3d80a0 test(sdk): Split tests for permalinks 2022-07-18 13:39:37 +02:00
Kévin Commaille c0a7b17324 test: Add method to create room member events in bulk 2022-07-18 13:39:37 +02:00
Kévin Commaille 66c5d5311e test: Add methods to add events in bulk 2022-07-18 13:39:36 +02:00
Stefan Ceriu f215c92d0b fix(bindings/apple): Remove briding header as no longer needed after corectly naming the module map 2022-07-18 13:09:39 +02:00
Stefan Ceriu d571ca718d fix(bindings/apple): Allow any platform OS simulator to run the Apple specific unit tests. 2022-07-18 13:09:39 +02:00
Kévin Commaille 37eb058dac test: Reorganize JSON responses and events 2022-07-18 10:46:45 +02:00
Kévin Commaille 45ecd89387 test: Build sync response per room and event type
Allow to have more customizable and complete responses
2022-07-18 10:46:45 +02:00
Kévin Commaille 5d916e4a67 test: Expose default room ID used in sync JSON responses 2022-07-18 10:46:45 +02:00
Ivan Enderlin daa0fc0206 doc(bindings/crypto-js): Fix typos. 2022-07-18 10:05:05 +02:00
Ivan Enderlin 3d1c96fbec feat(bindings/crypto-js): Redirect errors to console.error. 2022-07-18 09:51:44 +02:00
Ivan Enderlin decd3fcb43 feat(bindings/crypto-js) Simplify code for feature = "tracing".
This patch creates one `inner` module for when `feature = "tracing"`,
and one for when `no(feature = "tracing")`. Then, let's expose
everything from `inner::*`.

This patch also replaces `Tracing.install` by `new Tracing`. In case
of `not(feature = "tracing")`, `new Tracing` raises an error.

The goal is to remove all the `#[cfg(…)]` annotations everywhere. Now
there is only 2 of them.
2022-07-18 09:44:42 +02:00
Ivan Enderlin c763ce3f41 feat(bindings/crypto-js): Tracing can be installed more than once. 2022-07-18 09:23:37 +02:00
Johannes Becker 09c56ea057 feat(appservice)!: Allow specifying device id for registration 2022-07-14 15:23:21 +02:00
github-actions 163ce94806 Tagging Crypto-Node.js for release 2022-07-14 10:40:57 +00:00
Benjamin Kampmann ebfa235dab chore(crypto-nodejs): Update changelog for beta.1 2022-07-14 12:31:04 +02:00
Benjamin Kampmann 0112396c99 ci(crypto-nodejs): trigger build for new tag 2022-07-14 12:31:04 +02:00
Benjamin Kampmann 8170d2c996 Merge remote-tracking branch 'origin/main' into ben-release-crypto-nodes-beta-1 2022-07-14 11:40:45 +02:00
Benjamin Kampmann 41de3e0af8 Merge pull request #844 from Hywan/fix-issue-842
fix(bindings/crypto-nodejs): Fix pre-built download link
2022-07-14 11:36:15 +02:00
Benjamin Kampmann 81bf300000 Merge pull request #839 from johannescpk/appservice/virtual-users
feat(appservice): Add method to get virtual user map
2022-07-14 11:31:02 +02:00
Benjamin Kampmann 594e8c04cd Merge pull request #840 from matrix-org/jplatte/optional-dep-features
Remove implicit features for optional dependencies
2022-07-14 11:30:03 +02:00
Benjamin Kampmann b6d94ab7c6 Merge pull request #845 from Hywan/fix-issue-843
fix(bindings/crypto-js): Use `cross-env` to pass envvar on Windows
2022-07-14 11:28:57 +02:00
Ivan Enderlin 283c5ff51e fix(bindings/crypto-js): Let's not deal with Console.group.
Events and spans from `tracing` can happen asynchronously, and could
mess the `Console.group` structure.
2022-07-14 09:04:44 +02:00
Ivan Enderlin bb631f2f79 feat(bindings/crypto-js): Add ability to turn Tracing on and off, and change logger min level.
The patch updates the code to use `tracing_subscriber::reload`, so
that we get a `Handle` that can be used to modify the tracing at
runtime.

This patch also adds a new `tracing` feature.

This patch finally adds a test suite for the `Tracing` API.
2022-07-14 09:04:13 +02:00
Ivan Enderlin d39baf1295 test(bindings/crypto-js): Encrypt and decrypt a valid message. 2022-07-14 09:04:13 +02:00
Ivan Enderlin f5016dbb97 feat(bindings/crypto-js): Define Layer.max_level_hint. 2022-07-14 09:04:13 +02:00
Ivan Enderlin e7d0ee4379 !fixup 2022-07-14 09:04:13 +02:00
Ivan Enderlin 70561f9649 feat(bindings/crypto-js): Add the userLogger function to enable logging into Console. 2022-07-14 09:04:13 +02:00
Ivan Enderlin 8f8bd40e8d feat(bindings/crypto-js): Redirect Rust panics to JavaScript console. 2022-07-14 09:04:13 +02:00
Ivan Enderlin 04d326eec1 doc(bindings/crypto-nodejs): Fix package name in the README.md
Fix package name in readme for nodejs bindings
2022-07-14 08:39:53 +02:00
Ivan Enderlin 3567d19359 fix(bindings/crypto-js): Use cross-env to pass envvar on Windows. 2022-07-14 08:26:57 +02:00
Ivan Enderlin 65b1dfef6f fix(bindings/crypto-nodejs): Fix pre-built download link. 2022-07-14 08:14:45 +02:00
Travis Ralston 4f1718e587 Fix package name in readme for nodejs bindings 2022-07-13 13:45:07 -06:00
Jonas Platte 3c5f30d41e refactor: Remove implicit features for optional dependencies
Consistently use `dep:` syntax for optional dependencies so they don't
implicitly act as features of their own.
2022-07-13 18:55:41 +02:00
Jonas Platte 529bdc8e0a refactor: Remove unused optional dependencies 2022-07-13 18:23:52 +02:00
Johannes Becker f55a86dd66 feat(appservice): Add method to get virtual user map 2022-07-13 17:16:12 +02:00
Benjamin Kampmann f87764fabb ci(ffi-apple): fixing ffi build for apple
Merge pull request #806 from matrix-org/stefan/ffi-workflow-optimization
2022-07-13 11:58:26 +02:00
Stefan Ceriu 65654de7eb chore: sdk-ffi apple - try building the framework on x86_64 outside of Xcode 2022-07-13 11:19:07 +02:00
Stefan Ceriu 399bbc25e9 chore: sdk-ffi apple - run the CI build script from the Xcode project and only for the active architecture 2022-07-13 11:19:06 +02:00
Stefan Ceriu c61dbb657e chore: sdk-ffi apple - drop sample project deployment target to iOS 15 and macOS 12, disable catalyst. 2022-07-13 11:19:06 +02:00
Stefan Ceriu a73b104c59 chore: sdk-ffi apple - rename modulemap to module.modulemap as per xcframework specifications 2022-07-13 11:19:06 +02:00
Stefan Ceriu c10961f068 chore: sdk-ffi apple - remove mac catalyst target support 2022-07-13 11:19:06 +02:00
Benjamin Kampmann 15e22cba47 Merge pull request #837 from johannescpk/appservice/refactor-cleanup
refactor(appservice)!: Improve API and cleanup docs
2022-07-13 11:16:47 +02:00
Johannes Becker ec00af0bca refactor(appservice)!: Improve API and cleanup docs 2022-07-13 10:11:43 +02:00
Benjamin Kampmann a4f1c404f6 ci(crypto-nodejs): set npm publish level to public
Release Crypto-Node.js / Upload prebuilt libraries (gcc-aarch64-linux-gnu g++-aarch64-linux-gnu, ubuntu-latest, aarch64-unknown-linux-gnu) (push) Failing after 45s
Release Crypto-Node.js / Upload prebuilt libraries (gcc-arm-linux-gnueabihf, ubuntu-latest, arm-unknown-linux-gnueabihf) (push) Failing after 41s
Release Crypto-Node.js / Upload prebuilt libraries (gcc-i686-linux-gnu g++-i686-linux-gnu, ubuntu-latest, i686-unknown-linux-gnu) (push) Failing after 30s
Release Crypto-Node.js / Upload prebuilt libraries (ubuntu-latest, x86_64-unknown-linux-gnu) (push) Failing after 42s
Release Crypto-Node.js / Upload prebuilt libraries (ubuntu-latest, x86_64-unknown-linux-musl) (push) Failing after 35s
Release Crypto-Node.js / Upload prebuilt libraries (macos-latest, aarch64-apple-darwin) (push) Has been cancelled
Release Crypto-Node.js / Upload prebuilt libraries (macos-latest, x86_64-apple-darwin) (push) Has been cancelled
Release Crypto-Node.js / Upload prebuilt libraries (windows-latest, aarch64-pc-windows-msvc) (push) Has been cancelled
Release Crypto-Node.js / Upload prebuilt libraries (windows-latest, i686-pc-windows-msvc) (push) Has been cancelled
Release Crypto-Node.js / Upload prebuilt libraries (windows-latest, x86_64-pc-windows-msvc) (push) Has been cancelled
Release Crypto-Node.js / Package nodejs package (push) Has been cancelled
2022-07-12 19:28:59 +02:00
Benjamin Kampmann 402d061d42 ci(crypto-nodejs): fixing path to npm package for publishing 2022-07-12 18:02:59 +02:00
Benjamin Kampmann 2a1bc372fc chore(crypto-nodejs): setting version 2022-07-12 17:35:46 +02:00
Benjamin Kampmann bcab2a6d8c ci(crypto-nodejs): setting base branch 2022-07-12 17:24:34 +02:00
Benjamin Kampmann 703b3a3561 ci(crypto-nodejs): Fixing typo in workflow 2022-07-12 17:18:54 +02:00
Benjamin Kampmann 36f62ce67f ci(crypto-nodejs): Use regular npm version to set version 2022-07-12 17:14:15 +02:00
Benjamin Kampmann 9bc605a76d ci(crypto-nodejs): FIxing name and directory for action 2022-07-12 17:11:20 +02:00
Benjamin Kampmann 13a6825af7 ci(crypto-nodejs): Fix workflow syntax error 2022-07-12 17:07:49 +02:00
Benjamin Kampmann c5796991e8 chore(crypto-nodejs): Adding changelog 2022-07-12 17:05:40 +02:00
Benjamin Kampmann 9a45325683 ci(crypto-nodejs): use org-wide secrets (#835) 2022-07-12 17:00:44 +02:00
Ivan Enderlin 0bde5ccf38 feat(bindings/crypto-nodejs): Add #[napi(strict)] to force type checking from JavaScript (#829)
* feat(bindings/crypto-nodejs): Add `#[napi(strict)]` to force type checking from JavaScript.

* chore(bindings/crypto-nodejs): Use our own fork of `napi-rs` for the moment.
2022-07-12 16:24:24 +02:00
Benjamin Kampmann 94b635c074 build(crypto-nodejs): Crypto Node.js release infrastructure (#763)
* feat(crypto-nodejs): Download lib binary in postinstall

* build(crypto-nodejs): Workflow to prebuild napi bindings

* ci(crypto-nodejs): Disable broken target, install without download

* ci(apple-ffi): Don't run for drafts

* ci(coverage): Don't run for draft PRs

* fix(crypto-nodejs): bind to current version for download

* fix(crypto-nodejs): Ignore libs and package

* ci(crypto-nodejs): Build and upload NPM package

* fix(crypto-nodejs): Set proper target list

* ci(crypto-nodejs): Remove FreeBSD from build pipeline

* ci(crypto-nodejs): Linkers for linux cross compile

* ci(crypto-nodejs): Add arm64 build for windows

* ci(crypto-nodejs): Proper linkers for arm and musl

* ci(crypto-nodejs): Correct apt command for musl

* fix(crypto-nodejs): Drop arm64 linux musl support

* ci(crypto-nodejs): Manual Workflow trigger process

* chore(crypto-nodejs): Get Github to pickup our action

* ci(crypto-nodejs): Add i686 Linux built

* ci(crypto-nodejs): Configure cliff for nodejs changelogs

* ci(crypto-nodejs): Proper gcc for i868 targets

* docs(crypto-nodejs): Add supported targets for npm install

* ci(crypto-nodejs): Limit building of binaries to tags

* style: consol.log -> console.info; Improve docs

Co-authored-by: Ivan Enderlin <ivan@mnt.io>

* activate for testing

* fix broken merge

* 0.1.0

* fix(js): put in the proper package name

* activate for PR for testing

* fix(nodejs): getting ready for publishing

* ci(crypto-nodejs): Adding docs and fixing naming for workflows

* typo: missed one

* fixing package name

Co-authored-by: Ivan Enderlin <ivan@mnt.io>
2022-07-12 16:05:57 +02:00
Benjamin Kampmann f69123b0d8 style(indexeddb): rust fmt 2022-07-12 13:11:50 +02:00
Benjamin Kampmann 15be2dc45e Merge pull request #832 from johannescpk/sdk/identity-assertion-session
fix(sdk): Can't assert identity without session
2022-07-12 12:25:46 +02:00
Johannes Becker 420ca26bf5 fix(sdk): Can't assert identity without session 2022-07-12 10:44:56 +02:00
Benjamin Kampmann c1f0c73728 fix(indexeddb): New migration didn't create schema for new db 2022-07-11 16:18:29 +02:00
Benjamin Kampmann 54ed1af223 Merge remote-tracking branch 'origin/main' into gnunicorn/issue756 2022-07-11 15:17:03 +02:00
Benjamin Kampmann 6a57461f74 feat(indexeddb)!: Implement StateStoreBuilder pattern to configure migration preferences 2022-07-11 14:28:09 +02:00
Kévin Commaille 2d0653894c refactor(test): Rename LOGOUT to EMPTY
This name is more accurate for its uses.
2022-07-09 17:59:45 +02:00
Damir Jelić 47cfac7f4c test: Optimize sha2 even in debug builds
This makes the tests finish on my machine twice as fast. This works
mainly because some tests utilize pbkdf2 to derive a key from a
passphrase.
2022-07-08 18:47:36 +02:00
Kévin Commaille 9539cbcfb9 test(appservice): Replace mockito with wiremock 2022-07-08 16:33:29 +02:00
Kévin Commaille 9778518347 test(sdk): Replace mockito with wiremock 2022-07-08 16:33:29 +02:00
Ivan Enderlin dc2276cd8a feat(bindings/crypto-nodejs): Implement an Attachment API.
feat(bindings/crypto-nodejs): Implement an `Attachment` API.
2022-07-08 16:26:19 +02:00
Damir Jelić f1c880ff5f feat(bindings/ffi): Add an authentication service
This adds a basic authentication service to the bindings that abstracts away the Client until a login has been completed successfully.
2022-07-08 12:24:15 +02:00
Damir Jelić 93e5728d65 test(sdk): Move the integration tests
This moves the bulk of the Client tests into integration tests.
2022-07-08 12:08:27 +02:00
Damir Jelić a7af96d081 feat(crypto): Customized event types
This patch adds customized event types, currently only for the
m.room_key and m.secret.send to-device events.

This allows us to:
    a) Deserialize the session_key field into a vodozemac type
    b) Control when we zeroize secrets better
2022-07-07 19:20:42 +02:00
Benjamin Kampmann d7b974ac04 build(xtask): indexeddb alias for ci wasm-commands 2022-07-07 18:35:54 +02:00
Benjamin Kampmann aae9b5c6d8 refactor(test)!: More debugging info on errors in async_test macro 2022-07-07 18:35:16 +02:00
Doug 0dee880cd0 Address PR comments. 2022-07-07 17:15:12 +01:00
Ivan Enderlin f0190b4601 feat(bindings/crypto-nodejs): Transform timeout into milliseconds
feat(bindings/crypto-nodejs): Transform `timeout` into milliseconds
2022-07-07 14:54:18 +02:00
Ivan Enderlin 6d83f01e73 fix(sdk): THe MediaEncryptionInfo.web_key has been renamed. 2022-07-07 13:59:36 +02:00
Ivan Enderlin 2eb5fc77f5 feat(bindings/crypto-nodejs): Remove Clone impl for MediaEncryptionInfo.
We don't want to clone a struct that contains a secret.

However, on the Node.js side, we can only receive arguments by
references. The problem we have is that we cannot transfer the
ownership of `MediaEncryptionInfo` to `AttachmentDecryptor` because we
don't own it. To simulate this behavior, we use `Option.take`.

A new method then appears:
`EncryptedAttachment.hasMediaEncryptionInfoBeenConsumed` to know if
the media encryption info has been consumed by `Attachment.decrypt`
already or not. That way, we can decrypt only once. It is possible to
do a JSON-encoded backup of the media encryption info by calling
`EncryptedAttachment.mediaEncryptionInfo` though.
2022-07-07 13:53:46 +02:00
Kévin Commaille 5ab8bd0885 Fix missing import 2022-07-07 13:24:54 +02:00
Kévin Commaille ee69863912 Move event permalink test 2022-07-07 13:19:31 +02:00
Kévin Commaille e87d599f84 Merge remote-tracking branch 'upstream/main' into integration-tests 2022-07-07 13:16:09 +02:00
Ivan Enderlin 0b011d9097 doc(bindings/crypto-nodejs): Add link to the specification. 2022-07-07 13:15:14 +02:00
Ivan Enderlin 0f5851cc01 chore(crypto): Rename MediaEncryptionInfo.web_key to .key. 2022-07-07 13:14:05 +02:00
Kévin Commaille d6a2f15c68 Simplify use of via
Due to a ruma upgrade
2022-07-07 12:30:15 +02:00
Kévin Commaille 36a47c28ed Add note that the event should be part of the room 2022-07-07 12:30:15 +02:00
Kévin Commaille 900016b249 feat(sdk): Get a permalink for an event 2022-07-07 12:30:15 +02:00
Kévin Commaille de60a24602 Remove __test feature 2022-07-07 11:26:49 +02:00
Ivan Enderlin 29c10b8424 feat(bindings/crypto-nodejs): Convert timeout from u128 to u64.
First, u128 has a bug in `serde`,
cf. https://github.com/serde-rs/json/issues/625.

Second, we don't need to represent the timeout as a u128, it's clearly
too large. This patch tries to convert it to u64. It should never
fail, but we propagate the error anyway.
2022-07-07 11:12:12 +02:00
Johannes Becker 4b856ce9d6 fix(sdk): Use the local config variable to decide identity assertion 2022-07-07 10:16:23 +02:00
Ivan Enderlin c043daede0 test(crypto): Fix a test. 2022-07-07 10:15:24 +02:00
Ivan Enderlin 9f6988f766 Merge branch 'main' into fix-issue-796 2022-07-07 10:11:43 +02:00
Ivan Enderlin ed0709373d fix(crypto): Rename web_key to key for MediaEncryptionInfo.
Based on the [Section 11.11.1.6.1 Extensions to `m.room.message`
msgtypes](https://spec.matrix.org/v1.2/client-server-api/#extensions-to-mroommessage-msgtypes),
the parameter for the JSON Web Key is named `key`, not `web_key`. This
patch fixes that by renaming the field when serializing and
deserializing.
2022-07-07 10:04:34 +02:00
Ivan Enderlin acf9b15571 feat(bindings/crypto-nodejs): Use latest napi-rs version to avoid cloning Uint8Array.
The new `napi-rs` release includes a patch that avoids cloning and
copying data inside a `Uint8Array`
(https://github.com/napi-rs/napi-rs/pull/1224), it now returns a
“Node.js reference” of it.

This new `napi-rs` release also includes one of our patch,
https://github.com/napi-rs/napi-rs/pull/1200, which means we no longer
need to depend on our fork.
2022-07-07 09:49:34 +02:00
Charles Wright ba39185679 Fix build errors 2022-07-06 18:08:02 +02:00
Benjamin Kampmann dc40309cbe feat(sled): Introduce SledStoreBuilder, allow migration conflict strategy configuration 2022-07-06 17:51:51 +02:00
Doug da277c4978 Create a new client on login.
More clippy errors.
2022-07-06 12:43:02 +01:00
Doug 9925d73e7b Fix typos and clippy errors. 2022-07-06 11:52:33 +01:00
Benjamin Kampmann d465b70bea refactor(indexeddb)!: Rename SerializationError to IndexedDBStoreError 2022-07-06 12:18:58 +02:00
Doug fec879f0f3 Simplify AuthenticationError for now. 2022-07-06 10:29:13 +01:00
Doug 91427b82a5 Use an Optional client instead of failable init. 2022-07-05 18:14:25 +01:00
Ivan Enderlin d7739369ae chore(bindings/crypto-nodejs): Remove useless napi::Result. 2022-07-05 17:45:09 +02:00
Ivan Enderlin 4fd24eebea feat(bindings/crypto-nodejs): Implement an Attachment API.
This patch provides a new API to encrypt and decrypt attachment,
i.e. big buffer of type `Uint8Array`.

It's based on `matrix_sdk_crypto::AttachmentEncryptor` and `AttachmentDecryptor`.
2022-07-05 17:31:52 +02:00
Benjamin Kampmann 73daec3757 Merge pull request #810 from gnunicorn/expose-invite-details
feat(sdk): Expose details of invite for invited room
2022-07-05 14:56:05 +02:00
Benjamin Kampmann d9f3b257b4 Apply suggestions from code review
Co-authored-by: Ivan Enderlin <ivan@mnt.io>
2022-07-05 14:38:53 +02:00
Damir Jelić 771c33d710 chore(crypto): Bump vodozemac
Vodozemac used to accept and return strings when encrypting and
decrypting. This is quite unusual for a pure cryptographic library so we
switched towards the usual setup where we encrypt/decrypt raw bytes.

Since we do encrypt/decrypt JSON strings in Matrix land, we do the
string conversions over here.
2022-07-05 13:23:50 +02:00
Doug 56adf6a89b Add a client_container with locks. 2022-07-05 11:43:10 +01:00
Ivan Enderlin e5a7a975a3 feat(bindings/crypto-nodejs): Transform timeout into milliseconds. 2022-07-05 12:05:53 +02:00
Ivan Enderlin f3e69a2352 fix(bindings/cryto-nodejs): Fix memory corruption in async functions
fix(bindings/cryto-nodejs): Fix memory corruption in async functions
2022-07-05 10:25:16 +02:00
Ivan Enderlin 607d7ebc22 fix(bindings/cryto-nodejs): Fix memory corruption in async functions.
In async functions, the Node.js GC may or may not (that's a random
behavior) collect the arguments passed to the function as soon as it
returns. The function may not be executed yet, since it's async. Thus,
it leads to memory corruption: The function tries to read later on the
value inside an argument and… it crashes at best.

To avoid this bug, there is no other choice than cloning the values
before the function returns, in its “sync path” (so before any
transformation of an `.await` point into an “async block”).

The performance impact is not “massive”, I'm not sure it could be
noticeable easily since it is most of the time related to identifiers
(e.g. `UserId`), which are cheap to clone. I have to find the balance
here, and cloning offers the best trade off from my point of view.
2022-07-05 09:07:20 +02:00
Doug 0178b71437 Add basic AuthenticationService to the FFI. 2022-07-04 16:55:50 +01:00
Kévin Commaille dd6a902240 test(sdk): Move integration tests 2022-07-04 16:22:20 +02:00
Kévin Commaille 4eb1337dc8 ci: Remove whitespaces in config file 2022-07-04 16:22:19 +02:00
Benjamin Kampmann 81f02f0d0b Merge pull request #804 from gnunicorn/ben-hunting-the-nodjs-segfault
Hunting the nodejs segfault bug, long-term
2022-07-04 15:25:09 +02:00
Ivan Enderlin 76fe6d54ac feat(bindings/crypto-*): Add fallback_keys field to KeysUploadRequest
feat(bindings/crypto-*): Add `fallback_keys` field to `KeysUploadRequest`
2022-07-04 15:02:38 +02:00
Ivan Enderlin eb358889e9 Merge branch 'main' into fix-issue-800 2022-07-04 14:31:28 +02:00
Ivan Enderlin c82631c414 feat(bindings/crypto-js): Implement OlmMachine.sign
feat(bindings/crypto-js): Implement `OlmMachine.sign`
2022-07-04 14:16:27 +02:00
Ivan Enderlin fb4a940a26 chore: Make Clippy happy… 2022-07-04 13:50:28 +02:00
Ivan Enderlin 05561a8777 chore(crypto): Make Clippy happy. 2022-07-04 13:06:14 +02:00
Ivan Enderlin 909ada43d7 chore(base): Make Clippy happy.
So, Clippy suggests to change `(&member).into()` to `member.into()`
but it's the same, and `From<T>` is not implemented for this `T`, only
`From<&T>` is present. Thus, to deceive Clippy, I'm using
`std::borrow::Borrow` here. Not super happy with that though…
2022-07-04 12:00:42 +02:00
Ivan Enderlin 6176b3b658 feat(bindings/crypto-ffi): Add fallback_keys field to KeysUpload. 2022-07-04 11:49:45 +02:00
Ivan Enderlin 566227576e feat(bindings/crypto-js): Add fallback_keys field to KeysUploadRequest. 2022-07-04 11:47:27 +02:00
Ivan Enderlin d6c0ef1497 feat(bindings/crypto-nodejs): Add fallback_keys field to KeysUploadRequest. 2022-07-04 11:47:15 +02:00
Ivan Enderlin f72a14890d chore(crypto) Make Clippy happy. 2022-07-04 11:42:50 +02:00
Ivan Enderlin 62378b4abc Merge branch 'main' into fix-issue-797 2022-07-04 11:24:33 +02:00
Ivan Enderlin f96069f591 chore(store-encryption): Call DerefMut manually.
Clippy on nigtly is raising a warning, which is turned into an error
on the CI. It's the [`explicit_auto_deref`
lint](https://rust-lang.github.io/rust-clippy/master/index.html#explicit_auto_deref). I
suspect it's a false-positive but I'm not sure. Anyway, to workaround
this and unblock our CI, let's call `DerefMut::deref_mut` manually:
it's clearer anyway.
2022-07-04 11:00:23 +02:00
Ivan Enderlin 59615d4ae3 chore(bindings/crypto-nodejs): Clean up based on feedback. 2022-07-04 10:17:11 +02:00
Benjamin Kampmann fd38c757e4 feat(sdk): Expose details of invite for invited room 2022-07-01 19:44:27 +02:00
Jonas Platte 861d899541 refactor(base): Remove an unnecessary allocation 2022-07-01 16:16:29 +02:00
Jonas Platte fd08c9e7da refactor(base): Remove check for own user in notification handling
This is now done in Ruma.
Reverts commit bc78095611.
2022-07-01 16:16:29 +02:00
Jonas Platte cffb565a5f chore: Allow some usage of deprecated fields
… to allow CI to succeed. They should be removed soon.
2022-07-01 16:16:29 +02:00
Jonas Platte f20d1c3d76 chore: Upgrade ruma 2022-07-01 16:16:29 +02:00
Jonas Platte e4f6c0cc58 chore(sdk): Remove feature ruma/appservice-api-helper
No longer used as of https://github.com/matrix-org/matrix-rust-sdk/pull/710
2022-07-01 16:16:29 +02:00
Jonas Platte d3ae99eb22 chore: Silence new clippy lint 2022-07-01 12:39:46 +02:00
Jonas Platte bc47caa356 chore: Remove unnecessary map_err's 2022-07-01 11:55:28 +02:00
Ivan Enderlin afa96f1bf4 test(bindings/crypto-nodejs): Add more signing test cases. 2022-06-30 16:58:39 +02:00
Ivan Enderlin c99f42347c chore(bindings/crypto-nodejs): Simplify code by removing matches!. 2022-06-30 16:52:08 +02:00
Ivan Enderlin 51cb35502d doc(bindings/crypto-nodejs): Add missing documentation. 2022-06-30 16:50:33 +02:00
Ivan Enderlin b59077e83d chore(bindings/crypto-nodejs): Replacing into_iter by iter on &BTreeMap.
Calling `into_iter` on `&BTreeMap` will not consume it. It has the
same effect as calling `iter`. So let's do it.
2022-06-30 16:48:44 +02:00
Ivan Enderlin 3f197734d9 feat(bindings/crypto-nodejs) Implement OlmMachine.sign.
This patch first implements the new `Signatures`, `Signature` and `MaybeSignature` types.

Then, it moves some Vodozemac types into their own module, and
implements the new `Ed25519Signature` type.

Finally, it implements `OlmMachine.sign`.
2022-06-30 16:44:07 +02:00
Benjamin Kampmann 1961403512 ci(crypto-nodejs): Only build non-release version on failure, improve CI build time 2022-06-30 12:53:51 +02:00
Benjamin Kampmann f1ebbfd245 ci(crypto-nodejs): Create non-release build of version and upload everything as artifacts upon failure 2022-06-30 12:24:21 +02:00
Ivan Enderlin 0458ed9be1 feat(bindings/crypto-js): Implement DeviceKeyId, DeviceKeyAlgorithm and DeviceKeyAlgorithmName. 2022-06-30 08:51:36 +02:00
Ivan Enderlin 12c7b76fea feat(bindings/crypto-js): Implement `OlmMachine.crossSigningStatus. 2022-06-30 08:33:28 +02:00
Marcel a8601e186a fix(appservice): Don't process the same transaction twice 2022-06-29 16:17:25 +00:00
Stefan Ceriu 8a2d13feea feat(bindings): Session verification through FFI 2022-06-29 13:59:52 +02:00
Benjamin Kampmann e2ca56114e Merge pull request #785 from zecakeh/room-permalink
feat(sdk): Add method to get a room permalink
2022-06-29 13:58:25 +02:00
Anderas 3c6d159a04 refactor: Use ClientBuilder pattern in SDK FFI
Co-authored-by: Jonas Platte <jplatte@matrix.org>
2022-06-29 13:13:31 +02:00
Benjamin Kampmann 464bc43290 Merge pull request #793 from Hywan/test-crypto-nodejs-timeout
test(crypto-nodejs): Increase timeout
2022-06-29 12:58:11 +02:00
Kévin Commaille 297861e186 Fix docs styling 2022-06-29 12:20:57 +02:00
Kévin Commaille 8313029e33 Split into methods for both Matrix URI formats 2022-06-29 12:02:26 +02:00
Ivan Enderlin 913bdd683e feat(crypto-js): Change the package name
feat(crypto-js): Change the package name
2022-06-28 19:28:58 +02:00
Ivan Enderlin 041b9bc405 feat(crypto-js): Change the package name. 2022-06-28 17:05:21 +02:00
Ivan Enderlin 1526f76686 test(crypto-nodejs): Increase timeout.
For some unknown reasons, sometimes, randomly, one test (initializing
an `OlmMachine` with a local store with a passphrase) can take more
than 5s, only on Github Actions. Let's increase the test timeout value
so that the entire test suite doesn't fail.
2022-06-28 16:47:46 +02:00
Kévin Commaille f0e0194ff2 feat(sdk): Add method to get a room permalink
Include routing for room IDs
2022-06-26 13:38:01 +02:00
Kévin Commaille ebc7177438 feat(base): Add method to get Room alt aliases 2022-06-26 12:01:51 +02:00
Ivan Enderlin 091fab8a2a chore(bindings): Move matrix-sdk-ffi and matrix-sdk-crypto-ffi into the bindings/ directory
chore(bindings): Move `matrix-sdk-ffi` and `matrix-sdk-crypto-ffi` into the `bindings/` directory
2022-06-23 15:54:32 +02:00
Ivan Enderlin 818d715395 chore: Implement feedback. 2022-06-23 15:53:19 +02:00
Ivan Enderlin 5a0089da52 doc(bindings): Mention bindings in the top README.md file. 2022-06-23 15:12:51 +02:00
Ivan Enderlin 68b6c19dd4 test: Ensure all crates members of the workspace are compiled & tested. 2022-06-23 14:10:31 +02:00
Ivan Enderlin c29e2b9563 !fixup 2022-06-23 11:35:42 +02:00
Ivan Enderlin ecc28efd53 chore(bindings): Move matrix-sdk-ffi and matrix-sdk-crypto-ffi into the bindings/ directory. 2022-06-23 11:31:59 +02:00
Jonas Platte f3a61020e7 refactor(sdk): Rewrite sso login to be easier to read 2022-06-22 17:17:52 +02:00
Jonas Platte a423e92246 chore: Consistently capitalize 'device ID' 2022-06-22 17:17:52 +02:00
Jonas Platte b5d7f10c6b feature: Introduce a login builder API
This improves the readability of login calls.
The old login API is kept, but deprecated.
2022-06-22 17:17:52 +02:00
Ivan Enderlin 931eabf55c chore(bindings): Move crypto-nodejs and crypto-js into the bindings/ directory
chore(bindings): Move `crypto-nodejs` and `crypto-js` into the `bindings/` directory
2022-06-22 16:33:20 +02:00
Ivan Enderlin 8cd7fa9fb0 chore: Implement feedback. 2022-06-22 16:03:37 +02:00
Ivan Enderlin 1604f24136 chore(test): Fix YAML. 2022-06-22 16:03:37 +02:00
Ivan Enderlin 3da737b9e2 chore(test): Shorten job name for test-matrix-sdk-crypto-nodejs.
In the Github UI, we can only see:

    🐧 [m]-crypto-nodejs, Node.js…

What interests us is the Node.js version number.
2022-06-22 16:03:37 +02:00
Ivan Enderlin 2ffcc1a415 chore: Use [m] as an alias for matrix-sdk. 2022-06-22 16:03:37 +02:00
Ivan Enderlin 829dab42c5 chore(test): Rename the test-matrix-sdk-crypto-js job. 2022-06-22 16:03:37 +02:00
Ivan Enderlin 54acd314cc chore(test): Move the wasm workflow inside the ci workflow. 2022-06-22 16:03:37 +02:00
Ivan Enderlin 74953031ee chore(test): Use os-name in step name for test-appservice. 2022-06-22 16:03:37 +02:00
Ivan Enderlin 0436eb9349 chore(ci): Rephrase a little bit the Github Actions steps. 2022-06-22 16:03:37 +02:00
Ivan Enderlin a23bb8f5a0 chore(docs): Rephrase a little bit the Github Actions steps. 2022-06-22 11:57:41 +02:00
Ivan Enderlin 8db58986fb chore(bindings): Move crypto-nodejs and crypto-js into the bindings/ directory.
`matrix-sdk-crypto-nodejs` and `matrix-sdk-crypto-js` are no longer
default members of the Cargo virtual workspace. The Github Actions
workflows for the bindings now live in a `bindings_ci.yml` files
(ideally, it should be in a subdirectory,
`.github/workflows/bindings/ci.yml` but it doesn't work).
2022-06-22 11:54:49 +02:00
Ivan Enderlin 6ad323bc4e test: Run tests faster with nextest
test: Run tests faster with `nextest`
2022-06-22 09:56:02 +02:00
Ivan Enderlin b0d51fdfa5 test: There is no doctest for matrix-sdk-crypto-ffi. 2022-06-22 09:26:51 +02:00
Ivan Enderlin 3bfc68d476 test: Add missing cargo-nextest installation.
This patch also changes the step's name from Clippy to Test.
2022-06-22 09:26:51 +02:00
Ivan Enderlin eb33333925 test: Run doctests manually.
`cargo-nextest` doesn't support doctests for now, so we must run them
“manually” by running a separate `cargo test --doc` command.
2022-06-22 09:26:51 +02:00
Ivan Enderlin d9475c131a test(xtask): Remove xtask -- ci test as it is unused. 2022-06-22 09:26:48 +02:00
Ivan Enderlin 399862d955 test: Run tests faster with nextest.
> [`cargo-nextest`](https://nexte.st/index.html) is a next-generation
> test runner for Rust projects.

This patch installs and uses `nextest` to run our own tests.

Comparing `cargo test` and `cargo nextest` with hyperfine provides the
following results:

```sh
$ hyperfine 'cargo test --workspace' 'cargo nextest run --workspace && cargo test --doc'
Benchmark 1: cargo test --workspace
  Time (mean ± σ):     51.785 s ±  2.066 s    [User: 183.471 s, System: 10.563 s]
  Range (min … max):   49.151 s … 56.641 s    10 runs

Benchmark 2: cargo nextest run --workspace && cargo test --doc
  Time (mean ± σ):     44.556 s ±  0.894 s    [User: 192.213 s, System: 11.441 s]
  Range (min … max):   43.170 s … 45.762 s    10 runs
```

Benchmark 2 is 1.16 times faster than Benchmark 1.
2022-06-22 09:26:07 +02:00
Ivan Enderlin 2c1f5fed8d feat(crypto-js): Migrate tests and polish the API
feat(crypto-js): Migrate tests and polish the API
2022-06-21 12:04:45 +02:00
Ivan Enderlin 8b2237fa7a Merge branch 'main' into feat-crypto-js-next 2022-06-21 11:38:48 +02:00
Ivan Enderlin e5ea2a770b chore(crypto-js): Implement feedback from PR. 2022-06-21 11:25:58 +02:00
Jonas Platte 5f31e9d131 chore: Add missing json language specification to docs 2022-06-20 22:33:35 +02:00
Jonas Platte 6cb9c11b88 chore: Remove unnecessary pub visibility from OnceCell imports 2022-06-20 22:33:35 +02:00
Jonas Platte a00c130fc3 feature: Allow passing already-Arc'ed stores to StoreConfig methods 2022-06-20 18:00:33 +02:00
Jonas Platte 4971802e75 chore: Replace usage of Store with Arc<dyn StateStore> 2022-06-17 17:35:33 +02:00
Jonas Platte 8690addfd5 chore: Add Clone impl for ClientBuilder 2022-06-17 14:59:22 +02:00
Jonas Platte 00a20f325b chore: Add Clone impl for StoreConfig
… by storing the stores inside Arc's instead of Box'es.
2022-06-17 14:59:22 +02:00
Jonas Platte a4e4bfe833 refactor(sdk)!: Change store builder methods from Box<dyn Trait> to impl Trait
To migrate, don't box the store before passing it to `builder.state_store` or
`builder.crypto_store` (remove `Box::new`).
2022-06-17 14:59:22 +02:00
Jonas Platte 02aa537f2a chore: Keep uniffi version in sync across deps, CI 2022-06-17 13:37:07 +02:00
Benjamin Kampmann 5316d2e6e7 fix(indexeddb): Upgrade version to latest state store pattern 2022-06-16 13:17:45 +02:00
Benjamin Kampmann 7adef1d24e fix(sled): Upgrade db version to latest changes 2022-06-16 13:17:35 +02:00
Anderas c755e19fb3 Merge pull request #765 from matrix-org/andy/crypto_ffi
Build Crypto iOS framework
2022-06-16 11:25:39 +01:00
Jonas Platte 8250c24525 chore: Undo pinning of clap 2022-06-15 20:47:55 +02:00
Andy Uhnak fe29fa57eb Build Crypto iOS framework 2022-06-15 13:52:21 +01:00
Ivan Enderlin c564b1a5e1 feat(crypto-nodejs): Add store_path and store_passphrase to the OlmMachine constructor
feat(crypto-nodejs): Add `store_path` and `store_passphrase` to the `OlmMachine` constructor
2022-06-15 07:28:29 +02:00
Benjamin Kampmann 9d691e238a Merge pull request #759 from Hywan/fix-codecov-labs
chore(test): Remove `labs` from the projects + exclude `matrix-sdk-indexeddb` from code coverage report
2022-06-14 20:29:07 +02:00
Ivan Enderlin 520e2f30f7 doc(crypto-js): Add missing module documentation. 2022-06-14 16:54:22 +02:00
Ivan Enderlin c56ab5928c test(crypto-js): Add a workflow to test matrix-sdk-crypto-js. 2022-06-14 16:34:08 +02:00
Ivan Enderlin f8cd2310be feat(crypto-js): Implement OlmMachine.decryptRoomEvent & siblings. 2022-06-14 16:16:54 +02:00
Ivan Enderlin 073fb45580 feat(crypto-nodejs): Define Node.js versions policy.
We now support only “current”, “active” or “maintenance” versions
according to https://nodejs.org/en/about/releases/, which are
compatible with NAPI v6.
2022-06-14 16:05:01 +02:00
Ivan Enderlin 3833d35348 chore(crypto-nodejs): Drop Node.js v12.17.
There is a segfault with `napi-rs` and Node.js in v12.17. It's an old
version, it may be fair to drop its support for now. Let's see if
people would need it in the future, we may work on `napi-rs` to fix
this bug in case it's really necessary.
2022-06-14 16:05:01 +02:00
Ivan Enderlin 83b730d1c8 chore(crypto-nodejs): Make the code compatible with Node.js < 18. 2022-06-14 16:05:01 +02:00
Ivan Enderlin 6477cc5072 feat(crypto-nodejs): Add store_path and store_passphrase to the OlmMachine constructor.
This patch adds the `store_path` and the `store_passphrase` arguments
to the `OlmMachine` constructor to use a `CryptoStore` instead of
having an in-memory Olm machine.
2022-06-14 16:05:01 +02:00
Ivan Enderlin 2117b36a75 chore(test): Exclude matrix-sdk-indexeddb from code coverage report. 2022-06-14 16:04:41 +02:00
Ivan Enderlin 5e8ed3bcbf chore(test): Remove labs from the projects.
It's already part of the `ignore` section.
2022-06-14 16:04:41 +02:00
Jonas Platte 87639a4c4c fix(appservice): Remove erroneous ? operator 2022-06-14 15:20:24 +02:00
Amanda Graven de04aba5b3 fix(appservice): Remove erroneous ? operator 2022-06-14 15:02:55 +02:00
Amanda Graven 5243091bec test(appservice): Virtual client membership
Test that virtual clients get assigned the correct membership to rooms
when processing received transactions.
2022-06-14 14:39:54 +02:00
Amanda Graven 1d746f1ef1 fix(appservice): Virtual client non-membership
Don't assume virtual client membership is join if none is stored, since
that leads to a client being told it's joined in rooms it has no
membership of. The main appservice client still assumes it's joined
every room it receives transaction events about.
2022-06-14 14:39:54 +02:00
Ivan Enderlin 56d74e25b8 test(crypto-js): Finish to migrate the test suites + code clean up. 2022-06-14 14:09:52 +02:00
Ivan Enderlin a758d98f84 feat(crypto-nodejs): Update license. 2022-06-14 12:12:27 +02:00
Ivan Enderlin 5adae6fd41 feat(crypto-js): Migrate tests and polish the API. 2022-06-14 12:12:27 +02:00
Damir Jelić 38d771cca6 ci(coverage): Set the correct out format for CI coverage reports 2022-06-14 12:01:03 +02:00
Jonas Platte dd4c329f57 chore: Prevent clap upgrades beyond 3.2 2022-06-14 11:02:19 +02:00
Jonas Platte e3edf0139a Enable rustdoc-map nightly feature via .cargo/config.toml
… instead of using -Z on the command line.
2022-06-13 14:30:10 +02:00
Jonas Platte d07001a581 chore: Work around a cargo bug 2022-06-13 14:30:10 +02:00
Ivan Enderlin 62b8169ac2 chore(test): Ajust code coverage configurations (tarpaulin and codecov)
chore(test):  Code Coverage must ignore some `matrix-sdk-crypto-(js|nodejs)`
2022-06-13 14:24:22 +02:00
Ivan Enderlin d35063412f chore(test): Ignore matrix-sdk-test-macros and matrix-sdk-ffi. 2022-06-13 12:52:37 +02:00
Damir Jelić 1a162e5dd5 test(crypto): Test the double verification cancellation 2022-06-13 12:30:52 +02:00
Damir Jelić b8069af8ba fix(crypto): Cancel the verification flow if we multiple verifications
The spec claims that we should cancel verifications if multiple
verifications are attempted at once[1]:
    When the same device attempts to initiate multiple verification
    attempts, the recipient should cancel all attempts with that device.

So let's start doing this.

[1]: https://spec.matrix.org/v1.2/client-server-api/#error-and-exception-handling
2022-06-13 12:30:52 +02:00
Damir Jelić fa3e192c37 docs(crypto): Improve the signature verification docs some more
Co-authored-by: Denis Kasak <dkasak@termina.org.uk>
2022-06-13 12:12:09 +02:00
Damir Jelić efc53569ed refactor(crypto): Rename our is_signed_by methods 2022-06-13 12:12:09 +02:00
Damir Jelić 5c12132569 refactor(crypto): Introduce a SignedJsonObject trait
This should mostly remove the wild west of signature verification. We
define a trait that tells us which objects can contain signatures and
thus can be passed on to signature verification methods.

It also should be slightly more efficient, since we removed a bunch of
duplicate canonicalization steps.
2022-06-13 12:12:09 +02:00
Amanda Graven 251a38285c perf(appservice): Cache namespace regexes 2022-06-13 11:57:50 +02:00
Ivan Enderlin b500fa1daa chore(test): Configure Tarpaulin to collect data from matrix-sdk-common. 2022-06-13 11:27:22 +02:00
Ivan Enderlin 4430dae421 chore(test): Configure Tarpaulin to ignore more crates. 2022-06-13 11:25:54 +02:00
Ivan Enderlin eead09984c chore(test): Ask codecov.io to ignore the crates/matrix-sdk-crypto-ffi directory. 2022-06-13 11:25:38 +02:00
Ivan Enderlin dcfcac0bd3 chore(test): Ask codecov.io to ignore labs and xtask directories. 2022-06-13 11:24:10 +02:00
Jonas Platte dc32fc282d Remove sync_token from BaseClient
… as it is also accessible as self.store.sync_token in BaseClient methods.
2022-06-13 11:10:12 +02:00
Jonas Platte b6eed09564 Make session field in Store private
… for cleaner encapsulation.
2022-06-13 11:10:12 +02:00
Jonas Platte 29ba171953 Simplify ownership of server_versions
We couldn't originally take references to it when it was behind RwLock,
with OnceCell this is no longer a problem.
2022-06-13 11:10:12 +02:00
Jonas Platte 9e9152745c Remove homeserver_url from HttpClient 2022-06-13 11:10:12 +02:00
Jonas Platte 12d1607cdc Remove session from HttpClient 2022-06-13 11:10:12 +02:00
Jonas Platte 6c8b520f14 Remove unused Clone impls on private types 2022-06-13 11:10:12 +02:00
Jonas Platte fedcdb1e63 chore: Add some more tracing events 2022-06-13 11:10:12 +02:00
Jonas Platte 1cfd69a880 chore: Improve doc comment formatting 2022-06-13 11:10:12 +02:00
Ivan Enderlin dad035d170 chore(test): Configure tarpaulin to use its config file. 2022-06-13 10:46:29 +02:00
Ivan Enderlin 3c14acf163 chore(test): Exclude matrix-sdk-crypto-(js|nodejs) from code coverage reports. 2022-06-13 10:38:07 +02:00
Ivan Enderlin 253affeb0c feat(crypto-nodejs) Implement missing APIs
feat(crypto-nodejs) Implement missing APIs
2022-06-09 21:38:41 +02:00
Ivan Enderlin fe4ddfde89 chore(crypto-nodejs): Remove clone calls when possible. 2022-06-09 21:15:25 +02:00
Ivan Enderlin 8a332ca9e1 chore(crypto-nodejs): Implement feedbacks / polish. 2022-06-09 18:02:29 +02:00
Ivan Enderlin 506f57a22c feat(crypto-nodejs): Enable traace filtering and change the env var to MATRIX_LOG. 2022-06-09 14:06:42 +02:00
Damir Jelić 8b05f9276f fix(sdk): Remove a duplicate Session cell from the HttpClient 2022-06-09 13:37:42 +02:00
Damir Jelić e8b2655d52 docs(crypto-ffi): Explain what a timeout of 0 means when fetching identities 2022-06-09 11:58:23 +02:00
Damir Jelić 537ef1409b test(crypto): Test that we're now notifying when we receive a /keys/query 2022-06-09 11:58:23 +02:00
Damir Jelić e2bf3d0d18 chore(crypto-js): Silence some doc warnings 2022-06-09 11:58:23 +02:00
Damir Jelić d188ef3386 feat(crypto): Add a way wait for a keys/query to be done when fetching identities. 2022-06-09 11:58:23 +02:00
Damir Jelić ba7ccb40cc feat(crypto): Wait for a key query to be done if we're claming one-time keys 2022-06-09 11:58:23 +02:00
Ivan Enderlin 1b2c644277 test(crypto-nodejs): Set up CI to run the test suites. 2022-06-09 11:34:16 +02:00
Benjamin Kampmann 6a853d0173 Merge pull request #744 from matrix-org/jplatte/readme
chore: Fix `main` docs link in readme
2022-06-09 10:51:58 +02:00
Jonas Platte 7487b24fe3 chore: Fix main docs link in readme 2022-06-09 10:21:04 +02:00
Amanda Graven 5c4f2b3430 fix(appservice): Make membership keys consistent
Correct the inconsistency between the keys used for reading and writing
the membership of a virtual user in the appservice's namespace
2022-06-08 10:42:35 +02:00
Stefan Ceriu 901b670a22 Use the nightly toolchain together with the newly introduced target-applies-to-host on the sdk-ffi crate debug builds to avoid cache corruption issues. Switched back to debug mode as the internal tokio crashes went away 2022-06-08 08:55:28 +02:00
Jonas Platte 28d6e2821b chore: Replace new usage of Box<UserId> 2022-06-07 21:12:43 +02:00
Jonas Platte 7f0b74a39d fixup! style: Remove usage of assign! macro from doctests 2022-06-07 21:07:34 +02:00
Jonas Platte 7b6869310f style: Make assign! formatting consistent 2022-06-07 21:07:34 +02:00
Jonas Platte 445b2e627d style: Remove usage of assign! macro from examples 2022-06-07 21:07:34 +02:00
Jonas Platte 0e206506d9 style: Remove usage of assign! macro from doctests 2022-06-07 21:07:34 +02:00
Jonas Platte 0fb1d72100 style: Use anyhow::Ok in more places 2022-06-07 21:07:34 +02:00
Ivan Enderlin 6d8c54deb5 chore(crypto-nodejs): Add missing newline. 2022-06-07 17:03:02 +02:00
Ivan Enderlin 07620452df chore(crypto-node): Make Clippy happy. 2022-06-07 16:50:26 +02:00
Jonas Platte 099db20555 Use target-applies-to-host to avoid unnecessary cache invalidation 2022-06-07 16:43:17 +02:00
Ivan Enderlin 75571c2c30 fix(crypto-js): Fix missing symbol. 2022-06-07 16:42:34 +02:00
Ivan Enderlin 8c95b1c4cf chore(crypto-nodejs): Fix a typo. 2022-06-07 16:40:54 +02:00
Ivan Enderlin 530c268e61 doc(crypto-nodejs): Include the README.md in the generated documentation. 2022-06-07 16:35:22 +02:00
Ivan Enderlin 99dcf84340 chore(crypto-nodejs): Use napi::Result when possible. 2022-06-07 16:28:55 +02:00
Ivan Enderlin 2a76d17bd9 doc(crypto-nodejs): Generate JavaScript/TypeScript documentation. 2022-06-07 16:26:23 +02:00
Ivan Enderlin 15af364c97 Merge branch 'main' into feat-crypto-nodejs-next 2022-06-07 15:31:03 +02:00
Ivan Enderlin ec7724f393 doc(crypto-nodejs): Improve the README.md. 2022-06-07 15:27:35 +02:00
Ivan Enderlin 1e7d509920 chore(crypto-nodejs): Clean up. 2022-06-07 14:45:20 +02:00
Ivan Enderlin 520758bf1e test(crypto-nodejs): Finish the OlmMachine test suite. 2022-06-07 14:42:24 +02:00
Benjamin Kampmann 7f49618d35 Merge pull request #729 from gnunicorn/gnunicorn/issue609
Ensure all data state stores save is encrypted
2022-06-07 12:41:38 +02:00
Benjamin Kampmann a308771a7a fix(sled): Deserialize encrypted TimelineMetadata properly 2022-06-07 12:22:54 +02:00
Benjamin Kampmann 2c4379909c fix(sled): Wrap [u8] encoding in an explicit type to prevent accidential misuse 2022-06-07 12:22:54 +02:00
Damir Jelić d4f49ca334 chore: Fix some new clippy warnings 2022-06-07 11:41:29 +02:00
Damir Jelić c97bb83af9 refactor(base): Remove a bunch of OlmMachine wrapper methods
The whole machine is nowadays exposed through the base Client, so no
need to re-expose individual methods that don't add more functionality.
2022-06-07 11:41:29 +02:00
Ivan Enderlin 12c53bb2bc test(crypto-nodejs): Add more test cases. 2022-06-07 11:05:19 +02:00
Damir Jelić 7fd973c563 refactor(crypto-ffi): Make use of the BackupRecoveryKey type instead of a string 2022-06-07 10:47:19 +02:00
Benjamin Kampmann f8dae723c3 style: Fix review remarks 2022-06-07 10:20:55 +02:00
Benjamin Kampmann 8ccf78c025 fix(indexeddb): Ensure all values are encrypted (namely filters and timeline metadata) if asked to 2022-06-07 10:20:40 +02:00
Benjamin Kampmann 47bb73cf89 fix(sled): Ensure timeline metadata is also saved encrypted 2022-06-07 10:20:27 +02:00
Benjamin Kampmann f3d952839e style: Clean up rustfmt and clippy 2022-06-07 10:19:43 +02:00
Benjamin Kampmann 85ea9279dc fix(indexeddb): Use random db in plain test for consistency 2022-06-07 10:19:27 +02:00
Benjamin Kampmann be159356cd fix(sled): Encrypt custom key and value 2022-06-07 10:19:23 +02:00
Benjamin Kampmann 571b5e61cf fix(sled): Encrypt media content 2022-06-07 10:19:20 +02:00
Benjamin Kampmann 77af11bcbc fix(sled): Encrypt saved sync_token 2022-06-07 10:19:20 +02:00
Benjamin Kampmann 335251695a fix(sled): Encrypt saved filters 2022-06-07 10:19:17 +02:00
Benjamin Kampmann bf17012d6b test(base): Add integration store test for saving filters 2022-06-07 10:19:13 +02:00
Benjamin Kampmann 328ebdba9c fix(sled): Encrypt saved user_ids 2022-06-07 10:19:08 +02:00
Benjamin Kampmann c359b011fa refactor(sled): Rename for consistency event -> value 2022-06-07 10:19:04 +02:00
Ivan Enderlin 07fed7f4df test(crypto-nodejs): Continue to test OlmMachine and add tracing support. 2022-06-06 16:27:32 +02:00
Ivan Enderlin 0ed74d8c31 test(crypto-nodejs): Test OlmMachine.receiveSyncChanges, .outgoingRequests and .markRequestAsSent. 2022-06-06 12:09:37 +02:00
Ivan Enderlin 35d7cab330 feat(crypto-nodejs): Rename requests request_id to id + add type. 2022-06-06 12:08:58 +02:00
Ivan Enderlin 407e27d176 feat(crypto-nodejs): Make changed and left optional in DeviceLists constructor. 2022-06-06 10:27:32 +02:00
Damir Jelić 0f758a643c refactor(crypto): Make the boolean parameter for the backup verification clearer 2022-06-03 16:29:17 +02:00
Damir Jelić fd2ae1ed8f docs(crypto): Improve some backup verfication docs
Co-authored-by: Denis Kasak <dkasak@termina.org.uk>
2022-06-03 16:29:17 +02:00
Damir Jelić 2b13c0832f refactor(crypto): Introduce a struct for the backup info 2022-06-03 16:29:17 +02:00
Damir Jelić b3fbd15270 feat(crypto): Improve the API to verify backups
This API change allows us to inspect why a backup is considered to be
trusted instead of just returning a boolean telling us if it's trusted
or not.
2022-06-03 16:29:17 +02:00
Amanda Graven 4e3e393596 refactor(appservice): Better virtual client sync
Store the membership state of clients in the appservice's namespace, and
construct sync events based on that information
2022-06-03 15:03:31 +02:00
Jonas Platte 7f81e7c61b chore: Optimize quote even in debug mode 2022-06-03 14:48:48 +02:00
Ivan Enderlin a75ae16b79 test(crypto-nodejs): Add more test suites. 2022-06-02 15:58:30 +02:00
Ivan Enderlin 9ebc61ad0f test(crypto-nodejs): Adding more test suites. 2022-06-02 15:24:22 +02:00
Ivan Enderlin 0d66480cd6 fix(crypto-nodejs): OlmMachine.new effectively raises an error.
Returning an `napi::Error` doesn't raise it. We must return a
`Result<_, napi::Error>` to ensure `napi` will raise the error as
expected.
2022-06-02 15:23:25 +02:00
Ivan Enderlin 02802e9088 feat(crypto-nodejs): EncryptionSettings.rotation_period and .…_period_messages are now BigInt. 2022-06-02 13:59:00 +02:00
Ivan Enderlin 1a6adc6d41 chore(crypto-nodejs): Ignore package-lock.json for now. 2022-06-02 11:10:55 +02:00
Ivan Enderlin 6d10d6150c test(crypto-nodejs): Add some test suites. 2022-06-02 11:09:57 +02:00
Damir Jelić fb1a2f6d94 feat(appservice): Add support for appservice login
An appservice can log in by providing a valid appservice token and a user within the appservice’s namespace.

This allows the appservice to acquire a scoped access token for a single user. matrix-appservice-sdk can now take a persisted device id for virtual users. If e2ee is enabled, it will automatically perform an appservice login to create the an E2EE backed session for the virtual user.
2022-06-02 10:36:33 +02:00
Damir Jelić bdee4e0547 refactor(crypto): Use a result type for invalid signatures 2022-06-02 09:31:37 +02:00
Denis Kasak 42d5eec8b7 docs(crypto): Improve Signature doc comment. 2022-06-02 09:31:37 +02:00
Damir Jelić e50c1465ea docs(crypto): Improve some signature verification related docs
Co-authored-by: Denis Kasak <dkasak@termina.org.uk>
2022-06-02 09:31:37 +02:00
Damir Jelić 5827cc9a39 refactor(crypto): Use ? instead of nesting closures when searching for a key
Co-authored-by: Jonas Platte <jplatte@element.io>
2022-06-02 09:31:36 +02:00
Damir Jelić c95fd93666 fix(types): Allow Ed25519 signatures to be invalid
Since signatures can be uploaded by anyone, unlike one-time keys which
might only be uploaded by the given device for themselves, a Signatures
struct might fail to be deserialized because a signature was maliciously
attached to the object by someone else.

We don't want to fail to deserialize all the signatures just because
someone attached an invalid one. We still would like to have the
signature be deserialized into its proper type if possible so the Raw<T>
pattern was not used.
2022-06-02 09:31:36 +02:00
Damir Jelić d96fcf7199 refactor(crypto): Return a Signatures struct in the sign method 2022-06-02 09:31:36 +02:00
Damir Jelić e2348471db fix(crypto): Make fetching of the first cross signing key more robust 2022-06-02 09:31:36 +02:00
Ivan Enderlin 8e120eb648 doc(crypto-nodejs): Write missing documentation. 2022-06-02 09:23:26 +02:00
Ivan Enderlin c573985c64 chore(crypto-nodejs): Add a .gitignore for artifacts. 2022-06-02 09:19:17 +02:00
Ivan Enderlin 6a996c7657 doc(crypto-nodejs): Write missing documentation and clean up the code. 2022-06-02 09:18:26 +02:00
Ivan Enderlin 7bb96e0ece chore(crypto-node): Use Either7 (new pending feature). 2022-06-01 22:38:52 +02:00
Ivan Enderlin dc7f0389b1 chore(crypto-node): Document and add napi(getter) when necessary. 2022-06-01 20:55:34 +02:00
Ivan Enderlin 5d4b3a0457 feat(crypto-nodejs): Implement OlmMachine.decrypt_room_event. 2022-06-01 20:55:34 +02:00
Ivan Enderlin 888ffb0a56 chore(crypto-node): Use Either5 + Either3 instead of Either. 2022-06-01 20:55:34 +02:00
Ivan Enderlin 475fffb64d feat(crypto-nodejs): Implement OlmMachine.encrypt_room_event. 2022-06-01 20:55:34 +02:00
Ivan Enderlin a8b44f26ea feat(crypto-nodejs): Implement OlmMachine.share_room_key. 2022-06-01 20:55:34 +02:00
Ivan Enderlin a7697fbd32 feat(crypto-nodejs): Implement OlmMachine.get_missing_sessions. 2022-06-01 20:55:34 +02:00
Ivan Enderlin 02e63ab9c1 chore(crypto-js): Remove a useless import. 2022-06-01 20:55:34 +02:00
Ivan Enderlin 8d909ccabe feat(crypto-nodejs): Implement OlmMachine.mark_request_as_sent. 2022-06-01 20:55:34 +02:00
Ivan Enderlin 2e22f6b6c0 feat(crypto-nodejs): Implement OlmMachine.outgoing_requests. 2022-06-01 20:55:34 +02:00
Ivan Enderlin 7c85fdaf28 doc(crypto-js): Update documentation. 2022-06-01 20:55:34 +02:00
Ivan Enderlin 1ecf90bb42 feat(crypto-nodejs): Implement OlmMachine.receive_sync_changes. 2022-06-01 20:55:34 +02:00
Ivan Enderlin e2ecba7d45 feat(crypto-nodejs): Implement OlmMachine.update_tracked_users. 2022-06-01 20:55:34 +02:00
Ivan Enderlin 8a0e0a7a4d feat(crypto-nodejs): Start implementing OlmMachine API. 2022-06-01 20:55:34 +02:00
Charlotte 🦝 Delenk c562d91533 feat(appservice): Use appservice logins for e2ee
This commit also adds a virtual user builder, which allows you to
control the device id, change the client builder, perform an appservice
login, and even restore a previously created session.

https://spec.matrix.org/v1.2/client-server-api/#appservice-login
2022-06-01 15:29:04 +01:00
Ivan Enderlin 3cf4150df2 feat: Rename OlmMachine.share_group_session to OlmMachine.share_room_key
feat: Rename `OlmMachine.share_group_session` to `OlmMachine.share_room_key`
2022-06-01 15:08:58 +02:00
Ivan Enderlin b3d52ca68c feat: Rename OlmMachine.share_group_session to OlmMachine.share_room_key.
As discussed with @poljar, the Matrix event we are creating is
`m.room.key`, so it's preferable to rename the function
`share_room_key`. Note: Olm calls the things an inbound group session,
that's where the name comes from, but it's not aligned with the
specification.
2022-06-01 14:32:11 +02:00
Ivan Enderlin e673954b98 chore: Add missing new lines at the end of files
chore: Add missing new lines at the end of files
2022-05-31 10:31:08 +02:00
Ivan Enderlin 6d7573dced chore: Add missing new lines at the end of files. 2022-05-31 10:06:35 +02:00
Ivan Enderlin 2d14452398 Merge pull request #675 from Hywan/feat-crypto-wasm
feat(crypto): Port to Wasm (in a JS host) and to NodeJS
2022-05-31 10:01:57 +02:00
Ivan Enderlin 7931c4a589 chore(crypto-js): Clean up code and make CI happy. 2022-05-31 08:44:36 +02:00
Ivan Enderlin 4db1ad350b feat(crypto-nodejs): Derive Debug for UserId. 2022-05-31 08:40:16 +02:00
Ivan Enderlin 0debbf24d7 chore(crypto-js): Remove an unknown Clippy lint for now. 2022-05-31 08:40:16 +02:00
Ivan Enderlin bb8217d10f doc(crypto-nodejs) Disable missing docs for now. 2022-05-31 08:40:16 +02:00
Ivan Enderlin 6ff5c8e918 chore(crypto-js): Thanks Clippy. 2022-05-31 08:40:16 +02:00
Ivan Enderlin 7fa89f76aa chore(crypto-js): Update vodozemac's version to match matrix-sdk-crypto's. 2022-05-31 08:40:16 +02:00
Ivan Enderlin 0335fdd07f doc(crypto): Add missing module documentation. 2022-05-31 08:40:16 +02:00
Ivan Enderlin 3f8e3b61ff test(xtask) Replace WasmFeatureSet::MatrixSdkCrypto by *Js. 2022-05-31 08:40:16 +02:00
Ivan Enderlin efe5ea6a9c test(ci): Exclude matrix-sdk-crypto-(js|nodejs) from code coverage. 2022-05-31 08:40:16 +02:00
Ivan Enderlin 6afeeea56c test(ci): Do not compile matrix-sdk-crypto to Wasm, but -crypto-js instead. 2022-05-31 08:40:16 +02:00
Ivan Enderlin bef1dfbf79 chore(crypto-js): Fix typos. 2022-05-31 08:40:16 +02:00
Ivan Enderlin 51488b40d0 doc(crypto-js) Add missing documentation. 2022-05-31 08:40:16 +02:00
Ivan Enderlin b6a637893e chore(crypto-js): Fix cargo fmt. 2022-05-31 08:40:16 +02:00
Ivan Enderlin 2a4dce30b2 Merge branch 'main' into feat-crypto-wasm 2022-05-31 08:40:11 +02:00
Ivan Enderlin 3194ad1f9a feat(crypto-js): Implement OlmMachine.get_verification. 2022-05-31 08:39:34 +02:00
Ivan Enderlin ee648144a2 feat(crypto-nodejs): Split into a new crate: matrix-sdk-crypto-nodejs.
Why? Because `napi` and `wasm-bindgen` are too different. At this
step, the most notable bugs are the way `napi` is handling its proc
macros. There is too much conflicts when used with `#[cfg_attr]`. It
makes the code repetitive and harder to read and to understand (and
also to compile, we must be very careful). But on the short-term,
quickly, we will see more notable differences between `wasm-bindgen`
and `napi`, e.g. with array (in `wasm-bindgen`, we can downcast array
items into particular types, with `napi` it's going to be a very
different code).

Instead of fighting the proc macros bugs now, and having to split the
code later inside the same crate, we believe it's a good idea to split
the code now into 2 crates. At first we will see obvious code
duplications, but on the short-term, the code is likely to be more and
more different.
2022-05-31 08:39:34 +02:00
Ivan Enderlin afef9103a3 feat(crypto-js): Continue to port the API to NodeJS. 2022-05-31 08:39:34 +02:00
Ivan Enderlin 4df5ee6087 chore(crypto-js): Improve the Makefile for NodeJS support. 2022-05-31 08:39:34 +02:00
Ivan Enderlin 1a731ec385 feat(crypto-js): Rename OlmMachine.encrypt to .encrypt_room_event. 2022-05-31 08:39:34 +02:00
Ivan Enderlin 84fe78bab3 Merge branch 'main' into feat-crypto-wasm 2022-05-31 08:39:29 +02:00
Ivan Enderlin bce11b209e feat(crypto-js): Implement OlmMachine.update_tracked_users. 2022-05-31 08:38:24 +02:00
Ivan Enderlin 6c472f873f feat(crypto-js): Start adding support for NodeJS. 2022-05-31 08:38:24 +02:00
Ivan Enderlin 250b85dc79 feat(crypto): Extract js module to its own crate: matrix-sdk-crypto-js. 2022-05-31 08:38:13 +02:00
Ivan Enderlin f3ab1ae276 chore(crypto): Fix a typo. 2022-05-31 08:36:37 +02:00
Ivan Enderlin 6b2df7afdd feat(crypto): Implement `OlmMachine.get_missing_sessions. 2022-05-31 08:36:37 +02:00
Ivan Enderlin cdb252be5e chore(crypto): Move everything inside crates/matrix-sdk-crypto/. 2022-05-31 08:36:37 +02:00
Ivan Enderlin db30ef6ee4 test(crypto): Add tests for the Wasm API. 2022-05-31 08:36:37 +02:00
Ivan Enderlin da8699fe40 feat(crypto): DeviceLists.new expects Array<UserId>s now. 2022-05-31 08:36:37 +02:00
Ivan Enderlin 16b5eebe23 feat(crypto): Implement a hacky downcast function. 2022-05-31 08:36:37 +02:00
Ivan Enderlin 8161360852 feat(crypto): Add toString methods on identifier objects. 2022-05-31 08:36:37 +02:00
Ivan Enderlin f01cfe42b4 feat(crypto): Implement EncryptionSettings.new with default values. 2022-05-31 08:36:37 +02:00
Ivan Enderlin a024c9b268 docs(crypto): Add missing documentation. 2022-05-31 08:36:37 +02:00
Ivan Enderlin c20349f46f feat(crypto): Implement OlmMachine.share_group_session. 2022-05-31 08:36:37 +02:00
Ivan Enderlin e9d37d7c4e docs(crypto): Add missing docs. 2022-05-31 08:36:37 +02:00
Ivan Enderlin 8b94aed27f fix(crypto): Use txn_id for transaction_id. 2022-05-31 08:36:37 +02:00
Ivan Enderlin dc5b15e799 fix(crypto): OutgoingRequest::ToDeviceRequest was not correctly mapped. 2022-05-31 08:36:37 +02:00
Ivan Enderlin 30e9189f7b fix(crypto): Use JavaScript naming convention for OlmMachine.invalidate_group_session. 2022-05-31 08:36:37 +02:00
Ivan Enderlin b6a5d4962b Merge branch 'main' into feat-crypto-wasm 2022-05-31 08:36:30 +02:00
Ivan Enderlin ee713f928f feat(crypto): Implement OlmMachine.encrypt and .invalidate_group_session. 2022-05-31 08:35:09 +02:00
Ivan Enderlin 444ff9936b feat(crypto): Implement RoomId. 2022-05-31 08:35:09 +02:00
Ivan Enderlin 2451815226 feat(crypto): Implement *PublicKey.to_base64 and .length. 2022-05-31 08:35:09 +02:00
Ivan Enderlin 86c6e601bd chore(crypto): Refactor the code with TryFrom on a tuple. 2022-05-31 08:35:09 +02:00
Ivan Enderlin 9f159ff5a4 feat(crypto): Implement OlmMachine.mark_request_as_sent.
To implement this method, a new `responses::OwnedResponse`
intermediate type was needed. In addition to that, the `http` crate is
now required when the `js` feature is enabled.
2022-05-31 08:35:09 +02:00
Ivan Enderlin 056f34883f feat(crypto): Implement OlmMachine.trackedUsers. 2022-05-31 08:35:09 +02:00
Ivan Enderlin 2d15f758da feat(crypto): Use JavaScript naming style for methods. 2022-05-31 08:35:09 +02:00
Ivan Enderlin acd5de3cf3 feat(crypto): Implement ServerName, and add UserId.serverName. 2022-05-31 08:35:09 +02:00
Ivan Enderlin f0bb35a96c feat(crypto): Add changed and left to the constructor of DeviceLists. 2022-05-31 08:35:09 +02:00
Ivan Enderlin 1d38e54739 feat(crypto): Return a JsError rather than a String. 2022-05-31 08:35:09 +02:00
Ivan Enderlin 08665dcd1c feat(crypto): Implement our own future_to_promise helper to simplify code.
`wasm_bindgen_future::future_to_promise` expects a `Future<Output =
Result<JsValue, JsValue>>`. We reimplement this function by expecting
a `Future<Output = Result<T, anyhow::Error>>` where `T:
Into<JsValue>`. That way, we apply the type conversions to `JsValue`
inside this helper rather than in the call site. Additionally, all
errors are managed automatically without having to deal with `JsError`
or `JsValue`. It makes the code simpler to read and easier to write
from my point of view.
2022-05-31 08:35:09 +02:00
Ivan Enderlin 569adb7ceb feat(crypto) Implement OlmMachine.identity_keys. 2022-05-31 08:35:09 +02:00
Ivan Enderlin fd4dff79d4 feat(crypto) Implement OlmMachine.user_id, .device_id and .display_name. 2022-05-31 08:35:09 +02:00
Ivan Enderlin fdb9fe21c6 feat(crypto) Remove existing unwrap code. 2022-05-31 08:35:09 +02:00
Ivan Enderlin 7e5eec82c5 feat(crypto) Implement OlmMachine.outgoing_requests. 2022-05-31 08:35:09 +02:00
Ivan Enderlin 901715bcf3 chore(crypto) Generate a smaller Wasm module. 2022-05-31 08:35:09 +02:00
Ivan Enderlin 3aa46fa746 feat(crypto) Implement OlmMachine.receive_sync_changes & friends. 2022-05-31 08:35:09 +02:00
Ivan Enderlin 3318789a8b feat(crypto) Implement UserId, DeviceId and OlmMachine in Wasm for JS. 2022-05-31 08:35:09 +02:00
Ivan Enderlin 0fe0910fea feat(crypto) Reduce Wasm binary size by enabling LTO. 2022-05-31 08:35:09 +02:00
Damir Jelić a11633381b Merge branch 'poljar/borrow-signature-check-fix' 2022-05-30 12:54:35 +02:00
Benjamin Kampmann 2ff6497604 Merge pull request #715 from gnunicorn/gnunicorn/issue694
docs: configure docs.rs build to contain more features
2022-05-27 22:24:02 +02:00
Damir Jelić 7f87abf408 refactor(crypto): Simplify the signature checking method 2022-05-27 21:29:58 +02:00
Damir Jelić dd49a8bd43 fix(crypto): Don't require mutable borrows when signature checking 2022-05-27 21:28:35 +02:00
Damir Jelić f8c3a1d03b Merge branch 'poljar/signatures-struct' 2022-05-27 20:58:45 +02:00
Damir Jelić 808c4c6f3c chore(crypto): Remove some indentation levels in the types module
Co-authored-by: Jonas Platte <jplatte@element.io>
2022-05-27 20:55:17 +02:00
Damir Jelić a14549d5cc fix(crypto): Don't unwrap when converting to canonical json 2022-05-27 20:55:17 +02:00
Damir Jelić 9b5b4ab2b2 refactor(crypto): Use the Signatures struct for the CrossSigningKey 2022-05-27 20:55:17 +02:00
Damir Jelić 5756057719 refactor(crypto): Use the new Signatures struct for the DeviceKeys 2022-05-27 20:55:17 +02:00
Damir Jelić c5ef3e7c94 refactor(crypto): Turn the SignedKeySignatures into a struct 2022-05-27 20:55:17 +02:00
Damir Jelić fa7c1b60f6 feat(sdk): Replace some Mutex usage with a OnceCell
This makes some simpler getter methods non-async.
2022-05-27 16:37:51 +02:00
Julian Sparber 39b1fff218 Merge remote-tracking branch 'origin/main' into user_once_cell_for_session 2022-05-27 15:53:22 +02:00
Benjamin Kampmann c6df6b421c docs: fix target and feature-list for docsrs 2022-05-27 13:04:07 +02:00
Benjamin Kampmann f9b4fd2d12 docs: configure docs.rs build to contain more features 2022-05-27 10:44:16 +02:00
Damir Jelić e5390e18de refactor(crypto): Introduce a SignJson trait
This patch collects our json signing logic into a single place.
2022-05-27 10:39:12 +02:00
Brandon Lau 28cd0c19e9 fix(crypto-ffi): make crypto-ffi generate a static library for iOS clients 2022-05-27 10:38:21 +02:00
Damir Jelić 15ebc95cd0 chore(qrcode): Add more missing Eq implementations 2022-05-25 13:52:22 +02:00
Damir Jelić 39e12a86ca chore(crypto): Bump vodozemac 2022-05-25 13:49:00 +02:00
依云 ec9ec2567f feat: Add .resolve_room_alias() method to the Client 2022-05-24 08:43:02 +02:00
Damir Jelić fa9c91fb0e fix(crypto-ffi): Add support to encrypt custom events 2022-05-23 19:37:04 +02:00
Johannes Becker 24b71bf869 feat(appservice): Improve autojoin example 2022-05-23 14:14:05 +02:00
Benjamin Kampmann dd83cdd74b Merge pull request #704 from matrix-org/poljar/eq-store-encryption
feat(store-encryption): Derive Eq for some structs
2022-05-23 13:07:29 +02:00
Jonas Platte 453cae641b fix(docs): Remove history gh-pages branch
This should drastically reduce the repository size.
2022-05-23 12:57:45 +02:00
Damir Jelić f838b5fae8 fix(base): Fix a clippy warning about temporary variables 2022-05-23 11:35:23 +02:00
Damir Jelić 1f722f224f feat(crypto): Add a bunch of Eq implementations 2022-05-23 11:35:07 +02:00
Damir Jelić a992a4e831 feat(store-encryption): Derive Eq for some structs 2022-05-23 11:14:09 +02:00
Benjamin Kampmann 017359b081 Merge pull request #700 from gnunicorn/b-improve-coverage-reporting
Improve CI coverage reporting
2022-05-20 12:33:05 +02:00
Benjamin Kampmann 08718acd57 Merge pull request #698 from matrix-org/poljar/rename-encrypt-method
refactor(crypto): Make it clear that the encrypt method is for room events
2022-05-20 10:35:03 +02:00
Benjamin Kampmann dd1f817701 ci(CodeCoverage): exclude ffi & wasm from default project 2022-05-20 10:26:31 +02:00
Benjamin Kampmann 81db9ef4ca ci(CodeCoverage): Remove patch-level coverage reporting 2022-05-20 08:34:56 +02:00
Benjamin Kampmann e927834108 ci(CodeCoverage): split code coverage reporting in mandatory and optional areas 2022-05-20 08:34:39 +02:00
Damir Jelić f3045dbf99 fixup! refactor(crypto): Make it clear that the encrypt method is for room events 2022-05-20 08:32:50 +02:00
Jonas Platte d6c6211c00 chore: Use matrix_sdk::Result alias more 2022-05-20 07:52:39 +02:00
Jonas Platte 85949081ce chore: Consistently use anyhow for Result-returning doctests
Cuts down on syntactic noise.
2022-05-20 07:52:39 +02:00
Jonas Platte cbcc5feef2 fix(sled): Fix unused import when experimental-timeline isn't enabled 2022-05-20 07:52:39 +02:00
Jonas Platte 1b569a8fd4 chore: Consistently use anyhow::Result for example main fn's
When an `Err` is propagated out of `main`, it will be printed using
`Debug`, which is much easier to read in anyhow::Error's case. See also
https://docs.rs/anyhow/latest/anyhow/struct.Error.html#display-representations
2022-05-20 07:52:39 +02:00
Damir Jelić 813f388812 refactor(crypto): Make it clear that the encrypt method is for room events 2022-05-20 07:47:47 +02:00
Damir Jelić 552de33dbc Merge branch 'dkasak/docs-improvements' 2022-05-20 07:26:00 +02:00
Denis Kasak c3f2003eb7 docs: Slightly reword CryptoStore doc for consistency. 2022-05-19 16:22:09 +02:00
Denis Kasak 3b70d7f9ba docs: Improve wording of store module-level comment
Includes a fix to refer to the `e2e-encryption` feature instead of
`encryption` (which doesn't exist).
2022-05-19 16:22:09 +02:00
Denis Kasak c00c9d7b81 docs: Reword feature table so the wording is more uniform 2022-05-19 16:22:09 +02:00
Denis Kasak 126e8f1bd9 docs: Unify references to "cryptostore" as "crypto store" 2022-05-19 16:22:09 +02:00
Denis Kasak 9e6e76e5ed docs: Fix reference to ClientConfig in doc comment 2022-05-19 15:38:13 +02:00
Damir Jelić d1410fcded ci: Run cargo audit every day 2022-05-19 10:03:46 +02:00
Jonas Platte b955e7aad9 Use anyhow::Ok instead of turbofish on Result 2022-05-18 22:04:44 +02:00
Jonas Platte a364018c0e chore: Use serde::de::DeserializeOwned convenience trait 2022-05-18 22:04:44 +02:00
Jonas Platte 0f910b6229 fix(base): Make max_power_level reflect the current maximum only
… instead of taking into account an older maximum as well.
2022-05-18 14:03:12 +02:00
Benjamin Kampmann 736f0e7687 feat: Initial apple platforms support
Merge pull request #571 from matrix-org/jplatte/matrix-sdk-ffi
2022-05-18 13:14:29 +02:00
Stefan Ceriu 6a1b85c560 Fix xcframework debug build script 2022-05-18 13:43:29 +03:00
Benjamin Kampmann e3503fe102 ci: one more move 2022-05-18 11:56:38 +02:00
Benjamin Kampmann 4522b4e8f5 ci: move rust cache to include uniffi bindgen install 2022-05-18 11:32:03 +02:00
Benjamin Kampmann 886809b579 chore(Apple): Move apple into subfolder 2022-05-18 11:24:30 +02:00
Benjamin Kampmann 97b91a47f1 ci: Setup CI test runs FFI crate (Apple platforms support)
Merge pull request #679 from matrix-org/stefan/matrix-sdk-ffi
2022-05-18 10:52:39 +02:00
Stefan Ceriu 4b8b9db075 Have FII action only run on PRs targetting main, similar to the CI one. 2022-05-18 11:49:29 +03:00
Jonas Platte bc207f1e5c chore(sdk): Upgrade async-once-cell to 0.3.1 2022-05-18 10:31:52 +02:00
Stefan Ceriu d863b4eb75 Bump uniffi to version 0.18.0 2022-05-18 11:13:15 +03:00
Stefan Ceriu 45cb162e5a Fix sample project, cleanup tests and add github action 2022-05-18 11:08:51 +03:00
Stefan Ceriu ba2cef62b0 Move apple scripts; tweak the debug one to allow for CI builds 2022-05-18 11:08:51 +03:00
Jonas Platte 2d7fb1b61c fix(matrix-sdk): room::Common:messages() don't return decryption error
If decryption fails we want that the user still has access to
the events.
This was broken in a previous commit.
2022-05-17 18:09:09 +02:00
Julian Sparber d6f9e5f6b6 Remove extra controll flow 2022-05-17 17:52:12 +02:00
Julian Sparber 9c07ff1166 matrix-sdk: room::Common:messages() don't return decryption error
If decryption fails we want that the user still has access to
the events.
This was broken in a previous commit.
2022-05-17 17:23:32 +02:00
Julian Sparber 5bd7d17234 fix(matrix-sdk): room::Common:event() don't return decryption error 2022-05-17 17:03:28 +02:00
Benjamin Kampmann 7d439b1697 Merge pull request #680 from gnunicorn/ben-fix-docs
Fixing docs
2022-05-17 15:45:39 +02:00
Benjamin Kampmann 39f1b9d464 docs: fix link
Co-authored-by: Jonas Platte <jplatte+git@posteo.de>
2022-05-17 13:54:37 +02:00
Benjamin Kampmann 8a86369e68 Merge branch 'ben-fix-docs' into jplatte/matrix-sdk-ffi 2022-05-17 13:39:46 +02:00
Benjamin Kampmann a19999b240 docs: fixing broken inner link 2022-05-17 13:38:07 +02:00
Benjamin Kampmann a72a05edc3 Merge remote-tracking branch 'origin/main' into jplatte/matrix-sdk-ffi 2022-05-17 13:05:24 +02:00
Julian Sparber d0cc3d9c2b Don't split links to two lines
Co-authored-by: Jonas Platte <jplatte+git@posteo.de>
2022-05-17 12:56:24 +02:00
Benjamin Kampmann 2862934b87 style: fix clippy lints for ffi 2022-05-17 12:51:47 +02:00
Julian Sparber 3f3f9d653b Fix code style 2022-05-17 12:46:06 +02:00
Julian Sparber 83fc91f87e Add a pretty label for Session link 2022-05-17 12:39:11 +02:00
Julian Sparber 1e77c39498 Fix store example 2022-05-17 12:37:51 +02:00
Julian Sparber 1de27bcc0c Fix CI and address requested changes 2022-05-17 12:22:35 +02:00
Amanda Graven 248fff370a test(base): Remove invalid sync event from json
The test json used for mocking a sync response contained an ill-formed
event with a room_id key present in the event. Since the deserialization
ignores the room_id key, this resulted in the client's membership state
evaluating to left going by the contents of the state events, despite
the room being in the "joined" section of the sync response. This is a
violation of the spec.
2022-05-17 11:31:36 +02:00
Julian Sparber 26dd2d0e62 Merge remote-tracking branch 'origin/main' into user_once_cell_for_session 2022-05-17 11:14:28 +02:00
Benjamin Kampmann 4bbfa4345f Merge pull request #678 from Hywan/fix-crypto-doc
docs(crypto): Remove outdated documentation and use auto-link
2022-05-17 10:28:07 +02:00
Johannes Becker 5f92113627 chore: Use resolver2 for workspace 2022-05-17 10:24:28 +02:00
Ivan Enderlin 426a93f07c docs(crypto): Remove outdated documentation and use auto-link. 2022-05-17 10:08:42 +02:00
Benjamin Kampmann 0949979a1b Merge remote-tracking branch 'origin/main' into jplatte/matrix-sdk-ffi 2022-05-16 13:35:51 +02:00
Benjamin Kampmann 76144de881 Fix(SDK): add missing import for experimental-timeline feature
Merge pull request #671 from jsparber/fix_import
2022-05-13 10:33:03 +02:00
Stefan Ceriu bd4763235a chore(matrix-sdk-ffi) Use stable toolchain for targeting aarch64-apple-ios-sim 2022-05-12 16:49:49 +03:00
Julian Sparber 911b5415b9 ci: Use experimental-timeline feature 2022-05-12 13:59:18 +02:00
Julian Sparber c3fc6ff58f Fix missing import for experimental-timeline feature 2022-05-12 12:38:58 +02:00
Benjamin Kampmann 4c84f252d2 Merge pull request #667 from matrix-org/ben-releasing-base-0.5.1
Release matrix-sdk-base 0.5.1
2022-05-11 19:23:16 +02:00
Benjamin Kampmann 70c0626882 chore: tag base 0.5.1 2022-05-11 19:01:12 +02:00
Benjamin Kampmann 5570181bf8 fix(sdk): Fix regression with push rules being applied to the own user_id only instead of all but the own user_id
Merge pull request #664 from JCWasmx86/ignore_notification
2022-05-11 18:52:55 +02:00
Benjamin Kampmann 7088ff89b5 Merge pull request #665 from matrix-org/ben-releasing-0.5.0
Releasing 0.5.0
2022-05-11 18:50:34 +02:00
JCWasmx86 3f36528a98 fix(sdk): Fix regression 2022-05-11 18:15:33 +02:00
Jonas Platte 1fdd1ab23a Cleanup after rebase 2022-05-11 11:57:27 +02:00
Jonas Platte 40dcc988d6 fixup! feat: Initial apple platforms support 2022-05-11 11:07:50 +02:00
Jonas Platte 9909cb597a squash! feat: Initial apple platforms support
Enable sending of messages
2022-05-11 11:07:50 +02:00
Jonas Platte 56cfe8f231 squash! feat: Initial apple platforms support
Some FFI API cleanup
2022-05-11 11:07:50 +02:00
Jonas Platte ab9d8eb52b feat: Initial apple platforms support
Co-authored-by: Stefan Ceriu <stefan.ceriu@gmail.com>
Co-authored-by: Benjamin Kampmann <ben.kampmann@gmail.com>
2022-05-11 11:07:42 +02:00
Julian Sparber c8233b6c85 Drop CryptoHolder and use OnceCell for OlmMachine
THe CryptoHolder is just used to hold the crypto-store till the
matrix_sdk::Session is set and it is possible to create the OlmMachine.
But with this approch we need to use a Mutex and getting the OlmMachine
becomes more expensive because of this. Therefore this replaces the
Mutex with a OnceCell. The only downside is that the BaseClient needs to
hold onto a referance to the crypto-store. (It would be possible to drop
it after the OlmMachine is created, but I don't think gives use any
improvment)
2022-05-11 10:48:12 +02:00
Julian Sparber b72bdcd7d4 Use OnceCell to store matrix_sdk::Session
Since the session can be set only once there is no point in using a
Mutex or RwLock.
2022-05-10 17:10:34 +02:00
Ivan Enderlin 5c6a6464c4 chore(crypto) Fix a typo in the code. 2022-05-09 11:50:40 +02:00
Ivan Enderlin d3c20b2a13 feat(crypto) Generate a cdylib for the crate.
Ask `rustc` to generate a dynamic system library, which will be useful
to generate a Wasm module.
2022-05-09 10:51:18 +02:00
Ivan Enderlin 7817af9aa6 feat(crypto) Add the js feature.
This patch updates to code to raise a compilation error if the `js`
feature is used for another architecture than `wasm32`.
2022-05-09 10:40:32 +02:00
Ivan Enderlin 7569c08ada feat(crypto) Add wasm-bindgen as a dep and simplify Cargo.toml. 2022-05-09 10:40:13 +02:00
372 changed files with 44611 additions and 11726 deletions
+16
View File
@@ -1,3 +1,13 @@
# Pass the rustflags specified to host dependencies (build scripts, proc-macros)
# when a `--target` is passed to Cargo. Historically this was not the case, and
# because of that, cross-compilation would not set the rustflags configured
# below in `target.'cfg(all())'` for them, resulting in cache invalidation.
#
# Since this is an unstable feature (enabled at the bottom of the file), this
# setting is unfortunately ignored on stable toolchains, but it's still better
# to have it apply on nightly than using the old behavior for all toolchains.
target-applies-to-host = false
[alias]
xtask = "run --package xtask --"
@@ -23,3 +33,9 @@ rustflags = [
"-Wclippy::str_to_string",
"-Wclippy::todo",
]
# activate the target-applies-to-host feature.
# Required for `target-applies-to-host` at the top to take effect.
[unstable]
rustdoc-map = true
target-applies-to-host = true
+5
View File
@@ -0,0 +1,5 @@
[profile.default]
retries = 2
# kill the slow tests if they still aren't up after 180s
slow-timeout = { period = "60s", terminate-after = 3 }
+6
View File
@@ -0,0 +1,6 @@
root = true
# Unix-style newlines with a newline ending every file
[*]
end_of_line = lf
insert_final_newline = true
-46
View File
@@ -1,46 +0,0 @@
name: Appservice
on:
push:
branches: [main]
pull_request:
branches: [main]
types:
- opened
- reopened
- synchronize
- ready_for_review
env:
CARGO_TERM_COLOR: always
jobs:
test-appservice:
if: github.event_name == 'push' || !github.event.pull_request.draft
name: ${{ matrix.os }} / appservice / stable
runs-on: ${{ matrix.os }}-latest
strategy:
fail-fast: true
matrix:
os: [ubuntu, macOS]
steps:
- name: Checkout
uses: actions/checkout@v1
- name: Install Rust
uses: actions-rs/toolchain@v1
with:
toolchain: stable
profile: minimal
override: true
- name: Load cache
uses: Swatinem/rust-cache@v1
- name: Run checks
uses: actions-rs/cargo@v1
with:
command: run
args: -p xtask -- ci test-appservice
+13
View File
@@ -0,0 +1,13 @@
name: Security audit
on:
workflow_dispatch:
schedule:
- cron: '0 0 * * *'
jobs:
audit:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- uses: actions-rs/audit-check@v1
with:
token: ${{ secrets.GITHUB_TOKEN }}
+1 -1
View File
@@ -12,7 +12,7 @@ jobs:
steps:
- name: Checkout the repo
uses: actions/checkout@v2
uses: actions/checkout@v3
- name: Install Rust
uses: actions-rs/toolchain@v1
+177
View File
@@ -0,0 +1,177 @@
name: Bindings tests
on:
workflow_dispatch:
push:
branches: [main]
pull_request:
branches: [main]
types:
- opened
- reopened
- synchronize
- ready_for_review
env:
CARGO_TERM_COLOR: always
MATRIX_SDK_CRYPTO_NODEJS_PATH: bindings/matrix-sdk-crypto-nodejs
MATRIX_SDK_CRYPTO_JS_PATH: bindings/matrix-sdk-crypto-js
jobs:
test-matrix-sdk-crypto-nodejs:
name: ${{ matrix.os-name }} [m]-crypto-nodejs, v${{ matrix.node-version }}
if: github.event_name == 'push' || !github.event.pull_request.draft
runs-on: ${{ matrix.os }}
strategy:
fail-fast: true
matrix:
os: [ubuntu-latest]
node-version: [14.0, 16.0, 18.0]
include:
- os: ubuntu-latest
os-name: 🐧
- os: macos-latest
os-name: 🍏
node-version: 18.0
- node-version: 18.0
build-doc: true
steps:
- name: Checkout the repo
uses: actions/checkout@v3
- name: Install Rust
uses: actions-rs/toolchain@v1
with:
toolchain: stable
profile: minimal
override: true
- name: Load cache
uses: Swatinem/rust-cache@v1
- name: Install Node.js
uses: actions/setup-node@v3
with:
node-version: ${{ matrix.node-version }}
- name: Install NPM dependencies
working-directory: ${{ env.MATRIX_SDK_CRYPTO_NODEJS_PATH }}
run: npm install
- name: Build the Node.js binding
working-directory: ${{ env.MATRIX_SDK_CRYPTO_NODEJS_PATH }}
run: npm run release-build
- name: Test the Node.js binding
working-directory: ${{ env.MATRIX_SDK_CRYPTO_NODEJS_PATH }}
run: npm run test
# Building in dev-mode and copy lib in failure case
- name: Build the Node.js binding in non-release
if: failure()
working-directory: ${{ env.MATRIX_SDK_CRYPTO_NODEJS_PATH }}
run: |
cp *.node release-mode-lib.node
npm run build
- uses: actions/upload-artifact@v3
if: failure()
with:
name: Failure Files
path: |
bindings/matrix-sdk-crypto-nodejs/*.node
/var/crash/*.crash
- if: ${{ matrix.build-doc }}
name: Build the documentation
working-directory: ${{ env.MATRIX_SDK_CRYPTO_NODEJS_PATH }}
run: npm run doc
test-matrix-sdk-crypto-js:
name: 🕸 [m]-crypto-js
if: github.event_name == 'push' || !github.event.pull_request.draft
runs-on: ubuntu-latest
steps:
- name: Checkout the repo
uses: actions/checkout@v3
- name: Install Rust
uses: actions-rs/toolchain@v1
with:
toolchain: stable
target: wasm32-unknown-unknown
profile: minimal
override: true
- name: Load cache
uses: Swatinem/rust-cache@v1
- name: Install Node.js
uses: actions/setup-node@v3
with:
node-version: 18.0
- name: Install NPM dependencies
working-directory: ${{ env.MATRIX_SDK_CRYPTO_JS_PATH }}
run: npm install
- name: Build the WebAssembly + JavaScript binding
working-directory: ${{ env.MATRIX_SDK_CRYPTO_JS_PATH }}
run: npm run build
- name: Test the JavaScript binding
working-directory: ${{ env.MATRIX_SDK_CRYPTO_JS_PATH }}
run: npm run test
- name: Build the documentation
working-directory: ${{ env.MATRIX_SDK_CRYPTO_JS_PATH }}
run: npm run doc
test-apple:
name: matrix-rust-components-swift
runs-on: macos-12
if: github.event_name == 'push' || !github.event.pull_request.draft
steps:
- name: Checkout
uses: actions/checkout@v1
- name: Install Rust
uses: actions-rs/toolchain@v1
with:
toolchain: nightly
profile: minimal
override: true
- name: Install targets
run: |
rustup target add aarch64-apple-ios-sim --toolchain nightly
rustup target add x86_64-apple-ios --toolchain nightly
- name: Load cache
uses: Swatinem/rust-cache@v1
- name: Install Uniffi
uses: actions-rs/cargo@v1
with:
command: install
# keep in sync with uniffi dependency in Cargo.toml's
args: uniffi_bindgen --git https://github.com/mozilla/uniffi-rs --rev 091c3561656e72e1a4160412c83b36d98e556d06
- name: Generate .xcframework
working-directory: bindings/apple
run: sh ./debug_build_xcframework.sh x86_64 ci
- name: Run XCTests
working-directory: bindings/apple
run: |
xcodebuild test \
-scheme MatrixRustSDK \
-sdk iphonesimulator \
-destination 'platform=iOS Simulator,name=iPhone 13'
+365 -32
View File
@@ -1,4 +1,4 @@
name: CI
name: Rust tests
on:
workflow_dispatch:
@@ -16,8 +16,46 @@ env:
CARGO_TERM_COLOR: always
jobs:
test-features:
name: linux / features-${{ matrix.name }}
cancel-others:
if: github.event_name == 'pull_request'
runs-on: ubuntu-latest
steps:
- name: Cancel Previous Runs
uses: styfle/cancel-workflow-action@0.9.1
with:
access_token: ${{ github.token }}
xtask:
runs-on: ubuntu-latest
steps:
- name: Checkout repo
uses: actions/checkout@v2
- name: Check xtask cache
uses: actions/cache@v3
id: xtask-cache
with:
path: target/debug/xtask
key: xtask-${{ hashFiles('xtask/**') }}
- name: Install rust stable toolchain
if: steps.xtask-cache.outputs.cache-hit != 'true'
uses: actions-rs/toolchain@v1
with:
profile: minimal
toolchain: stable
override: true
- name: Build
if: steps.xtask-cache.outputs.cache-hit != 'true'
uses: actions-rs/cargo@v1
with:
command: build
args: -p xtask
test-matrix-sdk-features:
name: 🐧 [m], ${{ matrix.name }}
needs: xtask
if: github.event_name == 'push' || !github.event.pull_request.draft
runs-on: ubuntu-latest
@@ -48,58 +86,111 @@ jobs:
- name: Load cache
uses: Swatinem/rust-cache@v1
- name: Install nextest
uses: taiki-e/install-action@nextest
- name: Get xtask
uses: actions/cache@v3
with:
path: target/debug/xtask
key: xtask-${{ hashFiles('xtask/**') }}
- name: Test
uses: actions-rs/cargo@v1
with:
command: run
args: -p xtask -- ci test-features ${{ matrix.name }}
test-crypto-features:
name: linux / crypto-crate features
test-matrix-sdk-examples:
name: 🐧 [m]-examples
needs: xtask
runs-on: ubuntu-latest
if: github.event_name == 'push' || !github.event.pull_request.draft
steps:
- name: Checkout the repo
uses: actions/checkout@v2
- name: Checkout the repo
uses: actions/checkout@v3
- name: Install Rust
uses: actions-rs/toolchain@v1
with:
toolchain: stable
profile: minimal
override: true
- name: Install Rust
uses: actions-rs/toolchain@v1
with:
toolchain: stable
profile: minimal
override: true
- name: Load cache
uses: Swatinem/rust-cache@v1
- name: Load cache
uses: Swatinem/rust-cache@v1
- name: Clippy
uses: actions-rs/cargo@v1
with:
command: run
args: -p xtask -- ci test-crypto
- name: Install nextest
uses: taiki-e/install-action@nextest
test:
- name: Get xtask
uses: actions/cache@v3
with:
path: target/debug/xtask
key: xtask-${{ hashFiles('xtask/**') }}
- name: Test
uses: actions-rs/cargo@v1
with:
command: run
args: -p xtask -- ci examples
test-matrix-sdk-crypto:
name: 🐧 [m]-crypto
needs: xtask
runs-on: ubuntu-latest
if: github.event_name == 'push' || !github.event.pull_request.draft
steps:
- name: Checkout the repo
uses: actions/checkout@v3
- name: Install Rust
uses: actions-rs/toolchain@v1
with:
toolchain: stable
profile: minimal
override: true
- name: Load cache
uses: Swatinem/rust-cache@v1
- name: Install nextest
uses: taiki-e/install-action@nextest
- name: Get xtask
uses: actions/cache@v3
with:
path: target/debug/xtask
key: xtask-${{ hashFiles('xtask/**') }}
- name: Test
uses: actions-rs/cargo@v1
with:
command: run
args: -p xtask -- ci test-crypto
test-all-crates:
name: ${{ matrix.name }}
if: github.event_name == 'push' || !github.event.pull_request.draft
runs-on: ${{ matrix.os || 'ubuntu-latest' }}
runs-on: ${{ matrix.os }}
strategy:
fail-fast: true
matrix:
name:
- linux / stable
- linux / beta
- macOS / stable
include:
- name: linux / stable
- name: 🐧 all crates, 🦀 stable
rust: stable
os: ubuntu-latest
- name: linux / beta
- name: 🐧 all crates, 🦀 beta
rust: beta
os: ubuntu-latest
- name: macOS / stable
os: macOS-latest
- name: 🍏 all crates, 🦀 stable
rust: stable
os: macos-latest
steps:
- name: Checkout
@@ -108,14 +199,256 @@ jobs:
- name: Install Rust
uses: actions-rs/toolchain@v1
with:
toolchain: ${{ matrix.rust || 'stable' }}
toolchain: ${{ matrix.rust }}
profile: minimal
override: true
- name: Load cache
uses: Swatinem/rust-cache@v1
- name: Install nextest
uses: taiki-e/install-action@nextest
- name: Test
uses: actions-rs/cargo@v1
with:
command: nextest
args: run --workspace --exclude matrix-sdk-integration-testing
- name: Test documentation
uses: actions-rs/cargo@v1
with:
command: test
args: --doc
test-wasm:
name: 🕸️ ${{ matrix.name }}
needs: xtask
if: github.event_name == 'push' || !github.event.pull_request.draft
runs-on: ubuntu-latest
strategy:
fail-fast: true
matrix:
include:
- name: '[m]-qrcode'
cmd: matrix-sdk-qrcode
- name: '[m]-base'
cmd: matrix-sdk-base
- name: '[m]-common'
cmd: matrix-sdk-common
- name: '[m]-indexeddb, no crypto'
cmd: indexeddb-no-crypto
- name: '[m]-indexeddb, with crypto'
cmd: indexeddb-with-crypto
- name: '[m], no-default, wasm-flags'
cmd: matrix-sdk-no-default
- name: '[m], indexeddb stores'
cmd: matrix-sdk-indexeddb-stores
- name: '[m], indexeddb stores, no crypto'
cmd: matrix-sdk-indexeddb-stores-no-crypto
- name: '[m], wasm-example'
cmd: matrix-sdk-command-bot
steps:
- name: Checkout the repo
uses: actions/checkout@v3
- name: Install Rust
uses: actions-rs/toolchain@v1
with:
toolchain: stable
target: wasm32-unknown-unknown
components: clippy
profile: minimal
override: true
- name: Install wasm-pack
uses: jetli/wasm-pack-action@v0.3.0
with:
version: latest
- name: Load cache
uses: Swatinem/rust-cache@v1
- name: Install nextest
uses: taiki-e/install-action@nextest
- name: Get xtask
uses: actions/cache@v3
with:
path: target/debug/xtask
key: xtask-${{ hashFiles('xtask/**') }}
- name: Rust Check
uses: actions-rs/cargo@v1
with:
command: run
args: -p xtask -- ci wasm ${{ matrix.cmd }}
- name: Wasm-Pack test
uses: actions-rs/cargo@v1
with:
command: run
args: -p xtask -- ci wasm-pack ${{ matrix.cmd }}
test-appservice:
name: ${{ matrix.os-name }} [m]-appservice
needs: xtask
if: github.event_name == 'push' || !github.event.pull_request.draft
runs-on: ${{ matrix.os }}
strategy:
fail-fast: true
matrix:
include:
- os: ubuntu-latest
os-name: 🐧
- os: macos-latest
os-name: 🍏
steps:
- name: Checkout
uses: actions/checkout@v1
- name: Install Rust
uses: actions-rs/toolchain@v1
with:
toolchain: stable
profile: minimal
override: true
- name: Load cache
uses: Swatinem/rust-cache@v1
- name: Install nextest
uses: taiki-e/install-action@nextest
- name: Get xtask
uses: actions/cache@v3
with:
path: target/debug/xtask
key: xtask-${{ hashFiles('xtask/**') }}
- name: Run checks
uses: actions-rs/cargo@v1
with:
command: run
args: -p xtask -- ci test-appservice
formatting:
name: Check Formatting
runs-on: ubuntu-latest
if: github.event_name == 'push' || !github.event.pull_request.draft
steps:
- name: Checkout the repo
uses: actions/checkout@v3
- name: Install Rust
uses: actions-rs/toolchain@v1
with:
toolchain: nightly
components: rustfmt
profile: minimal
override: true
- name: Cargo fmt
uses: actions-rs/cargo@v1
with:
command: fmt
args: -- --check
typos:
name: Spell Check with Typos
runs-on: ubuntu-latest
if: github.event_name == 'push' || !github.event.pull_request.draft
steps:
- name: Checkout Actions Repository
uses: actions/checkout@v3
- name: Check the spelling of the files in our repo
uses: crate-ci/typos@master
clippy:
name: Run clippy
needs: xtask
runs-on: ubuntu-latest
if: github.event_name == 'push' || !github.event.pull_request.draft
steps:
- name: Checkout the repo
uses: actions/checkout@v3
- name: Install Rust
uses: actions-rs/toolchain@v1
with:
toolchain: nightly
components: clippy
profile: minimal
override: true
- name: Load cache
uses: Swatinem/rust-cache@v1
- name: Get xtask
uses: actions/cache@v3
with:
path: target/debug/xtask
key: xtask-${{ hashFiles('xtask/**') }}
- name: Clippy
uses: actions-rs/cargo@v1
with:
command: run
args: -p xtask -- ci clippy
integration-tests:
name: Integration test
if: github.event_name == 'push' || !github.event.pull_request.draft
runs-on: ubuntu-latest
steps:
- name: Checkout the repo
uses: actions/checkout@v3
- name: Install Rust
uses: actions-rs/toolchain@v1
with:
toolchain: stable
profile: minimal
override: true
- name: Load cache
uses: Swatinem/rust-cache@v1
- name: Install nextest
uses: taiki-e/install-action@nextest
- uses: actions/setup-python@v4
with:
python-version: 3.8
- uses: michaelkaye/setup-matrix-synapse@main
with:
uploadLogs: true
httpPort: 8228
disableRateLimiting: true
- name: Test
uses: actions-rs/cargo@v1
with:
command: nextest
args: run -p matrix-sdk-integration-testing
+17 -2
View File
@@ -13,10 +13,13 @@ jobs:
code_coverage:
name: Code Coverage
runs-on: "ubuntu-latest"
if: github.event_name == 'push' || !github.event.pull_request.draft
steps:
- name: Checkout repository
uses: actions/checkout@v2
uses: actions/checkout@v3
with:
ref: ${{ github.event.pull_request.head.sha }}
- name: Install Rust
uses: actions-rs/toolchain@v1
@@ -34,11 +37,23 @@ jobs:
command: install
args: cargo-tarpaulin
# set up backend for integration tests
- uses: actions/setup-python@v4
with:
python-version: 3.8
- uses: gnunicorn/setup-matrix-synapse@main
with:
uploadLogs: true
httpPort: 8228
disableRateLimiting: true
serverName: "matrix-sdk.rs"
- name: Run tarpaulin
uses: actions-rs/cargo@v1
with:
command: tarpaulin
args: --ignore-config --exclude-files "crates/matrix-sdk/examples/*,crates/matrix-sdk-common,crates/matrix-sdk-test" --out Xml
args: --out Xml
- name: Upload to codecov.io
uses: codecov/codecov-action@v3
-42
View File
@@ -1,42 +0,0 @@
name: Docs
on:
push:
branches: [main]
pull_request:
jobs:
docs:
name: Docs
runs-on: ubuntu-latest
if: github.event_name == 'push' || !github.event.pull_request.draft
steps:
- name: Checkout repository
uses: actions/checkout@v2
- name: Install Rust
uses: actions-rs/toolchain@v1
with:
profile: minimal
toolchain: nightly
override: true
- name: Load cache
uses: Swatinem/rust-cache@v1
# Keep in sync with xtask docs
- name: Build docs
uses: actions-rs/cargo@v1
env:
RUSTDOCFLAGS: "--enable-index-page -Zunstable-options --cfg docsrs -Dwarnings"
with:
command: doc
args: --no-deps --workspace --features docsrs -Zrustdoc-map
- name: Deploy docs
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
uses: peaceiris/actions-gh-pages@v3
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
publish_dir: ./target/doc/
+71
View File
@@ -0,0 +1,71 @@
name: Documentation
on:
push:
branches: [main]
pull_request:
jobs:
docs:
name: All crates
runs-on: ubuntu-latest
if: github.event_name == 'push' || !github.event.pull_request.draft
steps:
- name: Checkout repository
uses: actions/checkout@v3
- name: Install Rust
uses: actions-rs/toolchain@v1
with:
profile: minimal
toolchain: nightly
override: true
- name: Install Node.js
uses: actions/setup-node@v3
with:
node-version: 18
- name: Load cache
uses: Swatinem/rust-cache@v1
# Keep in sync with xtask docs
- name: Build rust documentation
uses: actions-rs/cargo@v1
env:
# Work around https://github.com/rust-lang/cargo/issues/10744
CARGO_TARGET_APPLIES_TO_HOST: "true"
RUSTDOCFLAGS: "--enable-index-page -Zunstable-options --cfg docsrs -Dwarnings"
with:
command: doc
args: --no-deps --features docsrs
- name: Build `matrix-sdk-crypto-nodejs` doc
run: |
cd bindings/matrix-sdk-crypto-nodejs
npm install
npm run build && npm run doc
- name: Build `matrix-sdk-crypto-js` doc
run: |
cd bindings/matrix-sdk-crypto-js
npm install
npm run build && npm run doc
- name: Prepare the doc hierarchy
shell: bash
run: |
mkdir -p doc/bindings/matrix-sdk-crypto-nodejs/
mkdir -p doc/bindings/matrix-sdk-crypto-js/
mv target/doc/* doc/
mv bindings/matrix-sdk-crypto-nodejs/docs/* doc/bindings/matrix-sdk-crypto-nodejs/
mv bindings/matrix-sdk-crypto-js/docs/* doc/bindings/matrix-sdk-crypto-js/
- name: Deploy documentation
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
uses: peaceiris/actions-gh-pages@v3
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
publish_dir: ./doc/
force_orphan: true
@@ -0,0 +1,117 @@
name: Prepare Crypto-Node.js Release
#
# This is a helper workflow to craft a new Node.js release, trigger this via
# the Github Workflow UI by dispatching it manually. Provide the version, the
# matrix-sdk-crypto-nodejs npm package should be set to, and a optionally the
# old version (as used in the git tag) this release should be compared to.
#
# This will then:
# 1. bump the npm version to the one you specified
# 2. commit that change together with the changelog (if it changed, see below)
# 3. create the appropriate tag on that commit
# 4. create the Github draft release, including the changes (if given, see below)
# 5. push these to a new branch, including tag, triggering the `release-crypto-nodejs` workflow
# 6. create a PR to merge these back into `main`
#
# Additionally, if you provide a tag to comapare this tag to, this will:
# 1. create a changelog between the two releases, used for the github release
# 2. update the Changelog.md and include it in the commit
#
# The remaining tasks are done by the release-crypto-nodejs workflow.
on:
workflow_dispatch:
inputs:
version:
description: 'New Node.js SemVer version to create'
required: true
type: string
previous_version:
description: 'Create the changelog by comparing to this old SemVer Version (as used in the tag) '
type: string
env:
PKG_PATH: "bindings/matrix-sdk-crypto-nodejs"
TAG_PREFIX: "matrix-sdk-crypto-nodejs-v"
jobs:
prepare-release:
name: "Preparing crypto-nodejs release tag"
runs-on: ubuntu-latest
outputs:
tag: "${{ env.TAG_PREFIX }}${{ inputs.version }}"
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
# Generate changelog since last tag, if given
- name: Generate a changelog for upload
if: inputs.previous_version
uses: orhun/git-cliff-action@v1
with:
config: "${{ env.PKG_PATH }}/cliff.toml"
args: --strip header "${{env.TAG_PREFIX}}${{ inputs.previous_version }}..HEAD"
env:
GIT_CLIFF_TAG: "Changes ${{ inputs.previous_version }} -> ${{ inputs.version }}"
GIT_CLIFF_OUTPUT: "${{ env.PKG_PATH }}/CHANGES-${{ inputs.version }}.md"
# Update changelog since last tag, if given
- name: Update existing Changelog
if: inputs.previous_version
uses: orhun/git-cliff-action@v1
with:
config: "${{ env.PKG_PATH }}/cliff.toml"
args: "${{ inputs.previous_version }}..HEAD"
env:
GIT_CLIFF_TAG: "${{ inputs.version }}"
GIT_CLIFF_PREPEND: "${{ env.PKG_PATH }}/CHANGELOG.md"
- name: Set version
id: package_version
working-directory: ${{ env.PKG_PATH }}
run: npm version ${{ inputs.version }}
- uses: EndBug/add-and-commit@v9
with:
default_author: github_actions
message: "Tagging Crypto-Node.js for release"
tag: "${{env.TAG_PREFIX}}${{ inputs.version }}"
new_branch: "gh-action/release-${{ env.TAG_PREFIX }}${{ inputs.version }}"
push: true
add: |
${{ env.PKG_PATH }}/package.json
${{ env.PKG_PATH }}/CHANGELOG.md
# if we have generated changes
- name: Update Github Release notes
if: inputs.previous_version
uses: softprops/action-gh-release@v1
with:
draft: true
tag_name: ${{ env.TAG_PREFIX }}${{ inputs.version }}
body_path: "${{ env.PKG_PATH }}/CHANGES-${{ inputs.version }}.md"
# no changes, use the default changelog for the body
- name: Update Github Release notes
if: ${{!inputs.previous_version}}
uses: softprops/action-gh-release@v1
with:
draft: true
tag_name: ${{ env.TAG_PREFIX }}${{ inputs.version }}
body_path: "${{ env.PKG_PATH }}/CHANGELOG.md"
# let's create a PR for all this, too
- name: Create Pull Request
uses: peter-evans/create-pull-request@v4
with:
title: "Preparing Release ${{ env.TAG_PREFIX }}${{ inputs.version }}"
body: |
Automatic Pull-Request to merge release ${{ env.TAG_PREFIX }}${{ inputs.version }}
trigger-release:
# and trigger the tagging release workflow
uses: matrix-org/matrix-rust-sdk/.github/workflows/release-crypto-nodejs.yml@main
needs: ['prepare-release']
name: "Trigger release Workflow"
with:
tag: ${{needs.prepare-release.outputs.tag}}
+139
View File
@@ -0,0 +1,139 @@
name: Release Crypto-Node.js
#
# This workflow releases the crypto-bindings for nodejs
#
# It is triggered when seeing a tag prefixed matching `matrix-sdk-crypto-nodejs-v[0-9]+.*`,
# which then build the native bindings for linux, mac and windows via the CI and uploads
# them to the corresponding Github Release tag. Once they are finished, this workflow will
# package the npm tar.gz and uploads that to the Github Release tag as well, before publishing
# it to npmjs.com automatically.
#
# The usual way to trigger this is by manually triggering the `prep-crypto-nodejs-release`
# workflow. See its documentation for instructions how to use it.
env:
PKG_PATH: "bindings/matrix-sdk-crypto-nodejs"
CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER: 'aarch64-linux-gnu-gcc'
CARGO_TARGET_I686_UNKNOWN_LINUX_GNU_LINKER: 'i686-linux-gnu-gcc'
CARGO_TARGET_ARM_UNKNOWN_LINUX_GNUEABIHF_LINKER: 'arm-linux-gnueabihf-gcc'
on:
push:
tags:
- matrix-sdk-crypto-nodejs-v[0-9]+.*
workflow_call:
inputs:
tag:
description: "The tag to build with"
required: true
type: string
jobs:
upload-assets:
name: "Upload prebuilt libraries"
strategy:
fail-fast: false
matrix:
include:
# ----------------------------------- Linux
- target: x86_64-unknown-linux-gnu
os: ubuntu-latest
- target: i686-unknown-linux-gnu
apt_install: gcc-i686-linux-gnu g++-i686-linux-gnu
os: ubuntu-latest
- target: aarch64-unknown-linux-gnu
os: ubuntu-latest
apt_install: gcc-aarch64-linux-gnu g++-aarch64-linux-gnu
- target: arm-unknown-linux-gnueabihf
os: ubuntu-latest
apt_install: gcc-arm-linux-gnueabihf
- target: x86_64-unknown-linux-musl
os: ubuntu-latest
# ----------------------------------- macOS
- target: aarch64-apple-darwin
os: macos-latest
- target: x86_64-apple-darwin
os: macos-latest
# ----------------------------------- Windows
- target: x86_64-pc-windows-msvc
os: windows-latest
- target: i686-pc-windows-msvc
os: windows-latest
- target: aarch64-pc-windows-msvc
os: windows-latest
runs-on: ${{ matrix.os }}
steps:
# use the given tag
- uses: actions/checkout@v3
name: "Checking out ${{ inputs.tag }}"
if: "${{ inputs.tag }}"
with:
ref: ${{ inputs.tag }}
# use the default
- uses: actions/checkout@v3
if: "${{ !inputs.tag }}"
- name: Install Rust
uses: actions-rs/toolchain@v1
with:
toolchain: nightly
profile: minimal
target: ${{ matrix.target }}
override: true
- name: Install Node.js
uses: actions/setup-node@v3
- name: Load cache
uses: Swatinem/rust-cache@v1
- if: ${{ matrix.apt_install }}
run: |
sudo apt-get update
sudo apt-get install -y ${{ matrix.apt_install }}
- name: Build lib
working-directory: ${{env.PKG_PATH}}
run: |
npm install --ignore-scripts
npx napi build --platform --release --strip --target ${{ matrix.target }}
- name: Upload artifacts to release
uses: softprops/action-gh-release@v1
with:
draft: true
files: ${{env.PKG_PATH}}/*.node
publish-nodejs-package:
name: "Package nodejs package"
runs-on: ubuntu-latest
needs:
- upload-assets
steps:
# use the given tag
- uses: actions/checkout@v3
name: "Checking out ${{ inputs.tag }}"
if: "${{ inputs.tag }}"
with:
ref: ${{ inputs.tag }}
# use the default
- uses: actions/checkout@v3
if: "${{ !inputs.tag }}"
- name: Install Rust
uses: actions-rs/toolchain@v1
with:
toolchain: nightly
profile: minimal
override: true
- name: Install Node.js
uses: actions/setup-node@v3
- name: Build lib
working-directory: ${{env.PKG_PATH}}
run: |
npm install --ignore-scripts
npm run build
npm pack
- name: Upload npm package to release
uses: softprops/action-gh-release@v1
with:
draft: true
files: ${{env.PKG_PATH}}/*tgz
- name: Publish to npmjs.com
uses: JS-DevTools/npm-publish@v1
with:
package: ${{env.PKG_PATH}}/package.json
access: public
token: ${{ secrets.NPM_TOKEN }}
+63
View File
@@ -0,0 +1,63 @@
# This workflow releases the `matrix-sdk-crypto-js` project.
#
# It is triggered when a new tag appears that matches
# `matrix-sdk-crypto-js-v[0-9]+.*`. This workflow builds the package
# for the binding, run its tests to ensure everything is still
# correct, and publish the package on NPM and on a newly created
# Github release.
name: Release `crypto-js`
env:
CARGO_TERM_COLOR: always
PKG_PATH: "bindings/matrix-sdk-crypto-js"
on:
push:
tags:
- matrix-sdk-crypto-js-v[0-9]+.*
jobs:
publish-matrix-sdk-crypto-js:
name: Publish 🕸 [m]-crypto-js
runs-on: ubuntu-latest
steps:
- name: Checkout the repo
uses: actions/checkout@v3
- name: Install Rust
uses: actions-rs/toolchain@v1
with:
toolchain: stable
target: wasm32-unknown-unknown
profile: minimal
override: true
- name: Load cache
uses: Swatinem/rust-cache@v1
- name: Install Node.js
uses: actions/setup-node@v3
with:
node-version: 18.0
- name: Install NPM dependencies
working-directory: ${{ env.PKG_PATH }}
run: npm install
- name: Configure NPM auth token
working-directory: ${{ env.PKG_PATH }}
run: npm set "//registry.npmjs.org/:_authToken" "${{ secrets.NPM_TOKEN }}"
- name: Publish the WebAssembly + JavaScript binding (imply building + testing)
working-directory: ${{ env.PKG_PATH }}
run: npm run publish
- name: Create the Github release
uses: softprops/action-gh-release@v1
with:
draft: true
files: ${{ env.PKG_PATH }}/pkg/matrix-org-matrix-sdk-crypto-js-*.tgz
-105
View File
@@ -1,105 +0,0 @@
name: Style
on:
workflow_dispatch:
push:
branches: [main]
pull_request:
branches: [main]
types:
- opened
- reopened
- synchronize
- ready_for_review
env:
CARGO_TERM_COLOR: always
jobs:
style:
name: Check Formatting
runs-on: ubuntu-latest
if: github.event_name == 'push' || !github.event.pull_request.draft
steps:
- name: Checkout the repo
uses: actions/checkout@v2
- name: Install Rust
uses: actions-rs/toolchain@v1
with:
toolchain: nightly
components: rustfmt
profile: minimal
override: true
- name: Cargo fmt
uses: actions-rs/cargo@v1
with:
command: fmt
args: -- --check
pre-commit-styles:
name: Check Style
if: github.event_name == 'push' || !github.event.pull_request.draft
runs-on: ubuntu-latest
steps:
- name: Checkout Actions Repository
uses: actions/checkout@v2
- name: Install Rust
uses: actions-rs/toolchain@v1
with:
toolchain: nightly
components: clippy
profile: minimal
override: true
- name: Setup Python Env
uses: actions/setup-python@v2
- name: Check Styles with pre-commit
uses: pre-commit/action@v2.0.3
with:
# only run `commit`-hooks, excludes typos, clippy, etc
extra_args: --show-diff-on-failure --hook-stage commit
typos:
name: Spell Check with Typos
needs: [style]
runs-on: ubuntu-latest
if: github.event_name == 'push' || !github.event.pull_request.draft
steps:
- name: Checkout Actions Repository
uses: actions/checkout@v2
- name: Check the spelling of the files in our repo
uses: crate-ci/typos@master
clippy:
name: Run clippy
needs: [style]
runs-on: ubuntu-latest
if: github.event_name == 'push' || !github.event.pull_request.draft
steps:
- name: Checkout the repo
uses: actions/checkout@v2
- name: Install Rust
uses: actions-rs/toolchain@v1
with:
toolchain: nightly
components: clippy
profile: minimal
override: true
- name: Load cache
uses: Swatinem/rust-cache@v1
- name: Clippy
uses: actions-rs/cargo@v1
with:
command: run
args: -p xtask -- ci clippy
-75
View File
@@ -1,75 +0,0 @@
name: WASM
on:
push:
branches: [main]
pull_request:
branches: [main]
types:
- opened
- reopened
- synchronize
- ready_for_review
env:
CARGO_TERM_COLOR: always
jobs:
check-wasm:
name: Build test / ${{ matrix.name }}
runs-on: ubuntu-latest
if: github.event_name == 'push' || !github.event.pull_request.draft
strategy:
fail-fast: true
matrix:
name:
- matrix-sdk-qrcode
- matrix-sdk-base
- matrix-sdk-common
- matrix-sdk-crypto
- indexeddb-no-crypto
- indexeddb-with-crypto
include:
- name: matrix-sdk (no-default, wasm-flags)
cmd: matrix-sdk-no-default
- name: matrix-sdk / indexeddb_stores
cmd: matrix-sdk-indexeddb-stores
- name: matrix-sdk / indexeddb_stores / no crypto
cmd: matrix-sdk-indexeddb-stores-no-crypto
- name: matrix-sdk / wasm-example
cmd: matrix-sdk-command-bot
steps:
- name: Checkout the repo
uses: actions/checkout@v2
- name: Install Rust
uses: actions-rs/toolchain@v1
with:
toolchain: stable
target: wasm32-unknown-unknown
components: clippy
profile: minimal
override: true
- name: Install WasmPack
uses: jetli/wasm-pack-action@v0.3.0
with:
version: 'latest'
- name: Load cache
uses: Swatinem/rust-cache@v1
- name: Rust Check
uses: actions-rs/cargo@v1
with:
command: run
args: -p xtask -- ci wasm ${{ matrix.cmd || matrix.name }}
- name: Wasm-Pack test
uses: actions-rs/cargo@v1
with:
command: run
args: -p xtask -- ci wasm-pack ${{ matrix.cmd || matrix.name }}
+8 -1
View File
@@ -1,6 +1,13 @@
Cargo.lock
target
generated
master.zip
emsdk-*
.idea/
.env
## User settings
xcuserdata/
.vscode/
## OS garbage
.DS_Store
-41
View File
@@ -1,41 +0,0 @@
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.2.0
hooks:
- id: check-yaml
- id: check-toml
- id: end-of-file-fixer
- id: trailing-whitespace
- id: check-merge-conflict
- id: mixed-line-ending
- repo: local
hooks:
- id: fmt
name: fmt
language: system
types: [file, rust]
entry: cargo fmt -- --check
- id: clippy
name: clippy
stages: [push]
language: system
types: [file, rust]
entry: cargo clippy --all-targets --all
pass_filenames: false
- id: test
name: test
stages: [push]
language: system
files: '\.rs$'
entry: cargo test --lib
pass_filenames: false
- id: typos
name: typos
stages: [push]
language: system
entry: typos
pass_filenames: false
+4 -1
View File
@@ -1,7 +1,10 @@
edition = "2018"
max_width = 100
comment_width = 80
wrap_comments = true
imports_granularity = "Crate"
use_small_heuristics = "Max"
group_imports = "StdExternalCrate"
format_code_in_doc_comments = true
doc_comment_code_block_width = 80
# Workaround for https://github.com/rust-lang/rust.vim/issues/464
edition = "2021"
+6
View File
@@ -4,6 +4,12 @@
Fo = "Fo"
BA = "BA"
UE = "UE"
Ure = "Ure"
Ot = "Ot"
# This is the thead html tag, remove this once typos is updated in the github
# action. 1.3.1 seems to work correctly, while 1.11.0 on the CI seems to get
# this wrong
thead = "thead"
[files]
# Our json files contain a bunch of base64 encoded ed25519 keys which aren't
+120
View File
@@ -0,0 +1,120 @@
# Conventional Commits
This project uses [Conventional
Commits](https://www.conventionalcommits.org/). Read the
[Summary](https://www.conventionalcommits.org/en/v1.0.0/#summary) or
the [Full
Specification](https://www.conventionalcommits.org/en/v1.0.0/#specification)
to learn more.
## Types
Conventional Commits defines _type_ (as in `type(scope):
message`). This section aims at listing the types used inside this
project:
| Type | Definition |
|-|-|
| `feat` | About a new feature. |
| `fix` | About a bug fix. |
| `test` | About a test (suite, case, runner…). |
| `doc` | About a documentation modification. |
| `refactor` | About a refactoring. |
| `ci` | About a Continuous Integration modification. |
| `chore` | About some cleanup, or regular tasks. |
## Scopes
Conventional Commits defines _scope_ (as in `type(scope): message`). This
section aims at listing all the scopes used inside this project:
<table>
<thead>
<tr>
<th>Group</th>
<th>Scope</th>
<th>Definition</th>
</tr>
</thead>
<tbody>
<tr>
<td rowspan="10">Crates</td>
<td><code>sdk</code></td>
<td>About the <code>matrix-sdk</code> crate.</td>
</tr>
<tr>
<td><code>appservice</code></td>
<td>About the <code>matrix-sdk-appservice</code> crate.</td>
</tr>
<tr>
<td><code>base</code></td>
<td>About the <code>matrix-sdk-base</code> crate.</td>
</tr>
<tr>
<td><code>common</code></td>
<td>About the <code>matrix-sdk-common</code> crate.</td>
</tr>
<tr>
<td><code>crypto</code></td>
<td>About the <code>matrix-sdk-crypto</code> crate.</td>
</tr>
<tr>
<td><code>indexeddb</code></td>
<td>About the <code>matrix-sdk-indexeddb</code> crate.</td>
</tr>
<tr>
<td><code>qrcode</code></td>
<td>About the <code>matrix-sdk-qrcode</code> crate.</td>
</tr>
<tr>
<td><code>sled</code></td>
<td>About the <code>matrix-sdk-sled</code> crate.</td>
</tr>
<tr>
<td><code>store-encryption</code></td>
<td>About the <code>matrix-sdk-store-encryption</code> crate.</td>
</tr>
<tr>
<td><code>test</code></td>
<td>About the <code>matrix-sdk-test</code> and <code>matrix-sdk-test-macros</code> crate.</td>
</tr>
<tr>
<td rowspan="4">Bindings</td>
<td><code>apple</code></td>
<td>About the <code>matrix-rust-components-swift</code> binding.</td>
</tr>
<tr>
<td><code>crypto-nodejs</code></td>
<td>About the <code>matrix-sdk-crypto-nodejs</code> binding.</td>
</tr>
<tr>
<td><code>crypto-js</code></td>
<td>About the <code>matrix-sdk-crypto-js</code> binding.</td>
</tr>
<tr>
<td><code>crypto-ffi</code></td>
<td>About the <code>matrix-sdk-crypto-ffi</code> binding.</td>
</tr>
<tr>
<td>Labs</td>
<td><code>sled-state-inspector</code></td>
<td>About the <code>sled-state-inspector</code> project.</td>
</tr>
<tr>
<td>Continuous Integration</td>
<td><code>xtask</code></td>
<td>About the <code>xtask</code> project.</td>
</tr>
</tbody>
</table>
## Generating `CHANGELOG.md`
The [`git-cliff`](https://github.com/orhun/git-cliff) project is used
to generate `CHANGELOG.md` automatically. Hence the various
`cliff.toml` files that are present in this project, or the
`package.metadata.git-cliff` sections in various `Cargo.toml` files.
Its companion,
[`git-cliff-action`](https://github.com/orhun/git-cliff-action)
project, is used inside Github Action workflows.
Generated
+5377
View File
File diff suppressed because it is too large Load Diff
+29 -2
View File
@@ -1,4 +1,31 @@
[workspace]
members = ["benchmarks", "crates/*", "labs/*", "xtask"]
# xtask and labs should only be compiled when invoked explicitly
members = [
"benchmarks",
"bindings/matrix-sdk-crypto-ffi",
"bindings/matrix-sdk-crypto-js",
"bindings/matrix-sdk-crypto-nodejs",
"bindings/matrix-sdk-ffi",
"crates/*",
"testing/*",
"examples/*",
"labs/*",
"xtask",
]
# xtask, labs, testing and the bindings should only be built when invoked explicitly.
default-members = ["benchmarks", "crates/*"]
resolver = "2"
[profile.release]
lto = true
[profile.dev]
# Copied from rust-analyzer. Saves a lot of disk space and hopefully
# compilation time / mem usage too, at the expense of potentially having to
# change this setting here when you want to use a debugger.
debug = 0
[profile.dev.package]
# Optimize quote even in debug mode. Speeds up proc-macros enough to account
# for the extra time of optimizing it for a clean build of matrix-sdk-ffi.
quote = { opt-level = 2 }
sha2 = { opt-level = 2 }
+7 -1
View File
@@ -2,7 +2,7 @@
[![codecov](https://img.shields.io/codecov/c/github/matrix-org/matrix-rust-sdk/main.svg?style=flat-square)](https://codecov.io/gh/matrix-org/matrix-rust-sdk)
[![License](https://img.shields.io/badge/License-Apache%202.0-yellowgreen.svg?style=flat-square)](https://opensource.org/licenses/Apache-2.0)
[![#matrix-rust-sdk](https://img.shields.io/badge/matrix-%23matrix--rust--sdk-blue?style=flat-square)](https://matrix.to/#/#matrix-rust-sdk:matrix.org)
[![Docs - Main](https://img.shields.io/badge/docs-main-blue.svg?style=flat-square)](https://matrix-org.github.io/matrix-rust-sdk/)
[![Docs - Main](https://img.shields.io/badge/docs-main-blue.svg?style=flat-square)](https://matrix-org.github.io/matrix-rust-sdk/matrix_sdk/)
[![Docs - Stable](https://img.shields.io/crates/v/matrix-sdk?color=blue&label=docs&style=flat-square)](https://docs.rs/matrix-sdk)
# matrix-rust-sdk
@@ -36,6 +36,12 @@ the API will change in breaking ways.
If you are interested in using the matrix-sdk now is the time to try it out and
provide feedback.
## Bindings
Some crates of the **matrix-rust-sdk** can be embedded inside other
environments, like Swift, Kotlin, JavaScript, Node.js etc. Please,
explore the [`bindings/`](./bindings/) directory to learn more.
## License
[Apache-2.0](https://www.apache.org/licenses/LICENSE-2.0)
-43
View File
@@ -1,43 +0,0 @@
# SDK 0.5 - stores and native crypto
The @matrix-org/rust team is happy to present to the wider public version 0.5 of the [`matrix-rust-sdk`][sdk], now available on crates.io for your convenience. This marks an important milestone after over half a year of work since the latest release (0.4) and with many new team members working on it. It comes with many bug fixes, improvements and updates, but a few we'd like to highlight here:
## Better, safer, native-er crypto
One of the biggest improvements under the hood is the replacement of the former crypto core written in C, libolm, with the fully rustic, fully audited [Vodozemac][vodozemac]. [Vodozemac][vodozemac] is a much more robust new implementation of the olm crypto primitives and engines with all the learning included and pitfalls from the previous C implementation avoided in a freshly baked, very robust library. With this release both matrix-sdk-crypto and matrix-sdk (when the `e2e-encryption` is enabled, which it is by default) use vodozemac to handle all crypto needs.
## Stores, stores, stores
This release has also seen a major refactoring around the state and crypto store primitives and implementations. From this release forward, the implementation of the storage layer is truly modular and pluggable, with the default implementation (based on `sled`) even being a separate crate. Furthermore this release has also additional support for the [`indexeddb`-storage][indexeddb] layer for in-browser WASM needs. As before, the base still ships with an in-memory store, but if none of them fits your needs, you are very much invited to build your own - we recommend looking at the implementation of the existing [`matrix-sdk-sled`][sled] to understand what is needed.
We've further extended and cleaned up the storage API and hardened the two existing implementations: both `sled` and `indexeddb` will now encrypt _all metadata_, including all keys, if a passphrase is given. Even a core dump of a database won't show any strings or other identifiable data. Both implementation also hold a database version string now, allowing future migrations of the database schema while we move forward.
## WebAssembly
It already came through in the previous paragraph: we now fully support `wasm` as a primary target for the main sdk and its dependencies (browser for now). While it was already possible to build the SDK for wasm before, if you were lucky and had the specific emscripten setup, even crypto didn't always fail to compile, our move to vodozemac frees us from these problems and our CI now makes sure all our PRs will continue to build on WebAssembly, too. And with the `indexeddb`-store, we also have a fully persistent storage layer implementation for all your in-browser matrix needs built in.
## More features
Of course a lot more has happened over the last few months as we've ramped up our work on the SDK. Most notably, you can now check whether a room has been created as a `space`, and we offer nice automatic thumbnailing and resizing support if you enable `image`. Additionally, there is a very early event-timeline API behind the `experimental-timeline`-feature-flag. Just to name a few. We really recommend you migrate from the older version to this one.
## Process and Workflow
We've also ramped up our CI, parallelized it a lot, while adding more tests. In general we don't merge anything breaking the tests, thus our `main` can also be considered `stable` to build again, though things might be changed without prior notice. We recommend keeping an eye out in our [team chat][chat] to stay current.
### Versions
This and all future releases of matrix-sdk adhere to [semver][semver] and we do our best to stick to it for the default-feature-set. As you will see only the main crate `matrix-sdk` is actually versioned at `0.5`, while other crates - especially newer ones - have different versions attached. We recommend to sticking to the high-level matrix-sdk-crate wherever reasonable as lower level crates might change more often, also in breaking fashion.
With this release all our crates are build with `rust v2021` and need a rust compiler of at least `1.60` (due to our need for weak-dependencies).
### Conventional Commit
We also want to make it easier for external parties to follow changes and stay up to date with what's-what, so, with this release, we are implementing the [conventional commits][cc] standard for our commits and will start putting in automatic changelog generation. Which makes it easier for us to create comprehensive changelogs for releases, but also for anyone following `main` to figure out what changed.
[sdk]: https://crates.io/crates/matrix-sdk/
[vodozemac]: https://github.com/matrix-org/vodozemac
[sled]: https://crates.io/crates/matrix-sdk-sled/
[indexeddb]: https://crates.io/crates/matrix-sdk-indexeddb/
[chat]: https://matrix.to/#/#matrix-rust-sdk:matrix.org
[semver]: https://semver.org/
[cc]: http://conventionalcommits.org/
+121
View File
@@ -0,0 +1,121 @@
# Upgrades 0.5 ➜ 0.6
This is a rough migration guide to help you upgrade your code using matrix-sdk 0.5 to the newly released matrix-sdk 0.6 . While it won't cover all edge cases and problems, we are trying to get the most common issues covered. If you experience any other difficulties in upgrade or need support with using the matrix-sdk in general, please approach us in our [matrix-sdk channel on matrix.org][matrix-channel].
## Minimum Supported Rust Version Update: `1.60`
We have updated the minimal rust version you need in order to build `matrix-sdk`, as we require some new dependency resolving features from it:
> These crates are built with the Rust language version 2021 and require a minimum compiler version of 1.60
## Dependencies
Many dependencies have been upgraded. Most notably, we are using `ruma` at version `0.7.0` now. It has seen some renamings and restructurings since our last release, so you might find that some Types have new names now.
## Repo Structure Updates
If you are looking at the repository itself, you will find we've rearranged the code quite a bit: we have split out any bindings-specific and testing related crates (and other things) into respective folders, and we've moved all `examples` into its own top-level-folder with each example as their own crate (rendering them easier to find and copy as starting points), all in all slimming down the `crates` folder to the core aspects.
## Architecture Changes / API overall
### Builder Pattern
We are moving to the [builder pattern][] (familiar from e.g. `std::io:process:Command`) as the main configurable path for many aspects of the API, including to construct Matrix-Requests and workflows. This has been and is an on-going effort, and this release sees a lot of APIs transitioning to this pattern, you should already be familiar with from the `matrix_sdk::Client::builder()` in `0.5`. This pattern been extended onto:
- the [login configuration][login builder] and [login with sso][ssologin builder],
- [`SledStore` configuratiion][sled-store builder]
- [`Indexeddb` configuration][indexeddb builder]
Most have fallback (though maybe with deprecation warning) support for an existing code path, but these are likely to be removed in upcoming releases.
### Splitting of concerns: Media
In an effort to declutter the `Client` API dedicated types have been created dealing with specific concerns in one place. In `0.5` we introduced `client.account()`, and `client.encryption()`, we are doing the same with `client.media()` to manage media and attachments in one place with the [`media::Media` type][media typ] now.
The signatures of media uploads, have also changed slightly: rather than expecting a reader `R: Read + Seek`, it now is a simple `&[u8]`. Which also means no more unnecessary `seek(0)` to reset the cursor, as we are just taking an immutable reference now.
### Event Handling & sync updaes
If you are using the `client.register_event_handler` function to receive updates on incoming sync events, you'll find yourself with a deprecation warning now. That is because we've refactored and redesigned the event handler logic to allowing `removing` of event handlers on the fly, too. For that the new `add_event_handler()` (and `add_room_event_handler`) will hand you an `EventHandlerHandle` (pardon the pun), which you can pass to `remove_event_handler`, or by using the convenient `client.event_handler_drop_guard` to create a `DropGuard` that will remove the handler when the guard is dropped. While the code still works, we recommend you switch to the new one, as we will be removing the `register_event_handler` and `register_event_handler_context` in a coming release.
Secondly, you will find a new [`sync_with_result_callback` sync function][sync with result]. Other than the previous sync functions, this will pass the entire `Result` to your callback, allowing you to handle errors or even raise some yourself to stop the loop. Further more, it will propagate any unhandled errors (it still handles retries as before) to the outer caller, allowing the higher level to decide how to handle that (e.g. in case of a network failure). This result-returning-behavior also punshes through the existing `sync` and `sync_with_callback`-API, allowing you to handle them on a higher level now (rather than the futures just resolving). If you find that warning, just adding a `?` to the `.await` of the call is probably the quickest way to move forward.
### Refresh Tokens
This release now [supports `refresh_token`s][refresh tokens PR] as part of the [`Session`][session]. It is implemented with a default-flag in serde so deserializing a previously serialized Session (e.g. in a store) will work as before. As part of `refresh_token` support, you can now configure the client via `ClientBuilder.request_refresh_token()` to refresh the access token automagically on certain failures or do it manually by calling `client.refresh_access_token()` yourself. Auto-refresh is _off_ by default.
You can stay informed about updates on the access token by listening to `client.session_tokens_signal()`.
### Further changes
- [`MessageOptions`][message options] has been updated to Matrix 1.3 by making the `from` parameter optional (and function signatures have been updated, too). You can now request the server sends you messages from the first one you are allowed to have received.
- `client.user_id()` is not a `future` anymore. Remove any `.await` you had behind it.
- `verified()`, `blacklisted()` and `deleted()` on `matrix_sdk::encryption::identities::Device` have been renamed with a `is_` prefix.
- `verified()` on `matrix_sdk::encryption::identities::UserIdentity`, too has been prefixed with `is_` and thus is onw called `is_verified()`.
- The top-level crypto and state-store types of Indexeddb and Sled have been renamed to unique types>
- `state_store` and `crypto_store` do not need to be boxed anymore when passed to the [`StoreConfig`][store config]
- Indexeddb's `SerializationError` is now `IndexedDBStoreError`
- Javascript specific features are now behind the `js` feature-gate
- The new experimental next generation of sync ("sliding sync"), with a totally revamped api, can be found behind the optional `sliding-sync`-feature-gate
## Quick Troubleshooting
You find yourself focussed with any of these, here are the steps to follow to upgrade your code accordingly:
### warning: use of deprecated associated function `matrix_sdk::Client::register_event_handler`: Use [`Client::add_event_handler`](#method.add_event_handler) instead
As it says on the tin: we have deprecated this function in favor of the newer removable handler approach (see above). You can still continue to use this `fn` for now, but it will be removed in a future release.
### warning: use of deprecated associated function `matrix_sdk::Client::login`: Replaced by [`Client::login_username`](#method.login_username)
We have replaced the login facilities with a `LoginBuilder` and recommend you use that from now on. This isn't an error yet, but the function will be removed in a future release.
### expected slice `[u8]`, found struct ...
We've updated the `send_attachment` and `Media` signatures to use `&[u8]` rather than `reader: Read + Seek` as it is more convenient and common place for most architectures anyways. If you are using `File::open(path)?` to get that handler, you can just replace that with `std::fs::read(path)?`
### no method named `verified` found for struct `matrix_sdk::encryption::identities::Device` in the current scope
Boolean flags like `verified`, `deleted`, `blacklisted`, etc have been renamed with a `is_` prefix. So, just follow the cargo suggestion:
```
|
69 | device.verified()
| ^^^^^^^^ help: there is an associated function with a similar name: `is_verified`
```
### unresolved import `matrix_sdk::ruma::events::AnySyncRoomEvent`
Ruma has been updated to `0.7.0`, you will find some ruma Events names have changed, most notably, the `AnySyncRoomEvent` is now named `AnySyncTimelineEvent` (and not `AnySyncStateEvent`, which cargo wrongly suggests). Just rename the import and usage of it.
### `std::option::Option<&matrix_sdk::ruma::UserId>` is not a future
You are seeing something along the lines of:
```
19 | if room_member.state_key != client.user_id().await.unwrap() {
| ^^^^^^ `std::option::Option<&matrix_sdk::ruma::UserId>` is not a future
|
= help: the trait `Future` is not implemented for `std::option::Option<&matrix_sdk::ruma::UserId>`
= note: std::option::Option<&matrix_sdk::ruma::UserId> must be a future or must implement `IntoFuture` to be awaited
= note: required because of the requirements on the impl of `IntoFuture` for `std::option::Option<&matrix_sdk::ruma::UserId>`
help: remove the `.await`
|
19 - if room_member.state_key != client.user_id().await.unwrap() {
19 + if room_member.state_key != client.user_id().unwrap() {
```
You are using `client.user_id().await` but `user_id()` is no longer `async`. Just follow the cargo suggestion and remove the `.await`, it is not necessary any longer.
[matrix-channel]: https://matrix.to/#/#matrix-rust-sdk:matrix.org
[builder pattern]: https://doc.rust-lang.org/1.0.0/style/ownership/builders.html
[login builder]: https://docs.rs/matrix-sdk/latest/matrix_sdk/struct.LoginBuilder.html
[ssologin builder]: https://docs.rs/matrix-sdk/latest/matrix_sdk/struct.SsoLoginBuilder.html
[sled-store builder]: https://docs.rs/matrix-sdk-sled/latest/matrix_sdk_sled/struct.SledStateStoreBuilder.html
[indexeddb builder]: https://docs.rs/matrix-sdk-indexeddb/latest/matrix_sdk_indexeddb/struct.IndexeddbStateStoreBuilder.html
[media type]: https://docs.rs/matrix-sdk/latest/matrix_sdk//media/struct.Media.html
[sync with result]: https://docs.rs/matrix-sdk/latest/matrix_sdk/struct.Client.html#method.sync_with_result_callback
[session]: https://docs.rs/matrix-sdk/latest/matrix_sdk/struct.Session.html
[refresh tokens PR]: https://github.com/matrix-org/matrix-rust-sdk/pull/892
[store config]: https://docs.rs/matrix-sdk-base/latest/matrix_sdk_base/store/struct.StoreConfig.html
[message options]: https://docs.rs/matrix-sdk/latest/matrix_sdk/room/struct.MessagesOptions.html
+5 -5
View File
@@ -9,16 +9,16 @@ publish = false
[dependencies]
criterion = { version = "0.3.5", features = ["async", "async_tokio", "html_reports"] }
matrix-sdk-crypto = { path = "../crates/matrix-sdk-crypto", version = "0.5.0" }
matrix-sdk-sled = { path = "../crates/matrix-sdk-sled", version = "0.1.0", default-features = false, features = ["crypto-store"] }
matrix-sdk-test = { path = "../crates/matrix-sdk-test", version = "0.5.0" }
ruma = "0.6.1"
matrix-sdk-crypto = { path = "../crates/matrix-sdk-crypto", version = "0.6.0"}
matrix-sdk-sled = { path = "../crates/matrix-sdk-sled", version = "0.2.0", default-features = false, features = ["crypto-store"] }
matrix-sdk-test = { path = "../testing/matrix-sdk-test", version = "0.6.0"}
ruma = "0.7.0"
serde_json = "1.0.79"
tempfile = "3.3.0"
tokio = { version = "1.17.0", default-features = false, features = ["rt-multi-thread"] }
[target.'cfg(target_os = "linux")'.dependencies]
pprof = { version = "0.8.0", features = ["flamegraph", "criterion"] }
pprof = { version = "0.10.0", features = ["flamegraph", "criterion"] }
[[bench]]
name = "crypto_bench"
+12 -12
View File
@@ -1,8 +1,8 @@
use std::ops::Deref;
use std::{ops::Deref, sync::Arc};
use criterion::*;
use matrix_sdk_crypto::{EncryptionSettings, OlmMachine};
use matrix_sdk_sled::CryptoStore as SledCryptoStore;
use matrix_sdk_sled::SledCryptoStore;
use matrix_sdk_test::response_from_file;
use ruma::{
api::{
@@ -63,7 +63,7 @@ pub fn keys_query(c: &mut Criterion) {
let mut group = c.benchmark_group("Keys querying");
group.throughput(Throughput::Elements(count as u64));
let name = format!("{} device and cross signing keys", count);
let name = format!("{count} device and cross signing keys");
group.bench_with_input(BenchmarkId::new("memory store", &name), &response, |b, response| {
b.to_async(&runtime)
@@ -71,7 +71,7 @@ pub fn keys_query(c: &mut Criterion) {
});
let dir = tempfile::tempdir().unwrap();
let store = Box::new(SledCryptoStore::open_with_passphrase(dir.path(), None).unwrap());
let store = Arc::new(SledCryptoStore::open_with_passphrase(dir.path(), None).unwrap());
let machine =
runtime.block_on(OlmMachine::with_store(alice_id(), alice_device_id(), store)).unwrap();
@@ -96,7 +96,7 @@ pub fn keys_claiming(c: &mut Criterion) {
let mut group = c.benchmark_group("Olm session creation");
group.throughput(Throughput::Elements(count as u64));
let name = format!("{} one-time keys", count);
let name = format!("{count} one-time keys");
group.bench_with_input(BenchmarkId::new("memory store", &name), &response, |b, response| {
b.iter_batched(
@@ -119,7 +119,7 @@ pub fn keys_claiming(c: &mut Criterion) {
|| {
let dir = tempfile::tempdir().unwrap();
let store =
Box::new(SledCryptoStore::open_with_passphrase(dir.path(), None).unwrap());
Arc::new(SledCryptoStore::open_with_passphrase(dir.path(), None).unwrap());
let machine = runtime
.block_on(OlmMachine::with_store(alice_id(), alice_device_id(), store))
@@ -158,12 +158,12 @@ pub fn room_key_sharing(c: &mut Criterion) {
let mut group = c.benchmark_group("Room key sharing");
group.throughput(Throughput::Elements(count as u64));
let name = format!("{} devices", count);
let name = format!("{count} devices");
group.bench_function(BenchmarkId::new("memory store", &name), |b| {
b.to_async(&runtime).iter(|| async {
let requests = machine
.share_group_session(
.share_room_key(
room_id,
users.iter().map(Deref::deref),
EncryptionSettings::default(),
@@ -181,7 +181,7 @@ pub fn room_key_sharing(c: &mut Criterion) {
})
});
let dir = tempfile::tempdir().unwrap();
let store = Box::new(SledCryptoStore::open_with_passphrase(dir.path(), None).unwrap());
let store = Arc::new(SledCryptoStore::open_with_passphrase(dir.path(), None).unwrap());
let machine =
runtime.block_on(OlmMachine::with_store(alice_id(), alice_device_id(), store)).unwrap();
@@ -191,7 +191,7 @@ pub fn room_key_sharing(c: &mut Criterion) {
group.bench_function(BenchmarkId::new("sled store", &name), |b| {
b.to_async(&runtime).iter(|| async {
let requests = machine
.share_group_session(
.share_room_key(
room_id,
users.iter().map(Deref::deref),
EncryptionSettings::default(),
@@ -225,7 +225,7 @@ pub fn devices_missing_sessions_collecting(c: &mut Criterion) {
let mut group = c.benchmark_group("Devices missing sessions collecting");
group.throughput(Throughput::Elements(count as u64));
let name = format!("{} devices", count);
let name = format!("{count} devices");
runtime.block_on(machine.mark_request_as_sent(&txn_id, &response)).unwrap();
@@ -236,7 +236,7 @@ pub fn devices_missing_sessions_collecting(c: &mut Criterion) {
});
let dir = tempfile::tempdir().unwrap();
let store = Box::new(SledCryptoStore::open_with_passphrase(dir.path(), None).unwrap());
let store = Arc::new(SledCryptoStore::open_with_passphrase(dir.path(), None).unwrap());
let machine =
runtime.block_on(OlmMachine::with_store(alice_id(), alice_device_id(), store)).unwrap();
+22
View File
@@ -0,0 +1,22 @@
# Matrix Rust SDK bindings
In this directory, one can find bindings to the Rust SDK that are
maintained by the owners of the Matrix Rust SDK project.
* [`apple`] or `matrix-rust-components-swift`, Swift bindings of the
[`matrix-sdk`] crate via [`matrix-sdk-ffi`],
* [`matrix-sdk-crypto-ffi`], bindings of the [`matrix-sdk-crypto`]
crate,
* [`matrix-sdk-crypto-js`], JavaScript bindings of the
[`matrix-sdk-crypto`] crate,
* [`matrix-sdk-crypto-nodejs`], Node.js bindings of the
[`matrix-sdk-crypto`] crate,
* [`matrix-sdk-ffi`], bindings of the [`matrix-sdk`] crate,
[`apple`]: ./apple
[`matrix-sdk-crypto-ffi`]: ./matrix-sdk-crypto-ffi
[`matrix-sdk-crypto-js`]: ../crates/matrix-sdk-crypto
[`matrix-sdk-crypto-nodejs`]: ../crates/matrix-sdk-crypto
[`matrix-sdk-crypto`]: ../crates/matrix-sdk-crypto
[`matrix-sdk-ffi`]: ./matrix-sdk-ffi
[`matrix-sdk`]: ../crates/matrix-sdk
+17
View File
@@ -0,0 +1,17 @@
Pod::Spec.new do |s|
s.name = "MatrixSDKCrypto"
s.version = "0.1.0"
s.summary = "Uniffi based bindings for the Rust SDK crypto crate."
s.homepage = "https://github.com/matrix-org/matrix-rust-sdk"
s.license = { :type => "Apache License, Version 2.0", :file => "LICENSE" }
s.author = { "matrix.org" => "support@matrix.org" }
s.ios.deployment_target = "11.0"
s.swift_versions = ['5.0']
s.source = { :http => "https://github.com/matrix-org/matrix-rust-sdk/releases/download/matrix-sdk-crypto-ffi-#{s.version}/MatrixSDKCryptoFFI.zip" }
s.vendored_frameworks = "MatrixSDKCryptoFFI.xcframework"
s.source_files = "Sources/**/*.{swift}"
end
+21
View File
@@ -0,0 +1,21 @@
// swift-tools-version: 5.6
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "MatrixRustSDK",
platforms: [.iOS(.v15)],
products: [
.library(name: "MatrixRustSDK",
targets: ["MatrixRustSDK"]),
],
targets: [
.binaryTarget(name: "MatrixSDKFFI", path: "generated/MatrixSDKFFI.xcframework"),
.target(name: "MatrixRustSDK",
dependencies: [.target(name: "MatrixSDKFFI")],
path: "generated/swift"),
.testTarget(name: "MatrixRustSDKTests",
dependencies: ["MatrixRustSDK"]),
]
)
+53
View File
@@ -0,0 +1,53 @@
# Apple platforms support
This project and build script demonstrate how to create an XCFramework that can be imported into an Xcode project and run on Apple platforms. It can compile and bundle an [entire SDK](#Building-the-SDK), or only a smaller [Crypto module](#Building-only-the-Crypto-SDK) that provides end-to-end encryption for clients that already depend on an SDK (e.g. [Matrix iOS SDK](https://github.com/matrix-org/matrix-ios-sdk))
## Prerequisites for building universal frameworks
* the Rust toolchain
* UniFFI - `cargo install uniffi_bindgen`
* Apple targets (e.g. `rustup target add aarch64-apple-ios`)
* `xcodebuild` command line tool from [Apple](https://developer.apple.com/library/archive/technotes/tn2339/_index.html)
* `lipo` for creating the fat static libs
## Building the SDK
```
sh build_xcframework.sh
```
The `build_xcframework.sh` script will go through all the steps required to generate a fully usable `.xcframework`:
1. compile `matrix-sdk-ffi` libraries for iOS, the iOS simulator, MacOS, and Mac Catalyst under `/target`. Some targets are not part of the standard library and they will be built using the nightly toolchain.
2. `lipo` together the libraries for the same platform under `/generated`
3. run `uniffi` and generate the C header, module map and swift files
4. `xcodebuild` an `xcframework` from the fat static libs and the original iOS one, and add the header and module map to it under `generated/MatrixSDKFFI.xcframework`
5. cleanup and delete the generated files except the .xcframework and the swift sources (that aren't part of the framework)
## Building only the Crypto SDK
```
sh build_crypto_xcframework.sh
```
The `build_crypto_xcframework.sh` script will go through all the steps required to generate a fully usable `.xcframework`:
1. compile `matrix-sdk-crypto-ffi` libraries for iOS and the iOS simulator under `/target`
2. `lipo` together the libraries for the same platform under `/generated`
3. run `uniffi` and generate the C header, module map and swift files
4. `xcodebuild` an `xcframework` from the fat static libs and the original iOS one, and add the header and module map to it under `generated/MatrixSDKCryptoFFI.xcframework`
5. cleanup and delete the generated files except the .xcframework and the swift sources (that aren't part of the framework)
## Running the Xcode project
The Xcode project is meant to provide a simple example on how to integrate everything together but also a place to run unit and integration tests from.
It's pre-configured to link to the generated .xcframework and .swift files so successfully running the script first is necessary for it to compile.
It makes the compiled code available to swift by importing the C header through its bridging header.
Once all the generated components are available running it should be as easy as choosing a platform and clicking run.
## Distribution
The generated framework and Swift code can be distributed and integrated directly but in order to make things simpler we bundle them together as a Swift package available [TBD](here) in the case of SDK, and as CocoaPods podspec in the case of Crypto SDK.
@@ -0,0 +1,50 @@
import XCTest
@testable import MatrixRustSDK
final class ClientTests: XCTestCase {
func testBuildingWithHomeserverURL() {
do {
_ = try ClientBuilder()
.homeserverUrl(url: "https://localhost:8008")
.build()
} catch {
XCTFail("The client should build successfully when given a homeserver.")
}
}
func testBuildingWithUsername() {
do {
_ = try ClientBuilder()
.username(username: "@test:matrix.org")
.build()
} catch {
XCTFail("The client should build successfully when given a username.")
}
}
func testBuildingWithInvalidUsername() {
do {
_ = try ClientBuilder()
.username(username: "@test:invalid")
.build()
XCTFail("The client should not build when given an invalid username.")
} catch ClientError.Generic(let message) {
XCTAssertTrue(message.contains(".well-known"), "The client should fail to do the well-known lookup.")
} catch {
XCTFail("Not expecting any other kind of exception")
}
}
// MARK: - Private
static private var basePath: String {
guard let url = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first else {
fatalError("Should always be able to retrieve the caches directory")
}
try? FileManager.default.createDirectory(at: url, withIntermediateDirectories: false, attributes: nil)
return url.path
}
}
+73
View File
@@ -0,0 +1,73 @@
#!/usr/bin/env bash
set -eEu
cd "$(dirname "$0")"
# Path to the repo root
SRC_ROOT=../..
TARGET_DIR="${SRC_ROOT}/target"
GENERATED_DIR="${SRC_ROOT}/generated"
if [ -d "${GENERATED_DIR}" ]; then rm -rf "${GENERATED_DIR}"; fi
mkdir -p ${GENERATED_DIR}
REL_FLAG="--release"
REL_TYPE_DIR="release"
TARGET_CRATE=matrix-sdk-crypto-ffi
# Build static libs for all the different architectures
# iOS
cargo build -p ${TARGET_CRATE} ${REL_FLAG} --target "aarch64-apple-ios"
# iOS Simulator
cargo build -p ${TARGET_CRATE} ${REL_FLAG} --target "aarch64-apple-ios-sim"
cargo build -p ${TARGET_CRATE} ${REL_FLAG} --target "x86_64-apple-ios"
# Lipo together the libraries for the same platform
# iOS Simulator
lipo -create \
"${TARGET_DIR}/x86_64-apple-ios/${REL_TYPE_DIR}/libmatrix_crypto_ffi.a" \
"${TARGET_DIR}/aarch64-apple-ios-sim/${REL_TYPE_DIR}/libmatrix_crypto_ffi.a" \
-output "${GENERATED_DIR}/libmatrix_crypto_ffi.a"
# Generate uniffi files
uniffi-bindgen generate "${SRC_ROOT}/bindings/${TARGET_CRATE}/src/olm.udl" --language swift --config "${SRC_ROOT}/bindings/${TARGET_CRATE}/uniffi.toml" --out-dir ${GENERATED_DIR}
# Move headers to the right place
HEADERS_DIR=${GENERATED_DIR}/headers
mkdir -p ${HEADERS_DIR}
mv ${GENERATED_DIR}/*.h ${HEADERS_DIR}
# Rename and move modulemap to the right place
mv ${GENERATED_DIR}/*.modulemap ${HEADERS_DIR}/module.modulemap
# Move source files to the right place
SWIFT_DIR="${GENERATED_DIR}/Sources"
mkdir -p ${SWIFT_DIR}
mv ${GENERATED_DIR}/*.swift ${SWIFT_DIR}
# Build the xcframework
if [ -d "${GENERATED_DIR}/MatrixSDKCryptoFFI.xcframework" ]; then rm -rf "${GENERATED_DIR}/MatrixSDKCryptoFFI.xcframework"; fi
xcodebuild -create-xcframework \
-library "${TARGET_DIR}/aarch64-apple-ios/${REL_TYPE_DIR}/libmatrix_crypto_ffi.a" \
-headers ${HEADERS_DIR} \
-library "${GENERATED_DIR}/libmatrix_crypto_ffi.a" \
-headers ${HEADERS_DIR} \
-output "${GENERATED_DIR}/MatrixSDKCryptoFFI.xcframework"
# Cleanup
if [ -f "${TARGET_DIR}/aarch64-apple-ios-sim/${REL_TYPE_DIR}/libmatrix_crypto_ffi.a" ]; then rm -rf "${TARGET_DIR}/aarch64-apple-ios-sim/${REL_TYPE_DIR}/libmatrix_crypto_ffi.a"; fi
if [ -f "${GENERATED_DIR}/libmatrix_crypto_ffi.a" ]; then rm -rf "${GENERATED_DIR}/libmatrix_crypto_ffi.a"; fi
if [ -d ${HEADERS_DIR} ]; then rm -rf ${HEADERS_DIR}; fi
# Zip up framework, sources and LICENSE, ready to be uploaded to GitHub Releases and used by MatrixSDKCrypto.podspec
cp ${SRC_ROOT}/LICENSE $GENERATED_DIR
cd $GENERATED_DIR
zip -r MatrixSDKCryptoFFI.zip MatrixSDKCryptoFFI.xcframework Sources LICENSE
+90
View File
@@ -0,0 +1,90 @@
#!/usr/bin/env bash
set -eEu
cd "$(dirname "$0")"
# Path to the repo root
SRC_ROOT=../..
TARGET_DIR="${SRC_ROOT}/target"
GENERATED_DIR="${SRC_ROOT}/generated"
mkdir -p ${GENERATED_DIR}
REL_FLAG="--release"
REL_TYPE_DIR="release"
# Build static libs for all the different architectures
# iOS
echo -e "Building for iOS [1/5]"
cargo build -p matrix-sdk-ffi ${REL_FLAG} --target "aarch64-apple-ios"
# MacOS
echo -e "\nBuilding for macOS (Apple Silicon) [2/5]"
cargo build -p matrix-sdk-ffi ${REL_FLAG} --target "aarch64-apple-darwin"
echo -e "\nBuilding for macOS (Intel) [3/5]"
cargo build -p matrix-sdk-ffi ${REL_FLAG} --target "x86_64-apple-darwin"
# iOS Simulator
echo -e "\nBuilding for iOS Simulator (Apple Silicon) [4/5]"
cargo build -p matrix-sdk-ffi ${REL_FLAG} --target "aarch64-apple-ios-sim"
echo -e "\nBuilding for iOS Simulator (Intel) [5/5]"
cargo build -p matrix-sdk-ffi ${REL_FLAG} --target "x86_64-apple-ios"
echo -e "\nCreating XCFramework"
# Lipo together the libraries for the same platform
# MacOS
lipo -create \
"${TARGET_DIR}/x86_64-apple-darwin/${REL_TYPE_DIR}/libmatrix_sdk_ffi.a" \
"${TARGET_DIR}/aarch64-apple-darwin/${REL_TYPE_DIR}/libmatrix_sdk_ffi.a" \
-output "${GENERATED_DIR}/libmatrix_sdk_ffi_macos.a"
# iOS Simulator
lipo -create \
"${TARGET_DIR}/x86_64-apple-ios/${REL_TYPE_DIR}/libmatrix_sdk_ffi.a" \
"${TARGET_DIR}/aarch64-apple-ios-sim/${REL_TYPE_DIR}/libmatrix_sdk_ffi.a" \
-output "${GENERATED_DIR}/libmatrix_sdk_ffi_iossimulator.a"
# Generate uniffi files
# Architecture for the .a file argument doesn't matter, since the API is the same on all
uniffi-bindgen generate \
--language swift \
--lib-file "${TARGET_DIR}/x86_64-apple-darwin/${REL_TYPE_DIR}/libmatrix_sdk_ffi.a" \
--out-dir ${GENERATED_DIR} \
"${SRC_ROOT}/bindings/matrix-sdk-ffi/src/api.udl"
# Move them to the right place
HEADERS_DIR=${GENERATED_DIR}/headers
mkdir -p ${HEADERS_DIR}
mv ${GENERATED_DIR}/*.h ${HEADERS_DIR}
# Rename and move modulemap to the right place
mv ${GENERATED_DIR}/*.modulemap ${HEADERS_DIR}/module.modulemap
SWIFT_DIR="${GENERATED_DIR}/swift"
mkdir -p ${SWIFT_DIR}
mv ${GENERATED_DIR}/*.swift ${SWIFT_DIR}
# Build the xcframework
if [ -d "${GENERATED_DIR}/MatrixSDKFFI.xcframework" ]; then rm -rf "${GENERATED_DIR}/MatrixSDKFFI.xcframework"; fi
xcodebuild -create-xcframework \
-library "${GENERATED_DIR}/libmatrix_sdk_ffi_macos.a" \
-headers ${HEADERS_DIR} \
-library "${GENERATED_DIR}/libmatrix_sdk_ffi_iossimulator.a" \
-headers ${HEADERS_DIR} \
-library "${TARGET_DIR}/aarch64-apple-ios/${REL_TYPE_DIR}/libmatrix_sdk_ffi.a" \
-headers ${HEADERS_DIR} \
-output "${GENERATED_DIR}/MatrixSDKFFI.xcframework"
# Cleanup
if [ -f "${GENERATED_DIR}/libmatrix_sdk_ffi_macos.a" ]; then rm -rf "${GENERATED_DIR}/libmatrix_sdk_ffi_macos.a"; fi
if [ -f "${GENERATED_DIR}/libmatrix_sdk_ffi_iossimulator.a" ]; then rm -rf "${GENERATED_DIR}/libmatrix_sdk_ffi_iossimulator.a"; fi
if [ -d ${HEADERS_DIR} ]; then rm -rf ${HEADERS_DIR}; fi
+90
View File
@@ -0,0 +1,90 @@
#!/usr/bin/env bash
set -eEu
cd "$(dirname "$0")"
IS_CI=false
ACTIVE_ARCH="arm64"
if [ $# -eq 2 ]; then
echo "Running CI build"
IS_CI=true
ARCHS=( $1 )
ACTIVE_ARCH=${ARCHS[0]}
elif [ $# -eq 1 ]; then
echo "Running debug build"
ARCHS=( $1 )
ACTIVE_ARCH=${ARCHS[0]}
else
echo "Running debug build"
fi
echo "Active architecture ${ACTIVE_ARCH}"
# Path to the repo root
SRC_ROOT=../..
TARGET_DIR="${SRC_ROOT}/target"
GENERATED_DIR="${SRC_ROOT}/bindings/apple/generated"
mkdir -p ${GENERATED_DIR}
REL_FLAG=""
REL_TYPE_DIR="debug"
# iOS Simulator arm64
if [ "$ACTIVE_ARCH" = "arm64" ]; then
TARGET="aarch64-apple-ios-sim"
# iOS Simulator intel
else
TARGET="x86_64-apple-ios"
fi
cargo build -p matrix-sdk-ffi ${REL_FLAG} --target "$TARGET"
lipo -create \
"${TARGET_DIR}/$TARGET/${REL_TYPE_DIR}/libmatrix_sdk_ffi.a" \
-output "${GENERATED_DIR}/libmatrix_sdk_ffi_iossimulator.a"
# Generate uniffi files
uniffi-bindgen generate \
--language swift \
--lib-file "${TARGET_DIR}/$TARGET/${REL_TYPE_DIR}/libmatrix_sdk_ffi.a" \
--out-dir ${GENERATED_DIR} \
"${SRC_ROOT}/bindings/matrix-sdk-ffi/src/api.udl"
# Move them to the right place
HEADERS_DIR=${GENERATED_DIR}/headers
mkdir -p ${HEADERS_DIR}
mv ${GENERATED_DIR}/*.h ${HEADERS_DIR}
# Rename and move modulemap to the right place
mv ${GENERATED_DIR}/*.modulemap ${HEADERS_DIR}/module.modulemap
SWIFT_DIR="${GENERATED_DIR}/swift"
mkdir -p ${SWIFT_DIR}
mv ${GENERATED_DIR}/*.swift ${SWIFT_DIR}
# Build the xcframework
if [ -d "${GENERATED_DIR}/MatrixSDKFFI.xcframework" ]; then rm -rf "${GENERATED_DIR}/MatrixSDKFFI.xcframework"; fi
xcodebuild -create-xcframework \
-library "${GENERATED_DIR}/libmatrix_sdk_ffi_iossimulator.a" \
-headers ${HEADERS_DIR} \
-output "${GENERATED_DIR}/MatrixSDKFFI.xcframework"
# Cleanup
if [ -f "${GENERATED_DIR}/libmatrix_sdk_ffi_iossimulator.a" ]; then rm -rf "${GENERATED_DIR}/libmatrix_sdk_ffi_iossimulator.a"; fi
if [ -d ${HEADERS_DIR} ]; then rm -rf ${HEADERS_DIR}; fi
if [ "$IS_CI" = false ] ; then
echo "Preparing matrix-rust-components-swift"
# Debug -> Copy generated files over to ../../../matrix-rust-components-swift
rsync -a --delete "${GENERATED_DIR}/MatrixSDKFFI.xcframework" "${SRC_ROOT}/../matrix-rust-components-swift/"
rsync -a --delete "${GENERATED_DIR}/swift/" "${SRC_ROOT}/../matrix-rust-components-swift/Sources/MatrixRustSDK"
fi
@@ -2,7 +2,7 @@
name = "matrix-sdk-crypto-ffi"
version = "0.1.0"
authors = ["Damir Jelić <poljar@termina.org.uk>"]
edition = "2018"
edition = "2021"
rust-version = "1.60"
description = "Uniffi based bindings for the Rust SDK crypto crate"
repository = "https://github.com/matrix-org/matrix-rust-sdk"
@@ -10,8 +10,8 @@ license = "Apache-2.0"
publish = false
[lib]
crate-type = ["cdylib", "lib"]
name = "matrix_crypto"
crate-type = ["cdylib", "staticlib"]
name = "matrix_crypto_ffi"
[dependencies]
anyhow = "1.0.57"
@@ -20,14 +20,15 @@ hmac = "0.12.1"
http = "0.2.6"
pbkdf2 = "0.11.0"
rand = "0.8.5"
ruma = { version = "0.6.1", features = ["client-api-c"] }
ruma = { version = "0.7.0", features = ["client-api-c"] }
serde = "1.0.136"
serde_json = "1.0.79"
sha2 = "0.10.2"
thiserror = "1.0.30"
tracing = "0.1.34"
tracing-subscriber = { version = "0.3.11", features = ["env-filter"] }
uniffi = "0.17.0"
# keep in sync with uniffi dependency in matrix-sdk-ffi, and uniffi_bindgen in ffi CI job
uniffi = { git = "https://github.com/mozilla/uniffi-rs", rev = "091c3561656e72e1a4160412c83b36d98e556d06" }
zeroize = { version = "1.3.0", features = ["zeroize_derive"] }
[dependencies.js_int]
@@ -35,17 +36,17 @@ version = "0.2.2"
features = ["lax_deserialize"]
[dependencies.matrix-sdk-common]
path = "../matrix-sdk-common"
version = "0.5.0"
path = "../../crates/matrix-sdk-common"
version = "0.6.0"
[dependencies.matrix-sdk-crypto]
path = "../matrix-sdk-crypto"
version = "0.5.0"
path = "../../crates/matrix-sdk-crypto"
version = "0.6.0"
features = ["qrcode", "backups_v1"]
[dependencies.matrix-sdk-sled]
path = "../matrix-sdk-sled"
version = "0.1.0"
path = "../../crates/matrix-sdk-sled"
version = "0.2.0"
default_features = false
features = ["crypto-store"]
@@ -55,10 +56,10 @@ default_features = false
features = ["rt-multi-thread"]
[dependencies.vodozemac]
version = "0.2.0"
version = "0.3.0"
[build-dependencies]
uniffi_build = { version = "0.17.0", features = ["builtin-bindgen"] }
uniffi_build = { git = "https://github.com/mozilla/uniffi-rs", rev = "091c3561656e72e1a4160412c83b36d98e556d06", features = ["builtin-bindgen"] }
[dev-dependencies]
tempfile = "3.3.0"
@@ -1,4 +1,4 @@
use std::{collections::HashMap, iter};
use std::{collections::HashMap, iter, ops::DerefMut};
use hmac::Hmac;
use matrix_sdk_crypto::{
@@ -13,8 +13,8 @@ use zeroize::Zeroize;
/// The private part of the backup key, the one used for recovery.
pub struct BackupRecoveryKey {
inner: RecoveryKey,
passphrase_info: Option<PassphraseInfo>,
pub(crate) inner: RecoveryKey,
pub(crate) passphrase_info: Option<PassphraseInfo>,
}
/// Error type for the decryption of backed up room keys.
@@ -101,7 +101,7 @@ impl BackupRecoveryKey {
let mut key = Box::new([0u8; Self::KEY_SIZE]);
let rounds = rounds as u32;
pbkdf2::<Hmac<Sha512>>(passphrase.as_bytes(), salt.as_bytes(), rounds, &mut *key);
pbkdf2::<Hmac<Sha512>>(passphrase.as_bytes(), salt.as_bytes(), rounds, key.deref_mut());
let recovery_key = RecoveryKey::from_bytes(&key);
@@ -14,7 +14,7 @@ mod responses;
mod users;
mod verification;
use std::{collections::HashMap, convert::TryFrom, str::FromStr, sync::Arc};
use std::{borrow::Borrow, collections::HashMap, str::FromStr, sync::Arc};
pub use backup_recovery_key::{
BackupRecoveryKey, DecodeError, MegolmV1BackupKey, PassphraseInfo, PkDecryptionError,
@@ -26,6 +26,7 @@ pub use error::{
use js_int::UInt;
pub use logger::{set_logger, Logger};
pub use machine::{KeyRequestPair, OlmMachine};
use matrix_sdk_crypto::types::{EventEncryptionAlgorithm, SigningKey};
pub use responses::{
BootstrapCrossSigningResult, DeviceLists, KeysImportResult, OutgoingVerificationRequest,
Request, RequestType, SignatureUploadRequest, UploadSigningKeysRequest,
@@ -48,7 +49,7 @@ pub struct MigrationData {
/// The list of Megolm inbound group sessions.
inbound_group_sessions: Vec<PickledInboundGroupSession>,
/// The Olm pickle key that was used to pickle all the Olm objects.
pickle_key: String,
pickle_key: Vec<u8>,
/// The backup version that is currently active.
backup_version: Option<String>,
// The backup recovery key, as a base58 encoded string.
@@ -67,7 +68,7 @@ pub struct MigrationData {
pub struct PickledAccount {
/// The user id of the account owner.
pub user_id: String,
/// The device id of the account owner.
/// The device ID of the account owner.
pub device_id: String,
/// The pickled version of the Olm account.
pub pickle: String,
@@ -161,7 +162,7 @@ pub fn migrate(
olm::PrivateCrossSigningIdentity,
store::{Changes as RustChanges, CryptoStore, RecoveryKey},
};
use matrix_sdk_sled::CryptoStore as SledStore;
use matrix_sdk_sled::SledCryptoStore;
use tokio::runtime::Runtime;
use vodozemac::{
megolm::InboundGroupSession,
@@ -184,13 +185,18 @@ pub fn migrate(
progress_listener.on_progress(progress as i32, total as i32)
};
let store = SledStore::open_with_passphrase(path, passphrase.as_deref())?;
let store = SledCryptoStore::open_with_passphrase(path, passphrase.as_deref())?;
let runtime = Runtime::new()?;
processed_steps += 1;
listener(processed_steps, total_steps);
let user_id: Arc<UserId> = (&*parse_user_id(&data.account.user_id)?).into();
let user_id: Arc<UserId> = {
let user_id: OwnedUserId = parse_user_id(&data.account.user_id)?;
let user_id: &UserId = user_id.borrow();
user_id.into()
};
let device_id: Box<DeviceId> = data.account.device_id.into();
let device_id: Arc<DeviceId> = device_id.into();
@@ -244,19 +250,26 @@ pub fn migrate(
let pickle =
InboundGroupSession::from_libolm_pickle(&session.pickle, &data.pickle_key)?.pickle();
let sender_key = Curve25519PublicKey::from_base64(&session.sender_key)?;
let pickle = matrix_sdk_crypto::olm::PickledInboundGroupSession {
pickle,
sender_key: session.sender_key,
sender_key,
signing_key: session
.signing_key
.into_iter()
.map(|(k, v)| Ok((DeviceKeyAlgorithm::try_from(k)?, v)))
.map(|(k, v)| {
let algorithm = DeviceKeyAlgorithm::try_from(k)?;
let key = SigningKey::from_parts(&algorithm, v)?;
Ok((algorithm, key))
})
.collect::<anyhow::Result<_>>()?,
room_id: RoomId::parse(session.room_id)?,
forwarding_chains: session.forwarding_chains,
imported: session.imported,
backed_up: session.backed_up,
history_visibility: None,
algorithm: EventEncryptionAlgorithm::MegolmV1AesSha2,
};
let session = matrix_sdk_crypto::olm::InboundGroupSession::from_pickle(pickle)?;
@@ -382,9 +395,21 @@ pub struct RoomKeyCounts {
/// Backup keys and information we load from the store.
pub struct BackupKeys {
/// The recovery key as a base64 encoded string.
pub recovery_key: String,
recovery_key: Arc<BackupRecoveryKey>,
/// The version that is used with the recovery key.
pub backup_version: String,
backup_version: String,
}
impl BackupKeys {
/// Get the recovery key that we're holding on to.
pub fn recovery_key(&self) -> Arc<BackupRecoveryKey> {
self.recovery_key.clone()
}
/// Get the backups version that we're holding on to.
pub fn backup_version(&self) -> String {
self.backup_version.to_owned()
}
}
impl TryFrom<matrix_sdk_crypto::store::BackupKeys> for BackupKeys {
@@ -392,7 +417,11 @@ impl TryFrom<matrix_sdk_crypto::store::BackupKeys> for BackupKeys {
fn try_from(keys: matrix_sdk_crypto::store::BackupKeys) -> Result<Self, Self::Error> {
Ok(Self {
recovery_key: keys.recovery_key.ok_or(())?.to_base64(),
recovery_key: BackupRecoveryKey {
inner: keys.recovery_key.ok_or(())?,
passphrase_info: None,
}
.into(),
backup_version: keys.backup_version.ok_or(())?,
})
}
@@ -521,7 +550,9 @@ mod test {
"backed_up":true
}
],
"pickle_key":"\u{0011}$xJ_N8$>{\u{0005}iJoF03eBVt\u{000e}rUU\\,GYc7J",
"pickle_key": [17, 36, 120, 74, 95, 78, 56, 36, 62, 123, 5, 105, 74,
111, 70, 48, 51, 101, 66, 86, 116, 14, 114, 85, 85,
92, 44, 71, 89, 99, 55, 74],
"backup_version":"3",
"backup_recovery_key":"EsTHScmRV5oT1WBhe2mj2Gn3odeYantZ4NEk7L51p6L8hrmB",
"cross_signing":{
@@ -552,7 +583,7 @@ mod test {
"JGgPQRuYj3ScMdPS+A0P+k/1qS9Hr3qeKXLscI+hS78"
);
let room_keys = machine.runtime.block_on(machine.inner.export_keys(|_| true))?;
let room_keys = machine.runtime.block_on(machine.inner.export_room_keys(|_| true))?;
assert_eq!(room_keys.len(), 2);
let cross_signing_status = machine.cross_signing_status();
@@ -1,15 +1,16 @@
use std::{
collections::{BTreeMap, HashMap},
convert::TryInto,
io::Cursor,
ops::Deref,
sync::Arc,
time::Duration,
};
use base64::{decode_config, encode, STANDARD_NO_PAD};
use js_int::UInt;
use matrix_sdk_common::deserialized_responses::AlgorithmInfo;
use matrix_sdk_crypto::{
backups::MegolmV1BackupKey as RustBackupKey, decrypt_key_export, encrypt_key_export,
backups::MegolmV1BackupKey as RustBackupKey, decrypt_room_key_export, encrypt_room_key_export,
matrix_sdk_qrcode::QrVerificationData, olm::ExportedRoomKey, store::RecoveryKey,
EncryptionSettings, LocalTrust, OlmMachine as InnerMachine, UserIdentities,
Verification as RustVerification,
@@ -30,10 +31,8 @@ use ruma::{
},
IncomingResponse,
},
events::{
key::verification::VerificationMethod, room::encrypted::OriginalSyncRoomEncryptedEvent,
AnyMessageLikeEventContent, AnySyncMessageLikeEvent, EventContent,
},
events::{key::verification::VerificationMethod, AnySyncMessageLikeEvent},
serde::Raw,
DeviceKeyAlgorithm, EventId, OwnedTransactionId, OwnedUserId, RoomId, UserId,
};
use serde::{Deserialize, Serialize};
@@ -45,11 +44,11 @@ use crate::{
error::{CryptoStoreError, DecryptionError, SecretImportError, SignatureError},
parse_user_id,
responses::{response_from_string, OutgoingVerificationRequest, OwnedResponse},
BackupKeys, BootstrapCrossSigningResult, ConfirmVerificationResult, CrossSigningKeyExport,
CrossSigningStatus, DecodeError, DecryptedEvent, Device, DeviceLists, KeyImportError,
KeysImportResult, MegolmV1BackupKey, ProgressListener, QrCode, Request, RequestType,
RequestVerificationResult, RoomKeyCounts, ScanResult, SignatureUploadRequest, StartSasResult,
UserIdentity, Verification, VerificationRequest,
BackupKeys, BackupRecoveryKey, BootstrapCrossSigningResult, ConfirmVerificationResult,
CrossSigningKeyExport, CrossSigningStatus, DecodeError, DecryptedEvent, Device, DeviceLists,
KeyImportError, KeysImportResult, MegolmV1BackupKey, ProgressListener, QrCode, Request,
RequestType, RequestVerificationResult, RoomKeyCounts, ScanResult, SignatureUploadRequest,
StartSasResult, UserIdentity, Verification, VerificationRequest,
};
/// A high level state machine that handles E2EE for Matrix.
@@ -92,8 +91,8 @@ impl OlmMachine {
let device_id = device_id.into();
let runtime = Runtime::new().expect("Couldn't create a tokio runtime");
let store = Box::new(
matrix_sdk_sled::CryptoStore::open_with_passphrase(path, passphrase.as_deref())
let store = Arc::new(
matrix_sdk_sled::SledCryptoStore::open_with_passphrase(path, passphrase.as_deref())
.map_err(|e| {
match e {
// This is a bit of an error in the sled store, the
@@ -133,28 +132,53 @@ impl OlmMachine {
}
/// Get a cross signing user identity for the given user ID.
pub fn get_identity(&self, user_id: &str) -> Result<Option<UserIdentity>, CryptoStoreError> {
///
/// # Arguments
///
/// * `user_id` - The unique id of the user that the identity belongs to
///
/// * `timeout` - The time in seconds we should wait before returning if
/// the user's device list has been marked as stale. Passing a 0 as the
/// timeout means that we won't wait at all. **Note**, this assumes that
/// the requests from [`OlmMachine::outgoing_requests`] are being processed
/// and sent out. Namely, this waits for a `/keys/query` response to be
/// received.
pub fn get_identity(
&self,
user_id: &str,
timeout: u32,
) -> Result<Option<UserIdentity>, CryptoStoreError> {
let user_id = parse_user_id(user_id)?;
Ok(if let Some(identity) = self.runtime.block_on(self.inner.get_identity(&user_id))? {
Some(self.runtime.block_on(UserIdentity::from_rust(identity))?)
} else {
None
})
let timeout = if timeout == 0 { None } else { Some(Duration::from_secs(timeout.into())) };
Ok(
if let Some(identity) =
self.runtime.block_on(self.inner.get_identity(&user_id, timeout))?
{
Some(self.runtime.block_on(UserIdentity::from_rust(identity))?)
} else {
None
},
)
}
/// Check if a user identity is considered to be verified by us.
pub fn is_identity_verified(&self, user_id: &str) -> Result<bool, CryptoStoreError> {
let user_id = parse_user_id(user_id)?;
Ok(if let Some(identity) = self.runtime.block_on(self.inner.get_identity(&user_id))? {
match identity {
UserIdentities::Own(i) => i.is_verified(),
UserIdentities::Other(i) => i.verified(),
}
} else {
false
})
Ok(
if let Some(identity) =
self.runtime.block_on(self.inner.get_identity(&user_id, None))?
{
match identity {
UserIdentities::Own(i) => i.is_verified(),
UserIdentities::Other(i) => i.is_verified(),
}
} else {
false
},
)
}
/// Manually the user with the given user ID.
@@ -171,7 +195,7 @@ impl OlmMachine {
pub fn verify_identity(&self, user_id: &str) -> Result<SignatureUploadRequest, SignatureError> {
let user_id = UserId::parse(user_id)?;
let user_identity = self.runtime.block_on(self.inner.get_identity(&user_id))?;
let user_identity = self.runtime.block_on(self.inner.get_identity(&user_id, None))?;
if let Some(user_identity) = user_identity {
Ok(match user_identity {
@@ -191,16 +215,26 @@ impl OlmMachine {
/// * `user_id` - The id of the device owner.
///
/// * `device_id` - The id of the device itself.
///
/// * `timeout` - The time in seconds we should wait before returning if
/// the user's device list has been marked as stale. Passing a 0 as the
/// timeout means that we won't wait at all. **Note**, this assumes that
/// the requests from [`OlmMachine::outgoing_requests`] are being processed
/// and sent out. Namely, this waits for a `/keys/query` response to be
/// received.
pub fn get_device(
&self,
user_id: &str,
device_id: &str,
timeout: u32,
) -> Result<Option<Device>, CryptoStoreError> {
let user_id = parse_user_id(user_id)?;
let timeout = if timeout == 0 { None } else { Some(Duration::from_secs(timeout.into())) };
Ok(self
.runtime
.block_on(self.inner.get_device(&user_id, device_id.into()))?
.block_on(self.inner.get_device(&user_id, device_id.into(), timeout))?
.map(|d| d.into()))
}
@@ -223,7 +257,8 @@ impl OlmMachine {
device_id: &str,
) -> Result<SignatureUploadRequest, SignatureError> {
let user_id = UserId::parse(user_id)?;
let device = self.runtime.block_on(self.inner.get_device(&user_id, device_id.into()))?;
let device =
self.runtime.block_on(self.inner.get_device(&user_id, device_id.into(), None))?;
if let Some(device) = device {
Ok(self.runtime.block_on(device.verify())?.into())
@@ -232,7 +267,7 @@ impl OlmMachine {
}
}
/// Mark the device of the given user with the given device id as trusted.
/// Mark the device of the given user with the given device ID as trusted.
pub fn mark_device_as_trusted(
&self,
user_id: &str,
@@ -240,7 +275,8 @@ impl OlmMachine {
) -> Result<(), CryptoStoreError> {
let user_id = parse_user_id(user_id)?;
let device = self.runtime.block_on(self.inner.get_device(&user_id, device_id.into()))?;
let device =
self.runtime.block_on(self.inner.get_device(&user_id, device_id.into(), None))?;
if let Some(device) = device {
self.runtime.block_on(device.set_local_trust(LocalTrust::Verified))?;
@@ -254,12 +290,24 @@ impl OlmMachine {
/// # Arguments
///
/// * `user_id` - The id of the device owner.
pub fn get_user_devices(&self, user_id: &str) -> Result<Vec<Device>, CryptoStoreError> {
///
/// * `timeout` - The time in seconds we should wait before returning if
/// the user's device list has been marked as stale. Passing a 0 as the
/// timeout means that we won't wait at all. **Note**, this assumes that
/// the requests from [`OlmMachine::outgoing_requests`] are being processed
/// and sent out. Namely, this waits for a `/keys/query` response to be
/// received.
pub fn get_user_devices(
&self,
user_id: &str,
timeout: u32,
) -> Result<Vec<Device>, CryptoStoreError> {
let user_id = parse_user_id(user_id)?;
let timeout = if timeout == 0 { None } else { Some(Duration::from_secs(timeout.into())) };
Ok(self
.runtime
.block_on(self.inner.get_user_devices(&user_id))?
.block_on(self.inner.get_user_devices(&user_id, timeout))?
.devices()
.map(|d| d.into())
.collect())
@@ -424,7 +472,7 @@ impl OlmMachine {
/// [mark_request_as_sent()](#method.mark_request_as_sent) method.
///
/// This method should be called every time before a call to
/// [`share_group_session()`](#method.share_group_session) is made.
/// [`share_room_key()`](#method.share_room_key) is made.
///
/// # Arguments
///
@@ -469,13 +517,13 @@ impl OlmMachine {
users.into_iter().filter_map(|u| UserId::parse(u).ok()).collect();
let room_id = RoomId::parse(room_id)?;
let requests = self.runtime.block_on(self.inner.share_group_session(
let requests = self.runtime.block_on(self.inner.share_room_key(
&room_id,
users.iter().map(Deref::deref),
EncryptionSettings::default(),
))?;
Ok(requests.into_iter().map(|r| (&*r).into()).collect())
Ok(requests.into_iter().map(|r| r.as_ref().into()).collect())
}
/// Encrypt the given event with the given type and content for the given
@@ -493,7 +541,7 @@ impl OlmMachine {
/// method. This method call should be locked per call.
///
/// 2. Share a room key with all the room members using the
/// [`share_group_session()`](#method.share_group_session). This method
/// [`share_room_key()`](#method.share_room_key). This method
/// call should be locked per room.
///
/// 3. Encrypt the event using this method.
@@ -518,12 +566,11 @@ impl OlmMachine {
content: &str,
) -> Result<String, CryptoStoreError> {
let room_id = RoomId::parse(room_id)?;
let content: Box<RawValue> = serde_json::from_str(content)?;
let content: Value = serde_json::from_str(content)?;
let content = AnyMessageLikeEventContent::from_parts(event_type, &content)?;
let encrypted_content = self
.runtime
.block_on(self.inner.encrypt(&room_id, content))
.block_on(self.inner.encrypt_room_event_raw(&room_id, content, event_type))
.expect("Encrypting an event produced an error");
Ok(serde_json::to_string(&encrypted_content)?)
@@ -552,7 +599,7 @@ impl OlmMachine {
content: &'a RawValue,
}
let event: OriginalSyncRoomEncryptedEvent = serde_json::from_str(event)?;
let event: Raw<_> = serde_json::from_str(event)?;
let room_id = RoomId::parse(room_id)?;
let decrypted = self.runtime.block_on(self.inner.decrypt_room_event(&event, &room_id))?;
@@ -563,16 +610,16 @@ impl OlmMachine {
let event_json: Event<'_> = serde_json::from_str(decrypted.event.json().get())?;
Ok(match &encryption_info.algorithm_info {
AlgorithmInfo::MegolmV1AesSha2 {
curve25519_key,
sender_claimed_keys,
forwarding_curve25519_key_chain,
} => DecryptedEvent {
clear_event: serde_json::to_string(&event_json)?,
sender_curve25519_key: curve25519_key.to_owned(),
claimed_ed25519_key: sender_claimed_keys.get(&DeviceKeyAlgorithm::Ed25519).cloned(),
forwarding_curve25519_chain: forwarding_curve25519_key_chain.to_owned(),
},
AlgorithmInfo::MegolmV1AesSha2 { curve25519_key, sender_claimed_keys } => {
DecryptedEvent {
clear_event: serde_json::to_string(&event_json)?,
sender_curve25519_key: curve25519_key.to_owned(),
claimed_ed25519_key: sender_claimed_keys
.get(&DeviceKeyAlgorithm::Ed25519)
.cloned(),
forwarding_curve25519_chain: vec![],
}
}
})
}
@@ -590,7 +637,7 @@ impl OlmMachine {
event: &str,
room_id: &str,
) -> Result<KeyRequestPair, DecryptionError> {
let event: OriginalSyncRoomEncryptedEvent = serde_json::from_str(event)?;
let event: Raw<_> = serde_json::from_str(event)?;
let room_id = RoomId::parse(room_id)?;
let (cancel, request) =
@@ -611,16 +658,20 @@ impl OlmMachine {
///
/// * `rounds` - The number of rounds that should be used when expanding the
/// passphrase into an key.
pub fn export_keys(&self, passphrase: &str, rounds: i32) -> Result<String, CryptoStoreError> {
let keys = self.runtime.block_on(self.inner.export_keys(|_| true))?;
pub fn export_room_keys(
&self,
passphrase: &str,
rounds: i32,
) -> Result<String, CryptoStoreError> {
let keys = self.runtime.block_on(self.inner.export_room_keys(|_| true))?;
let encrypted = encrypt_key_export(&keys, passphrase, rounds as u32)
let encrypted = encrypt_room_key_export(&keys, passphrase, rounds as u32)
.map_err(CryptoStoreError::Serialization)?;
Ok(encrypted)
}
fn import_keys_helper(
fn import_room_keys_helper(
&self,
keys: Vec<ExportedRoomKey>,
from_backup: bool,
@@ -630,7 +681,8 @@ impl OlmMachine {
progress_listener.on_progress(progress as i32, total as i32)
};
let result = self.runtime.block_on(self.inner.import_keys(keys, from_backup, listener))?;
let result =
self.runtime.block_on(self.inner.import_room_keys(keys, from_backup, listener))?;
Ok(KeysImportResult {
imported: result.imported_count as i64,
@@ -658,20 +710,20 @@ impl OlmMachine {
///
/// * `progress_listener` - A callback that can be used to introspect the
/// progress of the key import.
pub fn import_keys(
pub fn import_room_keys(
&self,
keys: &str,
passphrase: &str,
progress_listener: Box<dyn ProgressListener>,
) -> Result<KeysImportResult, KeyImportError> {
let keys = Cursor::new(keys);
let keys = decrypt_key_export(keys, passphrase)?;
self.import_keys_helper(keys, false, progress_listener)
let keys = decrypt_room_key_export(keys, passphrase)?;
self.import_room_keys_helper(keys, false, progress_listener)
}
/// Import room keys from the given serialized unencrypted key export.
///
/// This method is the same as [`OlmMachine::import_keys`] but the
/// This method is the same as [`OlmMachine::import_room_keys`] but the
/// decryption step is skipped and should be performed by the caller. This
/// should be used if the room keys are coming from the server-side backup,
/// the method will mark all imported room keys as backed up.
@@ -682,7 +734,7 @@ impl OlmMachine {
///
/// * `progress_listener` - A callback that can be used to introspect the
/// progress of the key import.
pub fn import_decrypted_keys(
pub fn import_decrypted_room_keys(
&self,
keys: &str,
progress_listener: Box<dyn ProgressListener>,
@@ -691,7 +743,7 @@ impl OlmMachine {
let keys = keys.into_iter().map(serde_json::from_value).filter_map(|k| k.ok()).collect();
self.import_keys_helper(keys, true, progress_listener)
self.import_room_keys_helper(keys, true, progress_listener)
}
/// Discard the currently active room key for the given room if there is
@@ -807,7 +859,7 @@ impl OlmMachine {
) -> Result<Option<String>, CryptoStoreError> {
let user_id = parse_user_id(user_id)?;
let identity = self.runtime.block_on(self.inner.get_identity(&user_id))?;
let identity = self.runtime.block_on(self.inner.get_identity(&user_id, None))?;
let methods = methods.into_iter().map(VerificationMethod::from).collect();
@@ -851,7 +903,7 @@ impl OlmMachine {
let event_id = EventId::parse(event_id)?;
let room_id = RoomId::parse(room_id)?;
let identity = self.runtime.block_on(self.inner.get_identity(&user_id))?;
let identity = self.runtime.block_on(self.inner.get_identity(&user_id, None))?;
let methods = methods.into_iter().map(VerificationMethod::from).collect();
@@ -891,7 +943,7 @@ impl OlmMachine {
Ok(
if let Some(device) =
self.runtime.block_on(self.inner.get_device(&user_id, device_id.into()))?
self.runtime.block_on(self.inner.get_device(&user_id, device_id.into(), None))?
{
let (verification, request) =
self.runtime.block_on(device.request_verification_with_methods(methods));
@@ -916,7 +968,8 @@ impl OlmMachine {
&self,
methods: Vec<String>,
) -> Result<Option<RequestVerificationResult>, CryptoStoreError> {
let identity = self.runtime.block_on(self.inner.get_identity(self.inner.user_id()))?;
let identity =
self.runtime.block_on(self.inner.get_identity(self.inner.user_id(), None))?;
let methods = methods.into_iter().map(VerificationMethod::from).collect();
@@ -1166,7 +1219,7 @@ impl OlmMachine {
Ok(
if let Some(device) =
self.runtime.block_on(self.inner.get_device(&user_id, device_id.into()))?
self.runtime.block_on(self.inner.get_device(&user_id, device_id.into(), None))?
{
let (sas, request) = self.runtime.block_on(device.start_verification())?;
@@ -1192,10 +1245,7 @@ impl OlmMachine {
) -> Option<OutgoingVerificationRequest> {
let user_id = UserId::parse(user_id).ok()?;
self.inner
.get_verification(&user_id, flow_id)
.and_then(|s| s.sas_v1())
.and_then(|s| s.accept().map(|r| r.into()))
self.inner.get_verification(&user_id, flow_id)?.sas_v1()?.accept().map(|r| r.into())
}
/// Get a list of emoji indices of the emoji representation of the short
@@ -1330,22 +1380,35 @@ impl OlmMachine {
Ok(self.runtime.block_on(self.inner.backup_machine().room_key_counts())?.into())
}
/// Store the recovery key in the cryptostore.
/// Store the recovery key in the crypto store.
///
/// This is useful if the client wants to support gossiping of the backup
/// key.
pub fn save_recovery_key(
&self,
key: Option<String>,
key: Option<Arc<BackupRecoveryKey>>,
version: Option<String>,
) -> Result<(), CryptoStoreError> {
let key = key.map(|k| RecoveryKey::from_base64(&k)).transpose().ok().flatten();
let key = key.map(|k| {
// We need to clone here due to FFI limitations but RecoveryKey does
// not want to expose clone since it's private key material.
let mut encoded = k.to_base64();
let key = RecoveryKey::from_base64(&encoded)
.expect("Encoding and decoding from base64 should always work");
encoded.zeroize();
key
});
Ok(self.runtime.block_on(self.inner.backup_machine().save_recovery_key(key, version))?)
}
/// Get the backup keys we have saved in our crypto store.
pub fn get_backup_keys(&self) -> Result<Option<BackupKeys>, CryptoStoreError> {
Ok(self.runtime.block_on(self.inner.backup_machine().get_backup_keys())?.try_into().ok())
pub fn get_backup_keys(&self) -> Result<Option<Arc<BackupKeys>>, CryptoStoreError> {
Ok(self
.runtime
.block_on(self.inner.backup_machine().get_backup_keys())?
.try_into()
.ok()
.map(Arc::new))
}
/// Sign the given message using our device key and if available cross
@@ -1354,14 +1417,46 @@ impl OlmMachine {
self.runtime
.block_on(self.inner.sign(message))
.into_iter()
.map(|(k, v)| (k.to_string(), v.into_iter().map(|(k, v)| (k.to_string(), v)).collect()))
.map(|(k, v)| {
(
k.to_string(),
v.into_iter()
.map(|(k, v)| {
(
k.to_string(),
match v {
Ok(s) => s.to_base64(),
Err(i) => i.source,
},
)
})
.collect(),
)
})
.collect()
}
/// Check if the given backup has been verified by us or by another of our
/// devices that we trust.
pub fn verify_backup(&self, auth_data: &str) -> Result<bool, CryptoStoreError> {
let auth_data = serde_json::from_str(auth_data)?;
Ok(self.runtime.block_on(self.inner.backup_machine().verify_backup(auth_data))?)
///
/// The `backup_info` should be a JSON encoded object with the following
/// format:
///
/// ```json
/// {
/// "algorithm": "m.megolm_backup.v1.curve25519-aes-sha2",
/// "auth_data": {
/// "public_key":"XjhWTCjW7l59pbfx9tlCBQolfnIQWARoKOzjTOPSlWM",
/// "signatures": {}
/// }
/// }
/// ```
pub fn verify_backup(&self, backup_info: &str) -> Result<bool, CryptoStoreError> {
let backup_info = serde_json::from_str(backup_info)?;
Ok(self
.runtime
.block_on(self.inner.backup_machine().verify_backup(backup_info, false))?
.trusted())
}
}
@@ -15,7 +15,7 @@ interface MigrationError {
};
callback interface Logger {
void log(string log_line);
void log(string logLine);
};
callback interface ProgressListener {
@@ -280,17 +280,17 @@ interface OlmMachine {
string encrypt([ByRef] string room_id, [ByRef] string event_type, [ByRef] string content);
[Throws=CryptoStoreError]
UserIdentity? get_identity([ByRef] string user_id);
UserIdentity? get_identity([ByRef] string user_id, u32 timeout);
[Throws=SignatureError]
SignatureUploadRequest verify_identity([ByRef] string user_id);
[Throws=CryptoStoreError]
Device? get_device([ByRef] string user_id, [ByRef] string device_id);
Device? get_device([ByRef] string user_id, [ByRef] string device_id, u32 timeout);
[Throws=CryptoStoreError]
void mark_device_as_trusted([ByRef] string user_id, [ByRef] string device_id);
[Throws=SignatureError]
SignatureUploadRequest verify_device([ByRef] string user_id, [ByRef] string device_id);
[Throws=CryptoStoreError]
sequence<Device> get_user_devices([ByRef] string user_id);
sequence<Device> get_user_devices([ByRef] string user_id, u32 timeout);
[Throws=CryptoStoreError]
boolean is_user_tracked([ByRef] string user_id);
@@ -358,15 +358,15 @@ interface OlmMachine {
KeyRequestPair request_room_key([ByRef] string event, [ByRef] string room_id);
[Throws=CryptoStoreError]
string export_keys([ByRef] string passphrase, i32 rounds);
string export_room_keys([ByRef] string passphrase, i32 rounds);
[Throws=KeyImportError]
KeysImportResult import_keys(
KeysImportResult import_room_keys(
[ByRef] string keys,
[ByRef] string passphrase,
ProgressListener progress_listener
);
[Throws=KeyImportError]
KeysImportResult import_decrypted_keys(
KeysImportResult import_decrypted_room_keys(
[ByRef] string keys,
ProgressListener progress_listener
);
@@ -390,7 +390,7 @@ interface OlmMachine {
[Throws=CryptoStoreError]
Request? backup_room_keys();
[Throws=CryptoStoreError]
void save_recovery_key(string? key, string? version);
void save_recovery_key(BackupRecoveryKey? key, string? version);
[Throws=CryptoStoreError]
RoomKeyCounts room_key_counts();
[Throws=CryptoStoreError]
@@ -412,9 +412,9 @@ dictionary MegolmV1BackupKey {
string backup_algorithm;
};
dictionary BackupKeys {
string recovery_key;
string backup_version;
interface BackupKeys {
BackupRecoveryKey recovery_key();
string backup_version();
};
dictionary RoomKeyCounts {
@@ -451,7 +451,7 @@ dictionary MigrationData {
sequence<PickledInboundGroupSession> inbound_group_sessions;
string? backup_version;
string? backup_recovery_key;
string pickle_key;
sequence<u8> pickle_key;
CrossSigningKeyExport cross_signing;
sequence<string> tracked_users;
};
@@ -132,6 +132,7 @@ impl From<OutgoingRequest> for Request {
let body = json!({
"device_keys": u.device_keys,
"one_time_keys": u.one_time_keys,
"fallback_keys": u.fallback_keys,
});
Request::KeysUpload {
@@ -0,0 +1,2 @@
[bindings.swift]
module_name = "MatrixSDKCrypto"
@@ -0,0 +1,2 @@
[build]
target = "wasm32-unknown-unknown"
+3
View File
@@ -0,0 +1,3 @@
/docs
/node_modules
/package-lock.json
+45
View File
@@ -0,0 +1,45 @@
[package]
name = "matrix-sdk-crypto-js"
description = "Matrix encryption library, for JavaScript"
authors = ["Ivan Enderlin <ivane@element.io>"]
edition = "2021"
homepage = "https://github.com/matrix-org/matrix-rust-sdk"
keywords = ["matrix", "chat", "messaging", "ruma", "nio"]
license = "Apache-2.0"
readme = "README.md"
repository = "https://github.com/matrix-org/matrix-rust-sdk"
rust-version = "1.60"
version = "0.1.0-alpha.0"
publish = false
[package.metadata.docs.rs]
rustdoc-args = ["--cfg", "docsrs"]
[package.metadata.wasm-pack.profile.release]
wasm-opt = ['-Oz']
[lib]
crate-type = ["cdylib"]
[features]
default = ["tracing", "qrcode"]
qrcode = ["matrix-sdk-crypto/qrcode", "dep:matrix-sdk-qrcode"]
tracing = []
[dependencies]
matrix-sdk-common = { version = "0.6.0", path = "../../crates/matrix-sdk-common", features = ["js"] }
matrix-sdk-crypto = { version = "0.6.0", path = "../../crates/matrix-sdk-crypto", features = ["js"] }
matrix-sdk-indexeddb = { version = "0.2.0", path = "../../crates/matrix-sdk-indexeddb", features = ["experimental-nodejs"] }
matrix-sdk-qrcode = { version = "0.4.0", path = "../../crates/matrix-sdk-qrcode", optional = true }
ruma = { version = "0.7.0", features = ["client-api-c", "js", "rand", "unstable-msc2676", "unstable-msc2677"] }
vodozemac = { version = "0.3.0", features = ["js"] }
wasm-bindgen = "0.2.80"
wasm-bindgen-futures = "0.4.30"
js-sys = "0.3.49"
console_error_panic_hook = "0.1.7"
serde_json = "1.0.79"
http = "0.2.6"
anyhow = "1.0.58"
tracing = { version = "0.1.35", default-features = false, features = ["attributes"] }
tracing-subscriber = { version = "0.3.14", default-features = false, features = ["registry", "std"] }
zeroize = "1.3.0"
+59
View File
@@ -0,0 +1,59 @@
# `matrix-sdk-crypto-js`
Welcome to the [WebAssembly] + JavaScript binding for the Rust
[`matrix-sdk-crypto`] library! WebAssembly can run anywhere, but these
bindings are designed to run on a JavaScript host. These bindings are
part of the [`matrix-rust-sdk`] project, which is a library
implementation of a [Matrix] client-server.
`matrix-sdk-crypto` is a no-network-IO implementation of a state
machine, named `OlmMachine`, that handles E2EE ([End-to-End
Encryption](https://en.wikipedia.org/wiki/End-to-end_encryption)) for
[Matrix] clients.
## Usage
These WebAssembly bindings are written in [Rust]. To build them, you
need to install the Rust compiler, see [the Install Rust
Page](https://www.rust-lang.org/tools/install). Then, the workflow is
pretty classical by using [npm], see [the Downloading and installing
Node.js and npm
Page](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm).
Once the Rust compiler, Node.js and npm are installed, you can run the
following commands:
```sh
$ npm install
$ npm run build
$ npm run test
```
A `matrix_sdk_crypto.js`, `matrix_sdk_crypto.d.ts` and a
`matrix_sdk_crypto_bg.wasm` files should be generated in the `pkg/`
directory.
TBD
## Documentation
[The documentation can be found
online](https://matrix-org.github.io/matrix-rust-sdk/bindings/matrix-sdk-crypto-js/).
To generate the documentation locally, please run the following
command:
```sh
$ npm run doc
```
The documentation is generated in the `./docs` directory.
[WebAssembly]: https://webassembly.org/
[`matrix-sdk-crypto`]: https://github.com/matrix-org/matrix-rust-sdk/tree/main/crates/matrix-sdk-crypto
[`matrix-rust-sdk`]: https://github.com/matrix-org/matrix-rust-sdk
[Matrix]: https://matrix.org/
[Rust]: https://www.rust-lang.org/
[npm]: https://www.npmjs.com/
+61
View File
@@ -0,0 +1,61 @@
# configuration file for git-cliff (0.1.0)
[changelog]
# changelog header
header = """
# Matrix SDK Crypto JavaScript Changelog\n
All notable changes to this project will be documented in this file.\n
"""
# template for the changelog body
# https://tera.netlify.app/docs/#introduction
body = """
{% if version %}\
## [{{ version | trim_start_matches(pat="v") }}] - {{ timestamp | date(format="%Y-%m-%d") }}
{% else %}\
## [unreleased]
{% endif %}\
{% for group, commits in commits | filter(attribute="scope", value="crypto-js") | group_by(attribute="group") %}
### {{ group | upper_first }}
{% for commit in commits %}
- {% if commit.breaking %}[**breaking**] {% endif %}{{ commit.message | upper_first }}\
{% endfor %}
{% endfor %}\n
"""
# remove the leading and trailing whitespace from the template
trim = true
# changelog footer
footer = """
"""
[git]
# parse the commits based on https://www.conventionalcommits.org
conventional_commits = true
# filter out the commits that are not conventional
filter_unconventional = true
# regex for preprocessing the commit messages
commit_preprocessors = [
{ pattern = '\((\w+\s)?#([0-9]+)\)', replace = "([#${2}](https://github.com/matrix-org/matrix-rust-sdk/issues/${2}))"},
]
# regex for parsing and grouping commits
commit_parsers = [
{ message = "^feat", group = "Features"},
{ message = "^fix", group = "Bug Fixes"},
{ message = "^test", group = "Testing"},
{ message = "^doc", group = "Documentation"},
{ message = "^refactor", group = "Refactoring"},
{ message = "^ci", group = "Continuous Integration"},
{ message = "^chore", group = "Miscellaneous Tasks"},
{ body = ".*security", group = "Security"},
]
# filter out the commits that are not matched by commit parsers
filter_commits = false
# glob pattern for matching git tags
tag_pattern = "v[0-9]*"
# regex for skipping tags
skip_tags = ""
# regex for ignoring tags
ignore_tags = ""
# sort the tags chronologically
date_order = false
# sort the commits inside sections by oldest/newest order
sort_commits = "oldest"
@@ -0,0 +1,48 @@
{
"name": "@matrix-org/matrix-sdk-crypto-js",
"version": "0.1.0-alpha.0",
"homepage": "https://github.com/matrix-org/matrix-rust-sdk",
"description": "Matrix encryption library, for JavaScript",
"license": "Apache-2.0",
"collaborators": [
"Ivan Enderlin <ivane@element.io>"
],
"repository": {
"type": "git",
"url": "https://github.com/matrix-org/matrix-rust-sdk"
},
"keywords": [
"matrix",
"chat",
"messaging",
"ruma",
"nio"
],
"main": "matrix_sdk_crypto.js",
"types": "pkg/matrix_sdk_crypto.d.ts",
"files": [
"pkg/matrix_sdk_crypto_bg.wasm",
"pkg/matrix_sdk_crypto.js",
"pkg/matrix_sdk_crypto.d.ts"
],
"devDependencies": {
"cross-env": "^7.0.3",
"fake-indexeddb": "^4.0",
"jest": "^28.1.0",
"typedoc": "^0.22.17",
"wasm-pack": "^0.10.2",
"yargs-parser": "~21.0.1"
},
"engines": {
"node": ">= 10"
},
"scripts": {
"build": "cross-env RUSTFLAGS='-C opt-level=z' wasm-pack build --release --target nodejs --scope matrix-org --out-dir ./pkg",
"test": "jest --verbose",
"doc": "typedoc --tsconfig .",
"prepack": "npm run build && npm run test",
"pack": "wasm-pack pack",
"prepublish": "npm run pack",
"publish": "wasm-pack publish"
}
}
@@ -0,0 +1,124 @@
//! Attachment API.
use std::io::{Cursor, Read};
use wasm_bindgen::prelude::*;
/// A type to encrypt and to decrypt anything that can fit in an
/// `Uint8Array`, usually big buffer.
#[wasm_bindgen]
#[derive(Debug)]
pub struct Attachment;
#[wasm_bindgen]
impl Attachment {
/// Encrypt the content of the `Uint8Array`.
///
/// It produces an `EncryptedAttachment`, which can be used to
/// retrieve the media encryption information, or the encrypted
/// data.
#[wasm_bindgen]
pub fn encrypt(array: &[u8]) -> Result<EncryptedAttachment, JsError> {
let mut cursor = Cursor::new(array);
let mut encryptor = matrix_sdk_crypto::AttachmentEncryptor::new(&mut cursor);
let mut encrypted_data = Vec::new();
encryptor.read_to_end(&mut encrypted_data)?;
let media_encryption_info = Some(encryptor.finish());
Ok(EncryptedAttachment { encrypted_data, media_encryption_info })
}
/// Decrypt an `EncryptedAttachment`.
///
/// The encrypted attachment can be created manually, or from the
/// `encrypt` method.
///
/// **Warning**: The encrypted attachment can be used only
/// **once**! The encrypted data will still be present, but the
/// media encryption info (which contain secrets) will be
/// destroyed. It is still possible to get a JSON-encoded backup
/// by calling `EncryptedAttachment.mediaEncryptionInfo`.
pub fn decrypt(attachment: &mut EncryptedAttachment) -> Result<Vec<u8>, JsError> {
let media_encryption_info = match attachment.media_encryption_info.take() {
Some(media_encryption_info) => media_encryption_info,
None => {
return Err(JsError::new(
"The media encryption info are absent from the given encrypted attachment",
))
}
};
let encrypted_data: &[u8] = attachment.encrypted_data.as_slice();
let mut cursor = Cursor::new(encrypted_data);
let mut decryptor =
matrix_sdk_crypto::AttachmentDecryptor::new(&mut cursor, media_encryption_info)?;
let mut decrypted_data = Vec::new();
decryptor.read_to_end(&mut decrypted_data)?;
Ok(decrypted_data)
}
}
/// An encrypted attachment, usually created from `Attachment.encrypt`.
#[wasm_bindgen]
#[derive(Debug)]
pub struct EncryptedAttachment {
media_encryption_info: Option<matrix_sdk_crypto::MediaEncryptionInfo>,
encrypted_data: Vec<u8>,
}
#[wasm_bindgen]
impl EncryptedAttachment {
/// Create a new encrypted attachment manually.
///
/// It needs encrypted data, stored in an `Uint8Array`, and a
/// [media encryption
/// information](https://docs.rs/matrix-sdk-crypto/latest/matrix_sdk_crypto/struct.MediaEncryptionInfo.html),
/// as a JSON-encoded string.
///
/// The media encryption information aren't stored as a string:
/// they are parsed, validated and fully deserialized.
///
/// See [the specification to learn
/// more](https://spec.matrix.org/unstable/client-server-api/#extensions-to-mroommessage-msgtypes).
#[wasm_bindgen(constructor)]
pub fn new(
encrypted_data: Vec<u8>,
media_encryption_info: &str,
) -> Result<EncryptedAttachment, JsError> {
Ok(Self {
encrypted_data,
media_encryption_info: Some(serde_json::from_str(media_encryption_info)?),
})
}
/// The actual encrypted data.
///
/// **Warning**: It returns a **copy** of the entire encrypted
/// data; be nice with your memory.
#[wasm_bindgen(getter, js_name = "encryptedData")]
pub fn encrypted_data(&self) -> Vec<u8> {
self.encrypted_data.clone()
}
/// Return the media encryption info as a JSON-encoded string. The
/// structure is fully valid.
///
/// If the media encryption info have been consumed already, it
/// will return `null`.
#[wasm_bindgen(getter, js_name = "mediaEncryptionInfo")]
pub fn media_encryption_info(&self) -> Option<String> {
serde_json::to_string(self.media_encryption_info.as_ref()?).ok()
}
/// Check whether the media encryption info has been consumed by
/// `Attachment.decrypt` already.
#[wasm_bindgen(getter, js_name = "hasMediaEncryptionInfoBeenConsumed")]
pub fn has_media_encryption_info_been_consumed(&self) -> bool {
self.media_encryption_info.is_none()
}
}
+249
View File
@@ -0,0 +1,249 @@
//! Types for a `Device`.
use js_sys::{Array, Map, Promise};
use wasm_bindgen::prelude::*;
use crate::{
future::future_to_promise,
identifiers::{self, DeviceId, UserId},
impl_from_to_inner,
js::try_array_to_vec,
types, verification, vodozemac,
};
/// A device represents a E2EE capable client of an user.
#[wasm_bindgen]
#[derive(Debug)]
pub struct Device {
pub(crate) inner: matrix_sdk_crypto::Device,
}
impl_from_to_inner!(matrix_sdk_crypto::Device => Device);
#[wasm_bindgen]
impl Device {
/// Request an interactive verification with this device.
#[wasm_bindgen(js_name = "requestVerification")]
pub fn request_verification(&self, methods: Option<Array>) -> Result<Promise, JsError> {
let methods =
methods.map(try_array_to_vec::<verification::VerificationMethod, _>).transpose()?;
let me = self.inner.clone();
Ok(future_to_promise(async move {
let tuple = Array::new();
let (verification_request, outgoing_verification_request) = match methods {
Some(methods) => me.request_verification_with_methods(methods).await,
None => me.request_verification().await,
};
tuple.set(0, verification::VerificationRequest::from(verification_request).into());
tuple.set(
1,
verification::OutgoingVerificationRequest::from(outgoing_verification_request)
.try_into()?,
);
Ok(tuple)
}))
}
/// Is this device considered to be verified.
///
/// This method returns true if either the `is_locally_trusted`
/// method returns `true` or if the `is_cross_signing_trusted`
/// method returns `true`.
#[wasm_bindgen(js_name = "isVerified")]
pub fn is_verified(&self) -> bool {
self.inner.is_verified()
}
/// Is this device considered to be verified using cross signing.
#[wasm_bindgen(js_name = "isCrossSigningTrusted")]
pub fn is_cross_signing_trusted(&self) -> bool {
self.inner.is_cross_signing_trusted()
}
/// Set the local trust state of the device to the given state.
///
/// This wont affect any cross signing trust state, this only
/// sets a flag marking to have the given trust state.
///
/// `trust_state` represents the new trust state that should be
/// set for the device.
#[wasm_bindgen(js_name = "setLocalTrust")]
pub fn set_local_trust(&self, local_state: LocalTrust) -> Promise {
let me = self.inner.clone();
future_to_promise(async move {
me.set_local_trust(local_state.into()).await?;
Ok(JsValue::NULL)
})
}
/// The user ID of the device owner.
#[wasm_bindgen(getter, js_name = "userId")]
pub fn user_id(&self) -> UserId {
self.inner.user_id().to_owned().into()
}
/// The unique ID of the device.
#[wasm_bindgen(getter, js_name = "deviceId")]
pub fn device_id(&self) -> DeviceId {
self.inner.device_id().to_owned().into()
}
/// Get the human readable name of the device.
#[wasm_bindgen(getter, js_name = "displayName")]
pub fn display_name(&self) -> Option<String> {
self.inner.display_name().map(ToOwned::to_owned)
}
/// Get the key of the given key algorithm belonging to this device.
#[wasm_bindgen(js_name = "getKey")]
pub fn get_key(
&self,
algorithm: identifiers::DeviceKeyAlgorithmName,
) -> Result<Option<vodozemac::DeviceKey>, JsError> {
Ok(self.inner.get_key(algorithm.try_into()?).cloned().map(Into::into))
}
/// Get the Curve25519 key of the given device.
#[wasm_bindgen(getter, js_name = "curve25519Key")]
pub fn curve25519_key(&self) -> Option<vodozemac::Curve25519PublicKey> {
self.inner.curve25519_key().map(Into::into)
}
/// Get the Ed25519 key of the given device.
#[wasm_bindgen(getter, js_name = "ed25519Key")]
pub fn ed25519_key(&self) -> Option<vodozemac::Ed25519PublicKey> {
self.inner.ed25519_key().map(Into::into)
}
/// Get a map containing all the device keys.
#[wasm_bindgen(getter)]
pub fn keys(&self) -> Map {
let map = Map::new();
for (device_key_id, device_key) in self.inner.keys() {
map.set(
&identifiers::DeviceKeyId::from(device_key_id.clone()).into(),
&vodozemac::DeviceKey::from(device_key.clone()).into(),
);
}
map
}
/// Get a map containing all the device signatures.
#[wasm_bindgen(getter)]
pub fn signatures(&self) -> types::Signatures {
self.inner.signatures().clone().into()
}
/// Get the trust state of the device.
#[wasm_bindgen(getter, js_name = "localTrustState")]
pub fn local_trust_state(&self) -> LocalTrust {
self.inner.local_trust_state().into()
}
/// Is the device locally marked as trusted?
#[wasm_bindgen(js_name = "isLocallyTrusted")]
pub fn is_locally_trusted(&self) -> bool {
self.inner.is_locally_trusted()
}
/// Is the device locally marked as blacklisted?
///
/// Blacklisted devices wont receive any group sessions.
#[wasm_bindgen(js_name = "isBlacklisted")]
pub fn is_blacklisted(&self) -> bool {
self.inner.is_blacklisted()
}
/// Is the device deleted?
#[wasm_bindgen(js_name = "isDeleted")]
pub fn is_deleted(&self) -> bool {
self.inner.is_deleted()
}
}
/// The local trust state of a device.
#[wasm_bindgen]
#[derive(Debug)]
pub enum LocalTrust {
/// The device has been verified and is trusted.
Verified,
/// The device been blacklisted from communicating.
BlackListed,
/// The trust state of the device is being ignored.
Ignored,
/// The trust state is unset.
Unset,
}
impl From<matrix_sdk_crypto::LocalTrust> for LocalTrust {
fn from(value: matrix_sdk_crypto::LocalTrust) -> Self {
use matrix_sdk_crypto::LocalTrust::*;
match value {
Verified => Self::Verified,
BlackListed => Self::BlackListed,
Ignored => Self::Ignored,
Unset => Self::Unset,
}
}
}
impl From<LocalTrust> for matrix_sdk_crypto::LocalTrust {
fn from(value: LocalTrust) -> Self {
use LocalTrust::*;
match value {
Verified => Self::Verified,
BlackListed => Self::BlackListed,
Ignored => Self::Ignored,
Unset => Self::Unset,
}
}
}
/// A read only view over all devices belonging to a user.
#[wasm_bindgen]
#[derive(Debug)]
pub struct UserDevices {
pub(crate) inner: matrix_sdk_crypto::UserDevices,
}
impl_from_to_inner!(matrix_sdk_crypto::UserDevices => UserDevices);
#[wasm_bindgen]
impl UserDevices {
/// Get the specific device with the given device ID.
pub fn get(&self, device_id: &DeviceId) -> Option<Device> {
self.inner.get(&device_id.inner).map(Into::into)
}
/// Returns true if there is at least one devices of this user
/// that is considered to be verified, false otherwise.
///
/// This won't consider your own device as verified, as your own
/// device is always implicitly verified.
#[wasm_bindgen(js_name = "isAnyVerified")]
pub fn is_any_verified(&self) -> bool {
self.inner.is_any_verified()
}
/// Array over all the device IDs of the user devices.
pub fn keys(&self) -> Array {
self.inner.keys().map(ToOwned::to_owned).map(DeviceId::from).map(JsValue::from).collect()
}
/// Iterator over all the devices of the user devices.
pub fn devices(&self) -> Array {
self.inner.devices().map(Device::from).map(JsValue::from).collect()
}
}
@@ -0,0 +1,135 @@
//! Encryption types & siblings.
use std::time::Duration;
use wasm_bindgen::prelude::*;
use crate::events;
/// Settings for an encrypted room.
///
/// This determines the algorithm and rotation periods of a group
/// session.
#[wasm_bindgen(getter_with_clone)]
#[derive(Debug, Clone)]
pub struct EncryptionSettings {
/// The encryption algorithm that should be used in the room.
pub algorithm: EncryptionAlgorithm,
/// How long the session should be used before changing it,
/// expressed in microseconds.
#[wasm_bindgen(js_name = "rotationPeriod")]
pub rotation_period: u64,
/// How many messages should be sent before changing the session.
#[wasm_bindgen(js_name = "rotationPeriodMessages")]
pub rotation_period_messages: u64,
/// The history visibility of the room when the session was
/// created.
#[wasm_bindgen(js_name = "historyVisibility")]
pub history_visibility: events::HistoryVisibility,
/// Should untrusted devices receive the room key, or should they be
/// excluded from the conversation.
#[wasm_bindgen(js_name = "onlyAllowTrustedDevices")]
pub only_allow_trusted_devices: bool,
}
impl Default for EncryptionSettings {
fn default() -> Self {
let default = matrix_sdk_crypto::olm::EncryptionSettings::default();
Self {
algorithm: default.algorithm.into(),
rotation_period: default.rotation_period.as_micros().try_into().unwrap(),
rotation_period_messages: default.rotation_period_msgs,
history_visibility: default.history_visibility.into(),
only_allow_trusted_devices: default.only_allow_trusted_devices,
}
}
}
#[wasm_bindgen]
impl EncryptionSettings {
/// Create a new `EncryptionSettings` with default values.
#[wasm_bindgen(constructor)]
pub fn new() -> EncryptionSettings {
Self::default()
}
}
impl From<&EncryptionSettings> for matrix_sdk_crypto::olm::EncryptionSettings {
fn from(value: &EncryptionSettings) -> Self {
let algorithm = value.algorithm.clone().into();
Self {
algorithm,
rotation_period: Duration::from_micros(value.rotation_period),
rotation_period_msgs: value.rotation_period_messages,
history_visibility: value.history_visibility.clone().into(),
only_allow_trusted_devices: value.only_allow_trusted_devices,
}
}
}
/// An encryption algorithm to be used to encrypt messages sent to a
/// room.
#[wasm_bindgen]
#[derive(Debug, Clone)]
pub enum EncryptionAlgorithm {
/// Olm version 1 using Curve25519, AES-256, and SHA-256.
OlmV1Curve25519AesSha2,
/// Megolm version 1 using AES-256 and SHA-256.
MegolmV1AesSha2,
}
impl From<EncryptionAlgorithm> for matrix_sdk_crypto::types::EventEncryptionAlgorithm {
fn from(value: EncryptionAlgorithm) -> Self {
use EncryptionAlgorithm::*;
match value {
OlmV1Curve25519AesSha2 => Self::OlmV1Curve25519AesSha2,
MegolmV1AesSha2 => Self::MegolmV1AesSha2,
}
}
}
impl From<matrix_sdk_crypto::types::EventEncryptionAlgorithm> for EncryptionAlgorithm {
fn from(value: matrix_sdk_crypto::types::EventEncryptionAlgorithm) -> Self {
use matrix_sdk_crypto::types::EventEncryptionAlgorithm::*;
match value {
OlmV1Curve25519AesSha2 => Self::OlmV1Curve25519AesSha2,
MegolmV1AesSha2 => Self::MegolmV1AesSha2,
_ => unreachable!("Unknown variant"),
}
}
}
/// The verification state of the device that sent an event to us.
#[wasm_bindgen]
#[derive(Debug)]
pub enum VerificationState {
/// The device is trusted.
Trusted,
/// The device is not trusted.
Untrusted,
/// The device is not known to us.
UnknownDevice,
}
impl From<&matrix_sdk_common::deserialized_responses::VerificationState> for VerificationState {
fn from(value: &matrix_sdk_common::deserialized_responses::VerificationState) -> Self {
use matrix_sdk_common::deserialized_responses::VerificationState::*;
match value {
Trusted => Self::Trusted,
Untrusted => Self::Untrusted,
UnknownDevice => Self::UnknownDevice,
}
}
}
@@ -0,0 +1,61 @@
//! Types related to events.
use ruma::events::room::history_visibility::HistoryVisibility as RumaHistoryVisibility;
use wasm_bindgen::prelude::*;
/// Who can see a room's history.
#[wasm_bindgen]
#[derive(Debug, Clone)]
pub enum HistoryVisibility {
/// Previous events are accessible to newly joined members from
/// the point they were invited onwards.
///
/// Events stop being accessible when the member's state changes
/// to something other than *invite* or *join*.
Invited,
/// Previous events are accessible to newly joined members from
/// the point they joined the room onwards.
///
/// Events stop being accessible when the member's state changes
/// to something other than *join*.
Joined,
/// Previous events are always accessible to newly joined members.
///
/// All events in the room are accessible, even those sent when
/// the member was not a part of the room.
Shared,
/// All events while this is the `HistoryVisibility` value may be
/// shared by any participating homeserver with anyone, regardless
/// of whether they have ever joined the room.
WorldReadable,
}
impl From<HistoryVisibility> for RumaHistoryVisibility {
fn from(value: HistoryVisibility) -> Self {
use HistoryVisibility::*;
match value {
Invited => Self::Invited,
Joined => Self::Joined,
Shared => Self::Shared,
WorldReadable => Self::WorldReadable,
}
}
}
impl From<RumaHistoryVisibility> for HistoryVisibility {
fn from(value: RumaHistoryVisibility) -> Self {
use RumaHistoryVisibility::*;
match value {
Invited => Self::Invited,
Joined => Self::Joined,
Shared => Self::Shared,
WorldReadable => Self::WorldReadable,
_ => unreachable!("Unknown variant"),
}
}
}
@@ -0,0 +1,26 @@
use std::future::Future;
use js_sys::Promise;
use wasm_bindgen::{JsValue, UnwrapThrowExt};
use wasm_bindgen_futures::spawn_local;
pub(crate) fn future_to_promise<F, T>(future: F) -> Promise
where
F: Future<Output = Result<T, anyhow::Error>> + 'static,
T: Into<JsValue>,
{
let mut future = Some(future);
Promise::new(&mut |resolve, reject| {
let future = future.take().unwrap_throw();
spawn_local(async move {
match future.await {
Ok(value) => resolve.call1(&JsValue::UNDEFINED, &value.into()).unwrap_throw(),
Err(value) => {
reject.call1(&JsValue::UNDEFINED, &value.to_string().into()).unwrap_throw()
}
};
});
})
}
@@ -0,0 +1,321 @@
//! Types for [Matrix](https://matrix.org/) identifiers for devices,
//! events, keys, rooms, servers, users and URIs.
use wasm_bindgen::prelude::*;
use crate::impl_from_to_inner;
/// A Matrix [user ID].
///
/// [user ID]: https://spec.matrix.org/v1.2/appendices/#user-identifiers
#[wasm_bindgen]
#[derive(Debug, Clone)]
pub struct UserId {
pub(crate) inner: ruma::OwnedUserId,
}
impl_from_to_inner!(ruma::OwnedUserId => UserId);
#[wasm_bindgen]
impl UserId {
/// Parse/validate and create a new `UserId`.
#[wasm_bindgen(constructor)]
pub fn new(id: &str) -> Result<UserId, JsError> {
Ok(Self::from(ruma::UserId::parse(id)?))
}
/// Returns the user's localpart.
#[wasm_bindgen(getter)]
pub fn localpart(&self) -> String {
self.inner.localpart().to_owned()
}
/// Returns the server name of the user ID.
#[wasm_bindgen(getter, js_name = "serverName")]
pub fn server_name(&self) -> ServerName {
ServerName { inner: self.inner.server_name().to_owned() }
}
/// Whether this user ID is a historical one.
///
/// A historical user ID is one that doesn't conform to the latest
/// specification of the user ID grammar but is still accepted
/// because it was previously allowed.
#[wasm_bindgen(js_name = "isHistorical")]
pub fn is_historical(&self) -> bool {
self.inner.is_historical()
}
/// Return the user ID as a string.
#[wasm_bindgen(js_name = "toString")]
#[allow(clippy::inherent_to_string)]
pub fn to_string(&self) -> String {
self.inner.as_str().to_owned()
}
}
/// A Matrix key ID.
///
/// Device identifiers in Matrix are completely opaque character
/// sequences. This type is provided simply for its semantic value.
#[wasm_bindgen]
#[derive(Debug, Clone)]
pub struct DeviceId {
pub(crate) inner: ruma::OwnedDeviceId,
}
impl_from_to_inner!(ruma::OwnedDeviceId => DeviceId);
#[wasm_bindgen]
impl DeviceId {
/// Create a new `DeviceId`.
#[wasm_bindgen(constructor)]
pub fn new(id: &str) -> DeviceId {
Self::from(ruma::OwnedDeviceId::from(id))
}
/// Return the device ID as a string.
#[wasm_bindgen(js_name = "toString")]
#[allow(clippy::inherent_to_string)]
pub fn to_string(&self) -> String {
self.inner.as_str().to_owned()
}
}
/// A Matrix device key ID.
///
/// A key algorithm and a device ID, combined with a :.
#[wasm_bindgen]
#[derive(Debug, Clone)]
pub struct DeviceKeyId {
pub(crate) inner: ruma::OwnedDeviceKeyId,
}
impl_from_to_inner!(ruma::OwnedDeviceKeyId => DeviceKeyId);
#[wasm_bindgen]
impl DeviceKeyId {
/// Parse/validate and create a new `DeviceKeyId`.
#[wasm_bindgen(constructor)]
pub fn new(id: String) -> Result<DeviceKeyId, JsError> {
Ok(Self::from(ruma::DeviceKeyId::parse(id.as_str())?))
}
/// Returns key algorithm of the device key ID.
#[wasm_bindgen(getter)]
pub fn algorithm(&self) -> DeviceKeyAlgorithm {
self.inner.algorithm().into()
}
/// Returns device ID of the device key ID.
#[wasm_bindgen(getter, js_name = "deviceId")]
pub fn device_id(&self) -> DeviceId {
self.inner.device_id().to_owned().into()
}
/// Return the device key ID as a string.
#[wasm_bindgen(js_name = "toString")]
#[allow(clippy::inherent_to_string)]
pub fn to_string(&self) -> String {
self.inner.to_string()
}
}
/// The basic key algorithms in the specification.
#[wasm_bindgen]
#[derive(Debug)]
pub struct DeviceKeyAlgorithm {
pub(crate) inner: ruma::DeviceKeyAlgorithm,
}
impl_from_to_inner!(ruma::DeviceKeyAlgorithm => DeviceKeyAlgorithm);
#[wasm_bindgen]
impl DeviceKeyAlgorithm {
/// Read the device key algorithm's name. If the name is
/// `Unknown`, one may be interested by the `to_string` method to
/// read the original name.
#[wasm_bindgen(getter)]
pub fn name(&self) -> DeviceKeyAlgorithmName {
self.inner.clone().into()
}
/// Return the device key algorithm as a string.
#[wasm_bindgen(js_name = "toString")]
#[allow(clippy::inherent_to_string)]
pub fn to_string(&self) -> String {
self.inner.to_string()
}
}
/// The basic key algorithm names in the specification.
#[wasm_bindgen]
#[derive(Debug)]
pub enum DeviceKeyAlgorithmName {
/// The Ed25519 signature algorithm.
Ed25519,
/// The Curve25519 ECDH algorithm.
Curve25519,
/// The Curve25519 ECDH algorithm, but the key also contains
/// signatures.
SignedCurve25519,
/// An unknown device key algorithm.
Unknown,
}
impl TryFrom<DeviceKeyAlgorithmName> for ruma::DeviceKeyAlgorithm {
type Error = JsError;
fn try_from(value: DeviceKeyAlgorithmName) -> Result<Self, Self::Error> {
use DeviceKeyAlgorithmName::*;
Ok(match value {
Ed25519 => Self::Ed25519,
Curve25519 => Self::Curve25519,
SignedCurve25519 => Self::SignedCurve25519,
Unknown => {
return Err(JsError::new(
"The `DeviceKeyAlgorithmName.Unknown` variant cannot be converted",
))
}
})
}
}
impl From<ruma::DeviceKeyAlgorithm> for DeviceKeyAlgorithmName {
fn from(value: ruma::DeviceKeyAlgorithm) -> Self {
use ruma::DeviceKeyAlgorithm::*;
match value {
Ed25519 => Self::Ed25519,
Curve25519 => Self::Curve25519,
SignedCurve25519 => Self::SignedCurve25519,
_ => Self::Unknown,
}
}
}
/// A Matrix [room ID].
///
/// [room ID]: https://spec.matrix.org/v1.2/appendices/#room-ids-and-event-ids
#[wasm_bindgen]
#[derive(Debug, Clone)]
pub struct RoomId {
pub(crate) inner: ruma::OwnedRoomId,
}
impl_from_to_inner!(ruma::OwnedRoomId => RoomId);
#[wasm_bindgen]
impl RoomId {
/// Parse/validate and create a new `RoomId`.
#[wasm_bindgen(constructor)]
pub fn new(id: &str) -> Result<RoomId, JsError> {
Ok(Self::from(ruma::RoomId::parse(id)?))
}
/// Returns the user's localpart.
#[wasm_bindgen(getter)]
pub fn localpart(&self) -> String {
self.inner.localpart().to_owned()
}
/// Returns the server name of the room ID.
#[wasm_bindgen(getter, js_name = "serverName")]
pub fn server_name(&self) -> ServerName {
ServerName { inner: self.inner.server_name().to_owned() }
}
/// Return the room ID as a string.
#[wasm_bindgen(js_name = "toString")]
#[allow(clippy::inherent_to_string)]
pub fn to_string(&self) -> String {
self.inner.as_str().to_owned()
}
}
/// A Matrix-spec compliant [server name].
///
/// It consists of a host and an optional port (separated by a colon if
/// present).
///
/// [server name]: https://spec.matrix.org/v1.2/appendices/#server-name
#[wasm_bindgen]
#[derive(Debug)]
pub struct ServerName {
inner: ruma::OwnedServerName,
}
#[wasm_bindgen]
impl ServerName {
/// Parse/validate and create a new `ServerName`.
#[wasm_bindgen(constructor)]
pub fn new(name: &str) -> Result<ServerName, JsError> {
Ok(Self { inner: ruma::ServerName::parse(name)? })
}
/// Returns the host of the server name.
///
/// That is: Return the part of the server before `:<port>` or the
/// full server name if there is no port.
#[wasm_bindgen(getter)]
pub fn host(&self) -> String {
self.inner.host().to_owned()
}
/// Returns the port of the server name if any.
#[wasm_bindgen(getter)]
pub fn port(&self) -> Option<u16> {
self.inner.port()
}
/// Returns true if and only if the server name is an IPv4 or IPv6
/// address.
#[wasm_bindgen(js_name = "isIpLiteral")]
pub fn is_ip_literal(&self) -> bool {
self.inner.is_ip_literal()
}
}
/// A Matrix [event ID].
///
/// An `EventId` is generated randomly or converted from a string
/// slice, and can be converted back into a string as needed.
///
/// [event ID]: https://spec.matrix.org/v1.2/appendices/#room-ids-and-event-ids
#[wasm_bindgen]
#[derive(Debug)]
pub struct EventId {
pub(crate) inner: ruma::OwnedEventId,
}
#[wasm_bindgen]
impl EventId {
/// Parse/validate and create a new `EventId`.
#[wasm_bindgen(constructor)]
pub fn new(id: &str) -> Result<EventId, JsError> {
Ok(Self { inner: <&ruma::EventId>::try_from(id)?.to_owned() })
}
/// Returns the event's localpart.
#[wasm_bindgen(getter)]
pub fn localpart(&self) -> String {
self.inner.localpart().to_owned()
}
/// Returns the server name of the event ID.
#[wasm_bindgen(getter, js_name = "serverName")]
pub fn server_name(&self) -> Option<ServerName> {
Some(ServerName { inner: self.inner.server_name()?.to_owned() })
}
/// Return the event ID as a string.
#[wasm_bindgen(js_name = "toString")]
#[allow(clippy::inherent_to_string)]
pub fn to_string(&self) -> String {
self.inner.as_str().to_owned()
}
}
@@ -0,0 +1,172 @@
//! User identities.
use js_sys::{Array, Promise};
use wasm_bindgen::prelude::*;
use crate::{
future::future_to_promise, identifiers, impl_from_to_inner, js::try_array_to_vec, requests,
verification,
};
pub(crate) struct UserIdentities {
inner: matrix_sdk_crypto::UserIdentities,
}
impl_from_to_inner!(matrix_sdk_crypto::UserIdentities => UserIdentities);
impl From<UserIdentities> for JsValue {
fn from(user_identities: UserIdentities) -> Self {
use matrix_sdk_crypto::UserIdentities::*;
match user_identities.inner {
Own(own) => JsValue::from(OwnUserIdentity::from(own)),
Other(other) => JsValue::from(UserIdentity::from(other)),
}
}
}
/// Struct representing a cross signing identity of a user.
///
/// This is the user identity of a user that is our own.
#[wasm_bindgen]
#[derive(Debug)]
pub struct OwnUserIdentity {
inner: matrix_sdk_crypto::OwnUserIdentity,
}
impl_from_to_inner!(matrix_sdk_crypto::OwnUserIdentity => OwnUserIdentity);
#[wasm_bindgen]
impl OwnUserIdentity {
/// Mark our user identity as verified.
///
/// This will mark the identity locally as verified and sign it with our own
/// device.
///
/// Returns a signature upload request that needs to be sent out.
pub fn verify(&self) -> Promise {
let me = self.inner.clone();
future_to_promise(async move {
Ok(requests::SignatureUploadRequest::try_from(&me.verify().await?)?)
})
}
/// Send a verification request to our other devices.
#[wasm_bindgen(js_name = "requestVerification")]
pub fn request_verification(&self, methods: Option<Array>) -> Result<Promise, JsError> {
let methods =
methods.map(try_array_to_vec::<verification::VerificationMethod, _>).transpose()?;
let me = self.inner.clone();
Ok(future_to_promise(async move {
let tuple = Array::new();
let (verification_request, outgoing_verification_request) = match methods {
Some(methods) => me.request_verification_with_methods(methods).await?,
None => me.request_verification().await?,
};
tuple.set(0, verification::VerificationRequest::from(verification_request).into());
tuple.set(
1,
verification::OutgoingVerificationRequest::from(outgoing_verification_request)
.try_into()?,
);
Ok(tuple)
}))
}
/// Does our user identity trust our own device, i.e. have we signed our own
/// device keys with our self-signing key?
#[wasm_bindgen(js_name = "trustsOurOwnDevice")]
pub fn trusts_our_own_device(&self) -> Promise {
let me = self.inner.clone();
future_to_promise(async move { Ok(me.trusts_our_own_device().await?) })
}
}
/// Struct representing a cross signing identity of a user.
///
/// This is the user identity of a user that isn't our own. Other users will
/// only contain a master key and a self signing key, meaning that only device
/// signatures can be checked with this identity.
///
/// This struct wraps a read-only version of the struct and allows verifications
/// to be requested to verify our own device with the user identity.
#[wasm_bindgen]
#[derive(Debug)]
pub struct UserIdentity {
inner: matrix_sdk_crypto::UserIdentity,
}
impl_from_to_inner!(matrix_sdk_crypto::UserIdentity => UserIdentity);
#[wasm_bindgen]
impl UserIdentity {
/// Is this user identity verified?
#[wasm_bindgen(js_name = "isVerified")]
pub fn is_verified(&self) -> bool {
self.inner.is_verified()
}
/// Manually verify this user.
///
/// This method will attempt to sign the user identity using our private
/// cross signing key.
///
/// This method fails if we don't have the private part of our user-signing
/// key.
///
/// Returns a request that needs to be sent out for the user to be marked as
/// verified.
pub fn verify(&self) -> Promise {
let me = self.inner.clone();
future_to_promise(async move {
Ok(requests::SignatureUploadRequest::try_from(&me.verify().await?)?)
})
}
/// Create a `VerificationRequest` object after the verification
/// request content has been sent out. }
#[wasm_bindgen(js_name = "requestVerification")]
pub fn request_verification(
&self,
room_id: &identifiers::RoomId,
request_event_id: &identifiers::EventId,
methods: Option<Array>,
) -> Result<Promise, JsError> {
let me = self.inner.clone();
let room_id = room_id.inner.clone();
let request_event_id = request_event_id.inner.clone();
let methods =
methods.map(try_array_to_vec::<verification::VerificationMethod, _>).transpose()?;
Ok(future_to_promise::<_, verification::VerificationRequest>(async move {
Ok(me
.request_verification(room_id.as_ref(), request_event_id.as_ref(), methods)
.await
.into())
}))
}
/// Send a verification request to the given user.
///
/// The returned content needs to be sent out into a DM room with the given
/// user.
///
/// After the content has been sent out a VerificationRequest can be started
/// with the `request_verification` method.
#[wasm_bindgen(js_name = "verificationRequestContent")]
pub fn verification_request_content(&self, methods: Option<Array>) -> Result<Promise, JsError> {
let me = self.inner.clone();
let methods =
methods.map(try_array_to_vec::<verification::VerificationMethod, _>).transpose()?;
Ok(future_to_promise(async move {
Ok(serde_json::to_string(&me.verification_request_content(methods).await)?)
}))
}
}
+40
View File
@@ -0,0 +1,40 @@
use js_sys::{Array, Object, Reflect};
use wasm_bindgen::{convert::RefFromWasmAbi, prelude::*};
/// A really hacky and dirty code to downcast a `JsValue` to `T:
/// RefFromWasmAbi`, inspired by
/// https://github.com/rustwasm/wasm-bindgen/issues/2231#issuecomment-656293288.
///
/// The returned value is likely to be a `wasm_bindgen::__ref::Ref<T>`.
pub(crate) fn downcast<T>(value: &JsValue, classname: &str) -> Result<T::Anchor, JsError>
where
T: RefFromWasmAbi<Abi = u32>,
{
let constructor_name = Object::get_prototype_of(value).constructor().name();
if constructor_name == classname {
let pointer = Reflect::get(value, &JsValue::from_str("ptr"))
.map_err(|_| JsError::new("Failed to read the `JsValue` pointer"))?;
let pointer = pointer
.as_f64()
.ok_or_else(|| JsError::new("Failed to read the `JsValue` pointer as a `f64`"))?
as u32;
Ok(unsafe { T::ref_from_abi(pointer) })
} else {
Err(JsError::new(&format!(
"Expect an `{classname}` instance, received `{constructor_name}` instead",
)))
}
}
/// Transform a value `JS` from JavaScript to a Rust wrapper, to a
/// Rust wrapped type.
pub(crate) fn try_array_to_vec<JS, Rust>(
array: Array,
) -> Result<Vec<Rust>, <JS as TryFrom<JsValue>>::Error>
where
JS: TryFrom<JsValue> + Into<Rust>,
{
array.iter().map(|item| JS::try_from(item).map(Into::into)).collect()
}
+50
View File
@@ -0,0 +1,50 @@
// Copyright 2022 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.
#![doc = include_str!("../README.md")]
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
#![warn(missing_docs, missing_debug_implementations)]
#![allow(clippy::drop_non_drop)] // triggered by wasm_bindgen code
pub mod attachment;
pub mod device;
pub mod encryption;
pub mod events;
mod future;
pub mod identifiers;
pub mod identities;
mod js;
pub mod machine;
mod macros;
pub mod olm;
pub mod requests;
pub mod responses;
pub mod store;
pub mod sync_events;
mod tracing;
pub mod types;
pub mod verification;
pub mod vodozemac;
use wasm_bindgen::prelude::*;
/// Run some stuff when the Wasm module is instantiated.
///
/// Right now, it does the following:
///
/// * Redirect Rust panics to JavaScript console.
#[wasm_bindgen(start)]
pub fn start() {
console_error_panic_hook::set_once();
}
@@ -0,0 +1,731 @@
//! The crypto specific Olm objects.
use std::collections::BTreeMap;
use js_sys::{Array, Function, Map, Promise, Set};
use ruma::{serde::Raw, DeviceKeyAlgorithm, OwnedTransactionId, UInt};
use serde_json::{json, Value as JsonValue};
use wasm_bindgen::prelude::*;
use crate::{
device, encryption,
future::future_to_promise,
identifiers, identities,
js::downcast,
olm, requests,
requests::OutgoingRequest,
responses::{self, response_from_string},
store, sync_events, types, verification, vodozemac,
};
/// State machine implementation of the Olm/Megolm encryption protocol
/// used for Matrix end to end encryption.
#[wasm_bindgen]
#[derive(Debug, Clone)]
pub struct OlmMachine {
inner: matrix_sdk_crypto::OlmMachine,
}
#[wasm_bindgen]
impl OlmMachine {
/// Create a new memory based `OlmMachine`.
///
/// The created machine will keep the encryption keys only in
/// memory and once the objects is dropped, the keys will be lost.
///
/// `user_id` represents the unique ID of the user that owns this
/// machine. `device_id` represents the unique ID of the device
/// that owns this machine.
///
/// `store_name` and `store_passphrase` are both optional, but
/// must be both set to have an effect. If they are both set, the
/// state of the machine will persist in a database named
/// `store_name` where its content is encrypted by the passphrase
/// given by `store_passphrase`. If they are not both set, the
/// created machine will keep the encryption keys only in memory,
/// and once the object is dropped, the keys will be lost.
#[wasm_bindgen(constructor)]
#[allow(clippy::new_ret_no_self)]
pub fn new(
user_id: &identifiers::UserId,
device_id: &identifiers::DeviceId,
store_name: Option<String>,
store_passphrase: Option<String>,
) -> Promise {
let user_id = user_id.inner.clone();
let device_id = device_id.inner.clone();
future_to_promise(async move {
let store = match (store_name, store_passphrase) {
// We need this `#[cfg]` because `IndexeddbCryptoStore`
// implements `CryptoStore` only on `target_arch =
// "wasm32"`. Without that, we could have a compilation
// error when checking the entire workspace. In
// practise, it doesn't impact this crate because it's
// always compiled for `wasm32`.
#[cfg(target_arch = "wasm32")]
(Some(store_name), Some(mut store_passphrase)) => {
use std::sync::Arc;
use zeroize::Zeroize;
let store = Some(
matrix_sdk_indexeddb::IndexeddbCryptoStore::open_with_passphrase(
&store_name,
&store_passphrase,
)
.await
.map(Arc::new)?,
);
store_passphrase.zeroize();
store
}
(Some(_), None) => return Err(anyhow::Error::msg("The `store_name` has been set, and so, it expects a `store_passphrase`, which is not set; please provide one")),
(None, Some(_)) => return Err(anyhow::Error::msg("The `store_passphrase` has been set, but it has an effect only if `store_name` is set, which is not; please provide one")),
_ => None,
};
Ok(OlmMachine {
inner: match store {
Some(store) => {
matrix_sdk_crypto::OlmMachine::with_store(
user_id.as_ref(),
device_id.as_ref(),
store,
)
.await?
}
None => {
matrix_sdk_crypto::OlmMachine::new(user_id.as_ref(), device_id.as_ref())
.await
}
},
})
})
}
/// The unique user ID that owns this `OlmMachine` instance.
#[wasm_bindgen(getter, js_name = "userId")]
pub fn user_id(&self) -> identifiers::UserId {
identifiers::UserId::from(self.inner.user_id().to_owned())
}
/// The unique device ID that identifies this `OlmMachine`.
#[wasm_bindgen(getter, js_name = "deviceId")]
pub fn device_id(&self) -> identifiers::DeviceId {
identifiers::DeviceId::from(self.inner.device_id().to_owned())
}
/// Get the public parts of our Olm identity keys.
#[wasm_bindgen(getter, js_name = "identityKeys")]
pub fn identity_keys(&self) -> vodozemac::IdentityKeys {
self.inner.identity_keys().into()
}
/// Get the display name of our own device.
#[wasm_bindgen(getter, js_name = "displayName")]
pub fn display_name(&self) -> Promise {
let me = self.inner.clone();
future_to_promise(async move { Ok(me.display_name().await?) })
}
/// Get all the tracked users of our own device.
///
/// Returns a `Set<UserId>`.
#[wasm_bindgen(js_name = "trackedUsers")]
pub fn tracked_users(&self) -> Set {
let set = Set::new(&JsValue::UNDEFINED);
for user in self.inner.tracked_users() {
set.add(&identifiers::UserId::from(user).into());
}
set
}
/// Update the tracked users.
///
/// `users` is an iterator over user IDs that should be marked for
/// tracking.
///
/// This will mark users that weren't seen before for a key query
/// and tracking.
///
/// If the user is already known to the Olm machine, it will not
/// be considered for a key query.
#[wasm_bindgen(js_name = "updateTrackedUsers")]
pub fn update_tracked_users(&self, users: &Array) -> Result<Promise, JsError> {
let users = users
.iter()
.map(|user| Ok(downcast::<identifiers::UserId>(&user, "UserId")?.inner.clone()))
.collect::<Result<Vec<ruma::OwnedUserId>, JsError>>()?;
let me = self.inner.clone();
Ok(future_to_promise(async move {
me.update_tracked_users(users.iter().map(AsRef::as_ref)).await;
Ok(JsValue::UNDEFINED)
}))
}
/// Handle to-device events and one-time key counts from a sync
/// response.
///
/// This will decrypt and handle to-device events returning the
/// decrypted versions of them.
///
/// To decrypt an event from the room timeline call
/// `decrypt_room_event`.
#[wasm_bindgen(js_name = "receiveSyncChanges")]
pub fn receive_sync_changes(
&self,
to_device_events: &str,
changed_devices: &sync_events::DeviceLists,
one_time_key_counts: &Map,
unused_fallback_keys: &Set,
) -> Result<Promise, JsError> {
let to_device_events = serde_json::from_str(to_device_events)?;
let changed_devices = changed_devices.inner.clone();
let one_time_key_counts: BTreeMap<DeviceKeyAlgorithm, UInt> = one_time_key_counts
.entries()
.into_iter()
.filter_map(|js_value| {
let pair = Array::from(&js_value.ok()?);
let (key, value) = (
DeviceKeyAlgorithm::from(pair.at(0).as_string()?),
UInt::new(pair.at(1).as_f64()? as u64)?,
);
Some((key, value))
})
.collect();
let unused_fallback_keys: Option<Vec<DeviceKeyAlgorithm>> = Some(
unused_fallback_keys
.values()
.into_iter()
.filter_map(|js_value| Some(DeviceKeyAlgorithm::from(js_value.ok()?.as_string()?)))
.collect(),
);
let me = self.inner.clone();
Ok(future_to_promise(async move {
Ok(serde_json::to_string(
&me.receive_sync_changes(
to_device_events,
&changed_devices,
&one_time_key_counts,
unused_fallback_keys.as_deref(),
)
.await?,
)?)
}))
}
/// Get the outgoing requests that need to be sent out.
///
/// This returns a list of `JsValue` to represent either:
/// * `KeysUploadRequest`,
/// * `KeysQueryRequest`,
/// * `KeysClaimRequest`,
/// * `ToDeviceRequest`,
/// * `SignatureUploadRequest`,
/// * `RoomMessageRequest` or
/// * `KeysBackupRequest`.
///
/// Those requests need to be sent out to the server and the
/// responses need to be passed back to the state machine using
/// `mark_request_as_sent`.
#[wasm_bindgen(js_name = "outgoingRequests")]
pub fn outgoing_requests(&self) -> Promise {
let me = self.inner.clone();
future_to_promise(async move {
Ok(me
.outgoing_requests()
.await?
.into_iter()
.map(OutgoingRequest)
.map(TryFrom::try_from)
.collect::<Result<Vec<JsValue>, _>>()?
.into_iter()
.collect::<Array>())
})
}
/// Mark the request with the given request ID as sent (see
/// `outgoing_requests`).
///
/// Arguments are:
///
/// * `request_id` represents the unique ID of the request that was sent
/// out. This is needed to couple the response with the now sent out
/// request.
/// * `response_type` represents the type of the request that was sent out.
/// * `response` represents the response that was received from the server
/// after the outgoing request was sent out.
#[wasm_bindgen(js_name = "markRequestAsSent")]
pub fn mark_request_as_sent(
&self,
request_id: &str,
request_type: requests::RequestType,
response: &str,
) -> Result<Promise, JsError> {
let transaction_id = OwnedTransactionId::from(request_id);
let response = response_from_string(response)?;
let incoming_response = responses::OwnedResponse::try_from((request_type, response))?;
let me = self.inner.clone();
Ok(future_to_promise(async move {
Ok(me.mark_request_as_sent(&transaction_id, &incoming_response).await.map(|_| true)?)
}))
}
/// Encrypt a room message for the given room.
///
/// Beware that a room key needs to be shared before this
/// method can be called using the `share_room_key` method.
///
/// `room_id` is the ID of the room for which the message should
/// be encrypted. `event_type` is the type of the event. `content`
/// is the plaintext content of the message that should be
/// encrypted.
///
/// # Panics
///
/// Panics if a group session for the given room wasn't shared
/// beforehand.
#[wasm_bindgen(js_name = "encryptRoomEvent")]
pub fn encrypt_room_event(
&self,
room_id: &identifiers::RoomId,
event_type: String,
content: &str,
) -> Result<Promise, JsError> {
let room_id = room_id.inner.clone();
let content: JsonValue = serde_json::from_str(content)?;
let me = self.inner.clone();
Ok(future_to_promise(async move {
Ok(serde_json::to_string(
&me.encrypt_room_event_raw(&room_id, content, event_type.as_ref()).await?,
)?)
}))
}
/// Decrypt an event from a room timeline.
///
/// # Arguments
///
/// * `event`, the event that should be decrypted.
/// * `room_id`, the ID of the room where the event was sent to.
#[wasm_bindgen(js_name = "decryptRoomEvent")]
pub fn decrypt_room_event(
&self,
event: &str,
room_id: &identifiers::RoomId,
) -> Result<Promise, JsError> {
let event: Raw<_> = serde_json::from_str(event)?;
let room_id = room_id.inner.clone();
let me = self.inner.clone();
Ok(future_to_promise(async move {
let room_event = me.decrypt_room_event(&event, room_id.as_ref()).await?;
Ok(responses::DecryptedRoomEvent::from(room_event))
}))
}
/// Get the status of the private cross signing keys.
///
/// This can be used to check which private cross signing keys we
/// have stored locally.
#[wasm_bindgen(js_name = "crossSigningStatus")]
pub fn cross_signing_status(&self) -> Promise {
let me = self.inner.clone();
future_to_promise::<_, olm::CrossSigningStatus>(async move {
Ok(me.cross_signing_status().await.into())
})
}
/// Export all the private cross signing keys we have.
///
/// The export will contain the seed for the ed25519 keys as a
/// unpadded base64 encoded string.
///
/// This method returns None if we dont have any private cross
/// signing keys.
#[wasm_bindgen(js_name = "exportCrossSigningKeys")]
pub fn export_cross_signing_keys(&self) -> Promise {
let me = self.inner.clone();
future_to_promise(async move {
Ok(me.export_cross_signing_keys().await.map(store::CrossSigningKeyExport::from))
})
}
/// Import our private cross signing keys.
///
/// The export needs to contain the seed for the ed25519 keys as
/// an unpadded base64 encoded string.
#[wasm_bindgen(js_name = "importCrossSigningKeys")]
pub fn import_cross_signing_keys(&self, export: store::CrossSigningKeyExport) -> Promise {
let me = self.inner.clone();
let export = export.inner;
future_to_promise(async move {
Ok(me.import_cross_signing_keys(export).await.map(olm::CrossSigningStatus::from)?)
})
}
/// Create a new cross signing identity and get the upload request
/// to push the new public keys to the server.
///
/// Warning: This will delete any existing cross signing keys that
/// might exist on the server and thus will reset the trust
/// between all the devices.
///
/// Uploading these keys will require user interactive auth.
#[wasm_bindgen(js_name = "bootstrapCrossSigning")]
pub fn bootstrap_cross_signing(&self, reset: bool) -> Promise {
let me = self.inner.clone();
future_to_promise(async move {
let (upload_signing_keys_request, upload_signatures_request) =
me.bootstrap_cross_signing(reset).await?;
let tuple = Array::new();
tuple.set(
0,
requests::SigningKeysUploadRequest::try_from(&upload_signing_keys_request)?.into(),
);
tuple.set(
1,
requests::SignatureUploadRequest::try_from(&upload_signatures_request)?.into(),
);
Ok(tuple)
})
}
/// Get the cross signing user identity of a user.
#[wasm_bindgen(js_name = "getIdentity")]
pub fn get_identity(&self, user_id: &identifiers::UserId) -> Promise {
let me = self.inner.clone();
let user_id = user_id.inner.clone();
future_to_promise(async move {
Ok(me.get_identity(user_id.as_ref(), None).await?.map(identities::UserIdentities::from))
})
}
/// Sign the given message using our device key and if available
/// cross-signing master key.
pub fn sign(&self, message: String) -> Promise {
let me = self.inner.clone();
future_to_promise::<_, types::Signatures>(async move { Ok(me.sign(&message).await.into()) })
}
/// Invalidate the currently active outbound group session for the
/// given room.
///
/// Returns true if a session was invalidated, false if there was
/// no session to invalidate.
#[wasm_bindgen(js_name = "invalidateGroupSession")]
pub fn invalidate_group_session(&self, room_id: &identifiers::RoomId) -> Promise {
let room_id = room_id.inner.clone();
let me = self.inner.clone();
future_to_promise(async move { Ok(me.invalidate_group_session(&room_id).await?) })
}
/// Get to-device requests to share a room key with users in a room.
///
/// `room_id` is the room ID. `users` is an array of `UserId`
/// objects. `encryption_settings` are an `EncryptionSettings`
/// object.
#[wasm_bindgen(js_name = "shareRoomKey")]
pub fn share_room_key(
&self,
room_id: &identifiers::RoomId,
users: &Array,
encryption_settings: &encryption::EncryptionSettings,
) -> Result<Promise, JsError> {
let room_id = room_id.inner.clone();
let users = users
.iter()
.map(|user| Ok(downcast::<identifiers::UserId>(&user, "UserId")?.inner.clone()))
.collect::<Result<Vec<ruma::OwnedUserId>, JsError>>()?;
let encryption_settings =
matrix_sdk_crypto::olm::EncryptionSettings::from(encryption_settings);
let me = self.inner.clone();
Ok(future_to_promise(async move {
Ok(serde_json::to_string(
&me.share_room_key(&room_id, users.iter().map(AsRef::as_ref), encryption_settings)
.await?,
)?)
}))
}
/// Get the a key claiming request for the user/device pairs that
/// we are missing Olm sessions for.
///
/// Returns `NULL` if no key claiming request needs to be sent
/// out, otherwise it returns an `Array` where the first key is
/// the transaction ID as a string, and the second key is the keys
/// claim request serialized to JSON.
///
/// Sessions need to be established between devices so group
/// sessions for a room can be shared with them.
///
/// This should be called every time a group session needs to be
/// shared as well as between sync calls. After a sync some
/// devices may request room keys without us having a valid Olm
/// session with them, making it impossible to server the room key
/// request, thus its necessary to check for missing sessions
/// between sync as well.
///
/// Note: Care should be taken that only one such request at a
/// time is in flight, e.g. using a lock.
///
/// The response of a successful key claiming requests needs to be
/// passed to the `OlmMachine` with the `mark_request_as_sent`.
///
/// `users` represents the list of users that we should check if
/// we lack a session with one of their devices. This can be an
/// empty iterator when calling this method between sync requests.
#[wasm_bindgen(js_name = "getMissingSessions")]
pub fn get_missing_sessions(&self, users: &Array) -> Result<Promise, JsError> {
let users = users
.iter()
.map(|user| Ok(downcast::<identifiers::UserId>(&user, "UserId")?.inner.clone()))
.collect::<Result<Vec<ruma::OwnedUserId>, JsError>>()?;
let me = self.inner.clone();
Ok(future_to_promise(async move {
match me.get_missing_sessions(users.iter().map(AsRef::as_ref)).await? {
Some((transaction_id, keys_claim_request)) => {
Ok(JsValue::from(requests::KeysClaimRequest::try_from((
transaction_id.to_string(),
&keys_claim_request,
))?))
}
None => Ok(JsValue::NULL),
}
}))
}
/// Get a map holding all the devices of a user.
///
/// `user_id` represents the unique ID of the user that the
/// devices belong to.
#[wasm_bindgen(js_name = "getUserDevices")]
pub fn get_user_devices(&self, user_id: &identifiers::UserId) -> Promise {
let user_id = user_id.inner.clone();
let me = self.inner.clone();
future_to_promise::<_, device::UserDevices>(async move {
Ok(me.get_user_devices(&user_id, None).await.map(Into::into)?)
})
}
/// Get a specific device of a user if one is found and the crypto store
/// didn't throw an error.
///
/// `user_id` represents the unique ID of the user that the
/// identity belongs to. `device_id` represents the unique ID of
/// the device.
#[wasm_bindgen(js_name = "getDevice")]
pub fn get_device(
&self,
user_id: &identifiers::UserId,
device_id: &identifiers::DeviceId,
) -> Promise {
let user_id = user_id.inner.clone();
let device_id = device_id.inner.clone();
let me = self.inner.clone();
future_to_promise::<_, Option<device::Device>>(async move {
Ok(me.get_device(&user_id, &device_id, None).await?.map(Into::into))
})
}
/// Get a verification object for the given user ID with the given
/// flow ID (a to-device request ID if the verification has been
/// requested by a to-device request, or a room event ID if the
/// verification has been requested by a room event).
///
/// It returns a “`Verification` object”, which is either a `Sas`
/// or `Qr` object.
#[wasm_bindgen(js_name = "getVerification")]
pub fn get_verification(
&self,
user_id: &identifiers::UserId,
flow_id: &str,
) -> Result<JsValue, JsError> {
self.inner
.get_verification(&user_id.inner, flow_id)
.map(verification::Verification)
.map(JsValue::try_from)
.transpose()
.map(JsValue::from)
}
/// Get a verification request object with the given flow ID.
#[wasm_bindgen(js_name = "getVerificationRequest")]
pub fn get_verification_request(
&self,
user_id: &identifiers::UserId,
flow_id: &str,
) -> Option<verification::VerificationRequest> {
self.inner.get_verification_request(&user_id.inner, flow_id).map(Into::into)
}
/// Get all the verification requests of a given user.
#[wasm_bindgen(js_name = "getVerificationRequests")]
pub fn get_verification_requests(&self, user_id: &identifiers::UserId) -> Array {
self.inner
.get_verification_requests(&user_id.inner)
.into_iter()
.map(verification::VerificationRequest::from)
.map(JsValue::from)
.collect()
}
/// Receive an unencrypted verification event.
///
/// This method can be used to pass verification events that are
/// happening in unencrypted rooms to the `OlmMachine`.
///
/// Note: This does not need to be called for encrypted events
/// since those will get passed to the `OlmMachine` during
/// decryption.
#[wasm_bindgen(js_name = "receiveUnencryptedVerificationEvent")]
pub fn receive_unencrypted_verification_event(&self, event: &str) -> Result<Promise, JsError> {
let event: ruma::events::AnyMessageLikeEvent = serde_json::from_str(event)?;
let me = self.inner.clone();
Ok(future_to_promise(async move {
Ok(me
.receive_unencrypted_verification_event(&event)
.await
.map(|_| JsValue::UNDEFINED)?)
}))
}
/// Export the keys that match the given predicate.
///
/// `predicate` is a closure that will be called for every known
/// `InboundGroupSession`, which represents a room key. If the closure
/// returns `true`, the `InboundGroupSession` will be included in the
/// export, otherwise it won't.
#[wasm_bindgen(js_name = "exportRoomKeys")]
pub fn export_room_keys(&self, predicate: Function) -> Promise {
let me = self.inner.clone();
future_to_promise(async move {
Ok(serde_json::to_string(
&me.export_room_keys(|session| {
let session = session.clone();
predicate
.call1(&JsValue::NULL, &olm::InboundGroupSession::from(session).into())
.expect("Predicate function passed to `export_room_keys` failed")
.as_bool()
.unwrap_or(false)
})
.await?,
)?)
})
}
/// Import the given room keys into our store.
///
/// `exported_keys` is a list of previously exported keys that should be
/// imported into our store. If we already have a better version of a key,
/// the key will _not_ be imported.
///
/// `progress_listener` is a closure that takes 2 arguments: `progress` and
/// `total`, and returns nothing.
#[wasm_bindgen(js_name = "importRoomKeys")]
pub fn import_room_keys(
&self,
exported_room_keys: &str,
progress_listener: Function,
) -> Result<Promise, JsError> {
let me = self.inner.clone();
let exported_room_keys: Vec<matrix_sdk_crypto::olm::ExportedRoomKey> =
serde_json::from_str(exported_room_keys)?;
Ok(future_to_promise(async move {
let matrix_sdk_crypto::RoomKeyImportResult { imported_count, total_count, keys } = me
.import_room_keys(exported_room_keys, false, |progress, total| {
let progress: u64 = progress.try_into().unwrap();
let total: u64 = total.try_into().unwrap();
progress_listener
.call2(&JsValue::NULL, &JsValue::from(progress), &JsValue::from(total))
.expect("Progress listener passed to `import_room_keys` failed");
})
.await?;
Ok(serde_json::to_string(&json!({
"imported_count": imported_count,
"total_count": total_count,
"keys": keys,
}))?)
}))
}
/// Encrypt the list of exported room keys using the given passphrase.
///
/// `exported_room_keys` is a list of sessions that should be encrypted
/// (it's generally returned by `export_room_keys`). `passphrase` is the
/// passphrase that will be used to encrypt the exported room keys. And
/// `rounds` is the number of rounds that should be used for the key
/// derivation when the passphrase gets turned into an AES key. More rounds
/// are increasingly computationnally intensive and as such help against
/// brute-force attacks. Should be at least `10_000`, while values in the
/// `100_000` ranges should be preferred.
#[wasm_bindgen(js_name = "encryptExportedRoomKeys")]
pub fn encrypt_exported_room_keys(
exported_room_keys: &str,
passphrase: &str,
rounds: u32,
) -> Result<String, JsError> {
let exported_room_keys: Vec<matrix_sdk_crypto::olm::ExportedRoomKey> =
serde_json::from_str(exported_room_keys)?;
Ok(matrix_sdk_crypto::encrypt_room_key_export(&exported_room_keys, passphrase, rounds)?)
}
/// Try to decrypt a reader into a list of exported room keys.
///
/// `encrypted_exported_room_keys` is the result from
/// `encrypt_exported_room_keys`. `passphrase` is the passphrase that was
/// used when calling `encrypt_exported_room_keys`.
#[wasm_bindgen(js_name = "decryptExportedRoomKeys")]
pub fn decrypt_exported_room_keys(
encrypted_exported_room_keys: &str,
passphrase: &str,
) -> Result<String, JsError> {
Ok(serde_json::to_string(&matrix_sdk_crypto::decrypt_room_key_export(
encrypted_exported_room_keys.as_bytes(),
passphrase,
)?)?)
}
}
@@ -0,0 +1,33 @@
/// We have the following pattern quite often in our code:
///
/// ```rust
/// struct Foo {
/// inner: Bar,
/// }
///
/// impl From<Bar> for Foo {
/// fn from(inner: Bar) -> Self {
/// Self { inner }
/// }
/// }
/// ```
///
/// Because I feel lazy, let's do a macro to write this:
///
/// ```rust
/// struct Foo {
/// inner: Bar,
/// }
///
/// impl_from_to_inner!(Bar => Foo);
/// ```
#[macro_export]
macro_rules! impl_from_to_inner {
($from:ty => $to:ty) => {
impl From<$from> for $to {
fn from(inner: $from) -> Self {
Self { inner }
}
}
};
}
+72
View File
@@ -0,0 +1,72 @@
//! Olm types.
use wasm_bindgen::prelude::*;
use crate::{identifiers, impl_from_to_inner};
/// Struct representing the state of our private cross signing keys,
/// it shows which private cross signing keys we have locally stored.
#[wasm_bindgen]
#[derive(Debug)]
pub struct CrossSigningStatus {
inner: matrix_sdk_crypto::olm::CrossSigningStatus,
}
impl_from_to_inner!(matrix_sdk_crypto::olm::CrossSigningStatus => CrossSigningStatus);
#[wasm_bindgen]
impl CrossSigningStatus {
/// Do we have the master key?
#[wasm_bindgen(getter, js_name = "hasMaster")]
pub fn has_master(&self) -> bool {
self.inner.has_master
}
/// Do we have the self signing key? This one is necessary to sign
/// our own devices.
#[wasm_bindgen(getter, js_name = "hasSelfSigning")]
pub fn has_self_signing(&self) -> bool {
self.inner.has_self_signing
}
/// Do we have the user signing key? This one is necessary to sign
/// other users.
#[wasm_bindgen(getter, js_name = "hasUserSigning")]
pub fn has_user_signing(&self) -> bool {
self.inner.has_user_signing
}
}
/// Inbound group session.
///
/// Inbound group sessions are used to exchange room messages between a group of
/// participants. Inbound group sessions are used to decrypt the room messages.
#[wasm_bindgen]
#[derive(Debug)]
pub struct InboundGroupSession {
inner: matrix_sdk_crypto::olm::InboundGroupSession,
}
impl_from_to_inner!(matrix_sdk_crypto::olm::InboundGroupSession => InboundGroupSession);
#[wasm_bindgen]
impl InboundGroupSession {
/// The room where this session is used in.
#[wasm_bindgen(getter, js_name = "roomId")]
pub fn room_id(&self) -> identifiers::RoomId {
self.inner.room_id().to_owned().into()
}
/// Returns the unique identifier for this session.
#[wasm_bindgen(getter, js_name = "sessionId")]
pub fn session_id(&self) -> String {
self.inner.session_id().to_owned()
}
/// Has the session been imported from a file or server-side backup? As
/// opposed to being directly received as an `m.room_key` event.
#[wasm_bindgen(js_name = "hasBeenImported")]
pub fn has_been_imported(&self) -> bool {
self.inner.has_been_imported()
}
}
@@ -0,0 +1,419 @@
//! Types to handle requests.
use js_sys::JsString;
use matrix_sdk_crypto::{
requests::{
KeysBackupRequest as OriginalKeysBackupRequest,
KeysQueryRequest as OriginalKeysQueryRequest,
RoomMessageRequest as OriginalRoomMessageRequest,
ToDeviceRequest as OriginalToDeviceRequest,
UploadSigningKeysRequest as OriginalUploadSigningKeysRequest,
},
OutgoingRequests,
};
use ruma::api::client::keys::{
claim_keys::v3::Request as OriginalKeysClaimRequest,
upload_keys::v3::Request as OriginalKeysUploadRequest,
upload_signatures::v3::Request as OriginalSignatureUploadRequest,
};
use wasm_bindgen::prelude::*;
/** Outgoing Requests * */
/// Data for a request to the `/keys/upload` API endpoint
/// ([specification]).
///
/// Publishes end-to-end encryption keys for the device.
///
/// [specification]: https://spec.matrix.org/unstable/client-server-api/#post_matrixclientv3keysupload
#[derive(Debug)]
#[wasm_bindgen(getter_with_clone)]
pub struct KeysUploadRequest {
/// The request ID.
#[wasm_bindgen(readonly)]
pub id: Option<JsString>,
/// A JSON-encoded object of form:
///
/// ```json
/// {"device_keys": …, "one_time_keys": …, "fallback_keys": …}
/// ```
#[wasm_bindgen(readonly)]
pub body: JsString,
}
#[wasm_bindgen]
impl KeysUploadRequest {
/// Create a new `KeysUploadRequest`.
#[wasm_bindgen(constructor)]
pub fn new(id: JsString, body: JsString) -> KeysUploadRequest {
Self { id: Some(id), body }
}
/// Get its request type.
#[wasm_bindgen(getter, js_name = "type")]
pub fn request_type(&self) -> RequestType {
RequestType::KeysUpload
}
}
/// Data for a request to the `/keys/query` API endpoint
/// ([specification]).
///
/// Returns the current devices and identity keys for the given users.
///
/// [specification]: https://spec.matrix.org/unstable/client-server-api/#post_matrixclientv3keysquery
#[derive(Debug)]
#[wasm_bindgen(getter_with_clone)]
pub struct KeysQueryRequest {
/// The request ID.
#[wasm_bindgen(readonly)]
pub id: Option<JsString>,
/// A JSON-encoded object of form:
///
/// ```json
/// {"timeout": …, "device_keys": …, "token": …}
/// ```
#[wasm_bindgen(readonly)]
pub body: JsString,
}
#[wasm_bindgen]
impl KeysQueryRequest {
/// Create a new `KeysQueryRequest`.
#[wasm_bindgen(constructor)]
pub fn new(id: JsString, body: JsString) -> KeysQueryRequest {
Self { id: Some(id), body }
}
/// Get its request type.
#[wasm_bindgen(getter, js_name = "type")]
pub fn request_type(&self) -> RequestType {
RequestType::KeysQuery
}
}
/// Data for a request to the `/keys/claim` API endpoint
/// ([specification]).
///
/// Claims one-time keys that can be used to establish 1-to-1 E2EE
/// sessions.
///
/// [specification]: https://spec.matrix.org/unstable/client-server-api/#post_matrixclientv3keysclaim
#[derive(Debug)]
#[wasm_bindgen(getter_with_clone)]
pub struct KeysClaimRequest {
/// The request ID.
#[wasm_bindgen(readonly)]
pub id: Option<JsString>,
/// A JSON-encoded object of form:
///
/// ```json
/// {"timeout": …, "one_time_keys": …}
/// ```
#[wasm_bindgen(readonly)]
pub body: JsString,
}
#[wasm_bindgen]
impl KeysClaimRequest {
/// Create a new `KeysClaimRequest`.
#[wasm_bindgen(constructor)]
pub fn new(id: JsString, body: JsString) -> KeysClaimRequest {
Self { id: Some(id), body }
}
/// Get its request type.
#[wasm_bindgen(getter, js_name = "type")]
pub fn request_type(&self) -> RequestType {
RequestType::KeysClaim
}
}
/// Data for a request to the `/sendToDevice` API endpoint
/// ([specification]).
///
/// Send an event to a single device or to a group of devices.
///
/// [specification]: https://spec.matrix.org/unstable/client-server-api/#put_matrixclientv3sendtodeviceeventtypetxnid
#[derive(Debug)]
#[wasm_bindgen(getter_with_clone)]
pub struct ToDeviceRequest {
/// The request ID.
#[wasm_bindgen(readonly)]
pub id: Option<JsString>,
/// A JSON-encoded object of form:
///
/// ```json
/// {"event_type": …, "txn_id": …, "messages": …}
/// ```
#[wasm_bindgen(readonly)]
pub body: JsString,
}
#[wasm_bindgen]
impl ToDeviceRequest {
/// Create a new `ToDeviceRequest`.
#[wasm_bindgen(constructor)]
pub fn new(id: JsString, body: JsString) -> ToDeviceRequest {
Self { id: Some(id), body }
}
/// Get its request type.
#[wasm_bindgen(getter, js_name = "type")]
pub fn request_type(&self) -> RequestType {
RequestType::ToDevice
}
}
/// Data for a request to the `/keys/signatures/upload` API endpoint
/// ([specification]).
///
/// Publishes cross-signing signatures for the user.
///
/// [specification]: https://spec.matrix.org/unstable/client-server-api/#post_matrixclientv3keyssignaturesupload
#[derive(Debug)]
#[wasm_bindgen(getter_with_clone)]
pub struct SignatureUploadRequest {
/// The request ID.
#[wasm_bindgen(readonly)]
pub id: Option<JsString>,
/// A JSON-encoded object of form:
///
/// ```json
/// {"signed_keys": …, "txn_id": …, "messages": …}
/// ```
#[wasm_bindgen(readonly)]
pub body: JsString,
}
#[wasm_bindgen]
impl SignatureUploadRequest {
/// Create a new `SignatureUploadRequest`.
#[wasm_bindgen(constructor)]
pub fn new(id: JsString, body: JsString) -> SignatureUploadRequest {
Self { id: Some(id), body }
}
/// Get its request type.
#[wasm_bindgen(getter, js_name = "type")]
pub fn request_type(&self) -> RequestType {
RequestType::SignatureUpload
}
}
/// A customized owned request type for sending out room messages
/// ([specification]).
///
/// [specification]: https://spec.matrix.org/unstable/client-server-api/#put_matrixclientv3roomsroomidsendeventtypetxnid
#[derive(Debug)]
#[wasm_bindgen(getter_with_clone)]
pub struct RoomMessageRequest {
/// The request ID.
#[wasm_bindgen(readonly)]
pub id: Option<JsString>,
/// A JSON-encoded object of form:
///
/// ```json
/// {"room_id": …, "txn_id": …, "content": …}
/// ```
#[wasm_bindgen(readonly)]
pub body: JsString,
}
#[wasm_bindgen]
impl RoomMessageRequest {
/// Create a new `RoomMessageRequest`.
#[wasm_bindgen(constructor)]
pub fn new(id: JsString, body: JsString) -> RoomMessageRequest {
Self { id: Some(id), body }
}
/// Get its request type.
#[wasm_bindgen(getter, js_name = "type")]
pub fn request_type(&self) -> RequestType {
RequestType::RoomMessage
}
}
/// A request that will back up a batch of room keys to the server
/// ([specification]).
///
/// [specification]: https://spec.matrix.org/unstable/client-server-api/#put_matrixclientv3room_keyskeys
#[derive(Debug)]
#[wasm_bindgen(getter_with_clone)]
pub struct KeysBackupRequest {
/// The request ID.
#[wasm_bindgen(readonly)]
pub id: Option<JsString>,
/// A JSON-encoded object of form:
///
/// ```json
/// {"rooms": …}
/// ```
#[wasm_bindgen(readonly)]
pub body: JsString,
}
/** Other Requests * */
/// Request that will publish a cross signing identity.
///
/// This uploads the public cross signing key triplet.
#[wasm_bindgen(getter_with_clone)]
#[derive(Debug)]
pub struct SigningKeysUploadRequest {
/// The request ID.
#[wasm_bindgen(readonly)]
pub id: Option<JsString>,
/// A JSON-encoded object of form:
///
/// ```json
/// {"master_key": …, "self_signing_key": …, "user_signing_key": …}
/// ```
#[wasm_bindgen(readonly)]
pub body: JsString,
}
#[wasm_bindgen]
impl KeysBackupRequest {
/// Create a new `KeysBackupRequest`.
#[wasm_bindgen(constructor)]
pub fn new(id: JsString, body: JsString) -> KeysBackupRequest {
Self { id: Some(id), body }
}
/// Get its request type.
#[wasm_bindgen(getter, js_name = "type")]
pub fn request_type(&self) -> RequestType {
RequestType::KeysBackup
}
}
macro_rules! request {
($destination_request:ident from $source_request:ident maps fields $( $field:ident ),+ $(,)? ) => {
impl $destination_request {
pub(crate) fn to_json(request: &$source_request) -> Result<String, serde_json::Error> {
let mut map = serde_json::Map::new();
$(
map.insert(stringify!($field).to_owned(), serde_json::to_value(&request.$field).unwrap());
)+
let object = serde_json::Value::Object(map);
serde_json::to_string(&object)
}
}
impl TryFrom<&$source_request> for $destination_request {
type Error = serde_json::Error;
fn try_from(request: &$source_request) -> Result<Self, Self::Error> {
Ok($destination_request {
id: None,
body: Self::to_json(request)?.into(),
})
}
}
impl TryFrom<(String, &$source_request)> for $destination_request {
type Error = serde_json::Error;
fn try_from(
(request_id, request): (String, &$source_request),
) -> Result<Self, Self::Error> {
Ok($destination_request {
id: Some(request_id.into()),
body: Self::to_json(request)?.into(),
})
}
}
};
}
// Outgoing Requests
request!(KeysUploadRequest from OriginalKeysUploadRequest maps fields device_keys, one_time_keys, fallback_keys);
request!(KeysQueryRequest from OriginalKeysQueryRequest maps fields timeout, device_keys, token);
request!(KeysClaimRequest from OriginalKeysClaimRequest maps fields timeout, one_time_keys);
request!(ToDeviceRequest from OriginalToDeviceRequest maps fields event_type, txn_id, messages);
request!(SignatureUploadRequest from OriginalSignatureUploadRequest maps fields signed_keys);
request!(RoomMessageRequest from OriginalRoomMessageRequest maps fields room_id, txn_id, content);
request!(KeysBackupRequest from OriginalKeysBackupRequest maps fields rooms);
// Other Requests
request!(SigningKeysUploadRequest from OriginalUploadSigningKeysRequest maps fields master_key, self_signing_key, user_signing_key);
// JavaScript has no complex enums like Rust. To return structs of
// different types, we have no choice that hiding everything behind a
// `JsValue`.
pub(crate) struct OutgoingRequest(pub(crate) matrix_sdk_crypto::OutgoingRequest);
impl TryFrom<OutgoingRequest> for JsValue {
type Error = serde_json::Error;
fn try_from(outgoing_request: OutgoingRequest) -> Result<Self, Self::Error> {
let request_id = outgoing_request.0.request_id().to_string();
Ok(match outgoing_request.0.request() {
OutgoingRequests::KeysUpload(request) => {
JsValue::from(KeysUploadRequest::try_from((request_id, request))?)
}
OutgoingRequests::KeysQuery(request) => {
JsValue::from(KeysQueryRequest::try_from((request_id, request))?)
}
OutgoingRequests::KeysClaim(request) => {
JsValue::from(KeysClaimRequest::try_from((request_id, request))?)
}
OutgoingRequests::ToDeviceRequest(request) => {
JsValue::from(ToDeviceRequest::try_from((request_id, request))?)
}
OutgoingRequests::SignatureUpload(request) => {
JsValue::from(SignatureUploadRequest::try_from((request_id, request))?)
}
OutgoingRequests::RoomMessage(request) => {
JsValue::from(RoomMessageRequest::try_from((request_id, request))?)
}
OutgoingRequests::KeysBackup(request) => {
JsValue::from(KeysBackupRequest::try_from((request_id, request))?)
}
})
}
}
/// Represent the type of a request.
#[wasm_bindgen]
#[derive(Debug)]
pub enum RequestType {
/// Represents a `KeysUploadRequest`.
KeysUpload,
/// Represents a `KeysQueryRequest`.
KeysQuery,
/// Represents a `KeysClaimRequest`.
KeysClaim,
/// Represents a `ToDeviceRequest`.
ToDevice,
/// Represents a `SignatureUploadRequest`.
SignatureUpload,
/// Represents a `RoomMessageRequest`.
RoomMessage,
/// Represents a `KeysBackupRequest`.
KeysBackup,
}
@@ -0,0 +1,206 @@
//! Types related to responses.
use std::borrow::Borrow;
use js_sys::{Array, JsString};
use matrix_sdk_common::deserialized_responses::{AlgorithmInfo, EncryptionInfo};
use matrix_sdk_crypto::IncomingResponse;
pub(crate) use ruma::api::client::{
backup::add_backup_keys::v3::Response as KeysBackupResponse,
keys::{
claim_keys::v3::Response as KeysClaimResponse, get_keys::v3::Response as KeysQueryResponse,
upload_keys::v3::Response as KeysUploadResponse,
upload_signatures::v3::Response as SignatureUploadResponse,
},
message::send_message_event::v3::Response as RoomMessageResponse,
to_device::send_event_to_device::v3::Response as ToDeviceResponse,
};
use ruma::api::IncomingResponse as RumaIncomingResponse;
use wasm_bindgen::prelude::*;
use crate::{encryption, identifiers, requests::RequestType};
pub(crate) fn response_from_string(body: &str) -> http::Result<http::Response<Vec<u8>>> {
http::Response::builder().status(200).body(body.as_bytes().to_vec())
}
/// Intermediate private type to store an incoming owned response,
/// without the need to manage lifetime.
pub(crate) enum OwnedResponse {
KeysUpload(KeysUploadResponse),
KeysQuery(KeysQueryResponse),
KeysClaim(KeysClaimResponse),
ToDevice(ToDeviceResponse),
SignatureUpload(SignatureUploadResponse),
RoomMessage(RoomMessageResponse),
KeysBackup(KeysBackupResponse),
}
impl From<KeysUploadResponse> for OwnedResponse {
fn from(response: KeysUploadResponse) -> Self {
OwnedResponse::KeysUpload(response)
}
}
impl From<KeysQueryResponse> for OwnedResponse {
fn from(response: KeysQueryResponse) -> Self {
OwnedResponse::KeysQuery(response)
}
}
impl From<KeysClaimResponse> for OwnedResponse {
fn from(response: KeysClaimResponse) -> Self {
OwnedResponse::KeysClaim(response)
}
}
impl From<ToDeviceResponse> for OwnedResponse {
fn from(response: ToDeviceResponse) -> Self {
OwnedResponse::ToDevice(response)
}
}
impl From<SignatureUploadResponse> for OwnedResponse {
fn from(response: SignatureUploadResponse) -> Self {
Self::SignatureUpload(response)
}
}
impl From<RoomMessageResponse> for OwnedResponse {
fn from(response: RoomMessageResponse) -> Self {
OwnedResponse::RoomMessage(response)
}
}
impl From<KeysBackupResponse> for OwnedResponse {
fn from(r: KeysBackupResponse) -> Self {
Self::KeysBackup(r)
}
}
impl TryFrom<(RequestType, http::Response<Vec<u8>>)> for OwnedResponse {
type Error = JsError;
fn try_from(
(request_type, response): (RequestType, http::Response<Vec<u8>>),
) -> Result<Self, Self::Error> {
match request_type {
RequestType::KeysUpload => {
KeysUploadResponse::try_from_http_response(response).map(Into::into)
}
RequestType::KeysQuery => {
KeysQueryResponse::try_from_http_response(response).map(Into::into)
}
RequestType::KeysClaim => {
KeysClaimResponse::try_from_http_response(response).map(Into::into)
}
RequestType::ToDevice => {
ToDeviceResponse::try_from_http_response(response).map(Into::into)
}
RequestType::SignatureUpload => {
SignatureUploadResponse::try_from_http_response(response).map(Into::into)
}
RequestType::RoomMessage => {
RoomMessageResponse::try_from_http_response(response).map(Into::into)
}
RequestType::KeysBackup => {
KeysBackupResponse::try_from_http_response(response).map(Into::into)
}
}
.map_err(JsError::from)
}
}
impl<'a> From<&'a OwnedResponse> for IncomingResponse<'a> {
fn from(response: &'a OwnedResponse) -> Self {
match response {
OwnedResponse::KeysUpload(response) => IncomingResponse::KeysUpload(response),
OwnedResponse::KeysQuery(response) => IncomingResponse::KeysQuery(response),
OwnedResponse::KeysClaim(response) => IncomingResponse::KeysClaim(response),
OwnedResponse::ToDevice(response) => IncomingResponse::ToDevice(response),
OwnedResponse::SignatureUpload(response) => IncomingResponse::SignatureUpload(response),
OwnedResponse::RoomMessage(response) => IncomingResponse::RoomMessage(response),
OwnedResponse::KeysBackup(response) => IncomingResponse::KeysBackup(response),
}
}
}
/// A decrypted room event.
#[wasm_bindgen(getter_with_clone)]
#[derive(Debug)]
pub struct DecryptedRoomEvent {
/// The JSON-encoded decrypted event.
#[wasm_bindgen(readonly)]
pub event: JsString,
encryption_info: Option<EncryptionInfo>,
}
#[wasm_bindgen]
impl DecryptedRoomEvent {
/// The user ID of the event sender, note this is untrusted data
/// unless the `verification_state` is as well trusted.
#[wasm_bindgen(getter)]
pub fn sender(&self) -> Option<identifiers::UserId> {
Some(identifiers::UserId::from(self.encryption_info.as_ref()?.sender.clone()))
}
/// The device ID of the device that sent us the event, note this
/// is untrusted data unless `verification_state` is as well
/// trusted.
#[wasm_bindgen(getter, js_name = "senderDevice")]
pub fn sender_device(&self) -> Option<identifiers::DeviceId> {
Some(identifiers::DeviceId::from(self.encryption_info.as_ref()?.sender_device.clone()))
}
/// The Curve25519 key of the device that created the megolm
/// decryption key originally.
#[wasm_bindgen(getter, js_name = "senderCurve25519Key")]
pub fn sender_curve25519_key(&self) -> Option<JsString> {
Some(match &self.encryption_info.as_ref()?.algorithm_info {
AlgorithmInfo::MegolmV1AesSha2 { curve25519_key, .. } => curve25519_key.clone().into(),
})
}
/// The signing Ed25519 key that have created the megolm key that
/// was used to decrypt this session.
#[wasm_bindgen(getter, js_name = "senderClaimedEd25519Key")]
pub fn sender_claimed_ed25519_key(&self) -> Option<JsString> {
match &self.encryption_info.as_ref()?.algorithm_info {
AlgorithmInfo::MegolmV1AesSha2 { sender_claimed_keys, .. } => {
sender_claimed_keys.get(&ruma::DeviceKeyAlgorithm::Ed25519).cloned().map(Into::into)
}
}
}
/// Chain of Curve25519 keys through which this session was
/// forwarded, via `m.forwarded_room_key` events.
#[wasm_bindgen(getter, js_name = "forwardingCurve25519KeyChain")]
pub fn forwarding_curve25519_key_chain(&self) -> Array {
Array::new()
}
/// The verification state of the device that sent us the event,
/// note this is the state of the device at the time of
/// decryption. It may change in the future if a device gets
/// verified or deleted.
#[wasm_bindgen(getter, js_name = "verificationState")]
pub fn verification_state(&self) -> Option<encryption::VerificationState> {
Some((self.encryption_info.as_ref()?.verification_state.borrow()).into())
}
}
impl From<matrix_sdk_common::deserialized_responses::TimelineEvent> for DecryptedRoomEvent {
fn from(value: matrix_sdk_common::deserialized_responses::TimelineEvent) -> Self {
Self {
event: value.event.json().get().to_owned().into(),
encryption_info: value.encryption_info,
}
}
}
@@ -0,0 +1,36 @@
//! Store types.
use wasm_bindgen::prelude::*;
use crate::impl_from_to_inner;
/// A struct containing private cross signing keys that can be backed
/// up or uploaded to the secret store.
#[wasm_bindgen]
#[derive(Debug)]
pub struct CrossSigningKeyExport {
pub(crate) inner: matrix_sdk_crypto::store::CrossSigningKeyExport,
}
impl_from_to_inner!(matrix_sdk_crypto::store::CrossSigningKeyExport => CrossSigningKeyExport);
#[wasm_bindgen]
impl CrossSigningKeyExport {
/// The seed of the master key encoded as unpadded base64.
#[wasm_bindgen(getter, js_name = "masterKey")]
pub fn master_key(&self) -> Option<String> {
self.inner.master_key.clone()
}
/// The seed of the self signing key encoded as unpadded base64.
#[wasm_bindgen(getter, js_name = "self_signing_key")]
pub fn self_signing_key(&self) -> Option<String> {
self.inner.self_signing_key.clone()
}
/// The seed of the user signing key encoded as unpadded base64.
#[wasm_bindgen(getter, js_name = "userSigningKey")]
pub fn user_signing_key(&self) -> Option<String> {
self.inner.user_signing_key.clone()
}
}
@@ -0,0 +1,69 @@
//! `GET /_matrix/client/*/sync`
use js_sys::Array;
use wasm_bindgen::prelude::*;
use crate::{identifiers, js::downcast};
/// Information on E2E device updates.
#[wasm_bindgen]
#[derive(Debug)]
pub struct DeviceLists {
pub(crate) inner: ruma::api::client::sync::sync_events::v3::DeviceLists,
}
#[wasm_bindgen]
impl DeviceLists {
/// Create an empty `DeviceLists`.
///
/// `changed` and `left` must be an array of `UserId`.
#[wasm_bindgen(constructor)]
pub fn new(changed: Option<Array>, left: Option<Array>) -> Result<DeviceLists, JsError> {
let mut inner = ruma::api::client::sync::sync_events::v3::DeviceLists::default();
inner.changed = changed
.unwrap_or_default()
.iter()
.map(|user| Ok(downcast::<identifiers::UserId>(&user, "UserId")?.inner.clone()))
.collect::<Result<Vec<ruma::OwnedUserId>, JsError>>()?;
inner.left = left
.unwrap_or_default()
.iter()
.map(|user| Ok(downcast::<identifiers::UserId>(&user, "UserId")?.inner.clone()))
.collect::<Result<Vec<ruma::OwnedUserId>, JsError>>()?;
Ok(Self { inner })
}
/// Returns true if there are no device list updates.
#[wasm_bindgen(js_name = "isEmpty")]
pub fn is_empty(&self) -> bool {
self.inner.is_empty()
}
/// List of users who have updated their device identity keys or
/// who now share an encrypted room with the client since the
/// previous sync
#[wasm_bindgen(getter)]
pub fn changed(&self) -> Array {
self.inner
.changed
.iter()
.map(|user| identifiers::UserId::from(user.clone()))
.map(JsValue::from)
.collect()
}
/// List of users who no longer share encrypted rooms since the
/// previous sync response.
#[wasm_bindgen(getter)]
pub fn left(&self) -> Array {
self.inner
.left
.iter()
.map(|user| identifiers::UserId::from(user.clone()))
.map(JsValue::from)
.collect()
}
}
@@ -0,0 +1,290 @@
use wasm_bindgen::prelude::*;
/// Logger level.
#[wasm_bindgen]
#[derive(Debug, Clone)]
pub enum LoggerLevel {
/// `TRACE` level.
///
/// Designate very low priority, often extremely verbose,
/// information.
Trace,
/// `DEBUG` level.
///
/// Designate lower priority information.
Debug,
/// `INFO` level.
///
/// Designate useful information.
Info,
/// `WARN` level.
///
/// Designate hazardous situations.
Warn,
/// `ERROR` level.
///
/// Designate very serious errors.
Error,
}
#[cfg(feature = "tracing")]
mod inner {
use std::{
fmt,
fmt::Write as _,
sync::{Arc, Once},
};
use tracing::{
field::{Field, Visit},
metadata::LevelFilter,
Event, Level, Metadata, Subscriber,
};
use tracing_subscriber::{
layer::{Context, Layer as TracingLayer},
prelude::*,
reload, Registry,
};
use super::*;
type TracingInner = Arc<reload::Handle<Layer, Registry>>;
/// Type to install and to manipulate the tracing layer.
#[wasm_bindgen]
pub struct Tracing {
handle: TracingInner,
}
impl fmt::Debug for Tracing {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Tracing").finish_non_exhaustive()
}
}
#[wasm_bindgen]
impl Tracing {
/// Check whether the `tracing` feature has been enabled.
#[wasm_bindgen(js_name = "isAvailable")]
pub fn is_available() -> bool {
true
}
/// Install the tracing layer.
///
/// `Tracing` is a singleton. Once it is installed,
/// consecutive calls to the constructor will construct a new
/// `Tracing` object but with the exact same inner
/// state. Calling the constructor with a new `min_level` will
/// just update the `min_level` parameter; in that regard, it
/// is similar to calling the `min_level` method on an
/// existing `Tracing` object.
#[wasm_bindgen(constructor)]
pub fn new(min_level: LoggerLevel) -> Result<Tracing, JsError> {
static mut INSTALL: Option<TracingInner> = None;
static INSTALLED: Once = Once::new();
INSTALLED.call_once(|| {
let (filter, reload_handle) = reload::Layer::new(Layer::new(min_level.clone()));
tracing_subscriber::registry().with(filter).init();
unsafe { INSTALL = Some(Arc::new(reload_handle)) };
});
let tracing = Tracing {
handle: unsafe { INSTALL.as_ref() }
.cloned()
.expect("`Tracing` has not been installed correctly"),
};
// If it's not the first call to `install`, the
// `min_level` can be different. Let's update it.
tracing.min_level(min_level);
Ok(tracing)
}
/// Re-define the minimum logger level.
#[wasm_bindgen(setter, js_name = "minLevel")]
pub fn min_level(&self, min_level: LoggerLevel) {
let _ = self.handle.modify(|layer| layer.min_level = min_level.into());
}
/// Turn the logger on, i.e. it emits logs again if it was turned
/// off.
#[wasm_bindgen(js_name = "turnOn")]
pub fn turn_on(&self) {
let _ = self.handle.modify(|layer| layer.turn_on());
}
/// Turn the logger off, i.e. it no long emits logs.
#[wasm_bindgen(js_name = "turnOff")]
pub fn turn_off(&self) {
let _ = self.handle.modify(|layer| layer.turn_off());
}
}
impl From<LoggerLevel> for Level {
fn from(value: LoggerLevel) -> Self {
use LoggerLevel::*;
match value {
Trace => Self::TRACE,
Debug => Self::DEBUG,
Info => Self::INFO,
Warn => Self::WARN,
Error => Self::ERROR,
}
}
}
#[wasm_bindgen]
extern "C" {
#[wasm_bindgen(js_namespace = console, js_name = "trace")]
fn log_trace(message: String);
#[wasm_bindgen(js_namespace = console, js_name = "debug")]
fn log_debug(message: String);
#[wasm_bindgen(js_namespace = console, js_name = "info")]
fn log_info(message: String);
#[wasm_bindgen(js_namespace = console, js_name = "warn")]
fn log_warn(message: String);
#[wasm_bindgen(js_namespace = console, js_name = "error")]
fn log_error(message: String);
}
struct Layer {
min_level: Level,
enabled: bool,
}
impl Layer {
fn new<L>(min_level: L) -> Self
where
L: Into<Level>,
{
Self { min_level: min_level.into(), enabled: true }
}
fn turn_on(&mut self) {
self.enabled = true;
}
fn turn_off(&mut self) {
self.enabled = false;
}
}
impl<S> TracingLayer<S> for Layer
where
S: Subscriber,
{
fn enabled(&self, metadata: &Metadata<'_>, _: Context<'_, S>) -> bool {
self.enabled && metadata.level() <= &self.min_level
}
fn max_level_hint(&self) -> Option<LevelFilter> {
if !self.enabled {
Some(LevelFilter::OFF)
} else {
Some(LevelFilter::from_level(self.min_level))
}
}
fn on_event(&self, event: &Event<'_>, _: Context<'_, S>) {
let mut recorder = StringVisitor::new();
event.record(&mut recorder);
let metadata = event.metadata();
let level = metadata.level();
let origin = metadata
.file()
.and_then(|file| metadata.line().map(|ln| format!("{file}:{ln}")))
.unwrap_or_default();
let message = format!("{level} {origin}{recorder}");
match *level {
Level::TRACE => log_trace(message),
Level::DEBUG => log_debug(message),
Level::INFO => log_info(message),
Level::WARN => log_warn(message),
Level::ERROR => log_error(message),
}
}
}
struct StringVisitor {
string: String,
}
impl StringVisitor {
fn new() -> Self {
Self { string: String::new() }
}
}
impl Visit for StringVisitor {
fn record_debug(&mut self, field: &Field, value: &dyn fmt::Debug) {
match field.name() {
"message" => {
if !self.string.is_empty() {
self.string.push('\n');
}
let _ = write!(self.string, "{value:?}");
}
field_name => {
let _ = write!(self.string, "\n{field_name} = {value:?}");
}
}
}
}
impl fmt::Display for StringVisitor {
fn fmt(&self, mut f: &mut fmt::Formatter<'_>) -> fmt::Result {
if !self.string.is_empty() {
write!(&mut f, " {}", self.string)
} else {
Ok(())
}
}
}
}
#[cfg(not(feature = "tracing"))]
mod inner {
use super::*;
/// Type to install and to manipulate the tracing layer.
#[wasm_bindgen]
#[derive(Debug)]
pub struct Tracing;
#[wasm_bindgen]
impl Tracing {
/// Check whether the `tracing` feature has been enabled.
#[wasm_bindgen(js_name = "isAvailable")]
pub fn is_available() -> bool {
false
}
/// The `tracing` feature is not enabled, so this constructor
/// will raise an error.
#[wasm_bindgen(constructor)]
pub fn new(_min_level: LoggerLevel) -> Result<Tracing, JsError> {
Err(JsError::new("The `tracing` feature is disabled. Check `Tracing.isAvailable` before constructing `Tracing`"))
}
}
}
pub use inner::*;
+156
View File
@@ -0,0 +1,156 @@
//! Extra types, like `Signatures`.
use js_sys::Map;
use wasm_bindgen::prelude::*;
use crate::{
identifiers::{DeviceKeyId, UserId},
impl_from_to_inner,
vodozemac::Ed25519Signature,
};
/// A collection of `Signature`.
#[wasm_bindgen]
#[derive(Debug, Default)]
pub struct Signatures {
inner: matrix_sdk_crypto::types::Signatures,
}
impl_from_to_inner!(matrix_sdk_crypto::types::Signatures => Signatures);
#[wasm_bindgen]
impl Signatures {
/// Creates a new, empty, signatures collection.
#[wasm_bindgen(constructor)]
pub fn new() -> Self {
matrix_sdk_crypto::types::Signatures::new().into()
}
/// Add the given signature from the given signer and the given key ID to
/// the collection.
#[wasm_bindgen(js_name = "addSignature")]
pub fn add_signature(
&mut self,
signer: &UserId,
key_id: &DeviceKeyId,
signature: &Ed25519Signature,
) -> Option<MaybeSignature> {
self.inner
.add_signature(signer.inner.clone(), key_id.inner.clone(), signature.inner)
.map(Into::into)
}
/// Try to find an Ed25519 signature from the given signer with
/// the given key ID.
#[wasm_bindgen(js_name = "getSignature")]
pub fn get_signature(&self, signer: &UserId, key_id: &DeviceKeyId) -> Option<Ed25519Signature> {
self.inner.get_signature(signer.inner.as_ref(), key_id.inner.as_ref()).map(Into::into)
}
/// Get the map of signatures that belong to the given user.
pub fn get(&self, signer: &UserId) -> Option<Map> {
let map = Map::new();
for (device_key_id, maybe_signature) in
self.inner.get(signer.inner.as_ref()).map(|map| {
map.iter().map(|(device_key_id, maybe_signature)| {
(
device_key_id.as_str().to_owned(),
MaybeSignature::from(maybe_signature.clone()),
)
})
})?
{
map.set(&device_key_id.into(), &maybe_signature.into());
}
Some(map)
}
/// Remove all the signatures we currently hold.
pub fn clear(&mut self) {
self.inner.clear();
}
/// Do we hold any signatures or is our collection completely
/// empty.
#[wasm_bindgen(js_name = "isEmpty")]
pub fn is_empty(&self) -> bool {
self.inner.is_empty()
}
/// How many signatures do we currently hold.
#[wasm_bindgen(getter)]
pub fn count(&self) -> usize {
self.inner.signature_count()
}
}
/// Represents a potentially decoded signature (but not a validated
/// one).
#[wasm_bindgen]
#[derive(Debug)]
pub struct Signature {
inner: matrix_sdk_crypto::types::Signature,
}
impl_from_to_inner!(matrix_sdk_crypto::types::Signature => Signature);
#[wasm_bindgen]
impl Signature {
/// Get the Ed25519 signature, if this is one.
#[wasm_bindgen(getter)]
pub fn ed25519(&self) -> Option<Ed25519Signature> {
self.inner.ed25519().map(Into::into)
}
/// Convert the signature to a base64 encoded string.
#[wasm_bindgen(js_name = "toBase64")]
pub fn to_base64(&self) -> String {
self.inner.to_base64()
}
}
type MaybeSignatureInner =
Result<matrix_sdk_crypto::types::Signature, matrix_sdk_crypto::types::InvalidSignature>;
/// Represents a signature that is either valid _or_ that could not be
/// decoded.
#[wasm_bindgen]
#[derive(Debug)]
pub struct MaybeSignature {
inner: MaybeSignatureInner,
}
impl_from_to_inner!(MaybeSignatureInner => MaybeSignature);
#[wasm_bindgen]
impl MaybeSignature {
/// Check whether the signature has been successfully decoded.
#[wasm_bindgen(js_name = "isValid")]
pub fn is_valid(&self) -> bool {
self.inner.is_ok()
}
/// Check whether the signature could not be successfully decoded.
#[wasm_bindgen(js_name = "isInvalid")]
pub fn is_invalid(&self) -> bool {
self.inner.is_err()
}
/// The signature, if successfully decoded.
#[wasm_bindgen(getter)]
pub fn signature(&self) -> Option<Signature> {
self.inner.as_ref().cloned().map(Into::into).ok()
}
/// The base64 encoded string that is claimed to contain a
/// signature but could not be decoded, if any.
#[wasm_bindgen(getter, js_name = "invalidSignatureSource")]
pub fn invalid_signature_source(&self) -> Option<String> {
match &self.inner {
Ok(_) => None,
Err(signature) => Some(signature.source.clone()),
}
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,193 @@
//! Vodozemac types.
use wasm_bindgen::prelude::*;
use crate::impl_from_to_inner;
/// An Ed25519 public key, used to verify digital signatures.
#[wasm_bindgen]
#[derive(Debug, Clone)]
pub struct Ed25519PublicKey {
inner: vodozemac::Ed25519PublicKey,
}
#[wasm_bindgen]
impl Ed25519PublicKey {
/// The number of bytes an Ed25519 public key has.
#[wasm_bindgen(getter)]
pub fn length(&self) -> usize {
vodozemac::Ed25519PublicKey::LENGTH
}
/// Serialize an Ed25519 public key to an unpadded base64
/// representation.
#[wasm_bindgen(js_name = "toBase64")]
pub fn to_base64(&self) -> String {
self.inner.to_base64()
}
}
impl_from_to_inner!(vodozemac::Ed25519PublicKey => Ed25519PublicKey);
/// An Ed25519 digital signature, can be used to verify the
/// authenticity of a message.
#[wasm_bindgen]
#[derive(Debug)]
pub struct Ed25519Signature {
pub(crate) inner: vodozemac::Ed25519Signature,
}
impl_from_to_inner!(vodozemac::Ed25519Signature => Ed25519Signature);
#[wasm_bindgen]
impl Ed25519Signature {
/// Try to create an Ed25519 signature from an unpadded base64
/// representation.
#[wasm_bindgen(constructor)]
pub fn new(signature: String) -> Result<Ed25519Signature, JsError> {
Ok(Self { inner: vodozemac::Ed25519Signature::from_base64(signature.as_str())? })
}
/// Serialize a Ed25519 signature to an unpadded base64
/// representation.
#[wasm_bindgen(js_name = "toBase64")]
pub fn to_base64(&self) -> String {
self.inner.to_base64()
}
}
/// A Curve25519 public key.
#[wasm_bindgen]
#[derive(Debug, Clone)]
pub struct Curve25519PublicKey {
inner: vodozemac::Curve25519PublicKey,
}
#[wasm_bindgen]
impl Curve25519PublicKey {
/// The number of bytes a Curve25519 public key has.
#[wasm_bindgen(getter)]
pub fn length(&self) -> usize {
vodozemac::Curve25519PublicKey::LENGTH
}
/// Serialize an Curve25519 public key to an unpadded base64
/// representation.
#[wasm_bindgen(js_name = "toBase64")]
pub fn to_base64(&self) -> String {
self.inner.to_base64()
}
}
impl_from_to_inner!(vodozemac::Curve25519PublicKey => Curve25519PublicKey);
/// Struct holding the two public identity keys of an account.
#[wasm_bindgen(getter_with_clone)]
#[derive(Debug)]
pub struct IdentityKeys {
/// The Ed25519 public key, used for signing.
pub ed25519: Ed25519PublicKey,
/// The Curve25519 public key, used for establish shared secrets.
pub curve25519: Curve25519PublicKey,
}
impl From<matrix_sdk_crypto::olm::IdentityKeys> for IdentityKeys {
fn from(value: matrix_sdk_crypto::olm::IdentityKeys) -> Self {
Self {
ed25519: Ed25519PublicKey { inner: value.ed25519 },
curve25519: Curve25519PublicKey { inner: value.curve25519 },
}
}
}
/// An enum over the different key types a device can have.
///
/// Currently devices have a curve25519 and ed25519 keypair. The keys
/// transport format is a base64 encoded string, any unknown key type
/// will be left as such a string.
#[wasm_bindgen]
#[derive(Debug)]
pub struct DeviceKey {
inner: matrix_sdk_crypto::types::DeviceKey,
}
impl_from_to_inner!(matrix_sdk_crypto::types::DeviceKey => DeviceKey);
#[wasm_bindgen]
impl DeviceKey {
/// Get the name of the device key.
#[wasm_bindgen(getter)]
pub fn name(&self) -> DeviceKeyName {
(&self.inner).into()
}
/// Get the value associated to the `Curve25519` device key name.
#[wasm_bindgen(getter)]
pub fn curve25519(&self) -> Option<Curve25519PublicKey> {
use matrix_sdk_crypto::types::DeviceKey::*;
match &self.inner {
Curve25519(key) => Some((*key).into()),
_ => None,
}
}
/// Get the value associated to the `Ed25519` device key name.
#[wasm_bindgen(getter)]
pub fn ed25519(&self) -> Option<Ed25519PublicKey> {
use matrix_sdk_crypto::types::DeviceKey::*;
match &self.inner {
Ed25519(key) => Some((*key).into()),
_ => None,
}
}
/// Get the value associated to the `Unknown` device key name.
#[wasm_bindgen(getter)]
pub fn unknown(&self) -> Option<String> {
use matrix_sdk_crypto::types::DeviceKey::*;
match &self.inner {
Unknown(key) => Some(key.clone()),
_ => None,
}
}
/// Convert the `DeviceKey` into a base64 encoded string.
#[wasm_bindgen(js_name = "toBase64")]
pub fn to_base64(&self) -> String {
self.inner.to_base64()
}
}
impl From<&matrix_sdk_crypto::types::DeviceKey> for DeviceKeyName {
fn from(device_key: &matrix_sdk_crypto::types::DeviceKey) -> Self {
use matrix_sdk_crypto::types::DeviceKey::*;
match device_key {
Curve25519(_) => Self::Curve25519,
Ed25519(_) => Self::Ed25519,
Unknown(_) => Self::Unknown,
}
}
}
/// An enum over the different key types a device can have.
///
/// Currently devices have a curve25519 and ed25519 keypair. The keys
/// transport format is a base64 encoded string, any unknown key type
/// will be left as such a string.
#[wasm_bindgen]
#[derive(Debug)]
pub enum DeviceKeyName {
/// The curve25519 device key.
Curve25519,
/// The ed25519 device key.
Ed25519,
/// An unknown device key.
Unknown,
}
@@ -0,0 +1,77 @@
const { Attachment, EncryptedAttachment } = require('../pkg/matrix_sdk_crypto_js');
describe(Attachment.name, () => {
const originalData = 'hello';
const textEncoder = new TextEncoder();
const textDecoder = new TextDecoder();
let encryptedAttachment;
test('can encrypt data', () => {
encryptedAttachment = Attachment.encrypt(textEncoder.encode(originalData));
const mediaEncryptionInfo = JSON.parse(encryptedAttachment.mediaEncryptionInfo);
expect(mediaEncryptionInfo).toMatchObject({
v: 'v2',
key: {
kty: expect.any(String),
key_ops: expect.arrayContaining(['encrypt', 'decrypt']),
alg: expect.any(String),
k: expect.any(String),
ext: expect.any(Boolean),
},
iv: expect.stringMatching(/^[A-Za-z0-9\+/]+$/),
hashes: {
sha256: expect.stringMatching(/^[A-Za-z0-9\+/]+$/)
}
});
const encryptedData = encryptedAttachment.encryptedData;
expect(encryptedData.every((i) => { i != 0 })).toStrictEqual(false);
});
test('can decrypt data', () => {
expect(encryptedAttachment.hasMediaEncryptionInfoBeenConsumed).toStrictEqual(false);
const decryptedAttachment = Attachment.decrypt(encryptedAttachment);
expect(textDecoder.decode(decryptedAttachment)).toStrictEqual(originalData);
expect(encryptedAttachment.hasMediaEncryptionInfoBeenConsumed).toStrictEqual(true);
});
test('can only decrypt once', () => {
expect(encryptedAttachment.hasMediaEncryptionInfoBeenConsumed).toStrictEqual(true);
expect(() => { textDecoder.decode(decryptedAttachment) }).toThrow()
});
});
describe(EncryptedAttachment.name, () => {
const originalData = 'hello';
const textDecoder = new TextDecoder();
test('can be created manually', () => {
const encryptedAttachment = new EncryptedAttachment(
new Uint8Array([24, 150, 67, 37, 144]),
JSON.stringify({
v: 'v2',
key: {
kty: 'oct',
key_ops: [ 'encrypt', 'decrypt' ],
alg: 'A256CTR',
k: 'QbNXUjuukFyEJ8cQZjJuzN6mMokg0HJIjx0wVMLf5BM',
ext: true
},
iv: 'xk2AcWkomiYAAAAAAAAAAA',
hashes: {
sha256: 'JsRbDXgOja4xvDiF3DwBuLHdxUzIrVYIuj7W/t3aEok'
}
})
);
expect(encryptedAttachment.hasMediaEncryptionInfoBeenConsumed).toStrictEqual(false);
expect(textDecoder.decode(Attachment.decrypt(encryptedAttachment))).toStrictEqual(originalData);
expect(encryptedAttachment.hasMediaEncryptionInfoBeenConsumed).toStrictEqual(true);
});
});
@@ -0,0 +1,900 @@
const {
OlmMachine,
UserId,
DeviceId,
DeviceKeyId,
RoomId,
Device,
LocalTrust,
UserDevices,
DeviceKey,
DeviceKeyName,
DeviceKeyAlgorithmName,
Ed25519PublicKey,
Curve25519PublicKey,
Signatures,
VerificationMethod,
VerificationRequest,
ToDeviceRequest,
DeviceLists,
KeysUploadRequest,
RequestType,
KeysQueryRequest,
Sas,
Emoji,
SigningKeysUploadRequest,
SignatureUploadRequest,
Qr,
QrCode,
QrCodeScan,
} = require('../pkg/matrix_sdk_crypto_js');
const { zip, addMachineToMachine } = require('./helper');
describe('LocalTrust', () => {
test('has the correct variant values', () => {
expect(LocalTrust.Verified).toStrictEqual(0);
expect(LocalTrust.BlackListed).toStrictEqual(1);
expect(LocalTrust.Ignored).toStrictEqual(2);
expect(LocalTrust.Unset).toStrictEqual(3);
});
});
describe('DeviceKeyName', () => {
test('has the correct variant values', () => {
expect(DeviceKeyName.Curve25519).toStrictEqual(0);
expect(DeviceKeyName.Ed25519).toStrictEqual(1);
expect(DeviceKeyName.Unknown).toStrictEqual(2);
});
});
describe(OlmMachine.name, () => {
const user = new UserId('@alice:example.org');
const device = new DeviceId('foobar');
const room = new RoomId('!baz:matrix.org');
function machine(new_user, new_device) {
return new OlmMachine(new_user || user, new_device || device);
}
test('can read user devices', async () => {
const m = await machine();
const userDevices = await m.getUserDevices(user);
expect(userDevices).toBeInstanceOf(UserDevices);
expect(userDevices.get(device)).toBeInstanceOf(Device);
expect(userDevices.isAnyVerified()).toStrictEqual(false);
expect(userDevices.keys().map(device_id => device_id.toString())).toStrictEqual([device.toString()]);
expect(userDevices.devices().map(device => device.deviceId.toString())).toStrictEqual([device.toString()]);
});
test('can read a user device', async () => {
const m = await machine();
const dev = await m.getDevice(user, device);
expect(dev).toBeInstanceOf(Device);
expect(dev.isVerified()).toStrictEqual(false);
expect(dev.isCrossSigningTrusted()).toStrictEqual(false);
expect(dev.localTrustState).toStrictEqual(LocalTrust.Unset);
expect(dev.isLocallyTrusted()).toStrictEqual(false);
expect(await dev.setLocalTrust(LocalTrust.Verified)).toBeNull();
expect(dev.localTrustState).toStrictEqual(LocalTrust.Verified);
expect(dev.isLocallyTrusted()).toStrictEqual(true);
expect(dev.userId.toString()).toStrictEqual(user.toString());
expect(dev.deviceId.toString()).toStrictEqual(device.toString());
expect(dev.deviceName).toBeUndefined();
const deviceKey = dev.getKey(DeviceKeyAlgorithmName.Ed25519);
expect(deviceKey).toBeInstanceOf(DeviceKey);
expect(deviceKey.name).toStrictEqual(DeviceKeyName.Ed25519);
expect(deviceKey.curve25519).toBeUndefined();
expect(deviceKey.ed25519).toBeInstanceOf(Ed25519PublicKey);
expect(deviceKey.unknown).toBeUndefined();
expect(deviceKey.toBase64()).toMatch(/^[A-Za-z0-9\+/]+$/);
expect(dev.curve25519Key).toBeInstanceOf(Curve25519PublicKey);
expect(dev.ed25519Key).toBeInstanceOf(Ed25519PublicKey);
for (const [deviceKeyId, deviceKey] of dev.keys) {
expect(deviceKeyId).toBeInstanceOf(DeviceKeyId);
expect(deviceKey).toBeInstanceOf(DeviceKey);
}
expect(dev.signatures).toBeInstanceOf(Signatures);
expect(dev.isBlacklisted()).toStrictEqual(false);
expect(dev.isDeleted()).toStrictEqual(false);
});
});
describe('Key Verification', () => {
const userId1 = new UserId('@alice:example.org');
const deviceId1 = new DeviceId('alice_device');
const userId2 = new UserId('@bob:example.org');
const deviceId2 = new DeviceId('bob_device');
function machine(new_user, new_device) {
return new OlmMachine(new_user || userId1, new_device || deviceId1);
}
describe('SAS', () => {
// First Olm machine.
let m1;
// Second Olm machine.
let m2;
beforeAll(async () => {
m1 = await machine(userId1, deviceId1);
m2 = await machine(userId2, deviceId2);
});
// Verification request for `m1`.
let verificationRequest1;
// The flow ID.
let flowId;
test('can request verification (`m.key.verification.request`)', async () => {
// Make `m1` and `m2` be aware of each other.
{
await addMachineToMachine(m2, m1);
await addMachineToMachine(m1, m2);
}
// Pick the device we want to start the verification with.
const device2 = await m1.getDevice(userId2, deviceId2);
expect(device2).toBeInstanceOf(Device);
let outgoingVerificationRequest;
// Request a verification from `m1` to `device2`.
[verificationRequest1, outgoingVerificationRequest] = await device2.requestVerification();
expect(verificationRequest1).toBeInstanceOf(VerificationRequest);
expect(verificationRequest1.ownUserId.toString()).toStrictEqual(userId1.toString());
expect(verificationRequest1.otherUserId.toString()).toStrictEqual(userId2.toString());
expect(verificationRequest1.otherDeviceId).toBeUndefined();
expect(verificationRequest1.roomId).toBeUndefined();
expect(verificationRequest1.cancelInfo).toBeUndefined();
expect(verificationRequest1.isPassive()).toStrictEqual(false);
expect(verificationRequest1.isReady()).toStrictEqual(false);
expect(verificationRequest1.timedOut()).toStrictEqual(false);
expect(verificationRequest1.theirSupportedMethods).toBeUndefined();
expect(verificationRequest1.ourSupportedMethods).toEqual(expect.arrayContaining([VerificationMethod.SasV1, VerificationMethod.ReciprocateV1]));
expect(verificationRequest1.flowId).toMatch(/^[a-f0-9]+$/);
expect(verificationRequest1.isSelfVerification()).toStrictEqual(false);
expect(verificationRequest1.weStarted()).toStrictEqual(true);
expect(verificationRequest1.isDone()).toStrictEqual(false);
expect(verificationRequest1.isCancelled()).toStrictEqual(false);
expect(outgoingVerificationRequest).toBeInstanceOf(ToDeviceRequest);
outgoingVerificationRequest = JSON.parse(outgoingVerificationRequest.body);
expect(outgoingVerificationRequest.event_type).toStrictEqual('m.key.verification.request');
const toDeviceEvents = {
events: [{
sender: userId1.toString(),
type: outgoingVerificationRequest.event_type,
content: outgoingVerificationRequest.messages[userId2.toString()][deviceId2.toString()],
}]
};
// Let's send the verification request to `m2`.
await m2.receiveSyncChanges(JSON.stringify(toDeviceEvents), new DeviceLists(), new Map(), new Set());
flowId = verificationRequest1.flowId;
});
// Verification request for `m2`.
let verificationRequest2;
test('can fetch received request verification', async () => {
// Oh, a new verification request.
verificationRequest2 = m2.getVerificationRequest(userId1, flowId);
expect(verificationRequest2).toBeInstanceOf(VerificationRequest);
expect(verificationRequest2.ownUserId.toString()).toStrictEqual(userId2.toString());
expect(verificationRequest2.otherUserId.toString()).toStrictEqual(userId1.toString());
expect(verificationRequest2.otherDeviceId.toString()).toStrictEqual(deviceId1.toString());
expect(verificationRequest2.roomId).toBeUndefined();
expect(verificationRequest2.cancelInfo).toBeUndefined();
expect(verificationRequest2.isPassive()).toStrictEqual(false);
expect(verificationRequest2.isReady()).toStrictEqual(false);
expect(verificationRequest2.timedOut()).toStrictEqual(false);
expect(verificationRequest2.theirSupportedMethods).toEqual(expect.arrayContaining([VerificationMethod.SasV1, VerificationMethod.ReciprocateV1]));
expect(verificationRequest2.ourSupportedMethods).toBeUndefined();
expect(verificationRequest2.flowId).toStrictEqual(flowId);
expect(verificationRequest2.isSelfVerification()).toStrictEqual(false);
expect(verificationRequest2.weStarted()).toStrictEqual(false);
expect(verificationRequest2.isDone()).toStrictEqual(false);
expect(verificationRequest2.isCancelled()).toStrictEqual(false);
const verificationRequests = m2.getVerificationRequests(userId1);
expect(verificationRequests).toHaveLength(1);
expect(verificationRequests[0].flowId).toStrictEqual(verificationRequest2.flowId); // there are the same
});
test('can accept a verification request (`m.key.verification.ready`)', async () => {
// Accept the verification request.
let outgoingVerificationRequest = verificationRequest2.accept();
expect(outgoingVerificationRequest).toBeInstanceOf(ToDeviceRequest);
// The request verification is ready.
outgoingVerificationRequest = JSON.parse(outgoingVerificationRequest.body);
expect(outgoingVerificationRequest.event_type).toStrictEqual('m.key.verification.ready');
const toDeviceEvents = {
events: [{
sender: userId2.toString(),
type: outgoingVerificationRequest.event_type,
content: outgoingVerificationRequest.messages[userId1.toString()][deviceId1.toString()],
}],
};
// Let's send the verification ready to `m1`.
await m1.receiveSyncChanges(JSON.stringify(toDeviceEvents), new DeviceLists(), new Map(), new Set());
});
test('verification requests are synchronized and automatically updated', () => {
expect(verificationRequest1.isReady()).toStrictEqual(true);
expect(verificationRequest2.isReady()).toStrictEqual(true);
expect(verificationRequest1.theirSupportedMethods).toEqual(expect.arrayContaining([VerificationMethod.SasV1, VerificationMethod.ReciprocateV1]));
expect(verificationRequest1.ourSupportedMethods).toEqual(expect.arrayContaining([VerificationMethod.SasV1, VerificationMethod.ReciprocateV1]));
expect(verificationRequest2.theirSupportedMethods).toEqual(expect.arrayContaining([VerificationMethod.SasV1, VerificationMethod.ReciprocateV1]));
expect(verificationRequest2.ourSupportedMethods).toEqual(expect.arrayContaining([VerificationMethod.SasV1, VerificationMethod.ReciprocateV1]));
});
// SAS verification for the second machine.
let sas2;
test('can start a SAS verification (`m.key.verification.start`)', async () => {
// Let's start a SAS verification, from `m2` for example.
[sas2, outgoingVerificationRequest] = await verificationRequest2.startSas();
expect(sas2).toBeInstanceOf(Sas);
expect(sas2.userId.toString()).toStrictEqual(userId2.toString());
expect(sas2.deviceId.toString()).toStrictEqual(deviceId2.toString());
expect(sas2.otherUserId.toString()).toStrictEqual(userId1.toString());
expect(sas2.otherDeviceId.toString()).toStrictEqual(deviceId1.toString());
expect(sas2.flowId).toStrictEqual(flowId);
expect(sas2.roomId).toBeUndefined();
expect(sas2.supportsEmoji()).toStrictEqual(false);
expect(sas2.startedFromRequest()).toStrictEqual(true);
expect(sas2.isSelfVerification()).toStrictEqual(false);
expect(sas2.haveWeConfirmed()).toStrictEqual(false);
expect(sas2.hasBeenAccepted()).toStrictEqual(false);
expect(sas2.cancelInfo()).toBeUndefined();
expect(sas2.weStarted()).toStrictEqual(false);
expect(sas2.timedOut()).toStrictEqual(false);
expect(sas2.canBePresented()).toStrictEqual(false);
expect(sas2.isDone()).toStrictEqual(false);
expect(sas2.isCancelled()).toStrictEqual(false);
expect(sas2.emoji()).toBeUndefined();
expect(sas2.emojiIndex()).toBeUndefined();
expect(sas2.decimals()).toBeUndefined();
expect(outgoingVerificationRequest).toBeInstanceOf(ToDeviceRequest);
outgoingVerificationRequest = JSON.parse(outgoingVerificationRequest.body);
expect(outgoingVerificationRequest.event_type).toStrictEqual('m.key.verification.start');
const toDeviceEvents = {
events: [{
sender: userId2.toString(),
type: outgoingVerificationRequest.event_type,
content: outgoingVerificationRequest.messages[userId1.toString()][deviceId1.toString()],
}],
};
// Let's send the SAS start to `m1`.
await m1.receiveSyncChanges(JSON.stringify(toDeviceEvents), new DeviceLists(), new Map(), new Set());
});
// SAS verification for the second machine.
let sas1;
test('can fetch and accept an ongoing SAS verification (`m.key.verification.accept`)', async () => {
// Let's fetch the ongoing SAS verification.
sas1 = await m1.getVerification(userId2, flowId);
expect(sas1).toBeInstanceOf(Sas);
expect(sas1.userId.toString()).toStrictEqual(userId1.toString());
expect(sas1.deviceId.toString()).toStrictEqual(deviceId1.toString());
expect(sas1.otherUserId.toString()).toStrictEqual(userId2.toString());
expect(sas1.otherDeviceId.toString()).toStrictEqual(deviceId2.toString());
expect(sas1.flowId).toStrictEqual(flowId);
expect(sas1.roomId).toBeUndefined();
expect(sas1.startedFromRequest()).toStrictEqual(true);
expect(sas1.isSelfVerification()).toStrictEqual(false);
expect(sas1.haveWeConfirmed()).toStrictEqual(false);
expect(sas1.hasBeenAccepted()).toStrictEqual(false);
expect(sas1.cancelInfo()).toBeUndefined();
expect(sas1.weStarted()).toStrictEqual(true);
expect(sas1.timedOut()).toStrictEqual(false);
expect(sas1.canBePresented()).toStrictEqual(false);
expect(sas1.isDone()).toStrictEqual(false);
expect(sas1.isCancelled()).toStrictEqual(false);
expect(sas1.emoji()).toBeUndefined();
expect(sas1.emojiIndex()).toBeUndefined();
expect(sas1.decimals()).toBeUndefined();
// Let's accept thet SAS start request.
let outgoingVerificationRequest = sas1.accept();
expect(outgoingVerificationRequest).toBeInstanceOf(ToDeviceRequest);
outgoingVerificationRequest = JSON.parse(outgoingVerificationRequest.body);
expect(outgoingVerificationRequest.event_type).toStrictEqual('m.key.verification.accept');
const toDeviceEvents = {
events: [{
sender: userId1.toString(),
type: outgoingVerificationRequest.event_type,
content: outgoingVerificationRequest.messages[userId2.toString()][deviceId2.toString()],
}],
};
// Let's send the SAS accept to `m2`.
await m2.receiveSyncChanges(JSON.stringify(toDeviceEvents), new DeviceLists(), new Map(), new Set());
});
test('emojis are supported by both sides', () => {
expect(sas1.supportsEmoji()).toStrictEqual(true);
expect(sas2.supportsEmoji()).toStrictEqual(true);
});
test('one side sends verification key (`m.key.verification.key`)', async () => {
// Let's send the verification keys from `m2` to `m1`.
const outgoingRequests = await m2.outgoingRequests();
let toDeviceRequest = outgoingRequests.find((request) => request.type == RequestType.ToDevice);
expect(toDeviceRequest).toBeInstanceOf(ToDeviceRequest);
const toDeviceRequestId = toDeviceRequest.id;
const toDeviceRequestType = toDeviceRequest.type;
toDeviceRequest = JSON.parse(toDeviceRequest.body);
expect(toDeviceRequest.event_type).toStrictEqual('m.key.verification.key');
const toDeviceEvents = {
events: [{
sender: userId2.toString(),
type: toDeviceRequest.event_type,
content: toDeviceRequest.messages[userId1.toString()][deviceId1.toString()],
}],
};
// Let's send te SAS key to `m1`.
await m1.receiveSyncChanges(JSON.stringify(toDeviceEvents), new DeviceLists(), new Map(), new Set());
m2.markRequestAsSent(toDeviceRequestId, toDeviceRequestType, '{}');
});
test('other side sends back verification key (`m.key.verification.key`)', async () => {
// Let's send the verification keys from `m1` to `m2`.
const outgoingRequests = await m1.outgoingRequests();
let toDeviceRequest = outgoingRequests.find((request) => request.type == RequestType.ToDevice);
expect(toDeviceRequest).toBeInstanceOf(ToDeviceRequest);
const toDeviceRequestId = toDeviceRequest.id;
const toDeviceRequestType = toDeviceRequest.type;
toDeviceRequest = JSON.parse(toDeviceRequest.body);
expect(toDeviceRequest.event_type).toStrictEqual('m.key.verification.key');
const toDeviceEvents = {
events: [{
sender: userId1.toString(),
type: toDeviceRequest.event_type,
content: toDeviceRequest.messages[userId2.toString()][deviceId2.toString()],
}],
};
// Let's send te SAS key to `m2`.
await m2.receiveSyncChanges(JSON.stringify(toDeviceEvents), new DeviceLists(), new Map(), new Set());
m1.markRequestAsSent(toDeviceRequestId, toDeviceRequestType, '{}');
});
test('emojis match from both sides', () => {
const emojis1 = sas1.emoji();
const emojiIndexes1 = sas1.emojiIndex();
const emojis2 = sas2.emoji();
const emojiIndexes2 = sas2.emojiIndex();
expect(emojis1).toHaveLength(7);
expect(emojiIndexes1).toHaveLength(emojis1.length);
expect(emojis2).toHaveLength(emojis1.length);
expect(emojiIndexes2).toHaveLength(emojis1.length);
const isEmoji = /(\u00a9|\u00ae|[\u2000-\u3300]|\ud83c[\ud000-\udfff]|\ud83d[\ud000-\udfff]|\ud83e[\ud000-\udfff])/;
for (const [emoji1, emojiIndex1, emoji2, emojiIndex2] of zip(emojis1, emojiIndexes1, emojis2, emojiIndexes2)) {
expect(emoji1).toBeInstanceOf(Emoji);
expect(emoji1.symbol).toMatch(isEmoji);
expect(emoji1.description).toBeTruthy();
expect(emojiIndex1).toBeGreaterThanOrEqual(0);
expect(emojiIndex1).toBeLessThanOrEqual(63);
expect(emoji2).toBeInstanceOf(Emoji);
expect(emoji2.symbol).toStrictEqual(emoji1.symbol);
expect(emoji2.description).toStrictEqual(emoji1.description);
expect(emojiIndex2).toStrictEqual(emojiIndex1);
}
});
test('decimals match from both sides', () => {
const decimals1 = sas1.decimals();
const decimals2 = sas2.decimals();
expect(decimals1).toHaveLength(3);
expect(decimals2).toHaveLength(decimals1.length);
const isDecimal = /^[0-9]{4}$/;
for (const [decimal1, decimal2] of zip(decimals1, decimals2)) {
expect(decimal1.toString()).toMatch(isDecimal);
expect(decimal2).toStrictEqual(decimal1);
}
});
test('can confirm keys match (`m.key.verification.mac`)', async () => {
// `m1` confirms.
const [outgoingVerificationRequests, signatureUploadRequest] = await sas1.confirm();
expect(signatureUploadRequest).toBeUndefined();
expect(outgoingVerificationRequests).toHaveLength(1);
let outgoingVerificationRequest = outgoingVerificationRequests[0];
expect(outgoingVerificationRequest).toBeInstanceOf(ToDeviceRequest);
outgoingVerificationRequest = JSON.parse(outgoingVerificationRequest.body);
expect(outgoingVerificationRequest.event_type).toStrictEqual('m.key.verification.mac');
const toDeviceEvents = {
events: [{
sender: userId1.toString(),
type: outgoingVerificationRequest.event_type,
content: outgoingVerificationRequest.messages[userId2.toString()][deviceId2.toString()],
}],
};
// Let's send te SAS confirmation to `m2`.
await m2.receiveSyncChanges(JSON.stringify(toDeviceEvents), new DeviceLists(), new Map(), new Set());
});
test('can confirm back keys match (`m.key.verification.done`)', async () => {
// `m2` confirms.
const [outgoingVerificationRequests, signatureUploadRequest] = await sas2.confirm();
expect(signatureUploadRequest).toBeUndefined();
expect(outgoingVerificationRequests).toHaveLength(2);
// `.mac`
{
let outgoingVerificationRequest = outgoingVerificationRequests[0];
expect(outgoingVerificationRequest).toBeInstanceOf(ToDeviceRequest);
outgoingVerificationRequest = JSON.parse(outgoingVerificationRequest.body);
expect(outgoingVerificationRequest.event_type).toStrictEqual('m.key.verification.mac');
const toDeviceEvents = {
events: [{
sender: userId2.toString(),
type: outgoingVerificationRequest.event_type,
content: outgoingVerificationRequest.messages[userId1.toString()][deviceId1.toString()],
}],
};
// Let's send te SAS confirmation to `m1`.
await m1.receiveSyncChanges(JSON.stringify(toDeviceEvents), new DeviceLists(), new Map(), new Set());
}
// `.done`
{
let outgoingVerificationRequest = outgoingVerificationRequests[1];
expect(outgoingVerificationRequest).toBeInstanceOf(ToDeviceRequest);
outgoingVerificationRequest = JSON.parse(outgoingVerificationRequest.body);
expect(outgoingVerificationRequest.event_type).toStrictEqual('m.key.verification.done');
const toDeviceEvents = {
events: [{
sender: userId2.toString(),
type: outgoingVerificationRequest.event_type,
content: outgoingVerificationRequest.messages[userId1.toString()][deviceId1.toString()],
}],
};
// Let's send te SAS done to `m1`.
await m1.receiveSyncChanges(JSON.stringify(toDeviceEvents), new DeviceLists(), new Map(), new Set());
}
});
test('can send final done (`m.key.verification.done`)', async () => {
const outgoingRequests = await m1.outgoingRequests();
expect(outgoingRequests).toHaveLength(4);
let toDeviceRequest = outgoingRequests.find((request) => request.type == RequestType.ToDevice);
expect(toDeviceRequest).toBeInstanceOf(ToDeviceRequest);
const toDeviceRequestId = toDeviceRequest.id;
const toDeviceRequestType = toDeviceRequest.type;
toDeviceRequest = JSON.parse(toDeviceRequest.body);
expect(toDeviceRequest.event_type).toStrictEqual('m.key.verification.done');
const toDeviceEvents = {
events: [{
sender: userId1.toString(),
type: toDeviceRequest.event_type,
content: toDeviceRequest.messages[userId2.toString()][deviceId2.toString()],
}],
};
// Let's send te SAS key to `m2`.
await m2.receiveSyncChanges(JSON.stringify(toDeviceEvents), new DeviceLists(), new Map(), new Set());
m1.markRequestAsSent(toDeviceRequestId, toDeviceRequestType, '{}');
});
test('can see if verification is done', () => {
expect(verificationRequest1.isDone()).toStrictEqual(true);
expect(verificationRequest2.isDone()).toStrictEqual(true);
expect(sas1.isDone()).toStrictEqual(true);
expect(sas2.isDone()).toStrictEqual(true);
});
});
describe('QR Code', () => {
if (undefined === Qr) {
// qrcode supports is not enabled
console.info('qrcode support is disabled, skip the associated test suite');
return;
}
// First Olm machine.
let m1;
// Second Olm machine.
let m2;
beforeAll(async () => {
m1 = await machine(userId1, deviceId1);
m2 = await machine(userId2, deviceId2);
});
// Verification request for `m1`.
let verificationRequest1;
// The flow ID.
let flowId;
test('can request verification (`m.key.verification.request`)', async () => {
// Make `m1` and `m2` be aware of each other.
{
await addMachineToMachine(m2, m1);
await addMachineToMachine(m1, m2);
}
// Pick the device we want to start the verification with.
const device2 = await m1.getDevice(userId2, deviceId2);
expect(device2).toBeInstanceOf(Device);
let outgoingVerificationRequest;
// Request a verification from `m1` to `device2`.
[verificationRequest1, outgoingVerificationRequest] = await device2.requestVerification([
VerificationMethod.QrCodeScanV1, // by default
VerificationMethod.QrCodeShowV1, // the one we add
]);
expect(verificationRequest1).toBeInstanceOf(VerificationRequest);
expect(verificationRequest1.ownUserId.toString()).toStrictEqual(userId1.toString());
expect(verificationRequest1.otherUserId.toString()).toStrictEqual(userId2.toString());
expect(verificationRequest1.otherDeviceId).toBeUndefined();
expect(verificationRequest1.roomId).toBeUndefined();
expect(verificationRequest1.cancelInfo).toBeUndefined();
expect(verificationRequest1.isPassive()).toStrictEqual(false);
expect(verificationRequest1.isReady()).toStrictEqual(false);
expect(verificationRequest1.timedOut()).toStrictEqual(false);
expect(verificationRequest1.theirSupportedMethods).toBeUndefined();
expect(verificationRequest1.ourSupportedMethods).toEqual(expect.arrayContaining([VerificationMethod.QrCodeShowV1]));
expect(verificationRequest1.flowId).toMatch(/^[a-f0-9]+$/);
expect(verificationRequest1.isSelfVerification()).toStrictEqual(false);
expect(verificationRequest1.weStarted()).toStrictEqual(true);
expect(verificationRequest1.isDone()).toStrictEqual(false);
expect(verificationRequest1.isCancelled()).toStrictEqual(false);
expect(outgoingVerificationRequest).toBeInstanceOf(ToDeviceRequest);
outgoingVerificationRequest = JSON.parse(outgoingVerificationRequest.body);
expect(outgoingVerificationRequest.event_type).toStrictEqual('m.key.verification.request');
const toDeviceEvents = {
events: [{
sender: userId1.toString(),
type: outgoingVerificationRequest.event_type,
content: outgoingVerificationRequest.messages[userId2.toString()][deviceId2.toString()],
}]
};
// Let's send the verification request to `m2`.
await m2.receiveSyncChanges(JSON.stringify(toDeviceEvents), new DeviceLists(), new Map(), new Set());
flowId = verificationRequest1.flowId;
});
// Verification request for `m2`.
let verificationRequest2;
test('can fetch received request verification', async () => {
// Oh, a new verification request.
verificationRequest2 = m2.getVerificationRequest(userId1, flowId);
expect(verificationRequest2).toBeInstanceOf(VerificationRequest);
expect(verificationRequest2.ownUserId.toString()).toStrictEqual(userId2.toString());
expect(verificationRequest2.otherUserId.toString()).toStrictEqual(userId1.toString());
expect(verificationRequest2.otherDeviceId.toString()).toStrictEqual(deviceId1.toString());
expect(verificationRequest2.roomId).toBeUndefined();
expect(verificationRequest2.cancelInfo).toBeUndefined();
expect(verificationRequest2.isPassive()).toStrictEqual(false);
expect(verificationRequest2.isReady()).toStrictEqual(false);
expect(verificationRequest2.timedOut()).toStrictEqual(false);
expect(verificationRequest2.theirSupportedMethods).toEqual(expect.arrayContaining([VerificationMethod.QrCodeScanV1, VerificationMethod.QrCodeShowV1]));
expect(verificationRequest2.ourSupportedMethods).toBeUndefined();
expect(verificationRequest2.flowId).toStrictEqual(flowId);
expect(verificationRequest2.isSelfVerification()).toStrictEqual(false);
expect(verificationRequest2.weStarted()).toStrictEqual(false);
expect(verificationRequest2.isDone()).toStrictEqual(false);
expect(verificationRequest2.isCancelled()).toStrictEqual(false);
const verificationRequests = m2.getVerificationRequests(userId1);
expect(verificationRequests).toHaveLength(1);
expect(verificationRequests[0].flowId).toStrictEqual(verificationRequest2.flowId); // there are the same
});
test('can accept a verification request with methods (`m.key.verification.ready`)', async () => {
// Accept the verification request.
let outgoingVerificationRequest = verificationRequest2.acceptWithMethods([
VerificationMethod.QrCodeScanV1, // by default
VerificationMethod.QrCodeShowV1, // the one we add
]);
expect(outgoingVerificationRequest).toBeInstanceOf(ToDeviceRequest);
// The request verification is ready.
outgoingVerificationRequest = JSON.parse(outgoingVerificationRequest.body);
expect(outgoingVerificationRequest.event_type).toStrictEqual('m.key.verification.ready');
const toDeviceEvents = {
events: [{
sender: userId2.toString(),
type: outgoingVerificationRequest.event_type,
content: outgoingVerificationRequest.messages[userId1.toString()][deviceId1.toString()],
}],
};
// Let's send the verification ready to `m1`.
await m1.receiveSyncChanges(JSON.stringify(toDeviceEvents), new DeviceLists(), new Map(), new Set());
});
test('verification requests are synchronized and automatically updated', () => {
expect(verificationRequest1.isReady()).toStrictEqual(true);
expect(verificationRequest2.isReady()).toStrictEqual(true);
expect(verificationRequest1.theirSupportedMethods).toEqual(expect.arrayContaining([VerificationMethod.QrCodeScanV1, VerificationMethod.QrCodeShowV1]));
expect(verificationRequest1.ourSupportedMethods).toEqual(expect.arrayContaining([VerificationMethod.QrCodeScanV1, VerificationMethod.QrCodeShowV1]));
expect(verificationRequest2.theirSupportedMethods).toEqual(expect.arrayContaining([VerificationMethod.QrCodeScanV1, VerificationMethod.QrCodeShowV1]));
expect(verificationRequest2.ourSupportedMethods).toEqual(expect.arrayContaining([VerificationMethod.QrCodeScanV1, VerificationMethod.QrCodeShowV1]));
});
// QR verification for the second machine.
let qr2;
test('can generate a QR code', async () => {
qr2 = await verificationRequest2.generateQrCode();
expect(qr2).toBeInstanceOf(Qr);
expect(qr2.hasBeenScanned()).toStrictEqual(false);
expect(qr2.hasBeenConfirmed()).toStrictEqual(false);
expect(qr2.userId.toString()).toStrictEqual(userId2.toString());
expect(qr2.otherUserId.toString()).toStrictEqual(userId1.toString());
expect(qr2.otherDeviceId.toString()).toStrictEqual(deviceId1.toString());
expect(qr2.weStarted()).toStrictEqual(false);
expect(qr2.cancelInfo()).toBeUndefined();
expect(qr2.isDone()).toStrictEqual(false);
expect(qr2.isCancelled()).toStrictEqual(false);
expect(qr2.isSelfVerification()).toStrictEqual(false);
expect(qr2.reciprocated()).toStrictEqual(false);
expect(qr2.flowId).toMatch(/^[a-f0-9]+$/);
expect(qr2.roomId).toBeUndefined();
});
let qrCodeBytes;
test('can read QR code\'s bytes', async () => {
const qrCodeHeader = 'MATRIX';
const qrCodeVersion = '\x02';
qrCodeBytes = qr2.toBytes();
expect(qrCodeBytes).toHaveLength(122);
expect(qrCodeBytes.slice(0, 7)).toStrictEqual([...qrCodeHeader, ...qrCodeVersion].map(char => char.charCodeAt(0)));
});
test('can render QR code', async () => {
const qrCode = qr2.toQrCode();
expect(qrCode).toBeInstanceOf(QrCode);
// Want to get `canvasBuffer` to render the QR code? Install `npm install canvas` and uncomment the following blocks.
//let canvasBuffer;
{
const buffer = qrCode.renderIntoBuffer();
expect(buffer).toBeInstanceOf(Uint8ClampedArray);
// 45px ⨉ 45px
expect(buffer).toHaveLength(45 * 45);
// 0 for a white pixel, 1 for a black pixel.
expect(buffer.every(p => p == 0 || p == 1)).toStrictEqual(true);
/*
const { Canvas } = require('canvas');
const canvas = new Canvas(55, 55);
const context = canvas.getContext('2d');
context.fillStyle = 'white';
context.fillRect(0, 0, canvas.width, canvas.height);
// New image data, filled with black, transparent pixels.
const imageData = context.createImageData(45, 45);
const data = imageData.data;
const [r, g, b, a] = [0, 1, 2, 3];
for (
let dataNth = 0,
bufferNth = 0;
dataNth < data.length && bufferNth < buffer.length;
dataNth += 4,
bufferNth += 1
) {
data[dataNth + a] = 255;
// White pixel
if (buffer[bufferNth] == 0) {
data[dataNth + r] = 255;
data[dataNth + g] = 255;
data[dataNth + b] = 255;
}
}
context.putImageData(imageData, 5, 5);
canvasBuffer = canvas.toBuffer('image/png');
*/
}
// Want to see the QR code? Uncomment the following block.
/*
{
const fs = require('fs/promises');
const path = require('path');
const os = require('os');
const tempDirectory = await fs.mkdtemp(path.join(os.tmpdir(), 'matrix-sdk-crypto--'));
const qrCodeFile = path.join(tempDirectory, 'qrcode.png');
console.log(`View the QR code at \`${qrCodeFile}\`.`);
expect(await fs.writeFile(qrCodeFile, canvasBuffer)).toBeUndefined();
}
*/
});
let qr1;
test('can scan a QR code from bytes', async () => {
const scan = QrCodeScan.fromBytes(qrCodeBytes);
expect(scan).toBeInstanceOf(QrCodeScan);
qr1 = await verificationRequest1.scanQrCode(scan);
expect(qr1).toBeInstanceOf(Qr);
expect(qr1.hasBeenScanned()).toStrictEqual(false);
expect(qr1.hasBeenConfirmed()).toStrictEqual(false);
expect(qr1.userId.toString()).toStrictEqual(userId1.toString());
expect(qr1.otherUserId.toString()).toStrictEqual(userId2.toString());
expect(qr1.otherDeviceId.toString()).toStrictEqual(deviceId2.toString());
expect(qr1.weStarted()).toStrictEqual(true);
expect(qr1.cancelInfo()).toBeUndefined();
expect(qr1.isDone()).toStrictEqual(false);
expect(qr1.isCancelled()).toStrictEqual(false);
expect(qr1.isSelfVerification()).toStrictEqual(false);
expect(qr1.reciprocated()).toStrictEqual(true);
expect(qr1.flowId).toMatch(/^[a-f0-9]+$/);
expect(qr1.roomId).toBeUndefined();
});
test('can start a QR verification/reciprocate (`m.key.verification.start`)', async () => {
let outgoingVerificationRequest = qr1.reciprocate();
expect(outgoingVerificationRequest).toBeInstanceOf(ToDeviceRequest);
outgoingVerificationRequest = JSON.parse(outgoingVerificationRequest.body);
expect(outgoingVerificationRequest.event_type).toStrictEqual('m.key.verification.start');
const toDeviceEvents = {
events: [{
sender: userId1.toString(),
type: outgoingVerificationRequest.event_type,
content: outgoingVerificationRequest.messages[userId2.toString()][deviceId2.toString()],
}]
};
// Let's send the verification request to `m2`.
await m2.receiveSyncChanges(JSON.stringify(toDeviceEvents), new DeviceLists(), new Map(), new Set());
});
test('can confirm QR code has been scanned', () => {
expect(qr2.hasBeenScanned()).toStrictEqual(true);
});
test('can confirm scanning (`m.key.verification.done`)', async () => {
let outgoingVerificationRequest = qr2.confirmScanning();
expect(outgoingVerificationRequest).toBeInstanceOf(ToDeviceRequest);
outgoingVerificationRequest = JSON.parse(outgoingVerificationRequest.body);
expect(outgoingVerificationRequest.event_type).toStrictEqual('m.key.verification.done');
const toDeviceEvents = {
events: [{
sender: userId2.toString(),
type: outgoingVerificationRequest.event_type,
content: outgoingVerificationRequest.messages[userId1.toString()][deviceId1.toString()],
}]
};
// Let's send the verification request to `m2`.
await m2.receiveSyncChanges(JSON.stringify(toDeviceEvents), new DeviceLists(), new Map(), new Set());
});
test('can confirm QR code has been confirmed', () => {
expect(qr2.hasBeenConfirmed()).toStrictEqual(true);
});
});
});
describe('VerificationMethod', () => {
test('has the correct variant values', () => {
expect(VerificationMethod.SasV1).toStrictEqual(0);
expect(VerificationMethod.QrCodeScanV1).toStrictEqual(1);
expect(VerificationMethod.QrCodeShowV1).toStrictEqual(2);
expect(VerificationMethod.ReciprocateV1).toStrictEqual(3);
});
});
@@ -0,0 +1,36 @@
const { EncryptionAlgorithm, EncryptionSettings, HistoryVisibility, VerificationState } = require('../pkg/matrix_sdk_crypto_js');
describe('EncryptionAlgorithm', () => {
test('has the correct variant values', () => {
expect(EncryptionAlgorithm.OlmV1Curve25519AesSha2).toStrictEqual(0);
expect(EncryptionAlgorithm.MegolmV1AesSha2).toStrictEqual(1);
});
});
describe(EncryptionSettings.name, () => {
test('can be instantiated with default values', () => {
const es = new EncryptionSettings();
expect(es.algorithm).toStrictEqual(EncryptionAlgorithm.MegolmV1AesSha2);
expect(es.rotationPeriod).toStrictEqual(604800000000n);
expect(es.rotationPeriodMessages).toStrictEqual(100n);
expect(es.historyVisibility).toStrictEqual(HistoryVisibility.Shared);
});
test('checks the history visibility values', () => {
const es = new EncryptionSettings();
es.historyVisibility = HistoryVisibility.Invited;
expect(es.historyVisibility).toStrictEqual(HistoryVisibility.Invited);
expect(() => { es.historyVisibility = 42 }).toThrow();
});
});
describe('VerificationState', () => {
test('has the correct variant values', () => {
expect(VerificationState.Trusted).toStrictEqual(0);
expect(VerificationState.Untrusted).toStrictEqual(1);
expect(VerificationState.UnknownDevice).toStrictEqual(2);
});
});
@@ -0,0 +1,10 @@
const { HistoryVisibility } = require('../pkg/matrix_sdk_crypto_js');
describe('HistoryVisibility', () => {
test('has the correct variant values', () => {
expect(HistoryVisibility.Invited).toStrictEqual(0);
expect(HistoryVisibility.Joined).toStrictEqual(1);
expect(HistoryVisibility.Shared).toStrictEqual(2);
expect(HistoryVisibility.WorldReadable).toStrictEqual(3);
});
});
@@ -0,0 +1,80 @@
const { DeviceLists, RequestType, KeysUploadRequest, KeysQueryRequest } = require('../pkg/matrix_sdk_crypto_js');
function* zip(...arrays) {
const len = Math.min(...arrays.map((array) => array.length));
for (let nth = 0; nth < len; ++nth) {
yield [...arrays.map((array) => array.at(nth))]
}
}
// Add a machine to another machine, i.e. be sure a machine knows
// another exists.
async function addMachineToMachine(machineToAdd, machine) {
const toDeviceEvents = JSON.stringify({});
const changedDevices = new DeviceLists();
const oneTimeKeyCounts = new Map();
const unusedFallbackKeys = new Set();
const receiveSyncChanges = JSON.parse(await machineToAdd.receiveSyncChanges(toDeviceEvents, changedDevices, oneTimeKeyCounts, unusedFallbackKeys));
expect(receiveSyncChanges).toEqual({});
const outgoingRequests = await machineToAdd.outgoingRequests();
expect(outgoingRequests).toHaveLength(2);
let keysUploadRequest;
// Read the `KeysUploadRequest`.
{
expect(outgoingRequests[0]).toBeInstanceOf(KeysUploadRequest);
expect(outgoingRequests[0].id).toBeDefined();
expect(outgoingRequests[0].type).toStrictEqual(RequestType.KeysUpload);
const body = JSON.parse(outgoingRequests[0].body);
expect(body.device_keys).toBeDefined();
expect(body.one_time_keys).toBeDefined();
// https://spec.matrix.org/v1.2/client-server-api/#post_matrixclientv3keysupload
const hypothetical_response = JSON.stringify({
"one_time_key_counts": {
"curve25519": 10,
"signed_curve25519": 20
}
});
const marked = await machineToAdd.markRequestAsSent(outgoingRequests[0].id, outgoingRequests[0].type, hypothetical_response);
expect(marked).toStrictEqual(true);
keysUploadRequest = body;
}
{
expect(outgoingRequests[1]).toBeInstanceOf(KeysQueryRequest);
let [signingKeysUploadRequest, _] = await machineToAdd.bootstrapCrossSigning(true);
signingKeysUploadRequest = JSON.parse(signingKeysUploadRequest.body);
// Let's forge a `KeysQuery`'s response.
let keyQueryResponse = {
device_keys: {},
master_keys: {},
self_signing_keys: {},
user_signing_keys: {},
};
const userId = machineToAdd.userId.toString();
const deviceId = machineToAdd.deviceId.toString();
keyQueryResponse.device_keys[userId] = {};
keyQueryResponse.device_keys[userId][deviceId] = keysUploadRequest.device_keys;
keyQueryResponse.master_keys[userId] = signingKeysUploadRequest.master_key;
keyQueryResponse.self_signing_keys[userId] = signingKeysUploadRequest.self_signing_key;
keyQueryResponse.user_signing_keys[userId] = signingKeysUploadRequest.user_signing_key;
const marked = await machine.markRequestAsSent(outgoingRequests[1].id, outgoingRequests[1].type, JSON.stringify(keyQueryResponse));
expect(marked).toStrictEqual(true);
}
}
module.exports = {
zip,
addMachineToMachine,
};
@@ -0,0 +1,181 @@
const {
DeviceId,
DeviceKeyAlgorithm,
DeviceKeyAlgorithmName,
DeviceKeyId,
EventId,
RoomId,
ServerName,
UserId,
} = require('../pkg/matrix_sdk_crypto_js');
describe(UserId.name, () => {
test('cannot be invalid', () => {
expect(() => { new UserId('@foobar') }).toThrow();
});
const user = new UserId('@foo:bar.org');
test('localpart is present', () => {
expect(user.localpart).toStrictEqual('foo');
});
test('server name is present', () => {
expect(user.serverName).toBeInstanceOf(ServerName);
});
test('user ID is not historical', () => {
expect(user.isHistorical()).toStrictEqual(false);
});
test('can read the user ID as a string', () => {
expect(user.toString()).toStrictEqual('@foo:bar.org');
})
});
describe(DeviceId.name, () => {
const device = new DeviceId('foo');
test('can read the device ID as a string', () => {
expect(device.toString()).toStrictEqual('foo');
})
});
describe(DeviceKeyId.name, () => {
for (const deviceKey of [
{ name: 'ed25519',
id: 'ed25519:foobar',
algorithmName: DeviceKeyAlgorithmName.Ed25519,
algorithm: 'ed25519',
deviceId: 'foobar' },
{ name: 'curve25519',
id: 'curve25519:foobar',
algorithmName: DeviceKeyAlgorithmName.Curve25519,
algorithm: 'curve25519',
deviceId: 'foobar' },
{ name: 'signed curve25519',
id: 'signed_curve25519:foobar',
algorithmName: DeviceKeyAlgorithmName.SignedCurve25519,
algorithm: 'signed_curve25519',
deviceId: 'foobar' },
{ name: 'unknown',
id: 'hello:foobar',
algorithmName: DeviceKeyAlgorithmName.Unknown,
algorithm: 'hello',
deviceId: 'foobar' },
]) {
test(`${deviceKey.name} algorithm`, () => {
const dk = new DeviceKeyId(deviceKey.id);
expect(dk.algorithm.name).toStrictEqual(deviceKey.algorithmName);
expect(dk.algorithm.toString()).toStrictEqual(deviceKey.algorithm);
expect(dk.deviceId.toString()).toStrictEqual(deviceKey.deviceId);
expect(dk.toString()).toStrictEqual(deviceKey.id);
});
}
});
describe('DeviceKeyAlgorithmName', () => {
test('has the correct variants', () => {
expect(DeviceKeyAlgorithmName.Ed25519).toStrictEqual(0);
expect(DeviceKeyAlgorithmName.Curve25519).toStrictEqual(1);
expect(DeviceKeyAlgorithmName.SignedCurve25519).toStrictEqual(2);
expect(DeviceKeyAlgorithmName.Unknown).toStrictEqual(3);
});
});
describe(RoomId.name, () => {
test('cannot be invalid', () => {
expect(() => { new RoomId('!foo') }).toThrow();
});
const room = new RoomId('!foo:bar.org');
test('localpart is present', () => {
expect(room.localpart).toStrictEqual('foo');
});
test('server name is present', () => {
expect(room.serverName).toBeInstanceOf(ServerName);
});
test('can read the room ID as string', () => {
expect(room.toString()).toStrictEqual('!foo:bar.org');
});
});
describe(ServerName.name, () => {
test('cannot be invalid', () => {
expect(() => { new ServerName('@foobar') }).toThrow()
});
test('host is present', () => {
expect(new ServerName('foo.org').host).toStrictEqual('foo.org');
});
test('port can be optional', () => {
expect(new ServerName('foo.org').port).toStrictEqual(undefined);
expect(new ServerName('foo.org:1234').port).toStrictEqual(1234);
});
test('server is not an IP literal', () => {
expect(new ServerName('foo.org').isIpLiteral()).toStrictEqual(false);
});
});
describe(EventId.name, () => {
test('cannot be invalid', () => {
expect(() => { new EventId('%foo') }).toThrow();
});
describe('Versions 1 & 2', () => {
const room = new EventId('$h29iv0s8:foo.org');
test('localpart is present', () => {
expect(room.localpart).toStrictEqual('h29iv0s8');
});
test('server name is present', () => {
expect(room.serverName).toBeInstanceOf(ServerName);
});
test('can read the room ID as string', () => {
expect(room.toString()).toStrictEqual('$h29iv0s8:foo.org');
});
});
describe('Version 3', () => {
const room = new EventId('$acR1l0raoZnm60CBwAVgqbZqoO/mYU81xysh1u7XcJk');
test('localpart is present', () => {
expect(room.localpart).toStrictEqual('acR1l0raoZnm60CBwAVgqbZqoO/mYU81xysh1u7XcJk');
});
test('server name is present', () => {
expect(room.serverName).toBeUndefined();
});
test('can read the room ID as string', () => {
expect(room.toString()).toStrictEqual('$acR1l0raoZnm60CBwAVgqbZqoO/mYU81xysh1u7XcJk');
});
});
describe('Version 4', () => {
const room = new EventId('$Rqnc-F-dvnEYJTyHq_iKxU2bZ1CI92-kuZq3a5lr5Zg');
test('localpart is present', () => {
expect(room.localpart).toStrictEqual('Rqnc-F-dvnEYJTyHq_iKxU2bZ1CI92-kuZq3a5lr5Zg');
});
test('server name is present', () => {
expect(room.serverName).toBeUndefined();
});
test('can read the room ID as string', () => {
expect(room.toString()).toStrictEqual('$Rqnc-F-dvnEYJTyHq_iKxU2bZ1CI92-kuZq3a5lr5Zg');
});
});
})
@@ -0,0 +1,569 @@
const {
CrossSigningStatus,
DecryptedRoomEvent,
DeviceId,
DeviceKeyId,
DeviceLists,
EncryptionSettings,
InboundGroupSession,
KeysClaimRequest,
KeysQueryRequest,
KeysUploadRequest,
MaybeSignature,
OlmMachine,
OwnUserIdentity,
RequestType,
RoomId,
SignatureUploadRequest,
ToDeviceRequest,
UserId,
VerificationRequest,
VerificationState,
} = require('../pkg/matrix_sdk_crypto_js');
const { addMachineToMachine } = require('./helper');
require('fake-indexeddb/auto');
describe(OlmMachine.name, () => {
test('can be instantiated with the async initializer', async () => {
expect(await new OlmMachine(new UserId('@foo:bar.org'), new DeviceId('baz'))).toBeInstanceOf(OlmMachine);
});
test('can be instantiated with a store', async () => {
// No databases.
expect(await indexedDB.databases()).toHaveLength(0);
let store_name = 'hello';
let store_passphrase = 'world';
// Creating a new Olm machine.
expect(await new OlmMachine(new UserId('@foo:bar.org'), new DeviceId('baz'), store_name, store_passphrase)).toBeInstanceOf(OlmMachine);
// Oh, there is 2 databases now, prefixed by `store_name`.
let databases = await indexedDB.databases();
expect(databases).toHaveLength(2);
expect(databases).toStrictEqual([
{ name: `${store_name}::matrix-sdk-crypto-meta`, version: 1 },
{ name: `${store_name}::matrix-sdk-crypto`, version: 1 },
]);
// Creating a new Olm machine, with the stored state.
expect(await new OlmMachine(new UserId('@foo:bar.org'), new DeviceId('baz'), store_name, store_passphrase)).toBeInstanceOf(OlmMachine);
// Same number of databases.
expect(await indexedDB.databases()).toHaveLength(2);
});
describe('cannot be instantiated with a store', () => {
test('store name is missing', async () => {
let store_name = null;
let store_passphrase = 'world';
let err = null;
try {
await new OlmMachine(new UserId('@foo:bar.org'), new DeviceId('baz'), store_name, store_passphrase);
} catch (error) {
err = error;
}
expect(err).toBeDefined();
});
test('store passphrase is missing', async () => {
let store_name = 'hello';
let store_passphrase = null;
let err = null;
try {
await new OlmMachine(new UserId('@foo:bar.org'), new DeviceId('baz'), store_name, store_passphrase);
} catch (error) {
err = error;
}
expect(err).toBeDefined();
});
});
const user = new UserId('@alice:example.org');
const device = new DeviceId('foobar');
const room = new RoomId('!baz:matrix.org');
function machine(new_user, new_device) {
return new OlmMachine(new_user || user, new_device || device);
}
test('can read user ID', async () => {
expect((await machine()).userId.toString()).toStrictEqual(user.toString());
});
test('can read device ID', async () => {
expect((await machine()).deviceId.toString()).toStrictEqual(device.toString());
});
test('can read identity keys', async () => {
const identityKeys = (await machine()).identityKeys;
expect(identityKeys.ed25519.toBase64()).toMatch(/^[A-Za-z0-9+/]+$/);
expect(identityKeys.curve25519.toBase64()).toMatch(/^[A-Za-z0-9+/]+$/);
});
test('can read display name', async () => {
expect(await machine().displayName).toBeUndefined();
});
test('can read tracked users', async () => {
const trackedUsers = (await machine()).trackedUsers();
expect(trackedUsers).toBeInstanceOf(Set);
expect(trackedUsers.size).toStrictEqual(0);
});
test('can update tracked users', async () => {
const m = await machine();
expect(await m.updateTrackedUsers([user])).toStrictEqual(undefined);
});
test('can receive sync changes', async () => {
const m = await machine();
const toDeviceEvents = JSON.stringify({});
const changedDevices = new DeviceLists();
const oneTimeKeyCounts = new Map();
const unusedFallbackKeys = new Set();
const receiveSyncChanges = JSON.parse(await m.receiveSyncChanges(toDeviceEvents, changedDevices, oneTimeKeyCounts, unusedFallbackKeys));
expect(receiveSyncChanges).toEqual({});
});
test('can get the outgoing requests that need to be send out', async () => {
const m = await machine();
const toDeviceEvents = JSON.stringify({});
const changedDevices = new DeviceLists();
const oneTimeKeyCounts = new Map();
const unusedFallbackKeys = new Set();
const receiveSyncChanges = JSON.parse(await m.receiveSyncChanges(toDeviceEvents, changedDevices, oneTimeKeyCounts, unusedFallbackKeys));
expect(receiveSyncChanges).toEqual({});
const outgoingRequests = await m.outgoingRequests();
expect(outgoingRequests).toHaveLength(2);
{
expect(outgoingRequests[0]).toBeInstanceOf(KeysUploadRequest);
expect(outgoingRequests[0].id).toBeDefined();
expect(outgoingRequests[0].type).toStrictEqual(RequestType.KeysUpload);
const body = JSON.parse(outgoingRequests[0].body);
expect(body.device_keys).toBeDefined();
expect(body.one_time_keys).toBeDefined();
}
{
expect(outgoingRequests[1]).toBeInstanceOf(KeysQueryRequest);
expect(outgoingRequests[1].id).toBeDefined();
expect(outgoingRequests[1].type).toStrictEqual(RequestType.KeysQuery);
const body = JSON.parse(outgoingRequests[1].body);
expect(body.timeout).toBeDefined();
expect(body.device_keys).toBeDefined();
expect(body.token).toBeDefined();
}
});
describe('setup workflow to mark requests as sent', () => {
let m;
let ougoingRequests;
beforeAll(async () => {
m = await machine(new UserId('@alice:example.org'), new DeviceId('DEVICEID'));
const toDeviceEvents = JSON.stringify({});
const changedDevices = new DeviceLists();
const oneTimeKeyCounts = new Map();
const unusedFallbackKeys = new Set();
const receiveSyncChanges = await m.receiveSyncChanges(toDeviceEvents, changedDevices, oneTimeKeyCounts, unusedFallbackKeys);
outgoingRequests = await m.outgoingRequests();
expect(outgoingRequests).toHaveLength(2);
});
test('can mark requests as sent', async () => {
{
const request = outgoingRequests[0];
expect(request).toBeInstanceOf(KeysUploadRequest);
// https://spec.matrix.org/v1.2/client-server-api/#post_matrixclientv3keysupload
const hypothetical_response = JSON.stringify({
"one_time_key_counts": {
"curve25519": 10,
"signed_curve25519": 20
}
});
const marked = await m.markRequestAsSent(request.id, request.type, hypothetical_response);
expect(marked).toStrictEqual(true);
}
{
const request = outgoingRequests[1];
expect(request).toBeInstanceOf(KeysQueryRequest);
// https://spec.matrix.org/v1.2/client-server-api/#post_matrixclientv3keysquery
const hypothetical_response = JSON.stringify({
"device_keys": {
"@alice:example.org": {
"JLAFKJWSCS": {
"algorithms": [
"m.olm.v1.curve25519-aes-sha2",
"m.megolm.v1.aes-sha2"
],
"device_id": "JLAFKJWSCS",
"keys": {
"curve25519:JLAFKJWSCS": "wjLpTLRqbqBzLs63aYaEv2Boi6cFEbbM/sSRQ2oAKk4",
"ed25519:JLAFKJWSCS": "nE6W2fCblxDcOFmeEtCHNl8/l8bXcu7GKyAswA4r3mM"
},
"signatures": {
"@alice:example.org": {
"ed25519:JLAFKJWSCS": "m53Wkbh2HXkc3vFApZvCrfXcX3AI51GsDHustMhKwlv3TuOJMj4wistcOTM8q2+e/Ro7rWFUb9ZfnNbwptSUBA"
}
},
"unsigned": {
"device_display_name": "Alice's mobile phone"
},
"user_id": "@alice:example.org"
}
}
},
"failures": {}
});
const marked = await m.markRequestAsSent(request.id, request.type, hypothetical_response);
expect(marked).toStrictEqual(true);
}
});
});
describe('setup workflow to encrypt/decrypt events', () => {
let m;
const user = new UserId('@alice:example.org');
const device = new DeviceId('JLAFKJWSCS');
const room = new RoomId('!test:localhost');
beforeAll(async () => {
m = await machine(user, device);
});
test('can pass keysquery and keysclaim requests directly', async () => {
{
// derived from https://github.com/matrix-org/matrix-rust-sdk/blob/7f49618d350fab66b7e1dc4eaf64ec25ceafd658/benchmarks/benches/crypto_bench/keys_query.json
const hypothetical_response = JSON.stringify({
"device_keys": {
"@example:localhost": {
"AFGUOBTZWM": {
"algorithms": [
"m.olm.v1.curve25519-aes-sha2",
"m.megolm.v1.aes-sha2"
],
"device_id": "AFGUOBTZWM",
"keys": {
"curve25519:AFGUOBTZWM": "boYjDpaC+7NkECQEeMh5dC+I1+AfriX0VXG2UV7EUQo",
"ed25519:AFGUOBTZWM": "NayrMQ33ObqMRqz6R9GosmHdT6HQ6b/RX/3QlZ2yiec"
},
"signatures": {
"@example:localhost": {
"ed25519:AFGUOBTZWM": "RoSWvru1jj6fs2arnTedWsyIyBmKHMdOu7r9gDi0BZ61h9SbCK2zLXzuJ9ZFLao2VvA0yEd7CASCmDHDLYpXCA"
}
},
"user_id": "@example:localhost",
"unsigned": {
"device_display_name": "rust-sdk"
}
},
}
},
"failures": {},
"master_keys": {
"@example:localhost": {
"user_id": "@example:localhost",
"usage": [
"master"
],
"keys": {
"ed25519:n2lpJGx0LiKnuNE1IucZP3QExrD4SeRP0veBHPe3XUU": "n2lpJGx0LiKnuNE1IucZP3QExrD4SeRP0veBHPe3XUU"
},
"signatures": {
"@example:localhost": {
"ed25519:TCSJXPWGVS": "+j9G3L41I1fe0++wwusTTQvbboYW0yDtRWUEujhwZz4MAltjLSfJvY0hxhnz+wHHmuEXvQDen39XOpr1p29sAg"
}
}
}
},
"self_signing_keys": {
"@example:localhost": {
"user_id": "@example:localhost",
"usage": [
"self_signing"
],
"keys": {
"ed25519:kQXOuy639Yt47mvNTdrIluoC6DMvfbZLYbxAmwiDyhI": "kQXOuy639Yt47mvNTdrIluoC6DMvfbZLYbxAmwiDyhI"
},
"signatures": {
"@example:localhost": {
"ed25519:n2lpJGx0LiKnuNE1IucZP3QExrD4SeRP0veBHPe3XUU": "q32ifix/qyRpvmegw2BEJklwoBCAJldDNkcX+fp+lBA4Rpyqtycxge6BA4hcJdxYsy3oV0IHRuugS8rJMMFyAA"
}
}
}
},
"user_signing_keys": {
"@example:localhost": {
"user_id": "@example:localhost",
"usage": [
"user_signing"
],
"keys": {
"ed25519:g4ED07Fnqf3GzVWNN1pZ0IFrPQVdqQf+PYoJNH4eE0s": "g4ED07Fnqf3GzVWNN1pZ0IFrPQVdqQf+PYoJNH4eE0s"
},
"signatures": {
"@example:localhost": {
"ed25519:n2lpJGx0LiKnuNE1IucZP3QExrD4SeRP0veBHPe3XUU": "nKQu8alQKDefNbZz9luYPcNj+Z+ouQSot4fU/A23ELl1xrI06QVBku/SmDx0sIW1ytso0Cqwy1a+3PzCa1XABg"
}
}
}
}
});
const marked = await m.markRequestAsSent('foo', RequestType.KeysQuery, hypothetical_response);
}
{
// derived from https://github.com/matrix-org/matrix-rust-sdk/blob/7f49618d350fab66b7e1dc4eaf64ec25ceafd658/benchmarks/benches/crypto_bench/keys_claim.json
const hypothetical_response = JSON.stringify({
"one_time_keys": {
"@example:localhost": {
"AFGUOBTZWM": {
"signed_curve25519:AAAABQ": {
"key": "9IGouMnkB6c6HOd4xUsNv4i3Dulb4IS96TzDordzOws",
"signatures": {
"@example:localhost": {
"ed25519:AFGUOBTZWM": "2bvUbbmJegrV0eVP/vcJKuIWC3kud+V8+C0dZtg4dVovOSJdTP/iF36tQn2bh5+rb9xLlSeztXBdhy4c+LiOAg"
}
}
}
},
}
},
"failures": {}
});
const marked = await m.markRequestAsSent('bar', RequestType.KeysClaim, hypothetical_response);
}
});
test('can share a room key', async () => {
const other_users = [new UserId('@example:localhost')];
const requests = JSON.parse(await m.shareRoomKey(room, other_users, new EncryptionSettings()));
expect(requests).toHaveLength(1);
expect(requests[0].event_type).toBeDefined();
expect(requests[0].txn_id).toBeDefined();
expect(requests[0].messages).toBeDefined();
expect(requests[0].messages['@example:localhost']).toBeDefined();
});
let encrypted;
test('can encrypt an event', async () => {
encrypted = JSON.parse(await m.encryptRoomEvent(
room,
'm.room.message',
JSON.stringify({
"msgtype": "m.text",
"body": "Hello, World!"
}),
));
expect(encrypted.algorithm).toBeDefined();
expect(encrypted.ciphertext).toBeDefined();
expect(encrypted.sender_key).toBeDefined();
expect(encrypted.device_id).toStrictEqual(device.toString());
expect(encrypted.session_id).toBeDefined();
});
test('can decrypt an event', async () => {
const decrypted = await m.decryptRoomEvent(
JSON.stringify({
"type": "m.room.encrypted",
"event_id": "$xxxxx:example.org",
"origin_server_ts": Date.now(),
"sender": user.toString(),
content: encrypted,
unsigned: {
"age": 1234
}
}),
room,
);
expect(decrypted).toBeInstanceOf(DecryptedRoomEvent);
const event = JSON.parse(decrypted.event);
expect(event.content.msgtype).toStrictEqual("m.text");
expect(event.content.body).toStrictEqual("Hello, World!");
expect(decrypted.sender.toString()).toStrictEqual(user.toString());
expect(decrypted.senderDevice.toString()).toStrictEqual(device.toString());
expect(decrypted.senderCurve25519Key).toBeDefined();
expect(decrypted.senderClaimedEd25519Key).toBeDefined();
expect(decrypted.forwardingCurve25519KeyChain).toHaveLength(0);
expect(decrypted.verificationState).toStrictEqual(VerificationState.Trusted);
});
});
test('can read cross-signing status', async () => {
const m = await machine();
const crossSigningStatus = await m.crossSigningStatus();
expect(crossSigningStatus).toBeInstanceOf(CrossSigningStatus);
expect(crossSigningStatus.hasMaster).toStrictEqual(false);
expect(crossSigningStatus.hasSelfSigning).toStrictEqual(false);
expect(crossSigningStatus.hasUserSigning).toStrictEqual(false);
});
test('can sign a message', async () => {
const m = await machine();
const signatures = await m.sign('foo');
expect(signatures.isEmpty()).toStrictEqual(false);
expect(signatures.count).toStrictEqual(1);
let base64;
// `get`
{
const signature = signatures.get(user);
expect(signature.has('ed25519:foobar')).toStrictEqual(true);
const s = signature.get('ed25519:foobar');
expect(s).toBeInstanceOf(MaybeSignature);
expect(s.isValid()).toStrictEqual(true);
expect(s.isInvalid()).toStrictEqual(false);
expect(s.invalidSignatureSource).toBeUndefined();
base64 = s.signature.toBase64();
expect(base64).toMatch(/^[A-Za-z0-9\+/]+$/);
expect(s.signature.ed25519.toBase64()).toStrictEqual(base64);
}
// `getSignature`
{
const signature = signatures.getSignature(user, new DeviceKeyId('ed25519:foobar'));
expect(signature.toBase64()).toStrictEqual(base64);
}
// Unknown signatures.
{
expect(signatures.get(new UserId('@hello:example.org'))).toBeUndefined();
expect(signatures.getSignature(user, new DeviceKeyId('world:foobar'))).toBeUndefined();
}
});
test('can get a user identities', async () => {
const m = await machine();
let _ = m.bootstrapCrossSigning(true);
const identity = await m.getIdentity(user);
expect(identity).toBeInstanceOf(OwnUserIdentity);
const signatureUploadRequest = await identity.verify();
expect(signatureUploadRequest).toBeInstanceOf(SignatureUploadRequest);
const [verificationRequest, outgoingVerificationRequest] = await identity.requestVerification();
expect(verificationRequest).toBeInstanceOf(VerificationRequest);
expect(outgoingVerificationRequest).toBeInstanceOf(ToDeviceRequest);
const isTrusted = await identity.trustsOurOwnDevice();
expect(isTrusted).toStrictEqual(false);
});
describe('can export/import room keys', () => {
let m;
let exportedRoomKeys;
test('can export room keys', async () => {
m = await machine();
await m.shareRoomKey(room, [new UserId('@bob:example.org')], new EncryptionSettings());
exportedRoomKeys = await m.exportRoomKeys(session => {
expect(session).toBeInstanceOf(InboundGroupSession);
expect(session.roomId.toString()).toStrictEqual(room.toString());
expect(session.sessionId).toBeDefined();
expect(session.hasBeenImported()).toStrictEqual(false);
return true;
});
const roomKeys = JSON.parse(exportedRoomKeys);
expect(roomKeys).toHaveLength(1);
expect(roomKeys[0]).toMatchObject({
algorithm: expect.any(String),
room_id: room.toString(),
sender_key: expect.any(String),
session_id: expect.any(String),
session_key: expect.any(String),
sender_claimed_keys: {
ed25519: expect.any(String),
},
forwarding_curve25519_key_chain: [],
});
});
let encryptedExportedRoomKeys;
let encryptionPassphrase = 'Hello, Matrix!';
test('can encrypt the exported room keys', () => {
encryptedExportedRoomKeys = OlmMachine.encryptExportedRoomKeys(
exportedRoomKeys,
encryptionPassphrase,
100_000,
);
expect(encryptedExportedRoomKeys).toMatch(/^-----BEGIN MEGOLM SESSION DATA-----/);
});
test('can decrypt the exported room keys', () => {
const decryptedExportedRoomKeys = OlmMachine.decryptExportedRoomKeys(
encryptedExportedRoomKeys,
encryptionPassphrase,
);
expect(decryptedExportedRoomKeys).toStrictEqual(exportedRoomKeys);
});
test('can import room keys', async () => {
const progressListener = (progress, total) => {
expect(progress).toBeLessThan(total);
// Since it's called only once, let's be crazy.
expect(progress).toStrictEqual(0n);
expect(total).toStrictEqual(1n);
};
const result = JSON.parse(await m.importRoomKeys(exportedRoomKeys, progressListener));
expect(result).toMatchObject({
imported_count: expect.any(Number),
total_count: expect.any(Number),
keys: expect.any(Object),
});
});
});
});
@@ -0,0 +1,35 @@
const { RequestType, KeysUploadRequest, KeysQueryRequest, KeysClaimRequest, ToDeviceRequest, SignatureUploadRequest, RoomMessageRequest, KeysBackupRequest } = require('../pkg/matrix_sdk_crypto_js');
describe('RequestType', () => {
test('has the correct variant values', () => {
expect(RequestType.KeysUpload).toStrictEqual(0);
expect(RequestType.KeysQuery).toStrictEqual(1);
expect(RequestType.KeysClaim).toStrictEqual(2);
expect(RequestType.ToDevice).toStrictEqual(3);
expect(RequestType.SignatureUpload).toStrictEqual(4);
expect(RequestType.RoomMessage).toStrictEqual(5);
expect(RequestType.KeysBackup).toStrictEqual(6);
});
});
for (const [request, requestType] of [
[KeysUploadRequest, RequestType.KeysUpload],
[KeysQueryRequest, RequestType.KeysQuery],
[KeysClaimRequest, RequestType.KeysClaim],
[ToDeviceRequest, RequestType.ToDevice],
[SignatureUploadRequest, RequestType.SignatureUpload],
[RoomMessageRequest, RequestType.RoomMessage],
[KeysBackupRequest, RequestType.KeysBackup],
]) {
describe(request.name, () => {
test('can be instantiated', () => {
const r = new (request)('foo', '{"bar": "baz"}');
expect(r).toBeInstanceOf(request);
expect(r.id).toStrictEqual('foo');
expect(r.body).toStrictEqual('{"bar": "baz"}');
expect(r.type).toStrictEqual(requestType);
});
})
}
@@ -0,0 +1,31 @@
const { DeviceLists, UserId } = require('../pkg/matrix_sdk_crypto_js');
describe(DeviceLists.name, () => {
test('can be empty', () => {
const empty = new DeviceLists();
expect(empty.isEmpty()).toStrictEqual(true);
expect(empty.changed).toHaveLength(0);
expect(empty.left).toHaveLength(0);
});
test('can be coerced empty', () => {
const empty = new DeviceLists([], []);
expect(empty.isEmpty()).toStrictEqual(true);
expect(empty.changed).toHaveLength(0);
expect(empty.left).toHaveLength(0);
});
test('returns the correct `changed` and `left`', () => {
const list = new DeviceLists([new UserId('@foo:bar.org')], [new UserId('@baz:qux.org')]);
expect(list.isEmpty()).toStrictEqual(false);
expect(list.changed).toHaveLength(1);
expect(list.changed[0].toString()).toStrictEqual('@foo:bar.org');
expect(list.left).toHaveLength(1);
expect(list.left[0].toString()).toStrictEqual('@baz:qux.org');
});
});
@@ -0,0 +1,84 @@
const { Tracing, LoggerLevel, OlmMachine, UserId, DeviceId } = require('../pkg/matrix_sdk_crypto_js');
describe('LoggerLevel', () => {
test('has the correct variant values', () => {
expect(LoggerLevel.Trace).toStrictEqual(0);
expect(LoggerLevel.Debug).toStrictEqual(1);
expect(LoggerLevel.Info).toStrictEqual(2);
expect(LoggerLevel.Warn).toStrictEqual(3);
expect(LoggerLevel.Error).toStrictEqual(4);
});
});
describe(Tracing.name, () => {
if (Tracing.isAvailable()) {
let tracing = new Tracing(LoggerLevel.Debug);
test('can installed several times', () => {
new Tracing(LoggerLevel.Debug);
new Tracing(LoggerLevel.Warn);
new Tracing(LoggerLevel.Debug);
});
const originalConsoleDebug = console.debug;
for (const [testName, testPreState, testPostState, expectedGotcha] of [
[
'can log something',
() => {},
() => {},
true,
],
[
'can change the logger level',
() => { tracing.minLevel = LoggerLevel.Warn },
() => { tracing.minLevel = LoggerLevel.Debug },
false,
],
[
'can be turned off',
() => { tracing.turnOff() },
() => {},
false,
],
[
'can be turned on',
() => { tracing.turnOn() },
() => {},
true,
],
// This one *must* be the last. We are turning tracing off
// again for the other tests.
[
'can be turned off',
() => { tracing.turnOff() },
() => {},
false,
],
]) {
test(testName, async () => {
testPreState();
let gotcha = false;
console.debug = (msg) => {
gotcha = true;
expect(msg).not.toHaveLength(0);
};
// Do something that emits a `DEBUG` log.
await new OlmMachine(new UserId('@alice:example.org'), new DeviceId('foo'));
console.debug = originalConsoleDebug;
testPostState();
expect(gotcha).toStrictEqual(expectedGotcha);
});
}
} else {
test('cannot be constructed', () => {
expect(() => { new Tracing(LoggerLevel.Error) }).toThrow();
});
}
});
@@ -0,0 +1,10 @@
{
"compilerOptions": {
"strict": true
},
"typedocOptions": {
"entryPoints": ["pkg/matrix_sdk_crypto_js.d.ts"],
"out": "docs",
"readme": "README.md",
}
}
@@ -0,0 +1,7 @@
/node_modules
/package-lock.json
/index.js
/index.d.ts
/matrix-sdk-crypto.*.node
/docs/*
*.tgz
@@ -0,0 +1,8 @@
src/
tests/
Cargo.toml
build.rs
*.node
*.tgz
tsconfig.json
cliff.toml
@@ -0,0 +1,32 @@
# Matrix-Rust-SDK Node.js Bindings
## 0.1.0-beta.1 - 2022-07-14
- Fixing broken download link, [#842](https://github.com/matrix-org/matrix-rust-sdk/issues/842)
## 0.1.0-beta.0 - 2022-07-12
Welcome to the first release of `matrix-sdk-crypto-nodejs`. This is a
Node.js binding for the Rust `matrix-sdk-crypto` library. This is a
no-network-IO implementation of a state machine, named `OlmMachine`,
that handles E2EE (End-to-End Encryption) for Matrix clients.
The goal of this binding is _not_ to cover the entirety of the
`matrix-sdk-crypto` API, but only what's required to build Matrix bots
or Matrix bridges (i.e. to connect different networks together via the
Matrix protocol).
This project replaces and deprecates a previous project, with the same
name and same goals, inside [the `matrix-rust-sdk-bindings`
repository](https://github.com/matrix-org/matrix-rust-sdk-bindings),
with the NPM package name `@turt2live/matrix-sdk-crypto-nodejs`. The
The new official package name is
`@matrix-org/matrix-sdk-crypto-nodejs`.
Note: All bindings are now part of [the `matrix-rust-sdk`
repository](https://github.com/matrix-org/matrix-rust-sdk) (see the
`bindings/` root directory).
[A documentation is available inside the new
`matrix-sdk-crypto-nodejs`
project](https://github.com/matrix-org/matrix-rust-sdk/tree/0bde5ccf38f8cda3865297a2d12ddcdaf4b80ca7/bindings/matrix-sdk-crypto-nodejs).
@@ -0,0 +1,42 @@
[package]
authors = ["Ivan Enderlin <ivane@element.io>"]
description = "Matrix encryption library, for NodeJS"
edition = "2021"
homepage = "https://github.com/matrix-org/matrix-rust-sdk"
keywords = ["matrix", "chat", "messaging", "ruma", "nio"]
license = "Apache-2.0"
name = "matrix-sdk-crypto-nodejs"
readme = "README.md"
repository = "https://github.com/matrix-org/matrix-rust-sdk"
rust-version = "1.60"
version = "0.6.0"
[package.metadata.docs.rs]
rustdoc-args = ["--cfg", "docsrs"]
[lib]
crate-type = ["cdylib"]
[features]
default = []
qrcode = ["matrix-sdk-crypto/qrcode"]
tracing = ["dep:tracing-subscriber"]
[dependencies]
matrix-sdk-crypto = { version = "0.6.0", path = "../../crates/matrix-sdk-crypto", features = ["js"] }
matrix-sdk-common = { version = "0.6.0", path = "../../crates/matrix-sdk-common", features = ["js"] }
matrix-sdk-sled = { version = "0.2.0", path = "../../crates/matrix-sdk-sled", default-features = false, features = ["crypto-store"] }
ruma = { version = "0.7.0", features = ["client-api-c", "rand", "unstable-msc2676", "unstable-msc2677"] }
napi = { version = "2.9.1", default-features = false, features = ["napi6", "tokio_rt"] }
napi-derive = "2.9.1"
serde_json = "1.0.79"
http = "0.2.6"
zeroize = "1.3.0"
tracing-subscriber = { version = "0.3", default-features = false, features = ["tracing-log", "time", "smallvec", "fmt", "env-filter"], optional = true }
[dependencies.vodozemac]
version = "0.3.0"
features = ["js"]
[build-dependencies]
napi-build = "2.0.0"
+208
View File
@@ -0,0 +1,208 @@
# `matrix-sdk-crypto-nodejs`
Welcome to the [Node.js] binding for the Rust [`matrix-sdk-crypto`]
library! This binding is part of the [`matrix-rust-sdk`] project,
which is a library implementation of a [Matrix] client-server.
`matrix-sdk-crypto-nodejs` is a no-network-IO implementation of a
state machine, named `OlmMachine`, that handles E2EE ([End-to-End
Encryption](https://en.wikipedia.org/wiki/End-to-end_encryption)) for
[Matrix] clients.
## Usage
Just add the latest release to your `package.json`:
```sh
$ npm install --save @matrix-org/matrix-sdk-crypto-nodejs
```
When installing, NPM will download the corresponding prebuilt Rust library for your current host system. The following are supported:
<table>
<thead>
<tr>
<th>Platform</th>
<th>Architecture</th>
<th>Triple</th>
<th>Prebuilt available</th>
</tr>
</thead>
<tbody>
<tr>
<td rowspan="5">Linux</td>
<td rowspan="2"><code>aarch</code></td>
<td><code>aarch64-unknown-linux-gnu</code></td>
<td>✅</td>
</tr>
<tr>
<td><code>arm-unknown-linux-gnueabihf</code></td>
<td>✅</td>
</tr>
<tr>
<td rowspan="3"><code>amd</code></td>
<td><code>x86_64-unknown-linux-gnu</code></td>
<td>✅</td>
</tr>
<tr>
<td><code>x86_64-unknown-linux-musl</code></td>
<td>✅</td>
</tr>
<tr>
<td><code>i686-unknown-linux-gnu</code></td>
<td>✅</td>
</tr>
<tr>
<td rowspan="2">macOS</td>
<td><code>aarch</code></td>
<td><code>arch64-apple-darwin</code></td>
<td>✅</td>
</tr>
<tr>
<td><code>amd</code></td>
<td><code>x86_64-apple-darwin</code></td>
<td>✅</td>
</tr>
<tr>
<td rowspan="3">Windows</td>
<td><code>aarch</code></td>
<td><code>aarch64-pc-windows-msvc</code></td>
<td>✅</td>
</tr>
<tr>
<td rowspan="2"><code>amd</code></td>
<td><code>x86_64-pc-windows-msvc</code></td>
<td>✅</td>
</tr>
<tr>
<td><code>i686-pc-windows-msvc</code></td>
<td>✅</td>
</tr>
</tbody>
</table>
## Development
This Node.js binding is written in [Rust]. To build this binding, you
need to install the Rust compiler, see [the Install Rust
Page](https://www.rust-lang.org/tools/install). Then, the workflow is
pretty classical by using [npm], see [the Downloading and installing
Node.js and npm
Page](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm).
The binding is compatible with, and tested against, the Node.js
versions that are in “current”, “active” or “maintenance” states,
according to [the Node.js Releases
Page](https://nodejs.org/en/about/releases/), _and_ which are
compatible with [NAPI v6 (Node.js
API)](https://nodejs.org/api/n-api.html#node-api-version-matrix). It
means that this binding will work with the following versions: 14.0.0,
16.0.0 and 18.0.0.
Once the Rust compiler, Node.js and npm are installed, you can run the
following commands:
```sh
$ npm install --ignore-scripts
$ npm run build
$ npm run test
```
An `index.js`, `index.d.ts` and a `*.node` files should be
generated. At the same level of those files, you can edit a file and
try this:
```javascript
const { OlmMachine } = require('./index.js');
// Let's see what we can do.
```
The `OlmMachine` state machine works in a push/pull manner:
* You push state changes and events retrieved from a Matrix homeserver
`/sync` response, into the state machine,
* You pull requests that you will need to send back to the homeserver
out of the state machine.
```javascript
const { OlmMachine, UserId, DeviceId, RoomId, DeviceLists } = require('./index.js');
async function main() {
// Define a user ID.
const alice = new UserId('@alice:example.org');
// Define a device ID.
const device = new DeviceId('DEVICEID');
// Let's create the `OlmMachine` state machine.
const machine = await OlmMachine.initialize(alice, device);
// Let's pretend we have received changes and events from a
// `/sync` endpoint of a Matrix homeserver, …
const toDeviceEvents = "{}"; // JSON-encoded
const changedDevices = new DeviceLists();
const oneTimeKeyCounts = {};
const unusedFallbackKeys = [];
// … and push them into the state machine.
const decryptedToDevice = await machine.receiveSyncChanges(
toDeviceEvents,
changedDevices,
oneTimeKeyCounts,
unusedFallbackKeys,
);
// Now, let's pull requests that we need to send out to the Matrix
// homeserver.
const outgoingRequests = await machine.outgoingRequests();
// To complete the workflow, send the requests here out and call
// `machine.markRequestAsSent`.
}
main();
```
### With tracing (experimental)
If you want to enable [tracing](https://tracing.rs), i.e. to get the
logs, you should re-compile the extension with the `tracing` feature
turned on:
```sh
$ npm run build -- --features tracing
```
Now, you can use the `MATRIX_LOG` environment variable to tweak the log filtering, such as:
```sh
$ MATRIX_LOG=debug npm run test
```
See
[`tracing-subscriber`](https://tracing.rs/tracing_subscriber/index.html)
to learn more about the `RUST_LOG`/`MATRIX_LOG` environment variable.
## Documentation
[The documentation can be found
online](https://matrix-org.github.io/matrix-rust-sdk/bindings/matrix-sdk-crypto-nodejs/).
To generate the documentation locally, please run the following
command:
```sh
$ npm run doc
```
The documentation is generated in the `./docs` directory.
[Node.js]: https://nodejs.org/
[`matrix-sdk-crypto`]: https://github.com/matrix-org/matrix-rust-sdk/tree/main/crates/matrix-sdk-crypto
[`matrix-rust-sdk`]: https://github.com/matrix-org/matrix-rust-sdk
[Matrix]: https://matrix.org/
[Rust]: https://www.rust-lang.org/
[npm]: https://www.npmjs.com/
@@ -0,0 +1,3 @@
fn main() {
napi_build::setup();
}
@@ -0,0 +1,61 @@
# configuration file for git-cliff (0.1.0)
[changelog]
# changelog header
header = """
# Matrix SDK Crypto Node.js Changelog\n
All notable changes to this project will be documented in this file.\n
"""
# template for the changelog body
# https://tera.netlify.app/docs/#introduction
body = """
{% if version %}\
## [{{ version | trim_start_matches(pat="v") }}] - {{ timestamp | date(format="%Y-%m-%d") }}
{% else %}\
## [unreleased]
{% endif %}\
{% for group, commits in commits | filter(attribute="scope", value="crypto-nodejs") | group_by(attribute="group") %}
### {{ group | upper_first }}
{% for commit in commits %}
- {{ commit.id | truncate(length=7, end="") }}{% if commit.breaking %} [**breaking**] {% endif %}: {{ commit.message | upper_first }}\
{% endfor %}
{% endfor %}\n
"""
# remove the leading and trailing whitespace from the template
trim = true
# changelog footer
footer = """
"""
[git]
# parse the commits based on https://www.conventionalcommits.org
conventional_commits = true
# filter out the commits that are not conventional
filter_unconventional = true
# regex for preprocessing the commit messages
commit_preprocessors = [
{ pattern = '\((\w+\s)?#([0-9]+)\)', replace = "([#${2}](https://github.com/matrix-org/matrix-rust-sdk/issues/${2}))"},
]
# regex for parsing and grouping commits
commit_parsers = [
{ message = "^feat", group = "Features"},
{ message = "^fix", group = "Bug Fixes"},
{ message = "^test", group = "Testing"},
{ message = "^doc", group = "Documentation"},
{ message = "^refactor", group = "Refactoring"},
{ message = "^ci", group = "Continuous Integration"},
{ message = "^chore", group = "Miscellaneous Tasks"},
{ body = ".*security", group = "Security"},
]
# filter out the commits that are not matched by commit parsers
filter_commits = true
# glob pattern for matching git tags
tag_pattern = "v[0-9]*"
# regex for skipping tags
skip_tags = "v0.1.0-beta.1"
# regex for ignoring tags
ignore_tags = ""
# sort the tags chronologically
date_order = false
# sort the commits inside sections by oldest/newest order
sort_commits = "oldest"
@@ -0,0 +1,113 @@
const { DownloaderHelper } = require('node-downloader-helper');
const { version } = require("./package.json");
const { platform, arch } = process
const DOWNLOADS_BASE_URL = "https://github.com/matrix-org/matrix-rust-sdk/releases/download";
const CURRENT_VERSION = `matrix-sdk-crypto-nodejs-v${version}`;
const byteHelper = function (value) {
if (value === 0) {
return '0 b';
}
const units = ['b', 'kB', 'MB', 'GB', 'TB'];
const number = Math.floor(Math.log(value) / Math.log(1024));
return (value / Math.pow(1024, Math.floor(number))).toFixed(1) + ' ' +
units[number];
};
function download_lib(libname) {
let startTime = new Date();
const url = `${DOWNLOADS_BASE_URL}/${CURRENT_VERSION}/${libname}`;
console.info(`Downloading lib ${libname} from ${url}`);
const dl = new DownloaderHelper(url, __dirname, {
override: true,
});
dl.on('end', () => console.info('Download Completed'));
dl.on('error', (err) => console.info('Download Failed', err));
dl.on('progress', stats => {
const progress = stats.progress.toFixed(1);
const speed = byteHelper(stats.speed);
const downloaded = byteHelper(stats.downloaded);
const total = byteHelper(stats.total);
// print every one second (`progress.throttled` can be used instead)
const currentTime = new Date();
const elaspsedTime = currentTime - startTime;
if (elaspsedTime > 1000) {
startTime = currentTime;
console.info(`${speed}/s - ${progress}% [${downloaded}/${total}]`);
}
});
dl.start().catch(err => console.error(err));
}
function isMusl() {
// For Node 10
if (!process.report || typeof process.report.getReport !== 'function') {
try {
return readFileSync('/usr/bin/ldd', 'utf8').includes('musl')
} catch (e) {
return true
}
} else {
const { glibcVersionRuntime } = process.report.getReport().header
return !glibcVersionRuntime
}
}
switch (platform) {
case 'win32':
switch (arch) {
case 'x64':
download_lib('matrix-sdk-crypto.win32-x64-msvc.node')
break
case 'ia32':
download_lib('matrix-sdk-crypto.win32-ia32-msvc.node')
break
case 'arm64':
download_lib('matrix-sdk-crypto.win32-arm64-msvc.node')
break
default:
throw new Error(`Unsupported architecture on Windows: ${arch}`)
}
break
case 'darwin':
switch (arch) {
case 'x64':
download_lib('matrix-sdk-crypto.darwin-x64.node')
break
case 'arm64':
download_lib('matrix-sdk-crypto.darwin-arm64.node')
break
default:
throw new Error(`Unsupported architecture on macOS: ${arch}`)
}
break
case 'linux':
switch (arch) {
case 'x64':
if (isMusl()) {
download_lib('matrix-sdk-crypto.linux-x64-musl.node')
} else {
download_lib('matrix-sdk-crypto.linux-x64-gnu.node')
}
break
case 'arm64':
if (isMusl()) {
throw new Error('Linux for arm64 musl isn\'t support at the moment')
} else {
download_lib('matrix-sdk-crypto.linux-arm64-gnu.node')
}
break
case 'arm':
download_lib('matrix-sdk-crypto.linux-arm-gnueabihf.node')
break
default:
throw new Error(`Unsupported architecture on Linux: ${arch}`)
}
break
default:
throw new Error(`Unsupported OS: ${platform}, architecture: ${arch}`)
}
@@ -0,0 +1,34 @@
{
"name": "@matrix-org/matrix-sdk-crypto-nodejs",
"version": "0.1.0-beta.1",
"main": "index.js",
"types": "index.d.ts",
"napi": {
"name": "matrix-sdk-crypto",
"triples": {
"additional": [
"aarch64-apple-darwin"
]
}
},
"license": "Apache-2.0",
"devDependencies": {
"@napi-rs/cli": "^2.9.0",
"jest": "^28.1.0",
"typedoc": "^0.22.17",
"yargs-parser": "~21.0.1"
},
"engines": {
"node": ">= 14"
},
"scripts": {
"release-build": "napi build --platform --release --strip",
"build": "napi build --platform",
"postinstall": "node download-lib.js",
"test": "jest --verbose --testTimeout 10000",
"doc": "typedoc --tsconfig ."
},
"dependencies": {
"node-downloader-helper": "^2.1.1"
}
}
@@ -0,0 +1,126 @@
use std::{
io::{Cursor, Read},
ops::Deref,
};
use napi::bindgen_prelude::Uint8Array;
use napi_derive::*;
use crate::into_err;
/// A type to encrypt and to decrypt anything that can fit in an
/// `Uint8Array`, usually big buffer.
#[napi]
pub struct Attachment;
#[napi]
impl Attachment {
/// Encrypt the content of the `Uint8Array`.
///
/// It produces an `EncryptedAttachment`, which can be used to
/// retrieve the media encryption information, or the encrypted
/// data.
#[napi]
pub fn encrypt(array: Uint8Array) -> napi::Result<EncryptedAttachment> {
let buffer: &[u8] = array.deref();
let mut cursor = Cursor::new(buffer);
let mut encryptor = matrix_sdk_crypto::AttachmentEncryptor::new(&mut cursor);
let mut encrypted_data = Vec::new();
encryptor.read_to_end(&mut encrypted_data).map_err(into_err)?;
let media_encryption_info = Some(encryptor.finish());
Ok(EncryptedAttachment {
encrypted_data: Uint8Array::new(encrypted_data),
media_encryption_info,
})
}
/// Decrypt an `EncryptedAttachment`.
///
/// The encrypted attachment can be created manually, or from the
/// `encrypt` method.
///
/// **Warning**: The encrypted attachment can be used only
/// **once**! The encrypted data will still be present, but the
/// media encryption info (which contain secrets) will be
/// destroyed. It is still possible to get a JSON-encoded backup
/// by calling `EncryptedAttachment.mediaEncryptionInfo`.
#[napi]
pub fn decrypt(attachment: &mut EncryptedAttachment) -> napi::Result<Uint8Array> {
let media_encryption_info = match attachment.media_encryption_info.take() {
Some(media_encryption_info) => media_encryption_info,
None => {
return Err(napi::Error::from_reason(
"The media encryption info are absent from the given encrypted attachment"
.to_owned(),
))
}
};
let encrypted_data: &[u8] = attachment.encrypted_data.deref();
let mut cursor = Cursor::new(encrypted_data);
let mut decryptor =
matrix_sdk_crypto::AttachmentDecryptor::new(&mut cursor, media_encryption_info)
.map_err(into_err)?;
let mut decrypted_data = Vec::new();
decryptor.read_to_end(&mut decrypted_data).map_err(into_err)?;
Ok(Uint8Array::new(decrypted_data))
}
}
/// An encrypted attachment, usually created from `Attachment.encrypt`.
#[napi]
pub struct EncryptedAttachment {
media_encryption_info: Option<matrix_sdk_crypto::MediaEncryptionInfo>,
/// The actual encrypted data.
pub encrypted_data: Uint8Array,
}
#[napi]
impl EncryptedAttachment {
/// Create a new encrypted attachment manually.
///
/// It needs encrypted data, stored in an `Uint8Array`, and a
/// [media encryption
/// information](https://docs.rs/matrix-sdk-crypto/latest/matrix_sdk_crypto/struct.MediaEncryptionInfo.html),
/// as a JSON-encoded string.
///
/// The media encryption information aren't stored as a string:
/// they are parsed, validated and fully deserialized.
///
/// See [the specification to learn
/// more](https://spec.matrix.org/unstable/client-server-api/#extensions-to-mroommessage-msgtypes).
#[napi(constructor)]
pub fn new(encrypted_data: Uint8Array, media_encryption_info: String) -> napi::Result<Self> {
Ok(Self {
encrypted_data,
media_encryption_info: Some(
serde_json::from_str(media_encryption_info.as_str()).map_err(into_err)?,
),
})
}
/// Return the media encryption info as a JSON-encoded string. The
/// structure is fully valid.
///
/// If the media encryption info have been consumed already, it
/// will return `null`.
#[napi(getter)]
pub fn media_encryption_info(&self) -> Option<String> {
serde_json::to_string(self.media_encryption_info.as_ref()?).ok()
}
/// Check whether the media encryption info has been consumed by
/// `Attachment.decrypt` already.
#[napi(getter)]
pub fn has_media_encryption_info_been_consumed(&self) -> bool {
self.media_encryption_info.is_none()
}
}
@@ -0,0 +1,133 @@
use std::time::Duration;
use napi::bindgen_prelude::{BigInt, ToNapiValue};
use napi_derive::*;
use crate::events;
/// An encryption algorithm to be used to encrypt messages sent to a
/// room.
#[napi]
pub enum EncryptionAlgorithm {
/// Olm version 1 using Curve25519, AES-256, and SHA-256.
OlmV1Curve25519AesSha2,
/// Megolm version 1 using AES-256 and SHA-256.
MegolmV1AesSha2,
}
impl From<EncryptionAlgorithm> for matrix_sdk_crypto::types::EventEncryptionAlgorithm {
fn from(value: EncryptionAlgorithm) -> Self {
use EncryptionAlgorithm::*;
match value {
OlmV1Curve25519AesSha2 => Self::OlmV1Curve25519AesSha2,
MegolmV1AesSha2 => Self::MegolmV1AesSha2,
}
}
}
impl From<matrix_sdk_crypto::types::EventEncryptionAlgorithm> for EncryptionAlgorithm {
fn from(value: matrix_sdk_crypto::types::EventEncryptionAlgorithm) -> Self {
use matrix_sdk_crypto::types::EventEncryptionAlgorithm::*;
match value {
OlmV1Curve25519AesSha2 => Self::OlmV1Curve25519AesSha2,
MegolmV1AesSha2 => Self::MegolmV1AesSha2,
_ => unreachable!("Unknown variant"),
}
}
}
/// Settings for an encrypted room.
///
/// This determines the algorithm and rotation periods of a group
/// session.
#[napi]
pub struct EncryptionSettings {
/// The encryption algorithm that should be used in the room.
pub algorithm: EncryptionAlgorithm,
/// How long the session should be used before changing it,
/// expressed in microseconds.
pub rotation_period: BigInt,
/// How many messages should be sent before changing the session.
pub rotation_period_messages: BigInt,
/// The history visibility of the room when the session was
/// created.
pub history_visibility: events::HistoryVisibility,
/// Should untrusted devices receive the room key, or should they be
/// excluded from the conversation.
pub only_allow_trusted_devices: bool,
}
impl Default for EncryptionSettings {
fn default() -> Self {
let default = matrix_sdk_crypto::olm::EncryptionSettings::default();
Self {
algorithm: default.algorithm.into(),
rotation_period: {
let n: u64 = default.rotation_period.as_micros().try_into().unwrap();
n.into()
},
rotation_period_messages: {
let n = default.rotation_period_msgs;
n.into()
},
history_visibility: default.history_visibility.into(),
only_allow_trusted_devices: default.only_allow_trusted_devices,
}
}
}
#[napi]
impl EncryptionSettings {
/// Create a new `EncryptionSettings` with default values.
#[napi(constructor)]
pub fn new() -> EncryptionSettings {
Self::default()
}
}
impl From<&EncryptionSettings> for matrix_sdk_crypto::olm::EncryptionSettings {
fn from(value: &EncryptionSettings) -> Self {
Self {
algorithm: value.algorithm.into(),
rotation_period: Duration::from_micros(value.rotation_period.get_u64().1),
rotation_period_msgs: value.rotation_period_messages.get_u64().1,
history_visibility: value.history_visibility.into(),
only_allow_trusted_devices: value.only_allow_trusted_devices,
}
}
}
/// The verification state of the device that sent an event to us.
#[napi]
pub enum VerificationState {
/// The device is trusted.
Trusted,
/// The device is not trusted.
Untrusted,
/// The device is not known to us.
UnknownDevice,
}
impl From<&matrix_sdk_common::deserialized_responses::VerificationState> for VerificationState {
fn from(value: &matrix_sdk_common::deserialized_responses::VerificationState) -> Self {
use matrix_sdk_common::deserialized_responses::VerificationState::*;
match value {
Trusted => Self::Trusted,
Untrusted => Self::Untrusted,
UnknownDevice => Self::UnknownDevice,
}
}
}
@@ -0,0 +1,28 @@
/// Generic error wrapping `napi::Error`.
#[derive(Debug)]
pub struct Error(napi::Error);
impl<E> From<E> for Error
where
E: std::error::Error,
{
fn from(error: E) -> Self {
Self(napi::Error::from_reason(error.to_string()))
}
}
impl From<Error> for napi::Error {
#[inline]
fn from(value: Error) -> Self {
value.0
}
}
/// Helper to replace the `E` to `Error` to `napi::Error` conversion.
#[inline]
pub fn into_err<E>(error: E) -> napi::Error
where
E: std::error::Error,
{
Error::from(error).into()
}
@@ -0,0 +1,62 @@
//! Types related to events.
use napi::bindgen_prelude::ToNapiValue;
use napi_derive::*;
use ruma::events::room::history_visibility::HistoryVisibility as RumaHistoryVisibility;
/// Who can see a room's history.
#[napi]
#[derive(Debug)]
pub enum HistoryVisibility {
/// Previous events are accessible to newly joined members from
/// the point they were invited onwards.
///
/// Events stop being accessible when the member's state changes
/// to something other than *invite* or *join*.
Invited,
/// Previous events are accessible to newly joined members from
/// the point they joined the room onwards.
///
/// Events stop being accessible when the member's state changes
/// to something other than *join*.
Joined,
/// Previous events are always accessible to newly joined members.
///
/// All events in the room are accessible, even those sent when
/// the member was not a part of the room.
Shared,
/// All events while this is the `HistoryVisibility` value may be
/// shared by any participating homeserver with anyone, regardless
/// of whether they have ever joined the room.
WorldReadable,
}
impl From<HistoryVisibility> for RumaHistoryVisibility {
fn from(value: HistoryVisibility) -> Self {
use HistoryVisibility::*;
match value {
Invited => Self::Invited,
Joined => Self::Joined,
Shared => Self::Shared,
WorldReadable => Self::WorldReadable,
}
}
}
impl From<RumaHistoryVisibility> for HistoryVisibility {
fn from(value: RumaHistoryVisibility) -> Self {
use RumaHistoryVisibility::*;
match value {
Invited => Self::Invited,
Joined => Self::Joined,
Shared => Self::Shared,
WorldReadable => Self::WorldReadable,
_ => unreachable!("Unknown variant"),
}
}
}

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