commit 42d478ec48c441790e9db69bc188297e7f68e074 Author: Arzumify Date: Sat Sep 28 19:41:34 2024 +0100 Initial commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..485dee6 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +.idea diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..5469257 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,660 @@ +# 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 . \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..932e832 --- /dev/null +++ b/README.md @@ -0,0 +1,69 @@ +# Fulgens Web Server +A simple and fast plugin-based web server written in Golang. + +It utilises Chi and the Go standard library to provide a fast and efficient web server, with the ability to add plugins to extend its functionality. + +## Features +- Fast and efficient +- Plugin-based +- Easy to use +- Comes with OAuth2 and Blob storage (known as the "nucleus" services) +- SQLite and PostgreSQL support +- Easy to extend + +## Installation +To install, git clone the repository: +```sh +git clone https://git.ailur.dev/Ailur/fulgens.git --depth 1 +``` + +Then, build the server: +```sh +./build.sh +``` + +## Usage +To run the server, simply run the binary: +```sh +./fulgens +``` + +## Configuration +The server can be configured using a `config.json` file. An example configuration file is provided in the repository. +### Global +- `port` - The port the server listens on +- `ip` - The IP address the server listens on +- `serviceDirectory` - The directory where services are stored +- `resourceDirectory` - The directory where service resources are stored +### Logging +- `enabled` - Whether file logging is enabled +- `file` - The file to log to +### Database +- `type` - The type of database to use (sqlite or postgres) +- `connectionString` - The connection string for the database (postgres only) +- `databasePath` - The **directory** to store the databases (sqlite only) +It is necessary to have a separate directory for each service, as SQLite does not support multiple schemas in a single file. +### Services +#### For all services +- `subdomain` - The subdomain the service is hosted on (optional, will run on the root domain if not specified) +#### Storage +**Note** the storage service is unfinished and should not be used in production. +- `path` - The path to store blobs +- `defaultQuota` - The maximum size of the storage in bytes +#### Auth +- `privacyPolicy` - The URL to the privacy policy +- `url` - The URL it is being hosted on +- `testAppEnabled` - Whether to enable the OAuth2 test app +- `testAppIsInteralApp` - Whether the test app should have seamless logon like an internal service (required if `testAppEnabled` is true) +- `identifier` - The name of the OAuth2 service +- `adminKey` - The key used to access the admin panel and list users + +## Contributing +Contributions are welcome! Please open a pull request with your changes. + +## Plugin development +Plugins require the use of the `library` package, found [here](https://pkg.go.dev/git.ailur.dev/Ailur/fulgens/library). +This provides them with the necessary resources to interact with the rest of the server + +## Enterprise support +For enterprise support, please visit [Ailur Enterprise](https://ailur.dev/enterprise). \ No newline at end of file diff --git a/build.sh b/build.sh new file mode 100755 index 0000000..ba9a75d --- /dev/null +++ b/build.sh @@ -0,0 +1,13 @@ +#!/bin/sh +path=$(realpath "$(dirname "$0")") || exit 1 +search_dir="$path/services-src" +find "$search_dir" -type f -name "build.sh" | while read -r build_script; do + echo "Running $build_script..." + build_dir=$(dirname "$build_script") + (cd "$build_dir" && ./build.sh) || { + echo "Error: $build_script failed." + exit 1 + } +done +go build --ldflags "-s -w" -o "$path/fulgens" || exit 1 +echo "Fulgens has been built successfully." diff --git a/config.json b/config.json new file mode 100644 index 0000000..54fda0c --- /dev/null +++ b/config.json @@ -0,0 +1,29 @@ +{ + "global": { + "ip": "0.0.0.0", + "port": "8000", + "serviceDirectory": "./services", + "resourceDirectory": "./resources" + }, + "logging": { + "enabled": true, + "file": "fulgens.log" + }, + "database": { + "databaseType": "sqlite", + "databasePath": "./databases" + }, + "services": { + "storage": { + "path": "./blob" + }, + "auth": { + "privacyPolicy": "https://git.ailur.dev/Paperwork/nucleus/src/commit/5d191eea87cffae8bdca42017ac26dc19e6cb3de/Privacy.md", + "url": "http://localhost:8000", + "identifier": "Authenticator", + "adminKey": "supersecretkey", + "testAppIsInternalApp": true, + "testAppEnabled": true + } + } +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..542cf33 --- /dev/null +++ b/go.mod @@ -0,0 +1,36 @@ +module git.ailur.dev/ailur/fulgens + +go 1.23.0 + +require ( + git.ailur.dev/ailur/pow-argon2 v0.0.0-20240922143345-8f9af6dce3a5 + github.com/cespare/xxhash/v2 v2.3.0 + github.com/go-chi/chi v1.5.5 + github.com/go-playground/validator/v10 v10.22.1 + github.com/golang-jwt/jwt v3.2.2+incompatible + github.com/google/uuid v1.6.0 + github.com/lib/pq v1.10.9 + golang.org/x/crypto v0.27.0 + modernc.org/sqlite v1.33.1 +) + +require ( + github.com/dustin/go-humanize v1.0.1 // indirect + github.com/gabriel-vasile/mimetype v1.4.3 // indirect + github.com/go-playground/locales v0.14.1 // indirect + github.com/go-playground/universal-translator v0.18.1 // indirect + github.com/hashicorp/golang-lru/v2 v2.0.7 // indirect + github.com/leodido/go-urn v1.4.0 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect + github.com/ncruces/go-strftime v0.1.9 // indirect + github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect + golang.org/x/net v0.21.0 // indirect + golang.org/x/sys v0.25.0 // indirect + golang.org/x/text v0.18.0 // indirect + modernc.org/gc/v3 v3.0.0-20240107210532-573471604cb6 // indirect + modernc.org/libc v1.55.3 // indirect + modernc.org/mathutil v1.6.0 // indirect + modernc.org/memory v1.8.0 // indirect + modernc.org/strutil v1.2.0 // indirect + modernc.org/token v1.1.0 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..2f6e606 --- /dev/null +++ b/go.sum @@ -0,0 +1,85 @@ +git.ailur.dev/ailur/pow-argon2 v0.0.0-20240922143345-8f9af6dce3a5 h1:QGICG5QsXtGVDV0YjR4bXiEV2kWQ96riPR9qFWuFpr4= +git.ailur.dev/ailur/pow-argon2 v0.0.0-20240922143345-8f9af6dce3a5/go.mod h1:dDulL+Bfr47BPmvSPRkRD3uOVNsfM6yOTwhdAkctZU4= +github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= +github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= +github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= +github.com/gabriel-vasile/mimetype v1.4.3 h1:in2uUcidCuFcDKtdcBxlR0rJ1+fsokWf+uqxgUFjbI0= +github.com/gabriel-vasile/mimetype v1.4.3/go.mod h1:d8uq/6HKRL6CGdk+aubisF/M5GcPfT7nKyLpA0lbSSk= +github.com/go-chi/chi v1.5.5 h1:vOB/HbEMt9QqBqErz07QehcOKHaWFtuj87tTDVz2qXE= +github.com/go-chi/chi v1.5.5/go.mod h1:C9JqLr3tIYjDOZpzn+BCuxY8z8vmca43EeMgyZt7irw= +github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s= +github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= +github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= +github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= +github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY= +github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= +github.com/go-playground/validator/v10 v10.22.1 h1:40JcKH+bBNGFczGuoBYgX4I6m/i27HYW8P9FDk5PbgA= +github.com/go-playground/validator/v10 v10.22.1/go.mod h1:dbuPbCMFw/DrkbEynArYaCwl3amGuJotoKCe95atGMM= +github.com/golang-jwt/jwt v3.2.2+incompatible h1:IfV12K8xAKAnZqdXVzCZ+TOjboZ2keLg81eXfW3O+oY= +github.com/golang-jwt/jwt v3.2.2+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzqecmYZeUEB8OUGHkxJ+I= +github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd h1:gbpYu9NMq8jhDVbvlGkMFWCjLFlqqEZjEmObmhUy6Vo= +github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd/go.mod h1:kf6iHlnVGwgKolg33glAes7Yg/8iWP8ukqeldJSO7jw= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k= +github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM= +github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ= +github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI= +github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw= +github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/ncruces/go-strftime v0.1.9 h1:bY0MQC28UADQmHmaF5dgpLmImcShSi2kHU9XLdhx/f4= +github.com/ncruces/go-strftime v0.1.9/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= +github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= +github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +golang.org/x/crypto v0.27.0 h1:GXm2NjJrPaiv/h1tb2UH8QfgC/hOf/+z0p6PT8o1w7A= +golang.org/x/crypto v0.27.0/go.mod h1:1Xngt8kV6Dvbssa53Ziq6Eqn0HqbZi5Z6R0ZpwQzt70= +golang.org/x/mod v0.17.0 h1:zY54UmvipHiNd+pm+m0x9KhZ9hl1/7QNMyxXbc6ICqA= +golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= +golang.org/x/net v0.21.0 h1:AQyQV4dYCvJ7vGmJyKki9+PBdyvhkSd8EIx/qb0AYv4= +golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44= +golang.org/x/sync v0.8.0 h1:3NFvSEYkUoMifnESzZl15y791HH1qU2xm6eCJU5ZPXQ= +golang.org/x/sync v0.8.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.25.0 h1:r+8e+loiHxRqhXVl6ML1nO3l1+oFoWbnlu2Ehimmi34= +golang.org/x/sys v0.25.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/text v0.18.0 h1:XvMDiNzPAl0jr17s6W9lcaIhGUfUORdGCNsuLmPG224= +golang.org/x/text v0.18.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY= +golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d h1:vU5i/LfpvrRCpgM/VPfJLg5KjxD3E+hfT1SH+d9zLwg= +golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +modernc.org/cc/v4 v4.21.4 h1:3Be/Rdo1fpr8GrQ7IVw9OHtplU4gWbb+wNgeoBMmGLQ= +modernc.org/cc/v4 v4.21.4/go.mod h1:HM7VJTZbUCR3rV8EYBi9wxnJ0ZBRiGE5OeGXNA0IsLQ= +modernc.org/ccgo/v4 v4.19.2 h1:lwQZgvboKD0jBwdaeVCTouxhxAyN6iawF3STraAal8Y= +modernc.org/ccgo/v4 v4.19.2/go.mod h1:ysS3mxiMV38XGRTTcgo0DQTeTmAO4oCmJl1nX9VFI3s= +modernc.org/fileutil v1.3.0 h1:gQ5SIzK3H9kdfai/5x41oQiKValumqNTDXMvKo62HvE= +modernc.org/fileutil v1.3.0/go.mod h1:XatxS8fZi3pS8/hKG2GH/ArUogfxjpEKs3Ku3aK4JyQ= +modernc.org/gc/v2 v2.4.1 h1:9cNzOqPyMJBvrUipmynX0ZohMhcxPtMccYgGOJdOiBw= +modernc.org/gc/v2 v2.4.1/go.mod h1:wzN5dK1AzVGoH6XOzc3YZ+ey/jPgYHLuVckd62P0GYU= +modernc.org/gc/v3 v3.0.0-20240107210532-573471604cb6 h1:5D53IMaUuA5InSeMu9eJtlQXS2NxAhyWQvkKEgXZhHI= +modernc.org/gc/v3 v3.0.0-20240107210532-573471604cb6/go.mod h1:Qz0X07sNOR1jWYCrJMEnbW/X55x206Q7Vt4mz6/wHp4= +modernc.org/libc v1.55.3 h1:AzcW1mhlPNrRtjS5sS+eW2ISCgSOLLNyFzRh/V3Qj/U= +modernc.org/libc v1.55.3/go.mod h1:qFXepLhz+JjFThQ4kzwzOjA/y/artDeg+pcYnY+Q83w= +modernc.org/mathutil v1.6.0 h1:fRe9+AmYlaej+64JsEEhoWuAYBkOtQiMEU7n/XgfYi4= +modernc.org/mathutil v1.6.0/go.mod h1:Ui5Q9q1TR2gFm0AQRqQUaBWFLAhQpCwNcuhBOSedWPo= +modernc.org/memory v1.8.0 h1:IqGTL6eFMaDZZhEWwcREgeMXYwmW83LYW8cROZYkg+E= +modernc.org/memory v1.8.0/go.mod h1:XPZ936zp5OMKGWPqbD3JShgd/ZoQ7899TUuQqxY+peU= +modernc.org/opt v0.1.3 h1:3XOZf2yznlhC+ibLltsDGzABUGVx8J6pnFMS3E4dcq4= +modernc.org/opt v0.1.3/go.mod h1:WdSiB5evDcignE70guQKxYUl14mgWtbClRi5wmkkTX0= +modernc.org/sortutil v1.2.0 h1:jQiD3PfS2REGJNzNCMMaLSp/wdMNieTbKX920Cqdgqc= +modernc.org/sortutil v1.2.0/go.mod h1:TKU2s7kJMf1AE84OoiGppNHJwvB753OYfNl2WRb++Ss= +modernc.org/sqlite v1.33.1 h1:trb6Z3YYoeM9eDL1O8do81kP+0ejv+YzgyFo+Gwy0nM= +modernc.org/sqlite v1.33.1/go.mod h1:pXV2xHxhzXZsgT/RtTFAPY6JJDEvOTcTdwADQCCWD4k= +modernc.org/strutil v1.2.0 h1:agBi9dp1I+eOnxXeiZawM8F4LawKv4NzGWSaLfyeNZA= +modernc.org/strutil v1.2.0/go.mod h1:/mdcBmfOibveCTBxUl5B5l6W+TTH1FXPLHZE6bTosX0= +modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y= +modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM= diff --git a/library/main.go b/library/main.go new file mode 100644 index 0000000..8610c00 --- /dev/null +++ b/library/main.go @@ -0,0 +1,40 @@ +package library + +import ( + "github.com/go-chi/chi" + "github.com/google/uuid" + "io/fs" + "time" +) + +type Permissions struct { + Authenticate bool `validate:"required"` + Database bool `validate:"required"` + BlobStorage bool `validate:"required"` + InterServiceCommunication bool `validate:"required"` + Resources bool `validate:"required"` +} + +type Service struct { + Name string `validate:"required"` + Permissions Permissions `validate:"required"` + ServiceID uuid.UUID `validate:"required"` +} + +type InterServiceMessage struct { + ServiceID uuid.UUID `validate:"required"` + ForServiceID uuid.UUID `validate:"required"` + MessageType uint64 `validate:"required"` + SentAt time.Time `validate:"required"` + Message any `validate:"required"` +} + +type ServiceInitializationInformation struct { + ServiceID uuid.UUID `validate:"required"` + Domain string `validate:"required"` + Outbox chan<- InterServiceMessage `validate:"required"` + Inbox <-chan InterServiceMessage `validate:"required"` + Router *chi.Mux `validate:"required"` + Configuration map[string]interface{} + ResourceDir fs.FS +} diff --git a/main.go b/main.go new file mode 100644 index 0000000..519b6b0 --- /dev/null +++ b/main.go @@ -0,0 +1,694 @@ +package main + +import ( + "errors" + "fmt" + "git.ailur.dev/ailur/fulgens/library" + "github.com/go-chi/chi/middleware" + "io" + "log" + "os" + "plugin" + "sort" + "time" + + "database/sql" + "encoding/json" + "log/slog" + "net/http" + "path/filepath" + + "github.com/go-chi/chi" + "github.com/go-playground/validator/v10" + "github.com/google/uuid" + + _ "github.com/lib/pq" + _ "modernc.org/sqlite" +) + +type Config struct { + Global struct { + IP string `json:"ip" validate:"required,ip_addr"` + Port string `json:"port" validate:"required"` + ServiceDirectory string `json:"serviceDirectory" validate:"required"` + ResourceDirectory string `json:"resourceDirectory" validate:"required"` + } `json:"global" validate:"required"` + Logging struct { + Enabled bool `json:"enabled"` + File string `json:"file" validate:"required_if=Enabled true"` + } `json:"logging"` + Database struct { + DatabaseType string `json:"databaseType" validate:"required,oneof=sqlite postgres"` + ConnectionString string `json:"connectionString" validate:"required_if=DatabaseType postgres"` + DatabasePath string `json:"databasePath" validate:"required_if=DatabaseType sqlite,isDirectory"` + } `json:"database" validate:"required"` + Services map[string]interface{} `json:"services"` +} + +type ActiveService struct { + ServiceID uuid.UUID + Inbox chan library.InterServiceMessage + ActivationConfirmed bool +} + +var ( + logger = func(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + next.ServeHTTP(w, r) + slog.Info(r.Method + " " + r.URL.Path) + }) + } + validate *validator.Validate + activeServices = make(map[uuid.UUID]ActiveService) + services = make(map[uuid.UUID]library.Service) +) + +func processInterServiceMessage(channel chan library.InterServiceMessage, config Config) { + for { + message := <-channel + if message.ForServiceID == uuid.MustParse("00000000-0000-0000-0000-000000000000") { + // Broadcast message + for _, service := range activeServices { + // We don't want to overwhelm a non-activated service + if service.ActivationConfirmed { + service.Inbox <- message + } + } + } else if message.ForServiceID == uuid.MustParse("00000000-0000-0000-0000-000000000001") { + // Service initialization service + switch message.MessageType { + case 0: + // Service initialization message, register the service + inbox := activeServices[message.ServiceID].Inbox + activeServices[message.ServiceID] = ActiveService{ + ServiceID: message.ServiceID, + Inbox: inbox, + ActivationConfirmed: true, + } + // Report a successful activation + inbox <- library.InterServiceMessage{ + ServiceID: uuid.MustParse("00000000-0000-0000-0000-000000000001"), + ForServiceID: message.ServiceID, + MessageType: 0, + SentAt: time.Now(), + Message: true, + } + case 1: + // Service database initialization message + // Check if the service has the necessary permissions + if services[message.ServiceID].Permissions.Database { + // Check if we are using sqlite or postgres + if config.Database.DatabaseType == "sqlite" { + // Open the database and return the connection + pluginConn, err := sql.Open("sqlite", filepath.Join(config.Database.DatabasePath, message.ServiceID.String()+".db")) + if err != nil { + // Report an error + activeServices[message.ServiceID].Inbox <- library.InterServiceMessage{ + ServiceID: uuid.MustParse("00000000-0000-0000-0000-000000000001"), + ForServiceID: message.ServiceID, + MessageType: 1, + SentAt: time.Now(), + Message: err, + } + } else { + // Report a successful activation + activeServices[message.ServiceID].Inbox <- library.InterServiceMessage{ + ServiceID: uuid.MustParse("00000000-0000-0000-0000-000000000001"), + ForServiceID: message.ServiceID, + MessageType: 2, + SentAt: time.Now(), + Message: pluginConn, + } + } + } else if config.Database.DatabaseType == "postgres" { + // Connect to the database + conn, err := sql.Open("postgres", config.Database.ConnectionString) + if err != nil { + // Report an error + activeServices[message.ServiceID].Inbox <- library.InterServiceMessage{ + ServiceID: uuid.MustParse("00000000-0000-0000-0000-000000000001"), + ForServiceID: message.ServiceID, + MessageType: 1, + SentAt: time.Now(), + Message: err, + } + } else { + // Try to create the schema + _, err = conn.Exec("CREATE SCHEMA IF NOT EXISTS " + message.ServiceID.String()) + if err != nil { + // Report an error + activeServices[message.ServiceID].Inbox <- library.InterServiceMessage{ + ServiceID: uuid.MustParse("00000000-0000-0000-0000-000000000001"), + ForServiceID: message.ServiceID, + MessageType: 1, + SentAt: time.Now(), + Message: err, + } + } else { + // Create a new connection to the database + pluginConn, err := sql.Open("postgres", config.Database.ConnectionString+" dbname="+message.ServiceID.String()) + if err != nil { + // Report an error + activeServices[message.ServiceID].Inbox <- library.InterServiceMessage{ + ServiceID: uuid.MustParse("00000000-0000-0000-0000-000000000001"), + ForServiceID: message.ServiceID, + MessageType: 1, + SentAt: time.Now(), + Message: err, + } + } else { + // Try to switch schemas + _, err = pluginConn.Exec("SET search_path TO " + message.ServiceID.String()) + if err != nil { + // Report an error + activeServices[message.ServiceID].Inbox <- library.InterServiceMessage{ + ServiceID: uuid.MustParse("00000000-0000-0000-0000-000000000001"), + ForServiceID: message.ServiceID, + MessageType: 1, + SentAt: time.Now(), + Message: err, + } + } else { + // Report a successful activation + activeServices[message.ServiceID].Inbox <- library.InterServiceMessage{ + ServiceID: uuid.MustParse("00000000-0000-0000-0000-000000000001"), + ForServiceID: message.ServiceID, + MessageType: 2, + SentAt: time.Now(), + Message: pluginConn, + } + } + } + } + } + } + } else { + // Report an error + activeServices[message.ServiceID].Inbox <- library.InterServiceMessage{ + ServiceID: uuid.MustParse("00000000-0000-0000-0000-000000000001"), + ForServiceID: message.ServiceID, + MessageType: 1, + SentAt: time.Now(), + Message: errors.New("database access not permitted"), + } + } + } + } else if message.ForServiceID == uuid.MustParse("00000000-0000-0000-0000-000000000002") { + // Logger service + service, ok := services[message.ServiceID] + if ok { + if message.MessageType == 0 { + // Log message + slog.Info(service.Name + " says: " + message.Message.(string)) + } else if message.MessageType == 1 { + // Warn message + slog.Warn(service.Name + " warns: " + message.Message.(string)) + } else if message.MessageType == 2 { + // Error message + slog.Error(service.Name + " complains: " + message.Message.(string)) + } else { + // Fatal message + slog.Error(service.Name + "'s dying wish: " + message.Message.(string)) + os.Exit(1) + } + } + } else if message.ForServiceID == uuid.MustParse("00000000-0000-0000-0000-000000000003") { + // We need to check if the service is allowed to access the Blob Storage service + serviceMetadata, ok := services[message.ServiceID] + if ok && serviceMetadata.Permissions.BlobStorage { + // Send message to Blob Storage service + service, ok := activeServices[uuid.MustParse("00000000-0000-0000-0000-000000000003")] + if ok && service.ActivationConfirmed { + service.Inbox <- message + } else if !ok { + // Send error message + service, ok := activeServices[message.ServiceID] + if ok { + service.Inbox <- library.InterServiceMessage{ + ServiceID: uuid.MustParse("00000000-0000-0000-0000-000000000001"), + ForServiceID: message.ServiceID, + MessageType: 1, + SentAt: time.Now(), + Message: errors.New("blob storage service not found"), + } + } else { + // This should never happen + slog.Error("Bit flip error: Impossible service ID. Move away from radiation or use ECC memory.") + os.Exit(1) + } + } else { + // Send error message + service, ok := activeServices[message.ServiceID] + if ok { + service.Inbox <- library.InterServiceMessage{ + ServiceID: uuid.MustParse("00000000-0000-0000-0000-000000000001"), + ForServiceID: message.ServiceID, + MessageType: 1, + SentAt: time.Now(), + Message: errors.New("blob storage is not yet available"), + } + } else { + // This should never happen + slog.Error("Bit flip error: Impossible service ID. Move away from radiation or use ECC memory.") + os.Exit(1) + } + } + } else { + // Send error message + service, ok := activeServices[message.ServiceID] + if ok { + service.Inbox <- library.InterServiceMessage{ + ServiceID: uuid.MustParse("00000000-0000-0000-0000-000000000001"), + ForServiceID: message.ServiceID, + MessageType: 1, + SentAt: time.Now(), + Message: errors.New("blob storage is not permitted"), + } + } else { + // This should never happen + slog.Error("Bit flip error: Impossible service ID. Move away from radiation or use ECC memory.") + fmt.Println(message.ServiceID, message.ForServiceID) + os.Exit(1) + } + } + } else if message.ForServiceID == uuid.MustParse("00000000-0000-0000-0000-000000000004") { + // We need to check if the service is allowed to access the Authentication service + serviceMetadata, ok := services[message.ServiceID] + if ok && serviceMetadata.Permissions.Authenticate { + // Send message to Authentication service + service, ok := activeServices[uuid.MustParse("00000000-0000-0000-0000-000000000004")] + if ok && service.ActivationConfirmed { + service.Inbox <- message + } else if !ok { + // Send error message + service, ok := activeServices[message.ServiceID] + if ok { + service.Inbox <- library.InterServiceMessage{ + ServiceID: uuid.MustParse("00000000-0000-0000-0000-000000000001"), + ForServiceID: message.ServiceID, + MessageType: 1, + SentAt: time.Now(), + Message: errors.New("authentication service not found"), + } + } else { + // This should never happen + slog.Error("Bit flip error: Impossible service ID. Move away from radiation or use ECC memory.") + os.Exit(1) + } + } else { + // Send error message + service, ok := activeServices[message.ServiceID] + if ok { + service.Inbox <- library.InterServiceMessage{ + ServiceID: uuid.MustParse("00000000-0000-0000-0000-000000000001"), + ForServiceID: message.ServiceID, + MessageType: 1, + SentAt: time.Now(), + Message: errors.New("authentication service not yet available"), + } + } else { + // This should never happen + slog.Error("Bit flip error: Impossible service ID. Move away from radiation or use ECC memory.") + os.Exit(1) + } + } + } else { + // Send error message + service, ok := activeServices[message.ServiceID] + if ok { + service.Inbox <- library.InterServiceMessage{ + ServiceID: uuid.MustParse("00000000-0000-0000-0000-000000000001"), + ForServiceID: message.ServiceID, + MessageType: 1, + SentAt: time.Now(), + Message: errors.New("authentication not permitted"), + } + } else { + // This should never happen + slog.Error("Bit flip error: Impossible service ID. Move away from radiation or use ECC memory.") + os.Exit(1) + } + } + } else { + serviceMetadata, ok := services[message.ServiceID] + if ok && serviceMetadata.Permissions.InterServiceCommunication { + // Send message to specific service + service, ok := activeServices[message.ForServiceID] + if ok && service.ActivationConfirmed { + service.Inbox <- message + } else if !ok { + // Send error message + service, ok := activeServices[message.ServiceID] + if ok { + service.Inbox <- library.InterServiceMessage{ + ServiceID: uuid.MustParse("00000000-0000-0000-0000-000000000001"), + ForServiceID: message.ServiceID, + MessageType: 1, + SentAt: time.Now(), + Message: errors.New("requested service not found"), + } + } else { + // This should never happen + slog.Error("Bit flip error: Impossible service ID. Move away from radiation or use ECC memory.") + os.Exit(1) + } + } else { + // Send error message + service, ok := activeServices[message.ServiceID] + if ok { + service.Inbox <- library.InterServiceMessage{ + ServiceID: uuid.MustParse("00000000-0000-0000-0000-000000000001"), + ForServiceID: message.ServiceID, + MessageType: 1, + SentAt: time.Now(), + Message: errors.New("requested service not yet available"), + } + } else { + // This should never happen + slog.Error("Bit flip error: Impossible service ID. Move away from radiation or use ECC memory.") + os.Exit(1) + } + } + } else { + // Send error message + service, ok := activeServices[message.ServiceID] + if ok { + service.Inbox <- library.InterServiceMessage{ + ServiceID: uuid.MustParse("00000000-0000-0000-0000-000000000001"), + ForServiceID: message.ServiceID, + MessageType: 1, + SentAt: time.Now(), + Message: errors.New("inter-service communication not permitted"), + } + } else { + // This should never happen + slog.Error("Bit flip error: Impossible service ID. Move away from radiation or use ECC memory.") + os.Exit(1) + } + } + } + } +} + +func parseConfig(path string) Config { + // Register the custom validators + validate = validator.New() + + // Register the custom isDirectory validator + err := validate.RegisterValidation("isDirectory", func(fl validator.FieldLevel) bool { + // Check if it exists + fileInfo, err := os.Stat(fl.Field().String()) + if err != nil { + return false + } + + // Check if it is a directory + return fileInfo.IsDir() + }) + if err != nil { + slog.Error("Error registering custom validator: ", err) + os.Exit(1) + } + + // Parse the configuration file + configFile, err := os.ReadFile(path) + if err != nil { + slog.Error("Error reading configuration file: ", err) + os.Exit(1) + } + + // Parse the configuration file + var config Config + err = json.Unmarshal(configFile, &config) + if err != nil { + slog.Error("Error parsing configuration file: ", err) + os.Exit(1) + } + + // Validate the configuration + err = validate.Struct(config) + if err != nil { + slog.Error(fmt.Sprintf("Invalid configuration: \n%s", err)) + os.Exit(1) + } + + // Check if we are logging to a file + if config.Logging != (Config{}.Logging) && config.Logging.Enabled { + // Check if the log file is set + logFilePath := config.Logging.File + + // Set the log file + logFile, err := os.OpenFile(logFilePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) + if err != nil { + slog.Error("Error opening log file: ", err) + os.Exit(1) + } + + log.SetOutput(io.MultiWriter(os.Stdout, logFile)) + } + + return config +} + +func main() { + // Parse the configuration file + var config Config + if len(os.Args) < 2 { + info, err := os.Stat("config.json") + if err != nil { + if errors.Is(err, os.ErrNotExist) { + slog.Error("No configuration file provided") + os.Exit(1) + } else { + slog.Error("Error reading configuration file: ", err) + os.Exit(1) + } + } + + if info.IsDir() { + slog.Error("No configuration file provided") + os.Exit(1) + } + + config = parseConfig("config.json") + } else { + config = parseConfig(os.Args[1]) + } + + // Create the router + router := chi.NewRouter() + router.Use(logger) + + var globalOutbox = make(chan library.InterServiceMessage) + + // Initialize the service discovery, health-check, and logging services + // Since these are core services, always allocate them the service IDs 0, 1, and 2 + // These are not dynamically loaded, as they are integral to the system functioning + go processInterServiceMessage(globalOutbox, config) + + // Initialize the storage service + // The storage service does not need a subdomain + // Since it is a core service, always allocate it the service ID 3 + // Load it from the services directory + storagePlugin, err := plugin.Open(config.Global.ServiceDirectory + "/storage.fgs") + if err != nil { + slog.Error("Could not load blob storage service: ", err) + os.Exit(1) + } + + // Load up the service information + storageServiceInformation, err := storagePlugin.Lookup("ServiceInformation") + if err != nil { + slog.Error("Blob storage service lacks necessary information: ", err) + os.Exit(1) + } + + services[uuid.MustParse("00000000-0000-0000-0000-000000000003")] = *storageServiceInformation.(*library.Service) + + // Load up the main function + storageMain, err := storagePlugin.Lookup("Main") + if err != nil { + slog.Error("Blob storage service lacks necessary main function: ", err) + os.Exit(1) + } + + // Initialize the storage service + var storageInbox = make(chan library.InterServiceMessage) + activeServices[uuid.MustParse("00000000-0000-0000-0000-000000000003")] = ActiveService{ + ServiceID: uuid.MustParse("00000000-0000-0000-0000-000000000003"), + Inbox: storageInbox, + ActivationConfirmed: false, + } + + storageMain.(func(library.ServiceInitializationInformation))(library.ServiceInitializationInformation{ + ServiceID: uuid.MustParse("00000000-0000-0000-0000-000000000003"), + Domain: "", + Configuration: config.Services["storage"].(map[string]interface{}), + Outbox: globalOutbox, + Inbox: storageInbox, + }) + + // Initialize the authentication service + // The authentication service does not need a subdomain + // Since it is a core service, always allocate it the service ID 4 + + // Load it from the services directory + authPlugin, err := plugin.Open(config.Global.ServiceDirectory + "/auth.fgs") + if err != nil { + slog.Error("Could not load authentication service: ", err) + os.Exit(1) + } + + // Load up the service information + authServiceInformation, err := authPlugin.Lookup("ServiceInformation") + if err != nil { + slog.Error("Authentication service lacks necessary information: ", err) + os.Exit(1) + } + + services[uuid.MustParse("00000000-0000-0000-0000-000000000004")] = *authServiceInformation.(*library.Service) + + // Load up the main function + authMain, err := authPlugin.Lookup("Main") + if err != nil { + slog.Error("Authentication service lacks necessary main function: ", err) + os.Exit(1) + } + + // Initialize the authentication service + var authInbox = make(chan library.InterServiceMessage) + activeServices[uuid.MustParse("00000000-0000-0000-0000-000000000004")] = ActiveService{ + ServiceID: uuid.MustParse("00000000-0000-0000-0000-000000000004"), + Inbox: authInbox, + ActivationConfirmed: false, + } + + // Check if they want a subdomain + var authRouter *chi.Mux + if config.Services["auth"].(map[string]interface{})["subdomain"] != nil { + subdomainRouter := chi.NewRouter() + router.Use(middleware.RouteHeaders(). + Route("Host", config.Services["auth"].(map[string]interface{})["subdomain"].(string), middleware.New(subdomainRouter)). + Handler) + authRouter = subdomainRouter + } else { + authRouter = router + } + + authMain.(func(library.ServiceInitializationInformation))(library.ServiceInitializationInformation{ + ServiceID: uuid.MustParse("00000000-0000-0000-0000-000000000004"), + Domain: "", + Configuration: config.Services["auth"].(map[string]interface{}), + Outbox: globalOutbox, + Inbox: authInbox, + ResourceDir: os.DirFS(filepath.Join(config.Global.ResourceDirectory, "00000000-0000-0000-0000-000000000004")), + Router: authRouter, + }) + + // Initialize all custom services + plugins := make(map[time.Time]string) + err = filepath.Walk(config.Global.ServiceDirectory, func(path string, info os.FileInfo, err error) error { + if err != nil { + return err + } + + if info.IsDir() || filepath.Ext(path) != ".fgs" || filepath.Base(path) == "auth.fgs" || filepath.Base(path) == "storage.fgs" { + return nil + } + + // Add the plugin to the list of plugins + plugins[info.ModTime()] = path + + return nil + }) + if err != nil { + slog.Error("Error walking the services directory: ", err) + os.Exit(1) + } + + // Sort the plugins by modification time, newest last + var keys []time.Time + for k := range plugins { + keys = append(keys, k) + } + + sort.Slice(keys, func(i, j int) bool { + return keys[i].Before(keys[j]) + }) + + for _, k := range keys { + // Get the plugin path + pluginPath := plugins[k] + + // Load the plugin + servicePlugin, err := plugin.Open(pluginPath) + if err != nil { + slog.Error("Could not load service: ", err) + os.Exit(1) + } + + // Load the service information + serviceInformation, err := servicePlugin.Lookup("ServiceInformation") + if err != nil { + slog.Error("Service lacks necessary information: ", err) + os.Exit(1) + } + + // Load the main function + main, err := servicePlugin.Lookup("Main") + if err != nil { + slog.Error("Service lacks necessary main function: ", err) + os.Exit(1) + } + + // Initialize the service + var inbox = make(chan library.InterServiceMessage) + activeServices[serviceInformation.(*library.Service).ServiceID] = ActiveService{ + ServiceID: serviceInformation.(*library.Service).ServiceID, + Inbox: inbox, + ActivationConfirmed: false, + } + + // Check if they want a subdomain + var finalRouter *chi.Mux + if config.Services[serviceInformation.(*library.Service).Name].(map[string]interface{})["subdomain"] != nil { + subdomainRouter := chi.NewRouter() + router.Use(middleware.RouteHeaders(). + Route("Host", config.Services["auth"].(map[string]interface{})["subdomain"].(string), middleware.New(subdomainRouter)). + Handler) + finalRouter = subdomainRouter + } else { + finalRouter = router + } + + // Check if they want a resource directory + if serviceInformation.(*library.Service).Permissions.Resources { + main.(func(library.ServiceInitializationInformation))(library.ServiceInitializationInformation{ + ServiceID: serviceInformation.(*library.Service).ServiceID, + Domain: serviceInformation.(*library.Service).Name, + Configuration: config.Services[serviceInformation.(*library.Service).Name].(map[string]interface{}), + Outbox: globalOutbox, + Inbox: inbox, + ResourceDir: os.DirFS(filepath.Join(config.Global.ServiceDirectory, serviceInformation.(*library.Service).ServiceID.String())), + Router: finalRouter, + }) + } else { + main.(func(library.ServiceInitializationInformation))(library.ServiceInitializationInformation{ + ServiceID: serviceInformation.(*library.Service).ServiceID, + Domain: serviceInformation.(*library.Service).Name, + Configuration: config.Services[serviceInformation.(*library.Service).Name].(map[string]interface{}), + Outbox: globalOutbox, + Inbox: inbox, + Router: router, + }) + } + } + + // Start the server + slog.Info(fmt.Sprintf("Starting server on %s:%s", config.Global.IP, config.Global.Port)) + err = http.ListenAndServe(config.Global.IP+":"+config.Global.Port, router) + if err != nil { + slog.Error("Error starting server: ", err) + os.Exit(1) + } +} diff --git a/services-src/auth/LICENSE.md b/services-src/auth/LICENSE.md new file mode 100644 index 0000000..969dabb --- /dev/null +++ b/services-src/auth/LICENSE.md @@ -0,0 +1,157 @@ +# GNU LESSER GENERAL PUBLIC LICENSE + +Version 3, 29 June 2007 + +Copyright (C) 2007 Free Software Foundation, Inc. + + +Everyone is permitted to copy and distribute verbatim copies of this +license document, but changing it is not allowed. + +This version of the GNU Lesser General Public License incorporates the +terms and conditions of version 3 of the GNU General Public License, +supplemented by the additional permissions listed below. + +## 0. Additional Definitions. + +As used herein, "this License" refers to version 3 of the GNU Lesser +General Public License, and the "GNU GPL" refers to version 3 of the +GNU General Public License. + +"The Library" refers to a covered work governed by this License, other +than an Application or a Combined Work as defined below. + +An "Application" is any work that makes use of an interface provided +by the Library, but which is not otherwise based on the Library. +Defining a subclass of a class defined by the Library is deemed a mode +of using an interface provided by the Library. + +A "Combined Work" is a work produced by combining or linking an +Application with the Library. The particular version of the Library +with which the Combined Work was made is also called the "Linked +Version". + +The "Minimal Corresponding Source" for a Combined Work means the +Corresponding Source for the Combined Work, excluding any source code +for portions of the Combined Work that, considered in isolation, are +based on the Application, and not on the Linked Version. + +The "Corresponding Application Code" for a Combined Work means the +object code and/or source code for the Application, including any data +and utility programs needed for reproducing the Combined Work from the +Application, but excluding the System Libraries of the Combined Work. + +## 1. Exception to Section 3 of the GNU GPL. + +You may convey a covered work under sections 3 and 4 of this License +without being bound by section 3 of the GNU GPL. + +## 2. Conveying Modified Versions. + +If you modify a copy of the Library, and, in your modifications, a +facility refers to a function or data to be supplied by an Application +that uses the facility (other than as an argument passed when the +facility is invoked), then you may convey a copy of the modified +version: + +- a) under this License, provided that you make a good faith effort + to ensure that, in the event an Application does not supply the + function or data, the facility still operates, and performs + whatever part of its purpose remains meaningful, or +- b) under the GNU GPL, with none of the additional permissions of + this License applicable to that copy. + +## 3. Object Code Incorporating Material from Library Header Files. + +The object code form of an Application may incorporate material from a +header file that is part of the Library. You may convey such object +code under terms of your choice, provided that, if the incorporated +material is not limited to numerical parameters, data structure +layouts and accessors, or small macros, inline functions and templates +(ten or fewer lines in length), you do both of the following: + +- a) Give prominent notice with each copy of the object code that + the Library is used in it and that the Library and its use are + covered by this License. +- b) Accompany the object code with a copy of the GNU GPL and this + license document. + +## 4. Combined Works. + +You may convey a Combined Work under terms of your choice that, taken +together, effectively do not restrict modification of the portions of +the Library contained in the Combined Work and reverse engineering for +debugging such modifications, if you also do each of the following: + +- a) Give prominent notice with each copy of the Combined Work that + the Library is used in it and that the Library and its use are + covered by this License. +- b) Accompany the Combined Work with a copy of the GNU GPL and this + license document. +- c) For a Combined Work that displays copyright notices during + execution, include the copyright notice for the Library among + these notices, as well as a reference directing the user to the + copies of the GNU GPL and this license document. +- d) Do one of the following: + - 0) Convey the Minimal Corresponding Source under the terms of + this License, and the Corresponding Application Code in a form + suitable for, and under terms that permit, the user to + recombine or relink the Application with a modified version of + the Linked Version to produce a modified Combined Work, in the + manner specified by section 6 of the GNU GPL for conveying + Corresponding Source. + - 1) Use a suitable shared library mechanism for linking with + the Library. A suitable mechanism is one that (a) uses at run + time a copy of the Library already present on the user's + computer system, and (b) will operate properly with a modified + version of the Library that is interface-compatible with the + Linked Version. +- e) Provide Installation Information, but only if you would + otherwise be required to provide such information under section 6 + of the GNU GPL, and only to the extent that such information is + necessary to install and execute a modified version of the + Combined Work produced by recombining or relinking the Application + with a modified version of the Linked Version. (If you use option + 4d0, the Installation Information must accompany the Minimal + Corresponding Source and Corresponding Application Code. If you + use option 4d1, you must provide the Installation Information in + the manner specified by section 6 of the GNU GPL for conveying + Corresponding Source.) + +## 5. Combined Libraries. + +You may place library facilities that are a work based on the Library +side by side in a single library together with other library +facilities that are not Applications and are not covered by this +License, and convey such a combined library under terms of your +choice, if you do both of the following: + +- a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities, conveyed under the terms of this License. +- b) Give prominent notice with the combined library that part of it + is a work based on the Library, and explaining where to find the + accompanying uncombined form of the same work. + +## 6. Revised Versions of the GNU Lesser General Public License. + +The Free Software Foundation may publish revised and/or new versions +of the GNU Lesser 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 Library +as you received it specifies that a certain numbered version of the +GNU Lesser General Public License "or any later version" applies to +it, you have the option of following the terms and conditions either +of that published version or of any later version published by the +Free Software Foundation. If the Library as you received it does not +specify a version number of the GNU Lesser General Public License, you +may choose any version of the GNU Lesser General Public License ever +published by the Free Software Foundation. + +If the Library as you received it specifies that a proxy can decide +whether future versions of the GNU Lesser General Public License shall +apply, that proxy's public statement of acceptance of any version is +permanent authorization for you to choose that version for the +Library. \ No newline at end of file diff --git a/services-src/auth/build.sh b/services-src/auth/build.sh new file mode 100755 index 0000000..7872946 --- /dev/null +++ b/services-src/auth/build.sh @@ -0,0 +1,23 @@ +#!/bin/sh + +path=$(realpath "$(dirname "$0")") || exit 1 +resourceDir="$path/../../resources/00000000-0000-0000-0000-000000000004" +rm -rf "$resourceDir" || exit 1 +rm -rf "$path/../../services/auth.fgs" || exit 1 +cd "$path" || exit 1 +go build -o "$path/../../services/auth.fgs" --buildmode=plugin -ldflags "-s -w" || exit 1 +mkdir -p "$resourceDir/static/wasm" || exit 1 +cd "$path/resources/wasm/login" || exit 1 +GOOS=js GOARCH=wasm go build -o "$resourceDir/static/wasm/login.wasm" -ldflags "-s -w" || exit 1 +cd "$path/resources/wasm/signup" || exit 1 +GOOS=js GOARCH=wasm go build -o "$resourceDir/static/wasm/signup.wasm" -ldflags "-s -w" || exit 1 +cd "$path/resources/wasm/authorize" || exit 1 +GOOS=js GOARCH=wasm go build -o "$resourceDir/static/wasm/authorize.wasm" -ldflags "-s -w" || exit 1 +cd "$path/resources/wasm/dashboard" || exit 1 +GOOS=js GOARCH=wasm go build -o "$resourceDir/static/wasm/dashboard.wasm" -ldflags "-s -w" || exit 1 +cd "$path/resources/wasm/testApp" || exit 1 +GOOS=js GOARCH=wasm go build -o "$resourceDir/static/wasm/testApp.wasm" -ldflags "-s -w" || exit 1 +cd "$path/resources/wasm/clientKeyShare" || exit 1 +GOOS=js GOARCH=wasm go build -o "$resourceDir/static/wasm/clientKeyShare.wasm" -ldflags "-s -w" || exit 1 +cp -r "$path/resources/static" "$resourceDir/" || exit 1 +cp -r "$path/resources/templates" "$resourceDir/" || exit 1 \ No newline at end of file diff --git a/services-src/auth/library/main.go b/services-src/auth/library/main.go new file mode 100644 index 0000000..d88336a --- /dev/null +++ b/services-src/auth/library/main.go @@ -0,0 +1,14 @@ +package library + +type OAuthInformation struct { + Token string `json:"token"` + Name string `json:"name"` + RedirectUri string `json:"redirectUri"` + KeyShareUri string `json:"keyShareUri"` + Scopes []string `json:"scopes"` +} + +type OAuthResponse struct { + AppID string `json:"appId"` + SecretKey string `json:"secretKey"` +} diff --git a/services-src/auth/main.go b/services-src/auth/main.go new file mode 100644 index 0000000..4986a38 --- /dev/null +++ b/services-src/auth/main.go @@ -0,0 +1,1807 @@ +package main + +import ( + // Fulgens libraries + "git.ailur.dev/ailur/fulgens/library" + authLibrary "git.ailur.dev/ailur/fulgens/services-src/auth/library" + + // First-party libraries + pow "git.ailur.dev/ailur/pow-argon2/library" + + // Standard libraries + "bytes" + "errors" + "io" + "strconv" + "strings" + "time" + + // Secondary libraries + "crypto/ed25519" + "crypto/rand" + "crypto/sha256" + "database/sql" + "encoding/base64" + "encoding/binary" + "encoding/json" + "html/template" + "io/fs" + "net/http" + + // Extra libraries + "golang.org/x/crypto/argon2" + + // External libraries + "github.com/cespare/xxhash/v2" + "github.com/golang-jwt/jwt" + "github.com/google/uuid" + _ "modernc.org/sqlite" +) + +var ServiceInformation = library.Service{ + Name: "Authentication", + Permissions: library.Permissions{ + Authenticate: false, // This service *is* the authentication service + Database: true, // This service does require database access + BlobStorage: false, // This service does not require blob storage + InterServiceCommunication: true, // This service does require inter-service communication + Resources: true, // This service does require its HTTP templates and static files to be served + }, + ServiceID: uuid.MustParse("00000000-0000-0000-0000-000000000004"), +} + +var serviceIDBytes []byte + +func logFunc(message string, messageType uint64, information library.ServiceInitializationInformation) { + // Log the message to the logger service + information.Outbox <- library.InterServiceMessage{ + ServiceID: information.ServiceID, + ForServiceID: uuid.MustParse("00000000-0000-0000-0000-000000000002"), // Logger service + MessageType: messageType, + SentAt: time.Now(), + Message: message, + } +} + +func ensureTrailingSlash(url string) string { + if !strings.HasSuffix(url, "/") { + return url + "/" + } + return url +} + +func randomChars(length int) (string, error) { + var saltChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" + if length <= 0 { + return "", errors.New("salt length must be greater than 0") + } + + salt := make([]byte, length) + randomBytes := make([]byte, length) + _, err := rand.Read(randomBytes) + if err != nil { + return "", err + } + + for i := range salt { + salt[i] = saltChars[int(randomBytes[i])%len(saltChars)] + } + return string(salt), nil +} + +func sha256Base64(s string) string { + hashed := sha256.Sum256([]byte(s)) + encoded := base64.URLEncoding.EncodeToString(hashed[:]) + encoded = strings.TrimRight(encoded, "=") + return encoded +} + +func renderTemplate(statusCode int, w http.ResponseWriter, data map[string]interface{}, templatePath string, information library.ServiceInitializationInformation) { + var err error + var requestedTemplate *template.Template + // Output ls of the resource directory + requestedTemplate, err = template.ParseFS(information.ResourceDir, "templates/"+templatePath) + if err != nil { + logFunc(err.Error(), 2, information) + renderString(500, w, "Sorry, something went wrong on our end. Error code: 01. Please report to the administrator.", information) + } else { + w.WriteHeader(statusCode) + err = requestedTemplate.Execute(w, data) + if err != nil { + logFunc(err.Error(), 2, information) + renderString(500, w, "Sorry, something went wrong on our end. Error code: 02. Please report to the administrator.", information) + } + } +} + +func renderString(statusCode int, w http.ResponseWriter, data string, information library.ServiceInitializationInformation) { + w.WriteHeader(statusCode) + _, err := w.Write([]byte(data)) + if err != nil { + logFunc(err.Error(), 2, information) + } +} + +func renderJSON(statusCode int, w http.ResponseWriter, data map[string]interface{}, information library.ServiceInitializationInformation) { + w.WriteHeader(statusCode) + err := json.NewEncoder(w).Encode(data) + if err != nil { + logFunc(err.Error(), 2, information) + } +} + +func verifyJwt(token string, publicKey ed25519.PublicKey, mem *sql.DB) ([]byte, jwt.MapClaims, bool) { + parsedToken, err := jwt.Parse(token, func(token *jwt.Token) (interface{}, error) { + return publicKey, nil + }) + if err != nil { + return nil, nil, false + } + + if !parsedToken.Valid { + return nil, nil, false + } + + claims, ok := parsedToken.Claims.(jwt.MapClaims) + if !ok { + return nil, nil, false + } + + // Check if the token expired + if claims.VerifyExpiresAt(time.Now().Unix(), true) == false { + return nil, claims, false + } + + // Check if the session exists + var userId []byte + err = mem.QueryRow("SELECT id FROM sessions WHERE session = ?", claims["session"]).Scan(&userId) + if err != nil { + return nil, claims, false + } + + return userId, claims, true +} + +func Main(information library.ServiceInitializationInformation) { + var conn *sql.DB + var mem *sql.DB + var publicKey ed25519.PublicKey + var privateKey ed25519.PrivateKey + // Load the configuration + privacyPolicy := information.Configuration["privacyPolicy"].(string) + hostName := information.Configuration["url"].(string) + testAppIsAvailable := information.Configuration["testAppEnabled"].(bool) + testAppIsInternalApp, ok := information.Configuration["testAppIsInternalApp"].(bool) + if !ok { + testAppIsAvailable = false + } + identifier := information.Configuration["identifier"].(string) + adminKey := information.Configuration["adminKey"].(string) + + var err error + serviceIDBytes, err = ServiceInformation.ServiceID.MarshalBinary() + if err != nil { + logFunc(err.Error(), 3, information) + } + + // Initiate a connection to the database + // Call service ID 1 to get the database connection information + information.Outbox <- library.InterServiceMessage{ + ServiceID: information.ServiceID, + ForServiceID: uuid.MustParse("00000000-0000-0000-0000-000000000001"), // Service initialization service + MessageType: 1, // Request connection information + SentAt: time.Now(), + Message: nil, + } + + // Wait for the response + response := <-information.Inbox + if response.MessageType == 2 { + // This is the connection information + // Set up the database connection + conn = response.Message.(*sql.DB) + // Create the global table + // Uniqueness check is a hack to ensure we only have one global row + _, err := conn.Exec("CREATE TABLE IF NOT EXISTS global (key BLOB NOT NULL, uniquenessCheck BOOLEAN NOT NULL UNIQUE CHECK (uniquenessCheck = true) DEFAULT true)") + // Create the users table + _, err = conn.Exec("CREATE TABLE IF NOT EXISTS users (id BLOB PRIMARY KEY NOT NULL UNIQUE, created INTEGER NOT NULL, username TEXT NOT NULL UNIQUE, password BLOB NOT NULL, salt BLOB NOT NULL)") + if err != nil { + logFunc(err.Error(), 3, information) + } + // Create the oauth table + _, err = conn.Exec("CREATE TABLE IF NOT EXISTS oauth (appId TEXT NOT NULL UNIQUE, secret TEXT, creator BLOB NOT NULL, redirectUri TEXT NOT NULL, name TEXT NOT NULL, keyShareUri TEXT NOT NULL DEFAULT '', scopes TEXT NOT NULL DEFAULT '[\"openid\"]')") + if err != nil { + logFunc(err.Error(), 3, information) + } + // Set up the in-memory cache + mem, err = sql.Open("sqlite", "file:"+ServiceInformation.ServiceID.String()+"?mode=memory&cache=shared") + if err != nil { + logFunc(err.Error(), 3, information) + } + // Create the sessions table + _, err = mem.Exec("CREATE TABLE IF NOT EXISTS sessions (id BLOB NOT NULL, session TEXT NOT NULL, device TEXT NOT NULL DEFAULT '?')") + if err != nil { + logFunc(err.Error(), 3, information) + } + // Create the logins table + _, err = mem.Exec("CREATE TABLE IF NOT EXISTS logins (appId TEXT NOT NULL, exchangeCode TEXT NOT NULL UNIQUE, pkce TEXT, pkceMethod TEXT, openid BOOLEAN NOT NULL, userId BLOB NOT NULL UNIQUE, nonce TEXT NOT NULL DEFAULT '', token TEXT NOT NULL)") + if err != nil { + logFunc(err.Error(), 3, information) + } + // Create the spent PoW table + _, err = mem.Exec("CREATE TABLE IF NOT EXISTS spent (hash BLOB NOT NULL UNIQUE, expires INTEGER NOT NULL)") + if err != nil { + logFunc(err.Error(), 3, information) + } + } else { + // This is an error message + // Log the error message to the logger service + logFunc(response.Message.(error).Error(), 3, information) + } + + // Set up the signing keys + // Check if the global table has the keys + err = conn.QueryRow("SELECT key FROM global LIMIT 1").Scan(&privateKey) + if err != nil { + if errors.Is(err, sql.ErrNoRows) { + // Generate a new key + var err error + publicKey, privateKey, err = ed25519.GenerateKey(rand.Reader) + if err != nil { + logFunc(err.Error(), 3, information) + } + // Insert the key into the global table + _, err = conn.Exec("INSERT INTO global (key) VALUES (?)", privateKey) + if err != nil { + logFunc(err.Error(), 3, information) + } + } else { + logFunc(err.Error(), 3, information) + } + } else { + publicKey = privateKey.Public().(ed25519.PublicKey) + } + + // Set up the test app + _, err = conn.Exec("DELETE FROM oauth WHERE appId = 'TestApp-DoNotUse'") + if err != nil { + testAppIsAvailable = false + logFunc(err.Error(), 2, information) + } + + if testAppIsInternalApp { + _, err = conn.Exec("INSERT INTO oauth (appId, secret, creator, name, redirectUri, scopes, keyShareUri) VALUES ('TestApp-DoNotUse', 'none', ?, 'Test App', ?, '[\"openid\", \"clientKeyShare\"]', ?)", serviceIDBytes, ensureTrailingSlash(hostName)+"testApp", ensureTrailingSlash(hostName)+"keyExchangeTester") + } else { + testAppCreator, err := uuid.New().MarshalBinary() + if err != nil { + testAppIsAvailable = false + logFunc(err.Error(), 2, information) + } + + _, err = conn.Exec("INSERT INTO oauth (appId, secret, creator, name, redirectUri, scopes, keyShareUri) VALUES ('TestApp-DoNotUse', 'none', ?, 'Test App', ?, '[\"openid\", \"clientKeyShare\"]', ?)", testAppCreator, ensureTrailingSlash(hostName)+"testApp", ensureTrailingSlash(hostName)+"keyExchangeTester") + } + if err != nil { + testAppIsAvailable = false + logFunc(err.Error(), 2, information) + } + + // Set up the router + router := information.Router + + // Set up the static routes + staticDir, err := fs.Sub(information.ResourceDir, "static") + if err != nil { + logFunc(err.Error(), 3, information) + } else { + router.Handle("/static/*", http.StripPrefix("/static/", http.FileServerFS(staticDir))) + } + + router.Get("/login", func(w http.ResponseWriter, r *http.Request) { + defer func(Body io.ReadCloser) { + err := Body.Close() + if err != nil { + logFunc(err.Error(), 1, information) + } + }(r.Body) + renderTemplate(200, w, map[string]interface{}{ + "identifier": identifier, + }, "login.html", information) + }) + + router.Get("/signup", func(w http.ResponseWriter, r *http.Request) { + defer func(Body io.ReadCloser) { + err := Body.Close() + if err != nil { + logFunc(err.Error(), 1, information) + } + }(r.Body) + renderTemplate(200, w, map[string]interface{}{ + "identifier": identifier, + }, "signup.html", information) + }) + + router.Get("/logout", func(w http.ResponseWriter, r *http.Request) { + defer func(Body io.ReadCloser) { + err := Body.Close() + if err != nil { + logFunc(err.Error(), 1, information) + } + }(r.Body) + renderTemplate(200, w, map[string]interface{}{ + "identifier": identifier, + }, "logout.html", information) + }) + + router.Get("/privacy", func(w http.ResponseWriter, r *http.Request) { + defer func(Body io.ReadCloser) { + err := Body.Close() + if err != nil { + logFunc(err.Error(), 1, information) + } + }(r.Body) + http.Redirect(w, r, privacyPolicy, 301) + }) + + router.Get("/testApp", func(w http.ResponseWriter, r *http.Request) { + defer func(Body io.ReadCloser) { + err := Body.Close() + if err != nil { + logFunc(err.Error(), 1, information) + } + }(r.Body) + if testAppIsAvailable { + renderTemplate(200, w, map[string]interface{}{ + "identifier": identifier, + }, "testApp.html", information) + } else { + renderTemplate(200, w, map[string]interface{}{ + "identifier": identifier, + }, "testAppNotAvailable.html", information) + } + }) + + router.Get("/authorize", func(w http.ResponseWriter, r *http.Request) { + defer func(Body io.ReadCloser) { + err := Body.Close() + if err != nil { + logFunc(err.Error(), 1, information) + } + }(r.Body) + var name string + var creator []byte + if r.URL.Query().Get("client_id") != "" { + err := conn.QueryRow("SELECT name, creator FROM oauth WHERE appId = ?", r.URL.Query().Get("client_id")).Scan(&name, &creator) + if err != nil { + if errors.Is(err, sql.ErrNoRows) { + renderString(404, w, "App not found", information) + } else { + logFunc(err.Error(), 2, information) + renderString(500, w, "Sorry, something went wrong on our end. Error code: 03. Please report to the administrator.", information) + } + return + } + } + + if !bytes.Equal(creator, serviceIDBytes) { + renderTemplate(200, w, map[string]interface{}{ + "identifier": identifier, + "name": name, + }, "authorize.html", information) + } else { + renderTemplate(200, w, map[string]interface{}{ + "identifier": identifier, + "name": name, + }, "autoAccept.html", information) + } + }) + + router.Get("/dashboard", func(w http.ResponseWriter, r *http.Request) { + defer func(Body io.ReadCloser) { + err := Body.Close() + if err != nil { + logFunc(err.Error(), 1, information) + } + }(r.Body) + renderTemplate(200, w, map[string]interface{}{ + "identifier": identifier, + }, "dashboard.html", information) + }) + + router.Get("/clientKeyShare", func(w http.ResponseWriter, r *http.Request) { + defer func(Body io.ReadCloser) { + err := Body.Close() + if err != nil { + logFunc(err.Error(), 1, information) + } + }(r.Body) + renderTemplate(200, w, map[string]interface{}{ + "identifier": identifier, + }, "clientKeyShare.html", information) + }) + + router.Get("/.well-known/openid-configuration", func(w http.ResponseWriter, r *http.Request) { + defer func(Body io.ReadCloser) { + err := Body.Close() + if err != nil { + logFunc(err.Error(), 1, information) + } + }(r.Body) + renderTemplate(200, w, map[string]interface{}{ + "hostName": hostName, + }, "openid.json", information) + }) + + router.Post("/api/changePassword", func(w http.ResponseWriter, r *http.Request) { + defer func(Body io.ReadCloser) { + err := Body.Close() + if err != nil { + logFunc(err.Error(), 1, information) + } + }(r.Body) + type changePassword struct { + Session string `json:"session"` + NewPassword string `json:"newPassword"` + } + var data changePassword + err = json.NewDecoder(r.Body).Decode(&data) + if err != nil { + renderJSON(400, w, map[string]interface{}{"error": "Invalid JSON"}, information) + return + } + + // Check if the session exists + var userId []byte + err = mem.QueryRow("SELECT id FROM sessions WHERE session = ?", data.Session).Scan(&userId) + if err != nil { + renderJSON(400, w, map[string]interface{}{"error": "Invalid session"}, information) + return + } + + // Generate a new salt + // We want it to be binary data, not alphanumerical, so we don't use randomChars + salt := make([]byte, 16) + _, err = rand.Read(salt) + if err != nil { + renderJSON(500, w, map[string]interface{}{"error": "Internal server error", "code": "04"}, information) + logFunc(err.Error(), 2, information) + return + } + + // Decode the new password + newPassword, err := base64.StdEncoding.DecodeString(data.NewPassword) + if err != nil { + renderJSON(400, w, map[string]interface{}{"error": "Invalid JSON"}, information) + return + } + + // Hash the password + hashedPassword := argon2.IDKey(newPassword, salt, 64, 4096, 1, 32) + + // Update the password + _, err = conn.Exec("UPDATE users SET password = ?, salt = ? WHERE id = ?", hashedPassword, salt, userId) + _, err = conn.Exec("UPDATE users SET password = ?, salt = ? WHERE id = ?", hashedPassword, salt, userId) + if err != nil { + renderJSON(500, w, map[string]interface{}{"error": "Internal server error", "code": "05"}, information) + logFunc(err.Error(), 2, information) + return + } + + // Invalidate all sessions + _, err = mem.Exec("DELETE FROM sessions WHERE id = ?", userId) + if err != nil { + renderJSON(500, w, map[string]interface{}{"error": "Internal server error", "code": "06"}, information) + logFunc(err.Error(), 2, information) + return + } + + // Return success + renderJSON(200, w, map[string]interface{}{"success": true}, information) + }) + + router.Post("/api/signup", func(w http.ResponseWriter, r *http.Request) { + defer func(Body io.ReadCloser) { + err := Body.Close() + if err != nil { + logFunc(err.Error(), 1, information) + } + }(r.Body) + type signup struct { + Username string `json:"username"` + Password string `json:"password"` + Salt string `json:"salt"` + ProofOfWork string `json:"proofOfWork"` + } + var data signup + err = json.NewDecoder(r.Body).Decode(&data) + if err != nil { + renderJSON(400, w, map[string]interface{}{"error": "Invalid JSON"}, information) + return + } + + // Check if the PoW is spent + hash := make([]byte, 8) + binary.LittleEndian.PutUint64(hash, xxhash.Sum64String(data.ProofOfWork)) + _, err = mem.Exec("INSERT INTO spent (hash, expires) VALUES (?, ?)", hash, time.Now().Unix()+60) + if err != nil { + if strings.Contains(err.Error(), "UNIQUE constraint failed") { + renderJSON(409, w, map[string]interface{}{"error": "Proof of work already spent"}, information) + return + } else { + renderJSON(500, w, map[string]interface{}{"error": "Internal server error", "code": "07"}, information) + logFunc(err.Error(), 2, information) + return + } + } + + // Check if the difficulty, timestamp and resource are correct + powSlice := strings.Split(data.ProofOfWork, ":") + if powSlice[0] != "3" || powSlice[3] != "fg-auth-signup" { + renderJSON(400, w, map[string]interface{}{"error": "Invalid PoW"}, information) + return + } + + timestamp, err := strconv.ParseInt(powSlice[1], 10, 64) + if err != nil { + renderJSON(400, w, map[string]interface{}{"error": "Invalid PoW"}, information) + return + } + + if time.Unix(timestamp, 0).Add(time.Minute*10).Compare(time.Now()) < 0 { + renderJSON(400, w, map[string]interface{}{"error": "PoW expired"}, information) + return + } + + // Verify the PoW + if !pow.VerifyPoW(data.ProofOfWork) { + renderJSON(400, w, map[string]interface{}{"error": "Invalid PoW"}, information) + return + } + + // Decode the password + password, err := base64.StdEncoding.DecodeString(data.Password) + if err != nil { + renderJSON(400, w, map[string]interface{}{"error": "Invalid JSON"}, information) + return + } + + // Decode the salt + salt, err := base64.StdEncoding.DecodeString(data.Salt) + if err != nil { + renderJSON(400, w, map[string]interface{}{"error": "Invalid JSON"}, information) + return + } + + // Try to insert the user + userId := uuid.New() + userIdBytes, err := userId.MarshalBinary() + if err != nil { + renderJSON(500, w, map[string]interface{}{"error": "Internal server error", "code": "08"}, information) + logFunc(err.Error(), 2, information) + return + } + _, err = conn.Exec("INSERT INTO users (id, created, username, password, salt, created) VALUES (?, ?, ?, ?, ?, ?)", userIdBytes, time.Now().Unix(), data.Username, password, salt, time.Now().Unix()) + if err != nil { + if strings.Contains(err.Error(), "UNIQUE constraint failed") { + renderJSON(409, w, map[string]interface{}{"error": "Username already taken"}, information) + } else { + renderJSON(500, w, map[string]interface{}{"error": "Internal server error", "code": "09"}, information) + logFunc(err.Error(), 2, information) + } + return + } + + // Create a new session + // We want the session token to be somewhat legible, so we use randomChars + // As a trade-off for this, we use a longer session token + session, err := randomChars(512) + if err != nil { + renderJSON(500, w, map[string]interface{}{"error": "Internal server error", "code": "10"}, information) + logFunc(err.Error(), 2, information) + return + } + + // Insert the session + _, err = mem.Exec("INSERT INTO sessions (id, session, device) VALUES (?, ?, ?)", userIdBytes, session, r.Header.Get("User-Agent")) + + // Return success, as well as the session token + renderJSON(200, w, map[string]interface{}{"key": session}, information) + }) + + router.Post("/api/loginChallenge", func(w http.ResponseWriter, r *http.Request) { + defer func(Body io.ReadCloser) { + err := Body.Close() + if err != nil { + logFunc(err.Error(), 1, information) + } + }(r.Body) + type login struct { + Username string `json:"username"` + } + + var data login + err = json.NewDecoder(r.Body).Decode(&data) + if err != nil { + renderJSON(400, w, map[string]interface{}{"error": "Invalid JSON"}, information) + return + } + + // Get the salt for the user + var salt []byte + err = conn.QueryRow("SELECT salt FROM users WHERE username = ?", data.Username).Scan(&salt) + if err != nil { + if errors.Is(err, sql.ErrNoRows) { + renderJSON(401, w, map[string]interface{}{"error": "Invalid username or password"}, information) + } else { + renderJSON(500, w, map[string]interface{}{"error": "Internal server error", "code": "12"}, information) + logFunc(err.Error(), 2, information) + } + return + } + + // Return the salt + renderJSON(200, w, map[string]interface{}{"salt": base64.StdEncoding.EncodeToString(salt)}, information) + }) + + router.Post("/api/login", func(w http.ResponseWriter, r *http.Request) { + defer func(Body io.ReadCloser) { + err := Body.Close() + if err != nil { + logFunc(err.Error(), 1, information) + } + }(r.Body) + type login struct { + Username string `json:"username"` + Password string `json:"password"` + } + + var data login + err = json.NewDecoder(r.Body).Decode(&data) + if err != nil { + renderJSON(400, w, map[string]interface{}{"error": "Invalid JSON"}, information) + return + } + + // Try to select the user + var userId []byte + var hashedPassword []byte + err = conn.QueryRow("SELECT id, password FROM users WHERE username = ?", data.Username).Scan(&userId, &hashedPassword) + if err != nil { + if errors.Is(err, sql.ErrNoRows) { + renderJSON(401, w, map[string]interface{}{"error": "Invalid username or password"}, information) + } else { + renderJSON(500, w, map[string]interface{}{"error": "Internal server error", "code": "12"}, information) + logFunc(err.Error(), 2, information) + } + return + } + + // Decode the password + password, err := base64.StdEncoding.DecodeString(data.Password) + if err != nil { + renderJSON(400, w, map[string]interface{}{"error": "Invalid JSON"}, information) + return + } + + // Verify the password + if !bytes.Equal(password, hashedPassword) { + renderJSON(401, w, map[string]interface{}{"error": "Invalid username or password"}, information) + return + } + + // Create a new session + // We want the session token to be somewhat legible, so we use randomChars + // As a trade-off for this, we use a longer session token + session, err := randomChars(512) + if err != nil { + renderJSON(500, w, map[string]interface{}{"error": "Internal server error", "code": "13"}, information) + logFunc(err.Error(), 2, information) + return + } + + // Insert the session + _, err = mem.Exec("INSERT INTO sessions (id, session, device) VALUES (?, ?, ?)", userId, session, r.Header.Get("User-Agent")) + if err != nil { + renderJSON(500, w, map[string]interface{}{"error": "Internal server error", "code": "14"}, information) + logFunc(err.Error(), 2, information) + return + } + + // Return success, as well as the session token + renderJSON(200, w, map[string]interface{}{"key": session}, information) + }) + + router.Post("/api/userinfo", func(w http.ResponseWriter, r *http.Request) { + defer func(Body io.ReadCloser) { + err := Body.Close() + if err != nil { + logFunc(err.Error(), 1, information) + } + }(r.Body) + type userinfo struct { + Token string `json:"token"` + } + + var data userinfo + err = json.NewDecoder(r.Body).Decode(&data) + if err != nil { + renderJSON(400, w, map[string]interface{}{"error": "Invalid JSON"}, information) + return + } + + // Check if the session exists + var userId []byte + err = mem.QueryRow("SELECT id FROM sessions WHERE session = ?", data.Token).Scan(&userId) + if err != nil { + renderJSON(400, w, map[string]interface{}{"error": "Invalid session"}, information) + return + } + + // Get the username and the creation date + var username string + var created int64 + err = conn.QueryRow("SELECT username, created FROM users WHERE id = ?", userId).Scan(&username, &created) + if err != nil { + renderJSON(500, w, map[string]interface{}{"error": "Internal server error", "code": "15"}, information) + logFunc(err.Error(), 2, information) + return + } + + // Return the username and the creation date + renderJSON(200, w, map[string]interface{}{"username": username, "created": created}, information) + }) + + // This exists to make sure you get logged out immediately with an invalidated session + router.Post("/api/loggedIn", func(w http.ResponseWriter, r *http.Request) { + defer func(Body io.ReadCloser) { + err := Body.Close() + if err != nil { + logFunc(err.Error(), 1, information) + } + }(r.Body) + type loggedIn struct { + Token string `json:"token"` + } + + var data loggedIn + err = json.NewDecoder(r.Body).Decode(&data) + if err != nil { + renderJSON(400, w, map[string]interface{}{"error": "Invalid JSON"}, information) + return + } + + // Check if the session exists + var session string + err = mem.QueryRow("SELECT session FROM sessions WHERE session = ?", data.Token).Scan(&session) + if err != nil { + if errors.Is(err, sql.ErrNoRows) { + renderJSON(401, w, map[string]interface{}{"error": "Invalid session"}, information) + } else { + renderJSON(500, w, map[string]interface{}{"error": "Internal server error", "code": "16"}, information) + logFunc(err.Error(), 2, information) + } + } else { + if session == data.Token { + // Return success + renderJSON(200, w, map[string]interface{}{"success": true}, information) + } else { + // I don't know why this happens, but it does + renderJSON(401, w, map[string]interface{}{"error": "Invalid session"}, information) + } + } + }) + + // Via the magic of JWTs, this support **both** access tokens and OpenID tokens. I love signing things. + // Just a shame in 15 years when Y2Q happens. That'll be a pain. + router.Get("/api/oauth/userinfo", func(w http.ResponseWriter, r *http.Request) { + defer func(Body io.ReadCloser) { + err := Body.Close() + if err != nil { + logFunc(err.Error(), 1, information) + } + }(r.Body) + // Parse the JWT + if r.Header.Get("Authorization") == "" { + renderJSON(401, w, map[string]interface{}{"error": "No token provided"}, information) + return + } + + // Verify the JWT + userId, claims, ok := verifyJwt(strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer "), publicKey, mem) + if !ok { + renderJSON(401, w, map[string]interface{}{"error": "Invalid token"}, information) + return + } + + // Check if they have the openid scope + var scopes string + err = conn.QueryRow("SELECT scopes FROM oauth WHERE appId = ?", claims["aud"]).Scan(&scopes) + if err != nil { + renderJSON(500, w, map[string]interface{}{"error": "Internal server error", "code": "17"}, information) + logFunc(err.Error(), 2, information) + return + } + + // Unmarshal the scopes + var scopesArray []string + err = json.Unmarshal([]byte(scopes), &scopesArray) + if err != nil { + renderJSON(500, w, map[string]interface{}{"error": "Internal server error", "code": "18"}, information) + logFunc(err.Error(), 2, information) + return + } + + // Check if the openid scope is present + var hasOpenid bool + for _, scope := range scopesArray { + if scope == "openid" { + hasOpenid = true + break + } + } + if !hasOpenid { + renderJSON(403, w, map[string]interface{}{"error": "Missing scope"}, information) + return + } + + // Get the username + var username string + err := conn.QueryRow("SELECT username FROM users WHERE id = ?", userId).Scan(&username) + if err != nil { + renderJSON(500, w, map[string]interface{}{"error": "Internal server error", "code": "19"}, information) + logFunc(err.Error(), 2, information) + return + } + + // Return the username and id as sub + renderJSON(200, w, map[string]interface{}{"username": username, "sub": uuid.Must(uuid.FromBytes(userId)).String()}, information) + }) + + router.Get("/api/oauth/clientKeyShare", func(w http.ResponseWriter, r *http.Request) { + defer func(Body io.ReadCloser) { + err := Body.Close() + if err != nil { + logFunc(err.Error(), 1, information) + } + }(r.Body) + // Parse the JWT + if r.Header.Get("Authorization") == "" { + renderJSON(401, w, map[string]interface{}{"error": "No token provided"}, information) + return + } + + // Verify the JWT + _, claims, ok := verifyJwt(strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer "), publicKey, mem) + if !ok { + renderJSON(401, w, map[string]interface{}{"error": "Invalid token"}, information) + return + } + + // Check if they have the clientKeyShare scope + var scopes string + err = conn.QueryRow("SELECT scopes FROM oauth WHERE appId = ?", claims["aud"]).Scan(&scopes) + if err != nil { + renderJSON(500, w, map[string]interface{}{"error": "Internal server error", "code": "20"}, information) + logFunc(err.Error(), 2, information) + return + } + + // Unmarshal the scopes + var scopesArray []string + err = json.Unmarshal([]byte(scopes), &scopesArray) + if err != nil { + renderJSON(500, w, map[string]interface{}{"error": "Internal server error", "code": "21"}, information) + logFunc(err.Error(), 2, information) + return + } + + // Check if the clientKeyShare scope is present + var hasClientKeyShare bool + for _, scope := range scopesArray { + if scope == "clientKeyShare" { + hasClientKeyShare = true + break + } + } + if !hasClientKeyShare { + renderJSON(403, w, map[string]interface{}{"error": "Missing scope"}, information) + return + } + + // Check it's not an openid token + if claims["isOpenID"] == true { + renderJSON(401, w, map[string]interface{}{"error": "Invalid token"}, information) + } else { + renderJSON(200, w, map[string]interface{}{"key": publicKey}, information) + } + }) + + router.Post("/api/authorize", func(w http.ResponseWriter, r *http.Request) { + defer func(Body io.ReadCloser) { + err := Body.Close() + if err != nil { + logFunc(err.Error(), 1, information) + } + }(r.Body) + type authorize struct { + AppId string `json:"appId"` + PKCECode string `json:"PKCECode"` + PKCEMethod string `json:"PKCEMethod"` + RedirectUri string `json:"redirectUri"` + Nonce string `json:"nonce"` + Deny bool `json:"deny"` + Token string `json:"token"` + } + + var data authorize + err = json.NewDecoder(r.Body).Decode(&data) + if err != nil { + renderJSON(400, w, map[string]interface{}{"error": "Invalid JSON"}, information) + return + } + + // Verify the AppID, redirectUri and scopes + var appId, redirectUri, scopes string + err = conn.QueryRow("SELECT appId, redirectUri, scopes FROM oauth WHERE appId = ?", data.AppId).Scan(&appId, &redirectUri, &scopes) + if err != nil { + renderJSON(404, w, map[string]interface{}{"error": "App not found"}, information) + return + } + + if ensureTrailingSlash(redirectUri) != ensureTrailingSlash(data.RedirectUri) || appId != data.AppId { + renderJSON(401, w, map[string]interface{}{"error": "OAuth screening failed"}, information) + return + } + + // If denied, return success + if data.Deny { + renderJSON(200, w, map[string]interface{}{"success": true}, information) + return + } + + // Unmarshal the scopes + var scopesArray []string + err = json.Unmarshal([]byte(scopes), &scopesArray) + if err != nil { + renderJSON(500, w, map[string]interface{}{"error": "Internal server error", "code": "22"}, information) + logFunc(err.Error(), 2, information) + return + } + + // Check if the OpenID scope is present + var hasOpenid bool + for _, scope := range scopesArray { + if scope == "openid" { + hasOpenid = true + break + } + } + + // Check for the session + var userId []byte + err = mem.QueryRow("SELECT id FROM sessions WHERE session = ?", data.Token).Scan(&userId) + if err != nil { + renderJSON(400, w, map[string]interface{}{"error": "Invalid session"}, information) + return + } + + // Delete all ongoing logins for this user + _, err = mem.Exec("DELETE FROM logins WHERE userId = ?", userId) + if err != nil { + renderJSON(500, w, map[string]interface{}{"error": "Internal server error", "code": "23"}, information) + logFunc(err.Error(), 2, information) + return + } + + // Check for nonce + if data.Nonce == "" { + // The nonce must actually be in a URL, so we can't have pure-binary data + data.Nonce, err = randomChars(512) + if err != nil { + renderJSON(500, w, map[string]interface{}{"error": "Internal server error", "code": "24"}, information) + logFunc(err.Error(), 2, information) + return + } + } + + // Create the exchange code + exchangeCode, err := randomChars(512) + if err != nil { + renderJSON(500, w, map[string]interface{}{"error": "Internal server error", "code": "25"}, information) + logFunc(err.Error(), 2, information) + return + } + + // Insert the login + if data.Nonce != "" { + _, err = mem.Exec("INSERT INTO logins (appId, exchangeCode, pkce, pkceMethod, openid, userId, token, nonce) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", data.AppId, exchangeCode, data.PKCECode, data.PKCEMethod, hasOpenid, userId, data.Token, data.Nonce) + } else { + _, err = mem.Exec("INSERT INTO logins (appId, exchangeCode, pkce, pkceMethod, openid, userId, token) VALUES (?, ?, ?, ?, ?, ?, ?)", data.AppId, exchangeCode, data.PKCECode, data.PKCEMethod, hasOpenid, userId, data.Token) + } + if err != nil { + renderJSON(500, w, map[string]interface{}{"error": "Internal server error", "code": "26"}, information) + logFunc(err.Error(), 2, information) + return + } + + // Return success + renderJSON(200, w, map[string]interface{}{"exchangeCode": exchangeCode}, information) + }) + + router.Post("/api/oauth/token", func(w http.ResponseWriter, r *http.Request) { + defer func(Body io.ReadCloser) { + err := Body.Close() + if err != nil { + logFunc(err.Error(), 1, information) + } + }(r.Body) + // Parse the form data + err := r.ParseForm() + if err != nil { + renderJSON(400, w, map[string]interface{}{"error": "Invalid form data"}, information) + return + } + + // Declare the variables + var appId, nonce, code string + var userId []byte + var openid bool + + // Check if the PKCE is present + if r.Form.Get("code_verifier") != "" { + // It is - get the PKCE code and method + var pkceCode, pkceMethod string + err = mem.QueryRow("SELECT pkce, pkceMethod, appId, userId, nonce, openid, token FROM logins WHERE exchangeCode = ?", r.Form.Get("code")).Scan(&pkceCode, &pkceMethod, &appId, &userId, &nonce, &openid, &code) + if err != nil { + renderJSON(404, w, map[string]interface{}{"error": "Code not found"}, information) + return + } + + // Check the appId matches + if appId != r.Form.Get("client_id") { + renderJSON(401, w, map[string]interface{}{"error": "OAuth screening failed"}, information) + return + } + + // Check the PKCE + if pkceMethod == "S256" { + if sha256Base64(r.Form.Get("code_verifier")) != pkceCode { + renderJSON(403, w, map[string]interface{}{"error": "Invalid PKCE code"}, information) + return + } + } else if pkceMethod == "plain" { + if r.Form.Get("code_verifier") != pkceCode { + renderJSON(403, w, map[string]interface{}{"error": "Invalid PKCE code"}, information) + return + } + } else { + renderJSON(400, w, map[string]interface{}{"error": "Invalid PKCE method"}, information) + return + } + } else { + // It isn't - don't get the PKCE code and method + err = mem.QueryRow("SELECT appId, userId, nonce, openid, token FROM logins WHERE exchangeCode = ?", r.Form.Get("code")).Scan(&appId, &userId, &nonce, &openid, &code) + if err != nil { + renderJSON(404, w, map[string]interface{}{"error": "Code not found"}, information) + return + } + + // Check the appId matches + if appId != r.Form.Get("client_id") { + renderJSON(401, w, map[string]interface{}{"error": "OAuth screening failed"}, information) + return + } + + // Verify the secret + var secret string + err = conn.QueryRow("SELECT secret FROM oauth WHERE appId = ?", r.Form.Get("client_id")).Scan(&secret) + if err != nil { + renderJSON(404, w, map[string]interface{}{"error": "App not found"}, information) + return + } + + if secret != r.Form.Get("client_secret") { + renderJSON(401, w, map[string]interface{}{"error": "Invalid client secret"}, information) + return + } + } + + // Delete the login + _, err = mem.Exec("DELETE FROM logins WHERE userId = ?", userId) + if err != nil { + renderJSON(500, w, map[string]interface{}{"error": "Internal server error", "code": "27"}, information) + logFunc(err.Error(), 2, information) + return + } + + // Generate a new nonce if it doesn't exist + if nonce == "" { + nonce, err = randomChars(512) + if err != nil { + renderJSON(500, w, map[string]interface{}{"error": "Internal server error", "code": "28"}, information) + logFunc(err.Error(), 2, information) + return + } + } + + // Create the JWTs + var openIDTokenString string + if openid { + var username string + err := conn.QueryRow("SELECT username FROM users WHERE id = ?", userId).Scan(&username) + if err != nil { + renderJSON(500, w, map[string]interface{}{"error": "Internal server error", "code": "29"}, information) + logFunc(err.Error(), 2, information) + return + } + + openIDTemplate := jwt.MapClaims{ + "sub": userId, + "iss": hostName, + "name": username, + "aud": appId, + "exp": time.Now().Add(time.Hour * 24 * 7).Unix(), + "iat": time.Now().Unix(), + "auth_time": time.Now().Unix(), + "session": code, + "nonce": nonce, + "isOpenID": true, + } + + openIDToken := jwt.NewWithClaims(jwt.SigningMethodEdDSA, openIDTemplate) + openIDToken.Header["kid"] = base64.StdEncoding.EncodeToString(publicKey[:8]) + openIDTokenString, err = openIDToken.SignedString(privateKey) + if err != nil { + renderJSON(500, w, map[string]interface{}{"error": "Internal server error", "code": "30"}, information) + logFunc(err.Error(), 2, information) + return + } + } + + accessTokenTemplate := jwt.MapClaims{ + "exp": time.Now().Add(time.Hour * 24 * 7).Unix(), + "iat": time.Now().Unix(), + "session": code, + "nonce": nonce, + "aud": appId, + "isOpenID": false, + } + + accessToken := jwt.NewWithClaims(jwt.SigningMethodEdDSA, accessTokenTemplate) + accessToken.Header["kid"] = base64.StdEncoding.EncodeToString(publicKey[:8]) + accessTokenString, err := accessToken.SignedString(privateKey) + if err != nil { + renderJSON(500, w, map[string]interface{}{"error": "Internal server error", "code": "31"}, information) + logFunc(err.Error(), 2, information) + return + } + + // Delete all ongoing logins for this user + _, err = mem.Exec("DELETE FROM logins WHERE userId = ?", userId) + if err != nil { + renderJSON(500, w, map[string]interface{}{"error": "Internal server error", "code": "32"}, information) + logFunc(err.Error(), 2, information) + return + } + + // Return the tokens + if openid { + renderJSON(200, w, map[string]interface{}{"access_token": accessTokenString, "id_token": openIDTokenString, "token_type": "Bearer", "expires_in": 604800}, information) + } else { + renderJSON(200, w, map[string]interface{}{"access_token": accessTokenString, "token_type": "Bearer", "expires_in": 604800}, information) + } + }) + + router.Post("/api/oauth/remove", func(w http.ResponseWriter, r *http.Request) { + defer func(Body io.ReadCloser) { + err := Body.Close() + if err != nil { + logFunc(err.Error(), 1, information) + } + }(r.Body) + type remove struct { + Token string `json:"token"` + AppID string `json:"appId"` + } + + var data remove + err = json.NewDecoder(r.Body).Decode(&data) + if err != nil { + renderJSON(400, w, map[string]interface{}{"error": "Invalid JSON"}, information) + return + } + + // Check if the session exists + var userId []byte + err = mem.QueryRow("SELECT id FROM sessions WHERE session = ?", data.Token).Scan(&userId) + if err != nil { + renderJSON(400, w, map[string]interface{}{"error": "Invalid session"}, information) + return + } + + // Delete the oauth entry + _, err = conn.Exec("DELETE FROM oauth WHERE appId = ? AND creator = ?", data.AppID, userId) + if err != nil { + if errors.Is(err, sql.ErrNoRows) { + renderJSON(404, w, map[string]interface{}{"error": "App not found"}, information) + } else { + renderJSON(500, w, map[string]interface{}{"error": "Internal server error", "code": "33"}, information) + logFunc(err.Error(), 2, information) + } + } else { + renderJSON(200, w, map[string]interface{}{"success": true}, information) + } + }) + + router.Post("/api/oauth/add", func(w http.ResponseWriter, r *http.Request) { + defer func(Body io.ReadCloser) { + err := Body.Close() + if err != nil { + logFunc(err.Error(), 1, information) + } + }(r.Body) + + // Conveniently, we use this one for ISB as well, so we can re-use the struct + var data authLibrary.OAuthInformation + err = json.NewDecoder(r.Body).Decode(&data) + if err != nil { + renderJSON(400, w, map[string]interface{}{"error": "Invalid JSON"}, information) + return + } + + // Check if the session exists + var userId []byte + err = mem.QueryRow("SELECT id FROM sessions WHERE session = ?", data.Token).Scan(&userId) + if err != nil { + renderJSON(400, w, map[string]interface{}{"error": "Invalid session"}, information) + return + } + + // Generate a new secret + // It must be able to be sent via JSON, so we can't have pure-binary data + secret, err := randomChars(512) + if err != nil { + renderJSON(500, w, map[string]interface{}{"error": "Internal server error", "code": "34"}, information) + logFunc(err.Error(), 2, information) + return + } + + // Generate a new appId + // It must be able to be sent via JSON, so we can't have pure-binary data + appId, err := randomChars(32) + if err != nil { + renderJSON(500, w, map[string]interface{}{"error": "Internal server error", "code": "35"}, information) + logFunc(err.Error(), 2, information) + return + } + + // Validate the scopes + var clientKeyShare bool + for _, scope := range data.Scopes { + if scope != "openid" && scope != "clientKeyShare" { + renderJSON(400, w, map[string]interface{}{"error": "Invalid scope"}, information) + return + } else { + if scope == "clientKeyShare" { + clientKeyShare = true + } else if scope != "openid" { + logFunc("An impossible logic error has occurred, please move away from radiation or use ECC RAM", 1, information) + renderJSON(400, w, map[string]interface{}{"error": "Invalid scope"}, information) + return + } + } + } + + // Marshal the scopes + scopes, err := json.Marshal(data.Scopes) + if err != nil { + renderJSON(500, w, map[string]interface{}{"error": "Internal server error", "code": "36"}, information) + logFunc(err.Error(), 2, information) + return + } + + // Insert the oauth entry + if clientKeyShare { + _, err = conn.Exec("INSERT INTO oauth (appId, secret, creator, name, redirectUri, scopes, keyShareUri) VALUES (?, ?, ?, ?, ?, ?, ?)", appId, secret, userId, data.Name, data.RedirectUri, scopes, data.KeyShareUri) + } else { + _, err = conn.Exec("INSERT INTO oauth (appId, secret, creator, name, redirectUri, scopes) VALUES (?, ?, ?, ?, ?, ?)", appId, secret, userId, data.Name, data.RedirectUri, scopes) + } + if err != nil { + renderJSON(500, w, map[string]interface{}{"error": "Internal server error", "code": "37"}, information) + logFunc(err.Error(), 2, information) + return + } + + // Return the appId and secret + renderJSON(200, w, map[string]interface{}{"appId": appId, "key": secret}, information) + }) + + router.Post("/api/oauth/list", func(w http.ResponseWriter, r *http.Request) { + defer func(Body io.ReadCloser) { + err := Body.Close() + if err != nil { + logFunc(err.Error(), 1, information) + } + }(r.Body) + type list struct { + Token string `json:"token"` + } + + var data list + err = json.NewDecoder(r.Body).Decode(&data) + if err != nil { + renderJSON(400, w, map[string]interface{}{"error": "Invalid JSON"}, information) + return + } + + // Check if the session exists + var userId []byte + err = mem.QueryRow("SELECT id FROM sessions WHERE session = ?", data.Token).Scan(&userId) + if err != nil { + renderJSON(400, w, map[string]interface{}{"error": "Invalid session"}, information) + return + } + + // Get the apps + rows, err := conn.Query("SELECT appId, name, redirectUri, scopes, keyShareUri FROM oauth WHERE creator = ?", userId) + if err != nil { + renderJSON(500, w, map[string]interface{}{"error": "Internal server error", "code": "38"}, information) + logFunc(err.Error(), 2, information) + return + } + + var dataOut []map[string]interface{} + for rows.Next() { + var appId, name, redirectUri, scopes, keyShareUri string + err = rows.Scan(&appId, &name, &redirectUri, &scopes, &keyShareUri) + if err != nil { + renderJSON(500, w, map[string]interface{}{"error": "Internal server error", "code": "39"}, information) + logFunc(err.Error(), 2, information) + return + } + + // Marshal the scopes + var scopesArray []string + err = json.Unmarshal([]byte(scopes), &scopesArray) + if err != nil { + renderJSON(500, w, map[string]interface{}{"error": "Internal server error", "code": "40"}, information) + logFunc(err.Error(), 2, information) + return + } + + dataOut = append(dataOut, map[string]interface{}{ + "appId": appId, + "name": name, + "redirectUri": redirectUri, + "scopes": scopesArray, + "keyShareUri": keyShareUri, + }) + } + err = rows.Err() + if err != nil { + renderJSON(500, w, map[string]interface{}{"error": "Internal server error", "code": "41"}, information) + logFunc(err.Error(), 2, information) + return + } + + // Close the rows + err = rows.Close() + if err != nil { + // Memory leak, but we can't do anything about it + logFunc(err.Error(), 1, information) + } + + // Return the apps + renderJSON(200, w, map[string]interface{}{ + "apps": dataOut, + }, information) + }) + + router.Post("/api/deleteAccount", func(w http.ResponseWriter, r *http.Request) { + defer func(Body io.ReadCloser) { + err := Body.Close() + if err != nil { + logFunc(err.Error(), 1, information) + } + }(r.Body) + type deleteAccount struct { + Token string `json:"token"` + } + + var data deleteAccount + err = json.NewDecoder(r.Body).Decode(&data) + if err != nil { + renderJSON(400, w, map[string]interface{}{"error": "Invalid JSON"}, information) + return + } + + // Check if the session exists + var userId []byte + err = mem.QueryRow("SELECT id FROM sessions WHERE session = ?", data.Token).Scan(&userId) + if err != nil { + renderJSON(400, w, map[string]interface{}{"error": "Invalid session"}, information) + return + } + + // Delete the user + _, err = conn.Exec("DELETE FROM users WHERE id = ?", userId) + if err != nil { + renderJSON(500, w, map[string]interface{}{"error": "Internal server error", "code": "42"}, information) + logFunc(err.Error(), 2, information) + return + } + + // Delete the user's sessions + _, err = mem.Exec("DELETE FROM sessions WHERE id = ?", userId) + if err != nil { + renderJSON(500, w, map[string]interface{}{"error": "Internal server error", "code": "43"}, information) + logFunc(err.Error(), 2, information) + return + } + + // Delete the user's oauth entries + _, err = conn.Exec("DELETE FROM oauth WHERE creator = ?", userId) + if err != nil { + renderJSON(500, w, map[string]interface{}{"error": "Internal server error", "code": "44"}, information) + logFunc(err.Error(), 2, information) + return + } + + // Delete the user's active logins + _, err = mem.Exec("DELETE FROM logins WHERE userId = ?", userId) + if err != nil { + renderJSON(500, w, map[string]interface{}{"error": "Internal server error", "code": "45"}, information) + logFunc(err.Error(), 2, information) + return + } + + // Return success + renderJSON(200, w, map[string]interface{}{"success": true}, information) + }) + + router.Post("/api/session/list", func(w http.ResponseWriter, r *http.Request) { + defer func(Body io.ReadCloser) { + err := Body.Close() + if err != nil { + logFunc(err.Error(), 1, information) + } + }(r.Body) + type list struct { + Token string `json:"token"` + } + + var data list + err = json.NewDecoder(r.Body).Decode(&data) + if err != nil { + renderJSON(400, w, map[string]interface{}{"error": "Invalid JSON"}, information) + return + } + + // Check if the session exists + var userId []byte + err = mem.QueryRow("SELECT id FROM sessions WHERE session = ?", data.Token).Scan(&userId) + if err != nil { + renderJSON(400, w, map[string]interface{}{"error": "Invalid session"}, information) + return + } + + // Get the sessions + rows, err := mem.Query("SELECT session, device FROM sessions WHERE id = ?", userId) + if err != nil { + renderJSON(500, w, map[string]interface{}{"error": "Internal server error", "code": "46"}, information) + logFunc(err.Error(), 2, information) + return + } + + var dataOut []map[string]interface{} + for rows.Next() { + var session, device string + err = rows.Scan(&session, &device) + if err != nil { + renderJSON(500, w, map[string]interface{}{"error": "Internal server error", "code": "47"}, information) + logFunc(err.Error(), 2, information) + return + } + dataOut = append(dataOut, map[string]interface{}{ + "session": session, + "device": device, + }) + } + err = rows.Err() + if err != nil { + renderJSON(500, w, map[string]interface{}{"error": "Internal server error", "code": "48"}, information) + logFunc(err.Error(), 2, information) + return + } + + // Close the rows + err = rows.Close() + if err != nil { + // Memory leak, but we can't do anything about it + logFunc(err.Error(), 1, information) + } + + // Return the sessions + renderJSON(200, w, map[string]interface{}{ + "sessions": dataOut, + }, information) + }) + + router.Post("/api/session/remove", func(w http.ResponseWriter, r *http.Request) { + defer func(Body io.ReadCloser) { + err := Body.Close() + if err != nil { + logFunc(err.Error(), 1, information) + } + }(r.Body) + type remove struct { + Token string `json:"token"` + Session string `json:"session"` + } + + var data remove + err = json.NewDecoder(r.Body).Decode(&data) + if err != nil { + renderJSON(400, w, map[string]interface{}{"error": "Invalid JSON"}, information) + return + } + + // Check if the session exists + var userId []byte + err = mem.QueryRow("SELECT id FROM sessions WHERE session = ?", data.Token).Scan(&userId) + if err != nil { + renderJSON(400, w, map[string]interface{}{"error": "Invalid session"}, information) + return + } + + // Delete the session + _, err = mem.Exec("DELETE FROM sessions WHERE id = ? AND session = ?", userId, data.Session) + if err != nil { + renderJSON(500, w, map[string]interface{}{"error": "Internal server error", "code": "49"}, information) + logFunc(err.Error(), 2, information) + return + } + + // Return success + renderJSON(200, w, map[string]interface{}{"success": true}, information) + }) + + router.Post("/api/listUsers", func(w http.ResponseWriter, r *http.Request) { + defer func(Body io.ReadCloser) { + err := Body.Close() + if err != nil { + logFunc(err.Error(), 1, information) + } + }(r.Body) + type listUsers struct { + AdminKey string `json:"adminKey"` + } + + var data listUsers + err = json.NewDecoder(r.Body).Decode(&data) + if err != nil { + renderJSON(400, w, map[string]interface{}{"error": "Invalid JSON"}, information) + return + } + + // Check if the admin key is correct + // Finally, I get to use the admin key + // In previous versions, the admin key was very important - it handled server cookie-based secrets + // as well as JWTs - but now it's just a glorified password + if data.AdminKey != adminKey { + renderJSON(401, w, map[string]interface{}{"error": "Invalid admin key"}, information) + return + } + + // Get the users + rows, err := conn.Query("SELECT id, username, created FROM users") + if err != nil { + renderJSON(500, w, map[string]interface{}{"error": "Internal server error", "code": "50"}, information) + logFunc(err.Error(), 2, information) + return + } + + var dataOut []map[string]interface{} + for rows.Next() { + var id []byte + var username string + var created int64 + err = rows.Scan(&id, &username, &created) + if err != nil { + renderJSON(500, w, map[string]interface{}{"error": "Internal server error", "code": "51"}, information) + logFunc(err.Error(), 2, information) + return + } + dataOut = append(dataOut, map[string]interface{}{ + // Also finally get a chance to represent UUIDs as strings. Everywhere else I just use them as bytes. + "id": uuid.Must(uuid.FromBytes(id)).String(), + "username": username, + "created": created, + }) + } + err = rows.Err() + if err != nil { + renderJSON(500, w, map[string]interface{}{"error": "Internal server error", "code": "52"}, information) + logFunc(err.Error(), 2, information) + return + } + + // Close the rows + err = rows.Close() + if err != nil { + // Memory leak, but we can't do anything about it + logFunc(err.Error(), 1, information) + } + + // Return the users + renderJSON(200, w, map[string]interface{}{ + "users": dataOut, + }, information) + }) + + router.Get("/.well-known/keys.json", func(w http.ResponseWriter, r *http.Request) { + defer func(Body io.ReadCloser) { + err := Body.Close() + if err != nil { + logFunc(err.Error(), 1, information) + } + }(r.Body) + // Return the public key + renderJSON(200, w, map[string]interface{}{ + "keys": []map[string]interface{}{ + { + "kty": "OKP", + "alg": "EdDSA", + "use": "sig", + "kid": base64.StdEncoding.EncodeToString(publicKey[:8]), + "x": base64.RawURLEncoding.EncodeToString(publicKey), + "crv": "Ed25519", + }, + }, + }, information) + }) + + go func() { + for { + // Sleep for half an hour + time.Sleep(time.Minute * 30) + + // Delete everything in the spent table past it's expiry date + affected, err := mem.Exec("DELETE FROM spent WHERE expires < ?", time.Now().Unix()) + if err != nil { + logFunc(err.Error(), 1, information) + } else { + affectedCount, err := affected.RowsAffected() + if err != nil { + logFunc(err.Error(), 1, information) + } else { + logFunc("Spent cleanup complete, deleted "+strconv.FormatInt(affectedCount, 10)+" entries", 0, information) + } + } + } + }() + + go func() { + for { + // Wait for a message + message := <-information.Inbox + + // Check the message type + switch message.MessageType { + case 0: + // A service would like to know our hostname + // Send it to them + information.Outbox <- library.InterServiceMessage{ + MessageType: 0, + ServiceID: ServiceInformation.ServiceID, + ForServiceID: message.ServiceID, + Message: hostName, + SentAt: time.Now(), + } + case 1: + // A service would like to register a new OAuth entry + // Generate a new secret + // It must be able to be sent via JSON, so we can't have pure-binary data + secret, err := randomChars(512) + if err != nil { + information.Outbox <- library.InterServiceMessage{ + MessageType: 1, + ServiceID: ServiceInformation.ServiceID, + ForServiceID: message.ServiceID, + Message: "36", + SentAt: time.Now(), + } + logFunc(err.Error(), 2, information) + return + } + + // Generate a new appId + // It must be able to be sent via JSON, so we can't have pure-binary data + appId, err := randomChars(32) + if err != nil { + information.Outbox <- library.InterServiceMessage{ + MessageType: 1, + ServiceID: ServiceInformation.ServiceID, + ForServiceID: message.ServiceID, + Message: "37", + SentAt: time.Now(), + } + logFunc(err.Error(), 2, information) + return + } + + // Validate the scopes + var clientKeyShare bool + for _, scope := range message.Message.(authLibrary.OAuthInformation).Scopes { + if scope != "openid" && scope != "clientKeyShare" { + information.Outbox <- library.InterServiceMessage{ + MessageType: 2, + ServiceID: ServiceInformation.ServiceID, + ForServiceID: message.ServiceID, + Message: "Invalid scope", + SentAt: time.Now(), + } + return + } else { + if scope == "clientKeyShare" { + clientKeyShare = true + } else if scope != "openid" { + logFunc("An impossible logic error has occurred, please move away from radiation or use ECC RAM", 1, information) + information.Outbox <- library.InterServiceMessage{ + MessageType: 2, + ServiceID: ServiceInformation.ServiceID, + ForServiceID: message.ServiceID, + Message: "Invalid scope", + SentAt: time.Now(), + } + return + } + } + } + + // Marshal the scopes + scopes, err := json.Marshal(message.Message.(authLibrary.OAuthInformation).Scopes) + if err != nil { + information.Outbox <- library.InterServiceMessage{ + MessageType: 1, + ServiceID: ServiceInformation.ServiceID, + ForServiceID: message.ServiceID, + Message: "38", + SentAt: time.Now(), + } + logFunc(err.Error(), 2, information) + return + } + + // Insert the oauth entry + if clientKeyShare { + _, err = conn.Exec("INSERT INTO oauth (appId, secret, creator, name, redirectUri, scopes, keyShareUri) VALUES (?, ?, ?, ?, ?, ?, ?)", appId, secret, serviceIDBytes, message.Message.(authLibrary.OAuthInformation).Name, message.Message.(authLibrary.OAuthInformation).RedirectUri, scopes, message.Message.(authLibrary.OAuthInformation).KeyShareUri) + } else { + _, err = conn.Exec("INSERT INTO oauth (appId, secret, creator, name, redirectUri, scopes) VALUES (?, ?, ?, ?, ?, ?)", appId, secret, serviceIDBytes, message.Message.(authLibrary.OAuthInformation).Name, message.Message.(authLibrary.OAuthInformation).RedirectUri, scopes) + } + if err != nil { + information.Outbox <- library.InterServiceMessage{ + MessageType: 1, + ServiceID: ServiceInformation.ServiceID, + ForServiceID: message.ServiceID, + Message: "39", + SentAt: time.Now(), + } + logFunc(err.Error(), 2, information) + return + } + + // Return the appId and secret + information.Outbox <- library.InterServiceMessage{ + MessageType: 0, + ServiceID: ServiceInformation.ServiceID, + ForServiceID: message.ServiceID, + Message: authLibrary.OAuthResponse{ + AppID: appId, + SecretKey: secret, + }, + SentAt: time.Now(), + } + } + } + }() +} diff --git a/services-src/auth/resources/go.mod b/services-src/auth/resources/go.mod new file mode 100644 index 0000000..0f68e65 --- /dev/null +++ b/services-src/auth/resources/go.mod @@ -0,0 +1,11 @@ +module git.ailur.dev/fulgens/services-src/auth/resources-src + +go 1.23.0 + +require ( + git.ailur.dev/ailur/pow-argon2 v0.0.0-20240922143345-8f9af6dce3a5 + github.com/cespare/xxhash/v2 v2.3.0 + golang.org/x/crypto v0.27.0 +) + +require golang.org/x/sys v0.25.0 // indirect diff --git a/services-src/auth/resources/go.sum b/services-src/auth/resources/go.sum new file mode 100644 index 0000000..e90db0e --- /dev/null +++ b/services-src/auth/resources/go.sum @@ -0,0 +1,8 @@ +git.ailur.dev/ailur/pow-argon2 v0.0.0-20240922143345-8f9af6dce3a5 h1:QGICG5QsXtGVDV0YjR4bXiEV2kWQ96riPR9qFWuFpr4= +git.ailur.dev/ailur/pow-argon2 v0.0.0-20240922143345-8f9af6dce3a5/go.mod h1:dDulL+Bfr47BPmvSPRkRD3uOVNsfM6yOTwhdAkctZU4= +github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= +github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +golang.org/x/crypto v0.27.0 h1:GXm2NjJrPaiv/h1tb2UH8QfgC/hOf/+z0p6PT8o1w7A= +golang.org/x/crypto v0.27.0/go.mod h1:1Xngt8kV6Dvbssa53Ziq6Eqn0HqbZi5Z6R0ZpwQzt70= +golang.org/x/sys v0.25.0 h1:r+8e+loiHxRqhXVl6ML1nO3l1+oFoWbnlu2Ehimmi34= +golang.org/x/sys v0.25.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= diff --git a/services-src/auth/resources/static/css/style.css b/services-src/auth/resources/static/css/style.css new file mode 100644 index 0000000..fd6ee05 --- /dev/null +++ b/services-src/auth/resources/static/css/style.css @@ -0,0 +1,309 @@ +@import url("../fonts/inter.css"); + +:root { + --invertdm: 0%; + --text-color: #000000; + --editor: #ffffff; + --border-color: #dadada; + --theme-color: #1c71d8; + --hover-theme-color: #4990e7; + --nonimporant-theme-color: #EBEBEB; + --hover-nonimportant-theme-color: #dbdbdb; + --nonimportant-text-color: #000; + --inOutDiv: #fafafa; +} + +/* dark mode */ + +@media (prefers-color-scheme: dark) { + :root { + --invertdm: 100%; + --inOutDiv: #2d2f31; + --text-color: #ffffff; + --editor: #1E1E1E; + --nonimportant-text-color: #fff; + --border-color: #393b3d; + } + + .inOutDiv p { + color: white !important; + } + + .inOutDiv a { + color: #969696 !important; + } + + .inOutDiv input { + color: white; + background-color: var(--editor); + } +} + +p, +li, +h1, +h2, +h3, +h4, +h5, +h6 { + color: var(--text-color); + white-space: break-spaces; +} + +p#statusBox { + overflow-wrap: break-word; +} + +body { + margin: 0; + background-color: var(--editor); + font-family: "Inter", sans-serif; +} + +/* Sign up/log in div */ + +.inOutDiv { + border-radius: 8px; + margin: 10%; + padding: 30px; + border: solid 1px var(--border-color); + background-color: var(--inOutDiv); +} + +table { + border-spacing: 0; +} + +input { + width: calc(100% - 35px); + margin-left: 10px; + margin-right: 10px; + height: 30px; + padding-left: 10px; + padding-right: 10px; + + border: solid; + border-color: var(--border-color); + border-width: 1px; + border-radius: 8px; + min-width: 20px; +} + +.inputBox input { + margin-left: 5px; + margin-right: 0; +} + +@media only screen and (max-width: 600px) { + body { + background-color: var(--inOutDiv); + } + .inOutDiv { + position: absolute; + top: 0; + left: 10px; + right: 10px; + border-radius: 0; + min-width: calc(100% - 20px); + min-height: 100%; + transform: none; + padding: 5px; + overflow-y: auto; + overflow-x: auto; + margin: 0; + border: 0; + } + .inOutDiv p { + font-size: 14px; + } + .inOutDiv h2 { + font-size: 21px; + } + .background { + display: none; + } + .inOutDiv input { + width: calc(100% - 32px); + } +} + +.inOutDiv img { + min-width: 200px; + max-width: 100%; + border-radius: 20px; + background-color: white; +} + +.iframe { + position: fixed; + right: 5px; + top: 47px; + border: none; + height: 278px; + width: 400px; + transform: translateX(26px); +} + +.spacer { + margin-top: 30px; +} + +.credit { + position: fixed; + left: 5px; + color: white; + z-index: -1; + margin: 0; + bottom: 5px; + text-shadow: black 1px 1px 5px; +} + +.newOauth, .oauthList, .sessionEntry, .oauthEntry { + text-align: center; + width: calc(100% - 17.5vh); + margin-top: 7vh; + margin-left: 7vh; + margin-right: 7vh; + padding: 15px 10px 30px; + border-style: solid; + border-image: none; + border-radius: 8px; + border-width: 1px; + font-size: 17px; + background-color: var(--inOutDiv); + border-color: var(--border-color); +} + +.oauthEntry, .sessionEntry { + display: flex; + flex-direction: column; + justify-content: center; + padding: 5px; + margin-top: 0; + margin-bottom: 20px; +} + +.oauthEntry button, .sessionEntry button { + padding: 10px; + background-color: red; + color: white +} + +.oauthEntry button:hover, .sessionEntry button:hover { + background-color: black; +} + +.oauthEntry img, .sessionEntry img { + max-height: 64px; + margin-top: 10px; +} + +button { + background-color: var(--theme-color); + color: white; + margin-right: 5px; + padding: 10px 20px; + border: none; + border-radius: 25px; + font-size: 14px; + transition: 0.125s; +} + +button:hover { + background-color: var(--hover-theme-color); + transition: all 0.3s ease 0s; +} + +.inOutDiv .inputContainer { + margin-bottom: 20px; + margin-right: 20px; + width: 100%; + display: flex; +} + +.inOutDiv .inputBox { + width: 100%; +} + +.unimportant { + background-color: var(--nonimporant-theme-color); + color: var(--nonimportant-text-color) !important; +} + +.unimportant:hover { + background-color: var(--hover-nonimportant-theme-color); + transition: all 0.3s ease 0s; +} + +h2 { + display: block; + margin-top: 20px; + font-weight: 300; +} + +.inOutDiv a { + color: grey; + text-align: center; +} + +.background { + position: fixed; + z-index: -2; + top: 0; + width: 100%; + height: 100%; + object-fit: cover; + -webkit-user-drag: none; + user-select: none; + -moz-user-select: none; + -webkit-user-select: none; + -ms-user-select: none; + pointer-events: none; +} + +.vAlign { + display: flex; + flex-direction: column; + justify-content: center; +} + +.hidden { + display: none !important; +} + +.w100 { + font-weight: 300; +} + +.w200 { + font-weight: 300; +} + +.w300 { + font-weight: 300; +} + +.w400 { + font-weight: 400; +} + +.w500 { + font-weight: 500; +} + +.w600 { + font-weight: 600; +} + +.w700 { + font-weight: 700; +} + +.w800 { + font-weight: 800; +} + +.w900 { + font-weight: 900; +} diff --git a/services-src/auth/resources/static/fonts/Inter-Black.woff2 b/services-src/auth/resources/static/fonts/Inter-Black.woff2 new file mode 100644 index 0000000..18b35db Binary files /dev/null and b/services-src/auth/resources/static/fonts/Inter-Black.woff2 differ diff --git a/services-src/auth/resources/static/fonts/Inter-BlackItalic.woff2 b/services-src/auth/resources/static/fonts/Inter-BlackItalic.woff2 new file mode 100644 index 0000000..02c9d8e Binary files /dev/null and b/services-src/auth/resources/static/fonts/Inter-BlackItalic.woff2 differ diff --git a/services-src/auth/resources/static/fonts/Inter-Bold.woff2 b/services-src/auth/resources/static/fonts/Inter-Bold.woff2 new file mode 100644 index 0000000..0f1b157 Binary files /dev/null and b/services-src/auth/resources/static/fonts/Inter-Bold.woff2 differ diff --git a/services-src/auth/resources/static/fonts/Inter-BoldItalic.woff2 b/services-src/auth/resources/static/fonts/Inter-BoldItalic.woff2 new file mode 100644 index 0000000..bc50f24 Binary files /dev/null and b/services-src/auth/resources/static/fonts/Inter-BoldItalic.woff2 differ diff --git a/services-src/auth/resources/static/fonts/Inter-ExtraBold.woff2 b/services-src/auth/resources/static/fonts/Inter-ExtraBold.woff2 new file mode 100644 index 0000000..b113368 Binary files /dev/null and b/services-src/auth/resources/static/fonts/Inter-ExtraBold.woff2 differ diff --git a/services-src/auth/resources/static/fonts/Inter-ExtraBoldItalic.woff2 b/services-src/auth/resources/static/fonts/Inter-ExtraBoldItalic.woff2 new file mode 100644 index 0000000..a5b76ca Binary files /dev/null and b/services-src/auth/resources/static/fonts/Inter-ExtraBoldItalic.woff2 differ diff --git a/services-src/auth/resources/static/fonts/Inter-ExtraLight.woff2 b/services-src/auth/resources/static/fonts/Inter-ExtraLight.woff2 new file mode 100644 index 0000000..1d77ae8 Binary files /dev/null and b/services-src/auth/resources/static/fonts/Inter-ExtraLight.woff2 differ diff --git a/services-src/auth/resources/static/fonts/Inter-ExtraLightItalic.woff2 b/services-src/auth/resources/static/fonts/Inter-ExtraLightItalic.woff2 new file mode 100644 index 0000000..8c68492 Binary files /dev/null and b/services-src/auth/resources/static/fonts/Inter-ExtraLightItalic.woff2 differ diff --git a/services-src/auth/resources/static/fonts/Inter-Italic.woff2 b/services-src/auth/resources/static/fonts/Inter-Italic.woff2 new file mode 100644 index 0000000..4c24ce2 Binary files /dev/null and b/services-src/auth/resources/static/fonts/Inter-Italic.woff2 differ diff --git a/services-src/auth/resources/static/fonts/Inter-Light.woff2 b/services-src/auth/resources/static/fonts/Inter-Light.woff2 new file mode 100644 index 0000000..dbe6143 Binary files /dev/null and b/services-src/auth/resources/static/fonts/Inter-Light.woff2 differ diff --git a/services-src/auth/resources/static/fonts/Inter-LightItalic.woff2 b/services-src/auth/resources/static/fonts/Inter-LightItalic.woff2 new file mode 100644 index 0000000..a40d042 Binary files /dev/null and b/services-src/auth/resources/static/fonts/Inter-LightItalic.woff2 differ diff --git a/services-src/auth/resources/static/fonts/Inter-Medium.woff2 b/services-src/auth/resources/static/fonts/Inter-Medium.woff2 new file mode 100644 index 0000000..0fd2ee7 Binary files /dev/null and b/services-src/auth/resources/static/fonts/Inter-Medium.woff2 differ diff --git a/services-src/auth/resources/static/fonts/Inter-MediumItalic.woff2 b/services-src/auth/resources/static/fonts/Inter-MediumItalic.woff2 new file mode 100644 index 0000000..9676715 Binary files /dev/null and b/services-src/auth/resources/static/fonts/Inter-MediumItalic.woff2 differ diff --git a/services-src/auth/resources/static/fonts/Inter-Regular.woff2 b/services-src/auth/resources/static/fonts/Inter-Regular.woff2 new file mode 100644 index 0000000..b8699af Binary files /dev/null and b/services-src/auth/resources/static/fonts/Inter-Regular.woff2 differ diff --git a/services-src/auth/resources/static/fonts/Inter-SemiBold.woff2 b/services-src/auth/resources/static/fonts/Inter-SemiBold.woff2 new file mode 100644 index 0000000..95c48b1 Binary files /dev/null and b/services-src/auth/resources/static/fonts/Inter-SemiBold.woff2 differ diff --git a/services-src/auth/resources/static/fonts/Inter-SemiBoldItalic.woff2 b/services-src/auth/resources/static/fonts/Inter-SemiBoldItalic.woff2 new file mode 100644 index 0000000..ddfe19e Binary files /dev/null and b/services-src/auth/resources/static/fonts/Inter-SemiBoldItalic.woff2 differ diff --git a/services-src/auth/resources/static/fonts/Inter-Thin.woff2 b/services-src/auth/resources/static/fonts/Inter-Thin.woff2 new file mode 100644 index 0000000..0790960 Binary files /dev/null and b/services-src/auth/resources/static/fonts/Inter-Thin.woff2 differ diff --git a/services-src/auth/resources/static/fonts/Inter-ThinItalic.woff2 b/services-src/auth/resources/static/fonts/Inter-ThinItalic.woff2 new file mode 100644 index 0000000..a7bf213 Binary files /dev/null and b/services-src/auth/resources/static/fonts/Inter-ThinItalic.woff2 differ diff --git a/services-src/auth/resources/static/fonts/InterDisplay-Black.woff2 b/services-src/auth/resources/static/fonts/InterDisplay-Black.woff2 new file mode 100644 index 0000000..8138123 Binary files /dev/null and b/services-src/auth/resources/static/fonts/InterDisplay-Black.woff2 differ diff --git a/services-src/auth/resources/static/fonts/InterDisplay-BlackItalic.woff2 b/services-src/auth/resources/static/fonts/InterDisplay-BlackItalic.woff2 new file mode 100644 index 0000000..735ba21 Binary files /dev/null and b/services-src/auth/resources/static/fonts/InterDisplay-BlackItalic.woff2 differ diff --git a/services-src/auth/resources/static/fonts/InterDisplay-Bold.woff2 b/services-src/auth/resources/static/fonts/InterDisplay-Bold.woff2 new file mode 100644 index 0000000..11c6719 Binary files /dev/null and b/services-src/auth/resources/static/fonts/InterDisplay-Bold.woff2 differ diff --git a/services-src/auth/resources/static/fonts/InterDisplay-BoldItalic.woff2 b/services-src/auth/resources/static/fonts/InterDisplay-BoldItalic.woff2 new file mode 100644 index 0000000..5b6a1fb Binary files /dev/null and b/services-src/auth/resources/static/fonts/InterDisplay-BoldItalic.woff2 differ diff --git a/services-src/auth/resources/static/fonts/InterDisplay-ExtraBold.woff2 b/services-src/auth/resources/static/fonts/InterDisplay-ExtraBold.woff2 new file mode 100644 index 0000000..9058e98 Binary files /dev/null and b/services-src/auth/resources/static/fonts/InterDisplay-ExtraBold.woff2 differ diff --git a/services-src/auth/resources/static/fonts/InterDisplay-ExtraBoldItalic.woff2 b/services-src/auth/resources/static/fonts/InterDisplay-ExtraBoldItalic.woff2 new file mode 100644 index 0000000..4cd61c0 Binary files /dev/null and b/services-src/auth/resources/static/fonts/InterDisplay-ExtraBoldItalic.woff2 differ diff --git a/services-src/auth/resources/static/fonts/InterDisplay-ExtraLight.woff2 b/services-src/auth/resources/static/fonts/InterDisplay-ExtraLight.woff2 new file mode 100644 index 0000000..8621b29 Binary files /dev/null and b/services-src/auth/resources/static/fonts/InterDisplay-ExtraLight.woff2 differ diff --git a/services-src/auth/resources/static/fonts/InterDisplay-ExtraLightItalic.woff2 b/services-src/auth/resources/static/fonts/InterDisplay-ExtraLightItalic.woff2 new file mode 100644 index 0000000..689c8d9 Binary files /dev/null and b/services-src/auth/resources/static/fonts/InterDisplay-ExtraLightItalic.woff2 differ diff --git a/services-src/auth/resources/static/fonts/InterDisplay-Italic.woff2 b/services-src/auth/resources/static/fonts/InterDisplay-Italic.woff2 new file mode 100644 index 0000000..11f20bc Binary files /dev/null and b/services-src/auth/resources/static/fonts/InterDisplay-Italic.woff2 differ diff --git a/services-src/auth/resources/static/fonts/InterDisplay-Light.woff2 b/services-src/auth/resources/static/fonts/InterDisplay-Light.woff2 new file mode 100644 index 0000000..446301c Binary files /dev/null and b/services-src/auth/resources/static/fonts/InterDisplay-Light.woff2 differ diff --git a/services-src/auth/resources/static/fonts/InterDisplay-LightItalic.woff2 b/services-src/auth/resources/static/fonts/InterDisplay-LightItalic.woff2 new file mode 100644 index 0000000..f688196 Binary files /dev/null and b/services-src/auth/resources/static/fonts/InterDisplay-LightItalic.woff2 differ diff --git a/services-src/auth/resources/static/fonts/InterDisplay-Medium.woff2 b/services-src/auth/resources/static/fonts/InterDisplay-Medium.woff2 new file mode 100644 index 0000000..29160b2 Binary files /dev/null and b/services-src/auth/resources/static/fonts/InterDisplay-Medium.woff2 differ diff --git a/services-src/auth/resources/static/fonts/InterDisplay-MediumItalic.woff2 b/services-src/auth/resources/static/fonts/InterDisplay-MediumItalic.woff2 new file mode 100644 index 0000000..ef1bcbe Binary files /dev/null and b/services-src/auth/resources/static/fonts/InterDisplay-MediumItalic.woff2 differ diff --git a/services-src/auth/resources/static/fonts/InterDisplay-Regular.woff2 b/services-src/auth/resources/static/fonts/InterDisplay-Regular.woff2 new file mode 100644 index 0000000..a6c04f6 Binary files /dev/null and b/services-src/auth/resources/static/fonts/InterDisplay-Regular.woff2 differ diff --git a/services-src/auth/resources/static/fonts/InterDisplay-SemiBold.woff2 b/services-src/auth/resources/static/fonts/InterDisplay-SemiBold.woff2 new file mode 100644 index 0000000..2b4db23 Binary files /dev/null and b/services-src/auth/resources/static/fonts/InterDisplay-SemiBold.woff2 differ diff --git a/services-src/auth/resources/static/fonts/InterDisplay-SemiBoldItalic.woff2 b/services-src/auth/resources/static/fonts/InterDisplay-SemiBoldItalic.woff2 new file mode 100644 index 0000000..59091db Binary files /dev/null and b/services-src/auth/resources/static/fonts/InterDisplay-SemiBoldItalic.woff2 differ diff --git a/services-src/auth/resources/static/fonts/InterDisplay-Thin.woff2 b/services-src/auth/resources/static/fonts/InterDisplay-Thin.woff2 new file mode 100644 index 0000000..dc0b948 Binary files /dev/null and b/services-src/auth/resources/static/fonts/InterDisplay-Thin.woff2 differ diff --git a/services-src/auth/resources/static/fonts/InterDisplay-ThinItalic.woff2 b/services-src/auth/resources/static/fonts/InterDisplay-ThinItalic.woff2 new file mode 100644 index 0000000..96439c0 Binary files /dev/null and b/services-src/auth/resources/static/fonts/InterDisplay-ThinItalic.woff2 differ diff --git a/services-src/auth/resources/static/fonts/InterVariable-Italic.woff2 b/services-src/auth/resources/static/fonts/InterVariable-Italic.woff2 new file mode 100644 index 0000000..f22ec25 Binary files /dev/null and b/services-src/auth/resources/static/fonts/InterVariable-Italic.woff2 differ diff --git a/services-src/auth/resources/static/fonts/InterVariable.woff2 b/services-src/auth/resources/static/fonts/InterVariable.woff2 new file mode 100644 index 0000000..22a12b0 Binary files /dev/null and b/services-src/auth/resources/static/fonts/InterVariable.woff2 differ diff --git a/services-src/auth/resources/static/fonts/inter.css b/services-src/auth/resources/static/fonts/inter.css new file mode 100644 index 0000000..413e197 --- /dev/null +++ b/services-src/auth/resources/static/fonts/inter.css @@ -0,0 +1,57 @@ +/* Variable fonts usage: +:root { font-family: "Inter", sans-serif; } +@supports (font-variation-settings: normal) { + :root { font-family: "InterVariable", sans-serif; font-optical-sizing: auto; } +} */ +@font-face { + font-family: InterVariable; + font-style: normal; + font-weight: 100 900; + font-display: swap; + src: url("InterVariable.woff2") format("woff2"); +} +@font-face { + font-family: InterVariable; + font-style: italic; + font-weight: 100 900; + font-display: swap; + src: url("InterVariable-Italic.woff2") format("woff2"); +} + +/* static fonts */ +@font-face { font-family: "Inter"; font-style: normal; font-weight: 100; font-display: swap; src: url("Inter-Thin.woff2") format("woff2"); } +@font-face { font-family: "Inter"; font-style: italic; font-weight: 100; font-display: swap; src: url("Inter-ThinItalic.woff2") format("woff2"); } +@font-face { font-family: "Inter"; font-style: normal; font-weight: 200; font-display: swap; src: url("Inter-ExtraLight.woff2") format("woff2"); } +@font-face { font-family: "Inter"; font-style: italic; font-weight: 200; font-display: swap; src: url("Inter-ExtraLightItalic.woff2") format("woff2"); } +@font-face { font-family: "Inter"; font-style: normal; font-weight: 300; font-display: swap; src: url("Inter-Light.woff2") format("woff2"); } +@font-face { font-family: "Inter"; font-style: italic; font-weight: 300; font-display: swap; src: url("Inter-LightItalic.woff2") format("woff2"); } +@font-face { font-family: "Inter"; font-style: normal; font-weight: 400; font-display: swap; src: url("Inter-Regular.woff2") format("woff2"); } +@font-face { font-family: "Inter"; font-style: italic; font-weight: 400; font-display: swap; src: url("Inter-Italic.woff2") format("woff2"); } +@font-face { font-family: "Inter"; font-style: normal; font-weight: 500; font-display: swap; src: url("Inter-Medium.woff2") format("woff2"); } +@font-face { font-family: "Inter"; font-style: italic; font-weight: 500; font-display: swap; src: url("Inter-MediumItalic.woff2") format("woff2"); } +@font-face { font-family: "Inter"; font-style: normal; font-weight: 600; font-display: swap; src: url("Inter-SemiBold.woff2") format("woff2"); } +@font-face { font-family: "Inter"; font-style: italic; font-weight: 600; font-display: swap; src: url("Inter-SemiBoldItalic.woff2") format("woff2"); } +@font-face { font-family: "Inter"; font-style: normal; font-weight: 700; font-display: swap; src: url("Inter-Bold.woff2") format("woff2"); } +@font-face { font-family: "Inter"; font-style: italic; font-weight: 700; font-display: swap; src: url("Inter-BoldItalic.woff2") format("woff2"); } +@font-face { font-family: "Inter"; font-style: normal; font-weight: 800; font-display: swap; src: url("Inter-ExtraBold.woff2") format("woff2"); } +@font-face { font-family: "Inter"; font-style: italic; font-weight: 800; font-display: swap; src: url("Inter-ExtraBoldItalic.woff2") format("woff2"); } +@font-face { font-family: "Inter"; font-style: normal; font-weight: 900; font-display: swap; src: url("Inter-Black.woff2") format("woff2"); } +@font-face { font-family: "Inter"; font-style: italic; font-weight: 900; font-display: swap; src: url("Inter-BlackItalic.woff2") format("woff2"); } +@font-face { font-family: "InterDisplay"; font-style: normal; font-weight: 100; font-display: swap; src: url("InterDisplay-Thin.woff2") format("woff2"); } +@font-face { font-family: "InterDisplay"; font-style: italic; font-weight: 100; font-display: swap; src: url("InterDisplay-ThinItalic.woff2") format("woff2"); } +@font-face { font-family: "InterDisplay"; font-style: normal; font-weight: 200; font-display: swap; src: url("InterDisplay-ExtraLight.woff2") format("woff2"); } +@font-face { font-family: "InterDisplay"; font-style: italic; font-weight: 200; font-display: swap; src: url("InterDisplay-ExtraLightItalic.woff2") format("woff2"); } +@font-face { font-family: "InterDisplay"; font-style: normal; font-weight: 300; font-display: swap; src: url("InterDisplay-Light.woff2") format("woff2"); } +@font-face { font-family: "InterDisplay"; font-style: italic; font-weight: 300; font-display: swap; src: url("InterDisplay-LightItalic.woff2") format("woff2"); } +@font-face { font-family: "InterDisplay"; font-style: normal; font-weight: 400; font-display: swap; src: url("InterDisplay-Regular.woff2") format("woff2"); } +@font-face { font-family: "InterDisplay"; font-style: italic; font-weight: 400; font-display: swap; src: url("InterDisplay-Italic.woff2") format("woff2"); } +@font-face { font-family: "InterDisplay"; font-style: normal; font-weight: 500; font-display: swap; src: url("InterDisplay-Medium.woff2") format("woff2"); } +@font-face { font-family: "InterDisplay"; font-style: italic; font-weight: 500; font-display: swap; src: url("InterDisplay-MediumItalic.woff2") format("woff2"); } +@font-face { font-family: "InterDisplay"; font-style: normal; font-weight: 600; font-display: swap; src: url("InterDisplay-SemiBold.woff2") format("woff2"); } +@font-face { font-family: "InterDisplay"; font-style: italic; font-weight: 600; font-display: swap; src: url("InterDisplay-SemiBoldItalic.woff2") format("woff2"); } +@font-face { font-family: "InterDisplay"; font-style: normal; font-weight: 700; font-display: swap; src: url("InterDisplay-Bold.woff2") format("woff2"); } +@font-face { font-family: "InterDisplay"; font-style: italic; font-weight: 700; font-display: swap; src: url("InterDisplay-BoldItalic.woff2") format("woff2"); } +@font-face { font-family: "InterDisplay"; font-style: normal; font-weight: 800; font-display: swap; src: url("InterDisplay-ExtraBold.woff2") format("woff2"); } +@font-face { font-family: "InterDisplay"; font-style: italic; font-weight: 800; font-display: swap; src: url("InterDisplay-ExtraBoldItalic.woff2") format("woff2"); } +@font-face { font-family: "InterDisplay"; font-style: normal; font-weight: 900; font-display: swap; src: url("InterDisplay-Black.woff2") format("woff2"); } +@font-face { font-family: "InterDisplay"; font-style: italic; font-weight: 900; font-display: swap; src: url("InterDisplay-BlackItalic.woff2") format("woff2"); } diff --git a/services-src/auth/resources/static/img/background.jpg b/services-src/auth/resources/static/img/background.jpg new file mode 100644 index 0000000..585ef41 Binary files /dev/null and b/services-src/auth/resources/static/img/background.jpg differ diff --git a/services-src/auth/resources/static/img/background.png b/services-src/auth/resources/static/img/background.png new file mode 100644 index 0000000..c745407 Binary files /dev/null and b/services-src/auth/resources/static/img/background.png differ diff --git a/services-src/auth/resources/static/js/logout.js b/services-src/auth/resources/static/js/logout.js new file mode 100644 index 0000000..656369a --- /dev/null +++ b/services-src/auth/resources/static/js/logout.js @@ -0,0 +1,7 @@ +// @license magnet:?xt=urn:btih:0ef1b8170b3b615170ff270def6427c317705f85&dn=lgpl-3.0.txt LGPL-3.0 +// This sad excuse for a script is used so LibreJS doesn't scream at me + +localStorage.clear() +window.location.replace("/login" + window.location.search) + +// @license-end \ No newline at end of file diff --git a/services-src/auth/resources/static/js/wasm_exec.js b/services-src/auth/resources/static/js/wasm_exec.js new file mode 100644 index 0000000..d0f279c --- /dev/null +++ b/services-src/auth/resources/static/js/wasm_exec.js @@ -0,0 +1,583 @@ +// @license magnet:?xt=urn:btih:0ef1b8170b3b615170ff270def6427c317705f85&dn=lgpl-3.0.txt LGPL-3.0 + +/* + * wasm_helper + * (c) Arzumify + * @license LGPL-3.0 + */ + +async function loadWasm(url) { + const go = new Go(); + WebAssembly.instantiateStreaming(fetch(url), go.importObject).then((result) => { + go.run(result.instance); + }) +} + +// @license-end +// @license magnet:?xt=urn:btih:c80d50af7d3db9be66a4d0a86db0286e4fd33292&dn=bsd-3-clause.txt BSD-3-Clause + +/* + * wasm_exec (https://github.com/golang/go) + * (c) The Go Authors + * @license BSD-3-Clause + */ + +"use strict"; + +(() => { + const enosys = () => { + const err = new Error("not implemented"); + err.code = "ENOSYS"; + return err; + }; + + if (!globalThis.fs) { + let outputBuf = ""; + globalThis.fs = { + constants: { O_WRONLY: -1, O_RDWR: -1, O_CREAT: -1, O_TRUNC: -1, O_APPEND: -1, O_EXCL: -1 }, // unused + writeSync(fd, buf) { + outputBuf += decoder.decode(buf); + const nl = outputBuf.lastIndexOf("\n"); + if (nl != -1) { + console.log(outputBuf.substring(0, nl)); + outputBuf = outputBuf.substring(nl + 1); + } + return buf.length; + }, + write(fd, buf, offset, length, position, callback) { + if (offset !== 0 || length !== buf.length || position !== null) { + callback(enosys()); + return; + } + const n = this.writeSync(fd, buf); + callback(null, n); + }, + chmod(path, mode, callback) { callback(enosys()); }, + chown(path, uid, gid, callback) { callback(enosys()); }, + close(fd, callback) { callback(enosys()); }, + fchmod(fd, mode, callback) { callback(enosys()); }, + fchown(fd, uid, gid, callback) { callback(enosys()); }, + fstat(fd, callback) { callback(enosys()); }, + fsync(fd, callback) { callback(null); }, + ftruncate(fd, length, callback) { callback(enosys()); }, + lchown(path, uid, gid, callback) { callback(enosys()); }, + link(path, link, callback) { callback(enosys()); }, + lstat(path, callback) { callback(enosys()); }, + mkdir(path, perm, callback) { callback(enosys()); }, + open(path, flags, mode, callback) { callback(enosys()); }, + read(fd, buffer, offset, length, position, callback) { callback(enosys()); }, + readdir(path, callback) { callback(enosys()); }, + readlink(path, callback) { callback(enosys()); }, + rename(from, to, callback) { callback(enosys()); }, + rmdir(path, callback) { callback(enosys()); }, + stat(path, callback) { callback(enosys()); }, + symlink(path, link, callback) { callback(enosys()); }, + truncate(path, length, callback) { callback(enosys()); }, + unlink(path, callback) { callback(enosys()); }, + utimes(path, atime, mtime, callback) { callback(enosys()); }, + }; + } + + if (!globalThis.process) { + globalThis.process = { + getuid() { return -1; }, + getgid() { return -1; }, + geteuid() { return -1; }, + getegid() { return -1; }, + getgroups() { throw enosys(); }, + pid: -1, + ppid: -1, + umask() { throw enosys(); }, + cwd() { throw enosys(); }, + chdir() { throw enosys(); }, + } + } + + if (!globalThis.crypto) { + throw new Error("globalThis.crypto is not available, polyfill required (crypto.getRandomValues only)"); + } + + if (!globalThis.performance) { + throw new Error("globalThis.performance is not available, polyfill required (performance.now only)"); + } + + if (!globalThis.TextEncoder) { + throw new Error("globalThis.TextEncoder is not available, polyfill required"); + } + + if (!globalThis.TextDecoder) { + throw new Error("globalThis.TextDecoder is not available, polyfill required"); + } + + const encoder = new TextEncoder("utf-8"); + const decoder = new TextDecoder("utf-8"); + + globalThis.Go = class { + constructor() { + this.argv = ["js"]; + this.env = {}; + this.exit = (code) => { + if (code !== 0) { + console.warn("exit code:", code); + } + }; + this._exitPromise = new Promise((resolve) => { + this._resolveExitPromise = resolve; + }); + this._pendingEvent = null; + this._scheduledTimeouts = new Map(); + this._nextCallbackTimeoutID = 1; + + const setInt64 = (addr, v) => { + this.mem.setUint32(addr + 0, v, true); + this.mem.setUint32(addr + 4, Math.floor(v / 4294967296), true); + } + + const setInt32 = (addr, v) => { + this.mem.setUint32(addr + 0, v, true); + } + + const getInt64 = (addr) => { + const low = this.mem.getUint32(addr + 0, true); + const high = this.mem.getInt32(addr + 4, true); + return low + high * 4294967296; + } + + const loadValue = (addr) => { + const f = this.mem.getFloat64(addr, true); + if (f === 0) { + return undefined; + } + if (!isNaN(f)) { + return f; + } + + const id = this.mem.getUint32(addr, true); + return this._values[id]; + } + + const storeValue = (addr, v) => { + const nanHead = 0x7FF80000; + + if (typeof v === "number" && v !== 0) { + if (isNaN(v)) { + this.mem.setUint32(addr + 4, nanHead, true); + this.mem.setUint32(addr, 0, true); + return; + } + this.mem.setFloat64(addr, v, true); + return; + } + + if (v === undefined) { + this.mem.setFloat64(addr, 0, true); + return; + } + + let id = this._ids.get(v); + if (id === undefined) { + id = this._idPool.pop(); + if (id === undefined) { + id = this._values.length; + } + this._values[id] = v; + this._goRefCounts[id] = 0; + this._ids.set(v, id); + } + this._goRefCounts[id]++; + let typeFlag = 0; + switch (typeof v) { + case "object": + if (v !== null) { + typeFlag = 1; + } + break; + case "string": + typeFlag = 2; + break; + case "symbol": + typeFlag = 3; + break; + case "function": + typeFlag = 4; + break; + } + this.mem.setUint32(addr + 4, nanHead | typeFlag, true); + this.mem.setUint32(addr, id, true); + } + + const loadSlice = (addr) => { + const array = getInt64(addr + 0); + const len = getInt64(addr + 8); + return new Uint8Array(this._inst.exports.mem.buffer, array, len); + } + + const loadSliceOfValues = (addr) => { + const array = getInt64(addr + 0); + const len = getInt64(addr + 8); + const a = new Array(len); + for (let i = 0; i < len; i++) { + a[i] = loadValue(array + i * 8); + } + return a; + } + + const loadString = (addr) => { + const saddr = getInt64(addr + 0); + const len = getInt64(addr + 8); + return decoder.decode(new DataView(this._inst.exports.mem.buffer, saddr, len)); + } + + const timeOrigin = Date.now() - performance.now(); + this.importObject = { + _gotest: { + add: (a, b) => a + b, + }, + gojs: { + // Go's SP does not change as long as no Go code is running. Some operations (e.g. calls, getters and setters) + // may synchronously trigger a Go event handler. This makes Go code get executed in the middle of the imported + // function. A goroutine can switch to a new stack if the current stack is too small (see morestack function). + // This changes the SP, thus we have to update the SP used by the imported function. + + // func wasmExit(code int32) + "runtime.wasmExit": (sp) => { + sp >>>= 0; + const code = this.mem.getInt32(sp + 8, true); + this.exited = true; + delete this._inst; + delete this._values; + delete this._goRefCounts; + delete this._ids; + delete this._idPool; + this.exit(code); + }, + + // func wasmWrite(fd uintptr, p unsafe.Pointer, n int32) + "runtime.wasmWrite": (sp) => { + sp >>>= 0; + const fd = getInt64(sp + 8); + const p = getInt64(sp + 16); + const n = this.mem.getInt32(sp + 24, true); + fs.writeSync(fd, new Uint8Array(this._inst.exports.mem.buffer, p, n)); + }, + + // func resetMemoryDataView() + "runtime.resetMemoryDataView": (sp) => { + sp >>>= 0; + this.mem = new DataView(this._inst.exports.mem.buffer); + }, + + // func nanotime1() int64 + "runtime.nanotime1": (sp) => { + sp >>>= 0; + setInt64(sp + 8, (timeOrigin + performance.now()) * 1000000); + }, + + // func walltime() (sec int64, nsec int32) + "runtime.walltime": (sp) => { + sp >>>= 0; + const msec = (new Date).getTime(); + setInt64(sp + 8, msec / 1000); + this.mem.setInt32(sp + 16, (msec % 1000) * 1000000, true); + }, + + // func scheduleTimeoutEvent(delay int64) int32 + "runtime.scheduleTimeoutEvent": (sp) => { + sp >>>= 0; + const id = this._nextCallbackTimeoutID; + this._nextCallbackTimeoutID++; + this._scheduledTimeouts.set(id, setTimeout( + () => { + this._resume(); + while (this._scheduledTimeouts.has(id)) { + // for some reason Go failed to register the timeout event, log and try again + // (temporary workaround for https://github.com/golang/go/issues/28975) + console.warn("scheduleTimeoutEvent: missed timeout event"); + this._resume(); + } + }, + getInt64(sp + 8), + )); + this.mem.setInt32(sp + 16, id, true); + }, + + // func clearTimeoutEvent(id int32) + "runtime.clearTimeoutEvent": (sp) => { + sp >>>= 0; + const id = this.mem.getInt32(sp + 8, true); + clearTimeout(this._scheduledTimeouts.get(id)); + this._scheduledTimeouts.delete(id); + }, + + // func getRandomData(r []byte) + "runtime.getRandomData": (sp) => { + sp >>>= 0; + crypto.getRandomValues(loadSlice(sp + 8)); + }, + + // func finalizeRef(v ref) + "syscall/js.finalizeRef": (sp) => { + sp >>>= 0; + const id = this.mem.getUint32(sp + 8, true); + this._goRefCounts[id]--; + if (this._goRefCounts[id] === 0) { + const v = this._values[id]; + this._values[id] = null; + this._ids.delete(v); + this._idPool.push(id); + } + }, + + // func stringVal(value string) ref + "syscall/js.stringVal": (sp) => { + sp >>>= 0; + storeValue(sp + 24, loadString(sp + 8)); + }, + + // func valueGet(v ref, p string) ref + "syscall/js.valueGet": (sp) => { + sp >>>= 0; + const result = Reflect.get(loadValue(sp + 8), loadString(sp + 16)); + sp = this._inst.exports.getsp() >>> 0; // see comment above + storeValue(sp + 32, result); + }, + + // func valueSet(v ref, p string, x ref) + "syscall/js.valueSet": (sp) => { + sp >>>= 0; + Reflect.set(loadValue(sp + 8), loadString(sp + 16), loadValue(sp + 32)); + }, + + // func valueDelete(v ref, p string) + "syscall/js.valueDelete": (sp) => { + sp >>>= 0; + Reflect.deleteProperty(loadValue(sp + 8), loadString(sp + 16)); + }, + + // func valueIndex(v ref, i int) ref + "syscall/js.valueIndex": (sp) => { + sp >>>= 0; + storeValue(sp + 24, Reflect.get(loadValue(sp + 8), getInt64(sp + 16))); + }, + + // valueSetIndex(v ref, i int, x ref) + "syscall/js.valueSetIndex": (sp) => { + sp >>>= 0; + Reflect.set(loadValue(sp + 8), getInt64(sp + 16), loadValue(sp + 24)); + }, + + // func valueCall(v ref, m string, args []ref) (ref, bool) + "syscall/js.valueCall": (sp) => { + sp >>>= 0; + try { + const v = loadValue(sp + 8); + const m = Reflect.get(v, loadString(sp + 16)); + const args = loadSliceOfValues(sp + 32); + const result = Reflect.apply(m, v, args); + sp = this._inst.exports.getsp() >>> 0; // see comment above + storeValue(sp + 56, result); + this.mem.setUint8(sp + 64, 1); + } catch (err) { + sp = this._inst.exports.getsp() >>> 0; // see comment above + storeValue(sp + 56, err); + this.mem.setUint8(sp + 64, 0); + } + }, + + // func valueInvoke(v ref, args []ref) (ref, bool) + "syscall/js.valueInvoke": (sp) => { + sp >>>= 0; + try { + const v = loadValue(sp + 8); + const args = loadSliceOfValues(sp + 16); + const result = Reflect.apply(v, undefined, args); + sp = this._inst.exports.getsp() >>> 0; // see comment above + storeValue(sp + 40, result); + this.mem.setUint8(sp + 48, 1); + } catch (err) { + sp = this._inst.exports.getsp() >>> 0; // see comment above + storeValue(sp + 40, err); + this.mem.setUint8(sp + 48, 0); + } + }, + + // func valueNew(v ref, args []ref) (ref, bool) + "syscall/js.valueNew": (sp) => { + sp >>>= 0; + try { + const v = loadValue(sp + 8); + const args = loadSliceOfValues(sp + 16); + const result = Reflect.construct(v, args); + sp = this._inst.exports.getsp() >>> 0; // see comment above + storeValue(sp + 40, result); + this.mem.setUint8(sp + 48, 1); + } catch (err) { + sp = this._inst.exports.getsp() >>> 0; // see comment above + storeValue(sp + 40, err); + this.mem.setUint8(sp + 48, 0); + } + }, + + // func valueLength(v ref) int + "syscall/js.valueLength": (sp) => { + sp >>>= 0; + setInt64(sp + 16, parseInt(loadValue(sp + 8).length)); + }, + + // valuePrepareString(v ref) (ref, int) + "syscall/js.valuePrepareString": (sp) => { + sp >>>= 0; + const str = encoder.encode(String(loadValue(sp + 8))); + storeValue(sp + 16, str); + setInt64(sp + 24, str.length); + }, + + // valueLoadString(v ref, b []byte) + "syscall/js.valueLoadString": (sp) => { + sp >>>= 0; + const str = loadValue(sp + 8); + loadSlice(sp + 16).set(str); + }, + + // func valueInstanceOf(v ref, t ref) bool + "syscall/js.valueInstanceOf": (sp) => { + sp >>>= 0; + this.mem.setUint8(sp + 24, (loadValue(sp + 8) instanceof loadValue(sp + 16)) ? 1 : 0); + }, + + // func copyBytesToGo(dst []byte, src ref) (int, bool) + "syscall/js.copyBytesToGo": (sp) => { + sp >>>= 0; + const dst = loadSlice(sp + 8); + const src = loadValue(sp + 32); + if (!(src instanceof Uint8Array || src instanceof Uint8ClampedArray)) { + this.mem.setUint8(sp + 48, 0); + return; + } + const toCopy = src.subarray(0, dst.length); + dst.set(toCopy); + setInt64(sp + 40, toCopy.length); + this.mem.setUint8(sp + 48, 1); + }, + + // func copyBytesToJS(dst ref, src []byte) (int, bool) + "syscall/js.copyBytesToJS": (sp) => { + sp >>>= 0; + const dst = loadValue(sp + 8); + const src = loadSlice(sp + 16); + if (!(dst instanceof Uint8Array || dst instanceof Uint8ClampedArray)) { + this.mem.setUint8(sp + 48, 0); + return; + } + const toCopy = src.subarray(0, dst.length); + dst.set(toCopy); + setInt64(sp + 40, toCopy.length); + this.mem.setUint8(sp + 48, 1); + }, + + "debug": (value) => { + console.log(value); + }, + } + }; + } + + async run(instance) { + if (!(instance instanceof WebAssembly.Instance)) { + throw new Error("Go.run: WebAssembly.Instance expected"); + } + this._inst = instance; + this.mem = new DataView(this._inst.exports.mem.buffer); + this._values = [ // JS values that Go currently has references to, indexed by reference id + NaN, + 0, + null, + true, + false, + globalThis, + this, + ]; + this._goRefCounts = new Array(this._values.length).fill(Infinity); // number of references that Go has to a JS value, indexed by reference id + this._ids = new Map([ // mapping from JS values to reference ids + [0, 1], + [null, 2], + [true, 3], + [false, 4], + [globalThis, 5], + [this, 6], + ]); + this._idPool = []; // unused ids that have been garbage collected + this.exited = false; // whether the Go program has exited + + // Pass command line arguments and environment variables to WebAssembly by writing them to the linear memory. + let offset = 4096; + + const strPtr = (str) => { + const ptr = offset; + const bytes = encoder.encode(str + "\0"); + new Uint8Array(this.mem.buffer, offset, bytes.length).set(bytes); + offset += bytes.length; + if (offset % 8 !== 0) { + offset += 8 - (offset % 8); + } + return ptr; + }; + + const argc = this.argv.length; + + const argvPtrs = []; + this.argv.forEach((arg) => { + argvPtrs.push(strPtr(arg)); + }); + argvPtrs.push(0); + + const keys = Object.keys(this.env).sort(); + keys.forEach((key) => { + argvPtrs.push(strPtr(`${key}=${this.env[key]}`)); + }); + argvPtrs.push(0); + + const argv = offset; + argvPtrs.forEach((ptr) => { + this.mem.setUint32(offset, ptr, true); + this.mem.setUint32(offset + 4, 0, true); + offset += 8; + }); + + // The linker guarantees global data starts from at least wasmMinDataAddr. + // Keep in sync with cmd/link/internal/ld/data.go:wasmMinDataAddr. + const wasmMinDataAddr = 4096 + 8192; + if (offset >= wasmMinDataAddr) { + throw new Error("total length of command line and environment variables exceeds limit"); + } + + this._inst.exports.run(argc, argv); + if (this.exited) { + this._resolveExitPromise(); + } + await this._exitPromise; + } + + _resume() { + if (this.exited) { + throw new Error("Go program has already exited"); + } + this._inst.exports.resume(); + if (this.exited) { + this._resolveExitPromise(); + } + } + + _makeFuncWrapper(id) { + const go = this; + return function () { + const event = { id: id, this: this, args: arguments }; + go._pendingEvent = event; + go._resume(); + return event.result; + }; + } + } +})(); + +// @license-end \ No newline at end of file diff --git a/services-src/auth/resources/static/svg/device_computer.svg b/services-src/auth/resources/static/svg/device_computer.svg new file mode 100644 index 0000000..5981880 --- /dev/null +++ b/services-src/auth/resources/static/svg/device_computer.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/services-src/auth/resources/static/svg/device_other.svg b/services-src/auth/resources/static/svg/device_other.svg new file mode 100644 index 0000000..410be0d --- /dev/null +++ b/services-src/auth/resources/static/svg/device_other.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/services-src/auth/resources/static/svg/device_smartphone.svg b/services-src/auth/resources/static/svg/device_smartphone.svg new file mode 100644 index 0000000..100f589 --- /dev/null +++ b/services-src/auth/resources/static/svg/device_smartphone.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/services-src/auth/resources/static/svg/device_terminal.svg b/services-src/auth/resources/static/svg/device_terminal.svg new file mode 100644 index 0000000..f8b0038 --- /dev/null +++ b/services-src/auth/resources/static/svg/device_terminal.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/services-src/auth/resources/static/svg/gopher.svg b/services-src/auth/resources/static/svg/gopher.svg new file mode 100644 index 0000000..d6451bf --- /dev/null +++ b/services-src/auth/resources/static/svg/gopher.svg @@ -0,0 +1,174 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/services-src/auth/resources/templates/authorize.html b/services-src/auth/resources/templates/authorize.html new file mode 100644 index 0000000..b74dfa6 --- /dev/null +++ b/services-src/auth/resources/templates/authorize.html @@ -0,0 +1,32 @@ + + + Authorize application - {{ .identifier }} + + + + + + + + + + + + +
+

Authorise Application

+

Loading...

+
+
+ + +
+
+ Return to Dashboard +
+ + + + diff --git a/services-src/auth/resources/templates/autoAccept.html b/services-src/auth/resources/templates/autoAccept.html new file mode 100644 index 0000000..63d0894 --- /dev/null +++ b/services-src/auth/resources/templates/autoAccept.html @@ -0,0 +1,25 @@ + + + Redirecting... - {{ .identifier }} + + + + + + + + + + + + +
+

Authorizing application

+

Please wait...

+
+ + + + diff --git a/services-src/auth/resources/templates/clientKeyShare.html b/services-src/auth/resources/templates/clientKeyShare.html new file mode 100644 index 0000000..f5b5b97 --- /dev/null +++ b/services-src/auth/resources/templates/clientKeyShare.html @@ -0,0 +1,22 @@ + + + + Key Exchange - {{ .identifier }} + + + + + + + + + +
+

Relaying back information, please wait...

+

Processing information sent...

+
+ + + diff --git a/services-src/auth/resources/templates/dashboard.html b/services-src/auth/resources/templates/dashboard.html new file mode 100644 index 0000000..d91f883 --- /dev/null +++ b/services-src/auth/resources/templates/dashboard.html @@ -0,0 +1,54 @@ + + + + Dashboard - {{ .identifier }} + + + + + + + + + +
+

Dashboard

+

Welcome to the {{ .identifier }} dashboard!

+ +
+ +
+
+

Account settings

+

Loading...

+

+
+ +
+
+

Sessions

+
+
+ + + diff --git a/services-src/auth/resources/templates/login.html b/services-src/auth/resources/templates/login.html new file mode 100644 index 0000000..96653b2 --- /dev/null +++ b/services-src/auth/resources/templates/login.html @@ -0,0 +1,36 @@ + + + + + Login - {{ .identifier }} + + + + + + + + + + + +
+

Login

+

+
+
+ + +
+ + + +
+
+ Privacy & Terms +
+ + + diff --git a/services-src/auth/resources/templates/logout.html b/services-src/auth/resources/templates/logout.html new file mode 100644 index 0000000..6324c8a --- /dev/null +++ b/services-src/auth/resources/templates/logout.html @@ -0,0 +1,15 @@ + + + + + Log out - {{ .identifier }} + + + + + + + +

Logging out...

+ + diff --git a/services-src/auth/resources/templates/openid.json b/services-src/auth/resources/templates/openid.json new file mode 100644 index 0000000..33d6719 --- /dev/null +++ b/services-src/auth/resources/templates/openid.json @@ -0,0 +1,9 @@ +{ + "issuer": "{{ .hostName }}", + "authorization_endpoint": "{{ .hostName }}/authorize", + "token_endpoint": "{{ .hostName }}/api/oauth/token", + "userinfo_endpoint": "{{ .hostName }}/api/oauth/userinfo", + "jwks_uri": "{{ .hostName }}/.well-known/keys.json", + "response_types_supported": ["code"], + "subject_types_supported": ["public"] +} diff --git a/services-src/auth/resources/templates/refresh.html b/services-src/auth/resources/templates/refresh.html new file mode 100644 index 0000000..2a118e4 --- /dev/null +++ b/services-src/auth/resources/templates/refresh.html @@ -0,0 +1,18 @@ + + + + + + + + + Please wait... + + + +

Please wait...

+

If your browser does not refresh, please refresh the page manually.

+ + \ No newline at end of file diff --git a/services-src/auth/resources/templates/signup.html b/services-src/auth/resources/templates/signup.html new file mode 100644 index 0000000..b37f57e --- /dev/null +++ b/services-src/auth/resources/templates/signup.html @@ -0,0 +1,41 @@ + + + + Signup - {{ .identifier }} + + + + + + + + + + +
+

Signup

+

Signup to {{ .identifier }}!

+

+ + + + + + + + + +
Username:
Password:
+
+ + +

+ Privacy & Terms +
+ + + + + \ No newline at end of file diff --git a/services-src/auth/resources/templates/testApp.html b/services-src/auth/resources/templates/testApp.html new file mode 100644 index 0000000..038724c --- /dev/null +++ b/services-src/auth/resources/templates/testApp.html @@ -0,0 +1,24 @@ + + + + Tester - {{ .identifier }} + + + + + + + + + +
+

{{ .identifier }} Tester

+

Click authorize to begin the test

+ +
+ + + + diff --git a/services-src/auth/resources/templates/testAppNotAvailable.html b/services-src/auth/resources/templates/testAppNotAvailable.html new file mode 100644 index 0000000..5fbae3a --- /dev/null +++ b/services-src/auth/resources/templates/testAppNotAvailable.html @@ -0,0 +1,18 @@ + + + + Tester - {{ .identifier }} + + + + + + + + +
+

{{ .identifier }} Tester

+

The tester has been disabled by the administrator.

+
+ + diff --git a/services-src/auth/resources/wasm/authorize/main.go b/services-src/auth/resources/wasm/authorize/main.go new file mode 100644 index 0000000..00c3251 --- /dev/null +++ b/services-src/auth/resources/wasm/authorize/main.go @@ -0,0 +1,217 @@ +package main + +import ( + "bytes" + "encoding/json" + "fmt" + "net/http" + "net/url" + "strings" + "syscall/js" +) + +func authorize(deny bool, query url.Values) { + // Get the token from local storage + localStorage := js.Global().Get("localStorage") + token := localStorage.Call("getItem", "DONOTSHARE-secretKey").String() + + // Fetch /api/authorize + requestUri, err := url.JoinPath(js.Global().Get("window").Get("location").Get("origin").String(), "/api/authorize") + if err != nil { + js.Global().Get("document").Call("getElementById", "statusBox").Set("innerText", "Error joining URL: "+err.Error()) + return + } + + authorizeBody := map[string]interface{}{ + "token": token, + "deny": deny, + "appId": query.Get("client_id"), + "redirectUri": query.Get("redirect_uri"), + } + + // Append the nonce if it exists + if query.Has("nonce") { + authorizeBody["nonce"] = query.Get("nonce") + } + + // Append the PKCE code challenge if it exists + if query.Has("code_challenge") { + authorizeBody["PKCECode"] = query.Get("code_challenge") + authorizeBody["PKCEMethod"] = query.Get("code_challenge_method") + } + + // Marshal the body + body, err := json.Marshal(authorizeBody) + if err != nil { + js.Global().Get("document").Call("getElementById", "statusBox").Set("innerText", "Error marshaling authorize body: "+err.Error()) + return + } + + // Send the request + response, err := http.Post(requestUri, "application/json", bytes.NewReader(body)) + if err != nil { + js.Global().Get("document").Call("getElementById", "statusBox").Set("innerText", "Error contacting server: "+err.Error()) + return + } + + // Get all our ducks in a row + var responseMap map[string]interface{} + + // Read the response + decoder := json.NewDecoder(response.Body) + err = decoder.Decode(&responseMap) + if err != nil { + js.Global().Get("document").Call("getElementById", "statusBox").Set("innerText", "Error decoding server response: "+err.Error()) + return + } + + // Close the response body + err = response.Body.Close() + if err != nil { + fmt.Println("Could not close response body: " + err.Error() + ", memory leaks may occur") + } + + if response.StatusCode == 200 { + if deny { + // Redirect to the redirect_uri with an error + denyUri := query.Get("redirect_uri") + "?error=access_denied" + if query.Has("state") { + denyUri += "&state=" + query.Get("state") + } + + js.Global().Get("window").Get("location").Call("replace", denyUri) + } else { + // Redirect to the redirect_uri with the code + allowUri := query.Get("redirect_uri") + "?code=" + responseMap["exchangeCode"].(string) + if query.Has("state") { + allowUri += "&state=" + query.Get("state") + } + + js.Global().Get("window").Get("location").Call("replace", allowUri) + } + } else if response.StatusCode == 401 { + js.Global().Get("document").Call("getElementById", "statusBox").Set("innerText", "OAuth screening failed! We could have just saved you from a bad actor!") + } else if response.StatusCode != 500 { + js.Global().Get("document").Call("getElementById", "statusBox").Set("innerText", responseMap["error"].(string)) + } else { + js.Global().Get("document").Call("getElementById", "statusBox").Set("innerText", "Something went wrong! (error code: "+responseMap["code"].(string)+")") + } +} + +func main() { + // Redirect to log-in if not signed in + localStorage := js.Global().Get("localStorage") + if localStorage.Call("getItem", "DONOTSHARE-secretKey").IsNull() { + js.Global().Get("window").Get("location").Call("replace", "/login"+js.Global().Get("window").Get("location").Get("search").String()) + } + + var query url.Values + + // Redirect to dashboard if client_id is not a URL parameter + if js.Global().Get("window").Get("location").Get("search").String() == "" { + js.Global().Get("window").Get("location").Call("replace", "/dashboard") + } else { + // Parse the url parameters using url.ParseQuery + var err error + query, err = url.ParseQuery(strings.TrimPrefix(js.Global().Get("window").Get("location").Get("search").String(), "?")) + if err != nil { + js.Global().Get("document").Call("getElementById", "statusBox").Set("innerText", "Error parsing URL query: "+err.Error()) + return + } + + // Redirect to dashboard if client_id is not a URL parameter + if !query.Has("client_id") { + js.Global().Get("window").Get("location").Call("replace", "/dashboard") + return + } + } + + var statusBox = js.Global().Get("document").Call("getElementById", "statusBox") + var autoAccept = js.Global().Get("document").Call("getElementById", "autoAccept") + + // Check if the token is valid + requestUri, err := url.JoinPath(js.Global().Get("window").Get("location").Get("origin").String(), "/api/loggedIn") + if err != nil { + statusBox.Set("innerText", "Error joining URL: "+err.Error()) + return + } + + loggedInBody := map[string]interface{}{ + "token": localStorage.Call("getItem", "DONOTSHARE-secretKey").String(), + } + + // Marshal the body + body, err := json.Marshal(loggedInBody) + if err != nil { + statusBox.Set("innerText", "Error marshaling signup body: "+err.Error()) + return + } + + response, err := http.Post(requestUri, "application/json", bytes.NewReader(body)) + if err != nil { + statusBox.Set("innerText", "Error contacting server: "+err.Error()) + return + } + + // Check if the response is 200 + if response.StatusCode == 401 { + // Close the response body + err = response.Body.Close() + if err != nil { + fmt.Println("Could not close response body: " + err.Error() + ", memory leaks may occur") + } + + // Redirect to log-out if not signed in + js.Global().Get("window").Get("location").Call("replace", "/logout"+js.Global().Get("window").Get("location").Get("search").String()) + return + } else if response.StatusCode == 500 { + // Read the response + var responseMap map[string]interface{} + decoder := json.NewDecoder(response.Body) + err = decoder.Decode(&responseMap) + if err != nil { + js.Global().Call("alert", "Error decoding server response: "+err.Error()) + return + } + + // Close the response body + err = response.Body.Close() + if err != nil { + fmt.Println("Could not close response body: " + err.Error() + ", memory leaks may occur") + } + + // Alert the user if the server is down + js.Global().Call("alert", "Something went wrong! (error code: "+responseMap["code"].(string)+")") + return + } + + // Close the response body + err = response.Body.Close() + if err != nil { + fmt.Println("Could not close response body: " + err.Error() + ", memory leaks may occur") + } + + if autoAccept.Get("innerText").String() == "0" { + // Change the status box to the authorization dialog + statusBox.Set("innerText", "Would you like to allow "+js.Global().Get("document").Call("getElementById", "passThrough").Get("innerText").String()+" to access your user information? You will be redirected to "+query.Get("redirect_uri")+" after you make your decision.") + + // Add an event listener to the Deny button + js.Global().Get("document").Call("getElementById", "denyButton").Call("addEventListener", "click", js.FuncOf(func(this js.Value, p []js.Value) interface{} { + // We still partially authorize the user to prevent open redirects + go authorize(true, query) + return nil + })) + + // Add an event listener to the Allow button + js.Global().Get("document").Call("getElementById", "allowButton").Call("addEventListener", "click", js.FuncOf(func(this js.Value, p []js.Value) interface{} { + go authorize(false, query) + return nil + })) + } else { + // Auto-accept the request, as it's from an internal service + go authorize(false, query) + } + + // Wait for events + select {} +} diff --git a/services-src/auth/resources/wasm/clientKeyShare/main.go b/services-src/auth/resources/wasm/clientKeyShare/main.go new file mode 100644 index 0000000..64e72a4 --- /dev/null +++ b/services-src/auth/resources/wasm/clientKeyShare/main.go @@ -0,0 +1,184 @@ +package main + +import ( + "bytes" + "crypto/aes" + "crypto/cipher" + "crypto/ecdh" + "crypto/rand" + "encoding/base64" + "encoding/json" + "fmt" + "net/http" + "net/url" + "strings" + "syscall/js" +) + +func main() { + // Redirect to log-in if not signed in + localStorage := js.Global().Get("localStorage") + if localStorage.Call("getItem", "DONOTSHARE-secretKey").IsNull() { + js.Global().Get("window").Get("location").Call("replace", "/login"+js.Global().Get("window").Get("location").Get("search").String()) + } + + statusBox := js.Global().Get("document").Call("getElementById", "statusBox") + + // Check if the token is valid + requestUri, err := url.JoinPath(js.Global().Get("window").Get("location").Get("origin").String(), "/api/loggedIn") + if err != nil { + statusBox.Set("innerText", "Error joining URL: "+err.Error()) + return + } + + loggedInBody := map[string]interface{}{ + "token": localStorage.Call("getItem", "DONOTSHARE-secretKey").String(), + } + + // Marshal the body + body, err := json.Marshal(loggedInBody) + if err != nil { + statusBox.Set("innerText", "Error marshaling signup body: "+err.Error()) + return + } + + response, err := http.Post(requestUri, "application/json", bytes.NewReader(body)) + if err != nil { + statusBox.Set("innerText", "Error contacting server: "+err.Error()) + return + } + + // Check if the response is 200 + if response.StatusCode == 401 { + // Close the response body + err = response.Body.Close() + if err != nil { + fmt.Println("Could not close response body: " + err.Error() + ", memory leaks may occur") + } + + // Redirect to log-out if not signed in + js.Global().Get("window").Get("location").Call("replace", "/logout"+js.Global().Get("window").Get("location").Get("search").String()) + return + } else if response.StatusCode == 500 { + // Read the response + var responseMap map[string]interface{} + decoder := json.NewDecoder(response.Body) + err = decoder.Decode(&responseMap) + if err != nil { + js.Global().Call("alert", "Error decoding server response: "+err.Error()) + return + } + + // Close the response body + err = response.Body.Close() + if err != nil { + fmt.Println("Could not close response body: " + err.Error() + ", memory leaks may occur") + } + + // Alert the user if the server is down + js.Global().Call("alert", "Something went wrong! (error code: "+responseMap["code"].(string)+")") + return + } + + // Close the response body + err = response.Body.Close() + if err != nil { + fmt.Println("Could not close response body: " + err.Error() + ", memory leaks may occur") + } + + query, err := url.ParseQuery(strings.TrimPrefix(js.Global().Get("window").Get("location").Get("search").String(), "?")) + if err != nil { + statusBox.Set("innerText", "Error parsing query: "+err.Error()) + return + } + + // Check if the access token we were given is valid and that the scope is correct + requestUri, err = url.JoinPath(js.Global().Get("window").Get("location").Get("origin").String(), "/api/oauth/clientKeyShare") + if err != nil { + statusBox.Set("innerText", "Error joining URL: "+err.Error()) + return + } + + request, err := http.NewRequest("GET", requestUri, nil) + if err != nil { + statusBox.Set("innerText", "Error creating request: "+err.Error()) + return + } + + request.Header.Set("Authorization", "Bearer "+query.Get("accessToken")) + + response, err = http.DefaultClient.Do(request) + if err != nil { + statusBox.Set("innerText", "Error contacting server: "+err.Error()) + return + } + + // Close the response body + err = response.Body.Close() + if err != nil { + fmt.Println("Could not close response body: " + err.Error() + ", memory leaks may occur") + } + + if response.StatusCode == 200 { + // Get the ECDH public key from the query string + clientKeyBytes, err := base64.URLEncoding.DecodeString(query.Get("ecdhPublicKey")) + if err != nil { + statusBox.Set("innerText", "Error decoding ECDH public key: "+err.Error()) + return + } + + // Encode the ECDH public key + key, err := ecdh.X25519().NewPublicKey(clientKeyBytes) + if err != nil { + statusBox.Set("innerText", "Error encoding ECDH public key: "+err.Error()) + return + } + + // Generate a new ECDH key pair + privateKey, err := ecdh.X25519().GenerateKey(rand.Reader) + if err != nil { + statusBox.Set("innerText", "Error generating ECDH key pair: "+err.Error()) + return + } + + // Generate the shared secret + sharedSecret, err := privateKey.ECDH(key) + if err != nil { + statusBox.Set("innerText", "Error generating shared secret: "+err.Error()) + return + } + + // AES-GCM encrypt the DONOTSHARE-clientKey + block, err := aes.NewCipher(sharedSecret) + if err != nil { + statusBox.Set("innerText", "Error creating AES cipher: "+err.Error()) + return + } + + gcm, err := cipher.NewGCM(block) + if err != nil { + statusBox.Set("innerText", "Error creating GCM cipher: "+err.Error()) + return + } + + nonce := make([]byte, gcm.NonceSize()) + _, err = rand.Read(nonce) + if err != nil { + statusBox.Set("innerText", "Error generating nonce: "+err.Error()) + return + } + + // Un-base64 the client key + decodedClientKey, err := base64.StdEncoding.DecodeString(localStorage.Call("getItem", "DONOTSHARE-clientKey").String()) + if err != nil { + statusBox.Set("innerText", "Error decoding client key: "+err.Error()) + return + } + + encryptedClientKey := gcm.Seal(nil, nonce, decodedClientKey, nil) + + // Redirect back to the referrer with the encrypted client key + redirectUri := strings.Split(js.Global().Get("document").Get("referrer").String(), "?")[0] + js.Global().Get("window").Get("location").Call("replace", redirectUri+"?ecdhPublicKey="+base64.URLEncoding.EncodeToString(privateKey.PublicKey().Bytes())+"&nonce="+base64.URLEncoding.EncodeToString(nonce)+"&cipherText="+base64.URLEncoding.EncodeToString(encryptedClientKey)) + } +} diff --git a/services-src/auth/resources/wasm/dashboard/main.go b/services-src/auth/resources/wasm/dashboard/main.go new file mode 100644 index 0000000..999ad5a --- /dev/null +++ b/services-src/auth/resources/wasm/dashboard/main.go @@ -0,0 +1,683 @@ +package main + +import ( + "bytes" + "encoding/json" + "fmt" + "net/http" + "net/url" + "strings" + "syscall/js" + "time" +) + +func fetchOauthClients(oauthList js.Value, localStorage js.Value, body []byte) { + // Fetch the OAuth clients + requestUri, err := url.JoinPath(js.Global().Get("window").Get("location").Get("origin").String(), "/api/oauth/list") + if err != nil { + var statusText = js.Global().Get("document").Call("createElement", "p") + statusText.Set("innerText", "Error joining URL: "+err.Error()) + oauthList.Call("appendChild", statusText) + return + } + + response, err := http.Post(requestUri, "application/json", bytes.NewReader(body)) + if err != nil { + var statusText = js.Global().Get("document").Call("createElement", "p") + statusText.Set("innerText", "Error contacting server: "+err.Error()) + oauthList.Call("appendChild", statusText) + return + } + + // Get all our ducks in a row + var responseMap map[string]interface{} + + // Read the response + decoder := json.NewDecoder(response.Body) + err = decoder.Decode(&responseMap) + if err != nil { + var statusText = js.Global().Get("document").Call("createElement", "p") + statusText.Set("innerText", "Error decoding server response: "+err.Error()) + oauthList.Call("appendChild", statusText) + return + } + + // Close the response body + err = response.Body.Close() + if err != nil { + fmt.Println("Could not close response body: " + err.Error() + ", memory leaks may occur") + } + + if response.StatusCode == 200 { + for i := 0; i < oauthList.Get("childNodes").Length(); i++ { + this := oauthList.Get("childNodes").Index(i) + if this.Get("tagName").String() != "H2" { + this.Call("remove") + } + } + + clients, ok := responseMap["apps"].([]interface{}) + if !ok { + var statusText = js.Global().Get("document").Call("createElement", "p") + statusText.Set("innerText", "Hi there! You don't have any OAuth2 clients yet. Create one above!") + oauthList.Call("appendChild", statusText) + } else { + for _, app := range clients { + var oauthElement = js.Global().Get("document").Call("createElement", "div") + var oauthText = js.Global().Get("document").Call("createElement", "p") + var oauthName = js.Global().Get("document").Call("createElement", "p") + var oauthUrl = js.Global().Get("document").Call("createElement", "p") + var oauthRemoveButton = js.Global().Get("document").Call("createElement", "button") + oauthText.Set("innerText", app.(map[string]interface{})["appId"].(string)) + oauthName.Set("innerText", app.(map[string]interface{})["name"].(string)) + oauthUrl.Set("innerText", app.(map[string]interface{})["redirectUri"].(string)) + oauthRemoveButton.Set("innerText", "Delete permanently") + oauthRemoveButton.Call("addEventListener", "click", js.FuncOf(func(this js.Value, args []js.Value) interface{} { + go func() { + if js.Global().Call("confirm", "Are you sure you want to delete this client? This action cannot be undone.").Bool() { + // Create the request body + requestBody := map[string]interface{}{ + "token": localStorage.Call("getItem", "DONOTSHARE-secretKey").String(), + "appId": app.(map[string]interface{})["appId"].(string), + } + + // Marshal the body + bodyBytes, err := json.Marshal(requestBody) + if err != nil { + js.Global().Call("alert", "Error marshaling body: "+err.Error()) + return + } + + // Send the request + requestUri, err := url.JoinPath(js.Global().Get("window").Get("location").Get("origin").String(), "/api/oauth/remove") + if err != nil { + js.Global().Call("alert", "Error joining URL: "+err.Error()) + return + } + + response, err := http.Post(requestUri, "application/json", bytes.NewReader(bodyBytes)) + if err != nil { + js.Global().Call("alert", "Error contacting server: "+err.Error()) + return + } + + // Get all our ducks in a row + var responseMap map[string]interface{} + + // Read the response + decoder := json.NewDecoder(response.Body) + err = decoder.Decode(&responseMap) + if err != nil { + js.Global().Call("alert", "Error decoding server response: "+err.Error()) + return + } + + // Close the response body + err = response.Body.Close() + if err != nil { + fmt.Println("Could not close response body: " + err.Error() + ", memory leaks may occur") + } + + if response.StatusCode == 200 { + oauthElement.Call("remove") + if oauthList.Get("childNodes").Length() == 1 { + var statusText = js.Global().Get("document").Call("createElement", "p") + statusText.Set("innerText", "Hi there! You don't have any OAuth2 clients yet. Create one above!") + oauthList.Call("appendChild", statusText) + } + } else if response.StatusCode != 500 { + js.Global().Call("alert", responseMap["error"].(string)) + } else { + js.Global().Call("alert", "Something went wrong! (error code: "+responseMap["code"].(string)+")") + } + } + }() + return nil + })) + + oauthElement.Call("append", oauthName) + oauthElement.Call("append", oauthText) + oauthElement.Call("append", oauthUrl) + + openId := false + clientKeyShare := false + scopes, ok := app.(map[string]interface{})["scopes"].([]interface{}) + if ok { + for _, scope := range scopes { + if scope.(string) == "openid" { + openId = true + } else if scope.(string) == "clientKeyShare" { + if app.(map[string]interface{})["keyShareUri"].(string) != "" { + clientKeyShare = true + keyShareUri := js.Global().Get("document").Call("createElement", "p") + keyShareUri.Set("innerText", "Key Share URI: "+app.(map[string]interface{})["keyShareUri"].(string)) + oauthElement.Call("append", keyShareUri) + } + } + } + + oauthScopes := js.Global().Get("document").Call("createElement", "p") + var scopeText strings.Builder + if openId { + scopeText.WriteString("OpenID") + } + + if clientKeyShare { + if openId { + scopeText.WriteString(", ") + } + scopeText.WriteString("clientKeyShare") + } + + oauthScopes.Set("innerText", "Scopes: "+scopeText.String()) + oauthElement.Call("append", oauthScopes) + } + + oauthElement.Call("append", oauthRemoveButton) + oauthElement.Get("classList").Call("add", "oauthEntry") + + oauthList.Call("appendChild", oauthElement) + } + } + } else if response.StatusCode != 500 { + statusText := js.Global().Get("document").Call("createElement", "p") + statusText.Set("innerText", responseMap["error"].(string)) + oauthList.Call("appendChild", statusText) + } else { + statusText := js.Global().Get("document").Call("createElement", "p") + statusText.Set("innerText", "Something went wrong! (error code: "+responseMap["code"].(string)+")") + oauthList.Call("appendChild", statusText) + } +} + +func main() { + // Redirect to log-in if not signed in + localStorage := js.Global().Get("localStorage") + if localStorage.Call("getItem", "DONOTSHARE-secretKey").IsNull() { + js.Global().Get("window").Get("location").Call("replace", "/login"+js.Global().Get("window").Get("location").Get("search").String()) + } + + var submitButton = js.Global().Get("document").Call("getElementById", "submitButton") + var nameBox = js.Global().Get("document").Call("getElementById", "nameBox") + var usernameBox = js.Global().Get("document").Call("getElementById", "usernameBox") + var dateBox = js.Global().Get("document").Call("getElementById", "dateBox") + var clientKeyShareBox = js.Global().Get("document").Call("getElementById", "clientKeyShareBox") + var redirectUriBox = js.Global().Get("document").Call("getElementById", "redirectUriBox") + var openIdBox = js.Global().Get("document").Call("getElementById", "openIdBox") + var statusBox = js.Global().Get("document").Call("getElementById", "statusBox") + var oauthList = js.Global().Get("document").Call("getElementById", "oauthList") + var sessionList = js.Global().Get("document").Call("getElementById", "sessionList") + var deleteAccountButton = js.Global().Get("document").Call("getElementById", "deleteAccountButton") + var logoutButton = js.Global().Get("document").Call("getElementById", "logoutButton") + var devAccountSwitcher = js.Global().Get("document").Call("getElementById", "devAccountSwitcher") + var developers = js.Global().Get("document").Call("getElementById", "developers") + var account = js.Global().Get("document").Call("getElementById", "account") + + // Fetch the OAuth clients and sessions + go func() { + // Check if the token is valid + requestUri, err := url.JoinPath(js.Global().Get("window").Get("location").Get("origin").String(), "/api/loggedIn") + if err != nil { + js.Global().Call("alert", "Error joining URL: "+err.Error()) + return + } + + loggedInBody := map[string]interface{}{ + "token": localStorage.Call("getItem", "DONOTSHARE-secretKey").String(), + } + + // Marshal the body + body, err := json.Marshal(loggedInBody) + if err != nil { + js.Global().Call("alert", "Error marshaling signup body: "+err.Error()) + return + } + + response, err := http.Post(requestUri, "application/json", bytes.NewReader(body)) + if err != nil { + js.Global().Call("alert", "Error contacting server: "+err.Error()) + return + } + + // Check if the response is 200 + if response.StatusCode == 401 { + // Close the response body + err = response.Body.Close() + if err != nil { + fmt.Println("Could not close response body: " + err.Error() + ", memory leaks may occur") + } + + // Redirect to log-out if not signed in + js.Global().Get("window").Get("location").Call("replace", "/logout") + return + } else if response.StatusCode == 500 { + // Read the response + var responseMap map[string]interface{} + decoder := json.NewDecoder(response.Body) + err = decoder.Decode(&responseMap) + if err != nil { + js.Global().Call("alert", "Error decoding server response: "+err.Error()) + return + } + + // Close the response body + err = response.Body.Close() + if err != nil { + fmt.Println("Could not close response body: " + err.Error() + ", memory leaks may occur") + } + + // Alert the user if the server is down + js.Global().Call("alert", "Something went wrong! (error code: "+responseMap["code"].(string)+")") + return + } + + // Close the response body + err = response.Body.Close() + if err != nil { + fmt.Println("Could not close response body: " + err.Error() + ", memory leaks may occur") + } + + // Fetch the OAuth clients + fetchOauthClients(oauthList, localStorage, body) + + // Fetch the sessions + requestUri, err = url.JoinPath(js.Global().Get("window").Get("location").Get("origin").String(), "/api/session/list") + if err != nil { + var statusText = js.Global().Get("document").Call("createElement", "p") + statusText.Set("innerText", "Error joining URL: "+err.Error()) + sessionList.Call("appendChild", statusText) + return + } + + response, err = http.Post(requestUri, "application/json", bytes.NewReader(body)) + if err != nil { + var statusText = js.Global().Get("document").Call("createElement", "p") + statusText.Set("innerText", "Error contacting server: "+err.Error()) + sessionList.Call("appendChild", statusText) + return + } + + // Get all our ducks in a row + var responseMap map[string]interface{} + + // Read the response + decoder := json.NewDecoder(response.Body) + err = decoder.Decode(&responseMap) + if err != nil { + var statusText = js.Global().Get("document").Call("createElement", "p") + statusText.Set("innerText", "Error decoding server response: "+err.Error()) + sessionList.Call("appendChild", statusText) + return + } + + // Close the response body + err = response.Body.Close() + if err != nil { + fmt.Println("Could not close response body: " + err.Error() + ", memory leaks may occur") + } + + if response.StatusCode == 200 { + if len(responseMap["sessions"].([]interface{})) == 0 { + var statusText = js.Global().Get("document").Call("createElement", "p") + statusText.Set("innerText", "Hi there! You don't have any sessions logged in, somehow. Congrats on breaking the laws of physics!") + sessionList.Call("appendChild", statusText) + } else { + for i := 0; i < sessionList.Get("childNodes").Length(); i++ { + this := sessionList.Get("childNodes").Index(i) + if this.Get("tagName").String() != "H2" { + this.Call("remove") + } + } + + for _, session := range responseMap["sessions"].([]interface{}) { + var sessionElement = js.Global().Get("document").Call("createElement", "div") + var sessionDevice = js.Global().Get("document").Call("createElement", "p") + var sessionImage = js.Global().Get("document").Call("createElement", "img") + var sessionRemoveButton = js.Global().Get("document").Call("createElement", "button") + if session.(map[string]interface{})["session"].(string) == localStorage.Call("getItem", "DONOTSHARE-secretKey").String() { + sessionDevice.Set("innerText", "(current) "+session.(map[string]interface{})["device"].(string)) + } else { + sessionDevice.Set("innerText", session.(map[string]interface{})["device"].(string)) + } + + if strings.Contains(strings.ToLower(session.(map[string]interface{})["device"].(string)), "nt") || strings.Contains(strings.ToLower(session.(map[string]interface{})["device"].(string)), "macintosh") { + sessionImage.Set("src", "/static/svg/device_computer.svg") + } else if strings.Contains(strings.ToLower(session.(map[string]interface{})["device"].(string)), "iphone") || strings.Contains(strings.ToLower(session.(map[string]interface{})["device"].(string)), "android") || strings.Contains(strings.ToLower(session.(map[string]interface{})["device"].(string)), "ipod") { + sessionImage.Set("src", "/static/svg/device_smartphone.svg") + } else if strings.Contains(strings.ToLower(session.(map[string]interface{})["device"].(string)), "curl") || strings.Contains(strings.ToLower(session.(map[string]interface{})["device"].(string)), "go-http-client") { + sessionImage.Set("src", "/static/svg/device_terminal.svg") + } else { + sessionImage.Set("src", "/static/svg/device_other.svg") + } + + sessionRemoveButton.Set("innerText", "Force log out") + sessionRemoveButton.Call("addEventListener", "click", js.FuncOf(func(this js.Value, args []js.Value) interface{} { + go func() { + // Create the request body + body := map[string]interface{}{ + "token": localStorage.Call("getItem", "DONOTSHARE-secretKey").String(), + "session": session.(map[string]interface{})["session"].(string), + } + + // Marshal the body + bodyBytes, err := json.Marshal(body) + if err != nil { + js.Global().Call("alert", "Error marshaling body: "+err.Error()) + return + } + + // Send the request + requestUri, err := url.JoinPath(js.Global().Get("window").Get("location").Get("origin").String(), "/api/session/remove") + if err != nil { + js.Global().Call("alert", "Error joining URL: "+err.Error()) + return + } + + response, err := http.Post(requestUri, "application/json", bytes.NewReader(bodyBytes)) + if err != nil { + js.Global().Call("alert", "Error contacting server: "+err.Error()) + return + } + + // Get all our ducks in a row + var responseMap map[string]interface{} + + // Read the response + decoder := json.NewDecoder(response.Body) + err = decoder.Decode(&responseMap) + if err != nil { + js.Global().Call("alert", "Error decoding server response: "+err.Error()) + return + } + + // Close the response body + err = response.Body.Close() + if err != nil { + fmt.Println("Could not close response body: " + err.Error() + ", memory leaks may occur") + } + + if response.StatusCode == 200 { + sessionElement.Call("remove") + if session.(map[string]interface{})["session"].(string) == localStorage.Call("getItem", "DONOTSHARE-secretKey").String() { + js.Global().Get("window").Get("location").Call("replace", "/logout") + } + } else if response.StatusCode != 500 { + js.Global().Call("alert", responseMap["error"].(string)) + } else { + js.Global().Call("alert", "Something went wrong! (error code: "+responseMap["code"].(string)+")") + } + }() + return nil + })) + + sessionElement.Call("append", sessionImage) + sessionElement.Call("append", sessionDevice) + sessionElement.Call("append", sessionRemoveButton) + sessionElement.Get("classList").Call("add", "sessionEntry") + + sessionList.Call("appendChild", sessionElement) + } + } + } else if response.StatusCode != 500 { + statusText := js.Global().Get("document").Call("createElement", "p") + statusText.Set("innerText", responseMap["error"].(string)) + sessionList.Call("appendChild", statusText) + } else { + statusText := js.Global().Get("document").Call("createElement", "p") + statusText.Set("innerText", "Something went wrong! (error code: "+responseMap["code"].(string)+")") + sessionList.Call("appendChild", statusText) + } + + // Fetch user information + requestUri, err = url.JoinPath(js.Global().Get("window").Get("location").Get("origin").String(), "/api/userinfo") + if err != nil { + js.Global().Call("alert", "Error joining URL: "+err.Error()) + return + } + + // Re-use the body variable for this request + response, err = http.Post(requestUri, "application/json", bytes.NewReader(body)) + if err != nil { + js.Global().Call("alert", "Error contacting server: "+err.Error()) + return + } + + // Read the response + decoder = json.NewDecoder(response.Body) + err = decoder.Decode(&responseMap) + if err != nil { + js.Global().Call("alert", "Error decoding server response: "+err.Error()) + return + } + + // Close the response body + err = response.Body.Close() + if err != nil { + js.Global().Call("alert", "Could not close response body: "+err.Error()+", memory leaks may occur") + } + + if response.StatusCode == 200 { + usernameBox.Set("innerText", "Username: "+responseMap["username"].(string)) + dateBox.Set("innerText", "Account created: "+time.Unix(int64(responseMap["created"].(float64)), 0).Format("2006-01-02 15:04:05")) + } else if response.StatusCode != 500 { + js.Global().Call("alert", responseMap["error"].(string)) + } else { + js.Global().Call("alert", "Something went wrong! (error code: "+responseMap["code"].(string)+")") + } + }() + + submitButton.Call("addEventListener", "click", js.FuncOf(func(this js.Value, args []js.Value) interface{} { + go func() { + // Validate the input + if nameBox.Get("value").String() == "" { + statusBox.Set("innerText", "An App Name is required!") + return + } else if redirectUriBox.Get("value").String() == "" { + statusBox.Set("innerText", "A Redirect URI is required!") + return + } + + // Check for scopes + var scopes []string + if openIdBox.Get("checked").Bool() { + scopes = append(scopes, "openid") + } + if clientKeyShareBox.Get("value").String() != "" { + scopes = append(scopes, "clientKeyShare") + } + + // Create the request body + body := map[string]interface{}{ + "name": nameBox.Get("value").String(), + "redirectUri": redirectUriBox.Get("value").String(), + "token": localStorage.Call("getItem", "DONOTSHARE-secretKey").String(), + "scopes": scopes, + "keyShareUri": redirectUriBox.Get("value").String(), + } + + // Marshal the body + bodyBytes, err := json.Marshal(body) + if err != nil { + statusBox.Set("innerText", "Error marshaling body: "+err.Error()) + return + } + + // Send the request + requestUri, err := url.JoinPath(js.Global().Get("window").Get("location").Get("origin").String(), "/api/oauth/add") + if err != nil { + statusBox.Set("innerText", "Error joining URL: "+err.Error()) + return + } + + response, err := http.Post(requestUri, "application/json", bytes.NewReader(bodyBytes)) + if err != nil { + statusBox.Set("innerText", "Error contacting server: "+err.Error()) + return + } + + // Get all our ducks in a row + var responseMap map[string]interface{} + + // Read the response + decoder := json.NewDecoder(response.Body) + err = decoder.Decode(&responseMap) + if err != nil { + statusBox.Set("innerText", "Error decoding server response: "+err.Error()) + return + } + + // Close the response body + err = response.Body.Close() + if err != nil { + fmt.Println("Could not close response body: " + err.Error() + ", memory leaks may occur") + } + + if response.StatusCode == 200 { + statusBox.Set("innerText", "Your secret key is: "+responseMap["key"].(string)+" and your client ID is: "+responseMap["appId"].(string)+". This will only ever be shown once!") + + // Update the OAuth clients + bodyMap := map[string]interface{}{ + "token": localStorage.Call("getItem", "DONOTSHARE-secretKey").String(), + } + + // Marshal the body + body, err := json.Marshal(bodyMap) + if err != nil { + fmt.Println("Error marshaling body: " + err.Error() + ", this is non-fatal.") + return + } + + // Perform the request + fetchOauthClients(oauthList, localStorage, body) + } else if response.StatusCode != 500 { + statusBox.Set("innerText", responseMap["error"].(string)) + } else { + statusBox.Set("innerText", "Something went wrong! (error code: "+responseMap["code"].(string)+")") + } + }() + return nil + })) + + deleteAccountButton.Call("addEventListener", "click", js.FuncOf(func(this js.Value, args []js.Value) interface{} { + go func() { + if js.Global().Call("confirm", "Are you sure you would like to delete your account forever? This cannot be undone.").Bool() { + // Create the request body + body := map[string]interface{}{ + "token": localStorage.Call("getItem", "DONOTSHARE-secretKey").String(), + } + + // Marshal the body + bodyBytes, err := json.Marshal(body) + if err != nil { + statusBox.Set("innerText", "Error marshaling body: "+err.Error()) + return + } + + // Send the request + requestUri, err := url.JoinPath(js.Global().Get("window").Get("location").Get("origin").String(), "/api/deleteAccount") + if err != nil { + statusBox.Set("innerText", "Error joining URL: "+err.Error()) + return + } + + response, err := http.Post(requestUri, "application/json", bytes.NewReader(bodyBytes)) + if err != nil { + statusBox.Set("innerText", "Error contacting server: "+err.Error()) + return + } + + // Get all our ducks in a row + var responseMap map[string]interface{} + + // Read the response + decoder := json.NewDecoder(response.Body) + err = decoder.Decode(&responseMap) + if err != nil { + statusBox.Set("innerText", "Error decoding server response: "+err.Error()) + return + } + + // Close the response body + err = response.Body.Close() + if err != nil { + fmt.Println("Could not close response body: " + err.Error() + ", memory leaks may occur") + } + + if response.StatusCode == 200 { + js.Global().Get("window").Get("location").Call("replace", "/logout") + } else if response.StatusCode != 500 { + js.Global().Call("alert", responseMap["error"].(string)) + } else { + js.Global().Call("alert", "Something went wrong! (error code: "+responseMap["code"].(string)+")") + } + } + }() + return nil + })) + + devAccountSwitcher.Call("addEventListener", "click", js.FuncOf(func(this js.Value, args []js.Value) interface{} { + developers.Get("classList").Call("toggle", "hidden") + account.Get("classList").Call("toggle", "hidden") + if devAccountSwitcher.Get("innerText").String() == "Switch to developer view" { + devAccountSwitcher.Set("innerText", "Switch to account view") + } else { + devAccountSwitcher.Set("innerText", "Switch to developer view") + } + return nil + })) + + logoutButton.Call("addEventListener", "click", js.FuncOf(func(this js.Value, args []js.Value) interface{} { + go func() { + // Try to remove the session + requestUri, err := url.JoinPath(js.Global().Get("window").Get("location").Get("origin").String(), "/api/session/remove") + if err != nil { + js.Global().Call("alert", "Error joining URL: "+err.Error()) + return + } + + // Create the request body + body := map[string]interface{}{ + "token": localStorage.Call("getItem", "DONOTSHARE-secretKey").String(), + "session": localStorage.Call("getItem", "DONOTSHARE-secretKey").String(), + } + + // Marshal the body + bodyBytes, err := json.Marshal(body) + if err != nil { + js.Global().Call("alert", "Error marshaling body: "+err.Error()) + return + } + + // Send the request + response, err := http.Post(requestUri, "application/json", bytes.NewReader(bodyBytes)) + if err != nil { + js.Global().Call("alert", "Error contacting server: "+err.Error()) + return + } + + // Get all our ducks in a row + var responseMap map[string]interface{} + + // Read the response + decoder := json.NewDecoder(response.Body) + err = decoder.Decode(&responseMap) + if err != nil { + js.Global().Call("alert", "Error decoding server response: "+err.Error()) + return + } + + // Close the response body + err = response.Body.Close() + if err != nil { + fmt.Println("Could not close response body: " + err.Error() + ", memory leaks may occur") + } + + // We don't care about the response, we're logging out anyway + js.Global().Get("window").Get("location").Call("replace", "/logout") + }() + return nil + })) + + // Wait for events + select {} +} diff --git a/services-src/auth/resources/wasm/login/main.go b/services-src/auth/resources/wasm/login/main.go new file mode 100644 index 0000000..27c4dab --- /dev/null +++ b/services-src/auth/resources/wasm/login/main.go @@ -0,0 +1,258 @@ +package main + +import ( + "bytes" + "encoding/base64" + "encoding/json" + "fmt" + "net/http" + "net/url" + "syscall/js" + "time" + + "golang.org/x/crypto/argon2" +) + +var currentInputType = 0 + +func hashPassword(password string, salt []byte) string { + return base64.StdEncoding.EncodeToString( + argon2.IDKey( + []byte(password), + salt, + 32, + 19264, + 1, + 32, + ), + ) +} + +func showInput(inputType int, inputContainer js.Value, usernameBox js.Value, signupButton js.Value, passwordBox js.Value, backButton js.Value, inputNameBox js.Value, statusBox js.Value, nextButton js.Value) { + if inputType == 0 { + // Show login + inputContainer.Get("classList").Call("remove", "hidden") + usernameBox.Get("classList").Call("remove", "hidden") + signupButton.Get("classList").Call("remove", "hidden") + passwordBox.Get("classList").Call("add", "hidden") + backButton.Get("classList").Call("add", "hidden") + inputNameBox.Set("innerText", "Username:") + // Get the current service name + serviceName := js.Global().Get("document").Call("getElementById", "passThrough").Get("innerText").String() + + // Set the service name + statusBox.Set("innerText", "Login to your "+serviceName+" account!") + + // Set the current input type + currentInputType = 0 + } else if inputType == 1 { + inputContainer.Get("classList").Call("remove", "hidden") + signupButton.Get("classList").Call("add", "hidden") + usernameBox.Get("classList").Call("add", "hidden") + passwordBox.Get("classList").Call("remove", "hidden") + backButton.Get("classList").Call("remove", "hidden") + inputNameBox.Get("classList").Call("remove", "hidden") + nextButton.Get("classList").Call("remove", "hidden") + inputNameBox.Get("classList").Call("remove", "hidden") + inputNameBox.Set("innerText", "Password:") + currentInputType = 1 + } else if inputType == 2 { + signupButton.Get("classList").Call("add", "hidden") + nextButton.Get("classList").Call("add", "hidden") + backButton.Get("classList").Call("add", "hidden") + inputContainer.Get("classList").Call("add", "hidden") + inputNameBox.Get("classList").Call("add", "hidden") + passwordBox.Get("classList").Call("add", "hidden") + usernameBox.Get("classList").Call("add", "hidden") + currentInputType = 2 + } +} + +func main() { + // Redirect to app if already signed in + localStorage := js.Global().Get("localStorage") + if !localStorage.Call("getItem", "DONOTSHARE-secretKey").IsNull() { + js.Global().Get("window").Get("location").Call("replace", "/authorize"+js.Global().Get("window").Get("location").Get("search").String()) + } + + var usernameBox = js.Global().Get("document").Call("getElementById", "usernameBox") + var passwordBox = js.Global().Get("document").Call("getElementById", "passwordBox") + var statusBox = js.Global().Get("document").Call("getElementById", "statusBox") + var nextButton = js.Global().Get("document").Call("getElementById", "nextButton") + var backButton = js.Global().Get("document").Call("getElementById", "backButton") + var signupButton = js.Global().Get("document").Call("getElementById", "signupButton") + var inputNameBox = js.Global().Get("document").Call("getElementById", "inputNameBox") + var inputContainer = js.Global().Get("document").Call("getElementById", "inputContainer") + + // Show the login screen + showInput(0, inputContainer, usernameBox, signupButton, passwordBox, backButton, inputNameBox, statusBox, nextButton) + + nextButton.Call("addEventListener", "click", js.FuncOf(func(this js.Value, args []js.Value) interface{} { + go func() { + if currentInputType == 0 { + if usernameBox.Get("value").IsNull() { + statusBox.Set("innerText", "A username is required!") + return + } else { + statusBox.Set("innerText", "Welcome back, "+usernameBox.Get("value").String()+"!") + showInput(1, inputContainer, usernameBox, signupButton, passwordBox, backButton, inputNameBox, statusBox, nextButton) + } + } else if currentInputType == 1 { + password := passwordBox.Get("value").String() + username := usernameBox.Get("value").String() + + if passwordBox.Get("value").IsNull() { + statusBox.Set("innerText", "A password is required!") + return + } + + showInput(2, inputContainer, usernameBox, signupButton, passwordBox, backButton, inputNameBox, statusBox, nextButton) + + // Hash the password + statusBox.Set("innerText", "Hashing password...") + fmt.Println("Hashing password...") + + // Fetch the salt from the server + body, err := json.Marshal(map[string]interface{}{ + "username": username, + }) + + if err != nil { + showInput(1, inputContainer, usernameBox, signupButton, passwordBox, backButton, inputNameBox, statusBox, nextButton) + statusBox.Set("innerText", "Error marshaling salt body: "+err.Error()) + return + } + + requestUri, err := url.JoinPath(js.Global().Get("window").Get("location").Get("origin").String(), "/api/loginChallenge") + if err != nil { + showInput(1, inputContainer, usernameBox, signupButton, passwordBox, backButton, inputNameBox, statusBox, nextButton) + statusBox.Set("innerText", "Error joining URL: "+err.Error()) + return + } + + response, err := http.Post(requestUri, "application/json", bytes.NewReader(body)) + if err != nil { + showInput(1, inputContainer, usernameBox, signupButton, passwordBox, backButton, inputNameBox, statusBox, nextButton) + statusBox.Set("innerText", "Error contacting server: "+err.Error()) + return + } + + // Get all our ducks in a row + var responseMap map[string]interface{} + + // Read the response + decoder := json.NewDecoder(response.Body) + err = decoder.Decode(&responseMap) + if err != nil { + showInput(1, inputContainer, usernameBox, signupButton, passwordBox, backButton, inputNameBox, statusBox, nextButton) + statusBox.Set("innerText", "Error decoding server response: "+err.Error()) + return + } + + // Close the response body + err = response.Body.Close() + if err != nil { + fmt.Println("Could not close response body: " + err.Error() + ", memory leaks may occur") + } + + // Decode the salt + salt, err := base64.StdEncoding.DecodeString(responseMap["salt"].(string)) + if err != nil { + showInput(1, inputContainer, usernameBox, signupButton, passwordBox, backButton, inputNameBox, statusBox, nextButton) + statusBox.Set("innerText", "Error decoding salt: "+err.Error()) + return + } + + hashedPassword := hashPassword(password, salt) + + // Hashed password computed, contact server + statusBox.Set("innerText", "Contacting server...") + signupBody := map[string]interface{}{ + "username": username, + "password": hashedPassword, + } + + // Marshal the body + body, err = json.Marshal(signupBody) + if err != nil { + showInput(1, inputContainer, usernameBox, signupButton, passwordBox, backButton, inputNameBox, statusBox, nextButton) + statusBox.Set("innerText", "Error marshaling signup body: "+err.Error()) + return + } + + // Send the password to the server + requestUri, err = url.JoinPath(js.Global().Get("window").Get("location").Get("origin").String(), "/api/login") + if err != nil { + showInput(1, inputContainer, usernameBox, signupButton, passwordBox, backButton, inputNameBox, statusBox, nextButton) + statusBox.Set("innerText", "Error joining URL: "+err.Error()) + return + } + + // Send the request + fmt.Println("Sending request to", requestUri) + response, err = http.Post(requestUri, "application/json", bytes.NewReader(body)) + if err != nil { + showInput(1, inputContainer, usernameBox, signupButton, passwordBox, backButton, inputNameBox, statusBox, nextButton) + statusBox.Set("innerText", "Error contacting server: "+err.Error()) + return + } + + // Read the response + fmt.Println("Reading response...") + decoder = json.NewDecoder(response.Body) + err = decoder.Decode(&responseMap) + if err != nil { + showInput(1, inputContainer, usernameBox, signupButton, passwordBox, backButton, inputNameBox, statusBox, nextButton) + statusBox.Set("innerText", "Error decoding server response: "+err.Error()) + return + } + + // Close the response body + err = response.Body.Close() + if err != nil { + fmt.Println("Could not close response body: " + err.Error() + ", memory leaks may occur") + } + + if response.StatusCode == 200 { + // Logged in + fmt.Println("Logged in!") + statusBox.Set("innerText", "Setting up encryption keys...") + localStorage.Call("setItem", "DONOTSHARE-secretKey", responseMap["key"].(string)) + localStorage.Call("setItem", "DONOTSHARE-clientKey", hashPassword(password, []byte("fg-auth-client"))) + + // Redirect to app + statusBox.Set("innerText", "Welcome!") + time.Sleep(time.Second) + js.Global().Get("window").Get("location").Call("replace", "/authorize"+js.Global().Get("window").Get("location").Get("search").String()) + } else if response.StatusCode == 401 { + // Login failed + showInput(1, inputContainer, usernameBox, signupButton, passwordBox, backButton, inputNameBox, statusBox, nextButton) + statusBox.Set("innerText", "Username or password incorrect!") + } else { + // Unknown error + showInput(1, inputContainer, usernameBox, signupButton, passwordBox, backButton, inputNameBox, statusBox, nextButton) + statusBox.Set("innerText", "Something went wrong! (error code: "+responseMap["code"].(string)+")") + } + } + }() + + return nil + })) + + backButton.Call("addEventListener", "click", js.FuncOf(func(this js.Value, args []js.Value) interface{} { + go func() { + showInput(0, inputContainer, usernameBox, signupButton, passwordBox, backButton, inputNameBox, statusBox, nextButton) + return + }() + + return nil + })) + + signupButton.Call("addEventListener", "click", js.FuncOf(func(this js.Value, args []js.Value) interface{} { + js.Global().Get("window").Get("location").Call("replace", "/signup"+js.Global().Get("window").Get("location").Get("search").String()) + return nil + })) + + // Wait for events + select {} +} diff --git a/services-src/auth/resources/wasm/signup/main.go b/services-src/auth/resources/wasm/signup/main.go new file mode 100644 index 0000000..04cf7ec --- /dev/null +++ b/services-src/auth/resources/wasm/signup/main.go @@ -0,0 +1,195 @@ +package main + +import ( + "bytes" + "crypto/rand" + "encoding/base64" + "fmt" + "time" + + "encoding/json" + "net/http" + "net/url" + + "git.ailur.dev/ailur/pow-argon2/library" + "golang.org/x/crypto/argon2" + + "syscall/js" +) + +func showElements(show bool, elements ...js.Value) { + for _, element := range elements { + if show { + element.Get("classList").Call("remove", "hidden") + } else { + element.Get("classList").Call("add", "hidden") + } + } +} + +func hashPassword(password string, salt []byte) string { + return base64.StdEncoding.EncodeToString( + argon2.IDKey( + []byte(password), + salt, + 32, + 19264, + 1, + 32, + ), + ) +} + +func main() { + // Redirect to app if already signed in + localStorage := js.Global().Get("localStorage") + if !localStorage.Call("getItem", "DONOTSHARE-secretKey").IsNull() { + js.Global().Get("window").Get("location").Call("replace", "/authorize"+js.Global().Get("window").Get("location").Get("search").String()) + } + + var usernameBox = js.Global().Get("document").Call("getElementById", "usernameBox") + var passwordBox = js.Global().Get("document").Call("getElementById", "passwordBox") + var statusBox = js.Global().Get("document").Call("getElementById", "statusBox") + var signupButton = js.Global().Get("document").Call("getElementById", "signupButton") + var loginButton = js.Global().Get("document").Call("getElementById", "loginButton") + var inputContainer = js.Global().Get("document").Call("getElementById", "inputContainer") + + signupButton.Call("addEventListener", "click", js.FuncOf(func(this js.Value, args []js.Value) interface{} { + go func() { + var username = usernameBox.Get("value").String() + var password = passwordBox.Get("value").String() + + if username == "" { + statusBox.Set("innerText", "A username is required!") + return + } else if len(username) > 20 { + statusBox.Set("innerText", "Username cannot be more than 20 characters!") + return + } else if password == "" { + statusBox.Set("innerText", "A password is required!") + return + } else if len(password) < 8 { + statusBox.Set("innerText", "Password must be at least 8 characters!") + return + } + + // Start the signup process + fmt.Println("Starting signup process for user: " + username) + showElements(false, inputContainer, signupButton, loginButton) + // Wait about 10ms to allow the UI to update + var pow string + if localStorage.Call("getItem", "DEBUG-customPoW").IsNull() { + var err error + statusBox.Set("innerText", "Computing PoW Challenge...\nThe UI may be unresponsive during this time, as we are performing a lot of work! Please wait a few minutes for the process to complete.") + time.Sleep(time.Millisecond * 10) + pow, err = library.PoW(3, "fg-auth-signup") + if err != nil { + showElements(true, inputContainer, signupButton, loginButton) + statusBox.Set("innerText", "Error computing PoW challenge: "+err.Error()) + return + } + } else { + pow = localStorage.Call("getItem", "DEBUG-customPoW").String() + } + + // PoW challenge computed, hash password + statusBox.Set("innerText", "Hashing password...") + + // Generate a random salt + salt := make([]byte, 32) + _, err := rand.Read(salt) + if err != nil { + showElements(true, inputContainer, signupButton, loginButton) + statusBox.Set("innerText", "Error generating salt: "+err.Error()) + return + } + + // Hash the password + hashedPassword := hashPassword(password, salt) + + // Hashed password computed, contact server + statusBox.Set("innerText", "Contacting server...") + signupBody := map[string]interface{}{ + "username": username, + "password": hashedPassword, + "salt": base64.StdEncoding.EncodeToString(salt), + "proofOfWork": pow, + } + + // Marshal the body + body, err := json.Marshal(signupBody) + if err != nil { + showElements(true, inputContainer, signupButton, loginButton) + statusBox.Set("innerText", "Error marshaling signup body: "+err.Error()) + return + } + + // Send the request + requestUri, err := url.JoinPath(js.Global().Get("window").Get("location").Get("origin").String(), "/api/signup") + if err != nil { + showElements(true, inputContainer, signupButton, loginButton) + statusBox.Set("innerText", "Error joining URL: "+err.Error()) + return + } + + response, err := http.Post(requestUri, "application/json", bytes.NewReader(body)) + if err != nil { + showElements(true, inputContainer, signupButton, loginButton) + statusBox.Set("innerText", "Error contacting server: "+err.Error()) + return + } + + // Get all our ducks in a row + var responseMap map[string]interface{} + + // Read the response + decoder := json.NewDecoder(response.Body) + err = decoder.Decode(&responseMap) + if err != nil { + showElements(true, inputContainer, signupButton, loginButton) + statusBox.Set("innerText", "Error decoding server response: "+err.Error()) + return + } + + // Close the response body + err = response.Body.Close() + if err != nil { + fmt.Println("Could not close response body: " + err.Error() + ", memory leaks may occur") + } + + if response.StatusCode == 200 { + // Signup successful + statusBox.Set("innerText", "Setting up encryption keys...") + localStorage.Call("setItem", "DONOTSHARE-secretKey", responseMap["key"].(string)) + localStorage.Call("setItem", "DONOTSHARE-clientKey", hashPassword(password, []byte("fg-auth-client"))) + + // Redirect to app + statusBox.Set("innerText", "Welcome!") + time.Sleep(time.Second) + js.Global().Get("window").Get("location").Call("replace", "/authorize"+js.Global().Get("window").Get("location").Get("search").String()) + } else if response.StatusCode == 409 { + // Username taken + showElements(true, inputContainer, signupButton, loginButton) + statusBox.Set("innerText", "Username or password taken!") + } else if response.StatusCode != 500 { + // Other error + showElements(true, inputContainer, signupButton, loginButton) + statusBox.Set("innerText", responseMap["error"].(string)) + } else { + // Other error + showElements(true, inputContainer, signupButton, loginButton) + statusBox.Set("innerText", "Something went wrong! (error code: "+responseMap["code"].(string)+")") + } + }() + + return nil + })) + + loginButton.Call("addEventListener", "click", js.FuncOf(func(this js.Value, args []js.Value) interface{} { + js.Global().Get("window").Get("location").Call("replace", "/login"+js.Global().Get("window").Get("location").Get("search").String()) + return nil + })) + + // Wait for events + select {} +} diff --git a/services-src/auth/resources/wasm/testApp/main.go b/services-src/auth/resources/wasm/testApp/main.go new file mode 100644 index 0000000..628b859 --- /dev/null +++ b/services-src/auth/resources/wasm/testApp/main.go @@ -0,0 +1,327 @@ +package main + +import ( + "bytes" + "crypto/aes" + "crypto/cipher" + "crypto/ecdh" + "crypto/rand" + "crypto/sha256" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "github.com/cespare/xxhash/v2" + "net/http" + "net/url" + "strconv" + "strings" + "syscall/js" +) + +func sha256Base64(s string) string { + hashed := sha256.Sum256([]byte(s)) + encoded := base64.URLEncoding.EncodeToString(hashed[:]) + encoded = strings.TrimRight(encoded, "=") + return encoded +} + +func randomChars(length int) (string, error) { + var saltChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" + if length <= 0 { + return "", errors.New("salt length must be greater than 0") + } + + salt := make([]byte, length) + randomBytes := make([]byte, length) + _, err := rand.Read(randomBytes) + if err != nil { + return "", err + } + + for i := range salt { + salt[i] = saltChars[int(randomBytes[i])%len(saltChars)] + } + return string(salt), nil +} + +func main() { + // Redirect to log-in if not signed in + localStorage := js.Global().Get("localStorage") + if localStorage.Call("getItem", "DONOTSHARE-secretKey").IsNull() { + js.Global().Get("window").Get("location").Call("replace", "/login"+js.Global().Get("window").Get("location").Get("search").String()) + } + + statusBox := js.Global().Get("document").Call("getElementById", "statusBox") + authorizeButton := js.Global().Get("document").Call("getElementById", "authorizeButton") + + // Check if the token is valid + requestUri, err := url.JoinPath(js.Global().Get("window").Get("location").Get("origin").String(), "/api/loggedIn") + if err != nil { + statusBox.Set("innerText", "Error joining URL: "+err.Error()) + return + } + + loggedInBody := map[string]interface{}{ + "token": localStorage.Call("getItem", "DONOTSHARE-secretKey").String(), + } + + // Marshal the body + body, err := json.Marshal(loggedInBody) + if err != nil { + statusBox.Set("innerText", "Error marshaling signup body: "+err.Error()) + return + } + + response, err := http.Post(requestUri, "application/json", bytes.NewReader(body)) + if err != nil { + statusBox.Set("innerText", "Error contacting server: "+err.Error()) + return + } + + // Check if the response is 200 + if response.StatusCode == 401 { + // Close the response body + err = response.Body.Close() + if err != nil { + fmt.Println("Could not close response body: " + err.Error() + ", memory leaks may occur") + } + + // Redirect to log-out if not signed in + js.Global().Get("window").Get("location").Call("replace", "/logout"+js.Global().Get("window").Get("location").Get("search").String()) + return + } else if response.StatusCode == 500 { + // Read the response + var responseMap map[string]interface{} + decoder := json.NewDecoder(response.Body) + err = decoder.Decode(&responseMap) + if err != nil { + js.Global().Call("alert", "Error decoding server response: "+err.Error()) + return + } + + // Close the response body + err = response.Body.Close() + if err != nil { + fmt.Println("Could not close response body: " + err.Error() + ", memory leaks may occur") + } + + // Alert the user if the server is down + js.Global().Call("alert", "Something went wrong! (error code: "+responseMap["code"].(string)+")") + return + } + + // Close the response body + err = response.Body.Close() + if err != nil { + fmt.Println("Could not close response body: " + err.Error() + ", memory leaks may occur") + } + + // Check if the URL has a code + urlParams, err := url.ParseQuery(strings.TrimPrefix(js.Global().Get("window").Get("location").Get("search").String(), "?")) + if err != nil { + statusBox.Set("innerText", "Error parsing URL: "+err.Error()) + return + } + + if urlParams.Has("code") { + // Set the status box + statusBox.Set("innerText", "Authenticating...") + + // Create the form data + var formData = url.Values{} + formData.Set("grant_type", "authorization_code") + formData.Set("code", urlParams.Get("code")) + formData.Set("client_id", "TestApp-DoNotUse") + formData.Set("redirect_uri", js.Global().Get("window").Get("location").Get("origin").String()+"/testApp") + formData.Set("code_verifier", localStorage.Call("getItem", "TESTER-verifier").String()) + + // Create the request + requestUri, err := url.JoinPath(js.Global().Get("window").Get("location").Get("origin").String(), "/api/oauth/token") + if err != nil { + statusBox.Set("innerText", "Error joining URL: "+err.Error()) + return + } + + response, err := http.Post(requestUri, "application/x-www-form-urlencoded", strings.NewReader(formData.Encode())) + if err != nil { + statusBox.Set("innerText", "Error contacting server: "+err.Error()) + return + } + + // Read the response + var responseMap map[string]interface{} + decoder := json.NewDecoder(response.Body) + err = decoder.Decode(&responseMap) + if err != nil { + statusBox.Set("innerText", "Error decoding server response: "+err.Error()) + return + } + + // Close the response body + err = response.Body.Close() + if err != nil { + fmt.Println("Could not close response body: " + err.Error() + ", memory leaks may occur") + } + + if response.StatusCode == 200 { + // Fetch userinfo + requestUri, err := url.JoinPath(js.Global().Get("window").Get("location").Get("origin").String(), "/api/oauth/userinfo") + if err != nil { + statusBox.Set("innerText", "Error joining URL: "+err.Error()) + return + } + + // Create the request + request, err := http.NewRequest("GET", requestUri, nil) + if err != nil { + statusBox.Set("innerText", "Error creating request: "+err.Error()) + return + } + + // Set the authorization header + request.Header.Set("Authorization", "Bearer "+responseMap["id_token"].(string)) + + // Send the request + response, err := http.DefaultClient.Do(request) + if err != nil { + statusBox.Set("innerText", "Error contacting server: "+err.Error()) + return + } + + // Read the response + decoder = json.NewDecoder(response.Body) + err = decoder.Decode(&responseMap) + if err != nil { + statusBox.Set("innerText", "Error decoding server response: "+err.Error()) + return + } + + // Close the response body + err = response.Body.Close() + if err != nil { + fmt.Println("Could not close response body: " + err.Error() + ", memory leaks may occur") + } + + // Set the username + localStorage.Call("setItem", "TESTER-username", responseMap["username"].(string)) + + // Generate the keypair + privateKey, err := ecdh.X25519().GenerateKey(rand.Reader) + if err != nil { + statusBox.Set("innerText", "Error generating private key: "+err.Error()) + return + } + + // Save the private key + localStorage.Call("setItem", "TESTER-privateKey", base64.StdEncoding.EncodeToString(privateKey.Bytes())) + + // Redirect to the client key exchange endpoint + js.Global().Get("window").Get("location").Call("replace", "/clientKeyShare?ecdhPublicKey="+base64.URLEncoding.EncodeToString(privateKey.PublicKey().Bytes())+"&accessToken="+responseMap["access_token"].(string)) + return + } else if response.StatusCode != 500 { + statusBox.Set("innerText", responseMap["error"].(string)) + } else { + statusBox.Set("innerText", "Something went wrong! (error code: "+responseMap["code"].(string)+")") + } + } else if urlParams.Has("error") { + if urlParams.Get("error") == "access_denied" { + statusBox.Set("innerText", "Access denied") + } else { + statusBox.Set("innerText", "Authentication failed (error code: "+urlParams.Get("error")+")") + } + } else if urlParams.Has("ecdhPublicKey") { + publicKeyByte, err := base64.URLEncoding.DecodeString(urlParams.Get("ecdhPublicKey")) + if err != nil { + statusBox.Set("innerText", "Error decoding public key: "+err.Error()) + return + } + + publicKey, err := ecdh.X25519().NewPublicKey(publicKeyByte) + if err != nil { + statusBox.Set("innerText", "Error encoding public key: "+err.Error()) + return + } + + privateKeyBytes, err := base64.StdEncoding.DecodeString(localStorage.Call("getItem", "TESTER-privateKey").String()) + if err != nil { + statusBox.Set("innerText", "Error decoding private key: "+err.Error()) + return + } + + privateKey, err := ecdh.X25519().NewPrivateKey(privateKeyBytes) + if err != nil { + statusBox.Set("innerText", "Error encoding private key: "+err.Error()) + return + } + + nonce, err := base64.URLEncoding.DecodeString(urlParams.Get("nonce")) + if err != nil { + statusBox.Set("innerText", "Error decoding nonce: "+err.Error()) + return + } + + ciphertext, err := base64.URLEncoding.DecodeString(urlParams.Get("cipherText")) + if err != nil { + statusBox.Set("innerText", "Error decoding ciphertext: "+err.Error()) + return + } + + // Generate the shared secret + sharedSecret, err := privateKey.ECDH(publicKey) + if err != nil { + statusBox.Set("innerText", "Error generating shared secret: "+err.Error()) + return + } + + // Decrypt the ciphertext + block, err := aes.NewCipher(sharedSecret) + if err != nil { + statusBox.Set("innerText", "Error creating AES cipher: "+err.Error()) + return + } + + gcm, err := cipher.NewGCM(block) + if err != nil { + statusBox.Set("innerText", "Error creating GCM cipher: "+err.Error()) + return + } + + plaintext, err := gcm.Open(nil, nonce, ciphertext, nil) + if err != nil { + statusBox.Set("innerText", "Error decrypting ciphertext: "+err.Error()) + return + } + + statusBox.Set("innerText", "Authentication complete! Authenticated as "+localStorage.Call("getItem", "TESTER-username").String()+" with client key "+strconv.FormatUint(xxhash.Sum64(plaintext), 10)) + + // Remove all our temporary data + localStorage.Call("removeItem", "TESTER-verifier") + localStorage.Call("removeItem", "TESTER-username") + localStorage.Call("removeItem", "TESTER-privateKey") + } + + // Add event listener for authorize button + authorizeButton.Call("addEventListener", "click", js.FuncOf(func(this js.Value, p []js.Value) interface{} { + go func() { + verifier, err := randomChars(128) + if err != nil { + statusBox.Set("innerText", "Error generating verifier: "+err.Error()) + return + } + + // Generate the challenge + verifierChallenge := sha256Base64(verifier) + + // Save the verifier + localStorage.Call("setItem", "TESTER-verifier", verifier) + + // Redirect to the authorization page + js.Global().Get("window").Get("location").Call("replace", "/authorize?response_type=code&client_id=TestApp-DoNotUse&redirect_uri="+url.QueryEscape(js.Global().Get("window").Get("location").Get("origin").String()+"/testApp")+"&code_challenge="+verifierChallenge+"&code_challenge_method=S256") + }() + return nil + })) + + // Wait for events + select {} +} diff --git a/services-src/storage/LICENSE.md b/services-src/storage/LICENSE.md new file mode 100644 index 0000000..969dabb --- /dev/null +++ b/services-src/storage/LICENSE.md @@ -0,0 +1,157 @@ +# GNU LESSER GENERAL PUBLIC LICENSE + +Version 3, 29 June 2007 + +Copyright (C) 2007 Free Software Foundation, Inc. + + +Everyone is permitted to copy and distribute verbatim copies of this +license document, but changing it is not allowed. + +This version of the GNU Lesser General Public License incorporates the +terms and conditions of version 3 of the GNU General Public License, +supplemented by the additional permissions listed below. + +## 0. Additional Definitions. + +As used herein, "this License" refers to version 3 of the GNU Lesser +General Public License, and the "GNU GPL" refers to version 3 of the +GNU General Public License. + +"The Library" refers to a covered work governed by this License, other +than an Application or a Combined Work as defined below. + +An "Application" is any work that makes use of an interface provided +by the Library, but which is not otherwise based on the Library. +Defining a subclass of a class defined by the Library is deemed a mode +of using an interface provided by the Library. + +A "Combined Work" is a work produced by combining or linking an +Application with the Library. The particular version of the Library +with which the Combined Work was made is also called the "Linked +Version". + +The "Minimal Corresponding Source" for a Combined Work means the +Corresponding Source for the Combined Work, excluding any source code +for portions of the Combined Work that, considered in isolation, are +based on the Application, and not on the Linked Version. + +The "Corresponding Application Code" for a Combined Work means the +object code and/or source code for the Application, including any data +and utility programs needed for reproducing the Combined Work from the +Application, but excluding the System Libraries of the Combined Work. + +## 1. Exception to Section 3 of the GNU GPL. + +You may convey a covered work under sections 3 and 4 of this License +without being bound by section 3 of the GNU GPL. + +## 2. Conveying Modified Versions. + +If you modify a copy of the Library, and, in your modifications, a +facility refers to a function or data to be supplied by an Application +that uses the facility (other than as an argument passed when the +facility is invoked), then you may convey a copy of the modified +version: + +- a) under this License, provided that you make a good faith effort + to ensure that, in the event an Application does not supply the + function or data, the facility still operates, and performs + whatever part of its purpose remains meaningful, or +- b) under the GNU GPL, with none of the additional permissions of + this License applicable to that copy. + +## 3. Object Code Incorporating Material from Library Header Files. + +The object code form of an Application may incorporate material from a +header file that is part of the Library. You may convey such object +code under terms of your choice, provided that, if the incorporated +material is not limited to numerical parameters, data structure +layouts and accessors, or small macros, inline functions and templates +(ten or fewer lines in length), you do both of the following: + +- a) Give prominent notice with each copy of the object code that + the Library is used in it and that the Library and its use are + covered by this License. +- b) Accompany the object code with a copy of the GNU GPL and this + license document. + +## 4. Combined Works. + +You may convey a Combined Work under terms of your choice that, taken +together, effectively do not restrict modification of the portions of +the Library contained in the Combined Work and reverse engineering for +debugging such modifications, if you also do each of the following: + +- a) Give prominent notice with each copy of the Combined Work that + the Library is used in it and that the Library and its use are + covered by this License. +- b) Accompany the Combined Work with a copy of the GNU GPL and this + license document. +- c) For a Combined Work that displays copyright notices during + execution, include the copyright notice for the Library among + these notices, as well as a reference directing the user to the + copies of the GNU GPL and this license document. +- d) Do one of the following: + - 0) Convey the Minimal Corresponding Source under the terms of + this License, and the Corresponding Application Code in a form + suitable for, and under terms that permit, the user to + recombine or relink the Application with a modified version of + the Linked Version to produce a modified Combined Work, in the + manner specified by section 6 of the GNU GPL for conveying + Corresponding Source. + - 1) Use a suitable shared library mechanism for linking with + the Library. A suitable mechanism is one that (a) uses at run + time a copy of the Library already present on the user's + computer system, and (b) will operate properly with a modified + version of the Library that is interface-compatible with the + Linked Version. +- e) Provide Installation Information, but only if you would + otherwise be required to provide such information under section 6 + of the GNU GPL, and only to the extent that such information is + necessary to install and execute a modified version of the + Combined Work produced by recombining or relinking the Application + with a modified version of the Linked Version. (If you use option + 4d0, the Installation Information must accompany the Minimal + Corresponding Source and Corresponding Application Code. If you + use option 4d1, you must provide the Installation Information in + the manner specified by section 6 of the GNU GPL for conveying + Corresponding Source.) + +## 5. Combined Libraries. + +You may place library facilities that are a work based on the Library +side by side in a single library together with other library +facilities that are not Applications and are not covered by this +License, and convey such a combined library under terms of your +choice, if you do both of the following: + +- a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities, conveyed under the terms of this License. +- b) Give prominent notice with the combined library that part of it + is a work based on the Library, and explaining where to find the + accompanying uncombined form of the same work. + +## 6. Revised Versions of the GNU Lesser General Public License. + +The Free Software Foundation may publish revised and/or new versions +of the GNU Lesser 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 Library +as you received it specifies that a certain numbered version of the +GNU Lesser General Public License "or any later version" applies to +it, you have the option of following the terms and conditions either +of that published version or of any later version published by the +Free Software Foundation. If the Library as you received it does not +specify a version number of the GNU Lesser General Public License, you +may choose any version of the GNU Lesser General Public License ever +published by the Free Software Foundation. + +If the Library as you received it specifies that a proxy can decide +whether future versions of the GNU Lesser General Public License shall +apply, that proxy's public statement of acceptance of any version is +permanent authorization for you to choose that version for the +Library. \ No newline at end of file diff --git a/services-src/storage/build.sh b/services-src/storage/build.sh new file mode 100755 index 0000000..0c7dacc --- /dev/null +++ b/services-src/storage/build.sh @@ -0,0 +1,5 @@ +#!/bin/sh + +path=$(realpath "$(dirname "$0")") || exit 1 +rm -rf "$path/../../services/storage.fgs" || exit 1 +go build -o "$path/../../services/storage.fgs" --buildmode=plugin -ldflags "-s -w" || exit 1 diff --git a/services-src/storage/main.go b/services-src/storage/main.go new file mode 100644 index 0000000..7766514 --- /dev/null +++ b/services-src/storage/main.go @@ -0,0 +1,376 @@ +package main + +import ( + "database/sql" + "git.ailur.dev/ailur/fulgens/library" + "path/filepath" + + "io" + "os" + "time" + + "github.com/go-playground/validator/v10" + "github.com/google/uuid" +) + +type InsertFile struct { + File File `validate:"required"` + Stream io.Reader `validate:"required"` +} + +type ReadFile struct { + File File `validate:"required"` + Stream io.Writer `validate:"required"` +} + +type File struct { + Name string `validate:"required"` + Size int64 `validate:"required"` + User uuid.UUID `validate:"required"` +} + +var ServiceInformation = library.Service{ + Name: "Storage", + Permissions: library.Permissions{ + Authenticate: false, // This service does not require authentication + Database: true, // This service requires database access to store quotas + BlobStorage: false, // This service *is* the blob storage + InterServiceCommunication: true, // This service does require inter-service communication + }, + ServiceID: uuid.MustParse("00000000-0000-0000-0000-000000000003"), +} + +var conn *sql.DB + +func getQuota(user uuid.UUID, information library.ServiceInitializationInformation) (int64, error) { + // Get the user's quota from the database + var quota int64 + err := conn.QueryRow("SELECT quota FROM quotas WHERE id = $1", user).Scan("a) + if err != nil { + return 0, err + } + + return quota, nil +} + +func getUsed(user uuid.UUID, information library.ServiceInitializationInformation) (int64, error) { + // Check the user's used space via the filesystem + var used int64 + err := filepath.Walk(filepath.Join(information.Configuration["path"].(string), user.String()), func(path string, info os.FileInfo, err error) error { + if err != nil { + return err + } + used += info.Size() + return nil + }) + if err != nil { + return 0, err + } + + return used, nil +} + +func logFunc(message string, messageType uint64, information library.ServiceInitializationInformation) { + // Log the error message to the logger service + information.Outbox <- library.InterServiceMessage{ + ServiceID: information.ServiceID, + ForServiceID: uuid.MustParse("00000000-0000-0000-0000-000000000002"), // Logger service + MessageType: messageType, + SentAt: time.Now(), + Message: message, + } +} + +func storeFile(file InsertFile, serviceID uuid.UUID, information library.ServiceInitializationInformation) { + // Create a folder for the user if it doesn't exist + err := os.MkdirAll(filepath.Join(information.Configuration["path"].(string), file.File.User.String()), 0755) + if err != nil { + // First contact the logger service + logFunc(err.Error(), 2, information) + + // Then send the error message to the requesting service + information.Outbox <- library.InterServiceMessage{ + ServiceID: information.ServiceID, + ForServiceID: serviceID, + MessageType: 1, // An error that's not your fault + SentAt: time.Now(), + Message: err.Error(), + } + } + + // Check if the user has enough space to store the file + quota, err := getQuota(file.File.User, information) + if err != nil { + // First contact the logger service + logFunc(err.Error(), 2, information) + + // Then send the error message to the requesting service + information.Outbox <- library.InterServiceMessage{ + ServiceID: information.ServiceID, + ForServiceID: serviceID, + MessageType: 1, // An error that's not your fault + SentAt: time.Now(), + Message: err.Error(), + } + } + + used, err := getUsed(file.File.User, information) + if err != nil { + // First contact the logger service + logFunc(err.Error(), 2, information) + + // Then send the error message to the requesting service + information.Outbox <- library.InterServiceMessage{ + ServiceID: information.ServiceID, + ForServiceID: serviceID, + MessageType: 1, // An error that's not your fault + SentAt: time.Now(), + Message: err.Error(), + } + } + + // Check if the user has enough space to store the file + if used+file.File.Size > quota { + // Then send the error message to the requesting service + information.Outbox <- library.InterServiceMessage{ + ServiceID: information.ServiceID, + ForServiceID: serviceID, + MessageType: 3, // It's the user's fault (never say that to the customer ;P) + SentAt: time.Now(), + Message: "User has exceeded their quota", + } + } + + // Create a folder within that for the service if it doesn't exist + err = os.MkdirAll(filepath.Join(information.Configuration["path"].(string), file.File.User.String(), serviceID.String()), 0755) + if err != nil { + // First contact the logger service + logFunc(err.Error(), 2, information) + + // Then send the error message to the requesting service + information.Outbox <- library.InterServiceMessage{ + ServiceID: information.ServiceID, + ForServiceID: serviceID, + MessageType: 1, // An error that's not your fault + SentAt: time.Now(), + Message: err.Error(), + } + } + + // Store the file + fileStream, err := os.OpenFile(filepath.Join(information.Configuration["path"].(string), file.File.User.String(), serviceID.String(), file.File.Name), os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644) + if err != nil { + // First contact the logger service + logFunc(err.Error(), 2, information) + + // Then send the error message to the requesting service + information.Outbox <- library.InterServiceMessage{ + ServiceID: information.ServiceID, + ForServiceID: serviceID, + MessageType: 1, // An error that's not your fault + SentAt: time.Now(), + Message: err.Error(), + } + } + + // Write the file + _, err = io.Copy(fileStream, file.Stream) + if err != nil { + // First contact the logger service + logFunc(err.Error(), 2, information) + + // Then send the error message to the requesting service + information.Outbox <- library.InterServiceMessage{ + ServiceID: information.ServiceID, + ForServiceID: serviceID, + MessageType: 1, // An error that's not your fault + SentAt: time.Now(), + Message: err.Error(), + } + } + + // Close the file + err = fileStream.Close() + if err != nil { + // First contact the logger service + logFunc(err.Error(), 2, information) + + // Then send the error message to the requesting service + information.Outbox <- library.InterServiceMessage{ + ServiceID: information.ServiceID, + ForServiceID: serviceID, + MessageType: 1, // An error that's not your fault + SentAt: time.Now(), + Message: err.Error(), + } + } + + // Report success + information.Outbox <- library.InterServiceMessage{ + ServiceID: information.ServiceID, + ForServiceID: serviceID, + MessageType: 0, // Success + SentAt: time.Now(), + Message: nil, + } +} + +func readFile(file ReadFile, serviceID uuid.UUID, information library.ServiceInitializationInformation) { + // Open the file + fileStream, err := os.Open(filepath.Join(information.Configuration["path"].(string), file.File.User.String(), serviceID.String(), file.File.Name)) + if err != nil { + // First contact the logger service + logFunc(err.Error(), 2, information) + + // Then send the error message to the requesting service + information.Outbox <- library.InterServiceMessage{ + ServiceID: information.ServiceID, + ForServiceID: serviceID, + MessageType: 1, // An error that's not your fault + SentAt: time.Now(), + Message: err.Error(), + } + } + + // Read the file + _, err = io.Copy(file.Stream, fileStream) + if err != nil { + // First contact the logger service + logFunc(err.Error(), 2, information) + + // Then send the error message to the requesting service + information.Outbox <- library.InterServiceMessage{ + ServiceID: information.ServiceID, + ForServiceID: serviceID, + MessageType: 1, // An error that's not your fault + SentAt: time.Now(), + Message: err.Error(), + } + } + + // Close the file + err = fileStream.Close() + if err != nil { + // First contact the logger service + logFunc(err.Error(), 2, information) + + // Then send the error message to the requesting service + information.Outbox <- library.InterServiceMessage{ + ServiceID: information.ServiceID, + ForServiceID: serviceID, + MessageType: 1, // An error that's not your fault + SentAt: time.Now(), + Message: err.Error(), + } + } + + // Report success + information.Outbox <- library.InterServiceMessage{ + ServiceID: information.ServiceID, + ForServiceID: serviceID, + MessageType: 0, // Success + SentAt: time.Now(), + Message: nil, + } +} + +func removeFile(file File, serviceID uuid.UUID, information library.ServiceInitializationInformation) { + // Remove the file + err := os.Remove(filepath.Join(information.Configuration["path"].(string), file.User.String(), serviceID.String(), file.Name)) + if err != nil { + // First contact the logger service + logFunc(err.Error(), 2, information) + + // Then send the error message to the requesting service + information.Outbox <- library.InterServiceMessage{ + ServiceID: information.ServiceID, + ForServiceID: serviceID, + MessageType: 1, // An error that's not your fault + SentAt: time.Now(), + Message: err.Error(), + } + } + + // Report success + information.Outbox <- library.InterServiceMessage{ + ServiceID: information.ServiceID, + ForServiceID: serviceID, + MessageType: 0, // Success + SentAt: time.Now(), + Message: nil, + } +} + +func Main(information library.ServiceInitializationInformation) { + go func() { + for { + message := <-information.Inbox + if message.ServiceID == uuid.MustParse("00000000-0000-0000-0000-000000000001") { + if message.MessageType == 1 { + // We've received an error message. This should never happen. + logFunc("Bit flip error: Error given to non-errored service. Move away from radiation or use ECC memory.", 3, information) + } + } else { + switch message.MessageType { + case 0: + // Insert file + validate := validator.New() + err := validate.Struct(message.Message.(InsertFile)) + if err != nil { + information.Outbox <- library.InterServiceMessage{ + ServiceID: information.ServiceID, + ForServiceID: message.ServiceID, + MessageType: 2, // An error that's your fault + SentAt: time.Now(), + Message: err.Error(), + } + } else { + // Store file + storeFile(message.Message.(InsertFile), message.ServiceID, information) + } + case 1: + // Read file + validate := validator.New() + err := validate.Struct(message.Message.(ReadFile)) + if err != nil { + information.Outbox <- library.InterServiceMessage{ + ServiceID: information.ServiceID, + ForServiceID: message.ServiceID, + MessageType: 2, // An error that's your fault + SentAt: time.Now(), + Message: err.Error(), + } + } else { + // Read file + readFile(message.Message.(ReadFile), message.ServiceID, information) + } + case 2: + // Remove file + validate := validator.New() + err := validate.Struct(message.Message.(File)) + if err != nil { + information.Outbox <- library.InterServiceMessage{ + ServiceID: information.ServiceID, + ForServiceID: message.ServiceID, + MessageType: 2, // An error that's your fault + SentAt: time.Now(), + Message: err.Error(), + } + } else { + // Remove file + removeFile(message.Message.(File), message.ServiceID, information) + } + } + } + } + }() + + // Report a successful activation + information.Outbox <- library.InterServiceMessage{ + ServiceID: information.ServiceID, + ForServiceID: uuid.MustParse("00000000-0000-0000-0000-000000000001"), // Activation service + MessageType: 0, + SentAt: time.Now(), + Message: true, + } +}