././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1712130070.0600474 synadm-0.46/0000755000076500000240000000000000000000000012252 5ustar00jacksonstaff././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1694375787.0 synadm-0.46/LICENSE0000644000076500000240000010451400000000000013264 0ustar00jacksonstaff GNU GENERAL PUBLIC LICENSE Version 3, 29 June 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 General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is 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. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. 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. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. 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 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. Use with the GNU Affero General Public License. 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 Affero 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 special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU 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 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 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 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 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". 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 GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read .././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1712130070.0594678 synadm-0.46/PKG-INFO0000644000076500000240000003457500000000000013365 0ustar00jacksonstaffMetadata-Version: 2.1 Name: synadm Version: 0.46 Summary: Command line admin tool for Synapse (Matrix reference homeserver) Home-page: https://github.com/joj0/synadm Author: Johannes Tiefenbacher Author-email: jt@peek-a-boo.at License: GPLv3+ Project-URL: Bug Tracker, https://github.com/joj0/synadm/issues Project-URL: Documentation, https://github.com/joj0/synadm Project-URL: Source Code, https://github.com/joj0/synadm Classifier: License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+) Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.6 Classifier: Programming Language :: Python :: 3.7 Classifier: Programming Language :: Python :: 3.8 Classifier: Programming Language :: Python :: 3.9 Classifier: Programming Language :: Python :: 3.10 Classifier: Operating System :: OS Independent Classifier: Topic :: System :: Systems Administration Classifier: Topic :: Communications :: Chat Classifier: Environment :: Console Description-Content-Type: text/markdown License-File: LICENSE Requires-Dist: Click<9.0,>=7.1 Requires-Dist: requests Requires-Dist: tabulate Requires-Dist: PyYaml Requires-Dist: click-option-group>=0.5.2 Requires-Dist: dnspython # synadm - the Matrix-Synapse admin CLI - [About](#about) - [Prerequisites](#prerequisites) - [Installation](#installation) - [Install from PyPI](#install-from-pypi) - [Install from git](#install-from-git) - [Configuration](#configuration) - [Getting an Admin Token](#getting-an-admin-token) - [The configurator](#the-configurator) - [matrix-docker-ansible-deploy](#matrix-docker-ansible-deploy) - [Usage](#usage) - [Command Line Reference](#command-line-reference) - [Advanced Usage](#advanced-usage) - [Update](#update) - [Update PyPI Package](#update-pypi-package) - [Update git Installation](#update-git-installation) - [Implementation Status / Commands List](#implementation-status--commands-list) - [Get in Touch](#get-in-touch) - [Contributing](#contributing) ## About A CLI tool to help admins of [Matrix-Synapse homeservers](https://github.com/matrix-org/synapse) conveniently issue commands available via its [Admin API](https://element-hq.github.io/synapse/develop/usage/administration/admin_api/index.html#the-admin-api). ## Prerequisites - Python 3.6+ - a running Synapse instance - an admin-enabled user on the instance - the admin user's access token `synadm` is designed to run either directly on the host running the Synapse instance or on a remote machine able to access Synapse's API port. Synapse's default Admin API endpoint address usually is http://localhost:8008/_synapse/admin or https://localhost:8448/_synapse/admin. ## Installation ### Install from PyPI `pip3 install synadm` ### Install from git #### 1. Check Python Version `python3 --version` should show at least v3.6.x #### 2. Clone Repo: ``` git clone https://github.com/joj0/synadm ``` #### 3. Install Package Globally This will install `synadm` and all dependent Python packages to your system's global Python site-packages directory: ``` cd synadm sudo pip install . ``` *Note: If you get an import error for setuptools, make sure the package is installed. Debian based systems: `sudo apt install python3-setuptools`, RedHat based: `sudo yum install python3-setuptools`* #### 4. Run `synadm` should now run fine without having to add a path in front of it: ``` synadm -h ``` *Note: Usually setuptools installs a command wrapper to `/usr/local/bin/synadm`, but that depends on your system.* *Note: In case you don't want `synadm` to be installed to a global system directory, you can find an [alternative way of installing](CONTRIBUTING.md#getting-the-source--installing) in the contribution docs*. *Note: synadm is multi-user aware - it stores its configuration inside the executing user's home directory. See chapter [configuration](#configuration).* ## Configuration ### Getting an Admin Token To find out your admin user's token in Element-Web: _Login as this user - "Click User Avatar" - "All Settings" - "Help & About" - Scroll down - "Advanced" - "Access Token"_ Or use synadm to fetch a token already. Use the fully qualified Matrix ID of the admin user: ``` synadm matrix login @admin_username:yourdomain.org Password: ``` If you issue this command in a fresh `synadm` installation, [the configurator](#the-configurator) will launch anyway. - Answer the questions. - Set token to "invalid" at first, to convience `synadm` to launch the `matrix login` command (otherwise you'd get a "Configuration incomplete" error). - After successfully entering your admin password you will be presented a token which you can finally set by re-launching the configurator as described below. ### The configurator `synadm` asks for necessary configuration items on first launch automatically. Also whenever new mandatory configuration items where added (eg after an update), the user will be prompted for missing items automatically. Configuration can be changed any time by launching the configurator directly: ``` synadm config ``` Configuration will be saved in `~/.config/synadm.yaml` *Note: Be aware that once you configured `synadm`, your admin user's token is saved in the configuration file. On Posix compatible systems permissions are set to mode 0600, on other OS's it is your responsibilty to change permissions accordingly.* ### matrix-docker-ansible-deploy To use `synadm` with Synapse homeservers that were installed using [matrix-docker-ansible-deploy](https://github.com/spantaleev/matrix-docker-ansible-deploy) you have two options. Access the Synapse Admin API's "via the public endpoint" similar to a Matrix client. - In [vars.yaml](https://github.com/spantaleev/matrix-docker-ansible-deploy/blob/master/docs/configuring-playbook.md#configuring-the-ansible-playbook) set `matrix_nginx_proxy_proxy_matrix_client_api_forwarded_location_synapse_admin_api_enabled: true`. - The API's are accessible on the Client-Server API port, at `https://matrix.DOMAIN`. - Install `synadm` on your Docker host or on a separate machine. - Configure `synadm` to access at `https://matrix.DOMAIN:443/_synapse/admin` Alternatively, you can access the API's on the container network `matrix`. - Synapse is accessible via the hostname `matrix-synapse` resolved by the internal Docker DNS server. - The containers are connected internally via a network named `matrix` by default. - Start a container on that same network and install `synadm` into it. - Configure `synadm` to access at `http://matrix-synapse:8008/_synapse/admin` (http here, not https). Find some more details about the topic in [this issue post on the matrix-docker-ansible-deploy repo](https://github.com/spantaleev/matrix-docker-ansible-deploy/issues/1846#issuecomment-1135516112). _Note that currently `synadm` is using a part of the Server-Server (Federation) API (`keys/v2/server`) to retrieve "its own homeserver name". This affects some of the `media` management commands. By default and also as the Matrix spec recommends, this API is not accessible via the Client-Server API port. We are working on a better solution to retrieve the own servername but as a workaround the `key` API's can be exposed by setting `matrix_synapse_http_listener_resource_names: ["client","keys"]` in [vars.yaml](https://github.com/spantaleev/matrix-docker-ansible-deploy/blob/master/docs/configuring-playbook.md#configuring-the-ansible-playbook)._ Find more details about the topic [here](https://github.com/spantaleev/matrix-docker-ansible-deploy/issues/1761#issuecomment-1101170229). ## Usage Use the online help of the main command: ``` synadm -h ``` and of the available subcommands: ``` synadm version -h synadm user -h synadm room -h ``` You even can spare the `-h` option, `synadm` will show some abbreviated help for the executed subcommand anyway. For example: ``` synadm user ``` or ``` synadm user details ``` will show essential help for the particular subcommand right away. *Note: A list of currently available commands is found in chapter [implementation status / commands list](#implementation-status--commands-list)* as well as in the following chapter. ### Command Line Reference A detailed [Command Line Reference](https://synadm.readthedocs.io/en/latest/index_cli_reference.html) can be found in `synadm's` readthedocs documentation. ### Advanced Usage Examples of how `synadm` can be used in shell scripts and oneliners is provided in the [Scripting Examples](https://synadm.readthedocs.io/en/latest/examples.html) docs chapter. ## Update ### Update PyPI Package ``` pip3 install synadm --upgrade ``` ### Update git Installation To update `synadm` to the latest development state, just update your git repo and reinstall: ``` cd synadm git pull pip install . ``` *Note: If you installed it to a Python venv, [activate it](CONTRIBUTING.md#3-set-up-a-python3-virtual-environment).* *Note: If you installed it in [editable mode](CONTRIBUTING.md#4-install-in-editable-mode) (or for development), you can spare the `pip install .` command - just `git pull` and you're done.* ## Implementation Status / Commands List [Follow this link to the official Synapse Admin API docs](https://element-hq.github.io/synapse/develop/usage/administration/admin_api/index.html) - direct links to the specific API documentation pages are provided in the list below. *Note: Most commands have several optional arguments available. Put -h after any of the below listed commands to view them or have a look at the [Command Line Reference](https://synadm.readthedocs.io/en/latest/index_cli_reference.html).* * [ ] [Account Validity](https://element-hq.github.io/synapse/develop/admin_api/account_validity.html) * [x] [Delete Group](https://element-hq.github.io/synapse/develop/admin_api/delete_group.html) (delete community) * [ ] [Event Reports](https://element-hq.github.io/synapse/develop/admin_api/event_reports.html) * [x] [Media Admin](https://element-hq.github.io/synapse/develop/admin_api/media_admin_api.html) * [x] `media list -r ` * [x] `media list -u ` (alias of `user media `) * [x] `media quarantine -s -i ` * [x] `media quarantine -r ` * [x] `media quarantine -u ` * [x] `media protect ` * [x] `media delete -s -i ` * [x] `media delete -s --before --size 1024` * [x] `media purge --before ` (purge remote media API) * [x] [Purge History](https://element-hq.github.io/synapse/develop/admin_api/purge_history_api.html) * [x] `history purge ` * [x] `history purge-status ` * [x] ~~[Purge Rooms](https://element-hq.github.io/synapse/develop/admin_api/purge_room.html)~~ (DEPRECATED, covered by `room delete`) * [ ] [Register Users](https://element-hq.github.io/synapse/develop/admin_api/register_api.html) * [x] [Manipulate Room Membership](https://element-hq.github.io/synapse/develop/admin_api/room_membership.html) * [x] `room join` * [x] [Rooms](https://element-hq.github.io/synapse/develop/admin_api/rooms.html) * [x] `room list` * [x] `room details ` * [x] `room members ` * [x] `room delete ` * [x] `room make-admin ` * [x] `room state ` * [ ] Additional commands and aliases around room management * [x] `room search ` (alias of `room list -n `) * [x] `room resolve ` * [x] `room power-levels` * [x] `room block` * [x] `room block-status` * [x] [Server Notices](https://element-hq.github.io/synapse/develop/admin_api/server_notices.html) * [x] ~~[Shutdown Room](https://element-hq.github.io/synapse/develop/admin_api/shutdown_room.html)~~ (DEPRECATED, covered by `room delete`) * [ ] [Statistics](https://element-hq.github.io/synapse/develop/admin_api/statistics.html) * [ ] `synadm media user-stats` * [ ] `synadm room largest` * [x] [Users](https://element-hq.github.io/synapse/develop/admin_api/user_admin_api.html) * [x] `user details ` * [x] `user modify ` (also used for user creation) * [x] `user list` * [x] `user deactivate ` (including GDPR erase) * [x] `user password ` * [x] `user membership ` * [x] `user whois ` * [x] `user shadow-ban ` * [x] `user media -u ` (also available as `media list -u `) * [x] `user login ` * [ ] Additional commands and aliases around user management * [x] `user search ` (shortcut to `user list -d -g -n `) * [ ] `user create ` (alias of `user modify ...`) * [x] `user prune-devices ` * [x] [Server Version](https://element-hq.github.io/synapse/develop/admin_api/version_api.html) * [x] `version` * [x] [Registration Tokens](https://element-hq.github.io/synapse/latest/usage/administration/admin_api/registration_tokens.html) * [x] `regtok list` * [x] `regtok details ` * [x] `regtok new` * [x] `regtok update ` * [x] `regtok delete ` ## Get in Touch If you need advice on using synadm, have a feature idea or would like to discuss anything else around `synadm`, get in touch via Matrix! We are hanging around in the official support room for Synapse, [#synapse:matrix.org](https://matrix.to/#/#synapse:matrix.org). Usually you'll find `synadm` users there that might answer your questions already. If not, mentioning `synadm` will ping us with the help of Element's keyword notify feature and we'll try to get in touch. The most direct way to reach synadm maintainers as well as seasoned users and Synapse admins is by joining [#synadm:peek-a-boo.at](https://matrix.to/#/#synadm:peek-a-boo.at). If you are sure you've found a bug that was not already reported, certainly directly opening an [issue on GitHub](https://github.com/JOJ0/synadm/issues) is a valid option too. If unsure, ask in [#synadm:peek-a-boo.at](https://matrix.to/#/#synadm:peek-a-boo.at) first. ## Contributing First of all, thanks for your interest in contributing to `synadm`! We appreciate any help, no matter if you are a programmer or a user. Both groups can do valuable things for the `synadm` project. We love providing a useful tool to fellow Synapse sysadmins but rely on contribution from the Synapse and Matrix community to keep `synadm` useful, current and stable. Please review the [contributing docs](CONTRIBUTING.md) for guidelines and help around the topic! ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1712129307.0 synadm-0.46/README.md0000644000076500000240000003227200000000000013537 0ustar00jacksonstaff # synadm - the Matrix-Synapse admin CLI - [About](#about) - [Prerequisites](#prerequisites) - [Installation](#installation) - [Install from PyPI](#install-from-pypi) - [Install from git](#install-from-git) - [Configuration](#configuration) - [Getting an Admin Token](#getting-an-admin-token) - [The configurator](#the-configurator) - [matrix-docker-ansible-deploy](#matrix-docker-ansible-deploy) - [Usage](#usage) - [Command Line Reference](#command-line-reference) - [Advanced Usage](#advanced-usage) - [Update](#update) - [Update PyPI Package](#update-pypi-package) - [Update git Installation](#update-git-installation) - [Implementation Status / Commands List](#implementation-status--commands-list) - [Get in Touch](#get-in-touch) - [Contributing](#contributing) ## About A CLI tool to help admins of [Matrix-Synapse homeservers](https://github.com/matrix-org/synapse) conveniently issue commands available via its [Admin API](https://element-hq.github.io/synapse/develop/usage/administration/admin_api/index.html#the-admin-api). ## Prerequisites - Python 3.6+ - a running Synapse instance - an admin-enabled user on the instance - the admin user's access token `synadm` is designed to run either directly on the host running the Synapse instance or on a remote machine able to access Synapse's API port. Synapse's default Admin API endpoint address usually is http://localhost:8008/_synapse/admin or https://localhost:8448/_synapse/admin. ## Installation ### Install from PyPI `pip3 install synadm` ### Install from git #### 1. Check Python Version `python3 --version` should show at least v3.6.x #### 2. Clone Repo: ``` git clone https://github.com/joj0/synadm ``` #### 3. Install Package Globally This will install `synadm` and all dependent Python packages to your system's global Python site-packages directory: ``` cd synadm sudo pip install . ``` *Note: If you get an import error for setuptools, make sure the package is installed. Debian based systems: `sudo apt install python3-setuptools`, RedHat based: `sudo yum install python3-setuptools`* #### 4. Run `synadm` should now run fine without having to add a path in front of it: ``` synadm -h ``` *Note: Usually setuptools installs a command wrapper to `/usr/local/bin/synadm`, but that depends on your system.* *Note: In case you don't want `synadm` to be installed to a global system directory, you can find an [alternative way of installing](CONTRIBUTING.md#getting-the-source--installing) in the contribution docs*. *Note: synadm is multi-user aware - it stores its configuration inside the executing user's home directory. See chapter [configuration](#configuration).* ## Configuration ### Getting an Admin Token To find out your admin user's token in Element-Web: _Login as this user - "Click User Avatar" - "All Settings" - "Help & About" - Scroll down - "Advanced" - "Access Token"_ Or use synadm to fetch a token already. Use the fully qualified Matrix ID of the admin user: ``` synadm matrix login @admin_username:yourdomain.org Password: ``` If you issue this command in a fresh `synadm` installation, [the configurator](#the-configurator) will launch anyway. - Answer the questions. - Set token to "invalid" at first, to convience `synadm` to launch the `matrix login` command (otherwise you'd get a "Configuration incomplete" error). - After successfully entering your admin password you will be presented a token which you can finally set by re-launching the configurator as described below. ### The configurator `synadm` asks for necessary configuration items on first launch automatically. Also whenever new mandatory configuration items where added (eg after an update), the user will be prompted for missing items automatically. Configuration can be changed any time by launching the configurator directly: ``` synadm config ``` Configuration will be saved in `~/.config/synadm.yaml` *Note: Be aware that once you configured `synadm`, your admin user's token is saved in the configuration file. On Posix compatible systems permissions are set to mode 0600, on other OS's it is your responsibilty to change permissions accordingly.* ### matrix-docker-ansible-deploy To use `synadm` with Synapse homeservers that were installed using [matrix-docker-ansible-deploy](https://github.com/spantaleev/matrix-docker-ansible-deploy) you have two options. Access the Synapse Admin API's "via the public endpoint" similar to a Matrix client. - In [vars.yaml](https://github.com/spantaleev/matrix-docker-ansible-deploy/blob/master/docs/configuring-playbook.md#configuring-the-ansible-playbook) set `matrix_nginx_proxy_proxy_matrix_client_api_forwarded_location_synapse_admin_api_enabled: true`. - The API's are accessible on the Client-Server API port, at `https://matrix.DOMAIN`. - Install `synadm` on your Docker host or on a separate machine. - Configure `synadm` to access at `https://matrix.DOMAIN:443/_synapse/admin` Alternatively, you can access the API's on the container network `matrix`. - Synapse is accessible via the hostname `matrix-synapse` resolved by the internal Docker DNS server. - The containers are connected internally via a network named `matrix` by default. - Start a container on that same network and install `synadm` into it. - Configure `synadm` to access at `http://matrix-synapse:8008/_synapse/admin` (http here, not https). Find some more details about the topic in [this issue post on the matrix-docker-ansible-deploy repo](https://github.com/spantaleev/matrix-docker-ansible-deploy/issues/1846#issuecomment-1135516112). _Note that currently `synadm` is using a part of the Server-Server (Federation) API (`keys/v2/server`) to retrieve "its own homeserver name". This affects some of the `media` management commands. By default and also as the Matrix spec recommends, this API is not accessible via the Client-Server API port. We are working on a better solution to retrieve the own servername but as a workaround the `key` API's can be exposed by setting `matrix_synapse_http_listener_resource_names: ["client","keys"]` in [vars.yaml](https://github.com/spantaleev/matrix-docker-ansible-deploy/blob/master/docs/configuring-playbook.md#configuring-the-ansible-playbook)._ Find more details about the topic [here](https://github.com/spantaleev/matrix-docker-ansible-deploy/issues/1761#issuecomment-1101170229). ## Usage Use the online help of the main command: ``` synadm -h ``` and of the available subcommands: ``` synadm version -h synadm user -h synadm room -h ``` You even can spare the `-h` option, `synadm` will show some abbreviated help for the executed subcommand anyway. For example: ``` synadm user ``` or ``` synadm user details ``` will show essential help for the particular subcommand right away. *Note: A list of currently available commands is found in chapter [implementation status / commands list](#implementation-status--commands-list)* as well as in the following chapter. ### Command Line Reference A detailed [Command Line Reference](https://synadm.readthedocs.io/en/latest/index_cli_reference.html) can be found in `synadm's` readthedocs documentation. ### Advanced Usage Examples of how `synadm` can be used in shell scripts and oneliners is provided in the [Scripting Examples](https://synadm.readthedocs.io/en/latest/examples.html) docs chapter. ## Update ### Update PyPI Package ``` pip3 install synadm --upgrade ``` ### Update git Installation To update `synadm` to the latest development state, just update your git repo and reinstall: ``` cd synadm git pull pip install . ``` *Note: If you installed it to a Python venv, [activate it](CONTRIBUTING.md#3-set-up-a-python3-virtual-environment).* *Note: If you installed it in [editable mode](CONTRIBUTING.md#4-install-in-editable-mode) (or for development), you can spare the `pip install .` command - just `git pull` and you're done.* ## Implementation Status / Commands List [Follow this link to the official Synapse Admin API docs](https://element-hq.github.io/synapse/develop/usage/administration/admin_api/index.html) - direct links to the specific API documentation pages are provided in the list below. *Note: Most commands have several optional arguments available. Put -h after any of the below listed commands to view them or have a look at the [Command Line Reference](https://synadm.readthedocs.io/en/latest/index_cli_reference.html).* * [ ] [Account Validity](https://element-hq.github.io/synapse/develop/admin_api/account_validity.html) * [x] [Delete Group](https://element-hq.github.io/synapse/develop/admin_api/delete_group.html) (delete community) * [ ] [Event Reports](https://element-hq.github.io/synapse/develop/admin_api/event_reports.html) * [x] [Media Admin](https://element-hq.github.io/synapse/develop/admin_api/media_admin_api.html) * [x] `media list -r ` * [x] `media list -u ` (alias of `user media `) * [x] `media quarantine -s -i ` * [x] `media quarantine -r ` * [x] `media quarantine -u ` * [x] `media protect ` * [x] `media delete -s -i ` * [x] `media delete -s --before --size 1024` * [x] `media purge --before ` (purge remote media API) * [x] [Purge History](https://element-hq.github.io/synapse/develop/admin_api/purge_history_api.html) * [x] `history purge ` * [x] `history purge-status ` * [x] ~~[Purge Rooms](https://element-hq.github.io/synapse/develop/admin_api/purge_room.html)~~ (DEPRECATED, covered by `room delete`) * [ ] [Register Users](https://element-hq.github.io/synapse/develop/admin_api/register_api.html) * [x] [Manipulate Room Membership](https://element-hq.github.io/synapse/develop/admin_api/room_membership.html) * [x] `room join` * [x] [Rooms](https://element-hq.github.io/synapse/develop/admin_api/rooms.html) * [x] `room list` * [x] `room details ` * [x] `room members ` * [x] `room delete ` * [x] `room make-admin ` * [x] `room state ` * [ ] Additional commands and aliases around room management * [x] `room search ` (alias of `room list -n `) * [x] `room resolve ` * [x] `room power-levels` * [x] `room block` * [x] `room block-status` * [x] [Server Notices](https://element-hq.github.io/synapse/develop/admin_api/server_notices.html) * [x] ~~[Shutdown Room](https://element-hq.github.io/synapse/develop/admin_api/shutdown_room.html)~~ (DEPRECATED, covered by `room delete`) * [ ] [Statistics](https://element-hq.github.io/synapse/develop/admin_api/statistics.html) * [ ] `synadm media user-stats` * [ ] `synadm room largest` * [x] [Users](https://element-hq.github.io/synapse/develop/admin_api/user_admin_api.html) * [x] `user details ` * [x] `user modify ` (also used for user creation) * [x] `user list` * [x] `user deactivate ` (including GDPR erase) * [x] `user password ` * [x] `user membership ` * [x] `user whois ` * [x] `user shadow-ban ` * [x] `user media -u ` (also available as `media list -u `) * [x] `user login ` * [ ] Additional commands and aliases around user management * [x] `user search ` (shortcut to `user list -d -g -n `) * [ ] `user create ` (alias of `user modify ...`) * [x] `user prune-devices ` * [x] [Server Version](https://element-hq.github.io/synapse/develop/admin_api/version_api.html) * [x] `version` * [x] [Registration Tokens](https://element-hq.github.io/synapse/latest/usage/administration/admin_api/registration_tokens.html) * [x] `regtok list` * [x] `regtok details ` * [x] `regtok new` * [x] `regtok update ` * [x] `regtok delete ` ## Get in Touch If you need advice on using synadm, have a feature idea or would like to discuss anything else around `synadm`, get in touch via Matrix! We are hanging around in the official support room for Synapse, [#synapse:matrix.org](https://matrix.to/#/#synapse:matrix.org). Usually you'll find `synadm` users there that might answer your questions already. If not, mentioning `synadm` will ping us with the help of Element's keyword notify feature and we'll try to get in touch. The most direct way to reach synadm maintainers as well as seasoned users and Synapse admins is by joining [#synadm:peek-a-boo.at](https://matrix.to/#/#synadm:peek-a-boo.at). If you are sure you've found a bug that was not already reported, certainly directly opening an [issue on GitHub](https://github.com/JOJ0/synadm/issues) is a valid option too. If unsure, ask in [#synadm:peek-a-boo.at](https://matrix.to/#/#synadm:peek-a-boo.at) first. ## Contributing First of all, thanks for your interest in contributing to `synadm`! We appreciate any help, no matter if you are a programmer or a user. Both groups can do valuable things for the `synadm` project. We love providing a useful tool to fellow Synapse sysadmins but rely on contribution from the Synapse and Matrix community to keep `synadm` useful, current and stable. Please review the [contributing docs](CONTRIBUTING.md) for guidelines and help around the topic! ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1712130070.0601346 synadm-0.46/setup.cfg0000644000076500000240000000004600000000000014073 0ustar00jacksonstaff[egg_info] tag_build = tag_date = 0 ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1712130008.0 synadm-0.46/setup.py0000755000076500000240000000430500000000000013771 0ustar00jacksonstaff# -*- coding: utf-8 -*- # synadm # Copyright (C) 2020-2023 Johannes Tiefenbacher # # synadm is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # synadm 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . from setuptools import setup, find_packages with open('README.md') as f: long_description = f.read() setup( name="synadm", version="0.46", author="Johannes Tiefenbacher", author_email="jt@peek-a-boo.at", description="Command line admin tool for Synapse (Matrix reference homeserver)", long_description=long_description, long_description_content_type="text/markdown", url="https://github.com/joj0/synadm", project_urls={ "Bug Tracker": "https://github.com/joj0/synadm/issues", "Documentation": "https://github.com/joj0/synadm", "Source Code": "https://github.com/joj0/synadm" }, license="GPLv3+", classifiers=[ "License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Operating System :: OS Independent", "Topic :: System :: Systems Administration", "Topic :: Communications :: Chat", "Environment :: Console" ], packages=find_packages(), install_requires=[ "Click>=7.1,<9.0", "requests", "tabulate", "PyYaml", "click-option-group>=0.5.2", "dnspython" ], entry_points=""" [console_scripts] synadm=synadm.cli:root """, ) ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1712130070.0462356 synadm-0.46/synadm/0000755000076500000240000000000000000000000013545 5ustar00jacksonstaff././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1694375787.0 synadm-0.46/synadm/__init__.py0000644000076500000240000000000000000000000015644 0ustar00jacksonstaff././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1711541543.0 synadm-0.46/synadm/__main__.py0000644000076500000240000000202600000000000015637 0ustar00jacksonstaff# -*- coding: utf-8 -*- # synadm # Copyright (C) 2023 Nicolas Peugnet # # synadm is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # synadm 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . """Alternative entry point for running synadm synadm is typically installed via pip, utilizing setuptools-configured entry points for accessibility as `synadm`. This file allows execution without formal installation using `python -m synadm`, which proves useful, for instance, in Debian GNU/Linux packaging. """ from synadm.cli import root root() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1712129429.0 synadm-0.46/synadm/api.py0000644000076500000240000015666400000000000014712 0ustar00jacksonstaff# -*- coding: utf-8 -*- # synadm # Copyright (C) 2020-2023 Johannes Tiefenbacher # # synadm is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # synadm 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . """Synapse Admin API and regular Matrix API clients Most API calls defined in this module respect the API's defaults and only pass what's necessary in the request body. A fully qualified Matrix user ID looks like this: @user:server, where server often is a domain name only, e.g @user@example.org See https://github.com/matrix-org/synapse/tree/master/docs/admin_api for documentation of the Synapse Admin APIs and the Matrix spec at https://matrix.org/docs/spec/#matrix-apis. """ import requests from http.client import HTTPConnection import datetime import json import urllib.parse import re class ApiRequest: """Basic API request handling and helper utilities This is subclassed by SynapseAdmin and Matrix """ def __init__(self, log, user, token, base_url, path, timeout, debug, verify=None): """Initialize an APIRequest object Args: log (logger object): an already initialized logger object user (string): the user with access to the API (currently unused). This can either be the fully qualified Matrix user ID, or just the localpart of the user ID. token (string): the API user's token base_url (string): URI e.g https://fqdn:port path (string): the path to the API endpoint; it's put after base_url to form the basis for all API endpoint paths timeout (int): requests module timeout used in query method debug (bool): enable/disable debugging in requests module verify(bool): SSL verification is turned on by default and can be turned off using this argument. """ self.log = log self.user = user self.token = token self.base_url = base_url.strip("/") self.path = path.strip("/") self.headers = { "Accept": "application/json", "Authorization": "Bearer " + self.token } self.timeout = timeout if debug: HTTPConnection.debuglevel = 1 self.verify = verify def query(self, method, urlpart, params=None, data=None, token=None, base_url_override=None, verify=None, *args, **kwargs): """Generic wrapper around requests methods. Handles requests methods, logging and exceptions, and URL encoding. Args: urlpart (string): The path to the API endpoint, excluding self.base_url and self.path (the part after proto://fqdn:port/path). It will be passed to Python's str.format, so the string should not be already formatted (as f-strings or with str.format) as to sanitize the URL. params (dict, optional): URL parameters (?param1&paarm2). Defaults to None. data (dict, optional): Request body used in POST, PUT, DELETE requests. Defaults to None. base_url_override (bool): The default setting of self.base_url set on initialization can be overwritten using this argument. verify(bool): Mandatory SSL verification is turned on by default and can be turned off using this method. *args: Arguments that will be URL encoded and passed to Python's str.format. **kwargs: Keyword arguments that will be URL encoded (only the values) and passed to Python's str.format. Returns: string or None: Usually a JSON string containing the response of the API; responses that are not 200(OK) (usally error messages returned by the API) will also be returned as JSON strings. On exceptions the error type and description are logged and None is returned. """ args = list(args) kwargs = dict(kwargs) for i in range(len(args)): args[i] = urllib.parse.quote(args[i], safe="") for i in kwargs.keys(): kwargs[i] = urllib.parse.quote(kwargs[i], safe="") urlpart = urlpart.format(*args, **kwargs) if base_url_override: self.log.debug("base_url override!") url = f"{base_url_override}/{self.path}/{urlpart}" host_descr = urllib.parse.urlparse(base_url_override).netloc else: url = f"{self.base_url}/{self.path}/{urlpart}" host_descr = "Synapse" self.log.info("Querying %s on %s", method, url) if token: self.log.debug("Token override! Adjusting headers.") self.headers["Authorization"] = "Bearer " + token override_verify = self.verify if verify is not None: override_verify = verify try: resp = requests.request( method, url, headers=self.headers, timeout=self.timeout, params=params, json=data, verify=override_verify ) if not resp.ok: self.log.warning(f"{host_descr} returned status code " f"{resp.status_code}") return resp.json() except Exception as error: self.log.error("%s while querying %s: %s", type(error).__name__, host_descr, error) return None def _timestamp_from_days_ago(self, days): """Get a unix timestamp in ms from days ago Args: days (int): number of days Returns: int: a unix timestamp in milliseconds (ms) """ return int(( datetime.datetime.now() - datetime.timedelta(days=days) ).timestamp() * 1000) def _timestamp_from_days_ahead(self, days): """Get a unix timestamp in ms for the given number of days ahead Args: days (int): number of days Returns: int: a unix timestamp in milliseconds (ms) """ return int(( datetime.datetime.now() + datetime.timedelta(days=days) ).timestamp() * 1000) def _timestamp_from_datetime(self, _datetime): """Get a unix timestamp in ms from a datetime object Args: _datetime (datetime object): an object built by datetime.datetime Returns: int: a unix timestamp in milliseconds (ms) """ return int(_datetime.timestamp()) * 1000 def _datetime_from_timestamp(self, timestamp, as_str=False): """ Get a datetime object from a unix timestamp in ms Args: timestamp (int): a unix timestamp in milliseconds (ms) Returns: datetime object: an object built by datetime.datetime. If as_str is set, return a string formatted by self._format_datetime() instead. """ dt_o = datetime.datetime.fromtimestamp(timestamp / 1000) if as_str: return self._format_datetime(dt_o) else: return dt_o def _format_datetime(self, datetime_obj): """ Get a formatted date as a string. Args: datetime_obj (int): A datetime object. Returns: string: A date in the format we use it throughout synadm. No sanity checking. """ return datetime_obj.strftime("%Y-%m-%d %H:%M:%S") class MiscRequest(ApiRequest): """ Miscellaneous HTTP requests Inheritance: ApiRequest (object): parent class containing general properties and methods for requesting REST API's """ def __init__(self, log, timeout, debug, verify=None): """Initialize the MiscRequest object Args: log (logger object): an already initialized logger object timeout (int): requests module timeout used in ApiRequest.query method debug (bool): enable/disable debugging in requests module verify(bool): SSL verification is turned on by default and can be turned off using this method. """ super().__init__( log, "", "", # Set user and token to empty string "", "", # Set base_url and path to empty string timeout, debug, verify ) def federation_uri_well_known(self, base_url): """Retrieve the URI to the Server-Server (Federation) API port via the .well-known resource of a Matrix server/domain. Args: base_url: proto://name or proto://fqdn Returns: string: https://fqdn:port of the delegated server for Server-Server communication between Matrix homeservers or None on errors. """ resp = self.query( "get", ".well-known/matrix/server", base_url_override=base_url, ) if resp is not None: if ":" in resp["m.server"]: return "https://" + resp["m.server"] else: return "https://" + resp["m.server"] + ":8448" self.log.error(".well-known/matrix/server could not be fetched.") return None class Matrix(ApiRequest): """ Matrix API client Inheritance: ApiRequest (object): parent class containing general properties and methods for requesting REST API's """ def __init__(self, log, user, token, base_url, matrix_path, timeout, debug, verify): """Initialize the Matrix API object Args: log (logger object): an already initialized logger object user (string): the user with access to the Matrix API (currently unused); This can either be the fully qualified Matrix user ID, or just the localpart of the user ID. token (string): the Matrix API user's token base_url (string): URI e.g https://fqdn:port path (string): the path to the API endpoint; it's put after base_url and forms the basis for all API endpoint paths timeout (int): requests module timeout used in ApiRequest.query method debug (bool): enable/disable debugging in requests module verify(bool): SSL verification is turned on by default and can be turned off using this method. """ super().__init__( log, user, token, base_url, matrix_path, timeout, debug, verify ) self.user = user def user_login(self, user_id, password): """Login as a Matrix user and retrieve an access token Args: user_id (string): a fully qualified Matrix user ID password (string): the Matrix user's password Returns: string: JSON string containing a token suitable to access the Matrix API on the user's behalf, a device_id and some more details on Matrix server and user. """ return self.query("post", "client/r0/login", data={ "password": password, "type": "m.login.password", "user": f"{user_id}", "initial_device_display_name": "synadm matrix login command" }) def room_get_id(self, room_alias): """ Get the room ID for a given room alias Args: room_alias (string): A Matrix room alias (#name:example.org) Returns: string, dict or None: A dict containing the room ID for the alias. If room_id is missing in the response we return the whole response as it might contain Synapse's error message. """ room_directory = self.query( "get", "client/r0/directory/room/{room_alias}", room_alias=room_alias ) if "room_id" in room_directory: return room_directory["room_id"] else: return room_directory # might contain useful error message def room_get_aliases(self, room_id): """ Get a list of room aliases for a given room ID Args: room_id (string): A Matrix room ID (!abc123:example.org) Returns: dict or None: A dict containing a list of room aliases, Synapse's error message or None on exceptions. """ return self.query( "get", "client/r0/rooms/{room_id}/aliases", room_id=room_id ) def raw_request(self, endpoint, method, data, token=None): data_dict = {} if method != "get": self.log.debug("The data we are trying to parse and submit:") self.log.debug(data) try: # user provided json might be crap data_dict = json.loads(data) except Exception as error: self.log.error("loading data: %s: %s", type(error).__name__, error) return None return self.query(method, endpoint, data=data_dict, token=token) def server_name_keys_api(self, server_server_uri): """Retrieve the Matrix server's own homeserver name via the Server-Server (Federation) API. Args: server_server_uri (string): proto://name:port or proto://fqdn:port Returns: string: The Matrix server's homeserver name or FQDN, usually something like matrix.DOMAIN or DOMAIN """ resp = self.query( "get", "key/v2/server", base_url_override=server_server_uri ) if not resp or not resp.get("server_name"): self.log.error("The homeserver name could not be fetched via the " "federation API key/v2/server.") return None return resp['server_name'] class SynapseAdmin(ApiRequest): """Synapse Admin API client Inheritance: ApiRequest (object): parent class containing general properties and methods for requesting REST API's """ def __init__(self, log, user, token, base_url, admin_path, timeout, debug, verify): """Initialize the SynapseAdmin object Args: log (logger object): An already initialized logger object user (string): An admin-enabled Synapse user (currently unused). This can either be the fully qualified Matrix user ID, or just the localpart of the user ID. FIXME is that true? token (string): The admin user's token base_url (string): URI e.g https://fqdn:port path (string): The path to the API endpoint; it's put after base_url and the basis for all API endpoint paths timeout (int): Requests module timeout used in ApiRequest.query method debug (bool): enable/disable debugging in requests module verify(bool): SSL verification is turned on by default and can be turned off using this argument. """ super().__init__( log, user, token, base_url, admin_path, timeout, debug, verify ) self.user = user def user_list(self, _from, _limit, _guests, _deactivated, _name, _user_id, _admin=None): """List and search users Args: _from (int): offsets user list by this number, used for pagination _limit (int): maximum number of users returned, used for pagination _guests (bool): enable/disable fetching of guest users _deactivated (bool): enable/disable fetching of deactivated users _name (string): user name localpart to search for, see Synapse Admin API docs for details _user_id (string): fully qualified Matrix user ID to search for _admin (bool or None): whether to filter for admins. a None does not filter. Returns: string: JSON string containing the found users """ params = { "from": _from, "limit": _limit, "guests": (str(_guests).lower() if isinstance(_guests, bool) else None), "deactivated": "true" if _deactivated else None, "name": _name, "user_id": _user_id } if _admin is not None: params["admins"] = str(_admin).lower() return self.query("get", "v2/users", params=params) def user_list_paginate(self, _limit, _guests, _deactivated, _name, _user_id, _from="0", admin=None): # documentation is mostly duplicated from user_list... """Yields API responses for all of the pagination. Args: _limit (int): Maximum number of users returned, used for pagination. _guests (bool): Enable/disable fetching of guest users. _deactivated (bool): Enable/disable fetching of deactivated users. _name (string): User name localpart to search for, see Synapse Admin API docs for details. _user_id (string): Fully qualified Matrix user ID to search for. _from (string): Offsets user list by this number, used for pagination. Yields: dict: The Admin API response for listing accounts. https://element-hq.github.io/synapse/latest/admin_api/user_admin_api.html#list-accounts """ while _from is not None: response = self.user_list(_from, _limit, _guests, _deactivated, _name, _user_id, admin) yield response _from = response.get("next_token", None) def user_membership(self, user_id, return_aliases, matrix_api): """Get a list of rooms the given user is member of Args: user_id (string): Fully qualified Matrix user ID room_aliases (bool): Return human readable room aliases instead of room ID's if applicable. matrix_api (object): An initialized Matrix object needs to be passes as we need some Matrix API functionality here. Returns: string: JSON string containing the Admin API's response or None if an exception occured. See Synapse Admin API docs for details. """ rooms = self.query("get", "v1/users/{user_id}/joined_rooms", user_id=user_id) # Translate room ID's into aliases if requested. if return_aliases and rooms is not None and "joined_rooms" in rooms: for i, room_id in enumerate(rooms["joined_rooms"]): aliases = matrix_api.room_get_aliases(room_id) if aliases["aliases"] != []: rooms["joined_rooms"][i] = " ".join(aliases["aliases"]) return rooms def user_deactivate(self, user_id, gdpr_erase): """Delete a given user Args: user_id (string): fully qualified Matrix user ID gdpr_erase (bool): enable/disable gdpr-erasing the user, see Synapse Admin API docs for details. Returns: string: JSON string containing the Admin API's response or None if an exception occured. See Synapse Admin API docs for details. """ return self.query("post", "v1/deactivate/{user_id}", data={ "erase": gdpr_erase }, user_id=user_id) def user_password(self, user_id, password, no_logout): """Set the user password, and log the user out if requested Args: user_id (string): fully qualified Matrix user ID password (string): new password that should be set no_logout (bool): the API defaults to logging out the user after password reset via the Admin API, this option can be used to disable this behaviour. Returns: string: JSON string containing the Admin API's response or None if an exception occured. See Synapse Admin API docs for details. """ data = {"new_password": password} if no_logout: data.update({"logout_devices": False}) return self.query("post", "v1/reset_password/{user_id}", data=data, user_id=user_id) def user_details(self, user_id): """Get information about a given user Note that the Admin API docs describe this function as "Query User Account". Args: user_id (string): fully qualified Matrix user ID Returns: string: JSON string containing the Admin API's response or None if an exception occured. See Synapse Admin API docs for details. """ return self.query("get", "v2/users/{user_id}", user_id=user_id) def user_login(self, user_id, expire_days, expire, _expire_ts): """Get an access token that can be used to authenticate as that user. If one of the args expire_days, expire or _expire_ts is set, the valid_until_ms field will be sent to the API endpoint. If this is not the case the default of the API would be used. At the time of writing, this would be that tokens never expire. Note: If this method is called by the CLI frontend code (synadm.cli.user.user_login_cmd), a default expiry date of 1 day (24h) is passed. Args: user_id (string): fully qualified Matrix user ID expire_days (int): token should expire after this number of days expire (datetime): token should expire after this date/time - a datetime object (e.g. as generated by Click.DateTime()) _expire_ts (int): token should expire after this date/time - a unix timestamp in ms. Returns: string: JSON string containing the Admin API's response or None if an exception occured. See Synapse Admin API docs for details. """ expire_ts = None if expire_days: self.log.debug("Received expire_days: %s", expire_days) expire_ts = self._timestamp_from_days_ahead(expire_days) elif expire: self.log.debug("Received expire: %s", expire) expire_ts = self._timestamp_from_datetime(expire) elif _expire_ts: self.log.debug("Received expire_ts: %s", _expire_ts) expire_ts = _expire_ts # Click checks for int already data = {} if expire_ts is not None: data.update({ "valid_until_ms": expire_ts, }) self.log.info("Token expiry date set to timestamp: %d,", expire_ts) self.log.info("which is the date/time: %s", self._datetime_from_timestamp(expire_ts)) else: self.log.info("Token will never expire.") return self.query("post", "v1/users/{user_id}/login", data=data, user_id=user_id) def user_modify(self, user_id, password, display_name, threepid, avatar_url, admin, deactivation, user_type, lock): """ Create or update information about a given user The threepid argument must be passed as a tuple in a tuple (which is what we usually get from a Click multi-arg option) """ data = {} if password: data.update({"password": password}) if display_name: data.update({"displayname": display_name}) if threepid: if threepid == (('', ''),): # empty strings clear all threepids data.update({"threepids": []}) else: data.update({"threepids": [ {"medium": m, "address": a} for m, a in threepid ]}) if avatar_url: data.update({"avatar_url": avatar_url}) if admin is not None: data.update({"admin": admin}) if lock is not None: data.update({"locked": lock}) if deactivation == "deactivate": data.update({"deactivated": True}) if deactivation == "activate": data.update({"deactivated": False}) if user_type: data.update({"user_type": None if user_type == 'null' else user_type}) return self.query("put", "v2/users/{user_id}", data=data, user_id=user_id) def user_whois(self, user_id): """ Return information about the active sessions for a specific user """ return self.query("get", "v1/whois/{user_id}", user_id=user_id) def user_devices(self, user_id): """ Return information about all devices for a specific user. Args: user_id (string): Fully qualified Matrix user ID. Returns: string: JSON string containing the Admin API's response or None if an exception occured. See Synapse Admin API docs for details. """ return self.query("get", "v2/users/{user_id}/devices", user_id=user_id) def user_devices_get_todelete(self, devices_data, min_days, min_surviving, device_id, readable_seen): """ Gather a list of devices that possibly could be deleted. This method is used by the 'user prune-devices' command. Args: devices_data (list): Containing dicts of all the user's devices, as returned by the user_devices method (the user/devices API endpoint). min_days (int): At least this number of days need to have passed from the last time a device was seen for it to be deleted. A reasonable default should be sent by the CLI level method. min_surviving: At least this amount of devices will be kept alive. A reasonable default should be sent by the CLI level method. device_id: Only search devices with this ID. datetime: When True, 'last seen timestamp' is replaced with a human readable format. Returns: list: Containing dicts of devices that possibly could be deleted. If non apply, an empty list is returned. """ def _log_kept_min_days(seen, min_days_ts): self.log.debug("Keeping device, since it's been used recently:") self.log.debug("Last seen: {} / {}".format( seen, self._datetime_from_timestamp( seen, as_str=True)) ) self.log.debug("Delete threshold: {} / {}".format( min_days_ts, self._datetime_from_timestamp( min_days_ts, as_str=True)) ) devices_todelete = [] devices_count = devices_data.get("total", 0) if devices_count <= min_surviving: # Nothing to do but return empty list anyway. Makes sure # checks of callers stay valid (eg. len()). return devices_todelete devices = devices_data.get("devices", []) devices.sort(key=lambda k: k["last_seen_ts"] or 0) for device in devices: if devices_count-len(devices_todelete) <= min_surviving: self.log.debug("Keeping device, since min_surviving threshold " "is reached.") break if device_id: if device.get("device_id", None) == device_id: # Found device in question. Make last_seen_ts human # readable (if requested) and add to deletion list. if readable_seen: device["last_seen_ts"] = self._datetime_from_timestamp( device.get("last_seen_ts", None), as_str=True) devices_todelete.append(device) break else: # Continue looking for the device in question. continue if min_days: seen = device.get("last_seen_ts", None) # Get ts or None # A device with "null" as last seen was either seen a very long # time ago _or_ was created through the matrix API (e.g. via # `synadm matrix login`). if seen: min_days_ts = self._timestamp_from_days_ago(min_days) if seen > min_days_ts: # Device was seen recently enough, keep it! _log_kept_min_days(seen, min_days_ts) continue # Make seen human readable if requested. if readable_seen: device["last_seen_ts"] = self._datetime_from_timestamp( seen, as_str=True) # Finally add to devices deletion list. devices_todelete.append(device) return devices_todelete def user_devices_delete(self, user_id, devices): """ Delete the specified devices for a specific user. Returns an empty JSON dict. devices is a list of device IDs """ return self.query("post", "v2/users/{user_id}/delete_devices", data={"devices": devices}, user_id=user_id) def user_auth_provider_search(self, provider, external_id): """ Finds a user based on their ID (external id) in auth provider represented by auth provider id (provider). """ return self.query("get", "v1/auth_providers/{provider}/users/{external_id}", provider=provider, external_id=external_id) def user_3pid_search(self, medium, address): """ Finds a user based on their Third Party ID by specifying what kind of 3PID it is as medium. """ return self.query("get", "v1/threepid/{medium}/users/{address}", address=address, medium=medium) def room_join(self, room_id_or_alias, user_id): """ Allow an administrator to join an user account with a given user_id to a room with a given room_id_or_alias """ data = {"user_id": user_id} return self.query("post", "v1/join/{room_id_or_alias}", data=data, room_id_or_alias=room_id_or_alias) def room_list(self, _from, limit, name, order_by, reverse): """ List and search rooms """ return self.query("get", "v1/rooms", params={ "from": _from, "limit": limit, "search_term": name, "order_by": order_by, "dir": "b" if reverse else None }) def room_list_paginate(self, limit, name, order_by, reverse, _from=0): """ Yields API responses for room listing. Args: limit (int): Maximum number of rooms returned per pagination. name (string or None): Search for a room by name. Passed as `search_term` in the room list API. Use Python None to avoid searching. order_by (string): Synapse Room list API specific argument. reverse (bool): Whether the results should be _from (int): Initial offset in pagination. Yields: dict: The Admin API response for listing accounts. https://element-hq.github.io/synapse/latest/admin_api/rooms.html#list-room-api """ while _from is not None: response = self.query("get", "v1/rooms", params={ "from": _from, "limit": limit, "search_term": name, "order_by": order_by, "dir": "b" if reverse else None }) yield response _from = response.get("next_batch", None) self.log.debug(f"room_list_paginate: next from value = {_from}") def room_details(self, room_id): """ Get details about a room """ return self.query("get", "v1/rooms/{room_id}", room_id=room_id) def room_members(self, room_id): """ Get a list of room members """ return self.query("get", "v1/rooms/{room_id}/members", room_id=room_id) def room_state(self, room_id): """ Get a list of all state events in a room. Args: room_id (string) Returns: string: JSON string containing the Admin API's response or None if an exception occured. See Synapse Admin API docs for details. """ return self.query("get", "v1/rooms/{room_id}/state", room_id=room_id) def room_power_levels(self, from_, limit, name, order_by, reverse, room_id=None, all_details=True, output_format="json"): """ Get a list of configured power_levels in all rooms. or a single room. Args: room_id (string): If left out, all rooms are fetched. Returns: string: JSON string containing the Admin API's response or None if an exception occured. See Synapse Admin API docs for details. """ if room_id: # We use the "name search" possibility of the room list API to get # a single room via it's ID. rooms = self.room_list(from_, limit, room_id, order_by, reverse) else: rooms = self.room_list(from_, limit, name, order_by, reverse) rooms_w_power_count = 0 for i, room in enumerate(rooms["rooms"]): rooms["rooms"][i]["power_levels"] = {} state = self.room_state(room["room_id"]) for s in state["state"]: if s["type"] == "m.room.power_levels": if output_format == "human": levels_list = [ f"{u} {l}" for u, l in s["content"]["users"].items() # noqa: E501 ] rooms["rooms"][i][ "power_levels" ] = "\n".join(levels_list) else: rooms["rooms"][i][ "power_levels" ] = s["content"]["users"] rooms_w_power_count += 1 if not all_details: for del_item in ["creator", "encryption", "federatable", "guest_access", "history_visibility", "join_rules", "joined_local_members", "joined_members", "public", "state_events", "version"]: del (rooms["rooms"][i][del_item]) rooms["rooms_w_power_levels_curr_batch"] = rooms_w_power_count return rooms def room_delete(self, room_id, new_room_user_id, room_name, message, block, no_purge, force_purge): """ Delete a room and purge it if requested """ data = { "block": block, # data with proper defaults from cli "purge": not bool(no_purge) # should go here } # everything else is optional and shouldn't even exist in post body if new_room_user_id: data.update({"new_room_user_id": new_room_user_id}) if room_name: data.update({"room_name": room_name}) if message: data.update({"message": message}) if force_purge: data.update({"force_purge": force_purge}) return self.query("delete", "v1/rooms/{room_id}", data=data, room_id=room_id) def room_delete_v2(self, room_id, new_room_user_id, room_name, message, block, purge, force_purge): """ Delete a room asynchronously and purge it if requested """ data = { "block": block, # data with proper defaults from cli "purge": purge } # everything else is optional and shouldn't even exist in post body if new_room_user_id: data.update({"new_room_user_id": new_room_user_id}) if room_name: data.update({"room_name": room_name}) if message: data.update({"message": message}) if force_purge: data.update({"force_purge": force_purge}) return self.query("delete", "v2/rooms/{room_id}", data=data, room_id=room_id) def room_delete_v2_status_by_room_id(self, room_id): return self.query("get", "v2/rooms/{room_id}/delete_status", room_id=room_id) def room_delete_v2_status_by_delete_id(self, delete_id): return self.query("get", "v2/rooms/delete_status/{delete_id}", delete_id=delete_id) def block_room(self, room_id, block): """ Block or unblock a room. Args: room_id (string): Required. block (boolean): Whether to block or unblock a room. Returns: string: JSON string containing the Admin API's response or None if an exception occurred. See Synapse Admin API docs for details. """ # TODO prevent usage on versions before 1.48 data = { "block": block } return self.query("put", "v1/rooms/{room_id}/block", data=data, room_id=room_id) def room_block_status(self, room_id): """ Returns if the room is blocked or not, and who blocked it. Args: room_id (string): Fully qualified Matrix room ID. Returns: string: JSON string containing the Admin API's response or None if an exception occured. See Synapse Admin API docs for details. """ # TODO prevent usage on versions before 1.48 return self.query("get", "v1/rooms/{room_id}/block", room_id=room_id) def room_make_admin(self, room_id, user_id): """ Grant a user room admin permission. If the user is not in the room, and it is not publicly joinable, then invite the user. """ data = {} if user_id: data.update({"user_id": user_id}) return self.query("post", "v1/rooms/{room_id}/make_room_admin", data=data, room_id=room_id) def room_media_list(self, room_id): """ Get a list of known media in an (unencrypted) room. """ return self.query("get", "v1/room/{room_id}/media", room_id=room_id) def media_quarantine(self, server_name, media_id): """ Quarantine a single piece of local or remote media """ return self.query( "post", "v1/media/quarantine/{server_name}/{media_id}", data={}, server_name=server_name, media_id=media_id ) def media_unquarantine(self, server_name, media_id): """ Removes a single piece of local or remote media from quarantine. """ return self.query( "post", "v1/media/unquarantine/{server_name}/{media_id}", data={}, server_name=server_name, media_id=media_id ) def room_media_quarantine(self, room_id): """ Quarantine all local and remote media in a room """ return self.query( "post", "v1/room/{room_id}/media/quarantine", data={}, room_id=room_id ) def user_media_quarantine(self, user_id): """ Quarantine all local and remote media of a user """ return self.query( "post", "v1/user/{user_id}/media/quarantine", data={}, user_id=user_id ) def user_media(self, user_id, _from, limit, order_by, reverse, readable): """ Get a user's uploaded media """ result = self.query("get", "v1/users/{user_id}/media", params={ "from": _from, "limit": limit, "order_by": order_by, "dir": "b" if reverse else None }, user_id=user_id) if (readable and result is not None and "media" in result): for i, media in enumerate(result["media"]): created = media["created_ts"] last_access = media["last_access_ts"] if created is not None: result["media"][i][ "created_ts" ] = self._datetime_from_timestamp(created, as_str=True) if last_access is not None: result["media"][i][ "last_access_ts" ] = self._datetime_from_timestamp(last_access, as_str=True) return result def media_delete(self, server_name, media_id): """ Delete a specific (local) media_id """ return self.query( "delete", "v1/media/{server_name}/{media_id}", data={}, server_name=server_name, media_id=media_id ) def media_delete_by_date_or_size(self, before_days, before, _before_ts, _size_gt, delete_profiles): """ Delete local media by date and/or size FIXME and/or? """ if before_days: self.log.debug("Received --before-days: %s", before_days) before_ts = self._timestamp_from_days_ago(before_days) elif before: self.log.debug("Received --before: %s", before) before_ts = self._timestamp_from_datetime(before) elif _before_ts is not None: # Could be 0 if it's an older server ;-) self.log.debug("Received --before-ts: %s", _before_ts) before_ts = _before_ts # Click checks for int already else: self.log.debug("Something wrong in click FIXME") self.log.info("Deleting local media older than timestamp: %d,", before_ts) self.log.info("which is the date: %s", self._datetime_from_timestamp(before_ts)) params = { } if before_ts is not None: params.update({ "before_ts": before_ts, }) if _size_gt: size_gt = _size_gt * 1024 self.log.info("Deleting local media greater than %d bytes,", size_gt) params.update({ "size_gt": size_gt }) if delete_profiles: params.update({ "keep_profiles": "false" }) return self.query( "post", "v1/media/delete", data={}, params=params ) def media_protect(self, media_id): """ Protect a single piece of local or remote media from being quarantined """ return self.query( "post", "v1/media/protect/{media_id}", data={}, media_id=media_id ) def purge_media_cache(self, before_days, before, _before_ts): """ Purge old cached remote media """ if before_days: self.log.debug("Received --before-days: %s", before_days) before_ts = self._timestamp_from_days_ago(before_days) if before: self.log.debug("Received --before: %s", before) before_ts = self._timestamp_from_datetime(before) if _before_ts: self.log.debug("Received --before-ts: %s", _before_ts) before_ts = _before_ts # Click checks for int already self.log.info("Purging cached remote media older than timestamp: %d,", before_ts) self.log.info("which is the date: %s", self._datetime_from_timestamp(before_ts)) return self.query( "post", "v1/purge_media_cache", data={}, params={ "before_ts": str(before_ts) } ) def version(self): """ Get the server version """ return self.query("get", "v1/server_version") def group_delete(self, group_id): """ Delete a local group (community) """ return self.query("post", "v1/delete_group/{group_id}", group_id=group_id) def purge_history(self, room_id, before_event_id, before_days, before, _before_ts, delete_local): """ Purge room history """ before_ts = None if before_days: self.log.debug("Received --before-days: %s", before_days) before_ts = self._timestamp_from_days_ago(before_days) elif before: self.log.debug("Received --before: %s", before) before_ts = self._timestamp_from_datetime(before) elif _before_ts: self.log.debug("Received --before-ts: %s", _before_ts) before_ts = _before_ts # Click checks for int already elif before_event_id: self.log.debug("Received --event-id: %s", before_event_id) data = {} if before_ts is not None: data.update({ "purge_up_to_ts": before_ts, }) self.log.info("Purging history older than timestamp: %d,", before_ts) self.log.info("which is the date/time: %s", self._datetime_from_timestamp(before_ts)) elif before_event_id: data.update({ "purge_up_to_event_id": before_event_id, }) if delete_local: data.update({ "delete_local_events": True, }) return self.query("post", "v1/purge_history/{room_id}", data=data, room_id=room_id) def purge_history_status(self, purge_id): """ Get status of a recent history purge The status will be one of active, complete, or failed. """ return self.query("get", "v1/purge_history_status/{purge_id}", purge_id=purge_id) def regtok_list(self, valid, readable_expiry): """ List registration tokens Args: valid (bool): List only valid (if True) or invalid (if False) tokens. Default is to list all tokens regardless of validity. readable_expiry (bool): If True, replace the expiry_time field with a human readable datetime. If False, expiry_time will be a unix timestamp. Returns: string: JSON string containing the Admin API's response or None if an exception occured. See Synapse Admin API docs for details. """ result = self.query("get", "v1/registration_tokens", params={ "valid": (str(valid).lower() if isinstance(valid, bool) else None) }) # Change expiry_time to a human readable format if requested if ( readable_expiry and result is not None and "registration_tokens" in result ): for i, regtok in enumerate(result["registration_tokens"]): expiry_time = regtok["expiry_time"] if expiry_time is not None: result["registration_tokens"][i][ "expiry_time" ] = self._datetime_from_timestamp(expiry_time, as_str=True) return result def regtok_details(self, token, readable_expiry): """ Get details about the given registration token Args: token (string): The registration token in question readable_expiry (bool): If True, replace the expiry_time field with a human readable datetime. If False, expiry_time will be a unix timestamp. Returns: string: JSON string containing the Admin API's response or None if an exception occured. See Synapse Admin API docs for details. """ result = self.query("get", "v1/registration_tokens/{t}", t=token) # Change expiry_time to a human readable format if requested if ( readable_expiry and result is not None and result.get("expiry_time") is not None ): result["expiry_time"] = self._datetime_from_timestamp( result["expiry_time"], as_str=True ) return result def regtok_new(self, token, length, uses_allowed, expiry_ts, expire_at): """ Create a new registration token Args: token (string): Registration token to create. Default is randomly generated by the server. length (int): The length of the token to generate if the token is not provided. uses_allowed (int): The number of times the token can be used to complete a registration before it becomes invalid. expiry_ts (int): The latest time the registration token is valid. Given as the number of milliseconds since 1970-01-01 00:00:00 UTC. expire_at (click.DateTime): The latest time the registration token is valid. Returns: string: JSON string containing the Admin API's response or None if an exception occured. See Synapse Admin API docs for details. """ data = { "length": length, "uses_allowed": uses_allowed, } if expiry_ts: self.log.debug(f"Received --expiry-ts: {expiry_ts}") data["expiry_time"] = expiry_ts elif expire_at: self.log.debug(f"Received --expire-at: {expire_at}") data["expiry_time"] = self._timestamp_from_datetime(expire_at) else: data["expiry_time"] = None # The token cannot be null, it must be a string if isinstance(token, str): data["token"] = token return self.query("post", "v1/registration_tokens/new", data=data) def regtok_update(self, token, uses_allowed, expiry_ts, expire_at): """ Update a registration token Args: token (string): Registration token to update. uses_allowed (int): The number of times the token can be used to complete a registration before it becomes invalid. expiry_ts (int): The latest time the registration token is valid. Given as the number of milliseconds since 1970-01-01 00:00:00 UTC. -1 indicates no expiry. expire_at (click.DateTime): The latest time the registration token is valid. Returns: string: JSON string containing the Admin API's response or None if an exception occured. See Synapse Admin API docs for details. """ # If uses_allowed or expiry time were not provided by the user, # do not add the corresponding parameter to the request so that # the server will not modify its value. data = {} if uses_allowed == -1: # A null value indicates unlimited uses data["uses_allowed"] = None elif uses_allowed is not None: data["uses_allowed"] = uses_allowed if expiry_ts: self.log.debug(f"Received --expiry-ts: {expiry_ts}") if expiry_ts == -1: # A null value indicates no expiry data["expiry_time"] = None else: data["expiry_time"] = expiry_ts elif expire_at: self.log.debug(f"Received --expire-at: {expire_at}") data["expiry_time"] = self._timestamp_from_datetime(expire_at) return self.query("put", "v1/registration_tokens/{t}", data=data, t=token) def regtok_delete(self, token): """ Delete a registration token Args: token (string): The registration token to delete Returns: string: JSON string containing the Admin API's response or None if an exception occured. See Synapse Admin API docs for details. """ # t because query also accepts token when we want it for the # request # https://github.com/JOJ0/synadm/issues/110#issuecomment-1590032158 return self.query("delete", "v1/registration_tokens/{t}", t=token) def user_shadow_ban(self, user_id, unban): """ Shadow-ban or unban a user. Args: user_id (string): The user to be banned/unbanned. unban (boolean): Unban the specified user. """ if unban: method = "delete" else: method = "post" return self.query(method, "v1/users/{user_id}/shadow_ban", user_id=user_id) def notice_send(self, receivers, content_plain, content_html, paginate, regex): """ Send server notices. Args: receivers (string): Target(s) of the notice. Either localpart or regular expression matching localparts. content_plain (string): Unformatted text of the notice. content_html (string): HTML-formatted text of the notice. paginate (int): Limits to how many users the notice is sent at once. Users are fetched with the user_list method and using its pagination capabilities. to_regex (bool): Selects whether receivers should be interpreted as a regular expression or a single recipient. Returns: list: A list of dictionaries, each containing the response of what a single notice Admin API call returned. Usually that is an event ID or an error. See Synapse Admin API docs for details. """ data = { "user_id": "", "content": { "msgtype": "m.text", "body": content_plain, "format": "org.matrix.custom.html", "formatted_body": content_html } } # A regular expression was supplied to match receivers. if regex: outputs = [] response = self.user_list(0, paginate, True, False, "", "", None) if "users" not in response: return while True: for user in response["users"]: if re.match(receivers, user["name"]): data["user_id"] = user["name"] outputs.append( self.query( "post", "v1/send_server_notice", data=data ) ) if "next_token" not in response: return outputs response = self.user_list(response["next_token"], 100, True, False, "", "", None) # Only a single user ID was supplied as receiver else: data["user_id"] = receivers return [self.query("post", "v1/send_server_notice", data=data)] def raw_request(self, endpoint, method, data): data_dict = {} if method != "get": self.log.debug("The data we are trying to parse and submit:") self.log.debug(data) try: # user provided json might be crap data_dict = json.loads(data) except Exception as error: self.log.error("loading data: %s: %s", type(error).__name__, error) return None return self.query(method, endpoint, data=data_dict) ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1712130070.0578904 synadm-0.46/synadm/cli/0000755000076500000240000000000000000000000014314 5ustar00jacksonstaff././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1712129307.0 synadm-0.46/synadm/cli/__init__.py0000644000076500000240000002417600000000000016437 0ustar00jacksonstaff# -*- coding: utf-8 -*- # synadm # Copyright (C) 2020-2023 Johannes Tiefenbacher # # synadm is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # synadm 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . """ CLI root-level commands; Subcommands are imported at the bottom of file """ import sys import click output_format_help = """The 'human' mode gives a tabular or list view depending on the fetched data, but often needs a lot of horizontal space to display correctly. 'json' returns formatted json. 'minified' is minified json, suitable for scripting purposes. 'pprint' shows a formatted output with the help of Python's built-in pprint module. 'yaml' is a compromise between human- and machine-readable output, it doesn't need as much terminal width as 'human' does and is the default on fresh installations.""" @click.group( invoke_without_command=False, context_settings=dict(help_option_names=["-h", "--help"])) @click.version_option() @click.option( "--verbose", "-v", count=True, default=False, help="Enable INFO (-v) or DEBUG (-vv) logging on console.") @click.option( "--no-confirm", "--batch", "--yes", "--non-interactive", "--scripting", default=False, is_flag=True, help="""Enable non-interactive mode. Use with caution! This will: \b - Disable all interactive prompts. - Disable automatic translation of unix timestamps to human readable formats. """) @click.option( "--output", "-o", default="", type=click.Choice(["yaml", "json", "minified", "human", "pprint", "y", "j", "m", "h", "p", ""]), show_choices=True, help=f"Override default output format. {output_format_help}") @click.option( "--config-file", "-c", type=click.Path(), default="~/.config/synadm.yaml", help="Configuration file path.", show_default=True) @click.pass_context def root(ctx, verbose, no_confirm, output, config_file): """ the Matrix-Synapse admin CLI """ from synadm.cli._helper import APIHelper ctx.obj = APIHelper(config_file, verbose, no_confirm, output) helper_loaded = ctx.obj.load() if ctx.invoked_subcommand != "config" and not helper_loaded: if no_confirm: click.echo("Please setup synadm: " + sys.argv[0] + " config.") raise SystemExit(2) else: ctx.invoke(config_cmd) @root.command(name="config") @click.option( "--user", "-u", "user_", type=str, help="Admin user allowed to access the Synapse Admin API's.") @click.option( "--token", "-t", type=str, help="The Admin user's access token.") @click.option( "--base-url", "-b", type=str, help="""The base URL Synapse is running on. Typically this is https://localhost:8008 or https://localhost:8448. If Synapse is configured to expose its Admin API's to the outside world it might as well be something like this: https://example.org:8448""") @click.option( "--admin-path", "-p", type=str, help="""The path Synapse provides its Admin API's, usually the default fits most installations.""") @click.option( "--matrix-path", "-m", type=str, help="""The path Synapse provides the regular Matrix API's, usually the default fits most installations.""") @click.option( "--timeout", "-w", type=int, help="""The time in seconds synadm should wait for responses from admin API's or Matrix API's. The default is 7 seconds. """) @click.option( "--output", "-o", type=click.Choice([ "yaml", "json", "minified", "human", "pprint"]), help=f"""How synadm displays data by default. {output_format_help} The default output format can always be overridden by using the global --output/-o switch (eg 'synadm -o pprint user list').""") @click.option( "--server-discovery", "-d", type=click.Choice(["well-known", "dns"]), help="""The method used for discovery of "the own homeserver name". Since none of the currently existing Admin API endpoints provide this information, the federation API among other things is asked for help. If set to "well-known" the URI of the federation API is tried to be fetched via the well-known resource of the configured "Synapse base URL". If set to "dns" the SRV record of the domain name found in the "Synapse base URL" is used to get that information. Once the federation URI is known, the homeserver name can be retrieved. In case "Synapse base URL" contains "localhost", it's assumed that the required federation API is listening on localhost:port already (the "keys" Matrix API endpoint). If that is failing as well, as a last resort solution, the homeserver name can just be saved to the configuration directly via the "homeserver" setting. Note that the fetching of the homeserver name is only executed when a synadm subcommand requires it (eg. like some of the media and user subcommands do), and the "homeserver" directive in the config is set to "auto-retrieval". """) @click.option( "--homeserver", "-n", type=str, help="""Synapse homeserver hostname. Usually matrix.DOMAIN or DOMAIN. The default value 'auto-retrieval' will try to discover the name using the method set by --server-discovery.""" ) @click.option( "--ssl-verify", "-i", is_flag=True, show_default=True, help="""Whether or not SSL certificates should be verified. Set to False to allow self-signed certifcates.""" ) @click.pass_obj def config_cmd(helper, user_, token, base_url, admin_path, matrix_path, output, timeout, server_discovery, homeserver, ssl_verify): """ Modify synadm's configuration. Configuration details are generally always asked interactively. Command line options override the suggested defaults in the prompts. """ def get_redacted_token_prompt(cli_token): redacted = "NOT SET" # Show as empty: []. if cli_token: redacted = "REDACTED" # Token passed via cli, show [REDACTED] else: conf_token = helper.config.get("token", None) if conf_token: redacted = "REDACTED" # Token found in config, show [REDACTED] return f"Synapse admin user token [{redacted}]" if helper.no_confirm: if not all([user, token, base_url, admin_path, matrix_path, output, timeout, server_discovery, homeserver, ssl_verify]): click.echo( "Missing config options for non-interactive configuration!" ) raise SystemExit(3) else: click.echo("Saving to config file.") if helper.write_config({ "user": user_, "token": token, "base_url": base_url, "admin_path": admin_path, "matrix_path": matrix_path, "format": output, "timeout": timeout, "server_discovery": server_discovery, "homeserver": homeserver, "ssl_verify": ssl_verify }): raise SystemExit(0) else: raise SystemExit(4) click.echo("Running configurator...") helper.write_config({ "user": click.prompt( "Synapse admin user name", default=user_ if user_ else helper.config.get("user", user_)), "token": click.prompt( get_redacted_token_prompt(token), default=token if token else helper.config.get("token", token), show_default=False, hide_input=True), "base_url": click.prompt( "Synapse base URL", default=base_url if base_url else helper.config.get( "base_url", base_url)), "admin_path": click.prompt( "Synapse Admin API path", default=admin_path if admin_path else helper.config.get( "admin_path", admin_path)), "matrix_path": click.prompt( "Matrix API path", default=matrix_path if matrix_path else helper.config.get( "matrix_path", matrix_path)), "format": click.prompt( "Default output format", default=output if output else helper.config.get("format", output), type=click.Choice([ "yaml", "json", "minified", "human", "pprint"])), "timeout": click.prompt( "Default http timeout", default=timeout if timeout else helper.config.get( "timeout", timeout)), "homeserver": click.prompt( "Homeserver name (\"auto-retrieval\" or the domain part in your " "MXID)", default=homeserver if homeserver else helper.config.get( "homeserver", homeserver)), "ssl_verify": click.prompt( "Verify certificate", type=bool, default=ssl_verify if ssl_verify else helper.config.get( "ssl_verify", ssl_verify)), "server_discovery": click.prompt( "Server discovery mode (used with homeserver name auto-retrieval)", default=server_discovery if server_discovery else helper.config.get( # noqa: E501 "server_discovery", server_discovery), type=click.Choice(["well-known", "dns"])), }) if not helper.load(): click.echo("Configuration incomplete, quitting.") raise SystemExit(5) @root.command() @click.pass_obj def version(helper): """ Get the Synapse server version. """ version_info = helper.api.version() if version_info is None: click.echo("Version could not be fetched.") raise SystemExit(1) helper.output(version_info) # Import additional commands from synadm.cli import room, user, media, group, history, matrix, regtok, notice, raw # noqa: F401, E402, E501 ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1711541543.0 synadm-0.46/synadm/cli/_common.py0000644000076500000240000000364600000000000016326 0ustar00jacksonstaff# -*- coding: utf-8 -*- # synadm # Copyright (C) 2020-2023 Johannes Tiefenbacher # # synadm is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # synadm 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . "Common CLI options, option groups, helpers and utilities." import click from click_option_group import MutuallyExclusiveOptionGroup def common_opts_raw_command(function): return click.argument( "endpoint", type=str )( click.option( "--method", "-m", type=click.Choice(["get", "post", "put", "delete"]), help="The HTTP method used for the request.", default="get", show_default=True )(function) ) data_group_raw_command = MutuallyExclusiveOptionGroup( "Data", help="" ) def data_opts_raw_command(function): return data_group_raw_command.option( "--data", "-d", type=str, default='{}', show_default=True, help="""The JSON string sent in the body of post, put and delete requests - provided as a string. Make sure to escape it from shell interpretation by using single quotes. E.g '{"key1": "value1", "key2": 123}'""" )( data_group_raw_command.option( "--data-file", "-f", type=click.File("rt"), show_default=True, help="""Read JSON data from file. To read from stdin use "-" as the filename argument.""" )(function) ) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1711541543.0 synadm-0.46/synadm/cli/_helper.py0000644000076500000240000002533500000000000016314 0ustar00jacksonstaff# -*- coding: utf-8 -*- # synadm # Copyright (C) 2020-2023 Johannes Tiefenbacher # # synadm is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # synadm 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . """ CLI helpers and utilities""" import os import logging import pprint import json import click import yaml import tabulate from urllib.parse import urlparse import dns.resolver import re from synadm import api def humanize(data): """ Try to display data in a human-readable form: - Lists of dicts are displayed as tables. - Dicts are displayed as pivoted tables. - Lists are displayed as a simple list. """ if isinstance(data, list) and len(data): if isinstance(data[0], dict): headers = {header: header for header in data[0]} return tabulate.tabulate(data, tablefmt="simple", headers=headers) if isinstance(data, list): return "\n".join(data) if isinstance(data, dict): return tabulate.tabulate(data.items(), tablefmt="plain") return str(data) class APIHelper: """ API client enriched with CLI-level functions, used as a proxy to the client object. """ FORMATTERS = { "pprint": pprint.pformat, "json": lambda data: json.dumps(data, indent=4), "minified": lambda data: json.dumps(data, separators=(",", ":")), "yaml": yaml.dump, "human": humanize } CONFIG = { "user": "", "token": "", "base_url": "http://localhost:8008", "admin_path": "/_synapse/admin", "matrix_path": "/_matrix", "timeout": 30, "server_discovery": "well-known", "homeserver": "auto-retrieval", "ssl_verify": True } def __init__(self, config_path, verbose, no_confirm, output_format_cli): self.config = APIHelper.CONFIG.copy() self.config_path = os.path.expanduser(config_path) self.no_confirm = no_confirm self.api = None self.init_logger(verbose) self.requests_debug = False if verbose >= 3: self.requests_debug = True self.output_format_cli = output_format_cli # override from cli def init_logger(self, verbose): """ Log both to console (defaults to WARNING) and file (DEBUG). """ log_path = os.path.expanduser("~/.local/share/synadm/debug.log") os.makedirs(os.path.dirname(log_path), exist_ok=True) log = logging.getLogger("synadm") log.setLevel(logging.DEBUG) file_handler = logging.FileHandler(log_path, encoding="utf-8") file_handler.setLevel(logging.DEBUG) console_handler = logging.StreamHandler() console_handler.setLevel( logging.DEBUG if verbose > 1 else logging.INFO if verbose == 1 else logging.WARNING ) file_formatter = logging.Formatter( "%(asctime)s %(name)-8s %(levelname)-7s %(message)s", datefmt="%Y-%m-%d %H:%M:%S" ) console_formatter = logging.Formatter("%(levelname)-5s %(message)s") console_handler.setFormatter(console_formatter) file_handler.setFormatter(file_formatter) log.addHandler(console_handler) log.addHandler(file_handler) self.log = log def _set_formatter(self, _output_format): for name, formatter in APIHelper.FORMATTERS.items(): if name.startswith(_output_format): self.output_format = name self.formatter = formatter break self.log.debug("Formatter in use: %s - %s", self.output_format, self.formatter) return True def load(self): """ Load the configuration and initialize the client. """ try: with open(self.config_path) as handle: self.config.update(yaml.load(handle, Loader=yaml.SafeLoader)) except Exception as error: self.log.error("%s while reading configuration file", error) for key, value in self.config.items(): if key == "ssl_verify" and not isinstance(value, bool): self.log.error("Config value error: %s, %s must be boolean", key, value) if not value and not isinstance(value, bool): self.log.error("Config entry missing: %s, %s", key, value) return False else: if key == "token": self.log.debug("Config entry read. %s: REDACTED", key) else: self.log.debug("Config entry read. %s: %s", key, value) if self.output_format_cli: # we have a cli output format override self._set_formatter(self.output_format_cli) else: # we use the configured default output format self._set_formatter(self.config["format"]) self.api = api.SynapseAdmin( self.log, self.config["user"], self.config["token"], self.config["base_url"], self.config["admin_path"], self.config["timeout"], self.requests_debug, self.config["ssl_verify"] ) self.matrix_api = api.Matrix( self.log, self.config["user"], self.config["token"], self.config["base_url"], self.config["matrix_path"], self.config["timeout"], self.requests_debug, self.config["ssl_verify"] ) self.misc_request = api.MiscRequest( self.log, self.config["timeout"], self.requests_debug, self.config["ssl_verify"] ) return True def write_config(self, config): """ Write a new version of the configuration to file. """ try: os.makedirs(os.path.dirname(self.config_path), exist_ok=True) with open(self.config_path, "w") as handle: yaml.dump(config, handle, default_flow_style=False, allow_unicode=True) if os.name == "posix": click.echo("Restricting access to config file to user only.") os.chmod(self.config_path, 0o600) else: click.echo(f"Unsupported OS, please adjust permissions of " f"{self.config_path} manually") return True except Exception as error: self.log.error("%s trying to write configuration", error) return False def output(self, data): """ Output data object using the configured formatter. """ click.echo(self.formatter(data)) def retrieve_homeserver_name(self, uri=None): """Try to retrieve the homeserver name. When homeserver is set in the config already, it's just returned and nothing is tried to be fetched automatically. If not, either the location of the Federation API is looked up via a .well-known resource or a DNS SRV lookup. This depends on the server_discovery setting in the config. Finally the Federation API is used to retrieve the homeserver name. Args: uri (string): proto://name:port or proto://fqdn:port Returns: string: hostname, FQDN or DOMAIN; or None on errors. """ uri = uri if uri else self.config["base_url"] echo = self.log.info if self.no_confirm else click.echo if self.config["homeserver"] != "auto-retrieval": return self.config["homeserver"] if self.config["server_discovery"] == "well-known": if "localhost" in self.config["base_url"]: echo( "Trying to fetch homeserver name via localhost..." ) return self.matrix_api.server_name_keys_api( self.config["base_url"] ) else: echo( "Trying to fetch federation URI via well-known resource..." ) federation_uri = self.misc_request.federation_uri_well_known( uri ) if not federation_uri: return None return self.matrix_api.server_name_keys_api(federation_uri) elif self.config["server_discovery"] == "dns": echo( "Trying to fetch federation URI via DNS SRV record..." ) hostname = urlparse(uri).hostname try: record = dns.resolver.query( "_matrix._tcp.{}".format(hostname), "SRV" ) except Exception as error: self.log.error( "resolving Matrix delegation for %s: %s: %s", hostname, type(error).__name__, error ) else: federation_uri = "https://{}:{}".format( record[0].target, record[0].port ) return self.matrix_api.server_name_keys_api(federation_uri) else: self.log.error("Unknown server_discovery mode. " "Launch synadm config!") return None def generate_mxid(self, user_id): """ Checks whether the given user ID is an MXID already or else generates it from the passed string and the homeserver name fetched via the retrieve_homeserver_name method. Args: user_id (string): User ID given by user as command argument. Returns: string: the fully qualified Matrix User ID (MXID) or None if the user_id parameter is None or no regex matched. """ if user_id is None: self.log.debug("Missing input in generate_mxid().") return None elif re.match(r"^@[-./=\w]+:[-\[\].:\w]+$", user_id): self.log.debug("A proper MXID was passed.") return user_id elif re.match(r"^@?[-./=\w]+:?$", user_id): self.log.debug("A proper localpart was passed, generating MXID " "for local homeserver.") localpart = re.sub("[@:]", "", user_id) mxid = "@{}:{}".format(localpart, self.retrieve_homeserver_name()) return mxid else: self.log.error("Neither an MXID nor a proper localpart was " "passed.") return None ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1711541543.0 synadm-0.46/synadm/cli/group.py0000644000076500000240000000266200000000000016030 0ustar00jacksonstaff# -*- coding: utf-8 -*- # synadm # Copyright (C) 2020-2023 Johannes Tiefenbacher # # synadm is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # synadm 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . """ Group-related CLI commands """ import click from synadm import cli @cli.root.group() def group(): """ Manage groups (communities). """ @group.command(name="delete") @click.argument("group_id", type=str) @click.pass_obj def delete(helper, group_id): """ Delete a local group (community). """ sure = ( helper.no_confirm or click.prompt("Are you sure you want to delete this group? (y/N)", type=bool, default=False, show_default=False) ) if sure: group_del = helper.api.group_delete(group_id) if group_del is None: click.echo("Group not deleted.") raise SystemExit(1) helper.output(group_del) else: click.echo("Abort.") ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1711541543.0 synadm-0.46/synadm/cli/history.py0000644000076500000240000001146500000000000016376 0ustar00jacksonstaff# -*- coding: utf-8 -*- # synadm # Copyright (C) 2020-2023 Johannes Tiefenbacher # # synadm is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # synadm 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . """ Purge-history-related CLI commands """ import click from click_option_group import optgroup, RequiredMutuallyExclusiveOptionGroup from synadm import cli @cli.root.group() def history(): """ Purge historic events from Synapse database. """ @history.command(name="purge") @click.argument("room_id", type=str) @optgroup.group( "Purge before", cls=RequiredMutuallyExclusiveOptionGroup, help="") @optgroup.option( "--before-event-id", "-i", type=str, help="""Purge all history before this event ID. Event ID's contain $, which is interpreted by the shell. Make sure it is surrounded by single quotes ('id').""") @optgroup.option( "--before-days", "-d", type=int, help="""Purge all history before this number of days ago.""") @optgroup.option( "--before", type=click.DateTime(), help="""Purge all history before this point in time. Eg. '2021-01-01', see above for available date/time formats.""") @optgroup.option( "--before-ts", type=int, help="""Purge all history before this point in time giving a unix timestamp in ms. """) @click.option( "--delete-local", is_flag=True, help="""This option overrides the default behavior and forces removal of events sent by local users.""") @click.pass_obj def history_purge_cmd(helper, room_id, before_event_id, before_days, before, before_ts, delete_local): """ Purge room events before a point in time or before an event ID. The purge history API allows server admins to purge historic events from their database, reclaiming disk space. Depending on the amount of history being purged a call to the API may take several minutes or longer. During this period users will not be able to paginate further back in the room from the point being purged from. Note that Synapse requires at least one message in each room, so it will never delete the last message in a room. By default, events sent by local users are not deleted, as they may represent the only copies of this content in existence. (Events sent by remote users are deleted.) Room state data (such as joins, leaves, topic) is always preserved. The API starts the purge running, and returns immediately with a JSON body with a purge id. Use 'synadm history purge-status ' to poll for updates on the running purge. """ sure = ( helper.no_confirm or click.prompt("Are you sure you want to purge room history? (y/N)", type=bool, default=False, show_default=False) ) if sure: history_purged = helper.api.purge_history( room_id, before_event_id, before_days, before, before_ts, delete_local ) if helper.no_confirm: helper.output(history_purged) if history_purged is None: raise SystemExit(1) else: if history_purged is None: click.echo("History could not be purged.") raise SystemExit(1) if "purge_id" in history_purged: click.echo( "Use 'synadm history purge-status {}' to get " "status of purge job.".format(history_purged["purge_id"]) ) helper.output(history_purged) @history.command(name="purge-status") @click.argument("purge_id", type=str) @click.pass_obj def history_purge_status_cmd(helper, purge_id): """ View status of a recent history purge.. Provide purge ID as argument. The status will be one of active, complete, or failed. """ purge_history_status = helper.api.purge_history_status(purge_id) if helper.no_confirm: if purge_history_status is None: raise SystemExit(1) helper.output(purge_history_status) else: if purge_history_status is None: click.echo("History purge status could not be fetched.") raise SystemExit(1) if "status" in purge_history_status: click.echo("Status of history purge is {}.".format( purge_history_status["status"])) else: helper.output(purge_history_status) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1711541543.0 synadm-0.46/synadm/cli/matrix.py0000644000076500000240000001132700000000000016176 0ustar00jacksonstaff# -*- coding: utf-8 -*- # synadm # Copyright (C) 2020-2023 Johannes Tiefenbacher # # synadm is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # synadm 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . """ CLI commands executing regular Matrix API calls """ import click from synadm import cli from synadm.cli._common import common_opts_raw_command, data_opts_raw_command from click_option_group import optgroup, MutuallyExclusiveOptionGroup @cli.root.group() def matrix(): """ Execute Matrix API calls. """ @matrix.command(name="login") @click.argument( "user_id", type=str) @click.option( "--password", "-p", type=str, help="""The Matrix user's password. If missing, an interactive password prompt is shown.""") @click.pass_obj def login_cmd(helper, user_id, password): """ Login to Matrix via username/password and receive an access token. The response also contains a newly generated device ID and further information about user and homeserver. Each successful login will show up in the user's devices list marked with a display name of 'synadm matrix login command'. """ if not password: if helper.no_confirm: helper.log.error( "Password prompt not available in non-interactive mode. " "Use -p.") raise SystemExit(1) else: password = click.prompt("Password", hide_input=True) mxid = helper.generate_mxid(user_id) login = helper.matrix_api.user_login(mxid, password) if helper.no_confirm: if login is None: raise SystemExit(1) helper.output(login) else: if login is None: click.echo("Matrix login failed.") raise SystemExit(1) else: helper.output(login) @matrix.command(name="raw") @common_opts_raw_command @data_opts_raw_command @optgroup.group( "Matrix token", cls=MutuallyExclusiveOptionGroup, help="") @optgroup.option( "--token", "-t", type=str, envvar='MTOKEN', show_default=True, help="""Token used for Matrix authentication instead of the configured admin user's token. If ``--token`` (and ``--prompt``) option is missing, the token is read from environment variable ``$MTOKEN`` instead. To make sure a user's token does not show up in system logs, don't provide it on the shell directly but set ``$MTOKEN`` with shell command ``read MTOKEN``.""") @optgroup.option( "--prompt", "-p", is_flag=True, show_default=True, help="""Prompt for the token used for Matrix authentication. This option always overrides $MTOKEN.""") @click.pass_obj def raw_request_cmd(helper, endpoint, method, data, data_file, token, prompt): """ Execute a custom request to the Matrix API. The endpoint argument is the part of the URL _after_ the configured base URL (actually "Synapse base URL") and "Matrix API path" (see ``synadm config``). A get request could look like this: ``synadm matrix raw client/versions`` URL encoding must be handled at this point. Consider enabling debug outputs via synadm's global flag ``-vv`` Use either ``--token`` or ``--prompt`` to provide a user's token and execute Matrix commands on their behalf. Respect the privacy of others! Act responsible! \b The precedence rules for token reading are: 1. Interactive input using ``--prompt``; 2. Set on CLI via ``--token`` 3. Read from environment variable ``$MTOKEN``; 4. Preconfigured admin token set via ``synadm config``. Caution: Passing secrets as CLI arguments or via environment variables is not considered secure. Know what you are doing! """ if prompt: token = click.prompt("Matrix token", type=str) if data_file: data = data_file.read() raw_request = helper.matrix_api.raw_request(endpoint, method, data, token=token) if helper.no_confirm: if raw_request is None: raise SystemExit(1) helper.output(raw_request) else: if raw_request is None: click.echo("The Matrix API's response was empty or JSON data " "could not be loaded.") raise SystemExit(1) else: helper.output(raw_request) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1712129841.0 synadm-0.46/synadm/cli/media.py0000644000076500000240000002422300000000000015750 0ustar00jacksonstaff# -*- coding: utf-8 -*- # synadm # Copyright (C) 2020-2023 Johannes Tiefenbacher # # synadm is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # synadm 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . """ Media-related CLI commands """ import click from click_option_group import optgroup from click_option_group import RequiredAnyOptionGroup, OptionGroup from click_option_group import RequiredMutuallyExclusiveOptionGroup from synadm import cli @cli.root.group() def media(): """ Manage local and remote media. """ @media.command(name="list") @optgroup.group( "List media by", cls=RequiredAnyOptionGroup, help="") @optgroup.option( "--room-id", "-r", type=str, help="""List all media in room with this room ID ('!abcdefg').""") @optgroup.option( "--user-id", "-u", type=str, help="""List all media uploaded by user with this matrix ID (@user:server).""") @click.option( "--from", "-f", "from_", type=int, default=0, show_default=True, help="""Offset media listing by given number. This option is also used for pagination but only supported together with --user-id.""") @click.option( "--limit", "-l", type=int, default=100, show_default=True, help="""Limit media listing to given number. This option is only supported together with --user-id.""") @click.option( "--sort", "-s", type=click.Choice([ "media_id", "upload_name", "created_ts", "last_access_ts", "media_length", "media_type", "quarantined_by", "safe_from_quarantine"]), help="""The method by which to sort the returned list of media. If the ordered field has duplicates, the second order is always by ascending media_id, which guarantees a stable ordering. This option is only supported together with --user-id.""") @click.option( "--reverse", "-R", is_flag=True, default=False, help="""Direction of media order. If set it will reverse the sort order of --order-by method. This option is only supported together with --user-id. """) @click.option( "--datetime/--timestamp", "--dt/--ts", default=True, help="""Display created and last accessed timestamps in a human readable format, or as a unix timestamp in milliseconds. This option only applies to user media and is ignored with room media. [default: datetime].""") @click.pass_obj @click.pass_context def media_list_cmd(ctx, helper, room_id, user_id, from_, limit, sort, reverse, datetime): """ List local media by room or user. """ if room_id: media_list = helper.api.room_media_list(room_id) if media_list is None: click.echo("Media list could not be fetched.") raise SystemExit(1) helper.output(media_list) elif user_id: from synadm.cli import user mxid = helper.generate_mxid(user_id) ctx.invoke( user.get_function("user_media_cmd"), user_id=mxid, from_=from_, limit=limit, sort=sort, reverse=reverse, datetime=datetime ) @media.command(name="quarantine") @optgroup.group( "Quarantine media by", cls=RequiredAnyOptionGroup, help="") @optgroup.option( "--media-id", "-i", type=str, help="""The media with this specific media ID will be quarantined. """) @optgroup.option( "--room-id", "-r", type=str, help="""All media in room with this room ID (!abcdefg) will be quarantined.""") @optgroup.option( "--user-id", "-u", type=str, help="""All media uploaded by user with this matrix ID (@user:server) will be quarantined.""") @click.option( "--server-name", "-s", type=str, help="""The server name of the media, mandatory when --media-id is used and _remote_ media should be processed. For locally stored media this option can be omitted. """) @click.pass_obj def media_quarantine_cmd(helper, server_name, media_id, user_id, room_id): """ Quarantine media in rooms, by users or by media ID. """ if media_id and not server_name: # We assume it is local media and fetch our own server name. fetched_name = helper.retrieve_homeserver_name( helper.config["base_url"]) media_quarantined = helper.api.media_quarantine(fetched_name, media_id) elif server_name and not media_id: click.echo("Media ID missing.") media_quarantined = None elif media_id and server_name: media_quarantined = helper.api.media_quarantine(server_name, media_id) elif room_id: media_quarantined = helper.api.room_media_quarantine(room_id) elif user_id: mxid = helper.generate_mxid(user_id) media_quarantined = helper.api.user_media_quarantine(mxid) if media_quarantined is None: click.echo("Media could not be quarantined.") raise SystemExit(1) helper.output(media_quarantined) @media.command(name="unquarantine") @optgroup.group( "unquarantine media by", cls=RequiredAnyOptionGroup, help="") @optgroup.option( "--media-id", "-i", type=str, help="""The media with this specific media ID will be removed from quarantine. """) @click.option( "--server-name", "-s", type=str, help="""The server name of the media, mandatory when --media-id is used and _remote_ media should be processed. For locally stored media this option can be omitted. """) @click.pass_obj def media_unquarantine_cmd(helper, server_name, media_id): """ Remove media from quarantine. """ if media_id and not server_name: # We assume it is local media and fetch our own server name. fetched_name = helper.retrieve_homeserver_name( helper.config["base_url"]) unquarantinend = helper.api.media_unquarantine(fetched_name, media_id) elif server_name and not media_id: click.echo("Media ID missing.") unquarantinend = None elif media_id and server_name: unquarantinend = helper.api.media_unquarantine(server_name, media_id) if unquarantinend is None: click.echo("Media could not be removed from quarantine.") raise SystemExit(1) helper.output(unquarantinend) @media.command(name="protect") @click.argument("media_id", type=str) @click.pass_obj def media_protect_cmd(helper, media_id): """ Protect specific media from being quarantined. """ media_protected = helper.api.media_protect(media_id) if media_protected is None: click.echo("Media could not be protected.") raise SystemExit(1) helper.output(media_protected) @media.command(name="purge") @optgroup.group( "Purge by", cls=RequiredMutuallyExclusiveOptionGroup, help="") @optgroup.option( "--before-days", "-d", type=int, help="""Purge all media that was last accessed before this number of days ago. """) @optgroup.option( "--before", "-b", type=click.DateTime(), help="""Purge all media that was last accessed before this date/time. Eg. '2021-01-01', see above for available date/time formats.""") @optgroup.option( "--before-ts", "-t", type=int, help="""Purge all media that was last accessed before this unix timestamp in ms. """) @click.pass_obj def media_purge_cmd(helper, before_days, before, before_ts): """ Purge old cached remote media To delete local media, use `synadm media delete` """ media_purged = helper.api.purge_media_cache(before_days, before, before_ts) if media_purged is None: click.echo("Media cache could not be purged.") raise SystemExit(1) helper.output(media_purged) @media.command(name="delete") @optgroup.group( "delete criteria", cls=RequiredMutuallyExclusiveOptionGroup, help="") @optgroup.option( "--media-id", "-i", type=str, help="""The media with this specific media ID will be deleted.""") @optgroup.option( "--before-days", "-d", type=int, help="""Delete all media that was last accessed before this number of days ago. """) @optgroup.option( "--before", "-b", type=click.DateTime(), help="""Delete all media that was last accessed before this date/time. Eg. '2021-01-01', see above for available date/time formats.""") @optgroup.option( "--before-ts", "-t", type=int, help="""Delete all media that was last accessed before this unix timestamp in ms.""") @optgroup.group( "Additional switches", cls=OptionGroup, help="") @optgroup.option( "--size", "--kib", type=int, help="""Delete all media that is larger than this size in KiB (1 KiB = 1024 bytes).""") @optgroup.option( "--delete-profiles", "--all", is_flag=True, help="""Also delete files that are still used in image data (e.g user profile, room avatar). If set, these files will be deleted too. Not valid when a specific media is being deleted (--media-id)""") @click.pass_obj def media_delete_cmd(helper, media_id, before_days, before, before_ts, size, delete_profiles): """ Delete local media by ID, size or age To delete cached remote media, use `synadm media purge` """ if media_id and delete_profiles: click.echo("Combination of --media-id and --delete-profiles not " "valid.") media_deleted = None elif media_id and size: click.echo("Combination of --media-id and --size not valid.") media_deleted = None elif media_id: server_name = helper.retrieve_homeserver_name( helper.config["base_url"]) media_deleted = helper.api.media_delete(server_name, media_id) else: media_deleted = helper.api.media_delete_by_date_or_size( before_days, before, before_ts, size, delete_profiles ) if media_deleted is None: click.echo("Media could not be deleted.") raise SystemExit(1) helper.output(media_deleted) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1711541543.0 synadm-0.46/synadm/cli/notice.py0000644000076500000240000001340300000000000016150 0ustar00jacksonstaff# -*- coding: utf-8 -*- # synadm # Copyright (C) 2022 Philip (a-0) # # synadm is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # synadm 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . """Server notice-related CLI commands """ import re import click from synadm import cli @cli.root.group() def notice(): """ Send messages to users. """ @notice.command(name="send") @click.option( "--from-file", "-f", default=False, show_default=True, is_flag=True, help="""Interpret arguments as file paths instead of notice content and read content from those files.""") @click.option( "--batch-size", "--paginate", "-p", type=int, default=100, show_default=True, metavar="SIZE", help="""The send command retrieves "pages" of users from the homeserver, filters them and sends out the notices, before retrieving the next page. SIZE sets how many users are in each of these "pages". It is a performance setting and may be useful for servers with a large amount of users.""") @click.option( "--regex", "-r", default=False, show_default=True, is_flag=True, help="Interpret TO as regular expression.") @click.option( "--preview-length", "-l", type=int, default=10, show_default=True, metavar="LENGTH", help="""Length of the displayed list of matched recipients shown in the confirmation prompt. Does not impact sending behavior. Is ignored when global --non-interactive flag is given.""") @click.option( "--silent", "-s", default=False, show_default=True, is_flag=True, help="""Usually synadm commands print to console what the API returned. With the "Server Notices Admin API", an event ID or an error messages would be printed for each message sent. Large amounts of recipients could possibly lead to performance impacts, thus this option can be used to disable printing of what the API responded. """) @click.argument("to", type=str, default=None) @click.argument("plain", type=str, default=None) @click.argument("formatted", type=str, default=None, required=False) @click.pass_obj def notice_send_cmd(helper, from_file, batch_size, regex, preview_length, silent, to, plain, formatted): """Send server notices to users on the local homeserver. \b TO Localpart or full matrix ID of the notice receiver. If --regex is set this will be interpreted as a regular expression. \b PLAIN Plain text content of the notice. \b FORMATTED Formatted content of the notice. If omitted, PLAIN will be used. """ def confirm_prompt(): prompt = "" if helper.no_confirm: return True if not silent: prompt += "\nNote: When sending to a large amount of recipients, " prompt += "consider using the --silent option.\n\n" prompt += "Recipients:\n" if not regex: prompt += " - " + to + "\n" else: # Build and print a list of receivers matching the regex ctr, next_token = 0, 0 # Outer loop: If fetching >1 pages of users is required while ctr < preview_length: batch = helper.api.user_list( next_token, batch_size, True, False, "", "", None) if "users" not in batch: break batch_mxids = [user['name'] for user in batch["users"]] # Match every matrix ID of this batch for mxid in batch_mxids: if re.match(to, mxid): if ctr < preview_length: prompt += " - " + mxid + "\n" ctr += 1 else: prompt += " - ...\n" break if "next_token" not in batch: break next_token = batch["next_token"] if ctr == 0: prompt += "(no recipient matched)\n" prompt += f"\nPlaintext message:\n---\n{plain_content}\n---" prompt += f"\nFormatted message:\n---\n{formatted_content}\n---" prompt += "\nSend now?" return click.confirm(prompt) if from_file: try: with open(plain, "r") as plain_file: plain_content = plain_file.read() if formatted: with open(formatted, "r") as formatted_file: formatted_content = formatted_file.read() else: formatted_content = plain_content except Exception as error: helper.log.error(error) raise SystemExit(1) else: plain_content = plain formatted_content = formatted if formatted else plain_content if regex: if "users" not in helper.api.user_list(0, 100, True, False, "", "", None): return if not confirm_prompt(): return else: to = helper.generate_mxid(to) if to is None: click.echo("The recipient you specified is invalid.") return if not confirm_prompt(): return outputs = helper.api.notice_send(to, plain_content, formatted_content, batch_size, regex) if not silent: helper.output(outputs) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1711541543.0 synadm-0.46/synadm/cli/raw.py0000644000076500000240000000367300000000000015470 0ustar00jacksonstaff# -*- coding: utf-8 -*- # synadm # Copyright (C) 2020-2023 Johannes Tiefenbacher # # synadm is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # synadm 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . """This module holds the `raw` command only.""" import click from synadm import cli from synadm.cli._common import common_opts_raw_command, data_opts_raw_command @cli.root.command(name="raw") @common_opts_raw_command @data_opts_raw_command @click.pass_obj def raw_request_cmd(helper, endpoint, method, data, data_file): """ Issue a custom request to the Synapse Admin API. The endpoint argument is the part of the URL _after_ the configured "Synapse base URL" and "Synapse Admin API path" (see ``synadm config``). A get request to the "Query User Account API" would look like this: ``synadm raw v2/users/%40testuser%3Aexample.org``. URL encoding must be handled at this point. Consider enabling debug outputs via synadm's global flag ``-vv`` """ if data_file: data = data_file.read() raw_request = helper.api.raw_request(endpoint, method, data) if helper.no_confirm: if raw_request is None: raise SystemExit(1) helper.output(raw_request) else: if raw_request is None: click.echo("The Admin API's response was empty or JSON data " "could not be loaded.") raise SystemExit(1) else: helper.output(raw_request) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1711541543.0 synadm-0.46/synadm/cli/regtok.py0000644000076500000240000001247600000000000016173 0ustar00jacksonstaff# -*- coding: utf-8 -*- # synadm # Copyright (C) 2021 Callum Brown # # synadm is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # synadm 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . """ Registration token-related CLI commands """ import click from synadm import cli @cli.root.group() def regtok(): """ Manage registration tokens. """ @regtok.command(name="list") @click.option( "--valid/--invalid", "-v/-V", default=None, show_default=True, help="List only valid/invalid tokens.") @click.option( "--datetime/--timestamp", "--dt/--ts", default=True, help="""Display expiry time in a human readable format, or as a unix timestamp in milliseconds. [default: datetime].""") @click.pass_obj def regtok_list_cmd(helper, valid, datetime): """ List registration tokens """ regtoks = helper.api.regtok_list(valid, datetime) if regtoks is None: click.echo("Registration tokens could not be fetched.") raise SystemExit(1) if "registration_tokens" not in regtoks: # Display error helper.output(regtoks) elif helper.output_format == "human": if regtoks["registration_tokens"] == []: click.echo("No registration tokens.") else: helper.output(regtoks["registration_tokens"]) else: helper.output(regtoks) @regtok.command(name="details") @click.argument("token", type=str) @click.option( "--datetime/--timestamp", "--dt/--ts", default=True, help="""Display expiry time in a human readable format, or as a unix timestamp in milliseconds. [default: datetime].""") @click.pass_obj def regtok_details_cmd(helper, token, datetime): """ View details of the given token. """ regtok = helper.api.regtok_details(token, datetime) if regtok is None: click.echo("Registration token could not be fetched.") raise SystemExit(1) helper.output(regtok) @regtok.command(name="new") @click.option( "--token", "-n", type=str, default=None, help="""Set the registration token. The default is a random value generated by the server.""") @click.option( "--length", "-l", type=int, default=16, show_default=True, help="""The length of the randomly generated token if the token is not specified.""") @click.option( "--uses-allowed", "-u", type=int, default=None, help="""The number of times the token can be used to complete a registration before it becomes invalid. [default: unlimited uses]""") @click.option( "--expiry-ts", "-t", type=int, default=None, help="""The latest time the registration token is valid. Given as the number of milliseconds since 1970-01-01 00:00:00 UTC. [default: no expiry]""") @click.option( "--expire-at", "-e", type=click.DateTime(), default=None, help="""The latest time the registration token is valid. See above for available date/time formats. [default: no expiry]""") @click.pass_obj def regtok_new(helper, token, length, uses_allowed, expiry_ts, expire_at): """ Create a new registration token. """ regtok = helper.api.regtok_new( token, length, uses_allowed, expiry_ts, expire_at ) if regtok is None: click.echo("Registration token could not be created.") raise SystemExit(1) helper.output(regtok) @regtok.command(name="update") @click.argument("token", type=str) @click.option( "--uses-allowed", "-u", type=int, default=None, help="""The number of times the token can be used to complete a registration before it becomes invalid. Use -1 for an unlimited number of uses. [default: unchanged]""") @click.option( "--expiry-ts", "-t", type=int, default=None, help="""The latest time the registration token is valid. Given as the number of milliseconds since 1970-01-01 00:00:00 UTC. Use -1 for no expiration. [default: unchanged]""") @click.option( "--expire-at", "-e", type=click.DateTime(), default=None, help="""The latest time the registration token is valid. See above for available date/time formats. [default: unchanged]""") @click.pass_obj def regtok_update(helper, token, uses_allowed, expiry_ts, expire_at): """ Update a registration token """ regtok = helper.api.regtok_update(token, uses_allowed, expiry_ts, expire_at) if regtok is None: click.echo("Registration token could not be created.") raise SystemExit(1) helper.output(regtok) @regtok.command(name="delete") @click.argument("token", type=str) @click.pass_obj def regtok_delete(helper, token): """ Delete a registration token. """ response = helper.api.regtok_delete(token) if response is None: click.echo("Registration token could not be deleted.") raise SystemExit(1) if response == {}: click.echo("Registration token successfully deleted.") else: helper.output(response) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1712129391.0 synadm-0.46/synadm/cli/room.py0000644000076500000240000004374200000000000015654 0ustar00jacksonstaff# -*- coding: utf-8 -*- # synadm # Copyright (C) 2020-2023 Johannes Tiefenbacher # # synadm is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # synadm 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . """ Room-related CLI commands """ import click from click_option_group import RequiredMutuallyExclusiveOptionGroup, optgroup from synadm import cli @cli.root.group() def room(): """ Manipulate rooms and room membership. The syntax of room IDs in synadm is as the Matrix spec defines: https://spec.matrix.org/latest/#room-structure. Make sure to escape the ! character from your shell. In bash and zsh this can be achieved by using single quotes ('), eg. '!id123abc:matrix.DOMAIN' """ @room.command() @click.argument("room_id_or_alias", type=str) @click.argument("user_id", type=str) @click.pass_obj def join(helper, room_id_or_alias, user_id): """ Join a room. """ mxid = helper.generate_mxid(user_id) out = helper.api.room_join(room_id_or_alias, mxid) helper.output(out) @room.command() @click.argument("room_id_or_alias", type=str) @click.option( "--reverse", "-r", is_flag=True, default=False, show_default=True, help="""Fetch all room aliases corresponding to a given room ID, instead of the other way round. """) @click.pass_obj def resolve(helper, room_id_or_alias, reverse): """ Lookup room ID from alias or vice versa. """ if reverse: out = helper.matrix_api.room_get_aliases(room_id_or_alias) else: out = helper.matrix_api.room_get_id(room_id_or_alias) if out is None: click.echo("Room resolve failed.") raise SystemExit(1) helper.output(out) @room.command(name="list") @click.pass_obj @click.option( "--from", "-f", "from_", type=int, default=0, show_default=True, help="""Offset room listing by given number. This option is used for pagination.""") @click.option( "--limit", "-l", type=int, default=100, show_default=True, help="Maximum amount of rooms to return.") @click.option( "--name", "-n", type=str, help="""Filter rooms by parts of their room name, canonical alias and room id.""") @click.option( "--sort", "-s", type=click.Choice( ["name", "canonical_alias", "joined_members", "joined_local_members", "version", "creator", "encryption", "federatable", "public", "join_rules", "guest_access", "history_visibility", "state_events"]), help="The method in which to sort the returned list of rooms.") @click.option( "--reverse", "-r", is_flag=True, default=False, help="""Direction of room order. If set it will reverse the sort order of --order-by method.""") def list_room_cmd(helper, from_, limit, name, sort, reverse): """ List and search for rooms. """ rooms = helper.api.room_list(from_, limit, name, sort, reverse) if rooms is None: click.echo("Rooms could not be fetched.") raise SystemExit(1) if helper.output_format == "human": if int(rooms["total_rooms"]) != 0: helper.output(rooms["rooms"]) if "next_batch" in rooms: click.echo("There are more rooms than shown, use '--from {}'" .format(rooms["next_batch"])) else: helper.output(rooms) @room.command() @click.argument("room_id", type=str) @click.pass_obj def details(helper, room_id): """ Get room details. """ room_details = helper.api.room_details(room_id) if room_details is None: click.echo("Room details could not be fetched.") raise SystemExit(1) helper.output(room_details) @room.command() @click.argument("room_id", type=str) @click.pass_obj def state(helper, room_id): """ Get a list of all state events in a room. """ room_state = helper.api.room_state(room_id) if room_state is None: click.echo("Room state could not be fetched.") raise SystemExit(1) helper.output(room_state) @room.command() @click.option( "--room-id", "-i", type=str, help="""View power levels of this room only.""") @click.option( "--all-details", "-a", is_flag=True, default=False, help="""Show detailed information about each room. The default is to only show room_id, name, canonical_alias and power_levels.""") @click.option( "--from", "-f", "from_", type=int, default=0, show_default=True, help="""Offset room listing by given number. This option is used for pagination.""") @click.option( "--limit", "-l", type=int, default=10, show_default=True, help="Maximum amount of rooms to return.") @click.option( "--name", "-n", type=str, help="""Filter rooms by parts of their room name, canonical alias and room id.""") @click.option( "--sort", "-s", type=click.Choice( ["name", "canonical_alias", "joined_members", "joined_local_members", "version", "creator", "encryption", "federatable", "public", "join_rules", "guest_access", "history_visibility", "state_events"]), help="The method in which to sort the returned list of rooms.") @click.option( "--reverse", "-r", is_flag=True, default=False, help="""Direction of room order. If set it will reverse the sort order of --order-by method.""") @click.pass_obj def power_levels(helper, room_id, all_details, from_, limit, name, sort, reverse): """ List user's power levels set in rooms. A combination of commands `room list` and `room state`. It enriches the room list response with a list of users and their corresponding power levels set. It only displays a subset of the available information (room name, id, aliases and power levels). Increase the number of rooms fetched using --limit/-l (default: 10) or use the pagination option --from/-f to go beyond the default. Use --name/-n to search. This command can require quite some time to complete depending on those options. """ rooms_power = helper.api.room_power_levels( from_, limit, name, sort, reverse, room_id, all_details, helper.output_format) if rooms_power is None: click.echo("Rooms and power levels could not be fetched.") raise SystemExit(1) if helper.output_format == "human": if int(rooms_power["total_rooms"]) != 0: helper.output(rooms_power["rooms"]) click.echo("Rooms with power levels found in current batch: {}" .format(rooms_power["rooms_w_power_levels_curr_batch"])) click.echo("Total rooms: {}" .format(rooms_power["total_rooms"])) if "next_batch" in rooms_power: click.echo("Use '--from/-f {}' to view next batch." .format(rooms_power["next_batch"])) else: helper.output(rooms_power) @room.command() @click.argument("room_id", type=str) @click.pass_obj def members(helper, room_id): """ List current room members. """ room_members = helper.api.room_members(room_id) if room_members is None: click.echo("Room members could not be fetched.") raise SystemExit(1) if helper.output_format == "human": click.echo("Total members in room: {}" .format(room_members["total"])) if int(room_members["total"]) != 0: helper.output(room_members["members"]) else: helper.output(room_members) @room.command() @click.argument("room_id", type=str) @click.option( "--new-room-user-id", "-u", type=str, help="""If set, a new room will be created with this user ID as the creator and admin, and all users in the old room will be moved into that room. If not set, no new room will be created and the users will just be removed from the old room. The user ID must be on the local server, but does not necessarily have to belong to a registered user.""") @click.option( "--room-name", "-n", type=str, help="""A string representing the name of the room that new users will be invited to. Defaults to "Content Violation Notification" """) @click.option( "--message", "-m", type=str, help="""A string containing the first message that will be sent as new_room_user_id in the new room. Ideally this will clearly convey why the original room was shut down. Defaults to "Sharing illegal content on this server is not permitted and rooms in violation will be blocked." """) @click.option( "--block", "-b", is_flag=True, default=False, show_default=True, help="""If set, this room will be added to a blocking list, preventing future attempts to join the room""") @click.option( "--no-purge", is_flag=True, default=False, show_default=True, help="""Prevent removing of all traces of the room from your database.""") @click.option( "--force-purge", is_flag=True, default=False, show_default=True, help="""Force a purge to go ahead even if there are local users still in the room. Do not use this unless a regular purge operation fails, as it could leave those users' clients in a confused state.""") @click.option( "--v1", is_flag=True, default=False, show_default=True, help="""Use version 1 of the room delete API instead of version 2""") @click.pass_obj @click.pass_context def delete(ctx, helper, room_id, new_room_user_id, room_name, message, block, no_purge, force_purge, v1): """ Delete and possibly purge a room. """ if no_purge and force_purge: click.echo("--force-purge will be ignored as --no-purge is set") room_details = helper.api.room_details(room_id) if "errcode" in room_details.keys(): if room_details["errcode"] == "M_NOT_FOUND": click.echo("Room not found.") raise SystemExit(1) else: click.echo("Unrecognized error") helper.output(room_details) raise SystemExit(1) helper.output(room_details) ctx.invoke(members, room_id=room_id) sure = ( helper.no_confirm or click.prompt("Are you sure you want to delete this room? (y/N)", type=bool, default=False, show_default=False) ) if sure: mxid = helper.generate_mxid(new_room_user_id) if v1: room_del = helper.api.room_delete( room_id, mxid, room_name, message, block, no_purge, force_purge) else: room_del = helper.api.room_delete_v2( room_id, mxid, room_name, message, block, not bool(no_purge), force_purge) if room_del is None: click.echo("Room not deleted.") raise SystemExit(1) helper.output(room_del) else: click.echo("Abort.") @room.command(name="purge-empty") @click.option( "--no-purge", is_flag=True, default=False, show_default=True, help="""Prevent removing of all traces of the room from your database.""") @click.option( "--force-purge", is_flag=True, default=False, show_default=True, help="""Force a purge to go ahead even if there are local users still in the room. Do not use this unless a regular purge operation fails, as it could leave those users' clients in a confused state.""") @click.option( "--v1", is_flag=True, default=False, show_default=True, help="""Use version 1 of the room delete API instead of version 2""") @click.option( "--dry-run", is_flag=True, default=False, help="""Only show the rooms IDs that will be deleted""") @click.option( "--batch-size", "--paginate", "-p", type=int, default=100, show_default=True, help="""How many rooms should be requested from the API one at a time. This option has no effect on how many empty rooms will be deleted. Increasing this is not necessary in most cases but useful if you have a lot of rooms on your homeserver.""") @click.pass_obj def purge_empty(helper, no_purge, force_purge, v1, dry_run, batch_size): """ Delete empty rooms (where 0 local members are currently in a room). """ if no_purge and force_purge: click.echo("--force-purge will be ignored as --no-purge is set") empty_rooms_ids = [] for room_list_response in helper.api.room_list_paginate( batch_size, None, "joined_local_members", True): found_empty_rooms = False if "rooms" not in room_list_response.keys(): helper.log.warn("\"rooms\" key is missing from room list" "response.") for room in room_list_response["rooms"]: room_id = room["room_id"] joined_local_members = room["joined_local_members"] if joined_local_members == 0: helper.log.debug(f"Added {room_id} to delete " f"(joined local members is " f"{joined_local_members})") empty_rooms_ids.append(room_id) found_empty_rooms = True else: helper.log.debug(f"Skipping {room_id} (joined local " f"members is {joined_local_members}, " f"not 0)") # very early cut off, hopefully always works and is never # wrong found_empty_rooms = False break # list is sorted by joined_local_members from smallest to biggest, # if there's no more where joined_local_members == 0 then just stop # early if not found_empty_rooms: helper.log.debug("No more empty rooms, stopping room list " "fetching early.") break helper.output(empty_rooms_ids) if dry_run: click.echo("Empty room purge dry run. Rooms will not be deleted " "is listed.", err=True) return sure = ( helper.no_confirm or click.prompt("Are you sure you want to delete the listed empty " "rooms? (y/N)", type=bool, default=False, show_default=False) ) if not sure: click.echo("Abort.", err=True) raise SystemExit(1) for room_id in empty_rooms_ids: if v1: result = helper.api.room_delete( room_id, None, None, None, False, not no_purge, force_purge) helper.output(result) else: result = helper.api.room_delete_v2( room_id, None, None, None, False, not no_purge, force_purge) helper.output(result) @room.command(name="delete-status") @optgroup.group( "Query type", cls=RequiredMutuallyExclusiveOptionGroup, help="Query room deletion status via either Room ID or Deletion ID" ) @optgroup.option( "--room-id", "-r", type=str, help="""The Room ID to query the deletion status for""") @optgroup.option( "--delete-id", "-d", type=str, help="""The Delete ID to query the deletion status for""") @click.pass_obj def delete_status(helper, room_id, delete_id): """ Get room deletion status via either the room ID or the delete ID. This requires the usage of the Room Delete v2 API. If you used v1 of the Room Delete API, this is irrelevant. """ output = None if room_id: output = helper.api.room_delete_v2_status_by_room_id( room_id ) if delete_id: output = helper.api.room_delete_v2_status_by_delete_id( delete_id ) helper.output(output) @room.command(name="search") @click.argument("search-term", type=str) @click.option( "--from", "-f", "from_", type=int, default=0, show_default=True, help="""Offset room listing by given number. This option is used for pagination.""") @click.option( "--limit", "-l", type=int, default=100, show_default=True, help="Maximum amount of rooms to return.") @click.option( "--sort", "-s", type=click.Choice( ["name", "canonical_alias", "joined_members", "joined_local_members", "version", "creator", "encryption", "federatable", "public", "join_rules", "guest_access", "history_visibility", "state_events"]), help="The method in which to sort the returned list of rooms.") @click.option( "--reverse", "-r", is_flag=True, default=False, help="""Direction of room order. If set it will reverse the sort order of --order-by method.""") @click.pass_context def search_room_cmd(ctx, search_term, from_, limit, sort, reverse): """ An alias to `synadm room list -n `. """ ctx.invoke(list_room_cmd, from_=from_, limit=limit, name=search_term, sort=sort, reverse=reverse) @room.command() @click.argument("room_id", type=str) @click.option( "--user-id", "-u", type=str, help="""By default the server admin (the caller) is granted power, but another user can optionally be specified.""") @click.pass_obj def make_admin(helper, room_id, user_id): """ Grant a user room admin permission. If the user is not in the room, and it is not publicly joinable, then invite the user. """ mxid = helper.generate_mxid(user_id) out = helper.api.room_make_admin(room_id, mxid) helper.output(out) @room.command() @click.argument("room_id", type=str) @click.option( "--block/--unblock", "-b/-u", type=bool, default=True, show_default=True, help="Specifies whether to block or unblock a room." ) @click.pass_obj def block(helper, room_id, block): """ Block or unblock a room. """ out = helper.api.block_room(room_id, block) helper.output(out) @room.command() @click.argument("room_id", type=str) @click.pass_obj def block_status(helper, room_id): """ Get if a room is blocked, and who blocked it. """ out = helper.api.room_block_status(room_id) helper.output(out) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1711541543.0 synadm-0.46/synadm/cli/user.py0000644000076500000240000007136000000000000015653 0ustar00jacksonstaff# -*- coding: utf-8 -*- # synadm # Copyright (C) 2020-2023 Johannes Tiefenbacher # # synadm is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # synadm 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . """ User-related CLI commands """ import re import click from click_option_group import optgroup, MutuallyExclusiveOptionGroup from click_option_group import RequiredAnyOptionGroup from synadm import cli # helper function to retrieve functions from within this package from another # package (e.g used in ctx.invoke calls) def get_function(function_name): if function_name == 'user_media_cmd': return user_media_cmd @cli.root.group() def user(): """ List, add, modify, deactivate/erase users, reset passwords. """ @user.command(name="list") @click.option( "--from", "-f", "from_", type=int, default=0, show_default=True, help="""Offset user listing by given number. This option is also used for pagination.""") @click.option( "--limit", "-l", type=int, default=100, show_default=True, help="Limit user listing to given number") @click.option( "--guests/--no-guests", "-g/-G", default=None, show_default=True, help="Show guest users.") @click.option( "--deactivated", "-d", is_flag=True, default=False, help="Also show deactivated/erased users", show_default=True) @click.option( "--admins/--non-admins", "-a/-A", default=None, help="""Whether to filter for admins, or non-admins. If not specified, no admin filter is applied.""") @optgroup.group( "Search options", cls=MutuallyExclusiveOptionGroup, help="") @optgroup.option( "--name", "-n", type=str, help="""Search users by name - filters to only return users with user ID localparts or displaynames that contain this value (localpart is the left part before the colon of the matrix ID (@user:server)""") @optgroup.option( "--user-id", "-i", type=str, help="""Search users by ID - filters to only return users with Matrix IDs (@user:server) that contain this value""") @click.pass_obj def list_user_cmd(helper, from_, limit, guests, deactivated, name, user_id, admins): """ List users, search for users. """ mxid = helper.generate_mxid(user_id) users = helper.api.user_list(from_, limit, guests, deactivated, name, mxid, admins) if users is None: click.echo("Users could not be fetched.") raise SystemExit(1) if helper.output_format == "human": click.echo("Total users on homeserver (excluding deactivated): {}" .format(users["total"])) if int(users["total"]) != 0: helper.output(users["users"]) if "next_token" in users: click.echo("There are more users than shown, use '--from {}' " .format(users["next_token"]) + "to go to next page") else: helper.output(users) @user.command() @click.argument("user_id", type=str) @click.option( "--gdpr-erase", "-e", is_flag=True, default=False, help="""Marks the user as GDPR-erased. This means messages sent by the user will still be visible by anyone that was in the room when these messages were sent, but hidden from users joining the room afterwards.""", show_default=True) @click.pass_obj @click.pass_context def deactivate(ctx, helper, user_id, gdpr_erase): """ Deactivate or gdpr-erase a user. Provide matrix user ID (@user:server) as argument. It removes active access tokens, resets the password, and deletes third-party IDs (to prevent the user requesting a password reset). """ click.echo(""" Note that deactivating/gdpr-erasing a user leads to the following: - Removal from all joined rooms - Password reset - Deletion of third-party-IDs (to prevent the user requesting a password) """) mxid = helper.generate_mxid(user_id) ctx.invoke(user_details_cmd, user_id=mxid) ctx.invoke(membership, user_id=mxid) m_erase_or_deact = "gdpr-erase" if gdpr_erase else "deactivate" m_erase_or_deact_p = "gdpr-erased" if gdpr_erase else "deactivated" sure = ( helper.no_confirm or click.prompt("Are you sure you want to {} this user? (y/N)" .format(m_erase_or_deact), type=bool, default=False, show_default=False) ) if sure: deactivated = helper.api.user_deactivate(mxid, gdpr_erase) if deactivated is None: click.echo("User could not be {}.".format(m_erase_or_deact)) raise SystemExit(1) if helper.output_format == "human": if deactivated["id_server_unbind_result"] == "success": click.echo("User successfully {}.".format(m_erase_or_deact_p)) else: click.echo("Synapse returned: {}".format( deactivated["id_server_unbind_result"])) else: helper.output(deactivated) else: click.echo("Abort.") @user.command() @click.argument("regex", type=str) @click.option( "--gdpr-erase", "-e", is_flag=True, default=False, help="""Marks the users as GDPR-erased. This means messages sent by the users will still be visible by anyone that was in the room when these messages were sent, but hidden from other users joining the room afterwards.""", show_default=True ) @click.option( "--dry-run", "-n", is_flag=True, default=False, help="""Do everything except deactivating users.""" ) @click.option( "--batch-size", "--paginate", "-p", type=int, default=500, show_default=True, help="""How many users should be requested from the API one at a time. This option has no effect on how many users will be deactivated. Increasing this is not necessary in most cases but useful if you have a lot of accounts on your homeserver.""" ) @click.pass_obj @click.pass_context def deactivate_regex(ctx, helper, regex, gdpr_erase, dry_run, batch_size): """ Deactivate or GDPR-erase accounts based on regex. Does everything normal deactivation does, just for multiple users matching the given regex. The regex argument takes a string and uses Python's re.match (matches regex starting from first character). A regex is expected to match a full Matrix ID, or partially at least from the first character. --dry-run can be used to see which accounts will be deactivated. This can be useful for reviewing the accounts that will be deactivated. Additionally, the --batch argument (given before the subcommands) will not prompt for if you want to deactivate a user (very useful for many users).""" helper.log.debug(f"Regex: {regex}") # if below fails, turn on debug mode to get the actual given regex. pattern = re.compile(regex) for list_user_response in helper.api.user_list_paginate(batch_size, True, False, "", ""): for user in list_user_response["users"]: if pattern.match(user["name"]): if dry_run: click.echo(f"Would deactivate: {user['name']}") continue else: ctx.invoke(deactivate, user_id=user["name"], gdpr_erase=gdpr_erase) @user.command(name="prune-devices") @click.argument("user_id", type=str) @click.option( "--list-only", "-l", is_flag=True, default=False, help="""Dry-run: does not perform the deletion but shows what would be done. If you want to list all devices/sessions, you can also use the whois command.""", show_default=True) @click.option( "--min-days", "-d", type=int, default=90, help="""How many days need to have passed from the last time a device was seen for it to be deleted.""", show_default=True) @click.option( "--min-surviving", "-s", type=int, default=1, help="""Stop processing devices when only this number of devices is left for this user. Allows to reduce disruption by preserving recently used devices/sessions.""", show_default=True) @click.option( "--device-id", "-i", type=str, default=None, help="""Only search devices with this ID. The other options still apply if they're not 0.""", show_default=True) @click.option( "--datetime/--timestamp", "--dt/--ts", default=True, help="""Display 'last seen date/time' in a human readable format, or as a unix timestamp in milliseconds. [default: datetime].""") @click.pass_obj def prune_devices_cmd(helper, user_id, list_only, min_days, min_surviving, device_id, datetime): """ Delete devices and invalidate access tokens of a user. Deletes devices of a user and invalidates any access token associated with them. Starts from deleting the oldest devices, not seen in a number of days, which may be abandoned. Note that this will affect the encryption and decryption of messages sent by other users to this user or to rooms where the user is present. """ mxid = helper.generate_mxid(user_id) devices_data = helper.api.user_devices(mxid) if "devices" not in devices_data: # Most probably the requested user is not existing, error out and quit. helper.output(devices_data) raise SystemExit(1) devices_todelete = helper.api.user_devices_get_todelete( devices_data, min_days, min_surviving, device_id, datetime ) if len(devices_todelete) < 1: # We didn't find anything to do. if helper.output_format == "human": click.echo(f"User {user_id} had no relevant devices to delete.") raise SystemExit(0) else: if helper.output_format == "human": keep_count = len(devices_data["devices"]) - len(devices_todelete) click.echo("User {} has {} device(s) marked for deletion " "and {} device(s) to be kept alive." .format(user_id, len(devices_todelete), keep_count)) helper.output(devices_todelete) if not list_only: devices_todelete_ids = [ d.get("device_id", None) for d in devices_todelete ] deleted = helper.api.user_devices_delete(user_id, devices_todelete_ids) # We should have received an empty dict if len(deleted) > 0: helper.log.error(f"Failed deleting user {user_id} " f"devices: {deleted}.") raise SystemExit(1) if helper.output_format == "human": click.echo("User {} devices successfully deleted: {}." .format(user_id, ", ".join(devices_todelete_ids))) @user.command(name="password") @click.argument("user_id", type=str) @click.option( "--no-logout", "-n", is_flag=True, default=False, help="Don't log user out of all sessions on all devices.") @click.option( "--password", "-p", prompt=True, hide_input=True, confirmation_prompt=True, help="New password.") @click.pass_obj def password_cmd(helper, user_id, password, no_logout): """ Change a user's password. To prevent the user from being logged out of all sessions use option -n. """ mxid = helper.generate_mxid(user_id) changed = helper.api.user_password(mxid, password, no_logout) if changed is None: click.echo("Password could not be reset.") raise SystemExit(1) if helper.output_format == "human": if changed == {}: click.echo("Password reset successfully.") else: click.echo("Synapse returned: {}".format(changed)) else: helper.output(changed) @user.command() @click.argument("user_id", type=str) @click.option( "--aliases/--ids", is_flag=True, default=True, help="""Display rooms as canonical aliases or room ID's. [default: aliases]""") @click.pass_obj def membership(helper, user_id, aliases): """ List all rooms a user is member of. Provide matrix user ID (@user:server) as argument. """ mxid = helper.generate_mxid(user_id) joined_rooms = helper.api.user_membership(mxid, aliases, helper.matrix_api) if joined_rooms is None: click.echo("Membership could not be fetched.") raise SystemExit(1) if helper.output_format == "human": click.echo("User is member of {} rooms." .format(joined_rooms["total"])) if int(joined_rooms["total"]) != 0: helper.output(joined_rooms["joined_rooms"]) else: helper.output(joined_rooms) @user.command(name="search") @click.argument("search-term", type=str) @click.option( "--from", "-f", "from_", type=int, default=0, show_default=True, help="""Offset user listing by given number. This option is also used for pagination.""") @click.option( "--limit", "-l", type=int, default=100, show_default=True, help="Maximum amount of users to return.") @click.pass_context def user_search_cmd(ctx, search_term, from_, limit): """ A shortcut to \'synadm user list -d -g -n \'. Searches for users by name/matrix-ID, including deactivated users as well as guest users. Also, compared to the original command, a case-insensitive search is done. """ click.echo("User search results for '{}':".format(search_term.lower())) ctx.invoke(list_user_cmd, from_=from_, limit=limit, name=search_term.lower(), deactivated=True, guests=True) click.echo("User search results for '{}':" .format(search_term.capitalize())) ctx.invoke(list_user_cmd, from_=from_, limit=limit, name=search_term.capitalize(), deactivated=True, guests=True) @user.command(name="details") @click.argument("user_id", type=str) @click.pass_obj def user_details_cmd(helper, user_id): """ View details of a user account. """ mxid = helper.generate_mxid(user_id) user_data = helper.api.user_details(mxid) if user_data is None: click.echo("User details could not be fetched.") raise SystemExit(1) helper.output(user_data) class UserModifyOptionGroup(RequiredAnyOptionGroup): @property def name_extra(self): return [] @user.command() @click.argument("user_id", type=str) @optgroup.group(cls=UserModifyOptionGroup) @optgroup.option( "--password-prompt", "-p", is_flag=True, help="Set password interactively.") @optgroup.option( "--password", "-P", type=str, help="Set password on command line.") @optgroup.option( "--display-name", "-n", type=str, help="Set display name. defaults to the value of user_id") @optgroup.option( "--threepid", "-t", type=str, multiple=True, nargs=2, help="""Set a third-party identifier (email address or phone number). Pass two arguments: `medium value` (eg. `--threepid email `). This option can be passed multiple times, which allows setting multiple entries for a user. When modifying existing users, all threepids are replaced by what's passed in all given `--threepid` options. Threepids are used for several things: For use when logging in, as an alternative to the user id; in the case of email, as an alternative contact to help with account recovery, as well as to receive notifications of missed messages.""") @optgroup.option( "--clear-threepids", is_flag=True, default=None, help="Remove all threepids of an existing user.") @optgroup.option( "--avatar-url", "-v", type=str, help="""Set avatar URL. Must be a MXC URI (https://matrix.org/docs/spec/client_server/r0.6.0#matrix-content-mxc-uris) """) @optgroup.option( "--admin/--no-admin", "-a/-u", default=None, help="""Grant user admin permission. Eg user is allowed to use the admin API.""", show_default=True,) @optgroup.option( "--activate", "deactivation", flag_value="activate", help="""Re-activate user.""") @optgroup.option( "--deactivate", "deactivation", flag_value="deactivate", help="""Deactivate user. Use with caution! Deactivating a user removes their active access tokens, resets their password, kicks them out of all rooms and deletes third-party identifiers (to prevent the user requesting a password reset). See also "user deactivate" command.""") @optgroup.option( "--user-type", type=str, default=None, show_default=True, help="""Change the type of the user. Currently understood by the Admin API are 'bot' and 'support'. Use 'regular' to create a regular Matrix user (which effectively sets the user-type to 'null'). If the --user-type option is omitted when modifying an existing user, the user-type will not be manipulated. If the --user-type option is omitted when creating a new user, a regular user will be created.""") @optgroup.option( "--lock/--unlock", "-l/-L", default=None, show_default=False, help="""Whether to lock or unlock the account, preventing or allowing logins respectively. Feature first present in Synapse 1.91.0.""") @click.pass_obj @click.pass_context def modify(ctx, helper, user_id, password, password_prompt, display_name, threepid, clear_threepids, avatar_url, admin, deactivation, user_type, lock): """ Create or modify a local user. Provide matrix user ID (@user:server) as argument. """ # sanity checks that can't easily be handled by Click. if password_prompt and password: click.echo("Use either '-p' or '-P secret', not both.") raise SystemExit(1) if deactivation == "deactivate" and (password_prompt or password): click.echo( "Deactivating a user and setting a password doesn't make sense.") raise SystemExit(1) mxid = helper.generate_mxid(user_id) click.echo("Current user account settings:") ctx.invoke(user_details_cmd, user_id=mxid) click.echo("User account settings to be modified:") for key, value in ctx.params.items(): # skip these, they get special treatment or can't be changed if key in ["user_id", "password", "password_prompt", "clear_threepids"]: continue if key == "threepid": if value == (('', ''),) or clear_threepids: click.echo("threepid: All entries will be cleared!") continue for t_key, t_val in value: click.echo(f"{key}: {t_key} {t_val}") if t_key not in ["email", "msisdn"]: helper.log.warning( f"{t_key} is probably not a supported medium " "type. Threepid medium types according to the " "current matrix spec are: email, msisdn.") elif key == "user_type" and value == 'regular': click.echo("user_type: null") elif value not in [None, {}, []]: # only show non-empty (aka changed) click.echo(f"{key}: {value}") if password_prompt: if helper.no_confirm: click.echo("Password prompt not available in non-interactive " "mode. Use -P.") else: password = click.prompt("Password", hide_input=True, confirmation_prompt=True) elif password: click.echo("Password will be set as provided on command line.") else: password = None sure = ( helper.no_confirm or click.prompt("Are you sure you want to modify/create user? (y/N)", type=bool, default=False, show_default=False) ) if sure: modified = helper.api.user_modify( mxid, password, display_name, (('', ''),) if clear_threepids else threepid, avatar_url, admin, deactivation, 'null' if user_type == 'regular' else user_type, lock ) if modified is None: click.echo("User could not be modified/created.") raise SystemExit(1) if helper.output_format == "human": if modified != {}: helper.output(modified) click.echo("User successfully modified/created.") else: click.echo("Synapse returned: {}".format(modified)) else: helper.output(modified) else: click.echo("Abort.") @user.command() @click.argument("user_id", type=str) @click.pass_obj def whois(helper, user_id): """ View information about a user's active session. """ mxid = helper.generate_mxid(user_id) user_data = helper.api.user_whois(mxid) helper.output(user_data) @user.command(name="media") @click.argument("user_id", type=str) @click.option( "--from", "-f", "from_", type=int, default=0, show_default=True, help="""Offset media listing by given number. This option is also used for pagination.""") @click.option( "--limit", "-l", type=int, default=100, show_default=True, help="Limit media listing to given number") @click.option( "--sort", "-s", type=click.Choice([ "media_id", "upload_name", "created_ts", "last_access_ts", "media_length", "media_type", "quarantined_by", "safe_from_quarantine"]), help="""The method by which to sort the returned list of media. If the ordered field has duplicates, the second order is always by ascending media_id, which guarantees a stable ordering.""") @click.option( "--reverse", "-r", is_flag=True, default=False, help="""Direction of media order. If set it will reverse the sort order of --order-by method.""") @click.option( "--datetime/--timestamp", "--dt/--ts", default=True, help="""Display created and last accessed timestamps in a human readable format, or as a unix timestamp in milliseconds. [default: datetime].""") @click.pass_obj def user_media_cmd(helper, user_id, from_, limit, sort, reverse, datetime): """ List all local media uploaded by a user. Provide matrix user ID (@user:server) as argument. Gets a list of all local media that a specific user_id has created. By default, the response is ordered by descending creation date and ascending media ID. The newest media is on top. You can change the order with options --order-by and --reverse. Caution. The database only has indexes on the columns media_id, user_id and created_ts. This means that if a different sort order is used (upload_name, last_access_ts, media_length, media_type, quarantined_by or safe_from_quarantine), this can cause a large load on the database, especially for large environments """ mxid = helper.generate_mxid(user_id) media = helper.api.user_media(mxid, from_, limit, sort, reverse, datetime) if media is None: click.echo("Media could not be fetched.") raise SystemExit(1) if helper.output_format == "human": click.echo("User has uploaded {} media blobs." .format(media["total"])) if int(media["total"]) != 0: helper.output(media["media"]) if "next_token" in media: click.echo("There are more results available than shown, " "use '--from {}' " "to go to next page (Total results: {})".format( media["next_token"], media["total"] )) else: helper.output(media) @user.command(name="login") @click.argument("user_id", type=str) @optgroup.group( "Token expires", cls=MutuallyExclusiveOptionGroup, help="") @optgroup.option( "--expire-days", "-d", type=int, help="""Expire token after this number of days.""") @optgroup.option( "--expire", type=click.DateTime(), help="""Expire token after this point in time. Eg. '2021-01-01', see above for available date/time formats.""") @optgroup.option( "--expire-ts", type=int, help="""Expire token after this point in time giving a unix timestamp in ms.""") @optgroup.option( "--expire-never", is_flag=True, default=False, show_default=True, help="""Never expire token.""") @click.pass_obj def user_login_cmd(helper, user_id, expire_days, expire, expire_ts, expire_never): """Get an access token for a given user. Useful for when admins wish to do actions on behalf of a user. If no --expire* option is given, a default token expiry time of exactly 1 day (24h) is used. If it's desired that the token never expires, use --expire-never This API does not generate a new device for the user, and so will not appear in their /devices list, and in general the target user should not be able to tell they have been logged in as. To expire the token before the expiry date/time is reached, call the standard /logout API with the token. Note: The token will expire if the admin user calls /logout/all from any of their devices, but the token will not expire if the target user does the same. """ mxid = helper.generate_mxid(user_id) if expire_never: user_login = helper.api.user_login(mxid, None, None, None) elif not expire_days and not expire and not expire_ts: user_login = helper.api.user_login(mxid, 1, expire, expire_ts) else: user_login = helper.api.user_login(mxid, expire_days, expire, expire_ts) if helper.no_confirm: if user_login is None: raise SystemExit(1) helper.output(user_login) else: click.echo("""You are fetching an authentication token of a user, which enables you to execute any Matrix command on their behalf. Please respect their privacy and know what you are doing! Be responsible!\n""") if user_login is None: click.echo(f"Login as user {user_id} not successful.") raise SystemExit(1) else: helper.output(user_login) @user.command(name="shadow-ban") @click.argument("user_id", type=str) @click.option( "-u", "--unban", is_flag=True, default=False, show_default=False, help="Unban the specified user" ) @click.pass_obj def user_shadow_ban(helper, user_id, unban): """Shadow-ban or unban a user. Useful for moderating malicious or egregiously abusive users. A shadow-banned user will not receive any notification, but still will be unable to contact anyone on the server. Use this as a tool of last resort since it may lead to confusing or broken behaviour for the client. Generally, it is more appropriate to ban or kick abusive users. """ mxid = helper.generate_mxid(user_id) user_ban = helper.api.user_shadow_ban(mxid, unban) if user_ban is None: click.echo("Failed to shadow-ban: {}".format(user_id)) raise SystemExit(1) if helper.output_format == "human": action = "shadow-ban" if unban: action = "shadow-unban" if user_ban: click.echo("Failed to {} the user: {}".format(action, user_id)) helper.output(user_ban) else: click.echo("Successfully {}ned user: {}".format(action, user_id)) else: helper.output(user_ban) @user.command(name="auth-provider") @click.argument("external_user_id", type=str) @click.option( "-p", "--provider", is_flag=False, required=True, default=None, show_default=True, help="""Provider ID as advertised in supported authenticated methods in `m.login.sso` api response such as 'oidc' or 'google' or 'github'""" ) @click.pass_obj def auth_provider_search(helper, provider, external_user_id): """Find a user based on their ID in auth-provider. Finds a user based on their external user ID in a particular auth provider where provider is the auth provider ID as advertised in supported authenticated methods in `m.login.sso` api response such as 'oidc' or 'google' or 'github'. """ helper.output( helper.api.user_auth_provider_search(provider, external_user_id) ) @user.command(name="3pid") @click.argument("address", type=str) @click.option( "-m", "--medium", is_flag=False, required=True, default="email", show_default=True, help="""Medium specifies what kind of Third Party ID is used such as 'email' or 'msidn'""" ) @click.pass_obj def third_party_id_search(helper, medium, address): """Find a user based on their Third Party ID. Finds a user based on their Third Party ID (3PID) where medium is the kind of Third Party ID that is used such as 'email' or 'msidn'. """ helper.output(helper.api.user_3pid_search(medium, address)) ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1712130070.0589488 synadm-0.46/synadm.egg-info/0000755000076500000240000000000000000000000015237 5ustar00jacksonstaff././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1712130070.0 synadm-0.46/synadm.egg-info/PKG-INFO0000644000076500000240000003457500000000000016352 0ustar00jacksonstaffMetadata-Version: 2.1 Name: synadm Version: 0.46 Summary: Command line admin tool for Synapse (Matrix reference homeserver) Home-page: https://github.com/joj0/synadm Author: Johannes Tiefenbacher Author-email: jt@peek-a-boo.at License: GPLv3+ Project-URL: Bug Tracker, https://github.com/joj0/synadm/issues Project-URL: Documentation, https://github.com/joj0/synadm Project-URL: Source Code, https://github.com/joj0/synadm Classifier: License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+) Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.6 Classifier: Programming Language :: Python :: 3.7 Classifier: Programming Language :: Python :: 3.8 Classifier: Programming Language :: Python :: 3.9 Classifier: Programming Language :: Python :: 3.10 Classifier: Operating System :: OS Independent Classifier: Topic :: System :: Systems Administration Classifier: Topic :: Communications :: Chat Classifier: Environment :: Console Description-Content-Type: text/markdown License-File: LICENSE Requires-Dist: Click<9.0,>=7.1 Requires-Dist: requests Requires-Dist: tabulate Requires-Dist: PyYaml Requires-Dist: click-option-group>=0.5.2 Requires-Dist: dnspython # synadm - the Matrix-Synapse admin CLI - [About](#about) - [Prerequisites](#prerequisites) - [Installation](#installation) - [Install from PyPI](#install-from-pypi) - [Install from git](#install-from-git) - [Configuration](#configuration) - [Getting an Admin Token](#getting-an-admin-token) - [The configurator](#the-configurator) - [matrix-docker-ansible-deploy](#matrix-docker-ansible-deploy) - [Usage](#usage) - [Command Line Reference](#command-line-reference) - [Advanced Usage](#advanced-usage) - [Update](#update) - [Update PyPI Package](#update-pypi-package) - [Update git Installation](#update-git-installation) - [Implementation Status / Commands List](#implementation-status--commands-list) - [Get in Touch](#get-in-touch) - [Contributing](#contributing) ## About A CLI tool to help admins of [Matrix-Synapse homeservers](https://github.com/matrix-org/synapse) conveniently issue commands available via its [Admin API](https://element-hq.github.io/synapse/develop/usage/administration/admin_api/index.html#the-admin-api). ## Prerequisites - Python 3.6+ - a running Synapse instance - an admin-enabled user on the instance - the admin user's access token `synadm` is designed to run either directly on the host running the Synapse instance or on a remote machine able to access Synapse's API port. Synapse's default Admin API endpoint address usually is http://localhost:8008/_synapse/admin or https://localhost:8448/_synapse/admin. ## Installation ### Install from PyPI `pip3 install synadm` ### Install from git #### 1. Check Python Version `python3 --version` should show at least v3.6.x #### 2. Clone Repo: ``` git clone https://github.com/joj0/synadm ``` #### 3. Install Package Globally This will install `synadm` and all dependent Python packages to your system's global Python site-packages directory: ``` cd synadm sudo pip install . ``` *Note: If you get an import error for setuptools, make sure the package is installed. Debian based systems: `sudo apt install python3-setuptools`, RedHat based: `sudo yum install python3-setuptools`* #### 4. Run `synadm` should now run fine without having to add a path in front of it: ``` synadm -h ``` *Note: Usually setuptools installs a command wrapper to `/usr/local/bin/synadm`, but that depends on your system.* *Note: In case you don't want `synadm` to be installed to a global system directory, you can find an [alternative way of installing](CONTRIBUTING.md#getting-the-source--installing) in the contribution docs*. *Note: synadm is multi-user aware - it stores its configuration inside the executing user's home directory. See chapter [configuration](#configuration).* ## Configuration ### Getting an Admin Token To find out your admin user's token in Element-Web: _Login as this user - "Click User Avatar" - "All Settings" - "Help & About" - Scroll down - "Advanced" - "Access Token"_ Or use synadm to fetch a token already. Use the fully qualified Matrix ID of the admin user: ``` synadm matrix login @admin_username:yourdomain.org Password: ``` If you issue this command in a fresh `synadm` installation, [the configurator](#the-configurator) will launch anyway. - Answer the questions. - Set token to "invalid" at first, to convience `synadm` to launch the `matrix login` command (otherwise you'd get a "Configuration incomplete" error). - After successfully entering your admin password you will be presented a token which you can finally set by re-launching the configurator as described below. ### The configurator `synadm` asks for necessary configuration items on first launch automatically. Also whenever new mandatory configuration items where added (eg after an update), the user will be prompted for missing items automatically. Configuration can be changed any time by launching the configurator directly: ``` synadm config ``` Configuration will be saved in `~/.config/synadm.yaml` *Note: Be aware that once you configured `synadm`, your admin user's token is saved in the configuration file. On Posix compatible systems permissions are set to mode 0600, on other OS's it is your responsibilty to change permissions accordingly.* ### matrix-docker-ansible-deploy To use `synadm` with Synapse homeservers that were installed using [matrix-docker-ansible-deploy](https://github.com/spantaleev/matrix-docker-ansible-deploy) you have two options. Access the Synapse Admin API's "via the public endpoint" similar to a Matrix client. - In [vars.yaml](https://github.com/spantaleev/matrix-docker-ansible-deploy/blob/master/docs/configuring-playbook.md#configuring-the-ansible-playbook) set `matrix_nginx_proxy_proxy_matrix_client_api_forwarded_location_synapse_admin_api_enabled: true`. - The API's are accessible on the Client-Server API port, at `https://matrix.DOMAIN`. - Install `synadm` on your Docker host or on a separate machine. - Configure `synadm` to access at `https://matrix.DOMAIN:443/_synapse/admin` Alternatively, you can access the API's on the container network `matrix`. - Synapse is accessible via the hostname `matrix-synapse` resolved by the internal Docker DNS server. - The containers are connected internally via a network named `matrix` by default. - Start a container on that same network and install `synadm` into it. - Configure `synadm` to access at `http://matrix-synapse:8008/_synapse/admin` (http here, not https). Find some more details about the topic in [this issue post on the matrix-docker-ansible-deploy repo](https://github.com/spantaleev/matrix-docker-ansible-deploy/issues/1846#issuecomment-1135516112). _Note that currently `synadm` is using a part of the Server-Server (Federation) API (`keys/v2/server`) to retrieve "its own homeserver name". This affects some of the `media` management commands. By default and also as the Matrix spec recommends, this API is not accessible via the Client-Server API port. We are working on a better solution to retrieve the own servername but as a workaround the `key` API's can be exposed by setting `matrix_synapse_http_listener_resource_names: ["client","keys"]` in [vars.yaml](https://github.com/spantaleev/matrix-docker-ansible-deploy/blob/master/docs/configuring-playbook.md#configuring-the-ansible-playbook)._ Find more details about the topic [here](https://github.com/spantaleev/matrix-docker-ansible-deploy/issues/1761#issuecomment-1101170229). ## Usage Use the online help of the main command: ``` synadm -h ``` and of the available subcommands: ``` synadm version -h synadm user -h synadm room -h ``` You even can spare the `-h` option, `synadm` will show some abbreviated help for the executed subcommand anyway. For example: ``` synadm user ``` or ``` synadm user details ``` will show essential help for the particular subcommand right away. *Note: A list of currently available commands is found in chapter [implementation status / commands list](#implementation-status--commands-list)* as well as in the following chapter. ### Command Line Reference A detailed [Command Line Reference](https://synadm.readthedocs.io/en/latest/index_cli_reference.html) can be found in `synadm's` readthedocs documentation. ### Advanced Usage Examples of how `synadm` can be used in shell scripts and oneliners is provided in the [Scripting Examples](https://synadm.readthedocs.io/en/latest/examples.html) docs chapter. ## Update ### Update PyPI Package ``` pip3 install synadm --upgrade ``` ### Update git Installation To update `synadm` to the latest development state, just update your git repo and reinstall: ``` cd synadm git pull pip install . ``` *Note: If you installed it to a Python venv, [activate it](CONTRIBUTING.md#3-set-up-a-python3-virtual-environment).* *Note: If you installed it in [editable mode](CONTRIBUTING.md#4-install-in-editable-mode) (or for development), you can spare the `pip install .` command - just `git pull` and you're done.* ## Implementation Status / Commands List [Follow this link to the official Synapse Admin API docs](https://element-hq.github.io/synapse/develop/usage/administration/admin_api/index.html) - direct links to the specific API documentation pages are provided in the list below. *Note: Most commands have several optional arguments available. Put -h after any of the below listed commands to view them or have a look at the [Command Line Reference](https://synadm.readthedocs.io/en/latest/index_cli_reference.html).* * [ ] [Account Validity](https://element-hq.github.io/synapse/develop/admin_api/account_validity.html) * [x] [Delete Group](https://element-hq.github.io/synapse/develop/admin_api/delete_group.html) (delete community) * [ ] [Event Reports](https://element-hq.github.io/synapse/develop/admin_api/event_reports.html) * [x] [Media Admin](https://element-hq.github.io/synapse/develop/admin_api/media_admin_api.html) * [x] `media list -r ` * [x] `media list -u ` (alias of `user media `) * [x] `media quarantine -s -i ` * [x] `media quarantine -r ` * [x] `media quarantine -u ` * [x] `media protect ` * [x] `media delete -s -i ` * [x] `media delete -s --before --size 1024` * [x] `media purge --before ` (purge remote media API) * [x] [Purge History](https://element-hq.github.io/synapse/develop/admin_api/purge_history_api.html) * [x] `history purge ` * [x] `history purge-status ` * [x] ~~[Purge Rooms](https://element-hq.github.io/synapse/develop/admin_api/purge_room.html)~~ (DEPRECATED, covered by `room delete`) * [ ] [Register Users](https://element-hq.github.io/synapse/develop/admin_api/register_api.html) * [x] [Manipulate Room Membership](https://element-hq.github.io/synapse/develop/admin_api/room_membership.html) * [x] `room join` * [x] [Rooms](https://element-hq.github.io/synapse/develop/admin_api/rooms.html) * [x] `room list` * [x] `room details ` * [x] `room members ` * [x] `room delete ` * [x] `room make-admin ` * [x] `room state ` * [ ] Additional commands and aliases around room management * [x] `room search ` (alias of `room list -n `) * [x] `room resolve ` * [x] `room power-levels` * [x] `room block` * [x] `room block-status` * [x] [Server Notices](https://element-hq.github.io/synapse/develop/admin_api/server_notices.html) * [x] ~~[Shutdown Room](https://element-hq.github.io/synapse/develop/admin_api/shutdown_room.html)~~ (DEPRECATED, covered by `room delete`) * [ ] [Statistics](https://element-hq.github.io/synapse/develop/admin_api/statistics.html) * [ ] `synadm media user-stats` * [ ] `synadm room largest` * [x] [Users](https://element-hq.github.io/synapse/develop/admin_api/user_admin_api.html) * [x] `user details ` * [x] `user modify ` (also used for user creation) * [x] `user list` * [x] `user deactivate ` (including GDPR erase) * [x] `user password ` * [x] `user membership ` * [x] `user whois ` * [x] `user shadow-ban ` * [x] `user media -u ` (also available as `media list -u `) * [x] `user login ` * [ ] Additional commands and aliases around user management * [x] `user search ` (shortcut to `user list -d -g -n `) * [ ] `user create ` (alias of `user modify ...`) * [x] `user prune-devices ` * [x] [Server Version](https://element-hq.github.io/synapse/develop/admin_api/version_api.html) * [x] `version` * [x] [Registration Tokens](https://element-hq.github.io/synapse/latest/usage/administration/admin_api/registration_tokens.html) * [x] `regtok list` * [x] `regtok details ` * [x] `regtok new` * [x] `regtok update ` * [x] `regtok delete ` ## Get in Touch If you need advice on using synadm, have a feature idea or would like to discuss anything else around `synadm`, get in touch via Matrix! We are hanging around in the official support room for Synapse, [#synapse:matrix.org](https://matrix.to/#/#synapse:matrix.org). Usually you'll find `synadm` users there that might answer your questions already. If not, mentioning `synadm` will ping us with the help of Element's keyword notify feature and we'll try to get in touch. The most direct way to reach synadm maintainers as well as seasoned users and Synapse admins is by joining [#synadm:peek-a-boo.at](https://matrix.to/#/#synadm:peek-a-boo.at). If you are sure you've found a bug that was not already reported, certainly directly opening an [issue on GitHub](https://github.com/JOJ0/synadm/issues) is a valid option too. If unsure, ask in [#synadm:peek-a-boo.at](https://matrix.to/#/#synadm:peek-a-boo.at) first. ## Contributing First of all, thanks for your interest in contributing to `synadm`! We appreciate any help, no matter if you are a programmer or a user. Both groups can do valuable things for the `synadm` project. We love providing a useful tool to fellow Synapse sysadmins but rely on contribution from the Synapse and Matrix community to keep `synadm` useful, current and stable. Please review the [contributing docs](CONTRIBUTING.md) for guidelines and help around the topic! ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1712130070.0 synadm-0.46/synadm.egg-info/SOURCES.txt0000644000076500000240000000077400000000000017133 0ustar00jacksonstaffLICENSE README.md setup.py synadm/__init__.py synadm/__main__.py synadm/api.py synadm.egg-info/PKG-INFO synadm.egg-info/SOURCES.txt synadm.egg-info/dependency_links.txt synadm.egg-info/entry_points.txt synadm.egg-info/requires.txt synadm.egg-info/top_level.txt synadm/cli/__init__.py synadm/cli/_common.py synadm/cli/_helper.py synadm/cli/group.py synadm/cli/history.py synadm/cli/matrix.py synadm/cli/media.py synadm/cli/notice.py synadm/cli/raw.py synadm/cli/regtok.py synadm/cli/room.py synadm/cli/user.py././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1712130070.0 synadm-0.46/synadm.egg-info/dependency_links.txt0000644000076500000240000000000100000000000021305 0ustar00jacksonstaff ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1712130070.0 synadm-0.46/synadm.egg-info/entry_points.txt0000644000076500000240000000005300000000000020533 0ustar00jacksonstaff[console_scripts] synadm = synadm.cli:root ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1712130070.0 synadm-0.46/synadm.egg-info/requires.txt0000644000076500000240000000011500000000000017634 0ustar00jacksonstaffClick<9.0,>=7.1 requests tabulate PyYaml click-option-group>=0.5.2 dnspython ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1712130070.0 synadm-0.46/synadm.egg-info/top_level.txt0000644000076500000240000000000700000000000017766 0ustar00jacksonstaffsynadm