├── .dockerignore ├── .gitignore ├── Changelog.md ├── Dockerfile ├── LICENSE.TXT ├── README.md ├── README.rst ├── contrib ├── ansible-role │ ├── README.md │ ├── meta │ │ └── main.yml │ ├── tasks │ │ ├── main.yml │ │ ├── setup_install.yml │ │ ├── setup_uninstall.yml │ │ └── validate_config.yml │ └── templates │ │ ├── config.yml.j2 │ │ └── matrix-registration-bot.service.j2 └── docker │ ├── Dockerfile │ └── TestDocker ├── docs ├── releases.md └── troubleshooting.md ├── example_config.yml ├── logo.png ├── matrix_registration_bot ├── __init__.py ├── bot.py ├── config.py └── registration_api.py ├── pyproject.toml ├── requirements.txt ├── setup.py └── tests ├── __init__.py └── test_registration_api.py /.dockerignore: -------------------------------------------------------------------------------- 1 | ## GIT ## 2 | .gitignore 3 | .git 4 | 5 | ## Dev files ## 6 | config.yml 7 | config.toml 8 | session.txt 9 | .env 10 | 11 | ## OSX ## 12 | .DS_Store 13 | .AppleDouble 14 | .LSOverride 15 | 16 | ## SublimeText ## 17 | # cache files for sublime text 18 | *.tmlanguage.cache 19 | *.tmPreferences.cache 20 | *.stTheme.cache 21 | 22 | # workspace files are user-specific 23 | *.sublime-workspace 24 | 25 | # project files should be checked into the repository, unless a significant 26 | # proportion of contributors will probably not be using SublimeText 27 | # *.sublime-project 28 | 29 | # sftp configuration file 30 | sftp-config.json 31 | 32 | # Basics 33 | *.py[cod] 34 | __pycache__ 35 | 36 | # Logs 37 | *.log 38 | 39 | # Unit test / coverage reports 40 | .coverage 41 | .tox 42 | nosetests.xml 43 | htmlcov 44 | 45 | # Translations 46 | *.mo 47 | *.pot 48 | 49 | # Pycharm 50 | .idea 51 | 52 | # Vim 53 | 54 | *~ 55 | *.swp 56 | *.swo 57 | 58 | 59 | # virtual environments 60 | .env 61 | venv 62 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | config.yml 2 | session.txt 3 | **/store 4 | .env 5 | 6 | # Byte-compiled / optimized / DLL files 7 | __pycache__/ 8 | *.py[cod] 9 | *$py.class 10 | 11 | # C extensions 12 | *.so 13 | 14 | # Distribution / packaging 15 | .Python 16 | build/ 17 | develop-eggs/ 18 | dist/ 19 | downloads/ 20 | eggs/ 21 | .eggs/ 22 | lib/ 23 | lib64/ 24 | parts/ 25 | sdist/ 26 | var/ 27 | wheels/ 28 | share/python-wheels/ 29 | *.egg-info/ 30 | .installed.cfg 31 | *.egg 32 | MANIFEST 33 | 34 | # PyInstaller 35 | # Usually these files are written by a python script from a template 36 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 37 | *.manifest 38 | *.spec 39 | 40 | # Installer logs 41 | pip-log.txt 42 | pip-delete-this-directory.txt 43 | 44 | # Unit test / coverage reports 45 | htmlcov/ 46 | .tox/ 47 | .nox/ 48 | .coverage 49 | .coverage.* 50 | .cache 51 | nosetests.xml 52 | coverage.xml 53 | *.cover 54 | *.py,cover 55 | .hypothesis/ 56 | .pytest_cache/ 57 | cover/ 58 | 59 | # Translations 60 | *.mo 61 | *.pot 62 | 63 | # Django stuff: 64 | *.log 65 | local_settings.py 66 | db.sqlite3 67 | db.sqlite3-journal 68 | 69 | # Flask stuff: 70 | instance/ 71 | .webassets-cache 72 | 73 | # Scrapy stuff: 74 | .scrapy 75 | 76 | # Sphinx documentation 77 | docs/_build/ 78 | 79 | # PyBuilder 80 | .pybuilder/ 81 | target/ 82 | 83 | # Jupyter Notebook 84 | .ipynb_checkpoints 85 | 86 | # IPython 87 | profile_default/ 88 | ipython_config.py 89 | 90 | # pyenv 91 | # For a library or package, you might want to ignore these files since the code is 92 | # intended to run in multiple environments; otherwise, check them in: 93 | # .python-version 94 | 95 | # pipenv 96 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 97 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 98 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 99 | # install all needed dependencies. 100 | #Pipfile.lock 101 | 102 | # poetry 103 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 104 | # This is especially recommended for binary packages to ensure reproducibility, and is more 105 | # commonly ignored for libraries. 106 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 107 | #poetry.lock 108 | 109 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 110 | __pypackages__/ 111 | 112 | # Celery stuff 113 | celerybeat-schedule 114 | celerybeat.pid 115 | 116 | # SageMath parsed files 117 | *.sage.py 118 | 119 | # Environments 120 | .env 121 | .venv 122 | env/ 123 | venv/ 124 | ENV/ 125 | env.bak/ 126 | venv.bak/ 127 | 128 | # Spyder project settings 129 | .spyderproject 130 | .spyproject 131 | 132 | # Rope project settings 133 | .ropeproject 134 | 135 | # mkdocs documentation 136 | /site 137 | 138 | # mypy 139 | .mypy_cache/ 140 | .dmypy.json 141 | dmypy.json 142 | 143 | # Pyre type checker 144 | .pyre/ 145 | 146 | # pytype static type analyzer 147 | .pytype/ 148 | 149 | # Cython debug symbols 150 | cython_debug/ 151 | 152 | # PyCharm 153 | # JetBrains specific template is maintainted in a separate JetBrains.gitignore that can 154 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 155 | # and can be added to the global gitignore or merged into this file. For a more nuclear 156 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 157 | # 158 | .idea/ 159 | -------------------------------------------------------------------------------- /Changelog.md: -------------------------------------------------------------------------------- 1 | # 1.2.2 2 | 3 | Updating dependencies 4 | 5 | **New docker versioning** 6 | We also introduce a new docker version scheme. Docker versions should follow the versioning 7 | of `-0` where 0 ist the docker iteration and is increased by one for each docker build of the same 8 | package version. This helps if the package is okay but the docker build has an error. Docker tag `1.2.2` can be seen as 9 | `1.2.2-0` but you should use `1.2.2-1` or newer. 10 | 11 | # 1.2.0 12 | 13 | **NO user action needed** 14 | 15 | ## Enhancements 16 | 17 | * **Encryption support 🥳**: The bot can now use encryption by default. This is possible thanks to the work of [simple-matrix-bot-lib](https://codeberg.org/imbev/simplematrixbotlib) 18 | (the framework this bot uses) and @noobping that added the support in this bot. 19 | 20 | * **Bot Prefix is now configurable:** The bot uses no prefix by default. To make the bot respond (only) when using a specific prefix (e.g. `!`) you can use 21 | ```yaml 22 | bot: 23 | prefix: "!" 24 | ``` 25 | 26 | ## Bugfixes 27 | 28 | * @olivercoad discovered and fixed a case where we don't safe the config correctly after disallowing a person/pattern -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM python:3.11-slim AS compile-image 2 | MAINTAINER Julian-Samuel Gebühr 3 | 4 | 5 | RUN apt-get update && apt-get install -y --no-install-recommends build-essential gcc libolm-dev 6 | 7 | RUN python -m venv /opt/venv 8 | 9 | WORKDIR /app 10 | COPY requirements.txt ./ 11 | RUN /opt/venv/bin/pip install -r requirements.txt 12 | COPY . . 13 | RUN /opt/venv/bin/pip install . 14 | RUN /opt/venv/bin/pip install matrix-nio==0.20.2 15 | 16 | FROM python:3.11-slim 17 | 18 | RUN apt-get update && apt-get install -y libolm-dev 19 | COPY --from=compile-image /opt/venv /opt/venv 20 | 21 | VOLUME ["/data"] 22 | WORKDIR /data 23 | 24 | CMD ["/opt/venv/bin/matrix-registration-bot"] 25 | -------------------------------------------------------------------------------- /LICENSE.TXT: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published by 637 | the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | 663 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Matrix Registration Bot 2 | 3 | ![Pypi badge](https://img.shields.io/pypi/v/matrix-registration-bot.svg) 4 | ![License](https://img.shields.io/pypi/l/matrix-registration-bot?color=%23008000) 5 | ![Docker pulls](https://img.shields.io/docker/pulls/moanos/matrix-registration-bot) 6 | 7 | This bot aims to create and manage registration tokens for a matrix server. It wants to help invitation based servers to 8 | maintain usability. It does not create a user itself, but allows registration only with a valid token as defined by 9 | Matrix standard 10 | [MSC3231](https://github.com/matrix-org/matrix-doc/blob/main/proposals/3231-token-authenticated-registration.md). The 11 | benefit is, that an administrator minimizes manual work and does not know a user's password at any time. 12 | 13 | This means, that a user that registers on your server has to provide a registration token to successfully create an 14 | account. The token can be created by interacting with this bot. So to invite a friend you would send `create` to the bot 15 | which answers with a token. You send the token to the friend, and they can use this to create an account. 16 | 17 | The feature was added in Matrix v1.2. More information can be found in the 18 | [Synapse Documentation](https://matrix-org.github.io/synapse/latest/usage/administration/admin_api/registration_tokens.html) 19 | . 20 | 21 | If you have any questions, or if you need help setting it up, read the [troublshooting guide](./docs/troubleshooting.md) 22 | or join [#matrix-registration-bot:hyteck.de](https://matrix.to/#/#matrix-registration-bot:hyteck.de). 23 | 24 | # Supported commands 25 | 26 | **Unrestricted commands** 27 | 28 | * `help`: Shows this help 29 | 30 | **Restricted commands** 31 | 32 | * `list`: Lists all registration tokens 33 | * `show `: Shows token details in human-readable format 34 | * `create`: Creates a token that that is valid for one registration for seven days 35 | * `delete ` Deletes the specified token(s) 36 | * `delete-all` Deletes all tokens 37 | * `allow @user:example.com` Allows the specified user (or a user matching a regex pattern) to use restricted commands 38 | * `disallow @user:example.com` Stops a specified user (or a user matching a regex pattern) from using restricted 39 | commands 40 | 41 | # Permissions 42 | 43 | By default, any user on the homeserver of the bot is allowed to use restricted commands. You can change that, by using 44 | the `allow` command to configure one (or multiple) specific user. Read 45 | the [simple-matrix-bot documentation](https://simple-matrix-bot-lib.readthedocs.io/en/latest/manual.html#allowlist) 46 | for more information. If you get locked out for any reason, simply modify the config.toml that is created in the bots 47 | working directory. 48 | 49 | # Getting started 50 | 51 | ## Install via [matrix-docker-ansible-deploy](https://github.com/spantaleev/matrix-docker-ansible-deploy) 52 | 53 | If you already installed your homeserver with this ansible playbook you can make use of a very simple setup. Check out [the setup instructions in the project's repo](https://github.com/spantaleev/matrix-docker-ansible-deploy/blob/master/docs/configuring-playbook-bot-matrix-registration-bot.md). 54 | 55 | ## Prerequisites for all other installation methods 56 | 57 | ### Server configuration 58 | 59 | Your server should be configured to a token restricted registration. Add the following to your `homeserver.yaml`: 60 | 61 | ```yaml 62 | enable_registration: true 63 | registration_requires_token: true 64 | ``` 65 | 66 | ## Create a bot account 67 | 68 | Then you need to create an account for the bot on the server, like you would do with any other account. A good username 69 | is `registration-bot`. If you want to use token based login, note the access token of the bot. One way to get the token 70 | is to log in as the bot and got to `Settings -> Help & About -> Access Token` in Element, however you mustn't log out or 71 | the token will be invalidated. As an alternative you can use the command 72 | 73 | ```shell 74 | curl -X POST --header 'Content-Type: application/json' -d '{ 75 | "identifier": { "type": "m.id.user", "user": "YourBotUsername" }, 76 | "password": "YourBotPassword", 77 | "type": "m.login.password" 78 | }' 'https://matrix.YOURDOMAIN/_matrix/client/r0/login' 79 | ``` 80 | 81 | Once you are finished you can start the installation of the bot. 82 | 83 | ## Manual Installation 84 | 85 | The installation can easily be done via [PyPi](https://pypi.org/project/matrix-registration-bot/) 86 | 87 | ```bash 88 | $ pip install matrix-registration-bot 89 | ``` 90 | 91 | ## Configuration 92 | 93 | Configure the bot with a file named `config.yml`. It should look like this 94 | 95 | ```yaml 96 | bot: 97 | server: "https://synapse.example.com" 98 | username: "registration-bot" 99 | access_token: "verysecret" 100 | # It is also possible to use a password based login by commenting out the access token line and adjusting the line below 101 | # password: "secretpassword" 102 | prefix: "" 103 | api: 104 | # API endpoint of the registration tokens 105 | base_url: 'https://synapse.example.com' 106 | # Access token of an administrator on the server. If you configured the bot to be an admin on the sever you can use the same token as above. 107 | token: "supersecret" 108 | logging: 109 | level: DEBUG/INFO/ERROR 110 | ``` 111 | 112 | It is also possible to use environment variables to configure the bot. The variable names are all upper case, 113 | concatenated with `_` e.g. `LOGGING_LEVEL`. 114 | 115 | 116 | ### Start the bot 117 | 118 | Start the bot with 119 | 120 | ```bash 121 | python -m matrix_registration_bot.bot 122 | ``` 123 | 124 | and then open a Direct Message to the bot. The type one of the following commands. 125 | 126 | ### Automatically (re-)start the bot with Systemd 127 | 128 | To have the bot start automatically after reboots create the file `/etc/systemd/system/matrix-registration-bot.service` 129 | with the following content on your server. This assumes you use that you place your configuration in 130 | `/matrix/matrix-registration-bot/config.yml`. 131 | 132 | ``` 133 | [Unit] 134 | Description=matrix-registration-bot 135 | 136 | [Service] 137 | Type=simple 138 | 139 | WorkingDirectory=/matrix/matrix-registration-bot 140 | ExecStart=python3 -m matrix_registration_bot.bot 141 | 142 | Restart=always 143 | RestartSec=30 144 | SyslogIdentifier=matrix-registration-bot 145 | 146 | [Install] 147 | WantedBy=multi-user.target 148 | ``` 149 | 150 | After creating the service reload your daemon and start+enable the service. 151 | 152 | ```bash 153 | $ sudo systemctl daemon-reload 154 | $ sudo systemctl start matrix-registration-bot 155 | $ sudo systemclt enable matrix-registration-bot 156 | ``` 157 | 158 | ## Install using docker-compose 159 | 160 | To use this container via docker you can create the following `docker-compose.yml` and start the container 161 | with `docker-compose up -d`. Explanation on how to obtain the correct values of the configuration can be found in the 162 | **Manual installation** section. 163 | 164 | ``` yaml 165 | version: "3.7" 166 | 167 | services: 168 | matrix-registration-bot: 169 | image: moanos/matrix-registration-bot:latest 170 | environment: 171 | LOGGING_LEVEL: DEBUG 172 | BOT_SERVER: "https://synapse.example.com" 173 | BOT_USERNAME: "registration-bot" 174 | BOT_PASSWORD: "password" 175 | API_BASE_URL: 'https://synapse.example.com' 176 | API_TOKEN: "syt_xxxxxxxxxxxxxxxxxxxxxxxx" 177 | 178 | ``` 179 | git checkout de 180 | # End-to-End Encryption 181 | 182 | From version 1.2.0 the bot supports E2E encryption. This is a bit safer and also allows to create direct messages (which are by default encrypted). 183 | This will be enabled by default. 184 | 185 | # Contributing 186 | 187 | Feel free to contribute or discuss this bot 188 | at [#matrix-registration-bot:hyteck.de](https://matrix.to/#/#matrix-registration-bot:hyteck.de) 189 | or simply open issues and PRs here. 190 | 191 | [Code of Conduct](https://www.contributor-covenant.org/version/2/1/code_of_conduct/) 192 | 193 | # Related Projects 194 | 195 | * The project is made possible by [Simple-Matrix-Bot-Lib](https://simple-matrix-bot-lib.readthedocs.io). 196 | * An alternative for managing tokens is [Synapse Admin](https://github.com/Awesome-Technologies/synapse-admin) 197 | 198 | 199 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | Matrix Registration Bot 2 | ======================= 3 | 4 | |Pypi badge| |License| |Docker pulls| 5 | 6 | This bot aims to create and manage registration tokens for a matrix 7 | server. It wants to help invitation based servers to maintain usability. 8 | It does not create a user itself, but allows registration only with a 9 | valid token as defined by Matrix standard 10 | `MSC3231 `__. 11 | The benefit is, that an administrator minimizes manual work and does not 12 | know a user’s password at any time. 13 | 14 | This means, that a user that registers on your server has to provide a 15 | registration token to successfully create an account. The token can be 16 | created by interacting with this bot. So to invite a friend you would 17 | send ``create`` to the bot which answers with a token. You send the 18 | token to the friend, and they can use this to create an account. 19 | 20 | The feature was added in Matrix v1.2. More information can be found in 21 | the `Synapse 22 | Documentation `__ 23 | . 24 | 25 | If you have any questions, or if you need help setting it up, read the 26 | `troublshooting guide <./docs/troubleshooting.md>`__ or join 27 | `#matrix-registration-bot:hyteck.de `__. 28 | 29 | Supported commands 30 | ================== 31 | 32 | **Unrestricted commands** 33 | 34 | - ``help``: Shows this help 35 | 36 | **Restricted commands** 37 | 38 | - ``list``: Lists all registration tokens 39 | - ``show ``: Shows token details in human-readable format 40 | - ``create``: Creates a token that that is valid for one registration 41 | for seven days 42 | - ``delete `` Deletes the specified token(s) 43 | - ``delete-all`` Deletes all tokens 44 | - ``allow @user:example.com`` Allows the specified user (or a user 45 | matching a regex pattern) to use restricted commands 46 | - ``disallow @user:example.com`` Stops a specified user (or a user 47 | matching a regex pattern) from using restricted commands 48 | 49 | Permissions 50 | =========== 51 | 52 | By default, any user on the homeserver of the bot is allowed to use 53 | restricted commands. You can change that, by using the ``allow`` command 54 | to configure one (or multiple) specific user. Read the 55 | `simple-matrix-bot 56 | documentation `__ 57 | for more information. If you get locked out for any reason, simply 58 | modify the config.toml that is created in the bots working directory. 59 | 60 | Getting started 61 | =============== 62 | 63 | Install via `matrix-docker-ansible-deploy `__ 64 | --------------------------------------------------------------------------------------------------------- 65 | 66 | If you already installed your homeserver with this ansible playbook you 67 | can make use of a very simple setup. Check out `the setup instructions 68 | in the project’s 69 | repo `__. 70 | 71 | Prerequisites for all other installation methods 72 | ------------------------------------------------ 73 | 74 | Server configuration 75 | ~~~~~~~~~~~~~~~~~~~~ 76 | 77 | Your server should be configured to a token restricted registration. Add 78 | the following to your ``homeserver.yaml``: 79 | 80 | .. code:: yaml 81 | 82 | enable_registration: true 83 | registration_requires_token: true 84 | 85 | Create a bot account 86 | -------------------- 87 | 88 | Then you need to create an account for the bot on the server, like you 89 | would do with any other account. A good username is 90 | ``registration-bot``. If you want to use token based login, note the 91 | access token of the bot. One way to get the token is to log in as the 92 | bot and got to ``Settings -> Help & About -> Access Token`` in Element, 93 | however you mustn’t log out or the token will be invalidated. As an 94 | alternative you can use the command 95 | 96 | .. code:: shell 97 | 98 | curl -X POST --header 'Content-Type: application/json' -d '{ 99 | "identifier": { "type": "m.id.user", "user": "YourBotUsername" }, 100 | "password": "YourBotPassword", 101 | "type": "m.login.password" 102 | }' 'https://matrix.YOURDOMAIN/_matrix/client/r0/login' 103 | 104 | Once you are finished you can start the installation of the bot. 105 | 106 | Manual Installation 107 | ------------------- 108 | 109 | The installation can easily be done via 110 | `PyPi `__ 111 | 112 | .. code:: bash 113 | 114 | $ pip install matrix-registration-bot 115 | 116 | Configuration 117 | ------------- 118 | 119 | Configure the bot with a file named ``config.yml``. It should look like 120 | this 121 | 122 | .. code:: yaml 123 | 124 | bot: 125 | server: "https://synapse.example.com" 126 | username: "registration-bot" 127 | access_token: "verysecret" 128 | # It is also possible to use a password based login by commenting out the access token line and adjusting the line below 129 | # password: "secretpassword" 130 | prefix: "" 131 | api: 132 | # API endpoint of the registration tokens 133 | base_url: 'https://synapse.example.com' 134 | # Access token of an administrator on the server. If you configured the bot to be an admin on the sever you can use the same token as above. 135 | token: "supersecret" 136 | logging: 137 | level: DEBUG/INFO/ERROR 138 | 139 | It is also possible to use environment variables to configure the bot. 140 | The variable names are all upper case, concatenated with ``_`` 141 | e.g. ``LOGGING_LEVEL``. 142 | 143 | Start the bot 144 | ~~~~~~~~~~~~~ 145 | 146 | Start the bot with 147 | 148 | .. code:: bash 149 | 150 | python -m matrix_registration_bot.bot 151 | 152 | and then open a Direct Message to the bot. The type one of the following 153 | commands. 154 | 155 | Automatically (re-)start the bot with Systemd 156 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 157 | 158 | To have the bot start automatically after reboots create the file 159 | ``/etc/systemd/system/matrix-registration-bot.service`` with the 160 | following content on your server. This assumes you use that you place 161 | your configuration in ``/matrix/matrix-registration-bot/config.yml``. 162 | 163 | :: 164 | 165 | [Unit] 166 | Description=matrix-registration-bot 167 | 168 | [Service] 169 | Type=simple 170 | 171 | WorkingDirectory=/matrix/matrix-registration-bot 172 | ExecStart=python3 -m matrix_registration_bot.bot 173 | 174 | Restart=always 175 | RestartSec=30 176 | SyslogIdentifier=matrix-registration-bot 177 | 178 | [Install] 179 | WantedBy=multi-user.target 180 | 181 | After creating the service reload your daemon and start+enable the 182 | service. 183 | 184 | .. code:: bash 185 | 186 | $ sudo systemctl daemon-reload 187 | $ sudo systemctl start matrix-registration-bot 188 | $ sudo systemclt enable matrix-registration-bot 189 | 190 | Install using docker-compose 191 | ---------------------------- 192 | 193 | To use this container via docker you can create the following 194 | ``docker-compose.yml`` and start the container with 195 | ``docker-compose up -d``. Explanation on how to obtain the correct 196 | values of the configuration can be found in the **Manual installation** 197 | section. 198 | 199 | .. code:: yaml 200 | 201 | version: "3.7" 202 | 203 | services: 204 | matrix-registration-bot: 205 | image: moanos/matrix-registration-bot:latest 206 | environment: 207 | LOGGING_LEVEL: DEBUG 208 | BOT_SERVER: "https://synapse.example.com" 209 | BOT_USERNAME: "registration-bot" 210 | BOT_PASSWORD: "password" 211 | API_BASE_URL: 'https://synapse.example.com' 212 | API_TOKEN: "syt_xxxxxxxxxxxxxxxxxxxxxxxx" 213 | 214 | git checkout de # End-to-End Encryption 215 | 216 | From version 1.2.0 the bot supports E2E encryption. This is a bit safer 217 | and also allows to create direct messages (which are by default 218 | encrypted). This will be enabled by default. 219 | 220 | Contributing 221 | ============ 222 | 223 | Feel free to contribute or discuss this bot at 224 | `#matrix-registration-bot:hyteck.de `__ 225 | or simply open issues and PRs here. 226 | 227 | `Code of 228 | Conduct `__ 229 | 230 | Related Projects 231 | ================ 232 | 233 | - The project is made possible by 234 | `Simple-Matrix-Bot-Lib `__. 235 | - An alternative for managing tokens is `Synapse 236 | Admin `__ 237 | 238 | .. |Pypi badge| image:: https://img.shields.io/pypi/v/matrix-registration-bot.svg 239 | .. |License| image:: https://img.shields.io/pypi/l/matrix-registration-bot?color=%23008000 240 | .. |Docker pulls| image:: https://img.shields.io/docker/pulls/moanos/matrix-registration-bot 241 | -------------------------------------------------------------------------------- /contrib/ansible-role/README.md: -------------------------------------------------------------------------------- 1 | # matrix-registration-bot Ansible role 2 | 3 | Written for Debian 11 4 | (does not work on Debian 10 with Python 3.7, 5 | because the [simplematrixbotlib](https://pypi.org/project/simplematrixbotlib/) 6 | dependency is only available for newer Python versions). 7 | 8 | Installs the virtual environment in `/opt/venvs/matrix-registration-bot` 9 | next to the virtual environment created by the official Matrix Synapse Debian package. 10 | 11 | 12 | ## Usage 13 | 14 | Copy this role to your desired Ansible roles directory, name and modify it as you see fit 15 | and configure the variables below for your groups/hosts. 16 | Use the Ansible Vault to store secrets. 17 | 18 | 19 | ### Variables 20 | 21 | * `matrix_registration_bot_enabled` True will enable the bot 22 | * `matrix_registration_bot_system_user` the username of the system user to run the bot as (will be created) 23 | * `matrix_client_api_endpoint` the Matrix client API base url to access (to access the `/_matrix/client/` endpoints) 24 | * `matrix_registration_bot_username` the Matrix username to identify as 25 | * `matrix_registration_bot_token` the Matrix bot user's authentication token 26 | * `synapse_api_endpoint` the Synapse server API base url (to access the `/_synapse/admin/` endpoints) 27 | * `synapse_admin_token` the access token of an administrative user 28 | -------------------------------------------------------------------------------- /contrib/ansible-role/meta/main.yml: -------------------------------------------------------------------------------- 1 | --- 2 | name: Install Matrix registration bot 3 | become: yes 4 | -------------------------------------------------------------------------------- /contrib/ansible-role/tasks/main.yml: -------------------------------------------------------------------------------- 1 | --- 2 | 3 | - import_tasks: "{{ role_path }}/tasks/validate_config.yml" 4 | when: "run_setup|bool and matrix_registration_bot_enabled|bool" 5 | tags: 6 | - setup-all 7 | - setup-matrix-registration-bot 8 | 9 | - import_tasks: "{{ role_path }}/tasks/setup_install.yml" 10 | when: "run_setup|bool and matrix_registration_bot_enabled|bool" 11 | tags: 12 | - setup-all 13 | - setup-matrix-registration-bot 14 | - import_tasks: "{{ role_path }}/tasks/setup_uninstall.yml" 15 | when: "run_setup|bool and not matrix_registration_bot_enabled|bool" 16 | tags: 17 | - setup-all 18 | - setup-matrix-registration-bot 19 | -------------------------------------------------------------------------------- /contrib/ansible-role/tasks/setup_install.yml: -------------------------------------------------------------------------------- 1 | --- 2 | - name: Update/install pip, virtualenv, setuptools and others 3 | ansible.builtin.apt: 4 | pkg: 5 | - python3 6 | - python3-pip 7 | - python3-setuptools 8 | - python3-virtualenv 9 | - python3-cryptography 10 | - python3-yaml 11 | update_cache: yes 12 | state: present 13 | - name: Update/install matrix-registration-bot 14 | ansible.builtin.pip: 15 | name: 16 | - simplematrixbotlib>=2.6.0,<3.0.0 17 | - aiohttp[speedups] 18 | - matrix-registration-bot 19 | state: latest 20 | virtualenv: /opt/venvs/matrix-registration-bot 21 | virtualenv_site_packages: yes 22 | - name: Ensure system user exists 23 | ansible.builtin.user: 24 | name: '{{ matrix_registration_bot_system_user }}' 25 | create_home: no 26 | home: /opt/venvs/matrix-registration-bot 27 | state: present 28 | system: yes 29 | - name: Ensure configuration directory exists 30 | ansible.builtin.file: 31 | path: /etc/matrix-registration-bot/ 32 | owner: '{{ matrix_registration_bot_system_user }}' 33 | group: '{{ matrix_registration_bot_system_user }}' 34 | mode: 0755 35 | state: directory 36 | - name: Update configuration file 37 | ansible.builtin.template: 38 | src: config.yml.j2 39 | dest: /etc/matrix-registration-bot/config.yml 40 | owner: '{{ matrix_registration_bot_system_user }}' 41 | group: '{{ matrix_registration_bot_system_user }}' 42 | mode: 0600 43 | - name: Upload systemd service file 44 | ansible.builtin.template: 45 | src: matrix-registration-bot.service.j2 46 | dest: /etc/systemd/system/matrix-registration-bot.service 47 | owner: root 48 | group: root 49 | mode: 0644 50 | - name: Enable/Restart matrix-registration-bot 51 | ansible.builtin.systemd: 52 | daemon_reload: yes 53 | name: matrix-registration-bot.service 54 | enabled: yes 55 | state: restarted 56 | -------------------------------------------------------------------------------- /contrib/ansible-role/tasks/setup_uninstall.yml: -------------------------------------------------------------------------------- 1 | --- 2 | - name: Check existence of matrix-registration-bot service 3 | stat: 4 | path: "/etc/systemd/system/matrix-registration-bot.service" 5 | register: matrix_registration_bot_service_stat 6 | 7 | - name: Stop/disable matrix-registration-bot 8 | ansible.builtin.systemd: 9 | daemon_reload: yes 10 | name: matrix-registration-bot.service 11 | enabled: no 12 | state: stopped 13 | when: "matrix_registration_bot_service_stat.stat.exists|bool" 14 | 15 | - name: Ensure system user is removed 16 | ansible.builtin.user: 17 | name: matrix-registration-bot 18 | state: absent 19 | remove: yes 20 | - name: Ensure configuration directory is removed 21 | ansible.builtin.file: 22 | path: /etc/matrix-registration-bot/ 23 | state: absent 24 | - name: Ensure systemd service file doesn't exist 25 | ansible.builtin.file: 26 | path: /etc/systemd/system/matrix-registration-bot.service 27 | state: absent 28 | when: "matrix_registration_bot_service_stat.stat.exists|bool" 29 | 30 | - name: Ensure systemd reloaded after systemd service removal 31 | service: 32 | daemon_reload: true 33 | when: "matrix_registration_bot_service_stat.stat.exists|bool" 34 | -------------------------------------------------------------------------------- /contrib/ansible-role/tasks/validate_config.yml: -------------------------------------------------------------------------------- 1 | --- 2 | 3 | - name: Fail if required settings not defined 4 | fail: 5 | msg: >- 6 | You need to define a required configuration setting (`{{ item }}`). 7 | when: "vars[item] == ''" 8 | with_items: 9 | - "matrix_registration_bot_enabled" 10 | - "matrix_registration_bot_system_user" 11 | - "matrix_client_api_endpoint" 12 | - "matrix_registration_bot_username" 13 | - "matrix_registration_bot_token" 14 | - "synapse_api_endpoint" 15 | - "synapse_admin_token" 16 | -------------------------------------------------------------------------------- /contrib/ansible-role/templates/config.yml.j2: -------------------------------------------------------------------------------- 1 | bot: 2 | server: "{{ matrix_client_api_endpoint }}" 3 | username: "{{ matrix_registration_bot_username }}" 4 | access_token: "{{ matrix_registration_bot_token }}" 5 | api: 6 | # API endpoint of the registration tokens 7 | base_url: "{{ synapse_api_endpoint }}" 8 | # Access token of an administrator on the server 9 | token: "{{ synapse_admin_token }}" 10 | logging: 11 | level: INFO 12 | -------------------------------------------------------------------------------- /contrib/ansible-role/templates/matrix-registration-bot.service.j2: -------------------------------------------------------------------------------- 1 | [Unit] 2 | Description=matrix-registration-bot 3 | 4 | [Service] 5 | Type=simple 6 | WorkingDirectory=/etc/matrix-registration-bot/ 7 | ExecStart=/opt/venvs/matrix-registration-bot/bin/python3 -m matrix_registration_bot.bot 8 | User={{ matrix_registration_bot_system_user }} 9 | Group={{ matrix_registration_bot_system_user }} 10 | Restart=always 11 | RestartSec=30 12 | SyslogIdentifier=matrix-reg-bot 13 | 14 | [Install] 15 | WantedBy=multi-user.target 16 | -------------------------------------------------------------------------------- /contrib/docker/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM python:3-slim AS compile-image 2 | MAINTAINER Julian-Samuel Gebühr 3 | 4 | RUN apt-get update && apt-get install -y --no-install-recommends build-essential gcc 5 | 6 | RUN python -m venv /opt/venv 7 | RUN /opt/venv/bin/pip install --no-cache-dir matrix-registration-bot 8 | 9 | FROM python:3-slim 10 | 11 | RUN apt-get update && libolm-dev 12 | COPY --from=compile-image /opt/venv /opt/venv 13 | 14 | VOLUME ["/data"] 15 | WORKDIR /data 16 | 17 | CMD ["/opt/venv/bin/matrix-registration-bot"] 18 | -------------------------------------------------------------------------------- /contrib/docker/TestDocker: -------------------------------------------------------------------------------- 1 | FROM python:3-slim AS compile-image 2 | MAINTAINER Julian-Samuel Gebühr 3 | 4 | RUN apt-get update && apt-get install -y --no-install-recommends build-essential gcc 5 | 6 | RUN python -m venv /opt/venv 7 | RUN /opt/venv/bin/pip install --no-cache-dir matrix-registration-bot 8 | 9 | FROM python:3-slim 10 | 11 | COPY --from=compile-image /opt/venv /opt/venv 12 | 13 | CMD ["/opt/venv/bin/matrix-registration-bot"] 14 | -------------------------------------------------------------------------------- /docs/releases.md: -------------------------------------------------------------------------------- 1 | # How-To Release 2 | 3 | 4 | ## General 5 | A release can be done when a number of changes come together that are stable or there is a bugfix that needs to 6 | be addressed. 7 | 8 | The version number should follow best practices of [semantic versioning](https://semver.org/). 9 | 10 | When it is decided to release and the `develop` branch should include all commits and merge requests that should be 11 | released. Create the `README.rst` (for PyPi) with `pandoc --from=markdown --to=rst --output=README.rst README.md `. 12 | Commit and then merge into the main branch. On the main branch there are only two changes to make: Bump the 13 | version in `matrix_registration_bot/__init__.py` and commit this with `Bump version to v1.0.0` 14 | 15 | ## Test a release 16 | 17 | ### Build 18 | 19 | ```bash 20 | python -m build 21 | ``` 22 | 23 | ### Test & Upload to Test-PyPI 24 | 25 | ```bash 26 | twine check dist/* 27 | twine upload -r testpypi dist/* 28 | ``` 29 | 30 | 31 | ## Release 32 | 33 | Create a git tag and push it to GitHub 34 | 35 | ```bash 36 | git tag -a v1.0.0 -m "Releasing version v1.0.0" 37 | git push origin v1.0.0 38 | ``` 39 | Afterward, you should mark the tag as release and include a changelog. Try to use a similar structure as previous 40 | releases. 41 | 42 | ## Upload to PyPi 43 | 44 | ```bash 45 | $ python -m build 46 | $ twine upload dist/* 47 | ``` 48 | 49 | ## Docker 50 | 51 | First build the latest docker version and test it. 52 | ```bash 53 | docker build . --tag moanos/matrix-registration-bot:latest 54 | docker run -e "CONFIG_PATH=/config/config.yml" --mount type=bind,src=./config.yml,dst=/config/config.yml,ro moanos/matrix-registration-bot:latest 55 | ``` 56 | 57 | If that looks good you can tag it with the appropriate docker version. Docker versions should follow the versioning 58 | of `-0` where 0 ist the docker iteration and is increased by one for each docker build of the same 59 | package version. This helps if the package is okay but the docker build has an error. 60 | 61 | Publish the image with 62 | ```bash 63 | docker login 64 | docker push moanos/matrix-registration-bot:1.2.2-0 65 | ``` 66 | and don't forget to update [spantaleev/matrix-docker-ansible-deploy](https://github.com/spantaleev/matrix-docker-ansible-deploy/blob/ddbbd42718b15172cdf409f2c1050362d42c3151/roles/custom/matrix-bot-matrix-registration-bot/defaults/main.yml#L11). 67 | -------------------------------------------------------------------------------- /docs/troubleshooting.md: -------------------------------------------------------------------------------- 1 | # Troubleshooting 2 | 3 | This document tries to help you with common problems. If you would rather ask a human or this document does not help you 4 | come join [#matrix-registration-bot:hyteck.de](https://matrix.to/#/#matrix-registration-bot:hyteck.de). If you believe 5 | that you found a bug please report it on [GitHub](https://github.com/moan0s/matrix-registration-bot/issues). 6 | 7 | ## Bot does not accept invite 8 | 9 | This indicates that the bot is not working properly. Check if the bot is still running and what the logs say. Usually 10 | this is a misconfiguration of the bot in `config.yml`. 11 | 12 | ## Bot accepts invite but does not answer 13 | 14 | Check if the chat with the bot is encrypted. The bot does not yet support encryption, therefore it will not work in such 15 | a room. You can circumvent this problem by creating an unencrypted room and invite the bot to it. 16 | 17 | ## ERROR:The token does not seem to fit the saved session. 18 | 19 | This can happen if you change the bot user. If this is the case, deleting the session.txt and restarting the bot will help. 20 | The session.txt is located in the working directory of the bot. For the docker deployment you can run the following 21 | command (make sure to adjust the container name if it is not `matrix-bot-matrix-registration-bot`). 22 | 23 | ```bash 24 | docker exec -it matrix-bot-matrix-registration-bot rm /data/session.txt 25 | ``` 26 | 27 | -------------------------------------------------------------------------------- /example_config.yml: -------------------------------------------------------------------------------- 1 | bot: 2 | server: "https://synapse.example.com" 3 | username: "registerbot" 4 | access_token: "verysecret" 5 | prefix: "" 6 | api: 7 | # API endpoint of the registration tokens 8 | base_url: 'https://synapse.example.com' 9 | endpoint: '/_synapse/admin/v1/registration_tokens' 10 | # Access token of an administrator on the server 11 | token: "supersecret" 12 | 13 | -------------------------------------------------------------------------------- /logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/moan0s/matrix-registration-bot/600ef746b129adfaf7a2f1a21cdb81732cfc222c/logo.png -------------------------------------------------------------------------------- /matrix_registration_bot/__init__.py: -------------------------------------------------------------------------------- 1 | __version__ = "1.3.0" 2 | __author__ = 'Julian-Samuel Gebühr' -------------------------------------------------------------------------------- /matrix_registration_bot/bot.py: -------------------------------------------------------------------------------- 1 | import cryptography 2 | import simplematrixbotlib as botlib 3 | import matrix_registration_bot 4 | from matrix_registration_bot.registration_api import RegistrationAPI 5 | from matrix_registration_bot.config import Config 6 | import logging 7 | import argparse 8 | 9 | parser = argparse.ArgumentParser(description='Start the matrix-registration-bot.') 10 | 11 | parser.add_argument('--config', default=None, help='Specify a configuration file to use') 12 | 13 | args = parser.parse_args() 14 | if args.config is None: 15 | config_path = 'config.yml' 16 | else: 17 | config_path = args.config 18 | config = Config(args.config) 19 | 20 | bot_server = config['bot']['server'] 21 | bot_username = config['bot']['username'] 22 | try: 23 | bot_access_token = config['bot']['access_token'] 24 | creds = botlib.Creds(bot_server, 25 | username=bot_username, 26 | access_token=bot_access_token) 27 | except KeyError: 28 | logging.info("Using password based authentication for the bot") 29 | try: 30 | bot_access_password = config['bot']['password'] 31 | except KeyError: 32 | error = "No access token or password for the bot provided" 33 | logging.error(error) 34 | raise KeyError(error) 35 | creds = botlib.Creds(bot_server, 36 | username=bot_username, 37 | password=bot_access_password) 38 | 39 | bot_prefix = config['bot']['prefix'] 40 | 41 | # Load a config file that configures bot behaviour 42 | smbl_config = botlib.Config() 43 | smbl_config.emoji_verify = True 44 | smbl_config.ignore_unverified_devices = True 45 | SIMPLE_MATRIX_BOT_CONFIG_FILE = "config.toml" 46 | try: 47 | smbl_config.load_toml(SIMPLE_MATRIX_BOT_CONFIG_FILE) 48 | logging.info(f"Loaded the simple-matrix-bot config file {SIMPLE_MATRIX_BOT_CONFIG_FILE}") 49 | except FileNotFoundError: 50 | logging.info(f"No simple-matrix-bot config file found. Creating {SIMPLE_MATRIX_BOT_CONFIG_FILE}") 51 | smbl_config.save_toml(SIMPLE_MATRIX_BOT_CONFIG_FILE) 52 | 53 | bot = botlib.Bot(creds, smbl_config) 54 | 55 | try: 56 | api_base_url = config['api']['base_url'] 57 | except KeyError: 58 | api_base_url = bot_server 59 | 60 | """ 61 | Here we get the configured credentials for the admin API. 62 | We first check if an API token is set, if not we try if there are credentials set in the api section of the config 63 | and after that we use the credentials provided for the bot. Users are encouraged to use the last option, but we allow 64 | to overwrite this. 65 | """ 66 | try: 67 | api_token = config['api']['token'] 68 | api = RegistrationAPI(api_base_url, api_token) 69 | logging.info("Using API token from api section of config") 70 | except KeyError: 71 | try: 72 | admin_username = config['api']['username'] 73 | admin_password = config['api']['password'] 74 | logging.info("Using username/password from api section of config") 75 | except KeyError: 76 | admin_username = config['bot']['username'] 77 | admin_password = config['bot']['password'] 78 | logging.info("Using username/password from bot section of config") 79 | # The API interface will obtain an API token by itself 80 | api = RegistrationAPI(api_base_url, username=admin_username, password=admin_password) 81 | 82 | help_string = ( 83 | f"""**[Matrix Registration Bot](https://github.com/moan0s/matrix-registration-bot/)** {matrix_registration_bot.__version__} 84 | You can always ask for help in 85 | [#matrix-registration-bot:hyteck.de](https://matrix.to/#/#matrix-registration-bot:hyteck.de)! 86 | 87 | **Unrestricted commands** 88 | 89 | * `{bot_prefix}help`: Shows this help 90 | 91 | **Restricted commands** 92 | 93 | * `{bot_prefix}list`: Lists all registration tokens 94 | * `{bot_prefix}show `: Shows token details in human-readable format 95 | * `{bot_prefix}create`: Creates a token that that is valid for one registration for seven days 96 | * `{bot_prefix}delete ` Deletes the specified token(s) 97 | * `{bot_prefix}delete-all` Deletes all tokens 98 | * `{bot_prefix}allow @user:example.com` Allows the specified user (or a user matching a regex pattern) to use restricted commands 99 | * `{bot_prefix}disallow @user:example.com` Stops a specified user (or a user matching a regex pattern) from using restricted commands 100 | """) 101 | 102 | 103 | def allowed_required(func): 104 | async def wrapper(match, room, *args, **kwargs): 105 | if match.is_from_allowed_user(): 106 | await func(match, room, *args, **kwargs) 107 | else: 108 | logging.info(f"{match.event.sender} tried to execute {func}") 109 | await bot.api.send_markdown_message( 110 | room.room_id, 111 | f'You are not allowed to do that (restricted command). Ask someone to allow you (send `help` to find ' 112 | f'out more)') 113 | 114 | return wrapper 115 | 116 | 117 | @allowed_required 118 | async def action_list(match, room): 119 | logging.info(f"{match.event.sender} listed all tokens") 120 | try: 121 | token_list = await api.list_tokens() 122 | except ConnectionError as e: 123 | logging.warning(f"Error while trying to list all tokens: {e}") 124 | await error_handler(room, e) 125 | return 126 | if len(token_list) < 10: 127 | message = "\n".join([RegistrationAPI.token_to_markdown(token) for token in token_list]) 128 | else: 129 | tokens_as_string = [RegistrationAPI.token_to_short_markdown(token) for token in token_list] 130 | message = f"All tokens: {', '.join(tokens_as_string)}" 131 | await bot.api.send_markdown_message(room.room_id, message) 132 | 133 | 134 | @allowed_required 135 | async def action_create_token(match, room): 136 | try: 137 | token = await api.create_token() 138 | logging.info(f"{match.event.sender} created token {token}") 139 | await bot.api.send_markdown_message(room.room_id, f"{RegistrationAPI.token_to_markdown(token)}") 140 | except (ConnectionError, PermissionError, FileNotFoundError) as e: 141 | logging.warning(f"Error while trying to create a token: {e}") 142 | await error_handler(room, e) 143 | 144 | 145 | @allowed_required 146 | async def action_delete(match, room): 147 | deleted_tokens = [] 148 | logging.info(f"{match.event.sender} tries to delete {match.args()}") 149 | if not len(match.args()) > 0: 150 | await bot.api.send_markdown_message(room.room_id, "You must give a token!") 151 | for token in match.args(): 152 | token = token.strip() 153 | try: 154 | deleted_tokens.append(await api.delete_token(token)) 155 | except ValueError as e: 156 | logging.info(f"Token {token} given by {match.event.sender} to delete was not in correct format") 157 | await error_handler(room, e) 158 | except FileNotFoundError as e: 159 | logging.info(f"Token {token} given by {match.event.sender} to delete was not found") 160 | await error_handler(room, e) 161 | except ConnectionError as e: 162 | logging.warning(f"Error: {e} while trying to get a token") 163 | await error_handler(room, e) 164 | logging.info(f"{match.event.sender} deleted token {deleted_tokens}") 165 | await send_info_on_deleted_token(room, deleted_tokens) 166 | 167 | 168 | @allowed_required 169 | async def action_delete_all(match, room): 170 | deleted_tokens = await api.delete_all_token() 171 | logging.info(f"{match.event.sender} deleted all tokens") 172 | await send_info_on_deleted_token(room, deleted_tokens) 173 | 174 | 175 | @allowed_required 176 | async def action_show(match, room): 177 | tokens_info = [] 178 | logging.info(f"{match.event.sender} tries to show {match.args()}") 179 | if not len(match.args()) > 0: 180 | await bot.api.send_markdown_message(room.room_id, "You must give a token!") 181 | return 182 | for token in match.args(): 183 | token = token.strip() 184 | try: 185 | token_info = await api.get_token(token) 186 | logging.info(f"Showing {token} to {match.event.sender}") 187 | tokens_info.append(RegistrationAPI.token_to_markdown(token_info)) 188 | except ConnectionError as e: 189 | logging.warning(f"Error while trying to get a token: {e}") 190 | await error_handler(room, e) 191 | except FileNotFoundError as e: 192 | logging.info(f"Token {token} given by {match.event.sender} to show was not found") 193 | await error_handler(room, e) 194 | except TypeError as e: 195 | logging.info(f"Token {token} given by {match.event.sender} to show was not in correct format") 196 | await error_handler(room, e) 197 | if len(tokens_info) > 0: 198 | await bot.api.send_markdown_message(room.room_id, "\n".join(tokens_info)) 199 | 200 | 201 | @allowed_required 202 | async def action_allow(match, room): 203 | sender = match.event.sender 204 | bot.config.add_allowlist(set(match.args()).union(set([sender,]))) 205 | bot.config.save_toml("config.toml") 206 | logging.info(f"{match.event.sender} allowed {set(match.args())} (if valid)") 207 | await bot.api.send_text_message( 208 | room.room_id, 209 | f'allowing {", ".join(arg for arg in match.args())} (if valid)') 210 | 211 | 212 | @allowed_required 213 | async def action_disallow(match, room): 214 | bot.config.remove_allowlist(set(match.args())) 215 | bot.config.save_toml("config.toml") 216 | logging.info(f"{match.event.sender} disallowed {set(match.args())} (if valid)") 217 | await bot.api.send_text_message( 218 | room.room_id, 219 | f'disallowing {", ".join(arg for arg in match.args())} (if valid)') 220 | 221 | @bot.listener.on_message_event 222 | async def token_actions(room, message): 223 | match = botlib.MessageMatch(room, message, bot, bot_prefix) 224 | 225 | if match.is_not_from_this_bot() and match.prefix(): 226 | # Unrestricted commands 227 | if match.contains("help"): 228 | """The help command should be accessible even to users that are not allowed""" 229 | logging.info(f"{match.event.sender} viewed the help") 230 | await bot.api.send_markdown_message(room.room_id, help_string) 231 | 232 | # Restricted commands 233 | if match.command("list"): 234 | await action_list(match, room) 235 | elif match.command("create"): 236 | await action_create_token(match, room) 237 | elif match.command("delete-all"): 238 | await action_delete_all(match, room) 239 | elif match.command("delete"): 240 | await action_delete(match, room) 241 | elif match.command("show"): 242 | await action_show(match, room) 243 | elif match.command("allow"): 244 | await action_allow(match, room) 245 | elif match.command("disallow"): 246 | await action_disallow(match, room) 247 | 248 | 249 | async def send_info_on_deleted_token(room, token_list): 250 | if len(token_list) > 0: 251 | message = f"Deleted the following token(s): " 252 | tokens_as_string = [RegistrationAPI.token_to_short_markdown(token) for token in token_list] 253 | message += ", ".join(tokens_as_string) 254 | else: 255 | message = "No token deleted" 256 | await bot.api.send_markdown_message(room.room_id, message) 257 | 258 | 259 | async def error_handler(room, error): 260 | message = f"The bot encountered the following error:\n" 261 | message += error.args[0] 262 | await bot.api.send_markdown_message(room.room_id, message) 263 | 264 | 265 | def run_bot(): 266 | try: 267 | bot.run() 268 | except cryptography.fernet.InvalidToken: 269 | logging.error("The token does not seem to fit the saved session. this can happen if you change the bot user." 270 | "If this is the case, deleting the session.txt and restarting the bot might help") 271 | exit(1) 272 | 273 | 274 | if __name__ == "__main__": 275 | run_bot() 276 | -------------------------------------------------------------------------------- /matrix_registration_bot/config.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import yaml 3 | from os import environ 4 | 5 | 6 | class Config(dict): 7 | """A class to manage the bot's configuration""" 8 | 9 | keys = ["BOT_SERVER", "BOT_USERNAME", "BOT_PASSWORD", "BOT_ACCESS_TOKEN", 10 | "API_BASE_URL", "API_TOKEN", 11 | "LOGGING_LEVEL"] 12 | 13 | def __init__(self, config_path=None): 14 | logging.basicConfig(format='%(asctime)s %(levelname)s:%(message)s', level=logging.DEBUG) 15 | 16 | """ 17 | The config is generated via 4 different paths from lowest to highest priority 18 | 4. a config.yml in the working directory of the bot 19 | 3. a file in yml format specified vie --config 20 | 2. a file in yml format specified via the CONFIG_PATH environment variable 21 | 1. config values specified via their name as environment variable 22 | """ 23 | # Try to find config via environment variable 24 | try: 25 | config_path = environ["CONFIG_PATH"] 26 | except KeyError: 27 | logging.debug(f"No config file set via the environment variable") 28 | pass 29 | if config_path is None: 30 | logging.debug(f"No config file set via the --config option, defaulting to config.yml in working directory") 31 | config_path = "config.yml" 32 | logging.info(f"Tying to load bot configuration from {config_path}") 33 | try: 34 | with open(config_path, 'r') as file: 35 | self.extend_by_dict(yaml.safe_load(file)) 36 | except FileNotFoundError: 37 | logging.error(f"Cold not find bot configuration at {config_path}") 38 | 39 | 40 | """ 41 | This maps all self.keys (e.g. "LOGGING_LEVEL") that are in the environment to the corresponding config value 42 | e.g. self["logging"]["level"]. Does not support more than 2 level 43 | """ 44 | for key in self.keys: 45 | scope, k = [x.lower() for x in key.split("_", maxsplit=1)] 46 | try: 47 | environ[key] 48 | except KeyError: 49 | logging.debug(f"{key} not set in environment") 50 | continue 51 | try: 52 | self[scope] 53 | except KeyError: 54 | self[scope] = {} 55 | self[scope][k] = environ[key] 56 | logging.debug(f"{key} set via environment") 57 | 58 | try: 59 | self["logging"] 60 | except KeyError: 61 | self["logging"] = dict() 62 | self["logging"]["level"] = "error" 63 | 64 | """Set the logging level according to config""" 65 | if self["logging"]['level'] in ["debug", "DEBUG"]: 66 | logging_level = logging.DEBUG 67 | elif self["logging"]['level'] in ["error", "ERROR"]: 68 | logging_level = logging.ERROR 69 | else: 70 | logging_level = logging.INFO 71 | logging.getLogger().setLevel(logging_level) 72 | 73 | try: 74 | self["bot"]["prefix"] 75 | except KeyError: 76 | self["bot"]["prefix"] = "" 77 | 78 | def extend_by_dict(self, data): 79 | for key in data: 80 | self[key] = data[key] 81 | -------------------------------------------------------------------------------- /matrix_registration_bot/registration_api.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import re 3 | from datetime import datetime, timedelta 4 | import aiohttp 5 | 6 | 7 | class RegistrationAPI: 8 | def __init__(self, base_url: str, api_token: str = "", username: str = "", password: str = "", 9 | device_ID: str = "matrix-registration-bot"): 10 | self.base_url = base_url 11 | self.api_token = api_token 12 | self.username = username 13 | self.password = password 14 | self.device_ID = device_ID 15 | self.headers = {"Authorization": f"Bearer {api_token}"} 16 | self.session = None 17 | self.registration_token_endpoint = '/_synapse/admin/v1/registration_tokens' 18 | 19 | def __str__(self): 20 | return f"API Connection to {self.base_url}" 21 | 22 | async def ensure_api_token(self): 23 | if len(self.api_token) == 0: 24 | assert len(self.password) > 0 and len(self.username) > 0 25 | logging.info("Fetching a new API token using user/password combination of the bot") 26 | self.api_token = await self.get_api_token(self.username, self.password, self.device_ID) 27 | self.headers = {"Authorization": f"Bearer {self.api_token}"} 28 | 29 | async def ensure_session(self): 30 | if self.session is None: 31 | self.session = aiohttp.ClientSession(self.base_url) 32 | 33 | async def ensure_api(self): 34 | await self.ensure_session() 35 | logging.debug(f"Session: {self.session}") 36 | await self.ensure_api_token() 37 | 38 | async def get_api_token(self, username, password, device_ID): 39 | logging.debug("Getting api token...") 40 | await self.ensure_session() 41 | data = {"identifier": {"type": "m.id.user", "user": f"{username}"}, 42 | "password": f"{password}", 43 | "type": "m.login.password", 44 | "device_id": f"{device_ID}"} 45 | async with self.session.post(f"/_matrix/client/r0/login", json=data) as r: 46 | self.check_response(r) 47 | response = await r.json() 48 | return response["access_token"] 49 | 50 | @staticmethod 51 | def verbose_response(r): 52 | return f"The registration api returned `{r.status}: {r.reason}` for {r.method}: {r.url}" 53 | 54 | @staticmethod 55 | def check_response(r): 56 | if r.status == 404: 57 | raise FileNotFoundError("Token not found or API not reachable (404 Not Found)") 58 | elif r.status == 401: 59 | raise PermissionError(RegistrationAPI.verbose_response(r) + 60 | f" Check, that the API access token is correct") 61 | elif r.status != 200: 62 | raise ConnectionError(RegistrationAPI.verbose_response(r)) 63 | 64 | @staticmethod 65 | def token_to_markdown(token_details: dict): 66 | """ 67 | Converts a token to markdown string 68 | 69 | :param token_details: A dictionary containing the token 70 | Example: {'token': '8iB~zWiDU1SC0NT3', 71 | 'uses_allowed': 1, 72 | 'pending': 0, 73 | 'completed': 1, 74 | 'expiry_time': 1642807497388} 75 | :return: a string in markdown format 76 | """ 77 | if token_details['uses_allowed'] is None: 78 | uses_left = "Unlimited" 79 | else: 80 | uses_left = token_details['uses_allowed'] - (token_details['completed'] + token_details['pending']) 81 | if token_details['expiry_time'] is None: 82 | timestamp = "Does not expire" 83 | else: 84 | datetime_obj = datetime.utcfromtimestamp(int(token_details['expiry_time']) / 1000) 85 | timestamp = datetime_obj.strftime("%d.%m.%y %H:%M UTC") 86 | md = (f"""**Token:** `{token_details['token']}` 87 | Expires: {timestamp} 88 | Uses left: {uses_left} 89 | """) 90 | return md 91 | 92 | @staticmethod 93 | def token_to_short_markdown(token_details: dict): 94 | """ 95 | Converts a token to markdown string 96 | 97 | :param token_details: A dictionary containing the token 98 | Example: {'token': '8iB~zWiDU1SC0NT3', 99 | 'uses_allowed': 1, 100 | 'pending': 0, 101 | 'completed': 1, 102 | 'expiry_time': 1642807497388} 103 | :return: a string of only the token value in markdown format 104 | """ 105 | md = f"`{token_details['token']}`" 106 | return md 107 | 108 | @staticmethod 109 | def valid_token_format(token: str): 110 | """ 111 | Checks if a string is a valid token. 112 | 113 | The string is checked against a regex pattern. Due to the restricted nature of the token format, the string is 114 | safe to use when in this format. More information: https://matrix-org.github.io/synapse/latest/usage/administration/admin_api/registration_tokens.html#create-token 115 | :param token: The token value to check. 116 | :return:bool: True if the token is in valid format, else false 117 | """ 118 | if len(token) > 64: 119 | return False 120 | pattern = re.compile("[A-Za-z0-9._~-]*") 121 | match = re.fullmatch(pattern, token) 122 | return match 123 | 124 | async def list_tokens(self): 125 | """ 126 | Gathers a list of all registration tokens 127 | 128 | :return: List of token_details 129 | """ 130 | await self.ensure_api() 131 | async with self.session.get(self.registration_token_endpoint, headers=self.headers) as r: 132 | try: 133 | assert r.status == 200 134 | except AssertionError: 135 | raise ConnectionError(self.verbose_response(r)) 136 | return (await r.json())["registration_tokens"] 137 | 138 | async def get_token(self, token): 139 | """ 140 | Gets token 141 | 142 | :return: token_details as dict 143 | """ 144 | await self.ensure_api() 145 | if self.valid_token_format(token): 146 | async with self.session.get(self.registration_token_endpoint + f"/{token}", headers=self.headers) as r: 147 | self.check_response(r) 148 | return await r.json() 149 | else: 150 | raise TypeError("Token is not a valid format!") 151 | 152 | async def delete_all_token(self): 153 | """ 154 | Deletes all token 155 | 156 | :return: List of deleted token 157 | """ 158 | await self.ensure_api() 159 | all_tokens = await self.list_tokens() 160 | for token in all_tokens: 161 | await self.delete_token(token["token"]) 162 | return all_tokens 163 | 164 | async def delete_token(self, token: str): 165 | """ 166 | Deletes the given token 167 | 168 | :param token: 169 | :return: The token_details that is deleted as dict 170 | """ 171 | await self.ensure_api() 172 | if self.valid_token_format(token): 173 | r = await self.session.get(f"{self.registration_token_endpoint}/{token}", headers=self.headers) 174 | self.check_response(r) 175 | token_details = await r.json() 176 | async with self.session.delete(f"{self.registration_token_endpoint}/{token}", headers=self.headers) as r: 177 | self.check_response(r) 178 | return token_details 179 | else: 180 | raise ValueError(f"Token {token} is not a valid format!") 181 | 182 | async def create_token(self, expiry_days=7): 183 | """ 184 | Create a token for registering a user 185 | 186 | expire_days:int 187 | Determines how long the token will be valid (in days) 188 | :return: token_details 189 | """ 190 | await self.ensure_api() 191 | expiry_time = int(datetime.timestamp(datetime.now() + timedelta(days=expiry_days)) * 1000) 192 | data = '{"uses_allowed": 1, "expiry_time": ' + str(expiry_time) + '}' 193 | async with self.session.post(f"{self.registration_token_endpoint}/new", data=data, headers=self.headers) as r: 194 | self.check_response(r) 195 | return await r.json() 196 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = ["setuptools", "wheel"] 3 | build-backend = "setuptools.build_meta" 4 | 5 | 6 | 7 | [project] 8 | name = "matrix-registration-bot" 9 | description = "A bot to manage user registration tokens on a matrix server." 10 | keywords = ["matrix", "registration", "bot", "user", "registration", "API" ] 11 | license = {text = "AGPL-3.0-or-later"} 12 | classifiers = [ 13 | "Development Status :: 5 - Production/Stable", 14 | "Intended Audience :: System Administrators", 15 | "License :: OSI Approved :: GNU Affero General Public License v3", 16 | "Operating System :: OS Independent", 17 | "Programming Language :: Python :: 3.9", 18 | "Programming Language :: Python :: 3.10", 19 | ] 20 | dependencies = [ 21 | "simplematrixbotlib>=2.7.3,<3.0.0", 22 | "pyyaml", 23 | "matrix-nio[e2e]", 24 | "aiohttp[speedups]", 25 | ] 26 | dynamic = ["version", "readme"] 27 | 28 | [project.scripts] 29 | matrix-registration-bot = "matrix_registration_bot.bot:run_bot" 30 | 31 | 32 | [tool.setuptools.packages] 33 | find = {} 34 | 35 | [tool.setuptools.dynamic] 36 | version = {attr = "matrix_registration_bot.__version__"} 37 | readme = {file = "README.rst"} 38 | 39 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | simplematrixbotlib>=2.7.3,<3.0.0 2 | matrix-nio[e2e] 3 | pyyaml 4 | aiohttp[speedups] 5 | pytest 6 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup 2 | 3 | setup() 4 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/moan0s/matrix-registration-bot/600ef746b129adfaf7a2f1a21cdb81732cfc222c/tests/__init__.py -------------------------------------------------------------------------------- /tests/test_registration_api.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | from matrix_registration_bot.registration_api import RegistrationAPI 3 | 4 | valid_tokens = ["TrwUI5zHm~Gn3M9Am", "gpWrPaFrbuP73A6N", "dada", "a", "1", "J_2NGPksUSbST1cp", 5 | "uERKLWlzIDhrVxQCSGLSmBdMEnKnnaOCNBUawgLgUyjjqnaIBFmMkJQATTpqhbXX"] 6 | invalid_tokens = ["dajaj/aeofjj", "", "<script>alert('1');</script>", 7 | "ɐuƃɐɯ", "register!", "uERKLWlzIDhrVxQCSGLSmBdMEnKnnaOCNBUawgLgUyjjqnaIBFmMkJQXAT65chars"] 8 | 9 | 10 | def test_valid_token_format(): 11 | for token in valid_tokens: 12 | if not RegistrationAPI.valid_token_format(token): 13 | raise AssertionError(f"Falsely said {token} is a invalid token") 14 | for token in invalid_tokens: 15 | if RegistrationAPI.valid_token_format(token): 16 | raise AssertionError(f"Falsely said {token} is a valid token") 17 | --------------------------------------------------------------------------------