Initial commit version 0.8.13

This commit is contained in:
PCoder 2022-04-18 14:27:08 +05:30
commit 9526dfa4f2
111 changed files with 35074 additions and 0 deletions

345
CHANGELOG.md Normal file
View file

@ -0,0 +1,345 @@
## [0.8.13] - 02nd Mar 2022
- fix: send oldusername in displayname changed event
- fix: Dont encrypt reactions
- refactor: Make MatrixFile final and move all image calculation into isolate
- fix: own profile containing mxid
- chore: Update fluffybox
## [0.8.12] - 02nd Mar 2022
- fix: Rooms sort order after login
- fix: Change password using email authentication
## [0.8.11] - 19nd Feb 2022
- fix: Change password using email authentication
## [0.8.10] - 19nd Feb 2022
- chore: Increase default thumbnail size to 800
- fix: sortRooms should be triggered right before onSync is called
- fix: UIA request stucks forever on unexpected matrixExceptions
## [0.8.9] - 16nd Feb 2022
- feat: Return homeserver summary on checkHomeserver
- fix: hasNewMessage true when last event is sent
- fix: Correctly end the call.
## [0.8.8] - 15nd Feb 2022
- fix: Has new messages compares ts
- fix: handle dynamic content for pinned events
## [0.8.7] - 14nd Feb 2022
- fix: Show reactions as last events and refactor hasNewMessage
## [0.8.6] - 14nd Feb 2022
- feat: Add hasNewMessages flag to room
- fix: Sort rooms after updating the UI on web
## [0.8.5] - 14nd Feb 2022
- fix: exception on removed widgets
- fix: Fix black screen when end screensharing with system buttons.
## [0.8.4] - 08nd Feb 2022
- fix: Call onChange correctly on redacted aggregation events
## [0.8.3] - 07nd Feb 2022
- fix: Remove onHistoryReceived which was broken anyway
- fix: Remove aggregation event doesnt trigger onChange
## [0.8.2] - 04nd Feb 2022
- fix: Add redaction events to timeline
- fix: Resize image with compute by using const class arguments
## [0.8.1] - 03nd Feb 2022
- refactor: Implement on history received in timeline
- fix: null-safety issues with widgets
- fix: Trigger onChange for index on aggregation event update
- feat: implement to get a room's widgets
## [0.8.0] - 25nd Jan 2022
- BREAKING CHANGE: high-level hadling of image sizes
- feat: expose Timeline.onChange to Room.getTimeline
- fix: Use where and map instead of a loop and a removeWhere
- fix: Remove sorts that shouldnt be required.
## [0.7.3] - 14nd Jan 2022
- fix: Fix turn credentials format issue for safari.
- fix: update fluffybox version to correctly clear rooms after logout.
- fix: Allow unpadded base64 decoding
## [0.7.2] - 08nd Jan 2022
- feat: Let sendDefaultMessage return false on encryption failure (Krille Fear)
- fix: Room Member updates should always be cached (Krille Fear)
- fix: Requested users are not stored (Christian Pauly)
- fix: Localize reactions (Krille Fear)
- refactor: Remove unnecessary type checks and imports (Krille Fear)
## [0.7.1] - 08nd Dec 2021
- fix: fallback in body for replies to replies (Nicolas Werner)
- fix: ignore 4xx errors when re-sending the to_device queue The to_device queue was introduced to ensure integrity if e.g. the server temporarily failed when attempting to send a to_device message. If, for whatever reason, the server responds with a 4xx error, though, then we want to ignore that to_device message from the queue and move on, as that means that something different was fundamentally wrong. This helps to fix the to_device queue clogging up, making clients incapable of sending to_device events anymore, should such clogging happen. (Sorunome)
- fix: Database corruptions by updating FluffyBox (Krille Fear)
- fix: Store the call state, fix the invite cannot be sent. (cloudwebrtc)
- fix: Allow consecutive edits for state events in-memory The lastEvent was incorrect when trying to process an edit of an edit. This fixes that by allowing consecutive edits for the last event. (Sorunome)
- fix: Only save state events from sync processing in-memory if needed If we dump all state events from sync into memory then we needlessly clog up our memory, potentially running out of ram. This is useless as when opening the timeline we post-load the unimportant state events anyways. So, this PR makes sure that only the state events of post-loaded rooms and important state events land in-memory when processing a sync request. (Sorunome)
- fix(ssss): Strip all whitespace characters from recovery keys upon decode Previously we stripped all spaces off of the recovery when decoding it, so that we could format the recovery key nicely. It turns out, however, that some element flavours also format with linebreaks, leading to the user having to manually remove them. We fix this by just stripping *all* whitespace off of the recovery key. (Sorunome)
## [0.7.0] - 03nd Dec 2021
- feat: Support for webRTC
- fix: Add missing calcDisplayname global rules to client constructor
## [0.7.0-nullsafety.10] - 26nd Nov 2021
- feat: Migrate olm sessions on database migration
- chore: Enable E2EE recovery by default
## [0.7.0-nullsafety.9] - 25nd Nov 2021
- fix: Limited timeline clean up on web
- fix: Remove account avatar
## [0.7.0-nullsafety.8] - 24nd Nov 2021
- chore: Update FluffyBox
## [0.7.0-nullsafety.7] - 23nd Nov 2021
- feat: Add commands to create chats
- feat: Add clear cache command
- feat: Implement new FluffyBox database API implementation
- fix: Workaround for a null exception for a non nullable boolean while user device key updating
- fix: Limited timeline clears too many events
- fix: Ability to remove avatar from room and account
- fix: Request history in archived rooms
- fix: Decrypt last event of a room
- refactor: Remove Sembast database implementation
## [0.7.0-nullsafety.6] - 16nd Nov 2021
- feat: Implement sembast store
- fix: HtmlToText crashes with an empty code block
- fix: use originServerTs to check if state event is old
- fix: Dont enable e2ee in new direct chats without encryption support
- fix: Change eventstatus of edits in prevEvent
- chore: Trim formatted username fallback
## [0.7.0-nullsafety.5] - 10nd Nov 2021
- fix: Edits as lastEvent do not update
- fix: JSON parsing in decryptRoomEvent method
- fix: Wrong null check in hive database
- fix: crash on invalid displaynames
- chore: Update matrix_api_lite
## [0.7.0-nullsafety.4] - 09nd Nov 2021
- feat: More advanced create chat methods (encryption is now enabled by default)
- feat: Make waiting on init db optional
- feat: Add more benchmarks for sync, timeline, init
- feat: Add onInsert, onRemove and onUpdate cb to timeline
- refactor: Move setreadmarker functionality to timeline
## [0.7.0-nullsafety.3] - 05nd Nov 2021
- fix: Null error in get own profile
## [0.7.0-nullsafety.2] - 04nd Nov 2021
- refactor: Make room in Event class not nullable
- refactor: download method should not return null
## [0.7.0-nullsafety.1] - 04nd Nov 2021
Prerelease of the null safety version of the SDK.
- feat: choose memberships returned by requestParticipants()
- refactor: Make SDK null safe
- fix: add room invite update to roomStateBox, so invites don't show empty room when app is restarted
- fix: Do not upload keys after logout
- fix: obay explicitly set ports in mxc URLs
## [0.6.2] - 25nd Oct 2021
- fix: Unnecessary null check
- fix: Auto update room states
## [0.6.1] - 18nd Oct 2021
- fix: Missing null check in a nested json map
## [0.6.0] - 15nd Oct 2021
- feat: Calc benchmarks for hive operations on init
- refactor: Change event status to enum
- refactor: Migrate more files to null safety
- fix: Type error when using CryptoKey in dart web
- fix: events with unknown users having invalid mxids This caused issues down the line where the sender id was assumed to be a valid matrix identifier
- fix: Sent events are sorted in SENDING timeline
- fix: use explicit type in fold instead of cast
- fix: apply review feedback
- fix: missing range check When requesting history the `start` parameter could become larger than the loaded events from the database were, resulting in an error when attempting to request history.
- fix: New verification requests on requesting history
- refactor: remove unused clientId
- fix: Add type checkings for User.displayName
## [0.5.5] - 20nd Sep 2021
fix: Autodetect mime type on file upload
## [0.5.4] - 20nd Sep 2021
- feat: Add waitForFirstSync parameter to init method
## [0.5.3] - 19nd Sep 2021
- feat: Add /discardsession command
- fix: Auto-reply key requests
- fix: Room previews not showing replies
- fix: missing content-type when changing avatar
- fix: only/number emotes in a reply
## [0.5.2] - 14nd Sep 2021
- fix: Delete box if it can not be cleared when calling database.clear() -> This should fix some box corruption problems
- fix: Do not set old events as state events -> This should fix the room list sort ordering bug
## [0.5.1] - 13nd Sep 2021
- fix: Room.notificationCount set to null sometimes
## [0.5.0] - 13nd Sep 2021
- hotfix: Key sharing security vulnerability! -> Please upgrade as soon as possible to this version
- feat: MSC2746: Improved Signalling for 1:1 VoIP
- fix: Get direct chat from user ID method crashes on more than one DM rooms with one account
- fix: compilation against newer matrix_api_lite
- refactor: Remove onRoomUpdate stream
## [0.4.3] - 8nd Sep 2021
- fix: Do not handle sending event updates which are already synced
## [0.4.2] - 6nd Sep 2021
- revert: Make bytes in EncryptedFile nullable
## [0.4.1] - 6nd Sep 2021
- fix: Make bytes in EncryptedFile nullable
## [0.4.0] - 3nd Sep 2021
- fix: Check if database got disposed in keyManager
- fix: Implement dummy transactions for hive
- fix: room account data key/type returned encoded
- fix: Missing null check
- fix: uiaRequests send broken auth object at first try
- fix: Requesting history being funky
- fix: Don't lag when sending messages in big rooms
- feat: Do not load all timeline events from store at once
- feat: Pin invited rooms
- refactor: Replace all logic regarding sortOrder
- refactor: Workarounds for missing mHeroes in rooms
## [0.3.6] - 30nd Aug 2021
- hotfix: uiaRequests send broken auth object at first try
## [0.3.5] - 28nd Aug 2021
- hotfix: Send unencrypted thumbnails
## [0.3.4] - 28nd Aug 2021
- fix: String.parseIdentifierIntoParts not working with unicode matrix.to links
Some clients do not uri-encode the identifier for matrix.to links, so we must
handle if we can't uri-decode them
- fix: missing null check in hideEdit condition
- fix: missing null check
It seems `device_keys` in the reply of `/keys/query` is not required. While synapse always
sent it, conduit did not, which resulted in an error.
## [0.3.3] - 20nd Aug 2021
- fix: room.lastEvent order now respects edits
- feat: use m.new_content in lastEvent (so no more * fallback)
## [0.3.2] - 20nd Aug 2021
- feat: cache archived rooms to access them with `getRoomById`
- fix: requestHistory() for archived rooms
- refactor: Change name of archive getter to function
## [0.3.1] - 20nd Aug 2021
- hotfix: Opt-out null safety for crypto files because of an error in web
## [0.3.0] - 20nd Aug 2021
- remove: deprecated moor database (breaking change)
- feat(events): add plain-text body representation from HTML
- feat: get new_content in getLocalizedBody
- feat: Add a way to get a verification request by its transaction id
A client might find the need to get the verification request object by
its transaction id, to be able to e.g. display for in-room verification
an "accept verification request" button easily.
- fix: Correctly parse the reason of a spoiler
Previously only the first child node of a spoiler was considered to
determine if there should be a spoiler reason. This was, unfortunately,
incorrect, as soon as e.g. the reason had more than one space. This is
fixed by properly iterating all child nodes to search for the reason.
- fix: Add space states to important events
We need the space state events in the important events to be able to
differentiate rooms and spaces in the room list.
- feat: Allow specifying extraContent for Room.sendFileEvent, in case clients want to specify some custom stuff
- fix: toDouble was called on null when you had a pinned room
- fix: Typo in key backup requests
This may lead to messages not decrypting after interactive verification,
which would make the user manually press the request keys button.
- refactor: rename LoginState.logged to loggedIn
## [0.2.1] - 2nd Aug 2021
- fix: accidental OTK uploads on fakeSync calls
## [0.2.0] - 27th Jul 2021
- Breaking API changes duo to use of code generated matrix API
- fix: Missing null checks in syncUpdate handling
## [0.1.11] - 26th Jul 2021
- fix: Upload OTKs if the otk_count field is missing
## [0.1.10] - 21th Jul 2021
Please note: This removes the isolate code from the SDK to make it compatible with dart web. If
you still want the SDK to execute code in the background to not block the UI on key generation
for example, pass the `compute` method from Flutter to your client:
```dart
// ...
final client = Client('name...',
// ...
compute: compute,
);
```
## [0.1.9] - 20th Jul 2021
- fix: Add missing null check which made bootstrap fail for newest Synapse release
## [0.1.8] - 18th Jul 2021
- fix: Provide a reasonable well-known fallback
- fix: Add locking to sending encrypted to_device messages to prevent potential race conditions
- fix: preserve homeserver port when creating thumbnail URIs
- feat: Add support for nicer mentions
- feat: Add general image pack handling as per MSC2545
## [0.1.7] - 10 Jul 2021
- change: Hive database schema (will trigger a database migration)
- fix: Dont migrate database from version null
- fix: Adjust emoji ranges to have less false positives
- fix: Sending of the to_device key
## [0.1.6] - 06 Jul 2021
- feat: Make it possible to get the current loginState
- fix: Broken nested accountData content maps
- fix: Mark unsent events as failed
- fix: Pin moor to 4.3.2 to fix the CI errors
## [0.1.5] - 26 Jun 2021
- fix: Don't run syncs while the client is being initialized
## [0.1.4] - 19 Jun 2021
- change: Replace onSyncError Stream with onSyncStatus
## [0.1.3] - 19 Jun 2021
- feat: Implement migration for hive schema versions
## [0.1.2] - 19 Jun 2021
- fix: Hive breaks if room IDs contain emojis (yes there are users with hacked synapses out there who needs this)
- feat: Also migrate inbound group sessions
## [0.1.1] - 18 Jun 2021
- refactor: Move pedantic to dev_dependencies
- chore: Update readme
- fix: Migrate missing device keys
## [0.1.0] - 17 Jun 2021
First stable version

104
CONTRIBUTING.md Normal file
View file

@ -0,0 +1,104 @@
# Contributing code to Famedly
*See also: Code of Conduct*
We look forward to you joining our team. Everyone is welcome to contribute code via pull requests or to file issues on Gitlab or help other peoples. We communicate primarily over Gitlab and on chat channels. You should be willing to license your contributions under the same license as the project itself.
# How to contribute
The only way to contribute changes to our project is to create a new branch or to fork it on Gitlab. Then create a merge request to ask us to merge your changes into the main branch of our repository. (https://docs.gitlab.com/ee/gitlab-basics/add-merge-request.html)
**The main branch is our development branch where all the work happens.**
## Merge request workflow in detail
- Create a new branch or fork the main branch of the project (Please follow the guidlines below of naming branch and commits)
- Make a merge request to merge your changes into the main branch
- We use the Gitlab merge request workflow to review your contribution
- Only merge requests with a working CI can be merged
- Only merge requests with at least one code reviewer of the core team can be merged
- Only merge requests which are signed-off can be merged
- Merge Requests may be refused if they don't follow the rules below.
**Never ever just push something directly to the main branch!**
## Naming guidelines & code style
### Create a branch
- Branches should get named by this pattern: `username/name-your-changes`.
*That means for example: "alice/fix-this-bug".*
- Use [Conventional Commits](https://www.conventionalcommits.org/)
### File structure:
- File names must be `snake_case`.
- Directories need to be lowercase.
### Code style:
- We recommend using Android Studio or VS Code for coding
- Follow the common Dart style in: https://dart.dev/guides/language/effective-dart/style
- Format the code with `flutter format lib` - otherwise the CI will fail
### Code quality
- Don't repeat yourself! Use local variables, functions, classes.
- Don't mix UI and business logic in the same environment.
- Write tests for new classes, functions and widgets.
- Keep it simple stupid: https://en.wikipedia.org/wiki/KISS_principle
- Describe all of your classes, methods and attributes using **dartdoc** comments. Read this for more information: https://dart.dev/guides/language/effective-dart/documentation
- Don't write functions to create new widgets. Write classes!
- Don't insert unlocalized strings!
- Use Dart extensions to extend class functionality instead of writing wrapper classes!
- Don't mix functions which changes the state of something (functions with a return type of `void` or `Future<void>`) and functional programming which doesn't.
## Sign off
In order to have a concrete record that your contribution is intentional and you agree to license it under the same terms as the project's license, we've adopted the same lightweight approach that [the Linux Kernel](https://www.kernel.org/doc/Documentation/SubmittingPatches), [Docker](https://github.com/docker/docker/blob/master/CONTRIBUTING.md), and many other projects use: the [**DCO - Developer Certificate of Origin**](http://developercertificate.org/). This is a simple declaration that you wrote the contribution or otherwise have the right to contribute it to Matrix:
```
Developer Certificate of Origin
Version 1.1
Copyright (C) 2004, 2006 The Linux Foundation and its contributors.
660 York Street, Suite 102,
San Francisco, CA 94110 USA
Everyone is permitted to copy and distribute verbatim copies of this
license document, but changing it is not allowed.
Developer's Certificate of Origin 1.1
By making a contribution to this project, I certify that:
(a) The contribution was created in whole or in part by me and I
have the right to submit it under the open source license
indicated in the file; or
(b) The contribution is based upon previous work that, to the best
of my knowledge, is covered under an appropriate open source
license and I have the right under that license to submit that
work with modifications, whether created in whole or in part
by me, under the same open source license (unless I am
permitted to submit under a different license), as indicated
in the file; or
(c) The contribution was provided directly to me by some other
person who certified (a), (b) or (c) and I have not modified
it.
(d) I understand and agree that this project and the contribution
are public and that a record of the contribution (including all
personal information I submit with it, including my sign-off) is
maintained indefinitely and may be redistributed consistent with
this project or the open source license(s) involved.
```
If you agree to this for your contribution, then all that's needed is to include the line in your commit or merge request comment:
`Signed-off-by: Your Name <your@email.example.org>`
We accept contributions under a legally identifiable name, such as your name on government documentation or common-law names (names claimed by legitimate usage or repute). Unfortunately, we cannot accept anonymous contributions at this time.
Git allows you to add this signoff automatically when using the `-s` flag to `git commit`, which uses the name and email set in your `user.name` and `user.email` git configs.
If you forgot to sign off your commits before making your pull request and are on Git 2.17+ you can mass signoff using rebase:
`git rebase --signoff origin/main`

661
LICENSE Normal file
View file

@ -0,0 +1,661 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
famedlySDK
Copyright (C) 2019 famedly
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<http://www.gnu.org/licenses/>.

74
README.md Normal file
View file

@ -0,0 +1,74 @@
# Matrix SDK
Matrix (matrix.org) SDK written in dart.
## Native libraries
For E2EE, libolm must be provided.
Additionally, OpenSSL (libcrypto) must be provided on native platforms for E2EE.
For flutter apps you can easily import it with the [flutter_olm](https://pub.dev/packages/flutter_olm) and the [flutter_openssl_crypto](https://pub.dev/packages/flutter_openssl_crypto) packages.
## How to use this
1. Import the sdk
```yaml
matrix: <latest-version>
# Optional:
flutter_olm: <latest-version>
flutter_openssl_crypto: <latest-version>
```
```dart
import 'package:matrix/matrix.dart';
```
2. Create a new client:
```dart
final client = Client("HappyChat");
```
The SDK works better with a database. Otherwise it has no persistence. For this you need to provide a databaseBuilder like this:
```dart
final client = Client(
"HappyChat",
databaseBuilder: (Client client) async {
await Hive.init('/path/to/your/storage');
final db = FamedlySdkHiveDatabase(client.clientName);
await db.open();
return db;
},
);
```
3. Connect to a Matrix Homeserver and listen to the streams:
```dart
client.onLoginStateChanged.stream.listen((bool loginState){
print("LoginState: ${loginState.toString()}");
});
client.onEvent.stream.listen((EventUpdate eventUpdate){
print("New event update!");
});
client.onRoomUpdate.stream.listen((RoomUpdate eventUpdate){
print("New room update!");
});
await client.checkHomeserver("https://yourhomeserver.abc");
await client.login(
identifier: AuthenticationUserIdentifier(user: 'alice'),
password: '123456',
);
```
4. Send a message to a Room:
```dart
await client.getRoomById('your_room_id').sendTextEvent('Hello world');
```

50
analysis_options.yaml Normal file
View file

@ -0,0 +1,50 @@
include: package:pedantic/analysis_options.yaml
linter:
rules:
- camel_case_types
- avoid_print
- constant_identifier_names
- prefer_final_locals
- prefer_final_in_for_each
analyzer:
errors:
todo: ignore
exclude:
- example/main.dart
# needed until crypto packages upgrade
- lib/src/database/database.g.dart
plugins:
# Show code metrics in IDE
# - dart_code_metrics
dart_code_metrics:
metrics:
cyclomatic-complexity: 20
number-of-arguments: 4
maximum-nesting-level: 5
source-lines-of-code: 50
# This is still unstable, so handle with care
maintainability-index: 40
metrics-exclude:
- test/**
rules:
#- newline-before-return
- no-boolean-literal-compare
- no-empty-block
#- prefer-trailing-comma
- prefer-conditional-expressions
- no-equal-arguments
- no-equal-then-else
- no-magic-number:
severity: style # too noisy otherwise atm
- avoid-late-keyword:
severity: style # too noisy otherwise atm
- avoid-non-null-assertion:
severity: style # too noisy otherwise atm
- avoid-unused-parameters
- binary-expression-operand-order
anti-patterns:
- long-method
- long-parameter-list

6
build.yaml Normal file
View file

@ -0,0 +1,6 @@
targets:
$default:
builders:
moor_generator:
options:
generate_connect_constructor: true

377
example/main.dart Normal file
View file

@ -0,0 +1,377 @@
import 'package:flutter/material.dart';
import 'package:matrix/matrix.dart';
import 'package:path_provider/path_provider.dart';
import 'package:provider/provider.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
final client = Client(
'Matrix Example Chat',
databaseBuilder: (_) async {
final dir = await getApplicationSupportDirectory();
final db = FluffyBoxDatabase('matrix_example_chat', dir.path);
await db.open();
return db;
},
);
await client.init();
runApp(MatrixExampleChat(client: client));
}
class MatrixExampleChat extends StatelessWidget {
final Client client;
const MatrixExampleChat({required this.client, Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Matrix Example Chat',
builder: (context, child) => Provider<Client>(
create: (context) => client,
child: child,
),
home: client.isLogged() ? const RoomListPage() : const LoginPage(),
);
}
}
class LoginPage extends StatefulWidget {
const LoginPage({Key? key}) : super(key: key);
@override
_LoginPageState createState() => _LoginPageState();
}
class _LoginPageState extends State<LoginPage> {
final TextEditingController _homeserverTextField = TextEditingController(
text: 'matrix.org',
);
final TextEditingController _usernameTextField = TextEditingController();
final TextEditingController _passwordTextField = TextEditingController();
bool _loading = false;
void _login() async {
setState(() {
_loading = true;
});
try {
final client = Provider.of<Client>(context, listen: false);
await client
.checkHomeserver(Uri.https(_homeserverTextField.text.trim(), ''));
await client.login(
LoginType.mLoginPassword,
password: _passwordTextField.text,
identifier: AuthenticationUserIdentifier(user: _usernameTextField.text),
);
Navigator.of(context).pushAndRemoveUntil(
MaterialPageRoute(builder: (_) => const RoomListPage()),
(route) => false,
);
} catch (e) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(e.toString()),
),
);
setState(() {
_loading = false;
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Login')),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
children: [
TextField(
controller: _homeserverTextField,
readOnly: _loading,
autocorrect: false,
decoration: const InputDecoration(
prefixText: 'https://',
border: OutlineInputBorder(),
labelText: 'Homeserver',
),
),
const SizedBox(height: 16),
TextField(
controller: _usernameTextField,
readOnly: _loading,
autocorrect: false,
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: 'Username',
),
),
const SizedBox(height: 16),
TextField(
controller: _passwordTextField,
readOnly: _loading,
autocorrect: false,
obscureText: true,
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: 'Password',
),
),
const SizedBox(height: 16),
SizedBox(
width: double.infinity,
child: ElevatedButton(
onPressed: _loading ? null : _login,
child: _loading
? const LinearProgressIndicator()
: const Text('Login'),
),
),
],
),
),
);
}
}
class RoomListPage extends StatefulWidget {
const RoomListPage({Key? key}) : super(key: key);
@override
_RoomListPageState createState() => _RoomListPageState();
}
class _RoomListPageState extends State<RoomListPage> {
void _logout() async {
final client = Provider.of<Client>(context, listen: false);
await client.logout();
Navigator.of(context).pushAndRemoveUntil(
MaterialPageRoute(builder: (_) => const LoginPage()),
(route) => false,
);
}
void _join(Room room) async {
if (room.membership != Membership.join) {
await room.join();
}
Navigator.of(context).push(
MaterialPageRoute(
builder: (_) => RoomPage(room: room),
),
);
}
@override
Widget build(BuildContext context) {
final client = Provider.of<Client>(context, listen: false);
return Scaffold(
appBar: AppBar(
title: const Text('Chats'),
actions: [
IconButton(
icon: const Icon(Icons.logout),
onPressed: _logout,
),
],
),
body: StreamBuilder(
stream: client.onSync.stream,
builder: (context, _) => ListView.builder(
itemCount: client.rooms.length,
itemBuilder: (context, i) => ListTile(
leading: CircleAvatar(
foregroundImage: client.rooms[i].avatar == null
? null
: NetworkImage(client.rooms[i].avatar!
.getThumbnail(
client,
width: 56,
height: 56,
)
.toString()),
),
title: Row(
children: [
Expanded(child: Text(client.rooms[i].displayname)),
if (client.rooms[i].notificationCount > 0)
Material(
borderRadius: BorderRadius.circular(99),
color: Colors.red,
child: Padding(
padding: const EdgeInsets.all(2.0),
child:
Text(client.rooms[i].notificationCount.toString()),
))
],
),
subtitle: Text(
client.rooms[i].lastEvent?.body ?? 'No messages',
maxLines: 1,
),
onTap: () => _join(client.rooms[i]),
),
),
),
);
}
}
class RoomPage extends StatefulWidget {
final Room room;
const RoomPage({required this.room, Key? key}) : super(key: key);
@override
_RoomPageState createState() => _RoomPageState();
}
class _RoomPageState extends State<RoomPage> {
late final Future<Timeline> _timelineFuture;
final GlobalKey<AnimatedListState> _listKey = GlobalKey<AnimatedListState>();
int _count = 0;
@override
void initState() {
_timelineFuture = widget.room.getTimeline(onChange: (i) {
print('on change! $i');
_listKey.currentState?.setState(() {});
}, onInsert: (i) {
print('on insert! $i');
_listKey.currentState?.insertItem(i);
_count++;
}, onRemove: (i) {
print('On remove $i');
_count--;
_listKey.currentState?.removeItem(i, (_, __) => const ListTile());
}, onHistoryReceived: (count) {
print('On History Received $count');
for (var i = 0; i < count; i++) {
_listKey.currentState?.insertItem(_count + i);
}
_count += count;
});
super.initState();
}
final TextEditingController _sendController = TextEditingController();
void _send() {
widget.room.sendTextEvent(_sendController.text.trim());
_sendController.clear();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.room.displayname),
),
body: SafeArea(
child: Column(
children: [
Expanded(
child: FutureBuilder<Timeline>(
future: _timelineFuture,
builder: (context, snapshot) {
final timeline = snapshot.data;
if (timeline == null) {
return const Center(
child: CircularProgressIndicator.adaptive(),
);
}
_count = timeline.events.length;
return Column(
children: [
Center(
child: TextButton(
onPressed: timeline.requestHistory,
child: const Text('Load more...')),
),
const Divider(height: 1),
Expanded(
child: AnimatedList(
key: _listKey,
reverse: true,
initialItemCount: timeline.events.length,
itemBuilder: (context, i, animation) => timeline
.events[i].relationshipEventId !=
null
? Container()
: ScaleTransition(
scale: animation,
child: Opacity(
opacity: timeline.events[i].status.isSent
? 1
: 0.5,
child: ListTile(
leading: CircleAvatar(
foregroundImage: timeline.events[i]
.sender.avatarUrl ==
null
? null
: NetworkImage(timeline
.events[i].sender.avatarUrl!
.getThumbnail(
widget.room.client,
width: 56,
height: 56,
)
.toString()),
),
title: Row(
children: [
Expanded(
child: Text(timeline
.events[i].sender
.calcDisplayname()),
),
Text(
timeline.events[i].originServerTs
.toIso8601String(),
style:
const TextStyle(fontSize: 10),
),
],
),
subtitle: Text(timeline.events[i]
.getDisplayEvent(timeline)
.body),
),
),
),
),
),
],
);
},
),
),
const Divider(height: 1),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16.0),
child: Row(
children: [
Expanded(
child: TextField(
controller: _sendController,
decoration: const InputDecoration(
hintText: 'Send message',
),
)),
IconButton(
icon: const Icon(Icons.send_outlined),
onPressed: _send,
),
],
),
),
],
),
),
);
}
}

12
home/index.html Normal file
View file

@ -0,0 +1,12 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Famedly Matrix SDK</title>
</head>
<body>
<a href="api/index.html">API</a>
<a href="doc/index.html">Documentation</a>
</body>
</html>

26
lib/encryption.dart Normal file
View file

@ -0,0 +1,26 @@
/*
* Famedly Matrix SDK
* Copyright (C) 2020, 2021 Famedly GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/// Matrix SDK encryption specific extension
library encryption;
export 'encryption/encryption.dart';
export 'encryption/key_manager.dart';
export 'encryption/ssss.dart';
export 'encryption/utils/key_verification.dart';
export 'encryption/utils/bootstrap.dart';

View file

@ -0,0 +1,210 @@
/*
* Famedly Matrix SDK
* Copyright (C) 2020, 2021 Famedly GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import 'dart:typed_data';
import 'package:matrix/encryption/utils/base64_unpadded.dart';
import 'package:olm/olm.dart' as olm;
import '../matrix.dart';
import 'encryption.dart';
import 'ssss.dart';
class CrossSigning {
final Encryption encryption;
Client get client => encryption.client;
CrossSigning(this.encryption) {
encryption.ssss.setValidator(EventTypes.CrossSigningSelfSigning,
(String secret) async {
final keyObj = olm.PkSigning();
try {
return keyObj.init_with_seed(base64decodeUnpadded(secret)) ==
client.userDeviceKeys[client.userID]!.selfSigningKey!.ed25519Key;
} catch (_) {
return false;
} finally {
keyObj.free();
}
});
encryption.ssss.setValidator(EventTypes.CrossSigningUserSigning,
(String secret) async {
final keyObj = olm.PkSigning();
try {
return keyObj.init_with_seed(base64decodeUnpadded(secret)) ==
client.userDeviceKeys[client.userID]!.userSigningKey!.ed25519Key;
} catch (_) {
return false;
} finally {
keyObj.free();
}
});
}
bool get enabled =>
encryption.ssss.isSecret(EventTypes.CrossSigningSelfSigning) &&
encryption.ssss.isSecret(EventTypes.CrossSigningUserSigning) &&
encryption.ssss.isSecret(EventTypes.CrossSigningMasterKey);
Future<bool> isCached() async {
if (!enabled) {
return false;
}
return (await encryption.ssss
.getCached(EventTypes.CrossSigningSelfSigning)) !=
null &&
(await encryption.ssss.getCached(EventTypes.CrossSigningUserSigning)) !=
null;
}
Future<void> selfSign(
{String? passphrase,
String? recoveryKey,
String? keyOrPassphrase,
OpenSSSS? openSsss}) async {
var handle = openSsss;
if (handle == null) {
handle = encryption.ssss.open(EventTypes.CrossSigningMasterKey);
await handle.unlock(
passphrase: passphrase,
recoveryKey: recoveryKey,
keyOrPassphrase: keyOrPassphrase,
postUnlock: false,
);
await handle.maybeCacheAll();
}
final masterPrivateKey = base64decodeUnpadded(
await handle.getStored(EventTypes.CrossSigningMasterKey));
final keyObj = olm.PkSigning();
String? masterPubkey;
try {
masterPubkey = keyObj.init_with_seed(masterPrivateKey);
} catch (e) {
masterPubkey = null;
} finally {
keyObj.free();
}
final userDeviceKeys =
client.userDeviceKeys[client.userID]?.deviceKeys[client.deviceID];
if (masterPubkey == null || userDeviceKeys == null) {
throw Exception('Master or user keys not found');
}
final masterKey = client.userDeviceKeys[client.userID]?.masterKey;
if (masterKey == null || masterKey.ed25519Key != masterPubkey) {
throw Exception('Master pubkey key doesn\'t match');
}
// master key is valid, set it to verified
await masterKey.setVerified(true, false);
// and now sign both our own key and our master key
await sign([
masterKey,
userDeviceKeys,
]);
}
bool signable(List<SignableKey> keys) => keys.any((key) =>
key is CrossSigningKey && key.usage.contains('master') ||
key is DeviceKeys &&
key.userId == client.userID &&
key.identifier != client.deviceID);
Future<void> sign(List<SignableKey> keys) async {
final signedKeys = <MatrixSignableKey>[];
Uint8List? selfSigningKey;
Uint8List? userSigningKey;
final userKeys = client.userDeviceKeys[client.userID];
if (userKeys == null) {
throw Exception('[sign] keys are not in cache but sign was called');
}
final addSignature =
(SignableKey key, SignableKey signedWith, String signature) {
final signedKey = key.cloneForSigning();
((signedKey.signatures ??=
<String, Map<String, String>>{})[signedWith.userId] ??=
<String, String>{})['ed25519:${signedWith.identifier}'] = signature;
signedKeys.add(signedKey);
};
for (final key in keys) {
if (key.userId == client.userID) {
// we are singing a key of ourself
if (key is CrossSigningKey) {
if (key.usage.contains('master')) {
// okay, we'll sign our own master key
final signature =
encryption.olmManager.signString(key.signingContent);
addSignature(key, userKeys.deviceKeys[client.deviceID]!, signature);
}
// we don't care about signing other cross-signing keys
} else {
// okay, we'll sign a device key with our self signing key
selfSigningKey ??= base64decodeUnpadded(await encryption.ssss
.getCached(EventTypes.CrossSigningSelfSigning) ??
'');
if (selfSigningKey.isNotEmpty) {
final signature = _sign(key.signingContent, selfSigningKey);
addSignature(key, userKeys.selfSigningKey!, signature);
}
}
} else if (key is CrossSigningKey && key.usage.contains('master')) {
// we are signing someone elses master key
userSigningKey ??= base64decodeUnpadded(await encryption.ssss
.getCached(EventTypes.CrossSigningUserSigning) ??
'');
if (userSigningKey.isNotEmpty) {
final signature = _sign(key.signingContent, userSigningKey);
addSignature(key, userKeys.userSigningKey!, signature);
}
}
}
if (signedKeys.isNotEmpty) {
// post our new keys!
final payload = <String, Map<String, Map<String, dynamic>>>{};
for (final key in signedKeys) {
if (key.identifier == null ||
key.signatures == null ||
key.signatures?.isEmpty != false) {
continue;
}
if (!payload.containsKey(key.userId)) {
payload[key.userId] = <String, Map<String, dynamic>>{};
}
if (payload[key.userId]?[key.identifier]?['signatures'] != null) {
// we need to merge signature objects
payload[key.userId]![key.identifier]!['signatures']
.addAll(key.signatures);
} else {
// we can just add signatures
payload[key.userId]![key.identifier!] = key.toJson();
}
}
await client.uploadCrossSigningSignatures(payload);
}
}
String _sign(String canonicalJson, Uint8List key) {
final keyObj = olm.PkSigning();
try {
keyObj.init_with_seed(key);
return keyObj.sign(canonicalJson);
} finally {
keyObj.free();
}
}
}

View file

@ -0,0 +1,455 @@
/*
* Famedly Matrix SDK
* Copyright (C) 2019, 2020, 2021 Famedly GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import 'dart:convert';
import 'dart:async';
import 'package:olm/olm.dart' as olm;
import '../matrix.dart';
import '../src/utils/run_in_root.dart';
import 'cross_signing.dart';
import 'key_manager.dart';
import 'key_verification_manager.dart';
import 'olm_manager.dart';
import 'ssss.dart';
import 'utils/bootstrap.dart';
class Encryption {
final Client client;
final bool debug;
bool get enabled => olmManager.enabled;
/// Returns the base64 encoded keys to store them in a store.
/// This String should **never** leave the device!
String? get pickledOlmAccount => olmManager.pickledOlmAccount;
String? get fingerprintKey => olmManager.fingerprintKey;
String? get identityKey => olmManager.identityKey;
late KeyManager keyManager;
late OlmManager olmManager;
late KeyVerificationManager keyVerificationManager;
late CrossSigning crossSigning;
late SSSS ssss;
Encryption({
required this.client,
this.debug = false,
}) {
ssss = SSSS(this);
keyManager = KeyManager(this);
olmManager = OlmManager(this);
keyVerificationManager = KeyVerificationManager(this);
crossSigning = CrossSigning(this);
}
// initial login passes null to init a new olm account
Future<void> init(String? olmAccount) async {
await olmManager.init(olmAccount);
_backgroundTasksRunning = true;
_backgroundTasks(); // start the background tasks
}
bool isMinOlmVersion(int major, int minor, int patch) {
try {
final version = olm.get_library_version();
return version[0] > major ||
(version[0] == major &&
(version[1] > minor ||
(version[1] == minor && version[2] >= patch)));
} catch (_) {
return false;
}
}
Bootstrap bootstrap({void Function()? onUpdate}) => Bootstrap(
encryption: this,
onUpdate: onUpdate,
);
void handleDeviceOneTimeKeysCount(
Map<String, int>? countJson, List<String>? unusedFallbackKeyTypes) {
runInRoot(() => olmManager.handleDeviceOneTimeKeysCount(
countJson, unusedFallbackKeyTypes));
}
void onSync() {
keyVerificationManager.cleanup();
}
Future<void> handleToDeviceEvent(ToDeviceEvent event) async {
if (event.type == EventTypes.RoomKey) {
// a new room key. We need to handle this asap, before other
// events in /sync are handled
await keyManager.handleToDeviceEvent(event);
}
if ([EventTypes.RoomKeyRequest, EventTypes.ForwardedRoomKey]
.contains(event.type)) {
// "just" room key request things. We don't need these asap, so we handle
// them in the background
// ignore: unawaited_futures
runInRoot(() => keyManager.handleToDeviceEvent(event));
}
if (event.type == EventTypes.Dummy) {
// the previous device just had to create a new olm session, due to olm session
// corruption. We want to try to send it the last message we just sent it, if possible
// ignore: unawaited_futures
runInRoot(() => olmManager.handleToDeviceEvent(event));
}
if (event.type.startsWith('m.key.verification.')) {
// some key verification event. No need to handle it now, we can easily
// do this in the background
// ignore: unawaited_futures
runInRoot(() => keyVerificationManager.handleToDeviceEvent(event));
}
if (event.type.startsWith('m.secret.')) {
// some ssss thing. We can do this in the background
// ignore: unawaited_futures
runInRoot(() => ssss.handleToDeviceEvent(event));
}
if (event.sender == client.userID) {
// maybe we need to re-try SSSS secrets
// ignore: unawaited_futures
runInRoot(() => ssss.periodicallyRequestMissingCache());
}
}
Future<void> handleEventUpdate(EventUpdate update) async {
if (update.type == EventUpdateType.ephemeral ||
update.type == EventUpdateType.history) {
return;
}
if (update.content['type'].startsWith('m.key.verification.') ||
(update.content['type'] == EventTypes.Message &&
(update.content['content']['msgtype'] is String) &&
update.content['content']['msgtype']
.startsWith('m.key.verification.'))) {
// "just" key verification, no need to do this in sync
// ignore: unawaited_futures
runInRoot(() => keyVerificationManager.handleEventUpdate(update));
}
if (update.content['sender'] == client.userID &&
update.content['unsigned']?['transaction_id'] == null) {
// maybe we need to re-try SSSS secrets
// ignore: unawaited_futures
runInRoot(() => ssss.periodicallyRequestMissingCache());
}
}
Future<ToDeviceEvent> decryptToDeviceEvent(ToDeviceEvent event) async {
try {
return await olmManager.decryptToDeviceEvent(event);
} catch (e, s) {
Logs().w(
'[LibOlm] Could not decrypt to device event from ${event.sender} with content: ${event.content}',
e,
s);
client.onEncryptionError.add(
SdkError(
exception: e is Exception ? e : Exception(e),
stackTrace: s,
),
);
return event;
}
}
Event decryptRoomEventSync(String roomId, Event event) {
final content = event.parsedRoomEncryptedContent;
if (event.type != EventTypes.Encrypted ||
content.ciphertextMegolm == null) {
return event;
}
Map<String, dynamic> decryptedPayload;
var canRequestSession = false;
try {
if (content.algorithm != AlgorithmTypes.megolmV1AesSha2) {
throw DecryptException(DecryptException.unknownAlgorithm);
}
final sessionId = content.sessionId;
final senderKey = content.senderKey;
if (sessionId == null) {
throw DecryptException(DecryptException.unknownSession);
}
final inboundGroupSession =
keyManager.getInboundGroupSession(roomId, sessionId, senderKey);
if (!(inboundGroupSession?.isValid ?? false)) {
canRequestSession = true;
throw DecryptException(DecryptException.unknownSession);
}
// decrypt errors here may mean we have a bad session key - others might have a better one
canRequestSession = true;
final decryptResult = inboundGroupSession!.inboundGroupSession!
.decrypt(content.ciphertextMegolm!);
canRequestSession = false;
// we can't have the key be an int, else json-serializing will fail, thus we need it to be a string
final messageIndexKey = 'key-' + decryptResult.message_index.toString();
final messageIndexValue = event.eventId +
'|' +
event.originServerTs.millisecondsSinceEpoch.toString();
final haveIndex =
inboundGroupSession.indexes.containsKey(messageIndexKey);
if (haveIndex &&
inboundGroupSession.indexes[messageIndexKey] != messageIndexValue) {
Logs().e('[Decrypt] Could not decrypt due to a corrupted session.');
throw DecryptException(DecryptException.channelCorrupted);
}
inboundGroupSession.indexes[messageIndexKey] = messageIndexValue;
if (!haveIndex) {
// now we persist the udpated indexes into the database.
// the entry should always exist. In the case it doesn't, the following
// line *could* throw an error. As that is a future, though, and we call
// it un-awaited here, nothing happens, which is exactly the result we want
client.database?.updateInboundGroupSessionIndexes(
json.encode(inboundGroupSession.indexes), roomId, sessionId);
}
decryptedPayload = json.decode(decryptResult.plaintext);
} catch (exception) {
// alright, if this was actually by our own outbound group session, we might as well clear it
if (exception.toString() != DecryptException.unknownSession &&
(keyManager
.getOutboundGroupSession(roomId)
?.outboundGroupSession
?.session_id() ??
'') ==
content.sessionId) {
runInRoot(() =>
keyManager.clearOrUseOutboundGroupSession(roomId, wipe: true));
}
if (canRequestSession) {
decryptedPayload = {
'content': event.content,
'type': EventTypes.Encrypted,
};
decryptedPayload['content']['body'] = exception.toString();
decryptedPayload['content']['msgtype'] = MessageTypes.BadEncrypted;
decryptedPayload['content']['can_request_session'] = true;
} else {
decryptedPayload = {
'content': <String, dynamic>{
'msgtype': MessageTypes.BadEncrypted,
'body': exception.toString(),
},
'type': EventTypes.Encrypted,
};
}
}
if (event.content['m.relates_to'] != null) {
decryptedPayload['content']['m.relates_to'] =
event.content['m.relates_to'];
}
return Event(
content: decryptedPayload['content'],
type: decryptedPayload['type'],
senderId: event.senderId,
eventId: event.eventId,
room: event.room,
originServerTs: event.originServerTs,
unsigned: event.unsigned,
stateKey: event.stateKey,
prevContent: event.prevContent,
status: event.status,
);
}
Future<Event> decryptRoomEvent(String roomId, Event event,
{bool store = false,
EventUpdateType updateType = EventUpdateType.timeline}) async {
if (event.type != EventTypes.Encrypted) {
return event;
}
final content = event.parsedRoomEncryptedContent;
final sessionId = content.sessionId;
try {
if (client.database != null &&
sessionId != null &&
!(keyManager
.getInboundGroupSession(
roomId,
sessionId,
content.senderKey,
)
?.isValid ??
false)) {
await keyManager.loadInboundGroupSession(
roomId,
sessionId,
content.senderKey,
);
}
event = decryptRoomEventSync(roomId, event);
if (event.type == EventTypes.Encrypted &&
event.content['can_request_session'] == true &&
sessionId != null) {
keyManager.maybeAutoRequest(
roomId,
sessionId,
content.senderKey,
);
}
if (event.type != EventTypes.Encrypted && store) {
if (updateType != EventUpdateType.history) {
event.room.setState(event);
}
await client.database?.storeEventUpdate(
EventUpdate(
content: event.toJson(),
roomID: roomId,
type: updateType,
),
client,
);
}
return event;
} catch (e, s) {
Logs().e('[Decrypt] Could not decrpyt event', e, s);
return event;
}
}
/// Encrypts the given json payload and creates a send-ready m.room.encrypted
/// payload. This will create a new outgoingGroupSession if necessary.
Future<Map<String, dynamic>> encryptGroupMessagePayload(
String roomId, Map<String, dynamic> payload,
{String type = EventTypes.Message}) async {
final Map<String, dynamic>? mRelatesTo = payload.remove('m.relates_to');
// Events which only contain a m.relates_to like reactions don't need to
// be encrypted.
if (payload.isEmpty && mRelatesTo != null) {
return {'m.relates_to': mRelatesTo};
}
final room = client.getRoomById(roomId);
if (room == null || !room.encrypted || !enabled) {
return payload;
}
if (room.encryptionAlgorithm != AlgorithmTypes.megolmV1AesSha2) {
throw ('Unknown encryption algorithm');
}
if (keyManager.getOutboundGroupSession(roomId)?.isValid != true) {
await keyManager.loadOutboundGroupSession(roomId);
}
await keyManager.clearOrUseOutboundGroupSession(roomId);
if (keyManager.getOutboundGroupSession(roomId)?.isValid != true) {
await keyManager.createOutboundGroupSession(roomId);
}
final sess = keyManager.getOutboundGroupSession(roomId);
if (sess?.isValid != true) {
throw ('Unable to create new outbound group session');
}
// we clone the payload as we do not want to remove 'm.relates_to' from the
// original payload passed into this function
payload = payload.copy();
final payloadContent = {
'content': payload,
'type': type,
'room_id': roomId,
};
final encryptedPayload = <String, dynamic>{
'algorithm': AlgorithmTypes.megolmV1AesSha2,
'ciphertext':
sess!.outboundGroupSession!.encrypt(json.encode(payloadContent)),
'device_id': client.deviceID,
'sender_key': identityKey,
'session_id': sess.outboundGroupSession!.session_id(),
if (mRelatesTo != null) 'm.relates_to': mRelatesTo,
};
await keyManager.storeOutboundGroupSession(roomId, sess);
return encryptedPayload;
}
Future<Map<String, dynamic>> encryptToDeviceMessage(
List<DeviceKeys> deviceKeys,
String type,
Map<String, dynamic> payload) async {
return await olmManager.encryptToDeviceMessage(deviceKeys, type, payload);
}
Future<void> autovalidateMasterOwnKey() async {
// check if we can set our own master key as verified, if it isn't yet
final userId = client.userID;
final masterKey = client.userDeviceKeys[userId]?.masterKey;
if (client.database != null &&
masterKey != null &&
userId != null &&
!masterKey.directVerified &&
masterKey.hasValidSignatureChain(onlyValidateUserIds: {userId})) {
await masterKey.setVerified(true);
}
}
// this method is responsible for all background tasks, such as uploading online key backups
bool _backgroundTasksRunning = true;
void _backgroundTasks() {
if (!_backgroundTasksRunning || !client.isLogged()) {
return;
}
keyManager.backgroundTasks();
// autovalidateMasterOwnKey();
if (_backgroundTasksRunning) {
Timer(Duration(seconds: 10), _backgroundTasks);
}
}
void dispose() {
_backgroundTasksRunning = false;
keyManager.dispose();
olmManager.dispose();
keyVerificationManager.dispose();
}
}
class DecryptException implements Exception {
String cause;
String? libolmMessage;
DecryptException(this.cause, [this.libolmMessage]);
@override
String toString() =>
cause + (libolmMessage != null ? ': $libolmMessage' : '');
static const String notEnabled = 'Encryption is not enabled in your client.';
static const String unknownAlgorithm = 'Unknown encryption algorithm.';
static const String unknownSession =
'The sender has not sent us the session key.';
static const String channelCorrupted =
'The secure channel with the sender was corrupted.';
static const String unableToDecryptWithAnyOlmSession =
'Unable to decrypt with any existing OLM session';
static const String senderDoesntMatch =
"Message was decrypted but sender doesn't match";
static const String recipientDoesntMatch =
"Message was decrypted but recipient doesn't match";
static const String ownFingerprintDoesntMatch =
"Message was decrypted but own fingerprint Key doesn't match";
static const String isntSentForThisDevice =
"The message isn't sent for this device";
static const String unknownMessageType = 'Unknown message type';
static const String decryptionFailed = 'Decryption failed';
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,148 @@
/*
* Famedly Matrix SDK
* Copyright (C) 2020, 2021 Famedly GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import '../matrix.dart';
import 'encryption.dart';
import 'utils/key_verification.dart';
class KeyVerificationManager {
final Encryption encryption;
Client get client => encryption.client;
KeyVerificationManager(this.encryption);
final Map<String, KeyVerification> _requests = {};
Future<void> cleanup() async {
final Set entriesToDispose = <String>{};
for (final entry in _requests.entries) {
var dispose = entry.value.canceled ||
entry.value.state == KeyVerificationState.done ||
entry.value.state == KeyVerificationState.error;
if (!dispose) {
dispose = !(await entry.value.verifyActivity());
}
if (dispose) {
entry.value.dispose();
entriesToDispose.add(entry.key);
}
}
entriesToDispose.forEach(_requests.remove);
}
void addRequest(KeyVerification request) {
if (request.transactionId == null) {
return;
}
_requests[request.transactionId!] = request;
}
KeyVerification? getRequest(String requestId) => _requests[requestId];
Future<void> handleToDeviceEvent(ToDeviceEvent event) async {
if (!event.type.startsWith('m.key.verification.') ||
client.verificationMethods.isEmpty) {
return;
}
// we have key verification going on!
final transactionId = KeyVerification.getTransactionId(event.content);
if (transactionId == null) {
return; // TODO: send cancel with unknown transaction id
}
final request = _requests[transactionId];
if (request != null) {
// make sure that new requests can't come from ourself
if (!{EventTypes.KeyVerificationRequest}.contains(event.type)) {
await request.handlePayload(event.type, event.content);
}
} else {
if (!{EventTypes.KeyVerificationRequest, EventTypes.KeyVerificationStart}
.contains(event.type)) {
return; // we can only start on these
}
final newKeyRequest =
KeyVerification(encryption: encryption, userId: event.sender);
await newKeyRequest.handlePayload(event.type, event.content);
if (newKeyRequest.state != KeyVerificationState.askAccept) {
// okay, something went wrong (unknown transaction id?), just dispose it
newKeyRequest.dispose();
} else {
_requests[transactionId] = newKeyRequest;
client.onKeyVerificationRequest.add(newKeyRequest);
}
}
}
Future<void> handleEventUpdate(EventUpdate update) async {
final event = update.content;
final type = event['type'].startsWith('m.key.verification.')
? event['type']
: event['content']['msgtype'];
if (type == null ||
!type.startsWith('m.key.verification.') ||
client.verificationMethods.isEmpty) {
return;
}
if (type == EventTypes.KeyVerificationRequest) {
event['content']['timestamp'] = event['origin_server_ts'];
}
final transactionId =
KeyVerification.getTransactionId(event['content']) ?? event['event_id'];
final req = _requests[transactionId];
if (req != null) {
final otherDeviceId = event['content']['from_device'];
if (event['sender'] != client.userID) {
await req.handlePayload(type, event['content'], event['event_id']);
} else if (event['sender'] == client.userID &&
otherDeviceId != null &&
otherDeviceId != client.deviceID) {
// okay, another of our devices answered
req.otherDeviceAccepted();
req.dispose();
_requests.remove(transactionId);
}
} else if (event['sender'] != client.userID) {
if (!{EventTypes.KeyVerificationRequest, EventTypes.KeyVerificationStart}
.contains(type)) {
return; // we can only start on these
}
final room = client.getRoomById(update.roomID) ??
Room(id: update.roomID, client: client);
final newKeyRequest = KeyVerification(
encryption: encryption, userId: event['sender'], room: room);
await newKeyRequest.handlePayload(
type, event['content'], event['event_id']);
if (newKeyRequest.state != KeyVerificationState.askAccept) {
// something went wrong, let's just dispose the request
newKeyRequest.dispose();
} else {
// new request! Let's notify it and stuff
_requests[transactionId] = newKeyRequest;
client.onKeyVerificationRequest.add(newKeyRequest);
}
}
}
void dispose() {
for (final req in _requests.values) {
req.dispose();
}
}
}

View file

@ -0,0 +1,690 @@
/*
* Famedly Matrix SDK
* Copyright (C) 2019, 2020, 2021 Famedly GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import 'dart:convert';
import 'package:canonical_json/canonical_json.dart';
import 'package:collection/collection.dart';
import 'package:matrix/matrix.dart';
import 'package:olm/olm.dart' as olm;
import '../encryption/utils/json_signature_check_extension.dart';
import '../src/utils/run_in_root.dart';
import 'encryption.dart';
import 'utils/olm_session.dart';
class OlmManager {
final Encryption encryption;
Client get client => encryption.client;
olm.Account? _olmAccount;
/// Returns the base64 encoded keys to store them in a store.
/// This String should **never** leave the device!
String? get pickledOlmAccount =>
enabled ? _olmAccount!.pickle(client.userID!) : null;
String? get fingerprintKey =>
enabled ? json.decode(_olmAccount!.identity_keys())['ed25519'] : null;
String? get identityKey =>
enabled ? json.decode(_olmAccount!.identity_keys())['curve25519'] : null;
bool get enabled => _olmAccount != null;
OlmManager(this.encryption);
/// A map from Curve25519 identity keys to existing olm sessions.
Map<String, List<OlmSession>> get olmSessions => _olmSessions;
final Map<String, List<OlmSession>> _olmSessions = {};
// NOTE(Nico): On initial login we pass null to create a new account
Future<void> init(String? olmAccount) async {
if (olmAccount == null) {
try {
await olm.init();
_olmAccount = olm.Account();
_olmAccount!.create();
if (!await uploadKeys(uploadDeviceKeys: true, updateDatabase: false)) {
throw ('Upload key failed');
}
} catch (_) {
_olmAccount?.free();
_olmAccount = null;
rethrow;
}
} else {
try {
await olm.init();
_olmAccount = olm.Account();
_olmAccount!.unpickle(client.userID!, olmAccount);
} catch (_) {
_olmAccount?.free();
_olmAccount = null;
rethrow;
}
}
}
/// Adds a signature to this json from this olm account and returns the signed
/// json.
Map<String, dynamic> signJson(Map<String, dynamic> payload) {
if (!enabled) throw ('Encryption is disabled');
final Map<String, dynamic>? unsigned = payload['unsigned'];
final Map<String, dynamic>? signatures = payload['signatures'];
payload.remove('unsigned');
payload.remove('signatures');
final canonical = canonicalJson.encode(payload);
final signature = _olmAccount!.sign(String.fromCharCodes(canonical));
if (signatures != null) {
payload['signatures'] = signatures;
} else {
payload['signatures'] = <String, dynamic>{};
}
if (!payload['signatures'].containsKey(client.userID)) {
payload['signatures'][client.userID] = <String, dynamic>{};
}
payload['signatures'][client.userID]['ed25519:${client.deviceID}'] =
signature;
if (unsigned != null) {
payload['unsigned'] = unsigned;
}
return payload;
}
String signString(String s) {
return _olmAccount!.sign(s);
}
/// Checks the signature of a signed json object.
@deprecated
bool checkJsonSignature(String key, Map<String, dynamic> signedJson,
String userId, String deviceId) {
if (!enabled) throw ('Encryption is disabled');
final Map<String, dynamic>? signatures = signedJson['signatures'];
if (signatures == null || !signatures.containsKey(userId)) return false;
signedJson.remove('unsigned');
signedJson.remove('signatures');
if (!signatures[userId].containsKey('ed25519:$deviceId')) return false;
final String signature = signatures[userId]['ed25519:$deviceId'];
final canonical = canonicalJson.encode(signedJson);
final message = String.fromCharCodes(canonical);
var isValid = false;
final olmutil = olm.Utility();
try {
olmutil.ed25519_verify(key, message, signature);
isValid = true;
} catch (e, s) {
isValid = false;
Logs().w('[LibOlm] Signature check failed', e, s);
} finally {
olmutil.free();
}
return isValid;
}
bool _uploadKeysLock = false;
/// Generates new one time keys, signs everything and upload it to the server.
Future<bool> uploadKeys({
bool uploadDeviceKeys = false,
int? oldKeyCount = 0,
bool updateDatabase = true,
bool? unusedFallbackKey = false,
}) async {
final _olmAccount = this._olmAccount;
if (_olmAccount == null) {
return true;
}
if (_uploadKeysLock) {
return false;
}
_uploadKeysLock = true;
try {
final signedOneTimeKeys = <String, dynamic>{};
int? uploadedOneTimeKeysCount;
if (oldKeyCount != null) {
// check if we have OTKs that still need uploading. If we do, we don't try to generate new ones,
// instead we try to upload the old ones first
final oldOTKsNeedingUpload = json
.decode(_olmAccount.one_time_keys())['curve25519']
.entries
.length as int;
// generate one-time keys
// we generate 2/3rds of max, so that other keys people may still have can
// still be used
final oneTimeKeysCount =
(_olmAccount.max_number_of_one_time_keys() * 2 / 3).floor() -
oldKeyCount -
oldOTKsNeedingUpload;
if (oneTimeKeysCount > 0) {
_olmAccount.generate_one_time_keys(oneTimeKeysCount);
}
uploadedOneTimeKeysCount = oneTimeKeysCount + oldOTKsNeedingUpload;
final Map<String, dynamic> oneTimeKeys =
json.decode(_olmAccount.one_time_keys());
// now sign all the one-time keys
for (final entry in oneTimeKeys['curve25519'].entries) {
final key = entry.key;
final value = entry.value;
signedOneTimeKeys['signed_curve25519:$key'] = signJson({
'key': value,
});
}
}
final signedFallbackKeys = <String, dynamic>{};
if (encryption.isMinOlmVersion(3, 2, 0) && unusedFallbackKey == false) {
// we don't have an unused fallback key uploaded....so let's change that!
_olmAccount.generate_fallback_key();
final fallbackKey = json.decode(_olmAccount.fallback_key());
// now sign all the fallback keys
for (final entry in fallbackKey['curve25519'].entries) {
final key = entry.key;
final value = entry.value;
signedFallbackKeys['signed_curve25519:$key'] = signJson({
'key': value,
'fallback': true,
});
}
}
// and now generate the payload to upload
final keysContent = <String, dynamic>{
if (uploadDeviceKeys)
'device_keys': {
'user_id': client.userID,
'device_id': client.deviceID,
'algorithms': [
AlgorithmTypes.olmV1Curve25519AesSha2,
AlgorithmTypes.megolmV1AesSha2
],
'keys': <String, dynamic>{},
},
};
if (uploadDeviceKeys) {
final Map<String, dynamic> keys =
json.decode(_olmAccount.identity_keys());
for (final entry in keys.entries) {
final algorithm = entry.key;
final value = entry.value;
keysContent['device_keys']['keys']['$algorithm:${client.deviceID}'] =
value;
}
keysContent['device_keys'] =
signJson(keysContent['device_keys'] as Map<String, dynamic>);
}
// we save the generated OTKs into the database.
// in case the app gets killed during upload or the upload fails due to bad network
// we can still re-try later
if (updateDatabase) {
await client.database?.updateClientKeys(pickledOlmAccount!);
}
// Workaround: Make sure we stop if we got logged out in the meantime.
if (!client.isLogged()) return true;
final response = await client.uploadKeys(
deviceKeys: uploadDeviceKeys
? MatrixDeviceKeys.fromJson(keysContent['device_keys'])
: null,
oneTimeKeys: signedOneTimeKeys,
fallbackKeys: signedFallbackKeys,
);
// mark the OTKs as published and save that to datbase
_olmAccount.mark_keys_as_published();
if (updateDatabase) {
await client.database?.updateClientKeys(pickledOlmAccount!);
}
return (uploadedOneTimeKeysCount != null &&
response['signed_curve25519'] == uploadedOneTimeKeysCount) ||
uploadedOneTimeKeysCount == null;
} finally {
_uploadKeysLock = false;
}
}
void handleDeviceOneTimeKeysCount(
Map<String, int>? countJson, List<String>? unusedFallbackKeyTypes) {
if (!enabled) {
return;
}
final haveFallbackKeys = encryption.isMinOlmVersion(3, 2, 0);
// Check if there are at least half of max_number_of_one_time_keys left on the server
// and generate and upload more if not.
// If the server did not send us a count, assume it is 0
final keyCount = countJson?.tryGet<int>('signed_curve25519') ?? 0;
// If the server does not support fallback keys, it will not tell us about them.
// If the server supports them but has no key, upload a new one.
var unusedFallbackKey = true;
if (unusedFallbackKeyTypes?.contains('signed_curve25519') == false) {
unusedFallbackKey = false;
}
// fixup accidental too many uploads. We delete only one of them so that the server has time to update the counts and because we will get rate limited anyway.
if (keyCount > _olmAccount!.max_number_of_one_time_keys()) {
final requestingKeysFrom = {
client.userID!: {client.deviceID!: 'signed_curve25519'}
};
client.claimKeys(requestingKeysFrom, timeout: 10000);
}
// Only upload keys if they are less than half of the max or we have no unused fallback key
if (keyCount < (_olmAccount!.max_number_of_one_time_keys() / 2) ||
!unusedFallbackKey) {
uploadKeys(
oldKeyCount: keyCount < (_olmAccount!.max_number_of_one_time_keys() / 2)
? keyCount
: null,
unusedFallbackKey: haveFallbackKeys ? unusedFallbackKey : null,
);
}
}
Future<void> storeOlmSession(OlmSession session) async {
if (session.sessionId == null || session.pickledSession == null) {
return;
}
_olmSessions[session.identityKey] ??= <OlmSession>[];
final ix = _olmSessions[session.identityKey]!
.indexWhere((s) => s.sessionId == session.sessionId);
if (ix == -1) {
// add a new session
_olmSessions[session.identityKey]!.add(session);
} else {
// update an existing session
_olmSessions[session.identityKey]![ix] = session;
}
await client.database?.storeOlmSession(
session.identityKey,
session.sessionId!,
session.pickledSession!,
session.lastReceived?.millisecondsSinceEpoch ??
DateTime.now().millisecondsSinceEpoch);
}
ToDeviceEvent _decryptToDeviceEvent(ToDeviceEvent event) {
if (event.type != EventTypes.Encrypted) {
return event;
}
final content = event.parsedRoomEncryptedContent;
if (content.algorithm != AlgorithmTypes.olmV1Curve25519AesSha2) {
throw DecryptException(DecryptException.unknownAlgorithm);
}
if (content.ciphertextOlm == null ||
!content.ciphertextOlm!.containsKey(identityKey)) {
throw DecryptException(DecryptException.isntSentForThisDevice);
}
String? plaintext;
final senderKey = content.senderKey;
final body = content.ciphertextOlm![identityKey]!.body;
final type = content.ciphertextOlm![identityKey]!.type;
if (type != 0 && type != 1) {
throw DecryptException(DecryptException.unknownMessageType);
}
final device = client.userDeviceKeys[event.sender]?.deviceKeys.values
.firstWhereOrNull((d) => d.curve25519Key == senderKey);
final existingSessions = olmSessions[senderKey];
final updateSessionUsage = ([OlmSession? session]) => runInRoot(() async {
if (session != null) {
session.lastReceived = DateTime.now();
await storeOlmSession(session);
}
if (device != null) {
device.lastActive = DateTime.now();
await client.database?.setLastActiveUserDeviceKey(
device.lastActive.millisecondsSinceEpoch,
device.userId,
device.deviceId!);
}
});
if (existingSessions != null) {
for (final session in existingSessions) {
if (session.session == null) {
continue;
}
if (type == 0 && session.session!.matches_inbound(body)) {
try {
plaintext = session.session!.decrypt(type, body);
} catch (e) {
// The message was encrypted during this session, but is unable to decrypt
throw DecryptException(
DecryptException.decryptionFailed, e.toString());
}
updateSessionUsage(session);
break;
} else if (type == 1) {
try {
plaintext = session.session!.decrypt(type, body);
updateSessionUsage(session);
break;
} catch (_) {
plaintext = null;
}
}
}
}
if (plaintext == null && type != 0) {
throw DecryptException(DecryptException.unableToDecryptWithAnyOlmSession);
}
if (plaintext == null) {
final newSession = olm.Session();
try {
newSession.create_inbound_from(_olmAccount!, senderKey, body);
_olmAccount!.remove_one_time_keys(newSession);
client.database?.updateClientKeys(pickledOlmAccount!);
plaintext = newSession.decrypt(type, body);
runInRoot(() => storeOlmSession(OlmSession(
key: client.userID!,
identityKey: senderKey,
sessionId: newSession.session_id(),
session: newSession,
lastReceived: DateTime.now(),
)));
updateSessionUsage();
} catch (e) {
newSession.free();
throw DecryptException(DecryptException.decryptionFailed, e.toString());
}
}
final Map<String, dynamic> plainContent = json.decode(plaintext);
if (plainContent['sender'] != event.sender) {
throw DecryptException(DecryptException.senderDoesntMatch);
}
if (plainContent['recipient'] != client.userID) {
throw DecryptException(DecryptException.recipientDoesntMatch);
}
if (plainContent['recipient_keys'] is Map &&
plainContent['recipient_keys']['ed25519'] is String &&
plainContent['recipient_keys']['ed25519'] != fingerprintKey) {
throw DecryptException(DecryptException.ownFingerprintDoesntMatch);
}
return ToDeviceEvent(
content: plainContent['content'],
encryptedContent: event.content,
type: plainContent['type'],
sender: event.sender,
);
}
Future<List<OlmSession>> getOlmSessionsFromDatabase(String senderKey) async {
final olmSessions =
await client.database?.getOlmSessions(senderKey, client.userID!);
return olmSessions?.where((sess) => sess.isValid).toList() ?? [];
}
Future<void> getOlmSessionsForDevicesFromDatabase(
List<String> senderKeys) async {
final rows = await client.database?.getOlmSessionsForDevices(
senderKeys,
client.userID!,
);
final res = <String, List<OlmSession>>{};
for (final sess in rows ?? []) {
res[sess.identityKey] ??= <OlmSession>[];
if (sess.isValid) {
res[sess.identityKey]!.add(sess);
}
}
for (final entry in res.entries) {
_olmSessions[entry.key] = entry.value;
}
}
Future<List<OlmSession>> getOlmSessions(String senderKey,
{bool getFromDb = true}) async {
var sess = olmSessions[senderKey];
if ((getFromDb) && (sess == null || sess.isEmpty)) {
final sessions = await getOlmSessionsFromDatabase(senderKey);
if (sessions.isEmpty) {
return [];
}
sess = _olmSessions[senderKey] = sessions;
}
if (sess == null) {
return [];
}
sess.sort((a, b) => a.lastReceived == b.lastReceived
? (a.sessionId ?? '').compareTo(b.sessionId ?? '')
: (b.lastReceived ?? DateTime(0))
.compareTo(a.lastReceived ?? DateTime(0)));
return sess;
}
final Map<String, DateTime> _restoredOlmSessionsTime = {};
Future<void> restoreOlmSession(String userId, String senderKey) async {
if (!client.userDeviceKeys.containsKey(userId)) {
return;
}
final device = client.userDeviceKeys[userId]!.deviceKeys.values
.firstWhereOrNull((d) => d.curve25519Key == senderKey);
if (device == null) {
return;
}
// per device only one olm session per hour should be restored
final mapKey = '$userId;$senderKey';
if (_restoredOlmSessionsTime.containsKey(mapKey) &&
DateTime.now()
.subtract(Duration(hours: 1))
.isBefore(_restoredOlmSessionsTime[mapKey]!)) {
return;
}
_restoredOlmSessionsTime[mapKey] = DateTime.now();
await startOutgoingOlmSessions([device]);
await client.sendToDeviceEncrypted([device], EventTypes.Dummy, {});
}
Future<ToDeviceEvent> decryptToDeviceEvent(ToDeviceEvent event) async {
if (event.type != EventTypes.Encrypted) {
return event;
}
final senderKey = event.parsedRoomEncryptedContent.senderKey;
final loadFromDb = () async {
final sessions = await getOlmSessions(senderKey);
return sessions.isNotEmpty;
};
if (!_olmSessions.containsKey(senderKey)) {
await loadFromDb();
}
try {
event = _decryptToDeviceEvent(event);
if (event.type != EventTypes.Encrypted || !(await loadFromDb())) {
return event;
}
// retry to decrypt!
return _decryptToDeviceEvent(event);
} catch (_) {
// okay, the thing errored while decrypting. It is safe to assume that the olm session is corrupt and we should generate a new one
// ignore: unawaited_futures
runInRoot(() => restoreOlmSession(event.senderId, senderKey));
rethrow;
}
}
Future<void> startOutgoingOlmSessions(List<DeviceKeys> deviceKeys) async {
Logs().v(
'[OlmManager] Starting session with ${deviceKeys.length} devices...');
final requestingKeysFrom = <String, Map<String, String>>{};
for (final device in deviceKeys) {
if (requestingKeysFrom[device.userId] == null) {
requestingKeysFrom[device.userId] = {};
}
requestingKeysFrom[device.userId]![device.deviceId!] =
'signed_curve25519';
}
final response = await client.claimKeys(requestingKeysFrom, timeout: 10000);
for (final userKeysEntry in response.oneTimeKeys.entries) {
final userId = userKeysEntry.key;
for (final deviceKeysEntry in userKeysEntry.value.entries) {
final deviceId = deviceKeysEntry.key;
final fingerprintKey =
client.userDeviceKeys[userId]!.deviceKeys[deviceId]!.ed25519Key;
final identityKey =
client.userDeviceKeys[userId]!.deviceKeys[deviceId]!.curve25519Key;
for (final Map<String, dynamic> deviceKey
in deviceKeysEntry.value.values) {
if (fingerprintKey == null ||
identityKey == null ||
!deviceKey.checkJsonSignature(fingerprintKey, userId, deviceId)) {
continue;
}
Logs().v('[OlmManager] Starting session with $userId:$deviceId');
final session = olm.Session();
try {
session.create_outbound(
_olmAccount!, identityKey, deviceKey['key']);
await storeOlmSession(OlmSession(
key: client.userID!,
identityKey: identityKey,
sessionId: session.session_id(),
session: session,
lastReceived:
DateTime.now(), // we want to use a newly created session
));
} catch (e, s) {
session.free();
Logs()
.e('[LibOlm] Could not create new outbound olm session', e, s);
}
}
}
}
}
Future<Map<String, dynamic>> encryptToDeviceMessagePayload(
DeviceKeys device, String type, Map<String, dynamic> payload,
{bool getFromDb = true}) async {
final sess =
await getOlmSessions(device.curve25519Key!, getFromDb: getFromDb);
if (sess.isEmpty) {
throw ('No olm session found for ${device.userId}:${device.deviceId}');
}
final fullPayload = {
'type': type,
'content': payload,
'sender': client.userID,
'keys': {'ed25519': fingerprintKey},
'recipient': device.userId,
'recipient_keys': {'ed25519': device.ed25519Key},
};
final encryptResult = sess.first.session!.encrypt(json.encode(fullPayload));
await storeOlmSession(sess.first);
if (client.database != null) {
// ignore: unawaited_futures
runInRoot(() => client.database?.setLastSentMessageUserDeviceKey(
json.encode({
'type': type,
'content': payload,
}),
device.userId,
device.deviceId!));
}
final encryptedBody = <String, dynamic>{
'algorithm': AlgorithmTypes.olmV1Curve25519AesSha2,
'sender_key': identityKey,
'ciphertext': <String, dynamic>{},
};
encryptedBody['ciphertext'][device.curve25519Key] = {
'type': encryptResult.type,
'body': encryptResult.body,
};
return encryptedBody;
}
Future<Map<String, dynamic>> encryptToDeviceMessage(
List<DeviceKeys> deviceKeys,
String type,
Map<String, dynamic> payload) async {
final data = <String, Map<String, Map<String, dynamic>>>{};
// first check if any of our sessions we want to encrypt for are in the database
if (client.database != null) {
await getOlmSessionsForDevicesFromDatabase(
deviceKeys.map((d) => d.curve25519Key!).toList());
}
final deviceKeysWithoutSession = List<DeviceKeys>.from(deviceKeys);
deviceKeysWithoutSession.removeWhere((DeviceKeys deviceKeys) =>
olmSessions[deviceKeys.curve25519Key]?.isNotEmpty ?? false);
if (deviceKeysWithoutSession.isNotEmpty) {
await startOutgoingOlmSessions(deviceKeysWithoutSession);
}
for (final device in deviceKeys) {
final userData = data[device.userId] ??= {};
try {
userData[device.deviceId!] = await encryptToDeviceMessagePayload(
device, type, payload,
getFromDb: false);
} catch (e, s) {
Logs().w('[LibOlm] Error encrypting to-device event', e, s);
continue;
}
}
return data;
}
Future<void> handleToDeviceEvent(ToDeviceEvent event) async {
if (event.type == EventTypes.Dummy) {
// We receive dan encrypted m.dummy. This means that the other end was not able to
// decrypt our last message. So, we re-send it.
final encryptedContent = event.encryptedContent;
if (encryptedContent == null || client.database == null) {
return;
}
final device = client.getUserDeviceKeysByCurve25519Key(
encryptedContent.tryGet<String>('sender_key') ?? '');
if (device == null) {
return; // device not found
}
Logs().v(
'[OlmManager] Device ${device.userId}:${device.deviceId} generated a new olm session, replaying last sent message...');
final lastSentMessageRes = await client.database
?.getLastSentMessageUserDeviceKey(device.userId, device.deviceId!);
if (lastSentMessageRes == null ||
lastSentMessageRes.isEmpty ||
lastSentMessageRes.first.isEmpty) {
return;
}
final lastSentMessage = json.decode(lastSentMessageRes.first);
// We do *not* want to re-play m.dummy events, as they hold no value except of saying
// what olm session is the most recent one. In fact, if we *do* replay them, then
// we can easily land in an infinite ping-pong trap!
if (lastSentMessage['type'] != EventTypes.Dummy) {
// okay, time to send the message!
await client.sendToDeviceEncrypted(
[device], lastSentMessage['type'], lastSentMessage['content']);
}
}
}
void dispose() {
for (final sessions in olmSessions.values) {
for (final sess in sessions) {
sess.dispose();
}
}
_olmAccount?.free();
_olmAccount = null;
}
}

755
lib/encryption/ssss.dart Normal file
View file

@ -0,0 +1,755 @@
/*
* Famedly Matrix SDK
* Copyright (C) 2020, 2021 Famedly GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import 'dart:async';
import 'dart:convert';
import 'dart:core';
import 'dart:typed_data';
import 'package:base58check/base58.dart';
import 'package:crypto/crypto.dart';
import 'package:collection/collection.dart';
import 'package:matrix/encryption/utils/base64_unpadded.dart';
import '../matrix.dart';
import '../src/utils/crypto/crypto.dart' as uc;
import '../src/utils/run_in_root.dart';
import 'encryption.dart';
import 'utils/ssss_cache.dart';
const cacheTypes = <String>{
EventTypes.CrossSigningSelfSigning,
EventTypes.CrossSigningUserSigning,
EventTypes.MegolmBackup,
};
const zeroStr =
'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00';
const base58Alphabet =
'123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
const base58 = Base58Codec(base58Alphabet);
const olmRecoveryKeyPrefix = [0x8B, 0x01];
const ssssKeyLength = 32;
const pbkdf2DefaultIterations = 500000;
const pbkdf2SaltLength = 64;
/// SSSS: **S**ecure **S**ecret **S**torage and **S**haring
/// Read more about SSSS at:
/// https://matrix.org/docs/guides/implementing-more-advanced-e-2-ee-features-such-as-cross-signing#3-implementing-ssss
class SSSS {
final Encryption encryption;
Client get client => encryption.client;
final pendingShareRequests = <String, _ShareRequest>{};
final _validators = <String, FutureOr<bool> Function(String)>{};
final _cacheCallbacks = <String, FutureOr<void> Function(String)>{};
final Map<String, SSSSCache> _cache = <String, SSSSCache>{};
SSSS(this.encryption);
// for testing
Future<void> clearCache() async {
await client.database?.clearSSSSCache();
_cache.clear();
}
static _DerivedKeys deriveKeys(Uint8List key, String name) {
final zerosalt = Uint8List(8);
final prk = Hmac(sha256, zerosalt).convert(key);
final b = Uint8List(1);
b[0] = 1;
final aesKey = Hmac(sha256, prk.bytes).convert(utf8.encode(name) + b);
b[0] = 2;
final hmacKey =
Hmac(sha256, prk.bytes).convert(aesKey.bytes + utf8.encode(name) + b);
return _DerivedKeys(
aesKey: Uint8List.fromList(aesKey.bytes),
hmacKey: Uint8List.fromList(hmacKey.bytes));
}
static Future<_Encrypted> encryptAes(String data, Uint8List key, String name,
[String? ivStr]) async {
Uint8List iv;
if (ivStr != null) {
iv = base64decodeUnpadded(ivStr);
} else {
iv = Uint8List.fromList(uc.secureRandomBytes(16));
}
// we need to clear bit 63 of the IV
iv[8] &= 0x7f;
final keys = deriveKeys(key, name);
final plain = Uint8List.fromList(utf8.encode(data));
final ciphertext = await uc.aesCtr.encrypt(plain, keys.aesKey, iv);
final hmac = Hmac(sha256, keys.hmacKey).convert(ciphertext);
return _Encrypted(
iv: base64.encode(iv),
ciphertext: base64.encode(ciphertext),
mac: base64.encode(hmac.bytes));
}
static Future<String> decryptAes(
_Encrypted data, Uint8List key, String name) async {
final keys = deriveKeys(key, name);
final cipher = base64decodeUnpadded(data.ciphertext);
final hmac = base64
.encode(Hmac(sha256, keys.hmacKey).convert(cipher).bytes)
.replaceAll(RegExp(r'=+$'), '');
if (hmac != data.mac.replaceAll(RegExp(r'=+$'), '')) {
throw Exception('Bad MAC');
}
final decipher = await uc.aesCtr
.encrypt(cipher, keys.aesKey, base64decodeUnpadded(data.iv));
return String.fromCharCodes(decipher);
}
static Uint8List decodeRecoveryKey(String recoveryKey) {
final result = base58.decode(recoveryKey.replaceAll(RegExp(r'\s'), ''));
final parity = result.fold<int>(0, (a, b) => a ^ b);
if (parity != 0) {
throw Exception('Incorrect parity');
}
for (var i = 0; i < olmRecoveryKeyPrefix.length; i++) {
if (result[i] != olmRecoveryKeyPrefix[i]) {
throw Exception('Incorrect prefix');
}
}
if (result.length != olmRecoveryKeyPrefix.length + ssssKeyLength + 1) {
throw Exception('Incorrect length');
}
return Uint8List.fromList(result.sublist(olmRecoveryKeyPrefix.length,
olmRecoveryKeyPrefix.length + ssssKeyLength));
}
static String encodeRecoveryKey(Uint8List recoveryKey) {
final keyToEncode = <int>[...olmRecoveryKeyPrefix, ...recoveryKey];
final parity = keyToEncode.fold<int>(0, (a, b) => a ^ b);
keyToEncode.add(parity);
// base58-encode and add a space every four chars
return base58
.encode(keyToEncode)
.replaceAllMapped(RegExp(r'.{4}'), (s) => '${s.group(0)} ')
.trim();
}
static Future<Uint8List> keyFromPassphrase(
String passphrase, PassphraseInfo info) async {
if (info.algorithm != AlgorithmTypes.pbkdf2) {
throw Exception('Unknown algorithm');
}
if (info.iterations == null) {
throw Exception('Passphrase info without iterations');
}
if (info.salt == null) {
throw Exception('Passphrase info without salt');
}
return await uc.pbkdf2(
Uint8List.fromList(utf8.encode(passphrase)),
Uint8List.fromList(utf8.encode(info.salt!)),
uc.sha512,
info.iterations!,
info.bits ?? 256);
}
void setValidator(String type, FutureOr<bool> Function(String) validator) {
_validators[type] = validator;
}
void setCacheCallback(String type, FutureOr<void> Function(String) callback) {
_cacheCallbacks[type] = callback;
}
String? get defaultKeyId => client
.accountData[EventTypes.SecretStorageDefaultKey]
?.parsedSecretStorageDefaultKeyContent
.key;
Future<void> setDefaultKeyId(String keyId) async {
await client.setAccountData(
client.userID!,
EventTypes.SecretStorageDefaultKey,
SecretStorageDefaultKeyContent(key: keyId).toJson(),
);
}
SecretStorageKeyContent? getKey(String keyId) {
return client.accountData[EventTypes.secretStorageKey(keyId)]
?.parsedSecretStorageKeyContent;
}
bool isKeyValid(String keyId) =>
getKey(keyId)?.algorithm == AlgorithmTypes.secretStorageV1AesHmcSha2;
/// Creates a new secret storage key, optional encrypts it with [passphrase]
/// and stores it in the user's `accountData`.
Future<OpenSSSS> createKey([String? passphrase]) async {
Uint8List privateKey;
final content = SecretStorageKeyContent();
if (passphrase != null) {
// we need to derive the key off of the passphrase
content.passphrase = PassphraseInfo(
iterations: pbkdf2DefaultIterations,
salt: base64.encode(uc.secureRandomBytes(pbkdf2SaltLength)),
algorithm: AlgorithmTypes.pbkdf2,
bits: ssssKeyLength * 8,
);
privateKey = await client
.runInBackground(
_keyFromPassphrase,
_KeyFromPassphraseArgs(
passphrase: passphrase,
info: content.passphrase!,
),
)
.timeout(Duration(seconds: 10));
} else {
// we need to just generate a new key from scratch
privateKey = Uint8List.fromList(uc.secureRandomBytes(ssssKeyLength));
}
// now that we have the private key, let's create the iv and mac
final encrypted = await encryptAes(zeroStr, privateKey, '');
content.iv = encrypted.iv;
content.mac = encrypted.mac;
content.algorithm = AlgorithmTypes.secretStorageV1AesHmcSha2;
const keyidByteLength = 24;
// make sure we generate a unique key id
final keyId = () sync* {
for (;;) {
yield base64.encode(uc.secureRandomBytes(keyidByteLength));
}
}()
.firstWhere((keyId) => getKey(keyId) == null);
final accountDataType = EventTypes.secretStorageKey(keyId);
// noooow we set the account data
final waitForAccountData = client.onSync.stream.firstWhere((syncUpdate) =>
syncUpdate.accountData != null &&
syncUpdate.accountData!
.any((accountData) => accountData.type == accountDataType));
await client.setAccountData(
client.userID!, accountDataType, content.toJson());
await waitForAccountData;
final key = open(keyId);
await key.setPrivateKey(privateKey);
return key;
}
Future<bool> checkKey(Uint8List key, SecretStorageKeyContent info) async {
if (info.algorithm == AlgorithmTypes.secretStorageV1AesHmcSha2) {
if ((info.mac is String) && (info.iv is String)) {
final encrypted = await encryptAes(zeroStr, key, '', info.iv);
return info.mac!.replaceAll(RegExp(r'=+$'), '') ==
encrypted.mac.replaceAll(RegExp(r'=+$'), '');
} else {
// no real information about the key, assume it is valid
return true;
}
} else {
throw Exception('Unknown Algorithm');
}
}
bool isSecret(String type) =>
client.accountData[type] != null &&
client.accountData[type]!.content['encrypted'] is Map;
Future<String?> getCached(String type) async {
if (client.database == null) {
return null;
}
// check if it is still valid
final keys = keyIdsFromType(type);
if (keys == null) {
return null;
}
final isValid = (dbEntry) =>
keys.contains(dbEntry.keyId) &&
dbEntry.ciphertext != null &&
client.accountData[type]?.content['encrypted'][dbEntry.keyId]
['ciphertext'] ==
dbEntry.ciphertext;
if (_cache.containsKey(type) && isValid(_cache[type])) {
return _cache[type]?.content;
}
final ret = await client.database?.getSSSSCache(type);
if (ret == null) {
return null;
}
if (isValid(ret)) {
_cache[type] = ret;
return ret.content;
}
return null;
}
Future<String> getStored(String type, String keyId, Uint8List key) async {
final secretInfo = client.accountData[type];
if (secretInfo == null) {
throw Exception('Not found');
}
if (!(secretInfo.content['encrypted'] is Map)) {
throw Exception('Content is not encrypted');
}
if (!(secretInfo.content['encrypted'][keyId] is Map)) {
throw Exception('Wrong / unknown key');
}
final enc = secretInfo.content['encrypted'][keyId];
final encryptInfo = _Encrypted(
iv: enc['iv'], ciphertext: enc['ciphertext'], mac: enc['mac']);
final decrypted = await decryptAes(encryptInfo, key, type);
final db = client.database;
if (cacheTypes.contains(type) && db != null) {
// cache the thing
await db.storeSSSSCache(type, keyId, enc['ciphertext'], decrypted);
if (_cacheCallbacks.containsKey(type) && await getCached(type) == null) {
_cacheCallbacks[type]!(decrypted);
}
}
return decrypted;
}
Future<void> store(String type, String secret, String keyId, Uint8List key,
{bool add = false}) async {
final encrypted = await encryptAes(secret, key, type);
Map<String, dynamic>? content;
if (add && client.accountData[type] != null) {
content = client.accountData[type]!.content.copy();
if (!(content['encrypted'] is Map)) {
content['encrypted'] = <String, dynamic>{};
}
}
content ??= <String, dynamic>{
'encrypted': <String, dynamic>{},
};
content['encrypted'][keyId] = <String, dynamic>{
'iv': encrypted.iv,
'ciphertext': encrypted.ciphertext,
'mac': encrypted.mac,
};
// store the thing in your account data
await client.setAccountData(client.userID!, type, content);
final db = client.database;
if (cacheTypes.contains(type) && db != null) {
// cache the thing
await db.storeSSSSCache(type, keyId, encrypted.ciphertext, secret);
if (_cacheCallbacks.containsKey(type) && await getCached(type) == null) {
_cacheCallbacks[type]!(secret);
}
}
}
Future<void> validateAndStripOtherKeys(
String type, String secret, String keyId, Uint8List key) async {
if (await getStored(type, keyId, key) != secret) {
throw Exception('Secrets do not match up!');
}
// now remove all other keys
final content = client.accountData[type]?.content.copy();
if (content == null) {
throw Exception('Key has no content!');
}
final otherKeys =
Set<String>.from(content['encrypted'].keys.where((k) => k != keyId));
content['encrypted'].removeWhere((k, v) => otherKeys.contains(k));
// yes, we are paranoid...
if (await getStored(type, keyId, key) != secret) {
throw Exception('Secrets do not match up!');
}
// store the thing in your account data
await client.setAccountData(client.userID!, type, content);
if (cacheTypes.contains(type)) {
// cache the thing
await client.database?.storeSSSSCache(
type, keyId, content['encrypted'][keyId]['ciphertext'], secret);
}
}
Future<void> maybeCacheAll(String keyId, Uint8List key) async {
for (final type in cacheTypes) {
final secret = await getCached(type);
if (secret == null) {
try {
await getStored(type, keyId, key);
} catch (_) {
// the entry wasn't stored, just ignore it
}
}
}
}
Future<void> maybeRequestAll([List<DeviceKeys>? devices]) async {
for (final type in cacheTypes) {
if (keyIdsFromType(type) != null) {
final secret = await getCached(type);
if (secret == null) {
await request(type, devices);
}
}
}
}
Future<void> request(String type, [List<DeviceKeys>? devices]) async {
// only send to own, verified devices
Logs().i('[SSSS] Requesting type $type...');
if (devices == null || devices.isEmpty) {
if (!client.userDeviceKeys.containsKey(client.userID)) {
Logs().w('[SSSS] User does not have any devices');
return;
}
devices =
client.userDeviceKeys[client.userID]!.deviceKeys.values.toList();
}
devices.removeWhere((DeviceKeys d) =>
d.userId != client.userID ||
!d.verified ||
d.blocked ||
d.deviceId == client.deviceID);
if (devices.isEmpty) {
Logs().w('[SSSS] No devices');
return;
}
final requestId = client.generateUniqueTransactionId();
final request = _ShareRequest(
requestId: requestId,
type: type,
devices: devices,
);
pendingShareRequests[requestId] = request;
await client.sendToDeviceEncrypted(devices, EventTypes.SecretRequest, {
'action': 'request',
'requesting_device_id': client.deviceID,
'request_id': requestId,
'name': type,
});
}
DateTime? _lastCacheRequest;
bool _isPeriodicallyRequestingMissingCache = false;
Future<void> periodicallyRequestMissingCache() async {
if (_isPeriodicallyRequestingMissingCache ||
(_lastCacheRequest != null &&
DateTime.now()
.subtract(Duration(minutes: 15))
.isBefore(_lastCacheRequest!)) ||
client.isUnknownSession) {
// we are already requesting right now or we attempted to within the last 15 min
return;
}
_lastCacheRequest = DateTime.now();
_isPeriodicallyRequestingMissingCache = true;
try {
await maybeRequestAll();
} finally {
_isPeriodicallyRequestingMissingCache = false;
}
}
Future<void> handleToDeviceEvent(ToDeviceEvent event) async {
if (event.type == EventTypes.SecretRequest) {
// got a request to share a secret
Logs().i('[SSSS] Received sharing request...');
if (event.sender != client.userID ||
!client.userDeviceKeys.containsKey(client.userID)) {
Logs().i('[SSSS] Not sent by us');
return; // we aren't asking for it ourselves, so ignore
}
if (event.content['action'] != 'request') {
Logs().i('[SSSS] it is actually a cancelation');
return; // not actually requesting, so ignore
}
final device = client.userDeviceKeys[client.userID]!
.deviceKeys[event.content['requesting_device_id']];
if (device == null || !device.verified || device.blocked) {
Logs().i('[SSSS] Unknown / unverified devices, ignoring');
return; // nope....unknown or untrusted device
}
// alright, all seems fine...let's check if we actually have the secret they are asking for
final type = event.content['name'];
final secret = await getCached(type);
if (secret == null) {
Logs()
.i('[SSSS] We don\'t have the secret for $type ourself, ignoring');
return; // seems like we don't have this, either
}
// okay, all checks out...time to share this secret!
Logs().i('[SSSS] Replying with secret for $type');
await client.sendToDeviceEncrypted(
[device],
EventTypes.SecretSend,
{
'request_id': event.content['request_id'],
'secret': secret,
});
} else if (event.type == EventTypes.SecretSend) {
// receiving a secret we asked for
Logs().i('[SSSS] Received shared secret...');
final encryptedContent = event.encryptedContent;
if (event.sender != client.userID ||
!pendingShareRequests.containsKey(event.content['request_id']) ||
encryptedContent == null) {
Logs().i('[SSSS] Not by us or unknown request');
return; // we have no idea what we just received
}
final request = pendingShareRequests[event.content['request_id']]!;
// alright, as we received a known request id, let's check if the sender is valid
final device = request.devices.firstWhereOrNull((d) =>
d.userId == event.sender &&
d.curve25519Key == encryptedContent['sender_key']);
if (device == null) {
Logs().i('[SSSS] Someone else replied?');
return; // someone replied whom we didn't send the share request to
}
final secret = event.content['secret'];
if (!(event.content['secret'] is String)) {
Logs().i('[SSSS] Secret wasn\'t a string');
return; // the secret wasn't a string....wut?
}
// let's validate if the secret is, well, valid
if (_validators.containsKey(request.type) &&
!(await _validators[request.type]!(secret))) {
Logs().i('[SSSS] The received secret was invalid');
return; // didn't pass the validator
}
pendingShareRequests.remove(request.requestId);
if (request.start.add(Duration(minutes: 15)).isBefore(DateTime.now())) {
Logs().i('[SSSS] Request is too far in the past');
return; // our request is more than 15min in the past...better not trust it anymore
}
Logs().i('[SSSS] Secret for type ${request.type} is ok, storing it');
final db = client.database;
if (db != null) {
final keyId = keyIdFromType(request.type);
if (keyId != null) {
final ciphertext = client.accountData[request.type]!
.content['encrypted'][keyId]['ciphertext'];
await db.storeSSSSCache(request.type, keyId, ciphertext, secret);
if (_cacheCallbacks.containsKey(request.type)) {
_cacheCallbacks[request.type]!(secret);
}
}
}
}
}
Set<String>? keyIdsFromType(String type) {
final data = client.accountData[type];
if (data == null) {
return null;
}
if (data.content['encrypted'] is Map) {
return data.content['encrypted'].keys.toSet();
}
return null;
}
String? keyIdFromType(String type) {
final keys = keyIdsFromType(type);
if (keys == null || keys.isEmpty) {
return null;
}
if (keys.contains(defaultKeyId)) {
return defaultKeyId;
}
return keys.first;
}
OpenSSSS open([String? identifier]) {
identifier ??= defaultKeyId;
if (identifier == null) {
throw Exception('Dont know what to open');
}
final keyToOpen = keyIdFromType(identifier) ?? identifier;
final key = getKey(keyToOpen);
if (key == null) {
throw Exception('Unknown key to open');
}
return OpenSSSS(ssss: this, keyId: keyToOpen, keyData: key);
}
}
class _ShareRequest {
final String requestId;
final String type;
final List<DeviceKeys> devices;
final DateTime start;
_ShareRequest(
{required this.requestId, required this.type, required this.devices})
: start = DateTime.now();
}
class _Encrypted {
final String iv;
final String ciphertext;
final String mac;
_Encrypted({required this.iv, required this.ciphertext, required this.mac});
}
class _DerivedKeys {
final Uint8List aesKey;
final Uint8List hmacKey;
_DerivedKeys({required this.aesKey, required this.hmacKey});
}
class OpenSSSS {
final SSSS ssss;
final String keyId;
final SecretStorageKeyContent keyData;
OpenSSSS({required this.ssss, required this.keyId, required this.keyData});
Uint8List? privateKey;
bool get isUnlocked => privateKey != null;
bool get hasPassphrase => keyData.passphrase != null;
String? get recoveryKey =>
isUnlocked ? SSSS.encodeRecoveryKey(privateKey!) : null;
Future<void> unlock(
{String? passphrase,
String? recoveryKey,
String? keyOrPassphrase,
bool postUnlock = true}) async {
if (keyOrPassphrase != null) {
try {
await unlock(recoveryKey: keyOrPassphrase, postUnlock: postUnlock);
} catch (_) {
if (hasPassphrase) {
await unlock(passphrase: keyOrPassphrase, postUnlock: postUnlock);
} else {
rethrow;
}
}
return;
} else if (passphrase != null) {
if (!hasPassphrase) {
throw Exception(
'Tried to unlock with passphrase while key does not have a passphrase');
}
privateKey = await ssss.client
.runInBackground(
_keyFromPassphrase,
_KeyFromPassphraseArgs(
passphrase: passphrase,
info: keyData.passphrase!,
),
)
.timeout(Duration(seconds: 10));
} else if (recoveryKey != null) {
privateKey = SSSS.decodeRecoveryKey(recoveryKey);
} else {
throw Exception('Nothing specified');
}
// verify the validity of the key
if (!await ssss.checkKey(privateKey!, keyData)) {
privateKey = null;
throw Exception('Inalid key');
}
if (postUnlock) {
await runInRoot(() => _postUnlock());
}
}
Future<void> setPrivateKey(Uint8List key) async {
if (!await ssss.checkKey(key, keyData)) {
throw Exception('Invalid key');
}
privateKey = key;
}
Future<String> getStored(String type) async {
final privateKey = this.privateKey;
if (privateKey == null) {
throw Exception('SSSS not unlocked');
}
return await ssss.getStored(type, keyId, privateKey);
}
Future<void> store(String type, String secret, {bool add = false}) async {
final privateKey = this.privateKey;
if (privateKey == null) {
throw Exception('SSSS not unlocked');
}
await ssss.store(type, secret, keyId, privateKey, add: add);
}
Future<void> validateAndStripOtherKeys(String type, String secret) async {
final privateKey = this.privateKey;
if (privateKey == null) {
throw Exception('SSSS not unlocked');
}
await ssss.validateAndStripOtherKeys(type, secret, keyId, privateKey);
}
Future<void> maybeCacheAll() async {
final privateKey = this.privateKey;
if (privateKey == null) {
throw Exception('SSSS not unlocked');
}
await ssss.maybeCacheAll(keyId, privateKey);
}
Future<void> _postUnlock() async {
// first try to cache all secrets that aren't cached yet
await maybeCacheAll();
// now try to self-sign
if (ssss.encryption.crossSigning.enabled &&
ssss.client.userDeviceKeys[ssss.client.userID]?.masterKey != null &&
(ssss
.keyIdsFromType(EventTypes.CrossSigningMasterKey)
?.contains(keyId) ??
false) &&
(ssss.client.isUnknownSession ||
ssss.client.userDeviceKeys[ssss.client.userID]!.masterKey
?.directVerified !=
true)) {
try {
await ssss.encryption.crossSigning.selfSign(openSsss: this);
} catch (e, s) {
Logs().e('[SSSS] Failed to self-sign', e, s);
}
}
}
}
class _KeyFromPassphraseArgs {
final String passphrase;
final PassphraseInfo info;
_KeyFromPassphraseArgs({required this.passphrase, required this.info});
}
Future<Uint8List> _keyFromPassphrase(_KeyFromPassphraseArgs args) async {
return await SSSS.keyFromPassphrase(args.passphrase, args.info);
}

View file

@ -0,0 +1,13 @@
import 'dart:convert';
import 'dart:typed_data';
/// decodes base64
///
/// Dart's native [base64.decode] requires a padded base64 input String.
/// This function allows unpadded base64 too.
///
/// See: https://github.com/dart-lang/sdk/issues/39510
Uint8List base64decodeUnpadded(String s) {
final needEquals = (4 - (s.length % 4)) % 4;
return base64.decode(s + ('=' * needEquals));
}

View file

@ -0,0 +1,606 @@
/*
* Famedly Matrix SDK
* Copyright (C) 2020, 2021 Famedly GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import 'dart:convert';
import 'dart:typed_data';
import 'package:canonical_json/canonical_json.dart';
import 'package:olm/olm.dart' as olm;
import '../encryption.dart';
import '../ssss.dart';
import '../key_manager.dart';
import '../../matrix.dart';
import 'base64_unpadded.dart';
enum BootstrapState {
/// Is loading.
loading,
/// Existing SSSS found, should we wipe it?
askWipeSsss,
/// Ask if an existing SSSS should be userDeviceKeys
askUseExistingSsss,
/// Ask to unlock all the SSSS keys
askUnlockSsss,
/// SSSS is in a bad state, continue with potential dataloss?
askBadSsss,
/// Ask for new SSSS key / passphrase
askNewSsss,
/// Open an existing SSSS key
openExistingSsss,
/// Ask if cross signing should be wiped
askWipeCrossSigning,
/// Ask if cross signing should be set up
askSetupCrossSigning,
/// Ask if online key backup should be wiped
askWipeOnlineKeyBackup,
/// Ask if the online key backup should be set up
askSetupOnlineKeyBackup,
/// An error has been occured.
error,
/// done
done,
}
/// Bootstrapping SSSS and cross-signing
class Bootstrap {
final Encryption encryption;
Client get client => encryption.client;
void Function()? onUpdate;
BootstrapState get state => _state;
BootstrapState _state = BootstrapState.loading;
Map<String, OpenSSSS>? oldSsssKeys;
OpenSSSS? newSsssKey;
Map<String, String>? secretMap;
Bootstrap({required this.encryption, this.onUpdate}) {
if (analyzeSecrets().isNotEmpty) {
state = BootstrapState.askWipeSsss;
} else {
state = BootstrapState.askNewSsss;
}
}
// cache the secret analyzing so that we don't drop stuff a different client sets during bootstrapping
Map<String, Set<String>>? _secretsCache;
Map<String, Set<String>> analyzeSecrets() {
final secretsCache = _secretsCache;
if (secretsCache != null) {
// deep-copy so that we can do modifications
final newSecrets = <String, Set<String>>{};
for (final s in secretsCache.entries) {
newSecrets[s.key] = Set<String>.from(s.value);
}
return newSecrets;
}
final secrets = <String, Set<String>>{};
for (final entry in client.accountData.entries) {
final type = entry.key;
final event = entry.value;
if (!(event.content['encrypted'] is Map)) {
continue;
}
final validKeys = <String>{};
final invalidKeys = <String>{};
for (final keyEntry in event.content['encrypted'].entries) {
final key = keyEntry.key;
final value = keyEntry.value;
if (!(value is Map)) {
// we don't add the key to invalidKeys as this was not a proper secret anyways!
continue;
}
if (!(value['iv'] is String) ||
!(value['ciphertext'] is String) ||
!(value['mac'] is String)) {
invalidKeys.add(key);
continue;
}
if (!encryption.ssss.isKeyValid(key)) {
invalidKeys.add(key);
continue;
}
validKeys.add(key);
}
if (validKeys.isEmpty && invalidKeys.isEmpty) {
continue; // this didn't contain any keys anyways!
}
// if there are no valid keys and only invalid keys then the validKeys set will be empty
// from that we know that there were errors with this secret and that we won't be able to migrate it
secrets[type] = validKeys;
}
_secretsCache = secrets;
return analyzeSecrets();
}
Set<String> badSecrets() {
final secrets = analyzeSecrets();
secrets.removeWhere((k, v) => v.isNotEmpty);
return Set<String>.from(secrets.keys);
}
String mostUsedKey(Map<String, Set<String>> secrets) {
final usage = <String, int>{};
for (final keys in secrets.values) {
for (final key in keys) {
usage.update(key, (i) => i + 1, ifAbsent: () => 1);
}
}
final entriesList = usage.entries.toList();
entriesList.sort((a, b) => a.value.compareTo(b.value));
return entriesList.first.key;
}
Set<String> allNeededKeys() {
final secrets = analyzeSecrets();
secrets.removeWhere(
(k, v) => v.isEmpty); // we don't care about the failed secrets here
final keys = <String>{};
final defaultKeyId = encryption.ssss.defaultKeyId;
final removeKey = (String key) {
final sizeBefore = secrets.length;
secrets.removeWhere((k, v) => v.contains(key));
return sizeBefore - secrets.length;
};
// first we want to try the default key id
if (defaultKeyId != null) {
if (removeKey(defaultKeyId) > 0) {
keys.add(defaultKeyId);
}
}
// now we re-try as long as we have keys for all secrets
while (secrets.isNotEmpty) {
final key = mostUsedKey(secrets);
removeKey(key);
keys.add(key);
}
return keys;
}
void wipeSsss(bool wipe) {
if (state != BootstrapState.askWipeSsss) {
throw BootstrapBadStateException('Wrong State');
}
if (wipe) {
state = BootstrapState.askNewSsss;
} else if (encryption.ssss.defaultKeyId != null &&
encryption.ssss.isKeyValid(encryption.ssss.defaultKeyId!)) {
state = BootstrapState.askUseExistingSsss;
} else if (badSecrets().isNotEmpty) {
state = BootstrapState.askBadSsss;
} else {
migrateOldSsss();
}
}
void useExistingSsss(bool use) {
if (state != BootstrapState.askUseExistingSsss) {
throw BootstrapBadStateException('Wrong State');
}
if (use) {
try {
newSsssKey = encryption.ssss.open(encryption.ssss.defaultKeyId);
state = BootstrapState.openExistingSsss;
} catch (e, s) {
Logs().e('[Bootstrapping] Error open SSSS', e, s);
state = BootstrapState.error;
return;
}
} else if (badSecrets().isNotEmpty) {
state = BootstrapState.askBadSsss;
} else {
migrateOldSsss();
}
}
void ignoreBadSecrets(bool ignore) {
if (state != BootstrapState.askBadSsss) {
throw BootstrapBadStateException('Wrong State');
}
if (ignore) {
migrateOldSsss();
} else {
// that's it, folks. We can't do anything here
state = BootstrapState.error;
}
}
void migrateOldSsss() {
final keys = allNeededKeys();
final oldSsssKeys = this.oldSsssKeys = {};
try {
for (final key in keys) {
oldSsssKeys[key] = encryption.ssss.open(key);
}
} catch (e, s) {
Logs().e('[Bootstrapping] Error construction ssss key', e, s);
state = BootstrapState.error;
return;
}
state = BootstrapState.askUnlockSsss;
}
void unlockedSsss() {
if (state != BootstrapState.askUnlockSsss) {
throw BootstrapBadStateException('Wrong State');
}
state = BootstrapState.askNewSsss;
}
Future<void> newSsss([String? passphrase]) async {
if (state != BootstrapState.askNewSsss) {
throw BootstrapBadStateException('Wrong State');
}
state = BootstrapState.loading;
try {
Logs().v('Create key...');
newSsssKey = await encryption.ssss.createKey(passphrase);
if (oldSsssKeys != null) {
// alright, we have to re-encrypt old secrets with the new key
final secrets = analyzeSecrets();
final removeKey = (String key) {
final s = secrets.entries
.where((e) => e.value.contains(key))
.map((e) => e.key)
.toSet();
secrets.removeWhere((k, v) => v.contains(key));
return s;
};
secretMap = <String, String>{};
for (final entry in oldSsssKeys!.entries) {
final key = entry.value;
final keyId = entry.key;
if (!key.isUnlocked) {
continue;
}
for (final s in removeKey(keyId)) {
Logs().v('Get stored key of type $s...');
secretMap![s] = await key.getStored(s);
Logs().v('Store new secret with this key...');
await newSsssKey!.store(s, secretMap![s]!, add: true);
}
}
// alright, we re-encrypted all the secrets. We delete the dead weight only *after* we set our key to the default key
}
final updatedAccountData = client.onSync.stream.firstWhere((syncUpdate) =>
syncUpdate.accountData != null &&
syncUpdate.accountData!.any((accountData) =>
accountData.type == EventTypes.SecretStorageDefaultKey));
await encryption.ssss.setDefaultKeyId(newSsssKey!.keyId);
await updatedAccountData;
if (oldSsssKeys != null) {
for (final entry in secretMap!.entries) {
Logs().v('Validate and stripe other keys ${entry.key}...');
await newSsssKey!.validateAndStripOtherKeys(entry.key, entry.value);
}
Logs().v('And make super sure we have everything cached...');
await newSsssKey!.maybeCacheAll();
}
} catch (e, s) {
Logs().e('[Bootstrapping] Error trying to migrate old secrets', e, s);
state = BootstrapState.error;
return;
}
// alright, we successfully migrated all secrets, if needed
checkCrossSigning();
}
Future<void> openExistingSsss() async {
final newSsssKey = this.newSsssKey;
if (state != BootstrapState.openExistingSsss || newSsssKey == null) {
throw BootstrapBadStateException();
}
if (!newSsssKey.isUnlocked) {
throw BootstrapBadStateException('Key not unlocked');
}
Logs().v('Maybe cache all...');
await newSsssKey.maybeCacheAll();
checkCrossSigning();
}
void checkCrossSigning() {
// so, let's see if we have cross signing set up
if (encryption.crossSigning.enabled) {
// cross signing present, ask for wipe
state = BootstrapState.askWipeCrossSigning;
return;
}
// no cross signing present
state = BootstrapState.askSetupCrossSigning;
}
void wipeCrossSigning(bool wipe) {
if (state != BootstrapState.askWipeCrossSigning) {
throw BootstrapBadStateException();
}
if (wipe) {
state = BootstrapState.askSetupCrossSigning;
} else {
checkOnlineKeyBackup();
}
}
Future<void> askSetupCrossSigning(
{bool setupMasterKey = false,
bool setupSelfSigningKey = false,
bool setupUserSigningKey = false}) async {
if (state != BootstrapState.askSetupCrossSigning) {
throw BootstrapBadStateException();
}
if (!setupMasterKey && !setupSelfSigningKey && !setupUserSigningKey) {
checkOnlineKeyBackup();
return;
}
final userID = client.userID!;
try {
Uint8List masterSigningKey;
final secretsToStore = <String, String>{};
MatrixCrossSigningKey? masterKey;
MatrixCrossSigningKey? selfSigningKey;
MatrixCrossSigningKey? userSigningKey;
String? masterPub;
if (setupMasterKey) {
final master = olm.PkSigning();
try {
masterSigningKey = master.generate_seed();
masterPub = master.init_with_seed(masterSigningKey);
final json = <String, dynamic>{
'user_id': userID,
'usage': ['master'],
'keys': <String, dynamic>{
'ed25519:$masterPub': masterPub,
},
};
masterKey = MatrixCrossSigningKey.fromJson(json);
secretsToStore[EventTypes.CrossSigningMasterKey] =
base64.encode(masterSigningKey);
} finally {
master.free();
}
} else {
Logs().v('Get stored key...');
masterSigningKey = base64decodeUnpadded(
await newSsssKey?.getStored(EventTypes.CrossSigningMasterKey) ??
'');
if (masterSigningKey.isEmpty) {
// no master signing key :(
throw BootstrapBadStateException('No master key');
}
final master = olm.PkSigning();
try {
masterPub = master.init_with_seed(masterSigningKey);
} finally {
master.free();
}
}
final _sign = (Map<String, dynamic> object) {
final keyObj = olm.PkSigning();
try {
keyObj.init_with_seed(masterSigningKey);
return keyObj
.sign(String.fromCharCodes(canonicalJson.encode(object)));
} finally {
keyObj.free();
}
};
if (setupSelfSigningKey) {
final selfSigning = olm.PkSigning();
try {
final selfSigningPriv = selfSigning.generate_seed();
final selfSigningPub = selfSigning.init_with_seed(selfSigningPriv);
final json = <String, dynamic>{
'user_id': userID,
'usage': ['self_signing'],
'keys': <String, dynamic>{
'ed25519:$selfSigningPub': selfSigningPub,
},
};
final signature = _sign(json);
json['signatures'] = <String, dynamic>{
userID: <String, dynamic>{
'ed25519:$masterPub': signature,
},
};
selfSigningKey = MatrixCrossSigningKey.fromJson(json);
secretsToStore[EventTypes.CrossSigningSelfSigning] =
base64.encode(selfSigningPriv);
} finally {
selfSigning.free();
}
}
if (setupUserSigningKey) {
final userSigning = olm.PkSigning();
try {
final userSigningPriv = userSigning.generate_seed();
final userSigningPub = userSigning.init_with_seed(userSigningPriv);
final json = <String, dynamic>{
'user_id': userID,
'usage': ['user_signing'],
'keys': <String, dynamic>{
'ed25519:$userSigningPub': userSigningPub,
},
};
final signature = _sign(json);
json['signatures'] = <String, dynamic>{
userID: <String, dynamic>{
'ed25519:$masterPub': signature,
},
};
userSigningKey = MatrixCrossSigningKey.fromJson(json);
secretsToStore[EventTypes.CrossSigningUserSigning] =
base64.encode(userSigningPriv);
} finally {
userSigning.free();
}
}
// upload the keys!
state = BootstrapState.loading;
Logs().v('Upload device signing keys.');
await client.uiaRequestBackground(
(AuthenticationData? auth) => client.uploadCrossSigningKeys(
masterKey: masterKey,
selfSigningKey: selfSigningKey,
userSigningKey: userSigningKey,
auth: auth,
));
Logs().v('Device signing keys have been uploaded.');
// aaaand set the SSSS secrets
final futures = <Future<void>>[];
if (masterKey != null) {
futures.add(
client.onSync.stream
.firstWhere((syncUpdate) =>
masterKey?.publicKey != null &&
client.userDeviceKeys[client.userID]?.masterKey?.ed25519Key ==
masterKey?.publicKey)
.then((_) => Logs().v('New Master Key was created')),
);
}
for (final entry in secretsToStore.entries) {
futures.add(
client.onSync.stream
.firstWhere((syncUpdate) =>
syncUpdate.accountData != null &&
syncUpdate.accountData!
.any((accountData) => accountData.type == entry.key))
.then((_) =>
Logs().v('New Key with type ${entry.key} was created')),
);
Logs().v('Store new SSSS key ${entry.key}...');
await newSsssKey?.store(entry.key, entry.value);
}
Logs().v(
'Wait for MasterKey and ${secretsToStore.entries.length} keys to be created');
await Future.wait<void>(futures);
final keysToSign = <SignableKey>[];
if (masterKey != null) {
if (client.userDeviceKeys[client.userID]?.masterKey?.ed25519Key !=
masterKey.publicKey) {
throw BootstrapBadStateException(
'ERROR: New master key does not match up!');
}
Logs().v('Set own master key to verified...');
await client.userDeviceKeys[client.userID]!.masterKey!
.setVerified(true, false);
keysToSign.add(client.userDeviceKeys[client.userID]!.masterKey!);
}
if (selfSigningKey != null) {
keysToSign.add(
client.userDeviceKeys[client.userID]!.deviceKeys[client.deviceID]!);
}
Logs().v('Sign ourself...');
await encryption.crossSigning.sign(keysToSign);
} catch (e, s) {
Logs().e('[Bootstrapping] Error setting up cross signing', e, s);
state = BootstrapState.error;
return;
}
checkOnlineKeyBackup();
}
void checkOnlineKeyBackup() {
// check if we have online key backup set up
if (encryption.keyManager.enabled) {
state = BootstrapState.askWipeOnlineKeyBackup;
return;
}
state = BootstrapState.askSetupOnlineKeyBackup;
}
void wipeOnlineKeyBackup(bool wipe) {
if (state != BootstrapState.askWipeOnlineKeyBackup) {
throw BootstrapBadStateException();
}
if (wipe) {
state = BootstrapState.askSetupOnlineKeyBackup;
} else {
state = BootstrapState.done;
}
}
Future<void> askSetupOnlineKeyBackup(bool setup) async {
if (state != BootstrapState.askSetupOnlineKeyBackup) {
throw BootstrapBadStateException();
}
if (!setup) {
state = BootstrapState.done;
return;
}
try {
final keyObj = olm.PkDecryption();
String pubKey;
Uint8List privKey;
try {
pubKey = keyObj.generate_key();
privKey = keyObj.get_private_key();
} finally {
keyObj.free();
}
Logs().v('Create the new backup version...');
await client.postRoomKeysVersion(
BackupAlgorithm.mMegolmBackupV1Curve25519AesSha2,
<String, dynamic>{
'public_key': pubKey,
},
);
Logs().v('Store the secret...');
await newSsssKey?.store(megolmKey, base64.encode(privKey));
Logs().v(
'And finally set all megolm keys as needing to be uploaded again...');
await client.database?.markInboundGroupSessionsAsNeedingUpload();
} catch (e, s) {
Logs().e('[Bootstrapping] Error setting up online key backup', e, s);
state = BootstrapState.error;
encryption.client.onEncryptionError.add(
SdkError(exception: e, stackTrace: s),
);
return;
}
state = BootstrapState.done;
}
set state(BootstrapState newState) {
Logs().v('BootstrapState: $newState');
if (state != BootstrapState.error) {
_state = newState;
}
onUpdate?.call();
}
}
class BootstrapBadStateException implements Exception {
String cause;
BootstrapBadStateException([this.cause = 'Bad state']);
@override
String toString() => 'BootstrapBadStateException: $cause';
}

View file

@ -0,0 +1,50 @@
/*
* Famedly Matrix SDK
* Copyright (C) 2020, 2021 Famedly GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import 'package:canonical_json/canonical_json.dart';
import 'package:olm/olm.dart' as olm;
import '../../matrix.dart';
extension JsonSignatureCheckExtension on Map<String, dynamic> {
/// Checks the signature of a signed json object.
bool checkJsonSignature(String key, String userId, String deviceId) {
final signatures = this['signatures'];
if (signatures == null ||
!(signatures is Map<String, dynamic>) ||
!signatures.containsKey(userId)) return false;
remove('unsigned');
remove('signatures');
if (!signatures[userId].containsKey('ed25519:$deviceId')) return false;
final String signature = signatures[userId]['ed25519:$deviceId'];
final canonical = canonicalJson.encode(this);
final message = String.fromCharCodes(canonical);
var isValid = false;
final olmutil = olm.Utility();
try {
olmutil.ed25519_verify(key, message, signature);
isValid = true;
} catch (e, s) {
isValid = false;
Logs().w('[LibOlm] Signature check failed', e, s);
} finally {
olmutil.free();
}
return isValid;
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,61 @@
/*
* Famedly Matrix SDK
* Copyright (C) 2020, 2021 Famedly GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import 'package:olm/olm.dart' as olm;
import '../../matrix.dart';
class OlmSession {
String identityKey;
String? sessionId;
olm.Session? session;
DateTime? lastReceived;
final String key;
String? get pickledSession => session?.pickle(key);
bool get isValid => session != null;
OlmSession({
required this.key,
required this.identityKey,
required this.sessionId,
required this.session,
required this.lastReceived,
});
OlmSession.fromJson(Map<String, dynamic> dbEntry, String key)
: key = key,
identityKey = dbEntry['identity_key'] ?? '' {
session = olm.Session();
try {
session!.unpickle(key, dbEntry['pickle']);
sessionId = dbEntry['session_id'];
lastReceived =
DateTime.fromMillisecondsSinceEpoch(dbEntry['last_received'] ?? 0);
assert(sessionId == session!.session_id());
} catch (e, s) {
Logs().e('[LibOlm] Could not unpickle olm session', e, s);
dispose();
}
}
void dispose() {
session?.free();
session = null;
}
}

View file

@ -0,0 +1,72 @@
/*
* Famedly Matrix SDK
* Copyright (C) 2019, 2020, 2021 Famedly GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import 'dart:convert';
import 'package:olm/olm.dart' as olm;
import '../../matrix.dart';
class OutboundGroupSession {
/// The devices is a map from user id to device id to if the device is blocked.
/// This way we can easily know if a new user is added, leaves, a new devices is added, and,
/// very importantly, if we block a device. These are all important for determining if/when
/// an outbound session needs to be rotated.
Map<String, Map<String, bool>> devices = {};
// Default to a date, that would get this session rotated in any case to make handling easier
DateTime creationTime = DateTime.fromMillisecondsSinceEpoch(0);
olm.OutboundGroupSession? outboundGroupSession;
int? get sentMessages => outboundGroupSession?.message_index();
bool get isValid => outboundGroupSession != null;
final String key;
OutboundGroupSession(
{required this.devices,
required this.creationTime,
required this.outboundGroupSession,
required this.key});
OutboundGroupSession.fromJson(Map<String, dynamic> dbEntry, String key)
: key = key {
try {
for (final entry in json.decode(dbEntry['device_ids']).entries) {
devices[entry.key] = Map<String, bool>.from(entry.value);
}
} catch (e) {
// devices is bad (old data), so just not use this session
Logs().i(
'[OutboundGroupSession] Session in database is old, not using it. ' +
e.toString());
return;
}
outboundGroupSession = olm.OutboundGroupSession();
try {
outboundGroupSession!.unpickle(key, dbEntry['pickle']);
creationTime =
DateTime.fromMillisecondsSinceEpoch(dbEntry['creation_time']);
} catch (e, s) {
dispose();
Logs().e('[LibOlm] Unable to unpickle outboundGroupSession', e, s);
}
}
void dispose() {
outboundGroupSession?.free();
outboundGroupSession = null;
}
}

View file

@ -0,0 +1,115 @@
/*
* Famedly Matrix SDK
* Copyright (C) 2019, 2020, 2021 Famedly GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import 'package:matrix/encryption/utils/stored_inbound_group_session.dart';
import 'package:matrix_api_lite/src/utils/filter_map_extension.dart';
import 'package:olm/olm.dart' as olm;
import '../../matrix.dart';
class SessionKey {
/// The raw json content of the key
Map<String, dynamic> content = <String, dynamic>{};
/// Map of stringified-index to event id, so that we can detect replay attacks
Map<String, String> indexes;
/// Map of userId to map of deviceId to index, that we know that device receivied, e.g. sending it ourself.
/// Used for automatically answering key requests
Map<String, Map<String, int>> allowedAtIndex;
/// Underlying olm [InboundGroupSession] object
olm.InboundGroupSession? inboundGroupSession;
/// Key for libolm pickle / unpickle
final String key;
/// Forwarding keychain
List<String> get forwardingCurve25519KeyChain =>
(content['forwarding_curve25519_key_chain'] != null
? List<String>.from(content['forwarding_curve25519_key_chain'])
: null) ??
<String>[];
/// Claimed keys of the original sender
late Map<String, String> senderClaimedKeys;
/// Sender curve25519 key
String senderKey;
/// Is this session valid?
bool get isValid => inboundGroupSession != null;
/// roomId for this session
String roomId;
/// Id of this session
String sessionId;
SessionKey(
{required this.content,
required this.inboundGroupSession,
required this.key,
Map<String, String>? indexes,
Map<String, Map<String, int>>? allowedAtIndex,
required this.roomId,
required this.sessionId,
required this.senderKey,
required this.senderClaimedKeys})
: indexes = indexes ?? <String, String>{},
allowedAtIndex = allowedAtIndex ?? <String, Map<String, int>>{};
SessionKey.fromDb(StoredInboundGroupSession dbEntry, String key)
: key = key,
content = Event.getMapFromPayload(dbEntry.content),
indexes = Event.getMapFromPayload(dbEntry.indexes)
.catchMap((k, v) => MapEntry<String, String>(k, v)),
allowedAtIndex = Event.getMapFromPayload(dbEntry.allowedAtIndex)
.catchMap((k, v) => MapEntry(k, Map<String, int>.from(v))),
roomId = dbEntry.roomId,
sessionId = dbEntry.sessionId,
senderKey = dbEntry.senderKey,
inboundGroupSession = olm.InboundGroupSession() {
final parsedSenderClaimedKeys =
Event.getMapFromPayload(dbEntry.senderClaimedKeys)
.catchMap((k, v) => MapEntry<String, String>(k, v));
// we need to try...catch as the map used to be <String, int> and that will throw an error.
senderClaimedKeys = (parsedSenderClaimedKeys.isNotEmpty)
? parsedSenderClaimedKeys
: (content['sender_claimed_keys'] is Map
? content['sender_claimed_keys']
.catchMap((k, v) => MapEntry<String, String>(k, v))
: (content['sender_claimed_ed25519_key'] is String
? <String, String>{
'ed25519': content['sender_claimed_ed25519_key']
}
: <String, String>{}));
try {
inboundGroupSession!.unpickle(key, dbEntry.pickle);
} catch (e, s) {
dispose();
Logs().e('[LibOlm] Unable to unpickle inboundGroupSession', e, s);
}
}
void dispose() {
inboundGroupSession?.free();
inboundGroupSession = null;
}
}

View file

@ -0,0 +1,40 @@
/*
* Famedly Matrix SDK
* Copyright (C) 2021 Famedly GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
class SSSSCache {
final String? type;
final String? keyId;
final String? ciphertext;
final String? content;
const SSSSCache({this.type, this.keyId, this.ciphertext, this.content});
factory SSSSCache.fromJson(Map<String, dynamic> json) => SSSSCache(
type: json['type'],
keyId: json['key_id'],
ciphertext: json['ciphertext'],
content: json['content'],
);
Map<String, dynamic> toJson() => {
'type': type,
'key_id': keyId,
'ciphertext': ciphertext,
'content': content,
};
}

View file

@ -0,0 +1,66 @@
/*
* Famedly Matrix SDK
* Copyright (C) 2021 Famedly GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
class StoredInboundGroupSession {
final String roomId;
final String sessionId;
final String pickle;
final String content;
final String indexes;
final String allowedAtIndex;
final bool uploaded;
final String senderKey;
final String senderClaimedKeys;
StoredInboundGroupSession({
required this.roomId,
required this.sessionId,
required this.pickle,
required this.content,
required this.indexes,
required this.allowedAtIndex,
required this.uploaded,
required this.senderKey,
required this.senderClaimedKeys,
});
factory StoredInboundGroupSession.fromJson(Map<String, dynamic> json) =>
StoredInboundGroupSession(
roomId: json['room_id'],
sessionId: json['session_id'],
pickle: json['pickle'],
content: json['content'],
indexes: json['indexes'],
allowedAtIndex: json['allowed_at_index'],
uploaded: json['uploaded'],
senderKey: json['sender_key'],
senderClaimedKeys: json['sender_claimed_keys'],
);
Map<String, dynamic> toJson() => {
'room_id': roomId,
'session_id': sessionId,
'pickle': pickle,
'content': content,
'indexes': indexes,
'allowed_at_index': allowedAtIndex,
'uploaded': uploaded,
'sender_key': senderKey,
'sender_claimed_keys': senderClaimedKeys,
};
}

49
lib/matrix.dart Normal file
View file

@ -0,0 +1,49 @@
/*
* Famedly Matrix SDK
* Copyright (C) 2019, 2020, 2021 Famedly GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/// Matrix SDK written in pure Dart.
library matrix;
export 'package:matrix_api_lite/matrix_api_lite.dart';
export 'src/client.dart';
export 'src/database/database_api.dart';
export 'src/database/hive_database.dart';
export 'src/database/fluffybox_database.dart';
export 'src/event.dart';
export 'src/event_status.dart';
export 'src/voip.dart';
export 'src/voip_content.dart';
export 'src/room.dart';
export 'src/timeline.dart';
export 'src/user.dart';
export 'src/utils/commands_extension.dart';
export 'src/utils/crypto/encrypted_file.dart';
export 'src/utils/device_keys_list.dart';
export 'src/utils/event_update.dart';
export 'src/utils/http_timeout.dart';
export 'src/utils/image_pack_extension.dart';
export 'src/utils/matrix_file.dart';
export 'src/utils/matrix_id_string_extension.dart';
export 'src/utils/matrix_localizations.dart';
export 'src/utils/receipt.dart';
export 'src/utils/sync_update_extension.dart';
export 'src/utils/to_device_event.dart';
export 'src/utils/uia_request.dart';
export 'src/utils/uri_extension.dart';
export 'src/voip_content.dart';

2542
lib/src/client.dart Normal file

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,309 @@
/*
* Famedly Matrix SDK
* Copyright (C) 2021 Famedly GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import 'dart:typed_data';
import 'package:matrix/encryption/utils/olm_session.dart';
import 'package:matrix/encryption/utils/outbound_group_session.dart';
import 'package:matrix/encryption/utils/ssss_cache.dart';
import 'package:matrix/encryption/utils/stored_inbound_group_session.dart';
import 'package:matrix/src/utils/queued_to_device_event.dart';
import '../../matrix.dart';
abstract class DatabaseApi {
int get maxFileSize => 1 * 1024 * 1024;
bool get supportsFileStoring => false;
Future<Map<String, dynamic>?> getClient(String name);
Future updateClient(
String homeserverUrl,
String token,
String userId,
String? deviceId,
String? deviceName,
String? prevBatch,
String? olmAccount,
);
Future insertClient(
String name,
String homeserverUrl,
String token,
String userId,
String? deviceId,
String? deviceName,
String? prevBatch,
String? olmAccount,
);
Future<List<Room>> getRoomList(Client client);
Future<Map<String, BasicEvent>> getAccountData();
/// Stores a RoomUpdate object in the database. Must be called inside of
/// [transaction].
Future<void> storeRoomUpdate(
String roomId, SyncRoomUpdate roomUpdate, Client client);
/// Stores an EventUpdate object in the database. Must be called inside of
/// [transaction].
Future<void> storeEventUpdate(EventUpdate eventUpdate, Client client);
Future<Event?> getEventById(String eventId, Room room);
Future<void> forgetRoom(String roomId);
Future<void> clearCache();
Future<void> clear();
Future<User?> getUser(String userId, Room room);
Future<List<User>> getUsers(Room room);
Future<List<Event>> getEventList(
Room room, {
int start = 0,
int limit,
});
Future<Uint8List?> getFile(Uri mxcUri);
Future storeFile(Uri mxcUri, Uint8List bytes, int time);
Future storeSyncFilterId(
String syncFilterId,
);
Future storeAccountData(String type, String content);
Future<Map<String, DeviceKeysList>> getUserDeviceKeys(Client client);
Future<SSSSCache?> getSSSSCache(String type);
Future<OutboundGroupSession?> getOutboundGroupSession(
String roomId,
String userId,
);
Future<List<StoredInboundGroupSession>> getAllInboundGroupSessions();
Future<StoredInboundGroupSession?> getInboundGroupSession(
String roomId,
String sessionId,
);
Future updateInboundGroupSessionIndexes(
String indexes,
String roomId,
String sessionId,
);
Future storeInboundGroupSession(
String roomId,
String sessionId,
String pickle,
String content,
String indexes,
String allowedAtIndex,
String senderKey,
String senderClaimedKey,
);
Future markInboundGroupSessionAsUploaded(
String roomId,
String sessionId,
);
Future updateInboundGroupSessionAllowedAtIndex(
String allowedAtIndex,
String roomId,
String sessionId,
);
Future removeOutboundGroupSession(String roomId);
Future storeOutboundGroupSession(
String roomId,
String pickle,
String deviceIds,
int creationTime,
);
Future updateClientKeys(
String olmAccount,
);
Future storeOlmSession(
String identitiyKey,
String sessionId,
String pickle,
int lastReceived,
);
Future setLastActiveUserDeviceKey(
int lastActive,
String userId,
String deviceId,
);
Future setLastSentMessageUserDeviceKey(
String lastSentMessage,
String userId,
String deviceId,
);
Future clearSSSSCache();
Future storeSSSSCache(
String type,
String keyId,
String ciphertext,
String content,
);
Future markInboundGroupSessionsAsNeedingUpload();
Future storePrevBatch(
String prevBatch,
);
Future deleteOldFiles(int savedAt);
Future storeUserDeviceKeysInfo(
String userId,
bool outdated,
);
Future storeUserDeviceKey(
String userId,
String deviceId,
String content,
bool verified,
bool blocked,
int lastActive,
);
Future removeUserDeviceKey(
String userId,
String deviceId,
);
Future removeUserCrossSigningKey(
String userId,
String publicKey,
);
Future storeUserCrossSigningKey(
String userId,
String publicKey,
String content,
bool verified,
bool blocked,
);
Future deleteFromToDeviceQueue(int id);
Future removeEvent(String eventId, String roomId);
Future updateRoomSortOrder(
double oldestSortOrder,
double newestSortOrder,
String roomId,
);
Future setRoomPrevBatch(
String prevBatch,
String roomId,
Client client,
);
Future resetNotificationCount(String roomId);
Future setVerifiedUserCrossSigningKey(
bool verified,
String userId,
String publicKey,
);
Future setBlockedUserCrossSigningKey(
bool blocked,
String userId,
String publicKey,
);
Future setVerifiedUserDeviceKey(
bool verified,
String userId,
String deviceId,
);
Future setBlockedUserDeviceKey(
bool blocked,
String userId,
String deviceId,
);
Future<List<Event>> getUnimportantRoomEventStatesForRoom(
List<String> events,
Room room,
);
Future<List<OlmSession>> getOlmSessions(
String identityKey,
String userId,
);
Future<Map<String, Map>> getAllOlmSessions();
Future<List<OlmSession>> getOlmSessionsForDevices(
List<String> identityKeys,
String userId,
);
Future<List<QueuedToDeviceEvent>> getToDeviceEventQueue();
/// Please do `jsonEncode(content)` in your code to stay compatible with
/// auto generated methods here.
Future insertIntoToDeviceQueue(
String type,
String txnId,
String content,
);
Future<List<String>> getLastSentMessageUserDeviceKey(
String userId,
String deviceId,
);
Future<List<StoredInboundGroupSession>> getInboundGroupSessionsToUpload();
Future<void> addSeenDeviceId(
String userId, String deviceId, String publicKeys);
Future<void> addSeenPublicKey(String publicKey, String deviceId);
Future<String?> deviceIdSeen(userId, deviceId);
Future<String?> publicKeySeen(String publicKey);
Future<dynamic> close();
Future<T> transaction<T>(Future<T> Function() action);
}

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

792
lib/src/event.dart Normal file
View file

@ -0,0 +1,792 @@
/*
* Famedly Matrix SDK
* Copyright (C) 2019, 2020, 2021 Famedly GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import 'dart:convert';
import 'dart:typed_data';
import 'package:http/http.dart' as http;
import '../matrix.dart';
import 'utils/event_localizations.dart';
import 'utils/html_to_text.dart';
abstract class RelationshipTypes {
static const String reply = 'm.in_reply_to';
static const String edit = 'm.replace';
static const String reaction = 'm.annotation';
}
/// All data exchanged over Matrix is expressed as an "event". Typically each client action (e.g. sending a message) correlates with exactly one event.
class Event extends MatrixEvent {
User get sender => room.getUserByMXIDSync(senderId);
@Deprecated('Use [originServerTs] instead')
DateTime get time => originServerTs;
@Deprecated('Use [type] instead')
String get typeKey => type;
@Deprecated('Use [sender.calcDisplayname()] instead')
String? get senderName => sender.calcDisplayname();
/// The room this event belongs to. May be null.
final Room room;
/// The status of this event.
EventStatus status;
static const EventStatus defaultStatus = EventStatus.synced;
/// Optional. The event that redacted this event, if any. Otherwise null.
Event? get redactedBecause {
final redacted_because = unsigned?['redacted_because'];
final room = this.room;
return (redacted_because is Map<String, dynamic>)
? Event.fromJson(redacted_because, room)
: null;
}
bool get redacted => redactedBecause != null;
User? get stateKeyUser => room.getUserByMXIDSync(stateKey!);
Event({
this.status = defaultStatus,
required Map<String, dynamic> content,
required String type,
required String eventId,
required String senderId,
required DateTime originServerTs,
Map<String, dynamic>? unsigned,
Map<String, dynamic>? prevContent,
String? stateKey,
required this.room,
}) : super(
content: content,
type: type,
eventId: eventId,
senderId: senderId,
originServerTs: originServerTs,
roomId: room.id,
) {
this.eventId = eventId;
this.unsigned = unsigned;
// synapse unfortunately isn't following the spec and tosses the prev_content
// into the unsigned block.
// Currently we are facing a very strange bug in web which is impossible to debug.
// It may be because of this line so we put this in try-catch until we can fix it.
try {
this.prevContent = (prevContent != null && prevContent.isNotEmpty)
? prevContent
: (unsigned != null &&
unsigned.containsKey('prev_content') &&
unsigned['prev_content'] is Map)
? unsigned['prev_content']
: null;
} catch (_) {
// A strange bug in dart web makes this crash
}
this.stateKey = stateKey;
// Mark event as failed to send if status is `sending` and event is older
// than the timeout. This should not happen with the deprecated Moor
// database!
if (status.isSending && room.client.database != null) {
// Age of this event in milliseconds
final age = DateTime.now().millisecondsSinceEpoch -
originServerTs.millisecondsSinceEpoch;
final room = this.room;
if (age > room.client.sendMessageTimeoutSeconds * 1000) {
// Update this event in database and open timelines
final json = toJson();
json['unsigned'] ??= <String, dynamic>{};
json['unsigned'][messageSendingStatusKey] = EventStatus.error.intValue;
room.client.handleSync(
SyncUpdate(
nextBatch: '',
rooms: RoomsUpdate(
join: {
room.id: JoinedRoomUpdate(
timeline: TimelineUpdate(
events: [MatrixEvent.fromJson(json)],
),
)
},
),
),
);
}
}
}
static Map<String, dynamic> getMapFromPayload(dynamic payload) {
if (payload is String) {
try {
return json.decode(payload);
} catch (e) {
return {};
}
}
if (payload is Map<String, dynamic>) return payload;
return {};
}
factory Event.fromMatrixEvent(
MatrixEvent matrixEvent,
Room room, {
EventStatus status = defaultStatus,
}) =>
Event(
status: status,
content: matrixEvent.content,
type: matrixEvent.type,
eventId: matrixEvent.eventId,
senderId: matrixEvent.senderId,
originServerTs: matrixEvent.originServerTs,
unsigned: matrixEvent.unsigned,
prevContent: matrixEvent.prevContent,
stateKey: matrixEvent.stateKey,
room: room,
);
/// Get a State event from a table row or from the event stream.
factory Event.fromJson(
Map<String, dynamic> jsonPayload,
Room room,
) {
final content = Event.getMapFromPayload(jsonPayload['content']);
final unsigned = Event.getMapFromPayload(jsonPayload['unsigned']);
final prevContent = Event.getMapFromPayload(jsonPayload['prev_content']);
return Event(
status: eventStatusFromInt(jsonPayload['status'] ??
unsigned[messageSendingStatusKey] ??
defaultStatus.intValue),
stateKey: jsonPayload['state_key'],
prevContent: prevContent,
content: content,
type: jsonPayload['type'],
eventId: jsonPayload['event_id'] ?? '',
senderId: jsonPayload['sender'],
originServerTs: jsonPayload.containsKey('origin_server_ts')
? DateTime.fromMillisecondsSinceEpoch(jsonPayload['origin_server_ts'])
: DateTime.now(),
unsigned: unsigned,
room: room,
);
}
@override
Map<String, dynamic> toJson() {
final data = <String, dynamic>{};
if (stateKey != null) data['state_key'] = stateKey;
if (prevContent?.isNotEmpty == true) {
data['prev_content'] = prevContent;
}
data['content'] = content;
data['type'] = type;
data['event_id'] = eventId;
data['room_id'] = roomId;
data['sender'] = senderId;
data['origin_server_ts'] = originServerTs.millisecondsSinceEpoch;
if (unsigned?.isNotEmpty == true) {
data['unsigned'] = unsigned;
}
return data;
}
User get asUser => User.fromState(
// state key should always be set for member events
stateKey: stateKey!,
prevContent: prevContent,
content: content,
typeKey: type,
eventId: eventId,
roomId: roomId,
senderId: senderId,
originServerTs: originServerTs,
unsigned: unsigned,
room: room);
String get messageType => type == EventTypes.Sticker
? MessageTypes.Sticker
: (content['msgtype'] is String ? content['msgtype'] : MessageTypes.Text);
void setRedactionEvent(Event redactedBecause) {
unsigned = {
'redacted_because': redactedBecause.toJson(),
};
prevContent = null;
final contentKeyWhiteList = <String>[];
switch (type) {
case EventTypes.RoomMember:
contentKeyWhiteList.add('membership');
break;
case EventTypes.RoomCreate:
contentKeyWhiteList.add('creator');
break;
case EventTypes.RoomJoinRules:
contentKeyWhiteList.add('join_rule');
break;
case EventTypes.RoomPowerLevels:
contentKeyWhiteList.add('ban');
contentKeyWhiteList.add('events');
contentKeyWhiteList.add('events_default');
contentKeyWhiteList.add('kick');
contentKeyWhiteList.add('redact');
contentKeyWhiteList.add('state_default');
contentKeyWhiteList.add('users');
contentKeyWhiteList.add('users_default');
break;
case EventTypes.RoomAliases:
contentKeyWhiteList.add('aliases');
break;
case EventTypes.HistoryVisibility:
contentKeyWhiteList.add('history_visibility');
break;
default:
break;
}
content.removeWhere((k, v) => !contentKeyWhiteList.contains(k));
}
/// Returns the body of this event if it has a body.
String get text => content['body'] is String ? content['body'] : '';
/// Returns the formatted boy of this event if it has a formatted body.
String get formattedText =>
content['formatted_body'] is String ? content['formatted_body'] : '';
/// Use this to get the body.
String get body {
if (redacted) return 'Redacted';
if (text != '') return text;
if (formattedText != '') return formattedText;
return '$type';
}
/// Use this to get a plain-text representation of the event, stripping things
/// like spoilers and thelike. Useful for plain text notifications.
String get plaintextBody => content['format'] == 'org.matrix.custom.html'
? HtmlToText.convert(formattedText)
: body;
/// Returns a list of [Receipt] instances for this event.
List<Receipt> get receipts {
final room = this.room;
final receipt = room.roomAccountData['m.receipt'];
if (receipt == null) return [];
return receipt.content.entries
.where((entry) => entry.value['event_id'] == eventId)
.map((entry) => Receipt(room.getUserByMXIDSync(entry.key),
DateTime.fromMillisecondsSinceEpoch(entry.value['ts'])))
.toList();
}
/// Removes this event if the status is [sending], [error] or [removed].
/// This event will just be removed from the database and the timelines.
/// Returns [false] if not removed.
Future<bool> remove() async {
final room = this.room;
if (!status.isSent) {
await room.client.database?.removeEvent(eventId, room.id);
room.client.onEvent.add(EventUpdate(
roomID: room.id,
type: EventUpdateType.timeline,
content: {
'event_id': eventId,
'status': EventStatus.removed.intValue,
'content': {'body': 'Removed...'}
},
));
return true;
}
return false;
}
/// Try to send this event again. Only works with events of status -1.
Future<String?> sendAgain({String? txid}) async {
if (!status.isError) return null;
// we do not remove the event here. It will automatically be updated
// in the `sendEvent` method to transition -1 -> 0 -> 1 -> 2
final newEventId = await room.sendEvent(
content,
txid: txid ?? unsigned?['transaction_id'] ?? eventId,
);
return newEventId;
}
/// Whether the client is allowed to redact this event.
bool get canRedact => senderId == room.client.userID || room.canRedact;
/// Redacts this event. Throws `ErrorResponse` on error.
Future<String?> redactEvent({String? reason, String? txid}) async =>
await room.redactEvent(eventId, reason: reason, txid: txid);
/// Searches for the reply event in the given timeline.
Future<Event?> getReplyEvent(Timeline timeline) async {
if (relationshipType != RelationshipTypes.reply) return null;
final relationshipEventId = this.relationshipEventId;
return relationshipEventId == null
? null
: await timeline.getEventById(relationshipEventId);
}
/// If this event is encrypted and the decryption was not successful because
/// the session is unknown, this requests the session key from other devices
/// in the room. If the event is not encrypted or the decryption failed because
/// of a different error, this throws an exception.
Future<void> requestKey() async {
if (type != EventTypes.Encrypted ||
messageType != MessageTypes.BadEncrypted ||
content['can_request_session'] != true) {
throw ('Session key not requestable');
}
await room.requestSessionKey(content['session_id'], content['sender_key']);
return;
}
/// Gets the info map of file events, or a blank map if none present
Map get infoMap =>
content['info'] is Map ? content['info'] : <String, dynamic>{};
/// Gets the thumbnail info map of file events, or a blank map if nonepresent
Map get thumbnailInfoMap => infoMap['thumbnail_info'] is Map
? infoMap['thumbnail_info']
: <String, dynamic>{};
/// Returns if a file event has an attachment
bool get hasAttachment => content['url'] is String || content['file'] is Map;
/// Returns if a file event has a thumbnail
bool get hasThumbnail =>
infoMap['thumbnail_url'] is String || infoMap['thumbnail_file'] is Map;
/// Returns if a file events attachment is encrypted
bool get isAttachmentEncrypted => content['file'] is Map;
/// Returns if a file events thumbnail is encrypted
bool get isThumbnailEncrypted => infoMap['thumbnail_file'] is Map;
/// Gets the mimetype of the attachment of a file event, or a blank string if not present
String get attachmentMimetype => infoMap['mimetype'] is String
? infoMap['mimetype'].toLowerCase()
: (content['file'] is Map && content['file']['mimetype'] is String
? content['file']['mimetype']
: '');
/// Gets the mimetype of the thumbnail of a file event, or a blank string if not present
String get thumbnailMimetype => thumbnailInfoMap['mimetype'] is String
? thumbnailInfoMap['mimetype'].toLowerCase()
: (infoMap['thumbnail_file'] is Map &&
infoMap['thumbnail_file']['mimetype'] is String
? infoMap['thumbnail_file']['mimetype']
: '');
/// Gets the underlying mxc url of an attachment of a file event, or null if not present
Uri? get attachmentMxcUrl {
final url = isAttachmentEncrypted ? content['file']['url'] : content['url'];
return url is String ? Uri.tryParse(url) : null;
}
/// Gets the underlying mxc url of a thumbnail of a file event, or null if not present
Uri? get thumbnailMxcUrl {
final url = isThumbnailEncrypted
? infoMap['thumbnail_file']['url']
: infoMap['thumbnail_url'];
return url is String ? Uri.tryParse(url) : null;
}
/// Gets the mxc url of an attachment/thumbnail of a file event, taking sizes into account, or null if not present
Uri? attachmentOrThumbnailMxcUrl({bool getThumbnail = false}) {
if (getThumbnail &&
infoMap['size'] is int &&
thumbnailInfoMap['size'] is int &&
infoMap['size'] <= thumbnailInfoMap['size']) {
getThumbnail = false;
}
if (getThumbnail && !hasThumbnail) {
getThumbnail = false;
}
return getThumbnail ? thumbnailMxcUrl : attachmentMxcUrl;
}
// size determined from an approximate 800x800 jpeg thumbnail with method=scale
static const _minNoThumbSize = 80 * 1024;
/// Gets the attachment https URL to display in the timeline, taking into account if the original image is tiny.
/// Returns null for encrypted rooms, if the image can't be fetched via http url or if the event does not contain an attachment.
/// Set [getThumbnail] to true to fetch the thumbnail, set [width], [height] and [method]
/// for the respective thumbnailing properties.
/// [minNoThumbSize] is the minimum size that an original image may be to not fetch its thumbnail, defaults to 80k
/// [useThumbnailMxcUrl] says weather to use the mxc url of the thumbnail, rather than the original attachment.
/// [animated] says weather the thumbnail is animated
Uri? getAttachmentUrl(
{bool getThumbnail = false,
bool useThumbnailMxcUrl = false,
double width = 800.0,
double height = 800.0,
ThumbnailMethod method = ThumbnailMethod.scale,
int minNoThumbSize = _minNoThumbSize,
bool animated = false}) {
if (![EventTypes.Message, EventTypes.Sticker].contains(type) ||
!hasAttachment ||
isAttachmentEncrypted) {
return null; // can't url-thumbnail in encrypted rooms
}
if (useThumbnailMxcUrl && !hasThumbnail) {
return null; // can't fetch from thumbnail
}
final thisInfoMap = useThumbnailMxcUrl ? thumbnailInfoMap : infoMap;
final thisMxcUrl =
useThumbnailMxcUrl ? infoMap['thumbnail_url'] : content['url'];
// if we have as method scale, we can return safely the original image, should it be small enough
if (getThumbnail &&
method == ThumbnailMethod.scale &&
thisInfoMap['size'] is int &&
thisInfoMap['size'] < minNoThumbSize) {
getThumbnail = false;
}
// now generate the actual URLs
if (getThumbnail) {
return Uri.parse(thisMxcUrl).getThumbnail(
room.client,
width: width,
height: height,
method: method,
animated: animated,
);
} else {
return Uri.parse(thisMxcUrl).getDownloadLink(room.client);
}
}
/// Returns if an attachment is in the local store
Future<bool> isAttachmentInLocalStore({bool getThumbnail = false}) async {
if (![EventTypes.Message, EventTypes.Sticker].contains(type)) {
throw ("This event has the type '$type' and so it can't contain an attachment.");
}
final mxcUrl = attachmentOrThumbnailMxcUrl(getThumbnail: getThumbnail);
if (mxcUrl == null) {
throw "This event hasn't any attachment or thumbnail.";
}
getThumbnail = mxcUrl != attachmentMxcUrl;
// Is this file storeable?
final thisInfoMap = getThumbnail ? thumbnailInfoMap : infoMap;
final database = room.client.database;
if (database == null) {
return false;
}
final storeable = thisInfoMap['size'] is int &&
thisInfoMap['size'] <= database.maxFileSize;
Uint8List? uint8list;
if (storeable) {
uint8list = await database.getFile(mxcUrl);
}
return uint8list != null;
}
/// Downloads (and decrypts if necessary) the attachment of this
/// event and returns it as a [MatrixFile]. If this event doesn't
/// contain an attachment, this throws an error. Set [getThumbnail] to
/// true to download the thumbnail instead.
Future<MatrixFile> downloadAndDecryptAttachment(
{bool getThumbnail = false,
Future<Uint8List> Function(Uri)? downloadCallback}) async {
if (![EventTypes.Message, EventTypes.Sticker].contains(type)) {
throw ("This event has the type '$type' and so it can't contain an attachment.");
}
final database = room.client.database;
final mxcUrl = attachmentOrThumbnailMxcUrl(getThumbnail: getThumbnail);
if (mxcUrl == null) {
throw "This event hasn't any attachment or thumbnail.";
}
getThumbnail = mxcUrl != attachmentMxcUrl;
final isEncrypted =
getThumbnail ? isThumbnailEncrypted : isAttachmentEncrypted;
if (isEncrypted && !room.client.encryptionEnabled) {
throw ('Encryption is not enabled in your Client.');
}
// Is this file storeable?
final thisInfoMap = getThumbnail ? thumbnailInfoMap : infoMap;
var storeable = database != null &&
thisInfoMap['size'] is int &&
thisInfoMap['size'] <= database.maxFileSize;
Uint8List? uint8list;
if (storeable) {
uint8list = await room.client.database?.getFile(mxcUrl);
}
// Download the file
if (uint8list == null) {
downloadCallback ??= (Uri url) async => (await http.get(url)).bodyBytes;
uint8list = await downloadCallback(mxcUrl.getDownloadLink(room.client));
storeable = database != null &&
storeable &&
uint8list.lengthInBytes < database.maxFileSize;
if (storeable) {
await database.storeFile(
mxcUrl, uint8list, DateTime.now().millisecondsSinceEpoch);
}
}
// Decrypt the file
if (isEncrypted) {
final fileMap =
getThumbnail ? infoMap['thumbnail_file'] : content['file'];
if (!fileMap['key']['key_ops'].contains('decrypt')) {
throw ("Missing 'decrypt' in 'key_ops'.");
}
final encryptedFile = EncryptedFile(
data: uint8list,
iv: fileMap['iv'],
k: fileMap['key']['k'],
sha256: fileMap['hashes']['sha256'],
);
uint8list = await room.client.runInBackground<Uint8List?, EncryptedFile>(
decryptFile, encryptedFile);
if (uint8list == null) {
throw ('Unable to decrypt file');
}
}
return MatrixFile(bytes: uint8list, name: body);
}
/// Returns if this is a known event type.
bool get isEventTypeKnown =>
EventLocalizations.localizationsMap.containsKey(type);
/// Returns a localized String representation of this event. For a
/// room list you may find [withSenderNamePrefix] useful. Set [hideReply] to
/// crop all lines starting with '>'. With [plaintextBody] it'll use the
/// plaintextBody instead of the normal body.
String getLocalizedBody(
MatrixLocalizations i18n, {
bool withSenderNamePrefix = false,
bool hideReply = false,
bool hideEdit = false,
bool plaintextBody = false,
}) {
if (redacted) {
return i18n.removedBy(redactedBecause?.sender.calcDisplayname() ?? '');
}
var body = plaintextBody ? this.plaintextBody : this.body;
// we need to know if the message is an html message to be able to determine
// if we need to strip the reply fallback.
var htmlMessage = content['format'] != 'org.matrix.custom.html';
// If we have an edit, we want to operate on the new content
if (hideEdit &&
relationshipType == RelationshipTypes.edit &&
content.tryGet<Map<String, dynamic>>('m.new_content') != null) {
if (plaintextBody &&
content['m.new_content']['format'] == 'org.matrix.custom.html') {
htmlMessage = true;
body = HtmlToText.convert(
(content['m.new_content'] as Map<String, dynamic>)
.tryGet<String>('formatted_body') ??
formattedText);
} else {
htmlMessage = false;
body = (content['m.new_content'] as Map<String, dynamic>)
.tryGet<String>('body') ??
body;
}
}
// Hide reply fallback
// Be sure that the plaintextBody already stripped teh reply fallback,
// if the message is formatted
if (hideReply && (!plaintextBody || htmlMessage)) {
body = body.replaceFirst(
RegExp(r'^>( \*)? <[^>]+>[^\n\r]+\r?\n(> [^\n]*\r?\n)*\r?\n'), '');
}
final callback = EventLocalizations.localizationsMap[type];
var localizedBody = i18n.unknownEvent(type);
if (callback != null) {
localizedBody = callback(this, i18n, body);
}
// Add the sender name prefix
if (withSenderNamePrefix &&
type == EventTypes.Message &&
textOnlyMessageTypes.contains(messageType)) {
final senderNameOrYou = senderId == room.client.userID
? i18n.you
: (sender.calcDisplayname());
localizedBody = '$senderNameOrYou: $localizedBody';
}
return localizedBody;
}
static const Set<String> textOnlyMessageTypes = {
MessageTypes.Text,
MessageTypes.Notice,
MessageTypes.Emote,
MessageTypes.None,
};
/// returns if this event matches the passed event or transaction id
bool matchesEventOrTransactionId(String? search) {
if (search == null) {
return false;
}
if (eventId == search) {
return true;
}
return unsigned?['transaction_id'] == search;
}
/// Get the relationship type of an event. `null` if there is none
String? get relationshipType {
if (content.tryGet<Map<String, dynamic>>('m.relates_to') == null) {
return null;
}
if (content['m.relates_to'].containsKey('m.in_reply_to')) {
return RelationshipTypes.reply;
}
return content
.tryGet<Map<String, dynamic>>('m.relates_to')
?.tryGet<String>('rel_type');
}
/// Get the event ID that this relationship will reference. `null` if there is none
String? get relationshipEventId {
if (!(content['m.relates_to'] is Map)) {
return null;
}
if (content['m.relates_to'].containsKey('event_id')) {
return content['m.relates_to']['event_id'];
}
if (content['m.relates_to']['m.in_reply_to'] is Map &&
content['m.relates_to']['m.in_reply_to'].containsKey('event_id')) {
return content['m.relates_to']['m.in_reply_to']['event_id'];
}
return null;
}
/// Get whether this event has aggregated events from a certain [type]
/// To be able to do that you need to pass a [timeline]
bool hasAggregatedEvents(Timeline timeline, String type) =>
timeline.aggregatedEvents[eventId]?.containsKey(type) == true;
/// Get all the aggregated event objects for a given [type]. To be able to do this
/// you have to pass a [timeline]
Set<Event> aggregatedEvents(Timeline timeline, String type) =>
timeline.aggregatedEvents[eventId]?[type] ?? <Event>{};
/// Fetches the event to be rendered, taking into account all the edits and the like.
/// It needs a [timeline] for that.
Event getDisplayEvent(Timeline timeline) {
if (redacted) {
return this;
}
if (hasAggregatedEvents(timeline, RelationshipTypes.edit)) {
// alright, we have an edit
final allEditEvents = aggregatedEvents(timeline, RelationshipTypes.edit)
// we only allow edits made by the original author themself
.where((e) => e.senderId == senderId && e.type == EventTypes.Message)
.toList();
// we need to check again if it isn't empty, as we potentially removed all
// aggregated edits
if (allEditEvents.isNotEmpty) {
allEditEvents.sort((a, b) => a.originServerTs.millisecondsSinceEpoch -
b.originServerTs.millisecondsSinceEpoch >
0
? 1
: -1);
final rawEvent = allEditEvents.last.toJson();
// update the content of the new event to render
if (rawEvent['content']['m.new_content'] is Map) {
rawEvent['content'] = rawEvent['content']['m.new_content'];
}
return Event.fromJson(rawEvent, room);
}
}
return this;
}
/// returns if a message is a rich message
bool get isRichMessage =>
content['format'] == 'org.matrix.custom.html' &&
content['formatted_body'] is String;
// regexes to fetch the number of emotes, including emoji, and if the message consists of only those
// to match an emoji we can use the following regex:
// (?:\x{00a9}|\x{00ae}|[\x{2600}-\x{27bf}]|[\x{2b00}-\x{2bff}]|\x{d83c}[\x{d000}-\x{dfff}]|\x{d83d}[\x{d000}-\x{dfff}]|\x{d83e}[\x{d000}-\x{dfff}])[\x{fe00}-\x{fe0f}]?
// we need to replace \x{0000} with \u0000, the comment is left in the other format to be able to paste into regex101.com
// to see if there is a custom emote, we use the following regex: <img[^>]+data-mx-(?:emote|emoticon)(?==|>|\s)[^>]*>
// now we combind the two to have four regexes:
// 1. are there only emoji, or whitespace
// 2. are there only emoji, emotes, or whitespace
// 3. count number of emoji
// 4- count number of emoji or emotes
static final RegExp _onlyEmojiRegex = RegExp(
r'^((?:\u00a9|\u00ae|[\u2600-\u27bf]|[\u2b00-\u2bff]|\ud83c[\ud000-\udfff]|\ud83d[\ud000-\udfff]|\ud83e[\ud000-\udfff])[\ufe00-\ufe0f]?|\s)*$',
caseSensitive: false,
multiLine: false);
static final RegExp _onlyEmojiEmoteRegex = RegExp(
r'^((?:\u00a9|\u00ae|[\u2600-\u27bf]|[\u2b00-\u2bff]|\ud83c[\ud000-\udfff]|\ud83d[\ud000-\udfff]|\ud83e[\ud000-\udfff])[\ufe00-\ufe0f]?|<img[^>]+data-mx-(?:emote|emoticon)(?==|>|\s)[^>]*>|\s)*$',
caseSensitive: false,
multiLine: false);
static final RegExp _countEmojiRegex = RegExp(
r'((?:\u00a9|\u00ae|[\u2600-\u27bf]|[\u2b00-\u2bff]|\ud83c[\ud000-\udfff]|\ud83d[\ud000-\udfff]|\ud83e[\ud000-\udfff])[\ufe00-\ufe0f]?)',
caseSensitive: false,
multiLine: false);
static final RegExp _countEmojiEmoteRegex = RegExp(
r'((?:\u00a9|\u00ae|[\u2600-\u27bf]|[\u2b00-\u2bff]|\ud83c[\ud000-\udfff]|\ud83d[\ud000-\udfff]|\ud83e[\ud000-\udfff])[\ufe00-\ufe0f]?|<img[^>]+data-mx-(?:emote|emoticon)(?==|>|\s)[^>]*>)',
caseSensitive: false,
multiLine: false);
/// Returns if a given event only has emotes, emojis or whitespace as content.
/// If the body contains a reply then it is stripped.
/// This is useful to determine if stand-alone emotes should be displayed bigger.
bool get onlyEmotes {
if (isRichMessage) {
final formattedTextStripped = formattedText.replaceAll(
RegExp('<mx-reply>.*<\/mx-reply>',
caseSensitive: false, multiLine: false, dotAll: true),
'');
return _onlyEmojiEmoteRegex.hasMatch(formattedTextStripped);
} else {
return _onlyEmojiRegex.hasMatch(plaintextBody);
}
}
/// Gets the number of emotes in a given message. This is useful to determine
/// if the emotes should be displayed bigger.
/// If the body contains a reply then it is stripped.
/// WARNING: This does **not** test if there are only emotes. Use `event.onlyEmotes` for that!
int get numberEmotes {
if (isRichMessage) {
final formattedTextStripped = formattedText.replaceAll(
RegExp('<mx-reply>.*<\/mx-reply>',
caseSensitive: false, multiLine: false, dotAll: true),
'');
return _countEmojiEmoteRegex.allMatches(formattedTextStripped).length;
} else {
return _countEmojiRegex.allMatches(plaintextBody).length;
}
}
}

70
lib/src/event_status.dart Normal file
View file

@ -0,0 +1,70 @@
/// Defines event status:
/// - removed
/// - error: (http request failed)
/// - sending: (http request started)
/// - sent: (http request successful)
/// - synced: (event came from sync loop)
/// - roomState
enum EventStatus {
removed,
error,
sending,
sent,
synced,
roomState,
}
/// Returns `EventStatusEnum` value from `intValue`.
///
/// - -2 == removed;
/// - -1 == error;
/// - 0 == sending;
/// - 1 == sent;
/// - 2 == synced;
/// - 3 == roomState;
EventStatus eventStatusFromInt(int intValue) =>
EventStatus.values[intValue + 2];
/// Takes two [EventStatus] values and returns the one with higher
/// (better in terms of message sending) status.
EventStatus latestEventStatus(EventStatus status1, EventStatus status2) =>
status1.intValue > status2.intValue ? status1 : status2;
extension EventStatusExtension on EventStatus {
/// Returns int value of the event status.
///
/// - -2 == removed;
/// - -1 == error;
/// - 0 == sending;
/// - 1 == sent;
/// - 2 == synced;
/// - 3 == roomState;
int get intValue => (index - 2);
/// Return `true` if the `EventStatus` equals `removed`.
bool get isRemoved => this == EventStatus.removed;
/// Return `true` if the `EventStatus` equals `error`.
bool get isError => this == EventStatus.error;
/// Return `true` if the `EventStatus` equals `sending`.
bool get isSending => this == EventStatus.sending;
/// Return `true` if the `EventStatus` equals `roomState`.
bool get isRoomState => this == EventStatus.roomState;
/// Returns `true` if the status is sent or later:
/// [EventStatus.sent], [EventStatus.synced] or [EventStatus.roomState].
bool get isSent => [
EventStatus.sent,
EventStatus.synced,
EventStatus.roomState
].contains(this);
/// Returns `true` if the status is `synced` or `roomState`:
/// [EventStatus.synced] or [EventStatus.roomState].
bool get isSynced => [
EventStatus.synced,
EventStatus.roomState,
].contains(this);
}

2100
lib/src/room.dart Normal file

File diff suppressed because it is too large Load diff

370
lib/src/timeline.dart Normal file
View file

@ -0,0 +1,370 @@
/*
* Famedly Matrix SDK
* Copyright (C) 2019, 2020, 2021 Famedly GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import 'dart:async';
import 'package:collection/src/iterable_extensions.dart';
import '../matrix.dart';
/// Represents the timeline of a room. The callback [onUpdate] will be triggered
/// automatically. The initial
/// event list will be retreived when created by the `room.getTimeline()` method.
class Timeline {
final Room room;
final List<Event> events;
/// Map of event ID to map of type to set of aggregated events
final Map<String, Map<String, Set<Event>>> aggregatedEvents = {};
final void Function()? onUpdate;
final void Function(int index)? onChange;
final void Function(int index)? onInsert;
final void Function(int index)? onRemove;
StreamSubscription<EventUpdate>? sub;
StreamSubscription<SyncUpdate>? roomSub;
StreamSubscription<String>? sessionIdReceivedSub;
bool isRequestingHistory = false;
final Map<String, Event> _eventCache = {};
/// Searches for the event in this timeline. If not
/// found, requests from the server. Requested events
/// are cached.
Future<Event?> getEventById(String id) async {
for (final event in events) {
if (event.eventId == id) return event;
}
if (_eventCache.containsKey(id)) return _eventCache[id];
final requestedEvent = await room.getEventById(id);
if (requestedEvent == null) return null;
_eventCache[id] = requestedEvent;
return _eventCache[id];
}
// When fetching history, we will collect them into the `_historyUpdates` set
// first, and then only process all events at once, once we have the full history.
// This ensures that the entire history fetching only triggers `onUpdate` only *once*,
// even if /sync's complete while history is being proccessed.
bool _collectHistoryUpdates = false;
bool get canRequestHistory {
if (events.isEmpty) return true;
return events.last.type != EventTypes.RoomCreate;
}
Future<void> requestHistory(
{int historyCount = Room.defaultHistoryCount}) async {
if (isRequestingHistory) {
return;
}
isRequestingHistory = true;
onUpdate?.call();
try {
// Look up for events in hive first
final eventsFromStore = await room.client.database?.getEventList(
room,
start: events.length,
limit: Room.defaultHistoryCount,
);
if (eventsFromStore != null && eventsFromStore.isNotEmpty) {
events.addAll(eventsFromStore);
final startIndex = events.length - eventsFromStore.length;
final endIndex = events.length;
for (var i = startIndex; i < endIndex; i++) {
onInsert?.call(i);
}
} else {
Logs().v('No more events found in the store. Request from server...');
await room.requestHistory(
historyCount: historyCount,
onHistoryReceived: () {
_collectHistoryUpdates = true;
},
);
}
} finally {
_collectHistoryUpdates = false;
isRequestingHistory = false;
onUpdate?.call();
}
}
Timeline({
required this.room,
List<Event>? events,
this.onUpdate,
this.onChange,
this.onInsert,
this.onRemove,
}) : events = events ?? [] {
sub = room.client.onEvent.stream.listen(_handleEventUpdate);
// If the timeline is limited we want to clear our events cache
roomSub = room.client.onSync.stream
.where((sync) => sync.rooms?.join?[room.id]?.timeline?.limited == true)
.listen(_removeEventsNotInThisSync);
sessionIdReceivedSub =
room.onSessionKeyReceived.stream.listen(_sessionKeyReceived);
// we want to populate our aggregated events
for (final e in this.events) {
addAggregatedEvent(e);
}
}
/// Removes all entries from [events] which are not in this SyncUpdate.
void _removeEventsNotInThisSync(SyncUpdate sync) {
final newSyncEvents = sync.rooms?.join?[room.id]?.timeline?.events ?? [];
final keepEventIds = newSyncEvents.map((e) => e.eventId);
events.removeWhere((e) => !keepEventIds.contains(e.eventId));
}
/// Don't forget to call this before you dismiss this object!
void cancelSubscriptions() {
sub?.cancel();
roomSub?.cancel();
sessionIdReceivedSub?.cancel();
}
void _sessionKeyReceived(String sessionId) async {
var decryptAtLeastOneEvent = false;
final decryptFn = () async {
final encryption = room.client.encryption;
if (!room.client.encryptionEnabled || encryption == null) {
return;
}
for (var i = 0; i < events.length; i++) {
if (events[i].type == EventTypes.Encrypted &&
events[i].messageType == MessageTypes.BadEncrypted &&
events[i].content['session_id'] == sessionId) {
events[i] = await encryption.decryptRoomEvent(room.id, events[i],
store: true);
onChange?.call(i);
if (events[i].type != EventTypes.Encrypted) {
decryptAtLeastOneEvent = true;
}
}
}
};
if (room.client.database != null) {
await room.client.database?.transaction(decryptFn);
} else {
await decryptFn();
}
if (decryptAtLeastOneEvent) onUpdate?.call();
}
/// Request the keys for undecryptable events of this timeline
void requestKeys() {
for (final event in events) {
if (event.type == EventTypes.Encrypted &&
event.messageType == MessageTypes.BadEncrypted &&
event.content['can_request_session'] == true) {
try {
room.client.encryption?.keyManager.maybeAutoRequest(room.id,
event.content['session_id'], event.content['sender_key']);
} catch (_) {
// dispose
}
}
}
}
/// Set the read marker to the last synced event in this timeline.
Future<void> setReadMarker([String? eventId]) async {
eventId ??=
events.firstWhereOrNull((event) => event.status.isSynced)?.eventId;
if (eventId == null) return;
return room.setReadMarker(eventId, mRead: eventId);
}
int _findEvent({String? event_id, String? unsigned_txid}) {
// we want to find any existing event where either the passed event_id or the passed unsigned_txid
// matches either the event_id or transaction_id of the existing event.
// For that we create two sets, searchNeedle, what we search, and searchHaystack, where we check if there is a match.
// Now, after having these two sets, if the intersect between them is non-empty, we know that we have at least one match in one pair,
// thus meaning we found our element.
final searchNeedle = <String>{};
if (event_id != null) {
searchNeedle.add(event_id);
}
if (unsigned_txid != null) {
searchNeedle.add(unsigned_txid);
}
int i;
for (i = 0; i < events.length; i++) {
final searchHaystack = <String>{events[i].eventId};
final txnid = events[i].unsigned?['transaction_id'];
if (txnid != null) {
searchHaystack.add(txnid);
}
if (searchNeedle.intersection(searchHaystack).isNotEmpty) {
break;
}
}
return i;
}
void _removeEventFromSet(Set<Event> eventSet, Event event) {
eventSet.removeWhere((e) =>
e.matchesEventOrTransactionId(event.eventId) ||
(event.unsigned != null &&
e.matchesEventOrTransactionId(event.unsigned?['transaction_id'])));
}
void addAggregatedEvent(Event event) {
// we want to add an event to the aggregation tree
final relationshipType = event.relationshipType;
final relationshipEventId = event.relationshipEventId;
if (relationshipType == null || relationshipEventId == null) {
return; // nothing to do
}
final events = (aggregatedEvents[relationshipEventId] ??=
<String, Set<Event>>{})[relationshipType] ??= <Event>{};
// remove a potential old event
_removeEventFromSet(events, event);
// add the new one
events.add(event);
if (onChange != null) {
final index = _findEvent(event_id: relationshipEventId);
onChange?.call(index);
}
}
void removeAggregatedEvent(Event event) {
aggregatedEvents.remove(event.eventId);
if (event.unsigned != null) {
aggregatedEvents.remove(event.unsigned?['transaction_id']);
}
for (final types in aggregatedEvents.values) {
for (final events in types.values) {
_removeEventFromSet(events, event);
}
}
}
void _handleEventUpdate(EventUpdate eventUpdate, {bool update = true}) {
try {
if (eventUpdate.roomID != room.id) return;
if (eventUpdate.type != EventUpdateType.timeline &&
eventUpdate.type != EventUpdateType.history) {
return;
}
final status = eventStatusFromInt(eventUpdate.content['status'] ??
(eventUpdate.content['unsigned'] is Map<String, dynamic>
? eventUpdate.content['unsigned'][messageSendingStatusKey]
: null) ??
EventStatus.synced.intValue);
if (status.isRemoved) {
final i = _findEvent(event_id: eventUpdate.content['event_id']);
if (i < events.length) {
removeAggregatedEvent(events[i]);
events.removeAt(i);
onRemove?.call(i);
}
} else {
final i = _findEvent(
event_id: eventUpdate.content['event_id'],
unsigned_txid: eventUpdate.content['unsigned'] is Map
? eventUpdate.content['unsigned']['transaction_id']
: null);
if (i < events.length) {
// if the old status is larger than the new one, we also want to preserve the old status
final oldStatus = events[i].status;
events[i] = Event.fromJson(
eventUpdate.content,
room,
);
// do we preserve the status? we should allow 0 -> -1 updates and status increases
if ((latestEventStatus(status, oldStatus) == oldStatus) &&
!(status.isError && oldStatus.isSending)) {
events[i].status = oldStatus;
}
addAggregatedEvent(events[i]);
onChange?.call(i);
} else {
final newEvent = Event.fromJson(
eventUpdate.content,
room,
);
if (eventUpdate.type == EventUpdateType.history &&
events.indexWhere(
(e) => e.eventId == eventUpdate.content['event_id']) !=
-1) return;
var index = events.length;
if (eventUpdate.type == EventUpdateType.history) {
events.add(newEvent);
} else {
index = events.firstIndexWhereNotError;
events.insert(index, newEvent);
}
onInsert?.call(index);
addAggregatedEvent(newEvent);
}
}
// Handle redaction events
if (eventUpdate.content['type'] == EventTypes.Redaction) {
final index = _findEvent(event_id: eventUpdate.content['redacts']);
if (index < events.length) {
removeAggregatedEvent(events[index]);
// Is the redacted event a reaction? Then update the event this
// belongs to:
if (onChange != null) {
final relationshipEventId = events[index].relationshipEventId;
if (relationshipEventId != null) {
onChange?.call(_findEvent(event_id: relationshipEventId));
}
}
events[index].setRedactionEvent(Event.fromJson(
eventUpdate.content,
room,
));
onChange?.call(index);
}
}
if (update && !_collectHistoryUpdates) {
onUpdate?.call();
}
} catch (e, s) {
Logs().w('Handle event update failed', e, s);
}
}
}
extension on List<Event> {
int get firstIndexWhereNotError {
if (isEmpty) return 0;
final index = indexWhere((event) => !event.status.isError);
if (index == -1) return length;
return index;
}
}

242
lib/src/user.dart Normal file
View file

@ -0,0 +1,242 @@
/*
* Famedly Matrix SDK
* Copyright (C) 2019, 2020, 2021 Famedly GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import '../matrix.dart';
/// Represents a Matrix User which may be a participant in a Matrix Room.
class User extends Event {
factory User(
String id, {
String? membership,
String? displayName,
String? avatarUrl,
required Room room,
}) {
return User.fromState(
stateKey: id,
content: {
if (membership != null) 'membership': membership,
if (displayName != null) 'displayname': displayName,
if (avatarUrl != null) 'avatar_url': avatarUrl,
},
typeKey: EventTypes.RoomMember,
roomId: room.id,
room: room,
originServerTs: DateTime.now(),
);
}
User.fromState({
dynamic prevContent,
required String stateKey,
dynamic content,
required String typeKey,
String eventId = 'fakevent',
String? roomId,
String senderId = 'fakesender',
required DateTime originServerTs,
dynamic unsigned,
required Room room,
}) : super(
stateKey: stateKey,
prevContent: prevContent,
content: content,
type: typeKey,
eventId: eventId,
senderId: senderId,
originServerTs: originServerTs,
unsigned: unsigned,
room: room,
);
/// The full qualified Matrix ID in the format @username:server.abc.
String get id => stateKey ?? '@unknown:unknown';
/// The displayname of the user if the user has set one.
String? get displayName =>
content.tryGet<String>('displayname') ??
prevContent?.tryGet<String>('displayname');
/// Returns the power level of this user.
int get powerLevel => room.getPowerLevelByUserId(id);
/// The membership status of the user. One of:
/// join
/// invite
/// leave
/// ban
Membership get membership => Membership.values.firstWhere((e) {
if (content['membership'] != null) {
return e.toString() == 'Membership.' + content['membership'];
}
return false;
}, orElse: () => Membership.join);
/// The avatar if the user has one.
Uri? get avatarUrl {
final prevContent = this.prevContent;
return content.containsKey('avatar_url')
? (content['avatar_url'] is String
? Uri.tryParse(content['avatar_url'])
: null)
: (prevContent != null && prevContent['avatar_url'] is String
? Uri.tryParse(prevContent['avatar_url'])
: null);
}
/// Returns the displayname or the local part of the Matrix ID if the user
/// has no displayname. If [formatLocalpart] is true, then the localpart will
/// be formatted in the way, that all "_" characters are becomming white spaces and
/// the first character of each word becomes uppercase.
/// If [mxidLocalPartFallback] is true, then the local part of the mxid will be shown
/// if there is no other displayname available. If not then this will return "Unknown user".
String calcDisplayname({
bool? formatLocalpart,
bool? mxidLocalPartFallback,
}) {
formatLocalpart ??= room.client.formatLocalpart;
mxidLocalPartFallback ??= room.client.mxidLocalPartFallback;
final displayName = this.displayName;
if (displayName != null && displayName.isNotEmpty) {
return displayName;
}
final stateKey = this.stateKey;
if (stateKey != null && mxidLocalPartFallback) {
if (!formatLocalpart) {
return stateKey.localpart ?? '';
}
final words = stateKey.localpart?.replaceAll('_', ' ').split(' ') ?? [];
for (var i = 0; i < words.length; i++) {
if (words[i].isNotEmpty) {
words[i] = words[i][0].toUpperCase() + words[i].substring(1);
}
}
return words.join(' ').trim();
}
return 'Unknown user';
}
/// Call the Matrix API to kick this user from this room.
Future<void> kick() async => await room.kick(id);
/// Call the Matrix API to ban this user from this room.
Future<void> ban() async => await room.ban(id);
/// Call the Matrix API to unban this banned user from this room.
Future<void> unban() async => await room.unban(id);
/// Call the Matrix API to change the power level of this user.
Future<void> setPower(int power) async => await room.setPower(id, power);
/// Returns an existing direct chat ID with this user or creates a new one.
/// Returns null on error.
Future<String> startDirectChat({
bool? enableEncryption,
List<StateEvent>? initialState,
bool waitForSync = true,
}) async =>
room.client.startDirectChat(
id,
enableEncryption: enableEncryption,
initialState: initialState,
waitForSync: waitForSync,
);
/// The newest presence of this user if there is any and null if not.
Presence? get presence => room.client.presences[id];
/// Whether the client is able to ban/unban this user.
bool get canBan => room.canBan && powerLevel < room.ownPowerLevel;
/// Whether the client is able to kick this user.
bool get canKick =>
[Membership.join, Membership.invite].contains(membership) &&
room.canKick &&
powerLevel < room.ownPowerLevel;
/// Whether the client is allowed to change the power level of this user.
/// Please be aware that you can only set the power level to at least your own!
bool get canChangePowerLevel =>
room.canChangePowerLevel && powerLevel < room.ownPowerLevel;
@override
bool operator ==(dynamic other) => (other is User &&
other.id == id &&
other.room == room &&
other.membership == membership);
/// Get the mention text to use in a plain text body to mention this specific user
/// in this specific room
String get mention {
// if the displayname has [ or ] or : we can't build our more fancy stuff, so fall back to the id
// [] is used for the delimitors
// If we allowed : we could get collissions with the mxid fallbacks
final displayName = this.displayName;
if (displayName == null ||
displayName.isEmpty ||
{'[', ']', ':'}.any(displayName.contains)) {
return id;
}
final identifier = '@' +
// if we have non-word characters we need to surround with []
(RegExp(r'^\w+$').hasMatch(displayName)
? displayName
: '[$displayName]');
// get all the users with the same display name
final allUsersWithSameDisplayname = room.getParticipants();
allUsersWithSameDisplayname.removeWhere((user) =>
user.id == id ||
(user.displayName?.isEmpty ?? true) ||
user.displayName != displayName);
if (allUsersWithSameDisplayname.isEmpty) {
return identifier;
}
// ok, we have multiple users with the same display name....time to calculate a hash
final hashes = allUsersWithSameDisplayname.map((u) => _hash(u.id));
final ourHash = _hash(id);
// hash collission...just return our own mxid again
if (hashes.contains(ourHash)) {
return id;
}
return '$identifier#$ourHash';
}
/// Get the mention fragments for this user.
Set<String> get mentionFragments {
final displayName = this.displayName;
if (displayName == null ||
displayName.isEmpty ||
{'[', ']', ':'}.any(displayName.contains)) {
return {};
}
final identifier = '@' +
// if we have non-word characters we need to surround with []
(RegExp(r'^\w+$').hasMatch(displayName)
? displayName
: '[$displayName]');
final hash = _hash(id);
return {identifier, '$identifier#$hash'};
}
}
const _maximumHashLength = 10000;
String _hash(String s) =>
(s.codeUnits.fold<int>(0, (a, b) => a + b) % _maximumHashLength).toString();

View file

@ -0,0 +1,237 @@
/*
* Famedly Matrix SDK
* Copyright (C) 2021 Famedly GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import 'dart:async';
import '../../matrix.dart';
extension CommandsClientExtension on Client {
/// Add a command to the command handler. `command` is its name, and `callback` is the
/// callback to invoke
void addCommand(
String command, FutureOr<String?> Function(CommandArgs) callback) {
commands[command.toLowerCase()] = callback;
}
/// Parse and execute a string, `msg` is the input. Optionally `inReplyTo` is the event being
/// replied to and `editEventId` is the eventId of the event being replied to
Future<String?> parseAndRunCommand(Room room, String msg,
{Event? inReplyTo, String? editEventId, String? txid}) async {
final args = CommandArgs(
inReplyTo: inReplyTo,
editEventId: editEventId,
msg: '',
room: room,
txid: txid,
);
if (!msg.startsWith('/')) {
final sendCommand = commands['send'];
if (sendCommand != null) {
args.msg = msg;
return await sendCommand(args);
}
return null;
}
// remove the /
msg = msg.substring(1);
var command = msg;
if (msg.contains(' ')) {
final idx = msg.indexOf(' ');
command = msg.substring(0, idx).toLowerCase();
args.msg = msg.substring(idx + 1);
} else {
command = msg.toLowerCase();
}
final commandOp = commands[command];
if (commandOp != null) {
return await commandOp(args);
}
if (msg.startsWith('/') && commands.containsKey('send')) {
// re-set to include the "command"
final sendCommand = commands['send'];
if (sendCommand != null) {
args.msg = msg;
return await sendCommand(args);
}
}
return null;
}
/// Unregister all commands
void unregisterAllCommands() {
commands.clear();
}
/// Register all default commands
void registerDefaultCommands() {
addCommand('send', (CommandArgs args) async {
return await args.room.sendTextEvent(
args.msg,
inReplyTo: args.inReplyTo,
editEventId: args.editEventId,
parseCommands: false,
txid: args.txid,
);
});
addCommand('me', (CommandArgs args) async {
return await args.room.sendTextEvent(
args.msg,
inReplyTo: args.inReplyTo,
editEventId: args.editEventId,
msgtype: MessageTypes.Emote,
parseCommands: false,
txid: args.txid,
);
});
addCommand('dm', (CommandArgs args) async {
final parts = args.msg.split(' ');
return await args.room.client.startDirectChat(
parts.first,
enableEncryption: !parts.any((part) => part == '--no-encryption'),
);
});
addCommand('create', (CommandArgs args) async {
final parts = args.msg.split(' ');
return await args.room.client.createGroupChat(
enableEncryption: !parts.any((part) => part == '--no-encryption'),
);
});
addCommand('plain', (CommandArgs args) async {
return await args.room.sendTextEvent(
args.msg,
inReplyTo: args.inReplyTo,
editEventId: args.editEventId,
parseMarkdown: false,
parseCommands: false,
txid: args.txid,
);
});
addCommand('html', (CommandArgs args) async {
final event = <String, dynamic>{
'msgtype': 'm.text',
'body': args.msg,
'format': 'org.matrix.custom.html',
'formatted_body': args.msg,
};
return await args.room.sendEvent(
event,
inReplyTo: args.inReplyTo,
editEventId: args.editEventId,
txid: args.txid,
);
});
addCommand('react', (CommandArgs args) async {
final inReplyTo = args.inReplyTo;
if (inReplyTo == null) {
return null;
}
return await args.room.sendReaction(inReplyTo.eventId, args.msg);
});
addCommand('join', (CommandArgs args) async {
await args.room.client.joinRoom(args.msg);
return null;
});
addCommand('leave', (CommandArgs args) async {
await args.room.leave();
return '';
});
addCommand('op', (CommandArgs args) async {
final parts = args.msg.split(' ');
if (parts.isEmpty) {
return null;
}
int? pl;
if (parts.length >= 2) {
pl = int.tryParse(parts[1]);
}
final mxid = parts.first;
return await args.room.setPower(mxid, pl ?? 50);
});
addCommand('kick', (CommandArgs args) async {
final parts = args.msg.split(' ');
await args.room.kick(parts.first);
return '';
});
addCommand('ban', (CommandArgs args) async {
final parts = args.msg.split(' ');
await args.room.ban(parts.first);
return '';
});
addCommand('unban', (CommandArgs args) async {
final parts = args.msg.split(' ');
await args.room.unban(parts.first);
return '';
});
addCommand('invite', (CommandArgs args) async {
final parts = args.msg.split(' ');
await args.room.invite(parts.first);
return '';
});
addCommand('myroomnick', (CommandArgs args) async {
final currentEventJson = args.room
.getState(EventTypes.RoomMember, args.room.client.userID!)
?.content
.copy() ??
{};
currentEventJson['displayname'] = args.msg;
return await args.room.client.setRoomStateWithKey(
args.room.id,
EventTypes.RoomMember,
args.room.client.userID!,
currentEventJson,
);
});
addCommand('myroomavatar', (CommandArgs args) async {
final currentEventJson = args.room
.getState(EventTypes.RoomMember, args.room.client.userID!)
?.content
.copy() ??
{};
currentEventJson['avatar_url'] = args.msg;
return await args.room.client.setRoomStateWithKey(
args.room.id,
EventTypes.RoomMember,
args.room.client.userID!,
currentEventJson,
);
});
addCommand('discardsession', (CommandArgs args) async {
await encryption?.keyManager
.clearOrUseOutboundGroupSession(args.room.id, wipe: true);
return '';
});
addCommand('clearcache', (CommandArgs args) async {
await clearCache();
return '';
});
}
}
class CommandArgs {
String msg;
String? editEventId;
Event? inReplyTo;
Room room;
String? txid;
CommandArgs(
{required this.msg,
this.editEventId,
this.inReplyTo,
required this.room,
this.txid});
}

View file

@ -0,0 +1,29 @@
/*
* Famedly Matrix SDK
* Copyright (C) 2019, 2020, 2021 Famedly GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
export 'native.dart' if (dart.library.js) 'js.dart';
import 'dart:typed_data';
import 'dart:math';
Uint8List secureRandomBytes(int len) {
final rng = Random.secure();
final list = Uint8List(len);
list.setAll(0, Iterable.generate(list.length, (i) => rng.nextInt(256)));
return list;
}

View file

@ -0,0 +1,60 @@
/*
* Famedly Matrix SDK
* Copyright (C) 2019, 2020, 2021 Famedly GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import 'dart:typed_data';
import 'dart:convert';
import 'package:matrix/encryption/utils/base64_unpadded.dart';
import 'crypto.dart';
class EncryptedFile {
EncryptedFile({
required this.data,
required this.k,
required this.iv,
required this.sha256,
});
Uint8List data;
String k;
String iv;
String sha256;
}
Future<EncryptedFile> encryptFile(Uint8List input) async {
final key = secureRandomBytes(32);
final iv = secureRandomBytes(16);
final data = await aesCtr.encrypt(input, key, iv);
final hash = await sha256(data);
return EncryptedFile(
data: data,
k: base64Url.encode(key).replaceAll('=', ''),
iv: base64.encode(iv).replaceAll('=', ''),
sha256: base64.encode(hash).replaceAll('=', ''),
);
}
Future<Uint8List?> decryptFile(EncryptedFile input) async {
if (base64.encode(await sha256(input.data)) !=
base64.normalize(input.sha256)) {
return null;
}
final key = base64decodeUnpadded(base64.normalize(input.k));
final iv = base64decodeUnpadded(base64.normalize(input.iv));
return await aesCtr.encrypt(input.data, key, iv);
}

View file

@ -0,0 +1,123 @@
/*
* Famedly Matrix SDK
* Copyright (C) 2019, 2020, 2021 Famedly GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import 'dart:ffi';
import 'dart:io';
final libcrypto = Platform.isIOS
? DynamicLibrary.process()
: DynamicLibrary.open(Platform.isAndroid
? 'libcrypto.so'
: Platform.isWindows
? 'libcrypto.dll'
: Platform.isMacOS
? 'libcrypto.1.1.dylib'
: 'libcrypto.so.1.1');
final PKCS5_PBKDF2_HMAC = libcrypto.lookupFunction<
IntPtr Function(
Pointer<Uint8> pass,
IntPtr passlen,
Pointer<Uint8> salt,
IntPtr saltlen,
IntPtr iter,
Pointer<NativeType> digest,
IntPtr keylen,
Pointer<Uint8> out),
int Function(
Pointer<Uint8> pass,
int passlen,
Pointer<Uint8> salt,
int saltlen,
int iter,
Pointer<NativeType> digest,
int keylen,
Pointer<Uint8> out)>('PKCS5_PBKDF2_HMAC');
final EVP_sha1 = libcrypto.lookupFunction<Pointer<NativeType> Function(),
Pointer<NativeType> Function()>('EVP_sha1');
final EVP_sha256 = libcrypto.lookupFunction<Pointer<NativeType> Function(),
Pointer<NativeType> Function()>('EVP_sha256');
final EVP_sha512 = libcrypto.lookupFunction<Pointer<NativeType> Function(),
Pointer<NativeType> Function()>('EVP_sha512');
final EVP_aes_128_ctr = libcrypto.lookupFunction<Pointer<NativeType> Function(),
Pointer<NativeType> Function()>('EVP_aes_128_ctr');
final EVP_aes_256_ctr = libcrypto.lookupFunction<Pointer<NativeType> Function(),
Pointer<NativeType> Function()>('EVP_aes_256_ctr');
final EVP_CIPHER_CTX_new = libcrypto.lookupFunction<
Pointer<NativeType> Function(),
Pointer<NativeType> Function()>('EVP_CIPHER_CTX_new');
final EVP_EncryptInit_ex = libcrypto.lookupFunction<
Pointer<NativeType> Function(
Pointer<NativeType> ctx,
Pointer<NativeType> alg,
Pointer<NativeType> some,
Pointer<Uint8> key,
Pointer<Uint8> iv),
Pointer<NativeType> Function(
Pointer<NativeType> ctx,
Pointer<NativeType> alg,
Pointer<NativeType> some,
Pointer<Uint8> key,
Pointer<Uint8> iv)>('EVP_EncryptInit_ex');
final EVP_EncryptUpdate = libcrypto.lookupFunction<
Pointer<NativeType> Function(Pointer<NativeType> ctx, Pointer<Uint8> output,
Pointer<IntPtr> outputLen, Pointer<Uint8> input, IntPtr inputLen),
Pointer<NativeType> Function(
Pointer<NativeType> ctx,
Pointer<Uint8> output,
Pointer<IntPtr> outputLen,
Pointer<Uint8> input,
int inputLen)>('EVP_EncryptUpdate');
final EVP_EncryptFinal_ex = libcrypto.lookupFunction<
Pointer<NativeType> Function(
Pointer<NativeType> ctx, Pointer<Uint8> data, Pointer<IntPtr> len),
Pointer<NativeType> Function(Pointer<NativeType> ctx, Pointer<Uint8> data,
Pointer<IntPtr> len)>('EVP_EncryptFinal_ex');
final EVP_CIPHER_CTX_free = libcrypto.lookupFunction<
Pointer<NativeType> Function(Pointer<NativeType> ctx),
Pointer<NativeType> Function(
Pointer<NativeType> ctx)>('EVP_CIPHER_CTX_free');
final EVP_Digest = libcrypto.lookupFunction<
IntPtr Function(
Pointer<Uint8> data,
IntPtr len,
Pointer<Uint8> hash,
Pointer<IntPtr> hsize,
Pointer<NativeType> alg,
Pointer<NativeType> engine),
int Function(
Pointer<Uint8> data,
int len,
Pointer<Uint8> hash,
Pointer<IntPtr> hsize,
Pointer<NativeType> alg,
Pointer<NativeType> engine)>('EVP_Digest');
final EVP_MD_size = libcrypto.lookupFunction<
IntPtr Function(Pointer<NativeType> ctx),
int Function(Pointer<NativeType> ctx)>('EVP_MD_size');

View file

@ -0,0 +1,64 @@
// Copyright (c) 2020 Famedly GmbH
// SPDX-License-Identifier: AGPL-3.0-or-later
import 'dart:typed_data';
import 'subtle.dart';
import 'subtle.dart' as subtle;
abstract class Hash {
Hash._(this.name);
String name;
Future<Uint8List> call(Uint8List input) async =>
Uint8List.view(await digest(name, input));
}
final Hash sha1 = _Sha1();
final Hash sha256 = _Sha256();
final Hash sha512 = _Sha512();
class _Sha1 extends Hash {
_Sha1() : super._('SHA-1');
}
class _Sha256 extends Hash {
_Sha256() : super._('SHA-256');
}
class _Sha512 extends Hash {
_Sha512() : super._('SHA-512');
}
abstract class Cipher {
Cipher._(this.name);
String name;
Object params(Uint8List iv);
Future<Uint8List> encrypt(
Uint8List input, Uint8List key, Uint8List iv) async {
final subtleKey = await importKey('raw', key, name, false, ['encrypt']);
return (await subtle.encrypt(params(iv), subtleKey, input)).asUint8List();
}
}
final Cipher aesCtr = _AesCtr();
class _AesCtr extends Cipher {
_AesCtr() : super._('AES-CTR');
@override
Object params(Uint8List iv) =>
AesCtrParams(name: name, counter: iv, length: 64);
}
Future<Uint8List> pbkdf2(Uint8List passphrase, Uint8List salt, Hash hash,
int iterations, int bits) async {
final raw =
await importKey('raw', passphrase, 'PBKDF2', false, ['deriveBits']);
final res = await deriveBits(
Pbkdf2Params(
name: 'PBKDF2', hash: hash.name, salt: salt, iterations: iterations),
raw,
bits);
return Uint8List.view(res);
}

View file

@ -0,0 +1,102 @@
import 'dart:async';
import 'dart:typed_data';
import 'dart:ffi';
import 'package:ffi/ffi.dart';
import 'ffi.dart';
abstract class Hash {
Hash._(this.ptr);
Pointer<NativeType> ptr;
FutureOr<Uint8List> call(Uint8List data) {
final outSize = EVP_MD_size(ptr);
final mem = malloc.call<Uint8>(outSize + data.length);
final dataMem = mem.elementAt(outSize);
try {
dataMem.asTypedList(data.length).setAll(0, data);
EVP_Digest(dataMem, data.length, mem, nullptr, ptr, nullptr);
return Uint8List.fromList(mem.asTypedList(outSize));
} finally {
malloc.free(mem);
}
}
}
final Hash sha1 = _Sha1();
final Hash sha256 = _Sha256();
final Hash sha512 = _Sha512();
class _Sha1 extends Hash {
_Sha1() : super._(EVP_sha1());
}
class _Sha256 extends Hash {
_Sha256() : super._(EVP_sha256());
}
class _Sha512 extends Hash {
_Sha512() : super._(EVP_sha512());
}
abstract class Cipher {
Cipher._();
Pointer<NativeType> getAlg(int keysize);
FutureOr<Uint8List> encrypt(Uint8List input, Uint8List key, Uint8List iv) {
final alg = getAlg(key.length * 8);
final mem = malloc
.call<Uint8>(sizeOf<IntPtr>() + key.length + iv.length + input.length);
final lenMem = mem.cast<IntPtr>();
final keyMem = mem.elementAt(sizeOf<IntPtr>());
final ivMem = keyMem.elementAt(key.length);
final dataMem = ivMem.elementAt(iv.length);
try {
keyMem.asTypedList(key.length).setAll(0, key);
ivMem.asTypedList(iv.length).setAll(0, iv);
dataMem.asTypedList(input.length).setAll(0, input);
final ctx = EVP_CIPHER_CTX_new();
EVP_EncryptInit_ex(ctx, alg, nullptr, keyMem, ivMem);
EVP_EncryptUpdate(ctx, dataMem, lenMem, dataMem, input.length);
EVP_EncryptFinal_ex(ctx, dataMem.elementAt(lenMem.value), lenMem);
EVP_CIPHER_CTX_free(ctx);
return Uint8List.fromList(dataMem.asTypedList(input.length));
} finally {
malloc.free(mem);
}
}
}
final Cipher aesCtr = _AesCtr();
class _AesCtr extends Cipher {
_AesCtr() : super._();
@override
Pointer<NativeType> getAlg(int keysize) {
switch (keysize) {
case 128:
return EVP_aes_128_ctr();
case 256:
return EVP_aes_256_ctr();
default:
throw ArgumentError('invalid key size');
}
}
}
FutureOr<Uint8List> pbkdf2(
Uint8List passphrase, Uint8List salt, Hash hash, int iterations, int bits) {
final outLen = bits ~/ 8;
final mem = malloc.call<Uint8>(passphrase.length + salt.length + outLen);
final saltMem = mem.elementAt(passphrase.length);
final outMem = saltMem.elementAt(salt.length);
try {
mem.asTypedList(passphrase.length).setAll(0, passphrase);
saltMem.asTypedList(salt.length).setAll(0, salt);
PKCS5_PBKDF2_HMAC(mem, passphrase.length, saltMem, salt.length, iterations,
hash.ptr, outLen, outMem);
return Uint8List.fromList(outMem.asTypedList(outLen));
} finally {
malloc.free(mem);
}
}

View file

@ -0,0 +1,93 @@
// Copyright (c) 2020 Famedly GmbH
// SPDX-License-Identifier: AGPL-3.0-or-later
@JS()
library subtle;
import 'package:js/js.dart';
import 'dart:async';
import 'dart:js_util';
import 'dart:typed_data';
@JS()
@anonymous
class Pbkdf2Params {
external factory Pbkdf2Params({
String name,
String hash,
Uint8List salt,
int iterations,
});
String? name;
String? hash;
Uint8List? salt;
int? iterations;
}
@JS()
@anonymous
class AesCtrParams {
external factory AesCtrParams({
String name,
Uint8List counter,
int length,
});
String? name;
Uint8List? counter;
int? length;
}
@JS('crypto.subtle.encrypt')
external dynamic _encrypt(dynamic algorithm, dynamic key, Uint8List data);
Future<ByteBuffer> encrypt(dynamic algorithm, dynamic key, Uint8List data) {
return promiseToFuture(_encrypt(algorithm, key, data));
}
@JS('crypto.subtle.decrypt')
external dynamic _decrypt(dynamic algorithm, dynamic key, Uint8List data);
Future<ByteBuffer> decrypt(dynamic algorithm, dynamic key, Uint8List data) {
return promiseToFuture(_decrypt(algorithm, key, data));
}
@JS('crypto.subtle.importKey')
external dynamic _importKey(String format, dynamic keyData, dynamic algorithm,
bool extractable, List<String> keyUsages);
Future<dynamic> importKey(String format, dynamic keyData, dynamic algorithm,
bool extractable, List<String> keyUsages) {
return promiseToFuture(
_importKey(format, keyData, algorithm, extractable, keyUsages));
}
@JS('crypto.subtle.exportKey')
external dynamic _exportKey(String algorithm, dynamic key);
Future<dynamic> exportKey(String algorithm, dynamic key) {
return promiseToFuture(_exportKey(algorithm, key));
}