diff --git a/.eslintrc.json b/.eslintrc.json new file mode 100644 index 0000000..cdf57c6 --- /dev/null +++ b/.eslintrc.json @@ -0,0 +1,114 @@ +{ + "root": true, + "parser": "@typescript-eslint/parser", + "plugins": [ + "@typescript-eslint" + ], + "parserOptions": { + "project": [ + "./tsconfig.json", + "./tsconfig.test.json", + "./tsconfig.frontend.json" + ] + }, + "extends": [ + "eslint:recommended", + "plugin:@typescript-eslint/recommended" + ], + "rules": { + "indent": [ + "error", + 4, + { + "SwitchCase": 1 + } + ], + "no-trailing-spaces": "error", + "max-len": [ + "error", + { + "code": 120, + "ignoreStrings": true, + "ignoreTemplateLiterals": true, + "ignoreRegExpLiterals": true + } + ], + "semi": "off", + "@typescript-eslint/semi": [ + "error" + ], + "no-extra-semi": "error", + "eol-last": "error", + "comma-dangle": "off", + "@typescript-eslint/comma-dangle": [ + "error", + { + "arrays": "always-multiline", + "objects": "always-multiline", + "imports": "always-multiline", + "exports": "always-multiline", + "functions": "always-multiline", + "enums": "always-multiline", + "generics": "always-multiline", + "tuples": "always-multiline" + } + ], + "no-extra-parens": "off", + "@typescript-eslint/no-extra-parens": [ + "error" + ], + "no-nested-ternary": "error", + "@typescript-eslint/no-inferrable-types": "off", + "@typescript-eslint/explicit-module-boundary-types": "error", + "@typescript-eslint/no-unnecessary-condition": "error", + "@typescript-eslint/no-unused-vars": [ + "error", + { + "argsIgnorePattern": "^_" + } + ], + "@typescript-eslint/no-non-null-assertion": "error", + "no-useless-return": "error", + "no-useless-constructor": "off", + "@typescript-eslint/no-useless-constructor": [ + "error" + ], + "no-return-await": "off", + "@typescript-eslint/return-await": [ + "error", + "always" + ], + "@typescript-eslint/explicit-member-accessibility": [ + "error", + { + "accessibility": "explicit" + } + ], + "@typescript-eslint/no-floating-promises": "error" + }, + "ignorePatterns": [ + "jest.config.js", + "webpack.config.js", + "dist/**/*", + "public/**/*", + "config/**/*" + ], + "overrides": [ + { + "files": [ + "test/**/*" + ], + "rules": { + "max-len": [ + "error", + { + "code": 120, + "ignoreTemplateLiterals": true, + "ignoreRegExpLiterals": true, + "ignoreStrings": true + } + ] + } + } + ] +} diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..be3f7b2 --- /dev/null +++ b/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/assets/config.json b/assets/config.json index d0d6024..dca23d4 100644 --- a/assets/config.json +++ b/assets/config.json @@ -1,11 +1,11 @@ { "bundles": { - "app": "js/app.js", - "register": "js/register.js", + "app": "ts/app.ts", + "register": "ts/register.ts", "layout": "sass/layout.scss", "error": "sass/error.scss", "logo": "img/logo.svg", "logo_png": "img/logox128.png", "logo_png_xxl": "img/logox1024.png" } -} \ No newline at end of file +} diff --git a/assets/img/logo.svg b/assets/img/logo.svg index 0e7a4fa..3a3b8d1 100644 --- a/assets/img/logo.svg +++ b/assets/img/logo.svg @@ -7,21 +7,24 @@ xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" - inkscape:version="1.0 (4035a4fb49, 2020-05-01)" - sodipodi:docname="logo.svg" - id="svg4" - version="1.1" - class="feather feather-key" - stroke-linejoin="round" - stroke-linecap="round" - stroke-width="2" - stroke="currentColor" - fill="none" - viewBox="0 0 24 24" + width="24" height="24" - width="24"> + viewBox="0 0 24 24" + fill="none" + stroke="currentColor" + stroke-width="2" + stroke-linecap="round" + stroke-linejoin="round" + class="feather feather-inbox" + version="1.1" + id="svg6" + sodipodi:docname="logo.svg" + inkscape:version="1.0.1 (3bc2e813f5, 2020-09-07)" + inkscape:export-filename="/r/arisu/dev/rainbox.email/assets/img/logox128.png" + inkscape:export-xdpi="512" + inkscape:export-ydpi="512"> + id="metadata12"> @@ -33,29 +36,141 @@ + id="defs10" /> + borderopacity="1" + objecttolerance="10" + gridtolerance="10" + guidetolerance="10" + inkscape:pageopacity="0" + inkscape:pageshadow="2" + inkscape:window-width="2560" + inkscape:window-height="1381" + id="namedview8" + showgrid="false" + inkscape:zoom="45.254834" + inkscape:cx="10.500648" + inkscape:cy="8.784376" + inkscape:window-x="0" + inkscape:window-y="32" + inkscape:window-maximized="1" + inkscape:current-layer="g862" /> + id="path1120" + style="display:inline;fill:#ffffff;stroke:#80e1ff;stroke-opacity:1;fill-opacity:1;stroke-width:1;stroke-miterlimit:4;stroke-dasharray:none" + d="m 22,12 h -6 l -2,3 H 10 L 8,12 H 2 M 22,12 18.55,5.11 C 18.21227,4.4303423 17.518944,4.0004027 16.76,4 H 7.24 C 6.481056,4.0004027 5.78773,4.4303423 5.45,5.11 L 2,12" /> + + + + + + + + + + + diff --git a/assets/img/logox1024.png b/assets/img/logox1024.png index 8defbac..ba4b746 100644 Binary files a/assets/img/logox1024.png and b/assets/img/logox1024.png differ diff --git a/assets/img/logox128.png b/assets/img/logox128.png index 3508f4a..27aaac7 100644 Binary files a/assets/img/logox128.png and b/assets/img/logox128.png differ diff --git a/assets/js/copyable_text.js b/assets/js/copyable_text.js deleted file mode 100644 index 6501a1a..0000000 --- a/assets/js/copyable_text.js +++ /dev/null @@ -1,12 +0,0 @@ -document.addEventListener('DOMContentLoaded', () => { - document.querySelectorAll('.copyable-text').forEach(el => { - const contentEl = el.querySelector('.content'); - contentEl.addEventListener('click', () => { - window.getSelection().selectAllChildren(contentEl); - }); - el.querySelector('.copy-button').addEventListener('click', () => { - window.getSelection().selectAllChildren(contentEl); - document.execCommand('copy'); - }); - }); -}); \ No newline at end of file diff --git a/assets/js/forms.js b/assets/js/forms.js deleted file mode 100644 index dd3f184..0000000 --- a/assets/js/forms.js +++ /dev/null @@ -1,29 +0,0 @@ -// For labels to update their state (css selectors based on the value attribute) -document.addEventListener('DOMContentLoaded', () => { - document.querySelectorAll('input').forEach(el => { - if (el.type !== 'checkbox') { - el.setAttribute('value', el.value); - el.addEventListener('change', () => { - el.setAttribute('value', el.value); - }); - } - }); -}); - -window.applyFormMessages = function (formElement, messages) { - for (const fieldName of Object.keys(messages)) { - const field = formElement.querySelector('#field-' + fieldName); - let parent = field.parentElement; - while (parent && !parent.classList.contains('form-field')) parent = parent.parentElement; - - if (field) { - let err = field.querySelector('.error'); - if (!err) { - err = document.createElement('div'); - err.classList.add('error'); - parent.insertBefore(err, parent.querySelector('.hint') || parent); - } - err.innerHTML = ` ${messages[fieldName].message}`; - } - } -} \ No newline at end of file diff --git a/assets/js/main_menu.js b/assets/js/main_menu.js deleted file mode 100644 index f2a89da..0000000 --- a/assets/js/main_menu.js +++ /dev/null @@ -1,17 +0,0 @@ -document.addEventListener('DOMContentLoaded', () => { - const menuButton = document.getElementById('menu-button'); - const mainMenu = document.getElementById('main-menu'); - - menuButton.addEventListener('click', (e) => { - e.stopPropagation(); - mainMenu.classList.toggle('open'); - }); - - mainMenu.addEventListener('click', (e) => { - e.stopPropagation(); - }); - - document.addEventListener('click', () => { - mainMenu.classList.remove('open'); - }); -}); \ No newline at end of file diff --git a/assets/js/register.js b/assets/js/register.js deleted file mode 100644 index 2eeb15a..0000000 --- a/assets/js/register.js +++ /dev/null @@ -1,27 +0,0 @@ -document.addEventListener('DOMContentLoaded', () => { - const createEmailAddress = document.getElementById('field-create_email'); - const username = document.getElementById('field-username'); - const email_username = document.getElementById('email_username'); - const domain = document.getElementById('field-domain'); - const recovery_email = document.getElementById('field-recovery_email'); - const recovery_email_label = recovery_email.parentElement.querySelector('.hint'); - - function updateForm() { - if (createEmailAddress.checked) { - recovery_email.removeAttribute('required'); - recovery_email_label.style.display = 'block'; - domain.disabled = false; - } else { - recovery_email.setAttribute('required', 'required'); - recovery_email_label.style.display = 'none'; - domain.disabled = true; - } - username.value = username.value.toLowerCase(); - email_username.innerText = username.value + '@'; - } - - createEmailAddress.addEventListener('change', updateForm); - username.addEventListener('change', updateForm); - username.addEventListener('keyup', updateForm); - updateForm(); -}); \ No newline at end of file diff --git a/assets/sass/_vars.scss b/assets/sass/_vars.scss index c7b0e18..eafa072 100644 --- a/assets/sass/_vars.scss +++ b/assets/sass/_vars.scss @@ -1,6 +1,6 @@ $primary: darken(#333333, 2%); $primaryForeground: #f0f0f0; -$secondary: lighten(#004698, 10%); +$secondary: #00c3ff; $secondaryForeground: $primaryForeground; $backgroundColor: darken($primary, 4%); @@ -9,6 +9,7 @@ $defaultTextColor: #ffffff; $headerBackground: darken($primary, 7.5%); $footerBackground: lighten($headerBackground, 1%); $panelBackground: lighten($headerBackground, 1%); +$inputBackground: darken($panelBackground, 4%); $info: #4499ff; $infoText: darken($info, 42%); @@ -27,4 +28,4 @@ $errorText: darken($error, 30%); $errorColor: desaturate($errorText, 50%); // Responsivity -$menuLayoutSwitchTreshold: 700px; +$mobileThreshold: 632px; diff --git a/assets/sass/app.scss b/assets/sass/app.scss index 673d561..7fcdd85 100644 --- a/assets/sass/app.scss +++ b/assets/sass/app.scss @@ -1,5 +1,11 @@ @import "layout"; +a { + &:hover { + color: lighten($secondary, 30%); + } +} + td.actions { display: flex; flex-direction: row; @@ -24,3 +30,77 @@ td.actions { } } } + +body > header { + background: transparent; + line-height: 16px; + + @include container; + padding-top: 8px; + padding-bottom: 8px; + align-items: center; + + @media (max-width: $mobileThreshold) { + padding: 0; + } + + .logo { + display: flex; + flex-direction: row; + align-items: center; + max-width: 148px; + padding: 8px; + + font-size: 18px; + line-height: 18px; + + > img { + margin: 0 8px 0 0; + width: initial; + height: 48px; + flex-shrink: 0; + } + } + + nav { + ul { + li { + margin-left: 8px; + + a, button { + display: flex; + flex-direction: row; + align-items: center; + height: auto; + padding: 8px; + + border-radius: 3px; + + .feather { + --icon-size: 16px; + } + + .tip { + position: static; + display: block; + visibility: visible; + height: auto; + padding: 0 0 0 4px; + transform: none; + color: inherit; + + opacity: 1; + background: transparent; + text-transform: uppercase; + font-size: 16px; + line-height: 16px; + } + } + } + } + } +} + +body > footer { + background: transparent; +} diff --git a/assets/sass/layout.scss b/assets/sass/layout.scss index eb52dc4..142a022 100644 --- a/assets/sass/layout.scss +++ b/assets/sass/layout.scss @@ -49,6 +49,11 @@ body { text-transform: initial; font-weight: initial; + + &.top { + top: auto; + bottom: calc(100% + 8px); + } } &:hover, &:active { @@ -61,7 +66,8 @@ body { } } -header { +body > header { + z-index: 50; display: flex; flex-direction: row; justify-content: space-between; @@ -101,6 +107,7 @@ header { font-size: 20px; li { + position: relative; list-style: none; a, button { @@ -140,6 +147,34 @@ header { align-items: center; padding: 0; } + + &.auth-user { + img { + width: 48px; + height: 48px; + border-radius: 3px; + margin-right: 8px; + } + } + + .dropdown { + position: absolute; + z-index: -1; + top: 100%; + right: 0; + + white-space: nowrap; + background: $headerBackground; + border-radius: 0 0 3px 3px; + + a { + padding: 0 8px; + } + } + + &:hover .dropdown { + display: block; + } } } @@ -148,7 +183,7 @@ header { } } - @media (max-width: $menuLayoutSwitchTreshold) { + @media (max-width: $mobileThreshold) { flex-direction: row-reverse; .logo { @@ -177,7 +212,7 @@ header { } } - ul { + > ul { flex-direction: column; position: absolute; z-index: 10; @@ -200,12 +235,18 @@ header { font-weight: inherit; } } + + .dropdown { + position: initial; + display: block; + padding-left: 32px; + } } } } } - @media (min-width: $menuLayoutSwitchTreshold) { + @media (min-width: $mobileThreshold) { nav ul li { a, button, .button { @include tip; @@ -233,7 +274,7 @@ footer { main { flex: 1; - padding: 8px; + padding: 8px 0; button, .button { @include tip; @@ -297,7 +338,7 @@ a { text-decoration: none; &:hover { - color: lighten($secondary, 5%); + color: lighten($secondary, 10%); } .feather.feather-external-link { @@ -312,11 +353,27 @@ form { text-align: center; .form-field { - position: relative; display: flex; flex-direction: column; margin: 16px auto; + .control { + position: relative; + background: $inputBackground; + border-radius: 5px; + } + + .feather.icon { + position: absolute; + top: 50%; + right: 8px; + transform: translateY(-50%); + z-index: 0; + + --icon-size: 24px; + opacity: 0.75; + } + label { position: absolute; left: 8px; @@ -341,11 +398,11 @@ form { } } - input, select, .input-group { + input, select, textarea, .input-group { + z-index: 1; border: 0; color: $defaultTextColor; - background: lighten($panelBackground, 4%); - border-radius: 5px; + background: transparent; font-size: 16px; &:focus, &:not([value=""]), &[type="file"] { @@ -356,7 +413,7 @@ form { } } - input, select, .form-display { + input, select, textarea, .form-display { display: block; padding: 32px 8px 8px 8px; width: 100%; @@ -387,30 +444,48 @@ form { } } + textarea { + resize: vertical; + min-height: 100px; + font-family: inherit; + } + input[type=color] { height: calc(32px + 8px + 32px); } &.inline { + display: flex; flex-direction: row; - input[type=checkbox] { - text-align: left; - width: min-content; - height: min-content; + .control { + display: flex; + flex-direction: row; + align-items: center; + flex-grow: 1; - & ~ label { - position: static; - display: inline; - padding-left: 8px; - font-size: 16px; + input[type=checkbox] { + width: min-content; + height: min-content; + margin: 8px; + text-align: left; + + & ~ label { + position: static; + flex-grow: 1; + display: inline; + padding: 8px; + + font-size: 16px; + text-align: left; + } } } } .input-group { display: flex; - flex-shrink: 1; + flex-grow: 1; flex-direction: row; div { @@ -419,19 +494,9 @@ form { input { width: 100%; - margin-top: 24px; - padding-top: 8px; border: 0; background: transparent; } - - > input + * { - position: absolute; - top: 32px; - right: 28px; - user-select: none; - text-align: right; - } } } } @@ -588,10 +653,22 @@ button, .button { text-align: center; } -.container { +@mixin container { + width: $mobileThreshold; padding: 0 16px; - max-width: 632px; - margin: 0 auto; + + @media (min-width: $mobileThreshold) { + margin: 0 auto; + } + + @media (max-width: $mobileThreshold) { + width: 100%; + padding: 0 8px; + } +} + +.container { + @include container; } .panel { @@ -630,16 +707,26 @@ button, .button { // --- Feather // --- .feather { + display: inline-flex; + justify-content: center; + align-items: center; + flex-shrink: 0; - --icon-size: 24px; width: var(--icon-size); height: var(--icon-size); + + --icon-size: 16px; + font-size: var(--icon-size); stroke: currentColor; stroke-width: 2; stroke-linecap: square; stroke-linejoin: miter; fill: none; vertical-align: middle; + + h1 > &, h2 > &, h3 > & { + --icon-size: 24px; + } } // --- diff --git a/assets/ts/PersistentWebSocket.ts b/assets/ts/PersistentWebSocket.ts new file mode 100644 index 0000000..98e474f --- /dev/null +++ b/assets/ts/PersistentWebSocket.ts @@ -0,0 +1,39 @@ +export default class PersistentWebsocket { + private webSocket?: WebSocket; + + public constructor( + protected readonly url: string, + private readonly handler: MessageHandler, + protected readonly reconnectOnClose: boolean = true, + ) { + } + + public run(): void { + const _webSocket = this.webSocket = new WebSocket(this.url); + this.webSocket.addEventListener('open', () => { + console.debug('Websocket connected'); + }); + this.webSocket.addEventListener('message', (e) => { + this.handler(_webSocket, e); + }); + this.webSocket.addEventListener('error', (e) => { + console.error('Websocket error', e); + }); + this.webSocket.addEventListener('close', (e) => { + this.webSocket = undefined; + console.debug('Websocket closed', e.code, e.reason); + + if (this.reconnectOnClose) { + setTimeout(() => this.run(), 1000); + } + }); + } + + public send(data: string): void { + if (!this.webSocket) throw new Error('WebSocket not connected'); + + this.webSocket.send(data); + } +} + +export type MessageHandler = (webSocket: WebSocket, e: MessageEvent) => void; diff --git a/assets/js/app.js b/assets/ts/app.ts similarity index 68% rename from assets/js/app.js rename to assets/ts/app.ts index 10fa287..8594552 100644 --- a/assets/js/app.js +++ b/assets/ts/app.ts @@ -2,8 +2,9 @@ import './external_links'; import './message_icons'; import './forms'; import './copyable_text'; +import './tooltips-and-dropdowns'; import './main_menu'; +import './font-awesome'; +// css import '../sass/app.scss'; - -console.log('Hello world!'); \ No newline at end of file diff --git a/assets/ts/copyable_text.ts b/assets/ts/copyable_text.ts new file mode 100644 index 0000000..60d58ab --- /dev/null +++ b/assets/ts/copyable_text.ts @@ -0,0 +1,15 @@ +document.addEventListener('DOMContentLoaded', () => { + document.querySelectorAll('.copyable-text').forEach(el => { + const contentEl = el.querySelector('.content'); + const selection = window.getSelection(); + if (contentEl && selection) { + contentEl.addEventListener('click', () => { + selection.selectAllChildren(contentEl); + }); + el.querySelector('.copy-button')?.addEventListener('click', () => { + selection.selectAllChildren(contentEl); + document.execCommand('copy'); + }); + } + }); +}); diff --git a/assets/js/external_links.js b/assets/ts/external_links.ts similarity index 59% rename from assets/js/external_links.js rename to assets/ts/external_links.ts index 7108c4e..bc9ba26 100644 --- a/assets/js/external_links.js +++ b/assets/ts/external_links.ts @@ -2,8 +2,10 @@ import feather from "feather-icons"; document.addEventListener('DOMContentLoaded', () => { document.querySelectorAll('a[target="_blank"]').forEach(el => { - el.innerHTML += ``; + if (!el.classList.contains('no-icon')) { + el.innerHTML += ``; + } }); feather.replace(); -}); \ No newline at end of file +}); diff --git a/assets/ts/font-awesome.ts b/assets/ts/font-awesome.ts new file mode 100644 index 0000000..5ce65ff --- /dev/null +++ b/assets/ts/font-awesome.ts @@ -0,0 +1,4 @@ +import '../../node_modules/@fortawesome/fontawesome-free/scss/fontawesome.scss'; +import '../../node_modules/@fortawesome/fontawesome-free/scss/regular.scss'; +import '../../node_modules/@fortawesome/fontawesome-free/scss/solid.scss'; +import '../../node_modules/@fortawesome/fontawesome-free/scss/brands.scss'; diff --git a/assets/ts/forms.ts b/assets/ts/forms.ts new file mode 100644 index 0000000..d08a65e --- /dev/null +++ b/assets/ts/forms.ts @@ -0,0 +1,43 @@ +/* + * For labels to update their state (css selectors based on the value attribute) + */ +import {ValidationError} from "wms-core/db/Validator"; + +export function updateInputs(): void { + document.querySelectorAll('input, textarea').forEach(el => { + if (!el.dataset.inputSetup) { + el.dataset.inputSetup = 'true'; + if (el.type !== 'checkbox') { + el.setAttribute('value', el.value); + el.addEventListener('change', () => { + el.setAttribute('value', el.value); + }); + } + } + }); +} + +document.addEventListener('DOMContentLoaded', () => { + updateInputs(); +}); + +export function applyFormMessages( + formElement: HTMLFormElement, + messages: { [p: string]: ValidationError }, +): void { + for (const fieldName of Object.keys(messages)) { + const field = formElement.querySelector('#field-' + fieldName); + if (!field) continue; + + let parent = field.parentElement; + while (parent && !parent.classList.contains('form-field')) parent = parent.parentElement; + + let err = field.querySelector('.error'); + if (!err) { + err = document.createElement('div'); + err.classList.add('error'); + parent?.insertBefore(err, parent.querySelector('.hint') || parent); + } + err.innerHTML = ` ${messages[fieldName].message}`; + } +} diff --git a/assets/ts/main_menu.ts b/assets/ts/main_menu.ts new file mode 100644 index 0000000..4e19e40 --- /dev/null +++ b/assets/ts/main_menu.ts @@ -0,0 +1,21 @@ +document.addEventListener('DOMContentLoaded', () => { + const menuButton = document.getElementById('menu-button'); + const mainMenu = document.getElementById('main-menu'); + + if (menuButton) { + menuButton.addEventListener('click', (e) => { + e.stopPropagation(); + mainMenu?.classList.toggle('open'); + }); + } + + if (mainMenu) { + mainMenu.addEventListener('click', (e) => { + e.stopPropagation(); + }); + + document.addEventListener('click', () => { + mainMenu.classList.remove('open'); + }); + } +}); diff --git a/assets/js/message_icons.js b/assets/ts/message_icons.ts similarity index 60% rename from assets/js/message_icons.js rename to assets/ts/message_icons.ts index b625f55..b737de3 100644 --- a/assets/js/message_icons.js +++ b/assets/ts/message_icons.ts @@ -1,21 +1,26 @@ import feather from "feather-icons"; document.addEventListener('DOMContentLoaded', () => { - const messageTypeToIcon = { + const messageTypeToIcon: { [p: string]: string } = { info: 'info', success: 'check', warning: 'alert-triangle', error: 'x-circle', question: 'help-circle', }; - document.querySelectorAll('.message').forEach(el => { - const type = el.dataset['type']; + + document.querySelectorAll('.message').forEach(el => { const icon = el.querySelector('.icon'); + const type = el.dataset['type']; + if (!icon || !type) return; + if (!messageTypeToIcon[type]) throw new Error(`No icon for type ${type}`); + const svgContainer = document.createElement('div'); svgContainer.innerHTML = feather.icons[messageTypeToIcon[type]].toSvg(); - el.insertBefore(svgContainer.firstChild, icon); + + if (svgContainer.firstChild) el.insertBefore(svgContainer.firstChild, icon); icon.remove(); }); feather.replace(); -}); \ No newline at end of file +}); diff --git a/assets/ts/register.ts b/assets/ts/register.ts new file mode 100644 index 0000000..8b916df --- /dev/null +++ b/assets/ts/register.ts @@ -0,0 +1,41 @@ +document.addEventListener('DOMContentLoaded', () => { + const createEmailAddress = document.querySelector('#field-create_email'); + const username = document.querySelector('#field-username'); + const email_username = document.querySelector('#email_username'); + const domain = document.querySelector('#field-domain'); + const recovery_email = document.querySelector('#field-recovery_email'); + const recovery_email_label = recovery_email?.parentElement?.querySelector('.hint'); + + if ( + !createEmailAddress || + !recovery_email || + !recovery_email_label || + !domain || + !username || + !email_username + ) { + console.warn('Some elements wern\'t found.'); + return; + } + + const updateForm = () => { + + if (createEmailAddress.checked) { + recovery_email.removeAttribute('required'); + recovery_email_label.style.display = 'block'; + domain.disabled = false; + } else { + recovery_email.setAttribute('required', 'required'); + recovery_email_label.style.display = 'none'; + domain.disabled = true; + } + + username.value = username.value.toLowerCase(); + email_username.innerText = username.value + '@'; + }; + + createEmailAddress.addEventListener('change', updateForm); + username.addEventListener('change', updateForm); + username.addEventListener('keyup', updateForm); + updateForm(); +}); diff --git a/assets/ts/tooltips-and-dropdowns.ts b/assets/ts/tooltips-and-dropdowns.ts new file mode 100644 index 0000000..069b405 --- /dev/null +++ b/assets/ts/tooltips-and-dropdowns.ts @@ -0,0 +1,31 @@ +export function updateTooltips(): void { + console.debug('Updating tooltips'); + const elements = document.querySelectorAll('.tip, .dropdown'); + + // Calculate max potential displacement + let max = 0; + elements.forEach(el => { + const box = el.getBoundingClientRect(); + if (max < box.height) max = box.height; + }); + + // Prevent displacement + elements.forEach(el => { + if (!el.dataset.tooltipSetup) { + el.dataset.tooltipSetup = 'true'; + const box = el.getBoundingClientRect(); + if (box.bottom >= document.body.clientHeight - (max + 32)) { + el.classList.add('top'); + } + } + }); +} + +document.addEventListener('DOMContentLoaded', () => { + window.addEventListener('popstate', () => { + updateTooltips(); + }); + window.requestAnimationFrame(() => { + updateTooltips(); + }); +}); diff --git a/config/default.ts b/config/default.json5 similarity index 63% rename from config/default.ts rename to config/default.json5 index cb6a0d4..75f1805 100644 --- a/config/default.ts +++ b/config/default.json5 @@ -1,32 +1,30 @@ -export default Object.assign(require("wms-core/config/default").default, { +{ app: { - name: 'ALDAP', - contact_email: 'contact@toot.party', + name: 'Rainbox Email', + contact_email: 'contact@rainbox.email', + webmail_url: 'https://rc.rainbox.email', }, log_level: "DEV", db_log_level: "ERROR", - base_url: "http://localhost:4899", + public_url: "http://localhost:4899", public_websocket_url: "ws://localhost:4899", - domain: 'localhost:4899', port: 4899, mysql: { connectionLimit: 10, host: "localhost", user: "root", password: "", - database: "aldap", + database: "rainbox_email", create_database_automatically: false, }, redis: { host: "127.0.0.1", port: 6379, - prefix: 'aldap', + prefix: 'rainbox.email', }, session: { - secret: "very_secret_not_known", cookie: { secure: false, - maxAge: 30 * 24 * 3600 * 1000, }, }, mail: { @@ -36,14 +34,14 @@ export default Object.assign(require("wms-core/config/default").default, { username: "", password: "", allow_invalid_tls: true, - from: 'contact@toot.party', - from_name: 'ALDAP - toot.party', + from: 'contact@rainbox.email', + from_name: 'Rainbox Email', }, view: { cache: false, }, + approval_mode: false, magic_link: { validity_period: 20, }, - approval_mode: false, -}); +} diff --git a/config/production.ts b/config/production.json5 similarity index 55% rename from config/production.ts rename to config/production.json5 index 933ee09..c3d13ab 100644 --- a/config/production.ts +++ b/config/production.json5 @@ -1,9 +1,8 @@ -export default Object.assign(require("wms-core/config/production").default, { +{ log_level: "DEBUG", db_log_level: "ERROR", - base_url: "https://aldap.toot.party", - public_websocket_url: "wss://aldap.toot.party", - domain: 'aldap.toot.party', + public_url: "https://rainbox.email", + public_websocket_url: "wss://rainbox.email", session: { cookie: { secure: true @@ -13,8 +12,8 @@ export default Object.assign(require("wms-core/config/production").default, { secure: true, allow_invalid_tls: false }, + approval_mode: true, magic_link: { validity_period: 900, - }, - approval_mode: true, -}); + } +} diff --git a/config/test.json5 b/config/test.json5 new file mode 100644 index 0000000..2bbf940 --- /dev/null +++ b/config/test.json5 @@ -0,0 +1,9 @@ +{ + mysql: { + host: "localhost", + user: "root", + password: "", + database: "rainbox_email_test", + create_database_automatically: true + }, +} diff --git a/config/test.ts b/config/test.ts deleted file mode 100644 index 67f64f6..0000000 --- a/config/test.ts +++ /dev/null @@ -1,6 +0,0 @@ -export default Object.assign(require("wms-core/config/test").default, { - mysql: { - database: "aldap_test", - create_database_automatically: true - }, -}); \ No newline at end of file diff --git a/package.json b/package.json index 3ce5607..397dcb9 100644 --- a/package.json +++ b/package.json @@ -1,36 +1,44 @@ { - "name": "aldap", - "version": "1.1.1", - "description": "Authentication LDAP server", - "repository": "git@gitlab.com:ArisuOngaku/aldap.git", + "name": "rainbox.email", + "version": "2.0.0", + "description": "ISP mail provider manager with mysql and integrated LDAP server", + "repository": "https://gitlab.com/ArisuOngaku/rainbox.email", "author": "Alice Gaudon ", - "private": true, - "main": "dist/main.js", + "main": "dist/src/main.js", + "license": "AGPL-3.0-only", "scripts": { - "test": "jest --verbose --runInBand", "dist-webpack": "webpack --mode production", - "dist": "tsc && npm run dist-webpack", + "clean": "(test ! -d dist || rm -r dist)", + "compile": "yarn clean && tsc", + "build": "yarn compile && yarn dist-webpack", + "lint": "eslint . --ext .js,.jsx,.ts,.tsx", "dev": "concurrently -k -n \"Typescript,Node,Webpack,Maildev\" -p \"[{name}]\" -c \"blue,green,red,yellow\" \"tsc --watch\" \"nodemon\" \"webpack --watch --mode development\" \"maildev\"", - "start": "yarn dist && node dist/main.js" + "start": "yarn build && node dist/src/main.js", + "test": "jest --verbose --runInBand" }, "devDependencies": { "@babel/core": "^7.9.0", "@babel/preset-env": "^7.9.5", + "@fortawesome/fontawesome-free": "^5.14.0", "@types/argon2": "^0.15.0", "@types/config": "^0.0.36", "@types/express": "^4.17.6", "@types/express-session": "^1.17.0", + "@types/feather-icons": "^4.7.0", "@types/formidable": "^1.0.31", "@types/jest": "^26.0.4", "@types/ldapjs": "^1.0.7", "@types/mysql": "^2.15.15", - "@types/node": "^14.0.23", + "@types/node": "^14.6.3", "@types/nodemailer": "^6.4.0", "@types/nunjucks": "^3.1.3", "@types/ws": "^7.2.6", + "@typescript-eslint/eslint-plugin": "^4.3.0", + "@typescript-eslint/parser": "^4.3.0", "babel-loader": "^8.1.0", "concurrently": "^5.1.0", - "css-loader": "^4.0.0", + "css-loader": "^5.0.0", + "eslint": "^7.10.0", "feather-icons": "^4.28.0", "file-loader": "^6.0.0", "imagemin": "^7.0.1", @@ -40,21 +48,22 @@ "imagemin-svgo": "^8.0.0", "img-loader": "^3.0.1", "jest": "^26.1.0", - "mini-css-extract-plugin": "^0.9.0", - "node-sass": "^4.14.0", + "mini-css-extract-plugin": "^1.2.1", + "node-sass": "^5.0.0", "nodemon": "^2.0.3", - "sass-loader": "^9.0.2", + "sass-loader": "^10.0.1", + "terser-webpack-plugin": "^5.0.3", "ts-jest": "^26.1.1", - "typescript": "^3.8.3", - "uglifyjs-webpack-plugin": "^2.2.0", - "webpack": "^4.43.0", - "webpack-cli": "^3.3.11", - "wms-core": "^0" + "ts-loader": "^8.0.4", + "typescript": "^4.0.2", + "webpack": "^5.3.2", + "webpack-cli": "^4.1.0" }, "dependencies": { - "argon2": "^0.26.2", + "argon2": "^0.27.0", "config": "^3.3.1", "express": "^4.17.1", - "ldapjs": "^2.0.0" + "ldapjs": "^2.0.0", + "wms-core": "^0.22.0" } } diff --git a/src/App.ts b/src/App.ts index aab3e1e..aff252d 100644 --- a/src/App.ts +++ b/src/App.ts @@ -1,6 +1,5 @@ import Application from "wms-core/Application"; -import {Type} from "wms-core/Utils"; -import Migration from "wms-core/db/Migration"; +import Migration, {MigrationType} from "wms-core/db/Migration"; import ExpressAppComponent from "wms-core/components/ExpressAppComponent"; import NunjucksComponent from "wms-core/components/NunjucksComponent"; import MysqlComponent from "wms-core/components/MysqlComponent"; @@ -20,9 +19,11 @@ import AuthGuard from "wms-core/auth/AuthGuard"; import {PasswordAuthProof} from "./models/UserPasswordComponent"; import LDAPServerComponent from "./LDAPServerComponent"; import AutoUpdateComponent from "wms-core/components/AutoUpdateComponent"; +import packageJson = require('../package.json'); +import DummyMigration from "wms-core/migrations/DummyMigration"; +import DropLegacyLogsTable from "wms-core/migrations/DropLegacyLogsTable"; import AccountController from "./controllers/AccountController"; import CreateMigrationsTable from "wms-core/migrations/CreateMigrationsTable"; -import CreateLogsTable from "wms-core/migrations/CreateLogsTable"; import CreateUsersAndUserEmailsTable from "wms-core/auth/migrations/CreateUsersAndUserEmailsTable"; import AddPasswordToUsers from "./migrations/AddPasswordToUsers"; import CreateMagicLinksTable from "wms-core/auth/migrations/CreateMagicLinksTable"; @@ -38,20 +39,22 @@ import AddNameToUsers from "./migrations/AddNameToUsers"; import CreateMailTables from "./migrations/CreateMailTables"; import MailboxBackendController from "./controllers/MailboxBackendController"; import RedirectBackComponent from "wms-core/components/RedirectBackComponent"; +import MailAutoConfigController from "./controllers/MailAutoConfigController"; export default class App extends Application { - private readonly port: number; - private magicLinkWebSocketListener?: MagicLinkWebSocketListener; + private magicLinkWebSocketListener?: MagicLinkWebSocketListener; - constructor(port: number) { - super(require('../package.json').version); - this.port = port; + public constructor( + private readonly addr: string, + private readonly port: number, + ) { + super(packageJson.version); } - protected getMigrations(): Type[] { + protected getMigrations(): MigrationType[] { return [ CreateMigrationsTable, - CreateLogsTable, + DummyMigration, CreateUsersAndUserEmailsTable, AddPasswordToUsers, CreateMagicLinksTable, @@ -60,6 +63,7 @@ export default class App extends Application { DropNameFromUsers, AddNameToUsers, CreateMailTables, + DropLegacyLogsTable, ]; } @@ -70,11 +74,11 @@ export default class App extends Application { } private registerComponents() { - const expressAppComponent = new ExpressAppComponent(this.port); const redisComponent = new RedisComponent(); const mysqlComponent = new MysqlComponent(); // Base + const expressAppComponent = new ExpressAppComponent(this.addr, this.port); this.use(expressAppComponent); this.use(new LogRequestsComponent()); @@ -110,9 +114,9 @@ export default class App extends Application { this.use(new AuthComponent(new class extends AuthGuard { public async getProofForSession(session: Express.Session): Promise { return PasswordAuthProof.getProofForSession(session) || - MagicLink.bySessionID(session.id); + await MagicLink.bySessionId(session.id); } - })); + }(this))); // WebSocket server this.use(new WebSocketServerComponent(this, expressAppComponent, redisComponent)); @@ -129,7 +133,7 @@ export default class App extends Application { private registerControllers() { // Priority routes / interrupting middlewares this.use(new AccountController()); - this.use(new MagicLinkController(this.magicLinkWebSocketListener!)) + this.use(new MagicLinkController(this.as(MagicLinkWebSocketListener))); this.use(new BackendController()); this.use(new MailboxBackendController()); this.use(new AuthController()); @@ -138,8 +142,9 @@ export default class App extends Application { this.use(new MailController()); // Other functionnality + this.use(new MailAutoConfigController()); // Semi-static routes this.use(new HomeController()); } -} \ No newline at end of file +} diff --git a/src/LDAPServerComponent.ts b/src/LDAPServerComponent.ts index b5f9e45..e13cb32 100644 --- a/src/LDAPServerComponent.ts +++ b/src/LDAPServerComponent.ts @@ -1,21 +1,20 @@ import ApplicationComponent from "wms-core/ApplicationComponent"; -import {Express} from "express"; import ldap, {InvalidCredentialsError, Server} from "ldapjs"; -import Logger from "wms-core/Logger"; +import {log} from "wms-core/Logger"; import UserPasswordComponent from "./models/UserPasswordComponent"; import Throttler from "wms-core/Throttler"; import User from "wms-core/auth/models/User"; -export default class LDAPServerComponent extends ApplicationComponent { +export default class LDAPServerComponent extends ApplicationComponent { private server?: Server; - public async start(app: Express): Promise { + public async start(): Promise { this.server = ldap.createServer({ - log: console + log: console, }); - this.server.bind('ou=users,dc=toot,dc=party', async (req: any, res: any, next: any) => { + this.server.bind('ou=users,dc=toot,dc=party', async (req: Record, res: Record void>, next: (err: unknown) => void) => { const rdns = req.dn.toString().split(', ').map((rdn: string) => rdn.split('=')); - let username; + let username: string = ''; let email; for (const rdn of rdns) { if (rdn[0] === 'cn') { @@ -25,12 +24,12 @@ export default class LDAPServerComponent extends ApplicationComponent { } } - Logger.debug('Matrix authentication attempt:', username, email); + log.debug('Matrix authentication attempt:', username, email); try { Throttler.throttle('ldap_auth', 3, 30 * 1000, username); } catch (e) { - Logger.debug('Too many auth requests'); + log.debug('Too many auth requests'); next(new InvalidCredentialsError()); return; } @@ -40,25 +39,25 @@ export default class LDAPServerComponent extends ApplicationComponent { const email = await user.mainEmail.get(); if (email) { if (await user.as(UserPasswordComponent).verifyPassword(req.credentials)) { - Logger.debug('Success'); + log.debug('Success'); res.end(); return; } } } - Logger.debug('Fail'); + log.debug('Fail'); next(new InvalidCredentialsError()); }); - this.server.unbind((req: any, res: any, next: any) => { - Logger.debug('Unbind', req); + this.server.unbind((req: unknown, res: unknown, next: () => void) => { + log.debug('Unbind', req); next(); }); this.server.listen(8389, '127.0.0.1', () => { - Logger.info(`LDAP server listening on ${this.server!.url}`); + log.info(`LDAP server listening on ${this.server?.url}`); }); this.server.on('close', () => { - Logger.info('LDAP server closed.'); + log.info('LDAP server closed.'); }); } @@ -66,7 +65,6 @@ export default class LDAPServerComponent extends ApplicationComponent { public async stop(): Promise { await new Promise(resolve => { if (this.server) { - // @ts-ignore this.server.close(() => { resolve(); }); @@ -75,4 +73,4 @@ export default class LDAPServerComponent extends ApplicationComponent { } }); } -} \ No newline at end of file +} diff --git a/src/Mails.ts b/src/Mails.ts index 6945665..ed5e93c 100644 --- a/src/Mails.ts +++ b/src/Mails.ts @@ -3,4 +3,4 @@ import {MailTemplate} from "wms-core/Mail"; export const ADD_RECOVERY_EMAIL_MAIL_TEMPLATE: MailTemplate = new MailTemplate( 'add_recovery_email', (data) => 'Add ' + data.email + ' as you recovery email.', -); \ No newline at end of file +); diff --git a/src/controllers/AccountController.ts b/src/controllers/AccountController.ts index 321acda..5101c76 100644 --- a/src/controllers/AccountController.ts +++ b/src/controllers/AccountController.ts @@ -1,13 +1,12 @@ import Controller from "wms-core/Controller"; -import {REQUIRE_AUTH_MIDDLEWARE} from "wms-core/auth/AuthComponent"; -import {NextFunction, Request, Response} from "express"; +import {RequireAuthMiddleware} from "wms-core/auth/AuthComponent"; +import {Request, Response} from "express"; import {ADD_RECOVERY_EMAIL_MAIL_TEMPLATE} from "../Mails"; -import Validator, {InvalidFormatValidationError, ValidationBag} from "wms-core/db/Validator"; -import {EMAIL_REGEX} from "wms-core/db/Model"; +import Validator, {EMAIL_REGEX, InvalidFormatValidationError, ValidationBag} from "wms-core/db/Validator"; import MagicLinkController from "./MagicLinkController"; import {MagicLinkActionType} from "./MagicLinkActionType"; import UserEmail from "wms-core/auth/models/UserEmail"; -import {BadRequestError, ForbiddenHttpError, NotFoundHttpError} from "wms-core/HttpError"; +import {BadRequestError, ForbiddenHttpError, NotFoundHttpError, ServerError} from "wms-core/HttpError"; import MailDomain from "../models/MailDomain"; import UserMailIdentityComponent from "../models/UserMailIdentityComponent"; import MailIdentity from "../models/MailIdentity"; @@ -19,18 +18,18 @@ export default class AccountController extends Controller { return '/account'; } - routes(): void { - this.get('/', this.getAccount, 'account', REQUIRE_AUTH_MIDDLEWARE); - this.post('/add-recovery-email', this.addRecoveryEmail, 'add-recovery-email', REQUIRE_AUTH_MIDDLEWARE); - this.post('/set-main-email', this.postSetMainRecoveryEmail, 'set-main-recovery-email', REQUIRE_AUTH_MIDDLEWARE); - this.post('/remove-email', this.postRemoveRecoveryEmail, 'remove-recovery-email', REQUIRE_AUTH_MIDDLEWARE); + public routes(): void { + this.get('/', this.getAccount, 'account', RequireAuthMiddleware); + this.post('/add-recovery-email', this.addRecoveryEmail, 'add-recovery-email', RequireAuthMiddleware); + this.post('/set-main-email', this.postSetMainRecoveryEmail, 'set-main-recovery-email', RequireAuthMiddleware); + this.post('/remove-email', this.postRemoveRecoveryEmail, 'remove-recovery-email', RequireAuthMiddleware); - this.post('/create-mail-identity', this.postCreateMailIdentity, 'create-mail-identity', REQUIRE_AUTH_MIDDLEWARE); - this.post('/delete-mail-identity', this.postDeleteMailIdentity, 'delete-mail-identity', REQUIRE_AUTH_MIDDLEWARE); + this.post('/create-mail-identity', this.postCreateMailIdentity, 'create-mail-identity', RequireAuthMiddleware); + this.post('/delete-mail-identity', this.postDeleteMailIdentity, 'delete-mail-identity', RequireAuthMiddleware); } - protected async getAccount(req: Request, res: Response, next: NextFunction): Promise { - const user = req.models.user!; + protected async getAccount(req: Request, res: Response): Promise { + const user = req.as(RequireAuthMiddleware).getUser(); const userMailIdentity = user.as(UserMailIdentityComponent); res.render('account', { @@ -41,7 +40,7 @@ export default class AccountController extends Controller { email: await identity.toEmail(), }))), domains: (await MailDomain.select() - .where('user_id', user.id!) + .where('user_id', user.id) .where('user_id', null, WhereTest.EQ, WhereOperator.OR) .sortBy('user_id', 'DESC') .get()) @@ -52,7 +51,7 @@ export default class AccountController extends Controller { }); } - protected async addRecoveryEmail(req: Request, res: Response, next: NextFunction): Promise { + protected async addRecoveryEmail(req: Request, res: Response): Promise { await this.validate({ email: new Validator().defined().regexp(EMAIL_REGEX), }, req.body); @@ -68,13 +67,16 @@ export default class AccountController extends Controller { throw bag; } + if (!req.sessionID) throw new ServerError('Session not initialized.'); + await MagicLinkController.sendMagicLink( - req.sessionID!, + this.getApp(), + req.sessionID, MagicLinkActionType.ADD_RECOVERY_EMAIL, Controller.route('account'), email, ADD_RECOVERY_EMAIL_MAIL_TEMPLATE, - {} + {}, ); res.redirect(Controller.route('magic_link_lobby', undefined, { @@ -86,16 +88,18 @@ export default class AccountController extends Controller { if (!req.body.id) throw new BadRequestError('Missing id field', 'Check form parameters.', req.url); + const user = req.as(RequireAuthMiddleware).getUser(); + const userEmail = await UserEmail.getById(req.body.id); if (!userEmail) throw new NotFoundHttpError('email', req.url); - if (userEmail.user_id !== req.models.user!.id) + if (userEmail.user_id !== user.id) throw new ForbiddenHttpError('email', req.url); - if (userEmail.id === req.models.user!.main_email_id) + if (userEmail.id === user.main_email_id) throw new BadRequestError('This address is already your main address', 'Try refreshing the account page.', req.url); - req.models.user!.main_email_id = userEmail.id; - await req.models.user!.save(); + user.main_email_id = userEmail.id; + await user.save(); req.flash('success', 'This email was successfully set as your main address.'); res.redirectBack(); @@ -105,12 +109,14 @@ export default class AccountController extends Controller { if (!req.body.id) throw new BadRequestError('Missing id field', 'Check form parameters.', req.url); + const user = req.as(RequireAuthMiddleware).getUser(); + const userEmail = await UserEmail.getById(req.body.id); if (!userEmail) throw new NotFoundHttpError('email', req.url); - if (userEmail.user_id !== req.models.user!.id) + if (userEmail.user_id !== user.id) throw new ForbiddenHttpError('email', req.url); - if (userEmail.id === req.models.user!.main_email_id) + if (userEmail.id === user.main_email_id) throw new BadRequestError('Cannot remove main email address', 'Try refreshing the account page.', req.url); await userEmail.delete(); @@ -123,7 +129,7 @@ export default class AccountController extends Controller { const domain = await MailDomain.getById(req.body.mail_domain_id); if (!domain) throw new NotFoundHttpError('domain', req.url); - const user = req.models.user!; + const user = req.as(RequireAuthMiddleware).getUser(); const mailIdentityComponent = user.as(UserMailIdentityComponent); const identity = MailIdentity.create({ @@ -137,7 +143,9 @@ export default class AccountController extends Controller { await this.validate({ name: new Validator().defined().equals(user.as(UserNameComponent).name), }, req.body); - if ((await mailIdentityComponent.getPublicAddressesCount()) >= mailIdentityComponent.getMaxPublicAddressesCount()) { + const actualPublicAddressesCount = await mailIdentityComponent.getPublicAddressesCount(); + const maxPublicAddressesCount = mailIdentityComponent.getMaxPublicAddressesCount(); + if (actualPublicAddressesCount >= maxPublicAddressesCount) { req.flash('error', 'You have reached maximum public email addresses.'); res.redirectBack(); return; @@ -158,22 +166,24 @@ export default class AccountController extends Controller { req.flash('info', 'Congratulations! You just created your mailbox.'); } - req.flash('success', 'Mail identity ' + (await identity.toEmail()) + ' successfully created.') + req.flash('success', 'Mail identity ' + await identity.toEmail() + ' successfully created.'); res.redirectBack(); } protected async postDeleteMailIdentity(req: Request, res: Response): Promise { + const user = req.as(RequireAuthMiddleware).getUser(); + const identity = await MailIdentity.getById(req.body.id); if (!identity) throw new NotFoundHttpError('Mail identity', req.url); - if (identity.user_id !== req.models.user!.id) throw new ForbiddenHttpError('mail identity', req.url); - if (req.models.user!.as(UserMailIdentityComponent).main_mail_identity_id === identity.id) { + if (identity.user_id !== user.id) throw new ForbiddenHttpError('mail identity', req.url); + if (user.as(UserMailIdentityComponent).main_mail_identity_id === identity.id) { req.flash('error', 'Cannot delete your mailbox identity.'); res.redirectBack(); return; } await identity.delete(); - req.flash('success', 'Identity ' + (await identity.toEmail()) + ' successfully deleted.'); + req.flash('success', 'Identity ' + await identity.toEmail() + ' successfully deleted.'); res.redirectBack(); } -} \ No newline at end of file +} diff --git a/src/controllers/AuthController.ts b/src/controllers/AuthController.ts index 350af6a..61ece83 100644 --- a/src/controllers/AuthController.ts +++ b/src/controllers/AuthController.ts @@ -1,6 +1,6 @@ import Controller from "wms-core/Controller"; -import {REQUIRE_AUTH_MIDDLEWARE, REQUIRE_GUEST_MIDDLEWARE} from "wms-core/auth/AuthComponent"; -import {NextFunction, Request, Response} from "express"; +import AuthComponent, {RequireAuthMiddleware, RequireGuestMiddleware} from "wms-core/auth/AuthComponent"; +import {Request, Response} from "express"; import Validator, {InvalidFormatValidationError, ValidationBag} from "wms-core/db/Validator"; import UserPasswordComponent, {PasswordAuthProof} from "../models/UserPasswordComponent"; import UserNameComponent, {USERNAME_REGEXP} from "../models/UserNameComponent"; @@ -11,12 +11,12 @@ import User from "wms-core/auth/models/User"; import Throttler from "wms-core/Throttler"; export default class AuthController extends _AuthController { - routes(): void { - this.get('/login', this.getLogin, 'auth', REQUIRE_GUEST_MIDDLEWARE); - this.post('/login', this.postLogin, 'auth', REQUIRE_GUEST_MIDDLEWARE); - this.get('/register', this.getRegister, 'register', REQUIRE_GUEST_MIDDLEWARE); - this.post('/register', this.postRegister, 'register', REQUIRE_GUEST_MIDDLEWARE); - this.post('/logout', this.postLogout, 'logout', REQUIRE_AUTH_MIDDLEWARE); + public routes(): void { + this.get('/login', this.getLogin, 'auth', RequireGuestMiddleware); + this.post('/login', this.postLogin, 'auth', RequireGuestMiddleware); + this.get('/register', this.getRegister, 'register', RequireGuestMiddleware); + this.post('/register', this.postRegister, 'register', RequireGuestMiddleware); + this.post('/logout', this.postLogout, 'logout', RequireAuthMiddleware); } protected async getLogin(req: Request, res: Response): Promise { @@ -35,15 +35,17 @@ export default class AuthController extends _AuthController { if (!user) throw new NotFoundHttpError(`Couldn't find a user with name ${req.body.username}`, req.url); - const passwordAuthProof = PasswordAuthProof.createProofForLogin(req.session!); + if (!req.session) throw new ServerError('Session not initialized.'); + + const passwordAuthProof = PasswordAuthProof.createProofForLogin(req.session); passwordAuthProof.setResource(user); await passwordAuthProof.authorize(req.body.password); try { - await req.authGuard.authenticateOrRegister(req.session!, passwordAuthProof); + await this.getApp().as(AuthComponent).getAuthGuard().authenticateOrRegister(req.session, passwordAuthProof); } catch (e) { if (e instanceof AuthError) { - Throttler.throttle('login_failed_attempts_user', 3, 180000, user.as(UserNameComponent).name!, 1000, 60000); + Throttler.throttle('login_failed_attempts_user', 3, 180000, user.getOrFail('name'), 1000, 60000); Throttler.throttle('login_failed_attempts_ip', 5, 60000, req.ip, 1000, 60000); if (e instanceof PendingApprovalAuthError) { @@ -54,7 +56,7 @@ export default class AuthController extends _AuthController { const bag = new ValidationBag(); const err = new InvalidFormatValidationError('Invalid password.'); err.thingName = 'password'; - bag.addMessage(err) + bag.addMessage(err); throw bag; } } else { @@ -80,21 +82,24 @@ export default class AuthController extends _AuthController { terms: new Validator().defined(), }, req.body); - const passwordAuthProof = PasswordAuthProof.createAuthorizedProofForRegistration(req.session!); + if(!req.session) throw new ServerError('Session not initialized.'); + + const passwordAuthProof = PasswordAuthProof.createAuthorizedProofForRegistration(req.session); try { - await req.authGuard.authenticateOrRegister(req.session!, passwordAuthProof, undefined, async (connection, user) => { - passwordAuthProof.setResource(user); + await this.getApp().as(AuthComponent).getAuthGuard().authenticateOrRegister(req.session, passwordAuthProof, + undefined, async (connection, user) => { + passwordAuthProof.setResource(user); - const callbacks: RegisterCallback[] = []; + const callbacks: RegisterCallback[] = []; - // Password - await user.as(UserPasswordComponent).setPassword(req.body.password); + // Password + await user.as(UserPasswordComponent).setPassword(req.body.password); - // Username - user.as(UserNameComponent).name = req.body.username; + // Username + user.as(UserNameComponent).name = req.body.username; - return callbacks; - }); + return callbacks; + }); } catch (e) { if (e instanceof PendingApprovalAuthError) { req.flash('info', `Your account was successfully created and is pending review from an administrator.`); @@ -105,17 +110,17 @@ export default class AuthController extends _AuthController { } } - const user = (await passwordAuthProof.getResource())!; + const user = await passwordAuthProof.getResource(); - req.flash('success', `Your account was successfully created! Welcome, ${user.as(UserNameComponent).name}.`); + req.flash('success', `Your account was successfully created! Welcome, ${user?.as(UserNameComponent).name}.`); res.redirect(Controller.route('home')); } - protected async getCheckAuth(req: Request, res: Response, next: NextFunction): Promise { + protected async getCheckAuth(): Promise { throw new ServerError('Not implemented.'); } - protected async postAuth(req: Request, res: Response, next: NextFunction): Promise { + protected async postAuth(): Promise { throw new ServerError('Not implemented.'); } -} \ No newline at end of file +} diff --git a/src/controllers/HomeController.ts b/src/controllers/HomeController.ts index 847c759..0413228 100644 --- a/src/controllers/HomeController.ts +++ b/src/controllers/HomeController.ts @@ -1,17 +1,28 @@ import Controller from "wms-core/Controller"; import {Request, Response} from "express"; +import config from "config"; export default class HomeController extends Controller { - routes(): void { + public routes(): void { this.get('/', this.getHome, 'home'); this.get('/about', this.getAbout, 'about'); + this.get('/back', this.goBack, 'back'); } - private async getHome(req: Request, res: Response) { - res.render('home'); + protected async getHome(req: Request, res: Response): Promise { + res.render('about', { + instance_url: config.get('public_url'), + }); } - private async getAbout(req: Request, res: Response) { - res.render('about'); + protected async getAbout(req: Request, res: Response): Promise { + res.redirect(Controller.route('home')); } -} \ No newline at end of file + + /** + * This is to test and assert that wms-core extended types are available + */ + protected async goBack(req: Request, res: Response): Promise { + res.redirectBack(); + } +} diff --git a/src/controllers/MagicLinkActionType.ts b/src/controllers/MagicLinkActionType.ts index eda96d5..c16998e 100644 --- a/src/controllers/MagicLinkActionType.ts +++ b/src/controllers/MagicLinkActionType.ts @@ -1,3 +1,3 @@ export enum MagicLinkActionType { ADD_RECOVERY_EMAIL = 'Add a recovery email', -} \ No newline at end of file +} diff --git a/src/controllers/MagicLinkController.ts b/src/controllers/MagicLinkController.ts index c315b0b..3e49fbd 100644 --- a/src/controllers/MagicLinkController.ts +++ b/src/controllers/MagicLinkController.ts @@ -6,46 +6,46 @@ import {MagicLinkActionType} from "./MagicLinkActionType"; import Controller from "wms-core/Controller"; import {BadOwnerMagicLink} from "wms-core/auth/magic_link/MagicLinkAuthController"; import UserEmail from "wms-core/auth/models/UserEmail"; +import App from "../App"; +import AuthComponent from "wms-core/auth/AuthComponent"; -export default class MagicLinkController extends _MagicLinkController { - constructor(magicLinkWebSocketListener: MagicLinkWebSocketListener) { +export default class MagicLinkController extends _MagicLinkController { + public constructor(magicLinkWebSocketListener: MagicLinkWebSocketListener) { super(magicLinkWebSocketListener); } protected async performAction(magicLink: MagicLink, req: Request, res: Response): Promise { - switch (magicLink.getActionType()) { - case MagicLinkActionType.ADD_RECOVERY_EMAIL: - if (magicLink.getSessionID() !== req.sessionID!) throw new BadOwnerMagicLink(); - await magicLink.delete(); + if (magicLink.action_type === MagicLinkActionType.ADD_RECOVERY_EMAIL) { + if (!req.session || !req.sessionID || magicLink.session_id !== req.sessionID) throw new BadOwnerMagicLink(); - const proof = await req.authGuard.isAuthenticated(req.session!); - const user = await proof?.getResource(); - if (!user) break; + await magicLink.delete(); - const email = await magicLink.getEmail(); + const authGuard = this.getApp().as(AuthComponent).getAuthGuard(); + const proof = await authGuard.isAuthenticated(req.session); + const user = await proof?.getResource(); + if (!user) return; - // Existing email - if (await UserEmail.select().with('user').where('email', email).first()) { - req.flash('error', 'An account already exists with this email address. Please first remove it there before adding it here.'); - res.redirect(Controller.route('account')); - break; - } - - const userEmail = UserEmail.create({ - user_id: user.id, - email: email, - main: false, - }); - await userEmail.save(); - - if (!user.main_email_id) { - user.main_email_id = userEmail.id; - await user.save(); - } - - req.flash('success', `Recovery email ${userEmail.email} successfully added.`); + const email = await magicLink.getOrFail('email'); + if (await UserEmail.select().with('user').where('email', email).first()) { + req.flash('error', 'An account already exists with this email address. Please first remove it there before adding it here.'); res.redirect(Controller.route('account')); - break; + return; + } + + const userEmail = UserEmail.create({ + user_id: user.id, + email: email, + main: false, + }); + await userEmail.save(); + + if (!user.main_email_id) { + user.main_email_id = userEmail.id; + await user.save(); + } + + req.flash('success', `Recovery email ${userEmail.email} successfully added.`); + res.redirect(Controller.route('account')); } } -} \ No newline at end of file +} diff --git a/src/controllers/MailAutoConfigController.ts b/src/controllers/MailAutoConfigController.ts new file mode 100644 index 0000000..e744a03 --- /dev/null +++ b/src/controllers/MailAutoConfigController.ts @@ -0,0 +1,40 @@ +import Controller from "wms-core/Controller"; +import {Request, Response} from "express"; +import MailDomain from "../models/MailDomain"; + +export default class MailAutoConfigController extends Controller { + public routes(): void { + this.get('/.well-known/autoconfig/mail/config-v1.1.xml', this.getAutoConfig, 'mail-auto-config'); + } + + /** + * See view and https://wiki.mozilla.org/Thunderbird:Autoconfiguration:ConfigFileFormat + */ + protected async getAutoConfig(req: Request, res: Response): Promise { + res.contentType('text/xml'); + const domains = await MailDomain.select().get(); + res.render('mail-auto-config.xml.njk', { + domain: domains[0], + domains: domains, + display_name: 'Rainbox Email', + display_name_short: 'Rainbox', + username: '%EMAILADDRESS%', + auth_method: 'password-cleartext', + imap: { + server: 'rainbox.email', + port: '143', + method: 'STARTTLS', + }, + pop3: { + server: 'rainbox.email', + port: '110', + method: 'STARTTLS', + }, + smtp: { + server: 'rainbox.email', + port: '587', + method: 'STARTTLS', + }, + }); + } +} diff --git a/src/controllers/MailboxBackendController.ts b/src/controllers/MailboxBackendController.ts index 3685e88..4d3b035 100644 --- a/src/controllers/MailboxBackendController.ts +++ b/src/controllers/MailboxBackendController.ts @@ -1,5 +1,4 @@ import Controller from "wms-core/Controller"; -import {REQUIRE_ADMIN_MIDDLEWARE, REQUIRE_AUTH_MIDDLEWARE} from "wms-core/auth/AuthComponent"; import {Request, Response} from "express"; import User from "wms-core/auth/models/User"; import {WhereTest} from "wms-core/db/ModelQuery"; @@ -9,6 +8,7 @@ import {NotFoundHttpError} from "wms-core/HttpError"; import MailDomain from "../models/MailDomain"; import BackendController from "wms-core/helpers/BackendController"; import MailIdentity from "../models/MailIdentity"; +import {RequireAdminMiddleware, RequireAuthMiddleware} from "wms-core/auth/AuthComponent"; export default class MailboxBackendController extends Controller { public constructor() { @@ -25,16 +25,16 @@ export default class MailboxBackendController extends Controller { } public routes(): void { - this.get('/', this.getMailboxesBackend, 'backend-mailboxes', REQUIRE_AUTH_MIDDLEWARE, REQUIRE_ADMIN_MIDDLEWARE); - this.get('/:id', this.getMailboxBackend, 'backend-mailbox', REQUIRE_AUTH_MIDDLEWARE, REQUIRE_ADMIN_MIDDLEWARE); + this.get('/', this.getMailboxesBackend, 'backend-mailboxes', RequireAuthMiddleware, RequireAdminMiddleware); + this.get('/:id', this.getMailboxBackend, 'backend-mailbox', RequireAuthMiddleware, RequireAdminMiddleware); - this.post('/add-domain', this.postAddDomain, 'backend-add-domain', REQUIRE_AUTH_MIDDLEWARE, REQUIRE_ADMIN_MIDDLEWARE); - this.get('/edit-domain/:id', this.getEditDomain, 'backend-edit-domain', REQUIRE_AUTH_MIDDLEWARE, REQUIRE_ADMIN_MIDDLEWARE); - this.post('/edit-domain/:id', this.postEditDomain, 'backend-edit-domain', REQUIRE_AUTH_MIDDLEWARE, REQUIRE_ADMIN_MIDDLEWARE); - this.post('/remove-domain', this.postRemoveDomain, 'backend-remove-domain', REQUIRE_AUTH_MIDDLEWARE, REQUIRE_ADMIN_MIDDLEWARE); + this.post('/add-domain', this.postAddDomain, 'backend-add-domain', RequireAuthMiddleware, RequireAdminMiddleware); + this.get('/edit-domain/:id', this.getEditDomain, 'backend-edit-domain', RequireAuthMiddleware, RequireAdminMiddleware); + this.post('/edit-domain/:id', this.postEditDomain, 'backend-edit-domain', RequireAuthMiddleware, RequireAdminMiddleware); + this.post('/remove-domain', this.postRemoveDomain, 'backend-remove-domain', RequireAuthMiddleware, RequireAdminMiddleware); - this.post('/:id/create-mail-identity', this.postCreateMailIdentity, 'backend-create-mail-identity', REQUIRE_AUTH_MIDDLEWARE, REQUIRE_ADMIN_MIDDLEWARE); - this.post('/delete-mail-identity', this.postDeleteMailIdentity, 'backend-delete-mail-identity', REQUIRE_AUTH_MIDDLEWARE, REQUIRE_ADMIN_MIDDLEWARE); + this.post('/:id/create-mail-identity', this.postCreateMailIdentity, 'backend-create-mail-identity', RequireAuthMiddleware, RequireAdminMiddleware); + this.post('/delete-mail-identity', this.postDeleteMailIdentity, 'backend-delete-mail-identity', RequireAuthMiddleware, RequireAdminMiddleware); } protected async getMailboxesBackend(req: Request, res: Response): Promise { @@ -80,16 +80,19 @@ export default class MailboxBackendController extends Controller { .first(); if (!user) throw new NotFoundHttpError('User', req.url); + const mainMailIdentity = await user.as(UserMailIdentityComponent).mainMailIdentity.get(); + const mailDomains = await MailDomain.select().get(); + const mailIdentities = await user.as(UserMailIdentityComponent).mailIdentities.get(); res.render('backend/mailbox', { mailbox: { id: user.id, - name: await (await user.as(UserMailIdentityComponent).mainMailIdentity.get())?.toEmail() || 'Not created.', + name: await mainMailIdentity?.toEmail() || 'Not created.', }, - domains: (await MailDomain.select().get()).map(d => ({ + domains: mailDomains.map(d => ({ display: d.name, value: d.id, })), - identities: await Promise.all((await user.as(UserMailIdentityComponent).mailIdentities.get()).map(async i => ({ + identities: await Promise.all(mailIdentities.map(async i => ({ id: i.id, email: await i.toEmail(), }))), @@ -97,10 +100,7 @@ export default class MailboxBackendController extends Controller { } protected async postAddDomain(req: Request, res: Response): Promise { - const domain = MailDomain.create({ - name: req.body.name, - user_id: req.body.user_id, - }); + const domain = MailDomain.create(req.body); await domain.save(); req.flash('success', `Domain ${domain.name} successfully added with owner ${(await domain.owner.get())?.name}`); res.redirectBack(); @@ -182,7 +182,7 @@ export default class MailboxBackendController extends Controller { req.flash('info', 'Mailbox created.'); } - req.flash('success', 'Mail identity ' + (await identity.toEmail()) + ' successfully created.') + req.flash('success', 'Mail identity ' + await identity.toEmail() + ' successfully created.'); res.redirectBack(); } @@ -201,7 +201,7 @@ export default class MailboxBackendController extends Controller { } await identity.delete(); - req.flash('success', 'Identity ' + (await identity.toEmail()) + ' successfully deleted.'); + req.flash('success', 'Identity ' + await identity.toEmail() + ' successfully deleted.'); res.redirectBack(); } -} \ No newline at end of file +} diff --git a/src/main.ts b/src/main.ts index 1706351..14be157 100644 --- a/src/main.ts +++ b/src/main.ts @@ -1,10 +1,20 @@ -import Logger from "wms-core/Logger"; +import {delimiter} from "path"; + +// Load config from specified path or default + wms-core/config (default defaults) +process.env['NODE_CONFIG_DIR'] = + __dirname + '/../../node_modules/wms-core/config/' + + delimiter + + (process.env['NODE_CONFIG_DIR'] || __dirname + '/../../config/'); + +import {log} from "wms-core/Logger"; import App from "./App"; import config from "config"; (async () => { - const app = new App(config.get('port')); + log.debug('Config path:', process.env['NODE_CONFIG_DIR']); + + const app = new App(config.get('listen_addr'), config.get('port')); await app.start(); })().catch(err => { - Logger.error(err); -}); \ No newline at end of file + log.error(err); +}); diff --git a/src/migrations/AddPasswordToUsers.ts b/src/migrations/AddPasswordToUsers.ts index fb44b62..11a2713 100644 --- a/src/migrations/AddPasswordToUsers.ts +++ b/src/migrations/AddPasswordToUsers.ts @@ -18,4 +18,4 @@ export default class AddPasswordToUsers extends Migration { public registerModels(): void { ModelFactory.get(User).addComponent(UserPasswordComponent); } -} \ No newline at end of file +} diff --git a/src/migrations/CreateMailTables.ts b/src/migrations/CreateMailTables.ts index dc410ee..5408678 100644 --- a/src/migrations/CreateMailTables.ts +++ b/src/migrations/CreateMailTables.ts @@ -46,4 +46,4 @@ export default class CreateMailTables extends Migration { ModelFactory.get(User).addComponent(UserMailIdentityComponent); } -} \ No newline at end of file +} diff --git a/src/models/MailDomain.ts b/src/models/MailDomain.ts index 5f40fbf..9dc3c69 100644 --- a/src/models/MailDomain.ts +++ b/src/models/MailDomain.ts @@ -1,30 +1,28 @@ import Model from "wms-core/db/Model"; import User from "wms-core/auth/models/User"; import {ManyModelRelation, OneModelRelation} from "wms-core/db/ModelRelation"; -import ModelFactory from "wms-core/db/ModelFactory"; import MailIdentity from "./MailIdentity"; export default class MailDomain extends Model { public id?: number = undefined; public name?: string = undefined; - public user_id?: number = undefined; + public user_id?: number | null = undefined; - public readonly owner: OneModelRelation = new OneModelRelation(this, ModelFactory.get(User), { + public readonly owner: OneModelRelation = new OneModelRelation(this, User, { localKey: 'user_id', foreignKey: 'id', }); - public readonly identities: ManyModelRelation = new ManyModelRelation(this, ModelFactory.get(MailIdentity), { - localKey: 'id', - foreignKey: 'mail_domain_id', - }); + public readonly identities: ManyModelRelation = new ManyModelRelation(this, MailIdentity, + { + localKey: 'id', + foreignKey: 'mail_domain_id', + }); - public updateWithData(data: any) { + public updateWithData(data: Pick | Record): void { super.updateWithData(data); - if (typeof this.user_id !== 'undefined' && this.user_id <= 0) { - this.user_id = undefined; - } + if (this.user_id !== null && this.user_id !== undefined && this.user_id <= 0) this.user_id = null; } protected init(): void { @@ -42,4 +40,4 @@ export default class MailDomain extends Model { public canCreateAddresses(user: User): boolean { return this.user_id === user.id || this.isPublic(); } -} \ No newline at end of file +} diff --git a/src/models/MailIdentity.ts b/src/models/MailIdentity.ts index 57293af..0fd691b 100644 --- a/src/models/MailIdentity.ts +++ b/src/models/MailIdentity.ts @@ -1,8 +1,8 @@ -import Model, {EMAIL_REGEX} from "wms-core/db/Model"; +import Model from "wms-core/db/Model"; import User from "wms-core/auth/models/User"; import MailDomain from "./MailDomain"; import {OneModelRelation} from "wms-core/db/ModelRelation"; -import ModelFactory from "wms-core/db/ModelFactory"; +import {EMAIL_REGEX} from "wms-core/db/Validator"; export default class MailIdentity extends Model { public static get table(): string { @@ -15,11 +15,11 @@ export default class MailIdentity extends Model { public name?: string = undefined; public redirects_to?: string = undefined; - public readonly user: OneModelRelation = new OneModelRelation(this, ModelFactory.get(User), { + public readonly user: OneModelRelation = new OneModelRelation(this, User, { foreignKey: 'id', localKey: 'user_id', }); - public readonly domain: OneModelRelation = new OneModelRelation(this, ModelFactory.get(MailDomain), { + public readonly domain: OneModelRelation = new OneModelRelation(this, MailDomain, { foreignKey: 'id', localKey: 'mail_domain_id', }); @@ -33,6 +33,6 @@ export default class MailIdentity extends Model { } public async toEmail(): Promise { - return this.name + '@' + (await this.domain.get())!.name; + return this.name + '@' + (await this.domain.get())?.name; } -} \ No newline at end of file +} diff --git a/src/models/UserMailIdentityComponent.ts b/src/models/UserMailIdentityComponent.ts index 9f38cc5..baee383 100644 --- a/src/models/UserMailIdentityComponent.ts +++ b/src/models/UserMailIdentityComponent.ts @@ -2,31 +2,29 @@ import ModelComponent from "wms-core/db/ModelComponent"; import User from "wms-core/auth/models/User"; import {ManyModelRelation, OneModelRelation} from "wms-core/db/ModelRelation"; import MailIdentity from "./MailIdentity"; -import ModelFactory from "wms-core/db/ModelFactory"; import MailDomain from "./MailDomain"; export default class UserMailIdentityComponent extends ModelComponent { public main_mail_identity_id?: number = undefined; - public readonly mailIdentities: ManyModelRelation = new ManyModelRelation(this._model, ModelFactory.get(MailIdentity), { - localKey: 'id', - foreignKey: 'user_id', - }); + public readonly mailIdentities: ManyModelRelation = new ManyModelRelation(this._model, + MailIdentity, { + localKey: 'id', + foreignKey: 'user_id', + }); public readonly publicMailIdentities: ManyModelRelation = this.mailIdentities.clone() - .filter(async model => (await model.domain.get())!.isPublic()); + .filter(async model => !!(await model.domain.get())?.isPublic()); - public readonly mailDomains: ManyModelRelation = new ManyModelRelation(this._model, ModelFactory.get(MailDomain), { + public readonly mailDomains: ManyModelRelation = new ManyModelRelation(this._model, MailDomain, { localKey: 'id', foreignKey: 'user_id', }); - public readonly mainMailIdentity: OneModelRelation = new OneModelRelation(this._model, ModelFactory.get(MailIdentity), { - foreignKey: 'id', - localKey: 'main_mail_identity_id', - }); - - protected init(): void { - } + public readonly mainMailIdentity: OneModelRelation = new OneModelRelation(this._model, + MailIdentity, { + foreignKey: 'id', + localKey: 'main_mail_identity_id', + }); public getMaxPublicAddressesCount(): number { return 1; @@ -35,4 +33,4 @@ export default class UserMailIdentityComponent extends ModelComponent { public async getPublicAddressesCount(): Promise { return (await this.publicMailIdentities.get()).length; } -} \ No newline at end of file +} diff --git a/src/models/UserNameComponent.ts b/src/models/UserNameComponent.ts index 9ae41c7..2a45b12 100644 --- a/src/models/UserNameComponent.ts +++ b/src/models/UserNameComponent.ts @@ -10,4 +10,4 @@ export default class UserNameComponent extends ModelComponent { this.setValidation('name').defined().between(3, 64).regexp(USERNAME_REGEXP).unique(this._model); } -} \ No newline at end of file +} diff --git a/src/models/UserPasswordComponent.ts b/src/models/UserPasswordComponent.ts index 26aeac3..fab9b86 100644 --- a/src/models/UserPasswordComponent.ts +++ b/src/models/UserPasswordComponent.ts @@ -7,10 +7,6 @@ import ModelComponent from "wms-core/db/ModelComponent"; export default class UserPasswordComponent extends ModelComponent { private password?: string = undefined; - public constructor(props: any) { - super(props); - } - public init(): void { this.setValidation('password').acceptUndefined().maxLength(128); } @@ -51,22 +47,23 @@ export class PasswordAuthProof implements AuthProof { } private readonly session: Express.Session; - private userID: number | null; + private userId: number | null; private authorized: boolean; private userPassword: UserPasswordComponent | null = null; private constructor(session: Express.Session) { this.session = session; this.authorized = session.auth_password_proof?.authorized || false; - this.userID = session.auth_password_proof?.userID || null; + this.userId = session.auth_password_proof?.userId || null; } public async getResource(): Promise { - return await User.getById(this.userID); + if (typeof this.userId !== 'number') return null; + return await User.getById(this.userId); } - public setResource(user: User) { - this.userID = user.id!; + public setResource(user: User): void { + this.userId = user.getOrFail('id'); this.save(); } @@ -75,11 +72,7 @@ export class PasswordAuthProof implements AuthProof { } public async isValid(): Promise { - if (typeof this.userID === 'number') { - return Boolean(await this.getResource()); - } else { - return await this.isAuthorized(); - } + return Boolean(await this.getResource()); } public async revoke(): Promise { @@ -88,7 +81,7 @@ export class PasswordAuthProof implements AuthProof { private async getUserPassword(): Promise { if (!this.userPassword) { - this.userPassword = (await User.getById(this.userID))?.as(UserPasswordComponent) || null; + this.userPassword = (await User.getById(this.userId))?.as(UserPasswordComponent) || null; } return this.userPassword; } @@ -105,7 +98,7 @@ export class PasswordAuthProof implements AuthProof { private save() { this.session.auth_password_proof = { authorized: this.authorized, - userID: this.userID, + userId: this.userId, }; } -} \ No newline at end of file +} diff --git a/test/App.test.ts b/test/App.test.ts index 451f0fb..d116a22 100644 --- a/test/App.test.ts +++ b/test/App.test.ts @@ -2,4 +2,4 @@ describe('Write your tests', () => { test('Remove this when you have some tests', () => { expect(false).toBe(true); }); -}); \ No newline at end of file +}); diff --git a/tsconfig.frontend.json b/tsconfig.frontend.json new file mode 100644 index 0000000..4b5a3f5 --- /dev/null +++ b/tsconfig.frontend.json @@ -0,0 +1,18 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "outDir": "public/js", + "target": "ES6", + "strict": true, + "lib": [ + "es2020", + "DOM" + ], + "typeRoots": [ + "./node_modules/@types" + ] + }, + "include": [ + "assets/ts/**/*" + ] +} diff --git a/tsconfig.json b/tsconfig.json index a6bf63a..5ea85f7 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -6,14 +6,16 @@ "target": "ES6", "strict": true, "lib": [ - "es2020" + "es2020", + "DOM" ], "typeRoots": [ "./node_modules/@types" - ] + ], + "resolveJsonModule": true }, "include": [ "src/**/*", - "node_modules/wms-core" + "node_modules/wms-core/types" ] -} \ No newline at end of file +} diff --git a/tsconfig.test.json b/tsconfig.test.json new file mode 100644 index 0000000..897a6b4 --- /dev/null +++ b/tsconfig.test.json @@ -0,0 +1,14 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "typeRoots": [ + "node_modules/@types", + "src/types", + "test/types" + ] + }, + "include": [ + "src/types/**/*", + "test/**/*" + ] +} \ No newline at end of file diff --git a/views/about.njk b/views/about.njk index dbea28c..a061d9e 100644 --- a/views/about.njk +++ b/views/about.njk @@ -1,24 +1,35 @@ {% extends 'layouts/base.njk' %} -{% set title = app.name + ' - About us' %} +{% set title = app.name + ': it\'s not just emails' %} {% block body %} -

ALDAP: an authentication system for many services

-
+

{{ title }}

+
-

What services use ALDAP?

+

What is Rainbox Email?

+

Rainbox Email is a FOSS service that allows anyone to + manage an ISP-like mail database.

+

You can find the source code on + GitLab.

+ + {{ macros.message('info', '' + instance_url + ' is just one instance of ' + app.name, true, true) }} +
+ +
+

Available authentication mechanisms

    -
  • mail.toot.party - a private mail service
  • +
  • Internal (shared database)
  • +
  • Integrated LDAP server
-

Authentication mechanisms

+

Useful resources

+
    -
  • Internal (shared database)
  • -
  • LDAP
  • +
  • ISP mail guide to setup your own mail server
-{% endblock %} \ No newline at end of file +{% endblock %} diff --git a/views/account.njk b/views/account.njk index 3d5fa1d..163095b 100644 --- a/views/account.njk +++ b/views/account.njk @@ -1,6 +1,6 @@ {% extends 'layouts/base.njk' %} -{% set title = 'ALDAP - Welcome to the toot.party auth center!' %} +{% set title = app.name + ' - Account' %} {% block body %}
@@ -46,7 +46,7 @@ onclick="return confirm('Are you sure you want to set {{ email.email }} as your main address?');"> Set as main address - {{ macros.csrf(getCSRFToken) }} + {{ macros.csrf(getCsrfToken) }}
@@ -56,7 +56,7 @@ onclick="return confirm('Are you sure you want to delete {{ email.email }}?');"> Remove - {{ macros.csrf(getCSRFToken) }} + {{ macros.csrf(getCsrfToken) }}
@@ -72,7 +72,7 @@ - {{ macros.csrf(getCSRFToken) }} + {{ macros.csrf(getCsrfToken) }} @@ -104,7 +104,7 @@ Delete - {{ macros.csrf(getCSRFToken) }} + {{ macros.csrf(getCsrfToken) }} @@ -131,8 +131,8 @@ - {{ macros.csrf(getCSRFToken) }} + {{ macros.csrf(getCsrfToken) }}
-{% endblock %} \ No newline at end of file +{% endblock %} diff --git a/views/backend/mail_domain.njk b/views/backend/mail_domain.njk index 861bc85..e861003 100644 --- a/views/backend/mail_domain.njk +++ b/views/backend/mail_domain.njk @@ -18,8 +18,8 @@ - {{ macros.csrf(getCSRFToken) }} + {{ macros.csrf(getCsrfToken) }} -{% endblock %} \ No newline at end of file +{% endblock %} diff --git a/views/backend/mailbox.njk b/views/backend/mailbox.njk index 773bd51..771326f 100644 --- a/views/backend/mailbox.njk +++ b/views/backend/mailbox.njk @@ -36,7 +36,7 @@ Delete - {{ macros.csrf(getCSRFToken) }} + {{ macros.csrf(getCsrfToken) }} @@ -55,8 +55,8 @@ - {{ macros.csrf(getCSRFToken) }} + {{ macros.csrf(getCsrfToken) }} -{% endblock %} \ No newline at end of file +{% endblock %} diff --git a/views/backend/mailboxes.njk b/views/backend/mailboxes.njk index 1f9dc20..ded89c7 100644 --- a/views/backend/mailboxes.njk +++ b/views/backend/mailboxes.njk @@ -21,7 +21,7 @@ - {{ macros.csrf(getCSRFToken) }} + {{ macros.csrf(getCsrfToken) }} @@ -55,7 +55,7 @@ Remove - {{ macros.csrf(getCSRFToken) }} + {{ macros.csrf(getCsrfToken) }} @@ -98,4 +98,4 @@
-{% endblock %} \ No newline at end of file +{% endblock %} diff --git a/views/home.njk b/views/home.njk index 057622b..04036fe 100644 --- a/views/home.njk +++ b/views/home.njk @@ -1,7 +1,7 @@ {% extends 'layouts/base.njk' %} -{% set title = app.name + ' - Welcome to the toot.party auth center!' %} +{% set title = app.name + ' - Say no to GAFAMs' %} {% block body %}

{{ title }}

-{% endblock %} \ No newline at end of file +{% endblock %} diff --git a/views/layouts/base.njk b/views/layouts/base.njk index 7192bfd..0412b17 100644 --- a/views/layouts/base.njk +++ b/views/layouts/base.njk @@ -16,7 +16,8 @@