pax_global_header 0000666 0000000 0000000 00000000064 14705742554 0014527 g ustar 00root root 0000000 0000000 52 comment=0c86beaef4d36a7719f982de4a2619536a1e5734
slixmpp-omemo-1.2.2/ 0000775 0000000 0000000 00000000000 14705742554 0014337 5 ustar 00root root 0000000 0000000 slixmpp-omemo-1.2.2/.flake8 0000664 0000000 0000000 00000000240 14705742554 0015506 0 ustar 00root root 0000000 0000000 [flake8]
max-line-length = 110
doctests = True
ignore = E201,E202,W503
per-file-ignores =
slixmpp_omemo/project.py:E203
slixmpp_omemo/__init__.py:F401
slixmpp-omemo-1.2.2/.github/ 0000775 0000000 0000000 00000000000 14705742554 0015677 5 ustar 00root root 0000000 0000000 slixmpp-omemo-1.2.2/.github/workflows/ 0000775 0000000 0000000 00000000000 14705742554 0017734 5 ustar 00root root 0000000 0000000 slixmpp-omemo-1.2.2/.github/workflows/test-and-publish.yml 0000664 0000000 0000000 00000003736 14705742554 0023653 0 ustar 00root root 0000000 0000000 name: Test & Publish
on: [push, pull_request]
permissions:
contents: read
jobs:
test:
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
python-version: ["3.9", "3.10", "3.11", "3.12", "3.13", "pypy-3.10"]
steps:
- uses: actions/checkout@v4
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python-version }}
- name: Update pip
run: python -m pip install --upgrade pip
- name: Build and install slixmpp-omemo
run: pip install .
- name: Install test dependencies
run: |
pip install --upgrade pytest pytest-asyncio pytest-cov mypy pylint flake8 setuptools
- name: Type-check using mypy
run: mypy --strict --disable-error-code str-bytes-safe --untyped-calls-exclude=slixmpp slixmpp_omemo/ setup.py examples/ tests/
- name: Lint using pylint
run: pylint slixmpp_omemo/ setup.py examples/ tests/
- name: Format-check using Flake8
run: flake8 slixmpp_omemo/ setup.py examples/ tests/
- name: Test using pytest
run: pytest --cov=slixmpp_omemo --cov-report term-missing:skip-covered
build:
name: Build source distribution and wheel
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Build source distribution and wheel
run: python3 setup.py sdist bdist_wheel
- uses: actions/upload-artifact@v4
with:
name: dist
path: |
dist/*.tar.gz
dist/*.whl
publish:
needs: [test, build]
runs-on: ubuntu-latest
permissions:
id-token: write
if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v')
steps:
- uses: actions/download-artifact@v4
with:
path: dist
merge-multiple: true
- name: Publish package distributions to PyPI
uses: pypa/gh-action-pypi-publish@release/v1
slixmpp-omemo-1.2.2/.gitignore 0000664 0000000 0000000 00000000147 14705742554 0016331 0 ustar 00root root 0000000 0000000 dist/
slixmpp_omemo.egg-info/
__pycache__/
.pytest_cache/
.mypy_cache/
.coverage
build/
docs/_build/
slixmpp-omemo-1.2.2/.readthedocs.yaml 0000664 0000000 0000000 00000000333 14705742554 0017565 0 ustar 00root root 0000000 0000000 version: 2
build:
os: ubuntu-lts-latest
tools:
python: "3"
sphinx:
configuration: docs/conf.py
fail_on_warning: true
python:
install:
- requirements: docs/requirements.txt
- method: pip
path: .
slixmpp-omemo-1.2.2/CHANGELOG.md 0000664 0000000 0000000 00000003715 14705742554 0016156 0 ustar 00root root 0000000 0000000 # Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [Unreleased]
## [1.2.2] - 22nd of October, 2024
### Changed
- Attempt device list download with max_items before falling back to full download
## [1.2.1] - 19th of October, 2024
### Fixed
- Handle groupchat messages in `decrypt_message`
## [1.2.0] - 15th of October, 2024
### Changed
- Drop support for Python3.8, add support for Python3.13, bump PyPy test version to 3.10
- Internal housekeeping, mostly related to pylint
## [1.1.1] - 8th of October, 2024
### Fixed
- Load the twomemo backend even though SCE is not supported
- Treat malformed device list as empty instead of an unrecoverable error
- Try uploading the twomemo bundle again without MAX_ITEMS if that option is not supported
## [1.1.0] - 7th of October, 2024
### Added
- Emit an event when OMEMO has initialized
- Manually subscribe to device list nodes of contacts without working PEP updates (i.e. missing presence subscription)
### Fixed
- Use only strings for data form values used in pubsub publish options and node configuration
- Ignore messages without body in the echo bot example
- Allow passing text content to the echo bot example's `encrypted_reply` method as advertized
## [1.0.0] - 26th of July, 2024
### Added
- Initial release
[Unreleased]: https://github.com/Syndace/slixmpp-omemo/compare/v1.2.2...HEAD
[1.2.2]: https://github.com/Syndace/slixmpp-omemo/compare/v1.2.1...v1.2.2
[1.2.1]: https://github.com/Syndace/slixmpp-omemo/compare/v1.2.0...v1.2.1
[1.2.0]: https://github.com/Syndace/slixmpp-omemo/compare/v1.1.1...v1.2.0
[1.1.1]: https://github.com/Syndace/slixmpp-omemo/compare/v1.1.0...v1.1.1
[1.1.0]: https://github.com/Syndace/slixmpp-omemo/compare/v1.0.0...v1.1.0
[1.0.0]: https://github.com/Syndace/slixmpp-omemo/releases/tag/v1.0.0
slixmpp-omemo-1.2.2/LICENSE 0000664 0000000 0000000 00000103333 14705742554 0015347 0 ustar 00root root 0000000 0000000 GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc.
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.
Copyright (C)
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 .
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
.
slixmpp-omemo-1.2.2/MANIFEST.in 0000664 0000000 0000000 00000000037 14705742554 0016075 0 ustar 00root root 0000000 0000000 include slixmpp_omemo/py.typed
slixmpp-omemo-1.2.2/README.md 0000664 0000000 0000000 00000004773 14705742554 0015631 0 ustar 00root root 0000000 0000000 [](https://pypi.org/project/slixmpp_omemo/)
[](https://pypi.org/project/slixmpp_omemo/)
[](https://github.com/Syndace/slixmpp-omemo/actions/workflows/test-and-publish.yml)
[](https://slixmpp-omemo.readthedocs.io/)
# slixmpp-omemo - Slixmpp OMEMO plugin #
A plugin for slixmpp offering the [OMEMO Multi-End Message and Object Encryption protocol](https://xmpp.org/extensions/xep-0384.html), based on [python-omemo](https://github.com/Syndace/python-omemo).
## OMEMO protocol version support ##
Currently supports OMEMO in the `eu.siacs.conversations.axolotl` namespace.
Support for OMEMO in the `omemo:2` namespace is prepared and will be enabled as soon as Slixmpp gains support for [XEP-0420: Stanza Content Encryption](https://xmpp.org/extensions/xep-0420.html).
## Trust ##
Supports [Blind Trust Before Verification](https://gultsch.de/trust.html) and manual trust management.
## Installation ##
Install the latest release using pip (`pip install slixmpp_omemo`) or manually from source by running `pip install .` in the cloned repository.
## Testing, Type Checks and Linting ##
slixmpp-omemo uses [pytest](https://docs.pytest.org/en/latest/) as its testing framework, [mypy](http://mypy-lang.org/) for static type checks and both [pylint](https://pylint.pycqa.org/en/latest/) and [Flake8](https://flake8.pycqa.org/en/latest/) for linting. All tests/checks can be run locally with the following commands:
```sh
$ pip install --upgrade pytest pytest-asyncio pytest-cov mypy pylint flake8
$ mypy --strict --disable-error-code str-bytes-safe --untyped-calls-exclude=slixmpp slixmpp_omemo/ setup.py examples/ tests/
$ pylint slixmpp_omemo/ setup.py examples/ tests/
$ flake8 slixmpp_omemo/ setup.py examples/ tests/
$ pytest --cov=slixmpp_omemo --cov-report term-missing:skip-covered
```
## Getting Started ##
Refer to the documentation on [readthedocs.io](https://slixmpp-omemo.readthedocs.io/), or build/view it locally in the `docs/` directory. To build the docs locally, install the requirements listed in `docs/requirements.txt`, e.g. using `pip install -r docs/requirements.txt`, and then run `make html` from within the `docs/` directory. The documentation can then be found in `docs/_build/html/`.
slixmpp-omemo-1.2.2/docs/ 0000775 0000000 0000000 00000000000 14705742554 0015267 5 ustar 00root root 0000000 0000000 slixmpp-omemo-1.2.2/docs/Makefile 0000664 0000000 0000000 00000001143 14705742554 0016726 0 ustar 00root root 0000000 0000000 # Minimal makefile for Sphinx documentation
#
# You can set these variables from the command line.
SPHINXOPTS =
SPHINXBUILD = sphinx-build
SPHINXPROJ = slixmpp-omemo
SOURCEDIR = .
BUILDDIR = _build
# Put it first so that "make" without argument is like "make help".
help:
@$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
.PHONY: help Makefile
# Catch-all target: route all unknown targets to Sphinx using the new
# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
%: Makefile
@$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
slixmpp-omemo-1.2.2/docs/_static/ 0000775 0000000 0000000 00000000000 14705742554 0016715 5 ustar 00root root 0000000 0000000 slixmpp-omemo-1.2.2/docs/_static/.gitkeep 0000664 0000000 0000000 00000000000 14705742554 0020334 0 ustar 00root root 0000000 0000000 slixmpp-omemo-1.2.2/docs/conf.py 0000664 0000000 0000000 00000006472 14705742554 0016577 0 ustar 00root root 0000000 0000000 # Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a full list see
# the documentation:
# http://www.sphinx-doc.org/en/master/config
# -- Path setup --------------------------------------------------------------------------
# If extensions (or modules to document with autodoc) are in another directory, add these
# directories to sys.path here. If the directory is relative to the documentation root,
# use os.path.abspath to make it absolute, like shown here.
import os
import sys
this_file_path = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.join(this_file_path, "..", "slixmpp_omemo"))
from version import __version__ as __version
from project import project as __project
# -- Project information -----------------------------------------------------------------
project = __project["name"]
author = __project["author"]
copyright = f"{__project['year']}, {__project['author']}"
# The short X.Y version
version = __version["short"]
# The full version, including alpha/beta/rc tags
release = __version["full"]
# -- General configuration ---------------------------------------------------------------
# Add any Sphinx extension module names here, as strings. They can be extensions coming
# with Sphinx (named "sphinx.ext.*") or your custom ones.
extensions = [
"sphinx.ext.autodoc",
"sphinx.ext.viewcode",
"sphinx.ext.napoleon",
"sphinx_autodoc_typehints"
]
# Add any paths that contain templates here, relative to this directory.
templates_path = [ "_templates" ]
# List of patterns, relative to source directory, that match files and directories to
# ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path.
exclude_patterns = [ "_build", "Thumbs.db", ".DS_Store" ]
# -- Options for HTML output -------------------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for a list of
# builtin themes.
html_theme = "sphinx_rtd_theme"
# Add any paths that contain custom static files (such as style sheets) here, relative to
# this directory. They are copied after the builtin static files, so a file named
# "default.css" will overwrite the builtin "default.css".
html_static_path = [ "_static" ]
# -- Autodoc Configuration ---------------------------------------------------------------
# The following two options seem to be ignored...
autodoc_typehints = "description"
autodoc_type_aliases = { type_alias: f"{type_alias}" for type_alias in {
} }
def autodoc_skip_member_handler(app, what, name, obj, skip, options):
# Skip private members, i.e. those that start with double underscores but do not end in underscores
if name.startswith("__") and not name.endswith("_"):
return True
# Could be achieved using exclude-members, but this is more comfy
if name in {
"__abstractmethods__",
"__annotations__",
"__dict__",
"__module__",
"__new__",
"__weakref__",
"_abc_impl"
}: return True
# Skip __init__s without documentation. Those are just used for type hints.
if name == "__init__" and obj.__doc__ is None:
return True
return None
def setup(app):
app.connect("autodoc-skip-member", autodoc_skip_member_handler)
slixmpp-omemo-1.2.2/docs/getting_started.rst 0000664 0000000 0000000 00000001510 14705742554 0021205 0 ustar 00root root 0000000 0000000 Getting Started
===============
To use the plugin, some customization is required first. For an example, see `examples/echo_client.py`.
Storage
-------
First, you have to prepare the storage backend for the OMEMO plugin to use. Refer to the
`official documentation `__
for details.
The plugin: XEP_0384
--------------------
Next, create a subclass of :class:`~slixmpp_omemo.xep_0384.XEP_0384` and fill out the abstract methods. Those allow you to provide
your prepared storage implementation to the plugin, tell the plugin whether BTBV is enabled and handle certain
trust-related events.
With your plugin implementation prepared, you can now register your customized plugin with Slixmpp using its
:func:`slixmpp.plugins.register_plugin` function.
slixmpp-omemo-1.2.2/docs/index.rst 0000664 0000000 0000000 00000001417 14705742554 0017133 0 ustar 00root root 0000000 0000000 slixmpp-omemo - Slixmpp OMEMO plugin
====================================
A plugin for slixmpp offering the `OMEMO Multi-End Message and Object Encryption protocol `__.
OMEMO protocol version support
------------------------------
Currently supports OMEMO in the `eu.siacs.conversations.axolotl` namespace. Support for OMEMO in the `omemo:2`
namespace is prepared and will be enabled as soon as Slixmpp gains support for
`XEP-0420: Stanza Content Encryption `__.
Trust
-----
Supports `Blind Trust Before Verification `__ and manual trust management.
.. toctree::
installation
getting_started
migration
API Documentation
slixmpp-omemo-1.2.2/docs/installation.rst 0000664 0000000 0000000 00000000257 14705742554 0020526 0 ustar 00root root 0000000 0000000 Installation
============
Install the latest release using pip (``pip install slixmpp_omemo``) or manually from source by running ``pip install .`` in the cloned repository.
slixmpp-omemo-1.2.2/docs/make.bat 0000664 0000000 0000000 00000001461 14705742554 0016676 0 ustar 00root root 0000000 0000000 @ECHO OFF
pushd %~dp0
REM Command file for Sphinx documentation
if "%SPHINXBUILD%" == "" (
set SPHINXBUILD=sphinx-build
)
set SOURCEDIR=.
set BUILDDIR=_build
set SPHINXPROJ=slixmpp-omemo
if "%1" == "" goto help
%SPHINXBUILD% >NUL 2>NUL
if errorlevel 9009 (
echo.
echo.The 'sphinx-build' command was not found. Make sure you have Sphinx
echo.installed, then set the SPHINXBUILD environment variable to point
echo.to the full path of the 'sphinx-build' executable. Alternatively you
echo.may add the Sphinx directory to PATH.
echo.
echo.If you don't have Sphinx installed, grab it from
echo.http://sphinx-doc.org/
exit /b 1
)
%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS%
goto end
:help
%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS%
:end
popd
slixmpp-omemo-1.2.2/docs/migration.rst 0000664 0000000 0000000 00000000051 14705742554 0020006 0 ustar 00root root 0000000 0000000 .. _migration:
Migration
=========
WIP
slixmpp-omemo-1.2.2/docs/requirements.txt 0000664 0000000 0000000 00000000061 14705742554 0020550 0 ustar 00root root 0000000 0000000 sphinx
sphinx-rtd-theme
sphinx-autodoc-typehints
slixmpp-omemo-1.2.2/docs/slixmpp_omemo/ 0000775 0000000 0000000 00000000000 14705742554 0020157 5 ustar 00root root 0000000 0000000 slixmpp-omemo-1.2.2/docs/slixmpp_omemo/base_session_manager.rst 0000664 0000000 0000000 00000000357 14705742554 0025065 0 ustar 00root root 0000000 0000000 Module: base_session_manager
============================
.. automodule:: slixmpp_omemo.base_session_manager
:members:
:special-members:
:private-members:
:undoc-members:
:member-order: bysource
:show-inheritance:
slixmpp-omemo-1.2.2/docs/slixmpp_omemo/migrations.rst 0000664 0000000 0000000 00000000321 14705742554 0023061 0 ustar 00root root 0000000 0000000 Module: migrations
==================
.. automodule:: slixmpp_omemo.migrations
:members:
:special-members:
:private-members:
:undoc-members:
:member-order: bysource
:show-inheritance:
slixmpp-omemo-1.2.2/docs/slixmpp_omemo/package.rst 0000664 0000000 0000000 00000000270 14705742554 0022303 0 ustar 00root root 0000000 0000000 Package: slixmpp_omemo
======================
.. toctree::
Module: base_session_manager
Module: migrations
Module: xep_0384
slixmpp-omemo-1.2.2/docs/slixmpp_omemo/xep_0384.rst 0000664 0000000 0000000 00000000313 14705742554 0022160 0 ustar 00root root 0000000 0000000 Module: xep_0384
================
.. automodule:: slixmpp_omemo.xep_0384
:members:
:special-members:
:private-members:
:undoc-members:
:member-order: bysource
:show-inheritance:
slixmpp-omemo-1.2.2/examples/ 0000775 0000000 0000000 00000000000 14705742554 0016155 5 ustar 00root root 0000000 0000000 slixmpp-omemo-1.2.2/examples/echo_client.py 0000664 0000000 0000000 00000021721 14705742554 0021006 0 ustar 00root root 0000000 0000000 from argparse import ArgumentParser
from getpass import getpass
import json
import logging
import sys
from typing import Any, Dict, FrozenSet, Literal, Optional, Union
from omemo.storage import Just, Maybe, Nothing, Storage
from omemo.types import DeviceInformation, JSONType
from slixmpp.clientxmpp import ClientXMPP
from slixmpp.jid import JID
from slixmpp.plugins import register_plugin # type: ignore[attr-defined]
from slixmpp.stanza import Message
from slixmpp.xmlstream.handler import CoroutineCallback
from slixmpp.xmlstream.matcher import MatchXPath
from slixmpp_omemo import TrustLevel, XEP_0384
log = logging.getLogger(__name__)
class StorageImpl(Storage):
"""
Example storage implementation that stores all data in a single JSON file.
"""
JSON_FILE = "/home/syndace/omemo-echo-client.json"
def __init__(self) -> None:
super().__init__()
self.__data: Dict[str, JSONType] = {}
try:
with open(self.JSON_FILE, encoding="utf8") as f:
self.__data = json.load(f)
except Exception: # pylint: disable=broad-exception-caught
pass
async def _load(self, key: str) -> Maybe[JSONType]:
if key in self.__data:
return Just(self.__data[key])
return Nothing()
async def _store(self, key: str, value: JSONType) -> None:
self.__data[key] = value
with open(self.JSON_FILE, "w", encoding="utf8") as f:
json.dump(self.__data, f)
async def _delete(self, key: str) -> None:
self.__data.pop(key, None)
with open(self.JSON_FILE, "w", encoding="utf8") as f:
json.dump(self.__data, f)
class XEP_0384Impl(XEP_0384): # pylint: disable=invalid-name
"""
Example implementation of the OMEMO plugin for Slixmpp.
"""
def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=redefined-outer-name
super().__init__(*args, **kwargs)
# Just the type definition here
self.__storage: Storage
def plugin_init(self) -> None:
self.__storage = StorageImpl()
super().plugin_init()
@property
def storage(self) -> Storage:
return self.__storage
@property
def _btbv_enabled(self) -> bool:
return True
async def _devices_blindly_trusted(
self,
blindly_trusted: FrozenSet[DeviceInformation],
identifier: Optional[str]
) -> None:
log.info(f"[{identifier}] Devices trusted blindly: {blindly_trusted}")
async def _prompt_manual_trust(
self,
manually_trusted: FrozenSet[DeviceInformation],
identifier: Optional[str]
) -> None:
# Since BTBV is enabled and we don't do any manual trust adjustments in the example, this method
# should never be called. All devices should be automatically trusted blindly by BTBV.
# To show how a full implementation could look like, the following code will prompt for a trust
# decision using `input`:
session_mananger = await self.get_session_manager()
for device in manually_trusted:
while True:
answer = input(f"[{identifier}] Trust the following device? (yes/no) {device}")
if answer in { "yes", "no" }:
await session_mananger.set_trust(
device.bare_jid,
device.identity_key,
TrustLevel.TRUSTED.value if answer == "yes" else TrustLevel.DISTRUSTED.value
)
break
print("Please answer yes or no.")
register_plugin(XEP_0384Impl)
class OmemoEchoClient(ClientXMPP):
"""
A simple Slixmpp bot that will echo encrypted messages it receives, along with a short thank you message.
For details on how to build a client with Slixmpp, look at examples in the Slixmpp repository.
"""
def __init__(self, jid: str, password: str) -> None:
super().__init__(jid, password)
self.add_event_handler("session_start", self.start)
self.register_handler(CoroutineCallback(
"Messages",
MatchXPath(f"{{{self.default_ns}}}message"),
self.message_handler # type: ignore[arg-type]
))
def start(self, _event: Any) -> None:
"""
Process the session_start event.
Typical actions for the session_start event are requesting the roster and broadcasting an initial
presence stanza.
Args:
event: An empty dictionary. The session_start event does not provide any additional data.
"""
self.send_presence()
self.get_roster() # type: ignore[no-untyped-call]
async def message_handler(self, stanza: Message) -> None:
"""
Process incoming message stanzas. Be aware that this also includes MUC messages and error messages. It
is usually a good idea to check the messages's type before processing or sending replies.
Args:
msg: The received message stanza. See the documentation for stanza objects and the Message stanza
to see how it may be used.
"""
xep_0384: XEP_0384 = self["xep_0384"]
mto = stanza["from"]
mtype = stanza["type"]
if mtype not in { "chat", "normal" }:
return
namespace = xep_0384.is_encrypted(stanza)
if namespace is None:
if not stanza["body"]:
# This is the case for things like read markers, ignore those.
return
self.plain_reply(
mto,
mtype,
f"Unencrypted message or unsupported message encryption: {stanza['body']}"
)
return
log.debug(f"Message in namespace {namespace} received: {stanza}")
try:
message, device_information = await xep_0384.decrypt_message(stanza)
log.debug(f"Information about sender: {device_information}")
if not message["body"]:
# This is the case for things like read markers, ignore those.
return
await self.encrypted_reply(mto, mtype, message)
except Exception as e: # pylint: disable=broad-exception-caught
self.plain_reply(mto, mtype, f"Error {type(e).__name__}: {e}")
def plain_reply(self, mto: JID, mtype: Literal["chat", "normal"], reply: str) -> None:
"""
Helper to reply with plain messages.
Args:
mto: The recipient JID.
mtype: The message type.
reply: The text content of the reply.
"""
stanza = self.make_message(mto=mto, mtype=mtype)
stanza["body"] = reply
stanza.send()
async def encrypted_reply(
self,
mto: JID,
mtype: Literal["chat", "normal"],
reply: Union[Message, str]
) -> None:
"""
Helper to reply with encrypted messages.
Args:
mto: The recipient JID.
mtype: The message type.
reply: Either the message stanza to encrypt and reply with, or the text content of the reply.
"""
xep_0384: XEP_0384 = self["xep_0384"]
if isinstance(reply, str):
reply_body = reply
reply = self.make_message(mto=mto, mtype=mtype)
reply["body"] = reply_body
reply.set_to(mto)
reply.set_from(self.boundjid)
# It might be a good idea to strip everything bot the body from the stanza, since some things might
# break when echoed.
messages, encryption_errors = await xep_0384.encrypt_message(reply, mto)
if len(encryption_errors) > 0:
log.info(f"There were non-critical errors during encryption: {encryption_errors}")
for namespace, message in messages.items():
message["eme"]["namespace"] = namespace
message["eme"]["name"] = self["xep_0380"].mechanisms[namespace]
message.send()
if __name__ == "__main__":
# Set up the command line argument parser
parser = ArgumentParser(description=OmemoEchoClient.__doc__)
parser.add_argument("-u", "--username", dest="username", help="account username (JID)")
parser.add_argument("-p", "--password", dest="password", help="account password")
args = parser.parse_args()
# Ask for username and password if not supplied via cli args
if args.username is None:
args.username = input("Username: ")
if args.password is None:
args.password = getpass("Password: ")
# Setup the OmemoEchoClient and register plugins. Note that while plugins may have interdependencies, the
# order in which you register them does not matter.
xmpp = OmemoEchoClient(args.username, args.password)
xmpp.register_plugin("xep_0199") # XMPP Ping
xmpp.register_plugin("xep_0380") # Explicit Message Encryption
xmpp.register_plugin("xep_0384", module=sys.modules[__name__]) # OMEMO
# Connect to the XMPP server and start processing XMPP stanzas.
xmpp.connect()
xmpp.process() # type: ignore[no-untyped-call]
slixmpp-omemo-1.2.2/pylintrc 0000664 0000000 0000000 00000051506 14705742554 0016135 0 ustar 00root root 0000000 0000000 [MAIN]
# Analyse import fallback blocks. This can be used to support both Python 2 and
# 3 compatible code, which means that the block might have code that exists
# only in one or another interpreter, leading to false positives when analysed.
analyse-fallback-blocks=yes
# Clear in-memory caches upon conclusion of linting. Useful if running pylint
# in a server-like mode.
clear-cache-post-run=no
# Load and enable all available extensions. Use --list-extensions to see a list
# all available extensions.
#enable-all-extensions=
# In error mode, messages with a category besides ERROR or FATAL are
# suppressed, and no reports are done by default. Error mode is compatible with
# disabling specific errors.
#errors-only=
# Always return a 0 (non-error) status code, even if lint errors are found.
# This is primarily useful in continuous integration scripts.
#exit-zero=
# A comma-separated list of package or module names from where C extensions may
# be loaded. Extensions are loading into the active Python interpreter and may
# run arbitrary code.
extension-pkg-allow-list=
# Return non-zero exit code if any of these messages/categories are detected,
# even if score is above --fail-under value. Syntax same as enable. Messages
# specified are enabled, while categories only check already-enabled messages.
fail-on=
# Specify a score threshold under which the program will exit with error.
fail-under=10
# Interpret the stdin as a python script, whose filename needs to be passed as
# the module_or_package argument.
#from-stdin=
# Files or directories to be skipped. They should be base names, not paths.
ignore=CVS
# Add files or directories matching the regular expressions patterns to the
# ignore-list. The regex matches against paths and can be in Posix or Windows
# format. Because '\\' represents the directory delimiter on Windows systems,
# it can't be used as an escape character.
ignore-paths=
# Files or directories matching the regular expression patterns are skipped.
# The regex matches against base names, not paths. The default value ignores
# Emacs file locks
ignore-patterns=
# List of module names for which member attributes should not be checked and
# will not be imported (useful for modules/projects where namespaces are
# manipulated during runtime and thus existing member attributes cannot be
# deduced by static analysis). It supports qualified module names, as well as
# Unix pattern matching.
ignored-modules=
# Python code to execute, usually for sys.path manipulation such as
# pygtk.require().
#init-hook=
# Use multiple processes to speed up Pylint. Specifying 0 will auto-detect the
# number of processors available to use, and will cap the count on Windows to
# avoid hangs.
jobs=1
# Control the amount of potential inferred values when inferring a single
# object. This can help the performance when dealing with large functions or
# complex, nested conditions.
limit-inference-results=100
# List of plugins (as comma separated values of python module names) to load,
# usually to register additional checkers.
load-plugins=
# Pickle collected data for later comparisons.
persistent=yes
# Resolve imports to .pyi stubs if available. May reduce no-member messages and
# increase not-an-iterable messages.
prefer-stubs=no
# Minimum Python version to use for version dependent checks. Will default to
# the version used to run pylint.
py-version=3.9
# Discover python modules and packages in the file system subtree.
recursive=no
# Add paths to the list of the source roots. Supports globbing patterns. The
# source root is an absolute path or a path relative to the current working
# directory used to determine a package namespace for modules located under the
# source root.
source-roots=
# When enabled, pylint would attempt to guess common misconfiguration and emit
# user-friendly hints instead of false-positive error messages.
suggestion-mode=yes
# Allow loading of arbitrary C extensions. Extensions are imported into the
# active Python interpreter and may run arbitrary code.
unsafe-load-any-extension=no
# In verbose mode, extra non-checker-related info will be displayed.
#verbose=
[BASIC]
# Naming style matching correct argument names.
argument-naming-style=snake_case
# Regular expression matching correct argument names. Overrides argument-
# naming-style. If left empty, argument names will be checked with the set
# naming style.
#argument-rgx=
# Naming style matching correct attribute names.
attr-naming-style=snake_case
# Regular expression matching correct attribute names. Overrides attr-naming-
# style. If left empty, attribute names will be checked with the set naming
# style.
#attr-rgx=
# Bad variable names which should always be refused, separated by a comma.
bad-names=foo,
bar,
baz,
toto,
tutu,
tata
# Bad variable names regexes, separated by a comma. If names match any regex,
# they will always be refused
bad-names-rgxs=
# Naming style matching correct class attribute names.
class-attribute-naming-style=UPPER_CASE
# Regular expression matching correct class attribute names. Overrides class-
# attribute-naming-style. If left empty, class attribute names will be checked
# with the set naming style.
#class-attribute-rgx=
# Naming style matching correct class constant names.
class-const-naming-style=UPPER_CASE
# Regular expression matching correct class constant names. Overrides class-
# const-naming-style. If left empty, class constant names will be checked with
# the set naming style.
#class-const-rgx=
# Naming style matching correct class names.
class-naming-style=PascalCase
# Regular expression matching correct class names. Overrides class-naming-
# style. If left empty, class names will be checked with the set naming style.
#class-rgx=
# Naming style matching correct constant names.
const-naming-style=any
# Regular expression matching correct constant names. Overrides const-naming-
# style. If left empty, constant names will be checked with the set naming
# style.
#const-rgx=
# Minimum line length for functions/classes that require docstrings, shorter
# ones are exempt.
docstring-min-length=-1
# Naming style matching correct function names.
function-naming-style=snake_case
# Regular expression matching correct function names. Overrides function-
# naming-style. If left empty, function names will be checked with the set
# naming style.
#function-rgx=
# Good variable names which should always be accepted, separated by a comma.
good-names=i,
j,
e, # exceptions in except blocks
_
# Good variable names regexes, separated by a comma. If names match any regex,
# they will always be accepted
good-names-rgxs=
# Include a hint for the correct naming format with invalid-name.
include-naming-hint=no
# Naming style matching correct inline iteration names.
inlinevar-naming-style=any
# Regular expression matching correct inline iteration names. Overrides
# inlinevar-naming-style. If left empty, inline iteration names will be checked
# with the set naming style.
#inlinevar-rgx=
# Naming style matching correct method names.
method-naming-style=snake_case
# Regular expression matching correct method names. Overrides method-naming-
# style. If left empty, method names will be checked with the set naming style.
#method-rgx=
# Naming style matching correct module names.
module-naming-style=snake_case
# Regular expression matching correct module names. Overrides module-naming-
# style. If left empty, module names will be checked with the set naming style.
#module-rgx=
# Colon-delimited sets of names that determine each other's naming style when
# the name regexes allow several styles.
name-group=
# Regular expression which should only match function or class names that do
# not require a docstring.
no-docstring-rgx=
# List of decorators that produce properties, such as abc.abstractproperty. Add
# to this list to register other decorators that produce valid properties.
# These decorators are taken in consideration only for invalid-name.
property-classes=abc.abstractproperty
# Regular expression matching correct type alias names. If left empty, type
# alias names will be checked with the set naming style.
#typealias-rgx=
# Regular expression matching correct type variable names. If left empty, type
# variable names will be checked with the set naming style.
#typevar-rgx=
# Naming style matching correct variable names.
variable-naming-style=snake_case
# Regular expression matching correct variable names. Overrides variable-
# naming-style. If left empty, variable names will be checked with the set
# naming style.
#variable-rgx=
[CLASSES]
# Warn about protected attribute access inside special methods
check-protected-access-in-special-methods=no
# List of method names used to declare (i.e. assign) instance attributes.
defining-attr-methods=__init__,
__new__,
setUp,
__post_init__,
create
# List of member names, which should be excluded from the protected access
# warning.
exclude-protected=_asdict,
_fields,
_replace,
_source,
_make
# List of valid names for the first argument in a class method.
valid-classmethod-first-arg=cls
# List of valid names for the first argument in a metaclass class method.
valid-metaclass-classmethod-first-arg=cls
[DESIGN]
# List of regular expressions of class ancestor names to ignore when counting
# public methods (see R0903)
exclude-too-few-public-methods=
# List of qualified class names to ignore when counting class parents (see
# R0901)
ignored-parents=
# Maximum number of arguments for function / method.
max-args=100
# Maximum number of attributes for a class (see R0902).
max-attributes=100
# Maximum number of boolean expressions in an if statement (see R0916).
max-bool-expr=10
# Maximum number of branch for function / method body.
max-branches=100
# Maximum number of locals for function / method body.
max-locals=100
# Maximum number of parents for a class (see R0901).
max-parents=10
# Maximum number of positional arguments for function / method.
max-positional-arguments=100
# Maximum number of public methods for a class (see R0904).
max-public-methods=100
# Maximum number of return / yield for function / method body.
max-returns=100
# Maximum number of statements in function / method body.
max-statements=1000
# Minimum number of public methods for a class (see R0903).
min-public-methods=0
[EXCEPTIONS]
# Exceptions that will emit a warning when caught.
overgeneral-exceptions=builtins.BaseException,builtins.Exception
[FORMAT]
# Expected format of line ending, e.g. empty (any line ending), LF or CRLF.
expected-line-ending-format=
# Regexp for a line that is allowed to be longer than the limit.
ignore-long-lines=^\s*(# )??$
# Number of spaces of indent required inside a hanging or continued line.
indent-after-paren=4
# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1
# tab).
indent-string=' '
# Maximum number of characters on a single line.
max-line-length=110
# Maximum number of lines in a module.
max-module-lines=10000
# Allow the body of a class to be on the same line as the declaration if body
# contains single statement.
single-line-class-stmt=no
# Allow the body of an if to be on the same line as the test if there is no
# else.
single-line-if-stmt=yes
[IMPORTS]
# List of modules that can be imported at any level, not just the top level
# one.
allow-any-import-level=
# Allow explicit reexports by alias from a package __init__.
allow-reexport-from-package=yes
# Allow wildcard imports from modules that define __all__.
allow-wildcard-with-all=no
# Deprecated modules which should not be used, separated by a comma.
deprecated-modules=optparse,tkinter.tix
# Output a graph (.gv or any supported image format) of external dependencies
# to the given file (report RP0402 must not be disabled).
ext-import-graph=
# Output a graph (.gv or any supported image format) of all (i.e. internal and
# external) dependencies to the given file (report RP0402 must not be
# disabled).
import-graph=
# Output a graph (.gv or any supported image format) of internal dependencies
# to the given file (report RP0402 must not be disabled).
int-import-graph=
# Force import order to recognize a module as part of the standard
# compatibility libraries.
known-standard-library=
# Force import order to recognize a module as part of a third party library.
known-third-party=
# Couples of modules and preferred modules, separated by a comma.
preferred-modules=
[LOGGING]
# The type of string formatting that logging methods do. `old` means using %
# formatting, `new` is for `{}` formatting.
logging-format-style=new
# Logging modules to check that the string format arguments are in logging
# function parameter format.
logging-modules=logging
[MESSAGES CONTROL]
# Only show warnings with the listed confidence levels. Leave empty to show
# all. Valid levels: HIGH, CONTROL_FLOW, INFERENCE, INFERENCE_FAILURE,
# UNDEFINED.
confidence=HIGH,
CONTROL_FLOW,
INFERENCE,
INFERENCE_FAILURE,
UNDEFINED
# Disable the message, report, category or checker with the given id(s). You
# can either give multiple identifiers separated by comma (,) or put this
# option multiple times (only on the command line, not in the configuration
# file where it should appear only once). You can also use "--disable=all" to
# disable everything first and then re-enable specific checks. For example, if
# you want to run only the similarities checker, you can use "--disable=all
# --enable=similarities". If you want to run only the classes checker, but have
# no Warning level messages displayed, use "--disable=all --enable=classes
# --disable=W".
disable=missing-module-docstring,
duplicate-code,
logging-fstring-interpolation,
fixme
# Enable the message, report, category or checker with the given id(s). You can
# either give multiple identifier separated by comma (,) or put this option
# multiple time (only on the command line, not in the configuration file where
# it should appear only once). See also the "--disable" option for examples.
enable=useless-suppression
[METHOD_ARGS]
# List of qualified names (i.e., library.method) which require a timeout
# parameter e.g. 'requests.api.get,requests.api.post'
timeout-methods=requests.api.delete,requests.api.get,requests.api.head,requests.api.options,requests.api.patch,requests.api.post,requests.api.put,requests.api.request
[MISCELLANEOUS]
# List of note tags to take in consideration, separated by a comma.
notes=FIXME,
XXX,
TODO
# Regular expression of note tags to take in consideration.
notes-rgx=
[REFACTORING]
# Maximum number of nested blocks for function / method body
max-nested-blocks=5
# Complete name of functions that never returns. When checking for
# inconsistent-return-statements if a never returning function is called then
# it will be considered as an explicit return statement and no message will be
# printed.
never-returning-functions=sys.exit
# Let 'consider-using-join' be raised when the separator to join on would be
# non-empty (resulting in expected fixes of the type: ``"- " + " -
# ".join(items)``)
suggest-join-with-non-empty-separator=yes
[REPORTS]
# Python expression which should return a score less than or equal to 10. You
# have access to the variables 'fatal', 'error', 'warning', 'refactor',
# 'convention', and 'info' which contain the number of messages in each
# category, as well as 'statement' which is the total number of statements
# analyzed. This score is used by the global evaluation report (RP0004).
evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10)
# Template used to display messages. This is a python new-style format string
# used to format the message information. See doc for all details.
msg-template=
# Set the output format. Available formats are: text, parseable, colorized,
# json2 (improved json format), json (old json format) and msvs (visual
# studio). You can also give a reporter class, e.g.
# mypackage.mymodule.MyReporterClass.
#output-format=
# Tells whether to display a full report or only the messages.
reports=no
# Activate the evaluation score.
score=yes
[SIMILARITIES]
# Comments are removed from the similarity computation
ignore-comments=yes
# Docstrings are removed from the similarity computation
ignore-docstrings=yes
# Imports are removed from the similarity computation
ignore-imports=no
# Signatures are removed from the similarity computation
ignore-signatures=yes
# Minimum lines number of a similarity.
min-similarity-lines=4
[SPELLING]
# Limits count of emitted suggestions for spelling mistakes.
max-spelling-suggestions=4
# Spelling dictionary name. No available dictionaries : You need to install
# both the python package and the system dependency for enchant to work.
spelling-dict=
# List of comma separated words that should be considered directives if they
# appear at the beginning of a comment and should not be checked.
spelling-ignore-comment-directives=fmt: on,fmt: off,noqa:,noqa,nosec,isort:skip,mypy:
# List of comma separated words that should not be checked.
spelling-ignore-words=
# A path to a file that contains the private dictionary; one word per line.
spelling-private-dict-file=
# Tells whether to store unknown words to the private dictionary (see the
# --spelling-private-dict-file option) instead of raising a message.
spelling-store-unknown-words=no
[STRING]
# This flag controls whether inconsistent-quotes generates a warning when the
# character used as a quote delimiter is used inconsistently within a module.
check-quote-consistency=no
# This flag controls whether the implicit-str-concat should generate a warning
# on implicit string concatenation in sequences defined over several lines.
check-str-concat-over-line-jumps=no
[TYPECHECK]
# List of decorators that produce context managers, such as
# contextlib.contextmanager. Add to this list to register other decorators that
# produce valid context managers.
contextmanager-decorators=contextlib.contextmanager
# List of members which are set dynamically and missed by pylint inference
# system, and so shouldn't trigger E1101 when accessed. Python regular
# expressions are accepted.
generated-members=
# Tells whether to warn about missing members when the owner of the attribute
# is inferred to be None.
ignore-none=no
# This flag controls whether pylint should warn about no-member and similar
# checks whenever an opaque object is returned when inferring. The inference
# can return multiple potential results while evaluating a Python object, but
# some branches might not be evaluated, which results in partial inference. In
# that case, it might be useful to still emit no-member and other checks for
# the rest of the inferred objects.
ignore-on-opaque-inference=no
# List of symbolic message names to ignore for Mixin members.
ignored-checks-for-mixins=no-member,
not-async-context-manager,
not-context-manager,
attribute-defined-outside-init
# List of class names for which member attributes should not be checked (useful
# for classes with dynamically set attributes). This supports the use of
# qualified names.
ignored-classes=optparse.Values,thread._local,_thread._local
# Show a hint with possible names when a member name was not found. The aspect
# of finding the hint is based on edit distance.
missing-member-hint=yes
# The minimum edit distance a name should have in order to be considered a
# similar match for a missing member name.
missing-member-hint-distance=1
# The total number of similar names that should be taken in consideration when
# showing a hint for a missing member.
missing-member-max-choices=1
# Regex pattern to define which classes are considered mixins.
mixin-class-rgx=.*[Mm]ixin
# List of decorators that change the signature of a decorated function.
signature-mutators=
[VARIABLES]
# List of additional names supposed to be defined in builtins. Remember that
# you should avoid defining new builtins when possible.
additional-builtins=
# Tells whether unused global variables should be treated as a violation.
allow-global-unused-variables=yes
# List of names allowed to shadow builtins
allowed-redefined-builtins=
# List of strings which can identify a callback function by name. A callback
# name must start or end with one of those strings.
callbacks=cb_,
_cb
# A regular expression matching the name of dummy variables (i.e. expected to
# not be used).
dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_
# Argument names that match this expression will be ignored.
ignored-argument-names=_.*|^ignored_|^unused_
# Tells whether we should check for unused import in __init__ files.
init-import=no
# List of qualified module names which can have objects that can redefine
# builtins.
redefining-builtins-modules=six.moves,past.builtins,future.builtins,builtins,io
slixmpp-omemo-1.2.2/pyproject.toml 0000664 0000000 0000000 00000000134 14705742554 0017251 0 ustar 00root root 0000000 0000000 [build-system]
requires = [ "setuptools", "wheel" ]
build-backend = "setuptools.build_meta"
slixmpp-omemo-1.2.2/requirements.txt 0000664 0000000 0000000 00000000151 14705742554 0017620 0 ustar 00root root 0000000 0000000 slixmpp>=1.8.0,<2
OMEMO>=1.1.0,<2
Oldmemo[xml]>=1.0.4,<2
Twomemo[xml]>=1.0.4,<2
typing-extensions>=4.4.0
slixmpp-omemo-1.2.2/setup.py 0000664 0000000 0000000 00000004216 14705742554 0016054 0 ustar 00root root 0000000 0000000 # pylint: disable=exec-used
import os
from typing import Dict, Union, List
from setuptools import setup, find_packages # type: ignore[import-untyped]
source_root = os.path.join(os.path.dirname(os.path.abspath(__file__)), "slixmpp_omemo")
version_scope: Dict[str, Dict[str, str]] = {}
with open(os.path.join(source_root, "version.py"), encoding="utf-8") as f:
exec(f.read(), version_scope)
version = version_scope["__version__"]
project_scope: Dict[str, Dict[str, Union[str, List[str]]]] = {}
with open(os.path.join(source_root, "project.py"), encoding="utf-8") as f:
exec(f.read(), project_scope)
project = project_scope["project"]
with open("README.md", encoding="utf-8") as f:
long_description = f.read()
classifiers = [
"Intended Audience :: Developers",
"License :: OSI Approved :: GNU General Public License v3 (GPLv3)",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3 :: Only",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
"Programming Language :: Python :: 3.13",
"Programming Language :: Python :: Implementation :: CPython",
"Programming Language :: Python :: Implementation :: PyPy"
]
classifiers.extend(project["categories"])
if version["tag"] == "alpha":
classifiers.append("Development Status :: 3 - Alpha")
if version["tag"] == "beta":
classifiers.append("Development Status :: 4 - Beta")
if version["tag"] == "stable":
classifiers.append("Development Status :: 5 - Production/Stable")
del project["categories"]
del project["year"]
setup(
version=version["short"],
long_description=long_description,
long_description_content_type="text/markdown",
license="GPLv3",
packages=find_packages(exclude=["tests"]),
install_requires=[
"slixmpp>=1.8.0,<2",
"OMEMO>=1.1.0,<2",
"Oldmemo[xml]>=1.0.4,<2",
"Twomemo[xml]>=1.0.4,<2",
"typing-extensions>=4.4.0"
],
python_requires=">=3.9",
include_package_data=True,
zip_safe=False,
classifiers=classifiers,
**project
)
slixmpp-omemo-1.2.2/slixmpp_omemo/ 0000775 0000000 0000000 00000000000 14705742554 0017227 5 ustar 00root root 0000000 0000000 slixmpp-omemo-1.2.2/slixmpp_omemo/__init__.py 0000664 0000000 0000000 00000000277 14705742554 0021346 0 ustar 00root root 0000000 0000000 from .version import __version__ as __version__
from .project import project as project
from .base_session_manager import TrustLevel as TrustLevel
from .xep_0384 import XEP_0384 as XEP_0384
slixmpp-omemo-1.2.2/slixmpp_omemo/base_session_manager.py 0000664 0000000 0000000 00000014464 14705742554 0023761 0 ustar 00root root 0000000 0000000 from abc import abstractmethod
import enum
from typing import FrozenSet, Optional, Set
from typing_extensions import assert_never
from omemo.session_manager import SessionManager, UnknownTrustLevel
from omemo.types import DeviceInformation, TrustLevel as CoreTrustLevel
__all__ = [
"TrustLevel",
"BaseSessionManager"
]
@enum.unique
class TrustLevel(enum.Enum):
"""
Trust levels modeling Blind Trust Before Verification (BTBV) and manual trust.
"""
TRUSTED: str = "TRUSTED"
BLINDLY_TRUSTED: str = "BLINDLY_TRUSTED"
UNDECIDED: str = "UNDECIDED"
DISTRUSTED: str = "DISTRUSTED"
class BaseSessionManager(SessionManager):
"""
Partial :class:`omemo.SessionManager` implementation with BTBV and manual trust as its trust systems.
"""
async def _evaluate_custom_trust_level(self, device: DeviceInformation) -> CoreTrustLevel:
try:
trust_level = TrustLevel(device.trust_level_name)
except ValueError as e:
raise UnknownTrustLevel(f"Unknown trust level name: {device.trust_level_name}") from e
# Those custom trust levels map directly to core trust levels
if trust_level is TrustLevel.TRUSTED:
return CoreTrustLevel.TRUSTED
if trust_level is TrustLevel.UNDECIDED:
return CoreTrustLevel.UNDECIDED
if trust_level is TrustLevel.DISTRUSTED:
return CoreTrustLevel.DISTRUSTED
# The blindly trusted state maps differently depending on whether BTBV is enabled
if trust_level is TrustLevel.BLINDLY_TRUSTED:
if self._btbv_enabled:
# The blindly trusted state is equivalent to the trusted state when BTBV is enabled.
return CoreTrustLevel.TRUSTED
# The blindly trusted state is equivalent to the undecided state when BTBV is disabled.
return CoreTrustLevel.UNDECIDED
assert_never(trust_level)
async def _make_trust_decision(
self,
undecided: FrozenSet[DeviceInformation],
identifier: Optional[str]
) -> None:
# For BTBV, affected JIDs can be separated into two pools: one pool of JIDs for which blind trust is
# active, i.e. no manual verification was performed before, and one pool of JIDs to use manual trust
# with instead.
bare_jids = { device.bare_jid for device in undecided }
blind_trust_bare_jids: Set[str] = set()
manual_trust_bare_jids: Set[str] = set()
# For each bare JID, decide whether blind trust applies
for bare_jid in bare_jids:
# Get all known devices belonging to the bare JID
devices = await self.get_device_information(bare_jid)
# If BTBV is disabled, use manual trust
if not self._btbv_enabled:
manual_trust_bare_jids.add(bare_jid)
continue
# If the trust levels of all devices correspond to those used by blind trust, blind trust
# applies.
# Otherwise, fall back to manual trust.
if all(TrustLevel(device.trust_level_name) in {
TrustLevel.UNDECIDED,
TrustLevel.BLINDLY_TRUSTED
} for device in devices):
blind_trust_bare_jids.add(bare_jid)
else:
manual_trust_bare_jids.add(bare_jid)
# With the JIDs sorted into their respective pools, the undecided devices can be categorized too
blindly_trusted_devices = { dev for dev in undecided if dev.bare_jid in blind_trust_bare_jids }
manually_trusted_devices = { dev for dev in undecided if dev.bare_jid in manual_trust_bare_jids }
# Blindly trust devices handled by blind trust
if len(blindly_trusted_devices) > 0:
for device in blindly_trusted_devices:
await self.set_trust(
device.bare_jid,
device.identity_key,
TrustLevel.BLINDLY_TRUSTED.name
)
await self._devices_blindly_trusted(frozenset(blindly_trusted_devices), identifier)
# Prompt the user for manual trust decisions on the devices handled by manual trust
if len(manually_trusted_devices) > 0:
await self._prompt_manual_trust(frozenset(manually_trusted_devices), identifier)
@property
@abstractmethod
def _btbv_enabled(self) -> bool:
"""
Returns:
Whether BTBV is enabled.
"""
async def _devices_blindly_trusted(
self,
blindly_trusted: FrozenSet[DeviceInformation],
identifier: Optional[str]
) -> None:
"""
Get notified about newly blindly trusted devices. This method is called automatically by
:meth:`_make_trust_decision` whenever at least one device was blindly trusted. You can use this method
for example to notify the user about the automated change in trust.
Does nothing by default.
Args:
blindly_trusted: A set of devices that were blindly trusted.
identifier: Forwarded from :meth:`_make_trust_decision`, refer to its documentation for details.
"""
@abstractmethod
async def _prompt_manual_trust(
self,
manually_trusted: FrozenSet[DeviceInformation],
identifier: Optional[str]
) -> None:
"""
Prompt manual trust decision on a set of undecided identity keys. The trust decisions are expected to
be persisted by calling :meth:`set_trust`.
Args:
manually_trusted: A set of devices whose trust has to be manually decided by the user.
identifier: Forwarded from :meth:`_make_trust_decision`, refer to its documentation for details.
Raises:
TrustDecisionFailed: if for any reason the trust decision failed/could not be completed. Feel free
to raise a subclass instead.
Note:
This is called when the encryption needs to know whether it is allowed to encrypt for these
devices or not. When this method returns, all previously undecided trust levels should have been
replaced by calling :meth:`set_trust` with a different trust level. If they are not replaced or
still evaluate to the undecided trust level after the call, the encryption will fail with an
exception. See :meth:`encrypt` for details.
"""
slixmpp-omemo-1.2.2/slixmpp_omemo/migrations.py 0000664 0000000 0000000 00000000000 14705742554 0021743 0 ustar 00root root 0000000 0000000 slixmpp-omemo-1.2.2/slixmpp_omemo/project.py 0000664 0000000 0000000 00000001015 14705742554 0021244 0 ustar 00root root 0000000 0000000 __all__ = [ "project" ]
project = {
"name" : "slixmpp-omemo",
"description" : "Slixmpp OMEMO plugin",
"url" : "https://github.com/Syndace/slixmpp-omemo",
"year" : "2024",
"author" : "Tim Henkes (Syndace)",
"author_email" : "me@syndace.dev",
"categories" : [
"Topic :: Communications :: Chat",
"Topic :: Internet :: XMPP",
"Topic :: Security :: Cryptography",
"Topic :: Software Development :: Libraries :: Python Modules"
]
}
slixmpp-omemo-1.2.2/slixmpp_omemo/py.typed 0000664 0000000 0000000 00000000000 14705742554 0020714 0 ustar 00root root 0000000 0000000 slixmpp-omemo-1.2.2/slixmpp_omemo/version.py 0000664 0000000 0000000 00000000256 14705742554 0021271 0 ustar 00root root 0000000 0000000 __all__ = [ "__version__" ]
__version__ = {}
__version__["short"] = "1.2.2"
__version__["tag"] = "beta"
__version__["full"] = f"{__version__['short']}-{__version__['tag']}"
slixmpp-omemo-1.2.2/slixmpp_omemo/xep_0384.py 0000664 0000000 0000000 00000136756 14705742554 0021075 0 ustar 00root root 0000000 0000000 from abc import ABCMeta, abstractmethod
import asyncio
from copy import copy
import logging
from typing import Any, Dict, FrozenSet, Optional, Set, Tuple, Type, Union
from xml.etree import ElementTree as ET
import omemo
from omemo.session_manager import EncryptionError, SessionManager
from omemo.session_manager import (
BundleDeletionFailed,
BundleDownloadFailed,
BundleNotFound,
BundleUploadFailed,
DeviceListDownloadFailed,
DeviceListUploadFailed,
MessageSendingFailed,
SenderNotFound,
UnknownNamespace
)
from omemo.storage import Storage
from omemo.types import DeviceInformation
import oldmemo
import oldmemo.etree
import twomemo
import twomemo.etree
from xmlschema import XMLSchemaValidationError
from slixmpp.basexmpp import BaseXMPP
from slixmpp.exceptions import IqError
from slixmpp.jid import JID
from slixmpp.plugins.base import BasePlugin
from slixmpp.plugins.xep_0004 import Form # type: ignore[attr-defined]
from slixmpp.plugins.xep_0045 import XEP_0045 # type: ignore[attr-defined]
from slixmpp.plugins.xep_0060 import XEP_0060 # type: ignore[attr-defined]
from slixmpp.plugins.xep_0163 import XEP_0163
from slixmpp.roster import RosterNode # type: ignore[attr-defined]
from slixmpp.stanza import Iq, Message, Presence
from .base_session_manager import BaseSessionManager, TrustLevel
__all__ = [
"XEP_0384"
]
TWOMEMO_DEVICE_LIST_NODE = "urn:xmpp:omemo:2:devices"
OLDMEMO_DEVICE_LIST_NODE = "eu.siacs.conversations.axolotl.devicelist"
log = logging.getLogger(__name__)
def _make_options_form(form_type: str, fields: Dict[str, Any]) -> Form:
"""
Build a form for publish options or manual pubsub node configuration.
Args:
form_type: The value of the form type field, either selecting publish-options or node_config.
fields: The options to set.
Returns:
The filled-out form ready to be included in a publish or node configuration call.
"""
form = Form()
form["type"] = "submit"
form.add_field(var="FORM_TYPE", ftype="hidden", value=form_type)
for key, value in fields.items():
form.add_field(var=key, value=value)
return form
async def _publish_item_and_configure_node(
xep_0060: XEP_0060,
service: str,
node: str,
item: ET.Element,
item_id: str,
options: Dict[str, str]
) -> None:
"""
Publishes an item and makes sure that the node is configured correctly.
Args:
xep_0060: The XEP_0060 instance for pubsub interaction.
service: The pubsub service to publish to.
node: The pubsub node to publish to.
item: The item to publish.
item_id: The item id to assign to the published item.
options: The configuration required on the target node. The configuration is applied either
dynamically using publish options or manually using pubsub node configuration.
Raises:
Exception: all exceptions raised by :meth:`XEP_0060.publish` and :meth:`XEP_0060.set_node_config` are
forwarded as-is.
"""
publish_options_form = _make_options_form("http://jabber.org/protocol/pubsub#publish-options", options)
node_config_form = _make_options_form("http://jabber.org/protocol/pubsub#node_config", options)
try:
await xep_0060.publish(JID(service), node, item_id, item, publish_options_form)
except IqError as e:
# There doesn't seem to be a clean way to find the error condition from an IqError yet.
if e.iq["error"].xml.find("{http://jabber.org/protocol/pubsub#errors}precondition-not-met") is None:
raise
# precondition-not-met is raised in case the node already exists with different configuration. Try
# to manually reconfigure the node as needed.
await xep_0060.set_node_config(JID(service), node, node_config_form)
# Attempt to publish the item again. This time, precondition-not-met should not fire.
await xep_0060.publish(JID(service), node, item_id, item, publish_options_form)
def _make_session_manager(xmpp: BaseXMPP, xep_0384: "XEP_0384") -> Type[SessionManager]:
"""
Returns an implementation of `SessionManager` that is tailored for use in the plugin. Pubsub interactions
are handled via the XEP_0060 plugin, messages are sent via the `BaseXMPP` instance and BTBV & manual trust
are provided as trust systems.
Args:
xmpp: The BaseXMPP object for interaction with Slixmpp/XMPP.
xep_0384: The plugin instance.
Returns:
The session manager implementation type, ready to be instantiated.
"""
our_bare_jid: str = xmpp.boundjid.bare
xep_0060: XEP_0060 = xmpp["xep_0060"]
class SessionManagerImpl(BaseSessionManager):
@staticmethod
async def _upload_bundle(bundle: omemo.Bundle) -> None:
if isinstance(bundle, twomemo.twomemo.BundleImpl):
node = "urn:xmpp:omemo:2:bundles"
item = twomemo.etree.serialize_bundle(bundle)
try:
await _publish_item_and_configure_node(
xep_0060,
our_bare_jid,
node,
item,
item_id=str(bundle.device_id),
options={
"pubsub#access_model": "open",
"pubsub#persist_items": "true",
"pubsub#max_items": "max"
}
)
except Exception: # pylint: disable=broad-exception-caught
# Try again without MAX_ITEMS set, which is not strictly necessary.
try:
await _publish_item_and_configure_node(
xep_0060,
our_bare_jid,
node,
item,
item_id=str(bundle.device_id),
options={
"pubsub#access_model": "open",
"pubsub#persist_items": "true"
}
)
except Exception as e:
raise BundleUploadFailed(f"Bundle upload failed: {bundle}") from e
return
if isinstance(bundle, oldmemo.oldmemo.BundleImpl):
node = f"eu.siacs.conversations.axolotl.bundles:{bundle.device_id}"
item = oldmemo.etree.serialize_bundle(bundle)
try:
await _publish_item_and_configure_node(
xep_0060,
our_bare_jid,
node,
item,
item_id="current",
options={
"pubsub#access_model": "open",
"pubsub#persist_items": "true",
"pubsub#max_items": "1"
}
)
except Exception: # pylint: disable=broad-exception-caught
# Try again without MAX_ITEMS set, which is not strictly necessary.
try:
await _publish_item_and_configure_node(
xep_0060,
our_bare_jid,
node,
item,
item_id="current",
options={
"pubsub#access_model": "open",
"pubsub#persist_items": "true"
}
)
except Exception as e:
raise BundleUploadFailed(f"Bundle upload failed: {bundle}") from e
return
raise UnknownNamespace(f"Unknown namespace: {bundle.namespace}")
@staticmethod
async def _download_bundle(namespace: str, bare_jid: str, device_id: int) -> omemo.Bundle:
items_iq: Optional[Iq] = None
try:
if namespace == twomemo.twomemo.NAMESPACE:
node = "urn:xmpp:omemo:2:bundles"
items_iq = await xep_0060.get_items(JID(bare_jid), node, item_ids=[ str(device_id) ])
if namespace == oldmemo.oldmemo.NAMESPACE:
node = f"eu.siacs.conversations.axolotl.bundles:{device_id}"
items_iq = await xep_0060.get_items(JID(bare_jid), node, max_items=1)
except Exception as e:
if isinstance(e, IqError):
if e.condition == "item-not-found":
raise BundleNotFound(
f"Bundle of {bare_jid}: {device_id} not found under namespace {namespace}. The"
f" node doesn't exist."
) from e
raise BundleDownloadFailed(
f"Bundle download failed for {bare_jid}: {device_id} under namespace {namespace}"
) from e
if items_iq is None:
raise UnknownNamespace(f"Unknown namespace: {namespace}")
items = items_iq["pubsub"]["items"]
if len(items) == 0:
raise BundleNotFound(
f"Bundle of {bare_jid}: {device_id} not found under namespace {namespace}. The node"
f" exists but is empty."
)
if len(items) > 1:
raise BundleDownloadFailed(
f"Bundle download failed for {bare_jid}: {device_id} under namespace {namespace}:"
f" Unexpected number of items retrieved: {len(items)}."
)
bundle_elt = next(iter(items["item"].xml), None)
if bundle_elt is None:
raise BundleDownloadFailed(
f"Bundle download failed for {bare_jid}: {device_id} under namespace {namespace}: Pubsub"
f" item is empty."
)
try:
if namespace == twomemo.twomemo.NAMESPACE:
return twomemo.etree.parse_bundle(bundle_elt, bare_jid, device_id)
if namespace == oldmemo.oldmemo.NAMESPACE:
return oldmemo.etree.parse_bundle(bundle_elt, bare_jid, device_id)
except Exception as e:
raise BundleDownloadFailed(
f"Bundle parsing failed for {bare_jid}: {device_id} under namespace {namespace}"
) from e
raise UnknownNamespace(f"Unknown namespace: {namespace}")
@staticmethod
async def _delete_bundle(namespace: str, device_id: int) -> None:
if namespace == twomemo.twomemo.NAMESPACE:
node = "urn:xmpp:omemo:2:bundles"
try:
await xep_0060.retract(JID(our_bare_jid), node, [ str(device_id) ], notify=False)
except Exception as e:
if isinstance(e, IqError):
if e.condition == "item-not-found":
return
raise BundleDeletionFailed(
f"Bundle deletion failed for {device_id} under namespace {namespace}"
) from e
return
if namespace == oldmemo.oldmemo.NAMESPACE:
node = f"eu.siacs.conversations.axolotl.bundles:{device_id}"
try:
await xep_0060.delete_node(JID(our_bare_jid), node)
except Exception as e:
if isinstance(e, IqError):
if e.condition == "item-not-found":
return
raise BundleDeletionFailed(
f"Bundle deletion failed for {device_id} under namespace {namespace}"
) from e
return
raise UnknownNamespace(f"Unknown namespace: {namespace}")
@staticmethod
async def _upload_device_list(namespace: str, device_list: Dict[int, Optional[str]]) -> None:
item: Optional[ET.Element] = None
node: Optional[str] = None
if namespace == twomemo.twomemo.NAMESPACE:
item = twomemo.etree.serialize_device_list(device_list)
node = TWOMEMO_DEVICE_LIST_NODE
if namespace == oldmemo.oldmemo.NAMESPACE:
item = oldmemo.etree.serialize_device_list(device_list)
node = OLDMEMO_DEVICE_LIST_NODE
if item is None or node is None:
raise UnknownNamespace(f"Unknown namespace: {namespace}")
try:
await _publish_item_and_configure_node(
xep_0060,
our_bare_jid,
node,
item,
item_id="current",
options={
"pubsub#access_model": "open",
"pubsub#persist_items": "true",
"pubsub#max_items": "1"
}
)
except Exception: # pylint: disable=broad-exception-caught
try:
# Try again without MAX_ITEMS set, which is not strictly necessary.
await _publish_item_and_configure_node(
xep_0060,
our_bare_jid,
node,
item,
item_id="current",
options={
"pubsub#access_model": "open",
"pubsub#persist_items": "true"
}
)
except Exception as e:
raise DeviceListUploadFailed(
f"Device list upload failed for namespace {namespace}"
) from e
@staticmethod
async def _download_device_list(namespace: str, bare_jid: str) -> Dict[int, Optional[str]]:
node: Optional[str] = None
if namespace == twomemo.twomemo.NAMESPACE:
node = TWOMEMO_DEVICE_LIST_NODE
if namespace == oldmemo.oldmemo.NAMESPACE:
node = OLDMEMO_DEVICE_LIST_NODE
if node is None:
raise UnknownNamespace(f"Unknown namespace: {namespace}")
try:
items_iq = await xep_0060.get_items(JID(bare_jid), node, max_items=1)
except Exception as e: # pylint: disable=broad-exception-caught
if isinstance(e, IqError):
if e.condition == "item-not-found":
return {}
log.warning(
f"Device list download failed for {bare_jid} under namespace {namespace}, trying again"
f" without max_items"
)
try:
items_iq = await xep_0060.get_items(JID(bare_jid), node)
except Exception as ex:
if isinstance(ex, IqError):
if ex.condition == "item-not-found":
return {}
raise DeviceListDownloadFailed(
f"Device list download failed for {bare_jid} under namespace {namespace}"
) from ex
items = items_iq["pubsub"]["items"]
if len(items) == 0:
return {}
if len(items) > 1:
raise DeviceListDownloadFailed(
f"Device list download failed for {bare_jid} under namespace {namespace}: Unexpected"
f" number of items retrieved: {len(items)}."
)
device_list_elt = next(iter(items["item"].xml), None)
if device_list_elt is None:
raise DeviceListDownloadFailed(
f"Device list download failed for {bare_jid} under namespace {namespace}: Pubsub item is"
f" empty."
)
try:
if namespace == twomemo.twomemo.NAMESPACE:
return twomemo.etree.parse_device_list(device_list_elt)
if namespace == oldmemo.oldmemo.NAMESPACE:
return oldmemo.etree.parse_device_list(device_list_elt)
except XMLSchemaValidationError as e:
log.warning(
f"Malformed device list for {bare_jid} under namespace {namespace}, treating as empty",
exc_info=e
)
return {}
except Exception as e:
raise DeviceListDownloadFailed(
f"Device list download failed for {bare_jid} under namespace {namespace}"
) from e
raise UnknownNamespace(f"Unknown namespace: {namespace}")
@property
def _btbv_enabled(self) -> bool:
return xep_0384._btbv_enabled # pylint: disable=protected-access
async def _devices_blindly_trusted(
self,
blindly_trusted: FrozenSet[DeviceInformation],
identifier: Optional[str]
) -> None:
return await xep_0384._devices_blindly_trusted( # pylint: disable=protected-access
blindly_trusted,
identifier
)
async def _prompt_manual_trust(
self,
manually_trusted: FrozenSet[DeviceInformation],
identifier: Optional[str]
) -> None:
return await xep_0384._prompt_manual_trust( # pylint: disable=protected-access
manually_trusted,
identifier
)
@staticmethod
async def _send_message(message: omemo.Message, bare_jid: str) -> None:
element: Optional[ET.Element] = None
if message.namespace == twomemo.twomemo.NAMESPACE:
element = twomemo.etree.serialize_message(message)
if message.namespace == oldmemo.oldmemo.NAMESPACE:
element = oldmemo.etree.serialize_message(message)
if element is None:
raise UnknownNamespace(f"Unknown namespace: {message.namespace}")
msg = xmpp.make_message(mto=JID(bare_jid))
msg.append(element)
msg.enable("store")
try:
# send() can't actually throw; it simply queues up the message and returns. The try/catch is
# here in case there's ever a throwing send.
msg.send()
except Exception as e:
raise MessageSendingFailed() from e
return SessionManagerImpl
async def _prepare(
xmpp: BaseXMPP,
xep_0384: "XEP_0384",
storage: Storage,
signed_pre_key_rotation_period: int = 7 * 24 * 60 * 60,
pre_key_refill_threshold: int = 99,
max_num_per_session_skipped_keys: int = 1000,
max_num_per_message_skipped_keys: Optional[int] = None
) -> SessionManager:
"""
Prepare the OMEMO library for use in this plugin.
Args:
xmpp: The BaseXMPP object for interaction with Slixmpp/XMPP.
xep_0384: The plugin instance.
storage: The storage for all OMEMO-related data.
signed_pre_key_rotation_period: The rotation period for the signed pre key, in seconds. The rotation
period is recommended to be between one week (the default) and one month.
pre_key_refill_threshold: The number of pre keys that triggers a refill to 100. Defaults to 99, which
means that each pre key gets replaced with a new one right away. The threshold can not be
configured to lower than 25.
max_num_per_session_skipped_keys: The maximum number of skipped message keys to keep around per
session. Once the maximum is reached, old message keys are deleted to make space for newer ones.
max_num_per_message_skipped_keys: The maximum number of skipped message keys to accept in a single
message. When set to ``None`` (the default), this parameter defaults to the per-session maximum
(i.e. the value of the ``max_num_per_session_skipped_keys`` parameter). This parameter may only be
0 if the per-session maximum is 0, otherwise it must be a number between 1 and the per-session
maximum.
Returns:
The session manager, i.e. the OMEMO library's core interface, initialized for use with Slixmpp.
Raises:
Exception: all exceptions raised by :meth:`SessionManager.create` are forwarded as-is.
"""
session_manager = await _make_session_manager(xmpp, xep_0384).create(
[
twomemo.Twomemo(
storage,
max_num_per_session_skipped_keys,
max_num_per_message_skipped_keys
),
oldmemo.Oldmemo(
storage,
max_num_per_session_skipped_keys,
max_num_per_message_skipped_keys
)
],
storage,
xmpp.boundjid.bare,
initial_own_label=None,
undecided_trust_level_name=TrustLevel.UNDECIDED.value,
signed_pre_key_rotation_period=signed_pre_key_rotation_period,
pre_key_refill_threshold=pre_key_refill_threshold
)
# This shouldn't hurt here since we're not running on overly constrainted devices.
# TODO: Consider ensuring data consistency regularly/in response to certain events
await session_manager.ensure_data_consistency()
# TODO: Correct entering/leaving of the history synchronization mode isn't terribly important for now,
# since it only prevents an extremely unlikely race condition of multiple devices choosing the same pre
# key for new sessions while the device was offline. I don't believe other clients seriously defend
# against that race condition either. In the long run, it might still be cool to have triggers for when
# history sync starts and ends (MAM, MUC catch-up, etc.) and to react to those triggers.
await session_manager.after_history_sync()
return session_manager
class XEP_0384(BasePlugin, metaclass=ABCMeta): # pylint: disable=invalid-name
"""
An implementation of XEP-0384: OMEMO Encryption.
Supports both the 0.3 version of the protocol (under the eu.siacs.conversations.axolotl namespace, also
known as legacy OMEMO, oldmemo and siacs OMEMO) and the current 0.8 version (under the omemo:2 namespace,
also known as newmemo, twomemo and OMEMO 2).
The plugin does not treat the protocol versions as separate encryption mechanisms, instead it manages all
versions transparently with no manual intervention required.
Certain initialization tasks such as a data consistency check are transparently ran in the background when
the plugin is loaded. The ``omemo_initialized`` event is fired when those initial background tasks are
done. Waiting for this event can be useful e.g. in automated testing environments to be sure that a test
client has generated and uploaded its OMEMO data before continuing.
Tip:
A lot of essential functionality is accessible via the `SessionManager` instance that is returned by
:meth:`get_session_manager`. The session manager is the core of the underlying OMEMO library and
offers functionality such as listing all devices known for an XMPP account, managing trust and
settings your own device's label. Refer to the library's
`API Documentation `__ for details.
"""
name = "xep_0384"
description = "OMEMO Encryption"
dependencies = { "xep_0004", "xep_0030", "xep_0060", "xep_0163", "xep_0280", "xep_0334" }
default_config = {
# TODO: Improve fallback text :)
"fallback_message": "This message is OMEMO encrypted."
}
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs) # type: ignore[no-untyped-call]
self.__session_manager: Optional[SessionManager] = None
self.__session_manager_task: Optional[asyncio.Task[SessionManager]] = None
def plugin_init(self) -> None:
xmpp: BaseXMPP = self.xmpp
xep_0060: XEP_0060 = xmpp["xep_0060"]
xep_0163: XEP_0163 = xmpp["xep_0163"]
xep_0060.map_node_event(TWOMEMO_DEVICE_LIST_NODE, "twomemo_device_list")
xep_0060.map_node_event(OLDMEMO_DEVICE_LIST_NODE, "oldmemo_device_list")
xmpp.add_event_handler("twomemo_device_list_publish", self._on_device_list_update)
xmpp.add_event_handler("oldmemo_device_list_publish", self._on_device_list_update)
xmpp.add_event_handler("changed_subscription", self._on_subscription_changed)
xep_0163.add_interest(TWOMEMO_DEVICE_LIST_NODE)
xep_0163.add_interest(OLDMEMO_DEVICE_LIST_NODE)
def plugin_end(self) -> None:
xmpp: BaseXMPP = self.xmpp
xep_0163: XEP_0163 = xmpp["xep_0163"]
xmpp.del_event_handler("twomemo_device_list_publish", self._on_device_list_update)
xmpp.del_event_handler("oldmemo_device_list_publish", self._on_device_list_update)
xep_0163.remove_interest(TWOMEMO_DEVICE_LIST_NODE)
xep_0163.remove_interest(OLDMEMO_DEVICE_LIST_NODE)
self.__session_manager = None
if self.__session_manager_task is not None:
self.__session_manager_task.cancel() # pylint: disable=no-member
self.__session_manager_task = None
def session_bind(self, jid: JID) -> None:
# Trigger async creation of the session manager
asyncio.create_task(self.get_session_manager())
@property
@abstractmethod
def storage(self) -> Storage:
"""
Returns:
The storage implementation to use to store OMEMO-related data.
"""
@property
@abstractmethod
def _btbv_enabled(self) -> bool:
"""
Returns:
Whether BTBV is enabled.
"""
async def _devices_blindly_trusted(
self,
blindly_trusted: FrozenSet[DeviceInformation],
identifier: Optional[str]
) -> None:
"""
Get notified about newly blindly trusted devices. This method is called automatically by whenever at
least one device was blindly trusted. You can use this method for example to notify the user about the
automated change in trust.
Does nothing by default.
Args:
blindly_trusted: A set of devices that were blindly trusted.
identifier: A piece of application-specific information that callers can pass to
:meth:`encrypt_message`, which is then forwarded here unaltered. This can be used, for
example, by instant messaging clients, to identify the chat tab which triggered the call to
:meth:`encrypt_message` and subsequently this call to :meth:`_devices_blindly_trusted`.
"""
@abstractmethod
async def _prompt_manual_trust(
self,
manually_trusted: FrozenSet[DeviceInformation],
identifier: Optional[str]
) -> None:
"""
Prompt manual trust decision on a set of undecided identity keys. The trust decisions are expected to
be persisted by calling :meth:`SessionManager.set_trust`.
Args:
manually_trusted: A set of devices whose trust has to be manually decided by the user.
identifier: A piece of application-specific information that callers can pass to
:meth:`encrypt_message`, which is then forwarded here unaltered. This can be used, for
example, by instant messaging clients, to identify the chat tab which triggered the call to
:meth:`encrypt_message` and subsequently this call to :meth:`_prompt_manual_trust`.
Raises:
TrustDecisionFailed: if for any reason the trust decision failed/could not be completed. Feel free
to raise a subclass instead.
Note:
This is called when the encryption needs to know whether it is allowed to encrypt for these
devices or not. When this method returns, all previously undecided trust levels should have been
replaced by calling :meth:`set_trust` with a different trust level. If they are not replaced or
still evaluate to the undecided trust level after the call, the encryption will fail with an
exception. See :meth:`encrypt` for details.
"""
async def get_session_manager(self) -> SessionManager:
"""
Access the session manager, which is the main interface to the underlying OMEMO library. A lot of
useful functionality is available on the session manager, refer to the library's
`API Documentation `__ for details.
Returns:
The session manager instance that is internally used by this plugin.
"""
# If the session manager is available, return it
if self.__session_manager is not None:
return self.__session_manager
# If the session manager is neither available nor currently being built, build it in a way that other
# tasks can await the build task
if self.__session_manager_task is None:
self.__session_manager_task = asyncio.create_task(_prepare(self.xmpp, self, self.storage))
session_manager = await self.__session_manager_task
self.__session_manager = session_manager
self.__session_manager_task = None
self.xmpp.event("omemo_initialized")
return session_manager
# If the session manager is currently being built, wait for it to be done
return await self.__session_manager_task
async def _on_device_list_update(self, msg: Message) -> None:
"""
Callback to handle PEP updates to the device list node of either OMEMO protocol version.
Args:
msg: The stanza containing the PEP update event.
"""
items = msg["pubsub_event"]["items"]
if len(items) == 0:
log.debug("Ignoring empty device list update.")
return
if len(items) > 1:
log.warning("Ignoring device list update with more than one element.")
return
item = items["item"].xml
device_list: Dict[int, Optional[str]] = {}
namespace: Optional[str] = None
twomemo_device_list_elt = item.find(f"{{{twomemo.twomemo.NAMESPACE}}}devices")
if twomemo_device_list_elt is not None:
try:
device_list = twomemo.etree.parse_device_list(twomemo_device_list_elt)
except XMLSchemaValidationError:
pass
else:
namespace = twomemo.twomemo.NAMESPACE
oldmemo_device_list_elt = item.find(f"{{{oldmemo.oldmemo.NAMESPACE}}}list")
if oldmemo_device_list_elt is not None:
try:
device_list = oldmemo.etree.parse_device_list(oldmemo_device_list_elt)
except XMLSchemaValidationError:
pass
else:
namespace = oldmemo.oldmemo.NAMESPACE
if namespace is None:
log.warning(f"Malformed device list update item: {ET.tostring(item, encoding='unicode')}")
return
session_manager = await self.get_session_manager()
await session_manager.update_device_list(namespace, msg["from"].bare, device_list)
async def _on_subscription_changed(self, presence: Presence) -> None:
"""
Callback to handle presence subscription changes.
Args:
presence: The presence stanza triggering this callback.
"""
jid = JID(presence["from"].bare)
roster: RosterNode = self.xmpp.client_roster
pep_enabled = jid in roster and roster[jid]["subscription"] == "both"
log.debug(f"Subscription changed for {jid}; PEP enabled: {pep_enabled}")
for namespace in [ twomemo.twomemo.NAMESPACE, oldmemo.oldmemo.NAMESPACE ]:
subscribed = (await self.storage.load_primitive(
f"/slixmpp/subscribed/{jid}/{namespace}",
bool
)).maybe(None)
if subscribed is None:
# This JID is not tracked.
return
# Remove manual subscriptions if PEP is enabled now
if pep_enabled and subscribed:
await self._unsubscribe(namespace, jid)
# Add a manual subscription if PEP is disabled now
if not pep_enabled and not subscribed:
await self._subscribe(namespace, jid)
async def _subscribe(self, namespace: str, jid: JID) -> None:
"""
Manually subscribe to the device list pubsub node of the JID and track the subscription status.
Args:
namespace: The OMEMO version namespace (not the node).
jid: The JID whose device list to manually subscribe to. Can be a bare (aka "userhost") JID but
doesn't have to.
"""
jid = JID(jid.bare)
log.debug(f"Manually subscribing to {namespace} device list for {jid}")
node = {
twomemo.twomemo.NAMESPACE: TWOMEMO_DEVICE_LIST_NODE,
oldmemo.oldmemo.NAMESPACE: OLDMEMO_DEVICE_LIST_NODE
}.get(namespace, None)
if node is None:
raise UnknownNamespace(f"Unknown namespace during device list subscription: {namespace}")
xep_0060: XEP_0060 = self.xmpp["xep_0060"]
try:
await xep_0060.subscribe(jid, node)
except IqError as e:
# Failure to subscribe is non-critical here, simply debug log the error (and don't update the
# subscription status).
log.debug(f"Couldn't subscribe to {namespace} device list of {jid.bare}", exc_info=e)
else:
await self.storage.store(f"/slixmpp/subscribed/{jid.bare}/{namespace}", True)
async def _unsubscribe(self, namespace: str, jid: JID) -> None:
"""
Manually unsubscribe from the device list pubsub node of the JID and track the subscription status.
Args:
namespace: The OMEMO version namespace (not the node).
jid: The JID whose device list to manually unsubscribe from. Can be a bare (aka "userhost") JID
but doesn't have to.
"""
jid = JID(jid.bare)
log.debug(f"Manually unsubscribing from {namespace} device list for {jid}")
node = {
twomemo.twomemo.NAMESPACE: TWOMEMO_DEVICE_LIST_NODE,
oldmemo.oldmemo.NAMESPACE: OLDMEMO_DEVICE_LIST_NODE
}.get(namespace, None)
if node is None:
raise UnknownNamespace(f"Unknown namespace during device list unsubscription: {namespace}")
xep_0060: XEP_0060 = self.xmpp["xep_0060"]
try:
await xep_0060.unsubscribe(jid, node)
except IqError as e:
# Don't really care about any of the possible Iq error cases:
# https://xmpp.org/extensions/xep-0060.html#subscriber-unsubscribe-error
# Worst case we keep receiving updates we don't need.
log.debug(f"Couldn't unsubscribe from {namespace} device list of {jid.bare}", exc_info=e)
await self.storage.store(f"/slixmpp/subscribed/{jid.bare}/{namespace}", False)
async def refresh_device_lists(self, jids: Set[JID], force_download: bool = False) -> None:
"""
Ensure that up-to-date device lists for the JIDs are cached. This is done automatically by
:meth:`encrypt_message`. You don't have to ever manually call this method, but you can do so for
optimization reasons. For example, in a UI-based IM application, this method can be called when an
OMEMO-enabled chat tab/window is opened, to be optimally prepared if the user decides to send an
encrypted message.
Args:
jids: The JIDs whose device lists to refresh. Can be bare (aka "userhost") JIDs but don't have
to.
force_download: Force downloading the device list even if pubsub/PEP are enabled to automatically
keep the cached device lists up-to-date.
Raises:
Exception: all exceptions raised by :meth:`SessionManager.refresh_device_lists` are forwarded
as-is.
"""
session_manager = await self.get_session_manager()
storage = self.storage
roster: RosterNode = self.xmpp.client_roster
for jid in jids:
jid = JID(jid.bare)
if jid.bare == self.xmpp.boundjid.bare:
# Skip ourselves
continue
# Track which namespaces require a manual refresh
refresh_namespaces: Set[str] = \
{ twomemo.twomemo.NAMESPACE, oldmemo.oldmemo.NAMESPACE } if force_download else set()
# PEP is "enabled" with mutual presence subscription and applies to all backends when enabled.
pep_enabled = jid in roster and roster[jid]["subscription"] == "both"
if not pep_enabled:
# If PEP is not enabled, check whether manual subscription is enabled instead. Manual
# subscription is tracked per-backend.
for namespace in [ twomemo.twomemo.NAMESPACE, oldmemo.oldmemo.NAMESPACE ]:
subscribed = (await storage.load_primitive(
f"/slixmpp/subscribed/{jid.bare}/{namespace}",
bool
)).maybe(None)
if not subscribed:
# If not subscribed already (or the subscription status is unknown), manually
# subscribe to stay up-to-date automatically in the future. This trusts that servers,
# even if they support multi-subscribe, would not generate exact duplicate
# subscriptions with differing subscription ids.
await self._subscribe(namespace, jid)
refresh_namespaces.add(namespace)
for namespace in refresh_namespaces:
# Force-download the device lists that need a manual refresh
try:
await session_manager.refresh_device_list(namespace, jid.bare)
except omemo.DeviceListDownloadFailed as e:
log.debug(f"Couldn't manually fetch {namespace} device list, probably doesn't exist: {e}")
async def encrypt_message(
self,
stanza: Message,
recipient_jids: Union[JID, Set[JID]],
identifier: Optional[str] = None
) -> Tuple[Dict[str, Message], FrozenSet[EncryptionError]]:
"""
Encrypt a message stanza. Selects the optimal OMEMO protocol version for each recipient device.
Twomemo encrypts the whole stanza using SCE, oldmemo encrypts only the body.
Args:
stanza: The stanza to encrypt.
recipient_jids: The JID of the recipients. Can be bare (aka "userhost") JIDs but doesn't have to.
A single JID can be used.
identifier: A value that is passed on to :meth:`_devices_blindly_trusted` and
:meth:`_prompt_manual_trust` in case a trust decision is required for any of the recipient
devices. This value is not processed or altered, it is simply passed through. Refer to the
documentation of :meth:`_devices_blindly_trusted` or :meth:`_prompt_manual_trust` for details.
Returns:
Encrypted messages ready to be sent and a set of non-critical errors encountered during
encryption. The key is the messages dictionary is the OMEMO version namespace, the value is the
encrypted message stanza for that OMEMO protocol version. The store hint is enabled on returned
stanzas.
Warning:
Encrypted message stanzas for oldmemo consist of only the bare minimum: the encrypted body and the
store hint. Other tags that can't be encrypted by oldmemo are _not_ automatically copied over from
the source stanza; this has to be done manually afterwards if desired.
Warning:
Messages without a body are not considered for oldmemo encryption.
Raises:
Exception: all exceptions raised by :meth:`SessionManager.encrypt` are forwarded as-is.
Tip:
In contrast to one to one messages, MUC messages are reflected to the sender. Thus, the sender
usually does not add messages to their local message log when sending them, but when the
reflection is received. This approach does not pair well with OMEMO, since for security reasons it
is forbidden to encrypt messages for the own device. Thus, when the reflection of an OMEMO message
is received, it can't be decrypted and added to the local message log as usual. To counteract
this, make sure the outgoing messages have some sort of id and cache the original stanza, such
that when the reflection is received, the plaintext can be looked up from the cache and added to
the local message log.
"""
if isinstance(recipient_jids, JID):
recipient_jids = { recipient_jids }
if not recipient_jids:
raise ValueError("At least one JID must be specified")
# Make sure all recipient device lists are available
await self.refresh_device_lists(recipient_jids)
recipient_bare_jids = frozenset({ recipient_jid.bare for recipient_jid in recipient_jids })
# Prepare the plaintext for all protocol versions
plaintexts: Dict[str, bytes] = {}
# Here I would prepare the plaintext for omemo:2 using my SCE plugin ... IF I HAD ONE!!!
# For oldmemo, only the body is encrypted
body: Optional[str] = stanza.get("body", None)
if body is not None:
plaintexts[oldmemo.oldmemo.NAMESPACE] = body.encode("utf-8")
log.debug(f"Plaintexts to encrypt: {plaintexts}")
# Exit early if there's no plaintext to encrypt
if len(plaintexts) == 0:
return {}, frozenset()
session_manager = await self.get_session_manager()
messages, encryption_errors = await session_manager.encrypt(
recipient_bare_jids,
plaintexts,
backend_priority_order=list(filter(
lambda namespace: namespace in plaintexts,
[ twomemo.twomemo.NAMESPACE, oldmemo.oldmemo.NAMESPACE ]
)),
identifier=identifier
)
encrypted_messages: Dict[str, Message] = {}
for message in messages:
namespace = message.namespace
message_elt: Optional[ET.Element] = None
if namespace == twomemo.twomemo.NAMESPACE:
message_elt = twomemo.etree.serialize_message(message)
if namespace == oldmemo.oldmemo.NAMESPACE:
message_elt = oldmemo.etree.serialize_message(message)
if message_elt is None:
raise UnknownNamespace(f"OMEMO version namespace {namespace} unknown")
stanza_copy = copy(stanza)
stanza_copy.clear()
stanza_copy.append(message_elt)
stanza_copy["body"] = self.fallback_message
stanza_copy.enable("store")
encrypted_messages[namespace] = stanza_copy
return encrypted_messages, encryption_errors
async def decrypt_message(self, stanza: Message) -> Tuple[Message, DeviceInformation]:
"""
Decrypt an OMEMO-encrypted message. Use :meth:`is_encrypted` to check whether a stanza contains an
OMEMO-encrypted message. The original stanza is not modified by this method. For oldmemo, the optional
fallback body is replaced with the decrypted content. For newmemo, the whole SCE stanza is returned.
Args:
stanza: The message stanza.
Returns:
The decrypted stanza and information about the sending device.
Raises:
ValueError: in case there is malformed data not caught be the XML schema validation.
ValueError: in case a groupchat message is passed but XEP-0045 is not loaded.
XMLSchemaValidationError: in case the element does not conform to the XML schema given in the
specification.
SenderNotFound: in case the public information about the sending device could not be found or is
incomplete.
Exception: all exceptions raised by :meth:`SessionManager.decrypt` are forwarded as-is.
"""
xmpp: BaseXMPP = self.xmpp
from_jid: JID = stanza.get_from()
sender_bare_jid: str
if stanza.get_type() == "groupchat":
xep_0045: Optional[XEP_0045] = xmpp["xep_0045"]
if not xep_0045:
raise ValueError("Attempt to decrypt groupchat message but XEP-0045 is not loaded")
real_jid = xep_0045.get_jid_property(JID(from_jid.bare), from_jid.resource, "jid")
if real_jid is None:
raise SenderNotFound(f"Couldn't find real JID of sender from groupchat JID {from_jid}")
sender_bare_jid = JID(real_jid).bare
else:
sender_bare_jid = from_jid.bare
session_manager = await self.get_session_manager()
message: Optional[omemo.Message] = None
encrypted_elt: Optional[ET.Element] = None
twomemo_encrypted_elt = stanza.xml.findall(f"{{{twomemo.twomemo.NAMESPACE}}}encrypted")
oldmemo_encrypted_elt = stanza.xml.findall(f"{{{oldmemo.oldmemo.NAMESPACE}}}encrypted")
if len(twomemo_encrypted_elt) > 1:
raise ValueError(
f"Stanza contains multiple encrypted elements in the {twomemo.twomemo.NAMESPACE} namespace"
)
if len(oldmemo_encrypted_elt) > 1:
raise ValueError(
f"Stanza contains multiple encrypted elements in the {oldmemo.oldmemo.NAMESPACE} namespace"
)
if len(twomemo_encrypted_elt) + len(oldmemo_encrypted_elt) > 1:
raise ValueError("Stanza contains a mix of encrypted elements in different OMEMO namespaces")
if len(twomemo_encrypted_elt) == 1:
encrypted_elt = twomemo_encrypted_elt[0]
message = twomemo.etree.parse_message(encrypted_elt, sender_bare_jid)
if len(oldmemo_encrypted_elt) == 1:
encrypted_elt = oldmemo_encrypted_elt[0]
message = await oldmemo.etree.parse_message(
encrypted_elt,
sender_bare_jid,
xmpp.boundjid.bare,
session_manager
)
if message is None or encrypted_elt is None:
raise ValueError(f"No supported encrypted content found in stanza: {message}")
plaintext, device_information, __ = await session_manager.decrypt(message)
if message.namespace == twomemo.twomemo.NAMESPACE:
# Do SCE unpacking here
raise NotImplementedError(f"SCE not supported yet. Plaintext: {plaintext}")
if message.namespace == oldmemo.oldmemo.NAMESPACE:
stanza = copy(stanza)
# Remove all body elements from the original element, since those act as fallbacks in case the
# encryption protocol is not supported
del stanza["body"]
if plaintext is not None:
# Add the decrypted body
stanza["body"] = plaintext.decode("utf-8")
return stanza, device_information
def is_encrypted(self, stanza: Message) -> Optional[str]:
"""
Args:
stanza: The stanza.
Returns:
The namespace of the OMEMO version this message is encrypted with, or `None` if the stanza is not
encrypted with any supported version of OMEMO.
"""
if stanza.xml.find(f"{{{twomemo.twomemo.NAMESPACE}}}encrypted") is not None:
return twomemo.twomemo.NAMESPACE
if stanza.xml.find(f"{{{oldmemo.oldmemo.NAMESPACE}}}encrypted") is not None:
return oldmemo.oldmemo.NAMESPACE
return None
slixmpp-omemo-1.2.2/tests/ 0000775 0000000 0000000 00000000000 14705742554 0015501 5 ustar 00root root 0000000 0000000 slixmpp-omemo-1.2.2/tests/__init__.py 0000664 0000000 0000000 00000000040 14705742554 0017604 0 ustar 00root root 0000000 0000000 # To make relative imports work
slixmpp-omemo-1.2.2/tests/test_plugin.py 0000664 0000000 0000000 00000000336 14705742554 0020412 0 ustar 00root root 0000000 0000000 import pytest
import slixmpp_omemo
__all__ = [
"test_placeholder"
]
pytestmark = pytest.mark.asyncio
async def test_placeholder() -> None:
"""
Placeholder test.
"""
print(slixmpp_omemo.version)